This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git


The following commit(s) were added to refs/heads/main by this push:
     new 871b177589 feat(agent-service): scope agents to their verified owner 
(#9580)
871b177589 is described below

commit 871b1775896135dec67e165a2a897557be3ccd3d
Author: Jiadong Bai <[email protected]>
AuthorDate: Wed Nov 25 08:17:54 2026 +0000

    feat(agent-service): scope agents to their verified owner (#9580)
    
    ### What changes were proposed in this PR?
    
    Each user now sees and opens only their own agents, and a login token
    needs a valid signature.
    
    | | Before | After |
    | --- | --- | --- |
    | Agent list (`GET /api/agents`) | Every user's agents | The caller's
    only |
    | Another user's agent, by id or websocket | Opens: its chat is
    readable, and prompts use the owner's token | 404 "Agent not found", as
    for an unknown id |
    | No token, or a forged one | Accepted: the only check read the expiry |
    401 |
    
    **Another user's agent.** e2e-reader opens "Penguin species comparison",
    which texera shared read-only. Before, the panel lists texera's "Penguin
    analyst" and shows its chat, texera's question marked "You":
    
    <img width="1120" height="760" alt="Before: e2e-reader's panel shows
    texera's Penguin analyst and its chat"
    
src="https://github.com/user-attachments/assets/79e3599d-c2a5-46a2-bffd-6062ff8ea4c6";
    />
    
    After, it lists only e2e-reader's own agent:
    
    <img width="1120" height="760" alt="After: e2e-reader's panel shows only
    Plot helper"
    
src="https://github.com/user-attachments/assets/9be5e65c-f078-459c-9642-26d59679ccd6";
    />
    
    - The agent service checks the HS256 signature with `AUTH_JWT_SECRET`,
    read as the dashboard service reads it (`auth.conf`'s default,
    lowercased, never `random`). Kubernetes passes it in.
    - Each agent records its creator, and every route and the websocket
    check the caller against it.
    - The frontend puts the token in the agent websocket's query, like the
    workflow websocket.
    
    #9043 adds a gateway check and will follow this PR, taking over the
    token check.
    
    ### Any related issues, documentation, discussions?
    
    Closes #5268
    
    Agent ids stay sequential: a guessed id gets the same 404 as a missing
    one.
    
    ### How was this PR tested?
    
    Agent-service tests cover every route and the websocket with another
    user's token, no token and forged tokens, and how the secret is read.
    Also tested in headless Chromium as two users with a real model. The
    second sees none of the first's agents or chat, and the owner's agent
    still builds and executes a workflow.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Fable 5.2, Claude Opus 5.5)
---
 agent-service/.env.example                         |   5 +
 agent-service/src/agent/texera-agent.spec.ts       |  12 +-
 agent-service/src/agent/texera-agent.ts            |   4 +
 agent-service/src/api/auth-api.spec.ts             | 133 +++++++++++++--------
 agent-service/src/api/auth-api.ts                  |  63 +++++-----
 agent-service/src/api/test-token.ts                |  49 ++++++++
 agent-service/src/config/env.ts                    |  18 ++-
 agent-service/src/server.spec.ts                   | 118 ++++++++++++++----
 agent-service/src/server.ts                        | 121 +++++++++++--------
 agent-service/src/server.ws.spec.ts                |  64 +++++++---
 .../agent-service/agent-service-deployment.yaml    |   8 ++
 .../workspace/service/agent/agent.service.spec.ts  |  17 +++
 .../app/workspace/service/agent/agent.service.ts   |  10 +-
 13 files changed, 449 insertions(+), 173 deletions(-)

diff --git a/agent-service/.env.example b/agent-service/.env.example
index 605f157ca0..ec57898687 100644
--- a/agent-service/.env.example
+++ b/agent-service/.env.example
@@ -15,6 +15,11 @@ LOG_PRETTY=true
 LLM_API_KEY=dummy
 LLM_ENDPOINT=http://localhost:9096
 
+# The secret the dashboard service signs login tokens with; every request's
+# token is verified with it. Unset, it is auth.conf's default, as it is for
+# the backend. Set it here only together with the backend's AUTH_JWT_SECRET.
+# AUTH_JWT_SECRET=
+
 # Texera backend services
 TEXERA_DASHBOARD_SERVICE_ENDPOINT=http://localhost:8080
 WORKFLOW_COMPILING_SERVICE_ENDPOINT=http://localhost:9090
diff --git a/agent-service/src/agent/texera-agent.spec.ts 
b/agent-service/src/agent/texera-agent.spec.ts
index 6d0718c5ce..0ccb784496 100644
--- a/agent-service/src/agent/texera-agent.spec.ts
+++ b/agent-service/src/agent/texera-agent.spec.ts
@@ -35,6 +35,7 @@ function makeAgent(): TexeraAgent {
     modelType: "test-model",
     agentId: "agent-1",
     userToken: "user-token",
+    ownerUid: 1,
   });
 }
 
@@ -110,8 +111,14 @@ describe("TexeraAgent", () => {
     test("falls back to a name derived from the id", () => {
       expect(makeAgent().agentName).toBe("Agent-agent-1");
       expect(
-        new TexeraAgent({ model: {} as any, modelType: "m", agentId: "a", 
agentName: "Named", userToken: "t" })
-          .agentName
+        new TexeraAgent({
+          model: {} as any,
+          modelType: "m",
+          agentId: "a",
+          agentName: "Named",
+          userToken: "t",
+          ownerUid: 1,
+        }).agentName
       ).toBe("Named");
     });
   });
@@ -411,6 +418,7 @@ function makeAgentWith(model: any): TexeraAgent {
     agentId: "agent-1",
     systemPrompt: "SYS-XYZ",
     userToken: "user-token",
+    ownerUid: 1,
   });
   liveAgents.push(agent);
   return agent;
diff --git a/agent-service/src/agent/texera-agent.ts 
b/agent-service/src/agent/texera-agent.ts
index 126ba33c8a..46bc2235a4 100644
--- a/agent-service/src/agent/texera-agent.ts
+++ b/agent-service/src/agent/texera-agent.ts
@@ -63,6 +63,8 @@ export interface TexeraAgentConfig {
   systemPrompt?: string;
   /** JWT of the user the agent acts for, sent on backend calls that are not 
tied to a workflow. */
   userToken?: string;
+  /** uid of the user who created the agent, the only one it is listed for and 
answers to. */
+  ownerUid: number;
 }
 
 export interface AgentMessageResult {
@@ -101,6 +103,7 @@ export class TexeraAgent {
   readonly agentName: string;
   readonly modelType: string;
   readonly createdAt: Date;
+  readonly ownerUid: number;
 
   private state: AgentStateEnum = AgentStateEnum.AVAILABLE;
   private workflowState: WorkflowState;
@@ -147,6 +150,7 @@ export class TexeraAgent {
     this.agentName = config.agentName || `Agent-${config.agentId}`;
     this.modelType = config.modelType;
     this.createdAt = new Date();
+    this.ownerUid = config.ownerUid;
     this.model = config.model;
     this.userToken = config.userToken;
     this.systemPrompt = config.systemPrompt || "";
diff --git a/agent-service/src/api/auth-api.spec.ts 
b/agent-service/src/api/auth-api.spec.ts
index 0037790ffc..553a4a52b7 100644
--- a/agent-service/src/api/auth-api.spec.ts
+++ b/agent-service/src/api/auth-api.spec.ts
@@ -18,88 +18,117 @@
  */
 
 import { describe, expect, test } from "bun:test";
-import { createAuthHeaders, extractBearerToken, extractUserFromToken, 
validateToken } from "./auth-api";
-
-/**
- * Builds a well-formed three-segment token carrying the given payload. All 
three segments are
- * required — `decodeJWT` rejects anything that is not exactly three — but 
only the payload one is
- * decoded, so the header and signature just have to be present.
- */
-function tokenWith(payload: Record<string, unknown>): string {
-  const encoded = Buffer.from(JSON.stringify(payload), 
"utf-8").toString("base64");
-  return `header.${encoded}.signature`;
-}
+import { createHmac } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { createAuthHeaders, extractBearerToken, verifyToken } from 
"./auth-api";
+import { encodeSegment, signTestToken } from "./test-token";
+import { env, EnvSchema } from "../config/env";
 
 /** `exp` is a UNIX second count, so expiries are built in seconds throughout. 
*/
 function nowInSeconds(): number {
   return Math.floor(Date.now() / 1000);
 }
 
-describe("extractUserFromToken", () => {
-  test("maps the JWT payload onto the user record", () => {
-    const token = tokenWith({ userId: 42, sub: "ada", email: 
"[email protected]", role: "ADMIN" });
+describe("verifyToken", () => {
+  test("maps a signed token's claims onto the user record", () => {
+    const token = signTestToken({ userId: 42, sub: "ada", email: 
"[email protected]", role: "ADMIN" });
 
-    expect(extractUserFromToken(token)).toEqual({
-      uid: 42,
-      name: "ada",
-      email: "[email protected]",
-      role: "ADMIN",
-    });
+    expect(verifyToken(token)).toEqual({ uid: 42, name: "ada", email: 
"[email protected]", role: "ADMIN" });
   });
 
   test("defaults a missing email to empty and a missing role to REGULAR", () 
=> {
     // Role defaulting is a privilege decision: absent must mean least 
privilege, never admin.
-    const user = extractUserFromToken(tokenWith({ userId: 7, sub: "grace" }));
+    const user = verifyToken(signTestToken({ userId: 7, sub: "grace" }));
 
-    expect(user.email).toBe("");
-    expect(user.role).toBe("REGULAR");
+    expect(user?.email).toBe("");
+    expect(user?.role).toBe("REGULAR");
   });
 
-  test("rejects a token missing its signature segment even when the payload 
decodes", () => {
-    // The payload here is perfectly good JSON, so only the segment-count 
check stands between an
-    // unsigned token and a populated user record.
-    const payload = Buffer.from(JSON.stringify({ userId: 1, sub: "ada" }), 
"utf-8").toString("base64");
+  test("accepts a token whose expiry is still in the future", () => {
+    expect(verifyToken(signTestToken({ userId: 1, exp: nowInSeconds() + 60 
}))).toBeDefined();
+  });
 
-    expect(() => extractUserFromToken(`header.${payload}`)).toThrow(/Failed to 
decode JWT/);
+  test("rejects a token whose expiry has passed", () => {
+    expect(verifyToken(signTestToken({ userId: 1, exp: nowInSeconds() - 60 
}))).toBeUndefined();
   });
 
-  test("rejects a token with too many segments", () => {
-    const payload = Buffer.from(JSON.stringify({ userId: 1, sub: "ada" }), 
"utf-8").toString("base64");
+  test("treats a token with no expiry as valid forever", () => {
+    // Deliberate: tokens minted without `exp` never expire. Pinned because it 
is a policy choice
+    // that reads like an oversight, and flipping it would lock out every 
non-expiring token.
+    expect(verifyToken(signTestToken({ userId: 1 }))).toBeDefined();
+  });
 
-    expect(() => 
extractUserFromToken(`header.${payload}.signature.extra`)).toThrow(/Failed to 
decode JWT/);
+  test("expiry is compared in seconds, not milliseconds", () => {
+    // exp is a UNIX second count; reading it as milliseconds would place 
every real token in 1970
+    // and reject it. A far-future second count must still verify.
+    expect(verifyToken(signTestToken({ userId: 1, exp: nowInSeconds() + 3600 
}))).toBeDefined();
   });
 
-  test("rejects a token whose payload is not JSON", () => {
-    const notJson = Buffer.from("<html>", "utf-8").toString("base64");
-    expect(() => 
extractUserFromToken(`header.${notJson}.signature`)).toThrow(/Failed to decode 
JWT/);
+  test("rejects a missing or malformed token rather than throwing", () => {
+    expect(verifyToken(undefined)).toBeUndefined();
+    expect(verifyToken("not-a-token")).toBeUndefined();
+    // A good payload without its signature segment, and a signed token with 
one segment too many.
+    expect(verifyToken(`${encodeSegment({ alg: "HS256" })}.${encodeSegment({ 
userId: 1 })}`)).toBeUndefined();
+    expect(verifyToken(`${signTestToken({ userId: 1 
})}.extra`)).toBeUndefined();
   });
-});
 
-describe("validateToken", () => {
-  test("accepts a token whose expiry is still in the future", () => {
-    expect(validateToken(tokenWith({ userId: 1, exp: nowInSeconds() + 60 
}))).toBe(true);
+  test("rejects a signed token whose claims are not JSON", () => {
+    // The signature holds, so only the decode stands between this token and a 
user record.
+    const signed = `${encodeSegment({ alg: "HS256" })}.${Buffer.from("<html>", 
"utf-8").toString("base64url")}`;
+    const token = `${signed}.${createHmac("sha256", 
env.AUTH_JWT_SECRET).update(signed).digest("base64url")}`;
+
+    expect(verifyToken(token)).toBeUndefined();
   });
 
-  test("rejects a token whose expiry has passed", () => {
-    expect(validateToken(tokenWith({ userId: 1, exp: nowInSeconds() - 60 
}))).toBe(false);
+  test("rejects a signed token without a whole-number user id", () => {
+    // Agents are matched to their owner by this id, so a token must name 
exactly one user.
+    expect(verifyToken(signTestToken({ sub: "ada" }))).toBeUndefined();
+    expect(verifyToken(signTestToken({ userId: "7", sub: "ada" 
}))).toBeUndefined();
+    expect(verifyToken(signTestToken({ userId: 1.5, sub: "ada" 
}))).toBeUndefined();
   });
 
-  test("treats a token with no expiry as valid forever", () => {
-    // Deliberate: tokens minted without `exp` never expire. Pinned because it 
is a policy choice
-    // that reads like an oversight, and flipping it would lock out every 
non-expiring token.
-    expect(validateToken(tokenWith({ userId: 1 }))).toBe(true);
+  test("rejects a token signed with another secret, whatever it claims", () => 
{
+    // Anyone can write these claims; only the dashboard service's secret can 
sign them. The
+    // agent service gives a token's user their agents, so an unsigned claim 
must count for nothing.
+    const claims = { userId: 1, sub: "texera", role: "ADMIN", exp: 
nowInSeconds() + 60 };
+
+    expect(verifyToken(signTestToken(claims, 
"not-the-secret"))).toBeUndefined();
   });
 
-  test("rejects a malformed token rather than letting the decode failure 
escape", () => {
-    // isTokenExpired swallows the decode error and reports "expired", so 
callers get false here
-    // instead of an exception. A caller that only catches would otherwise let 
a junk token through.
-    expect(validateToken("not-a-token")).toBe(false);
+  test("rejects a token whose claims were edited after it was signed", () => {
+    const [header, , signature] = signTestToken({ userId: 2, sub: "bob", exp: 
nowInSeconds() + 60 }).split(".");
+    const edited = encodeSegment({ userId: 1, sub: "bob", exp: nowInSeconds() 
+ 60 });
+
+    expect(verifyToken(`${header}.${edited}.${signature}`)).toBeUndefined();
   });
 
-  test("expiry is compared in seconds, not milliseconds", () => {
-    // exp is a UNIX second count; reading it as milliseconds would place 
every real token in 1970
-    // and reject it. A far-future second count must still validate.
-    expect(validateToken(tokenWith({ exp: nowInSeconds() + 3600 
}))).toBe(true);
+  test("rejects an unsigned token that declares no algorithm", () => {
+    // The check never reads the header's `alg`, so a token cannot ask for a 
weaker one.
+    const claims = encodeSegment({ userId: 1, sub: "texera", exp: 
nowInSeconds() + 60 });
+
+    expect(verifyToken(`${encodeSegment({ alg: "none" 
})}.${claims}.`)).toBeUndefined();
+  });
+});
+
+describe("AUTH_JWT_SECRET", () => {
+  test("defaults to the secret auth.conf gives the dashboard service", () => {
+    // env.ts repeats auth.conf's default. If the two drift, a stack that sets 
neither (local
+    // development, single-node) would reject every login token.
+    const conf = readFileSync(new 
URL("../../../common/config/src/main/resources/auth.conf", import.meta.url), 
"utf-8");
+
+    expect(EnvSchema.parse({}).AUTH_JWT_SECRET).toBe(/256-bit-secret = 
"([^"]+)"/.exec(conf)![1]);
+  });
+
+  test("reads a configured secret the way the dashboard service does", () => {
+    // AuthConfig.scala lowercases AUTH_JWT_SECRET before signing, so a 
deployment that sets
+    // "Xk9F-Shared" signs every login token with "xk9f-shared". Read as 
written, the secret
+    // would reject them all.
+    expect(EnvSchema.parse({ AUTH_JWT_SECRET: "Xk9F-Shared" 
}).AUTH_JWT_SECRET).toBe("xk9f-shared");
+  });
+
+  test('refuses "random", which makes each backend process invent its own 
key', () => {
+    // No other service can know such a key, so starting with it would only 
reject every token.
+    expect(() => EnvSchema.parse({ AUTH_JWT_SECRET: "Random" 
})).toThrow("cannot be 'random'");
   });
 });
 
diff --git a/agent-service/src/api/auth-api.ts 
b/agent-service/src/api/auth-api.ts
index 4a166269c7..228ddc30f5 100644
--- a/agent-service/src/api/auth-api.ts
+++ b/agent-service/src/api/auth-api.ts
@@ -17,44 +17,51 @@
  * under the License.
  */
 
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { env } from "../config/env";
 import type { UserInfo } from "../types/agent";
 
 export type { UserInfo } from "../types/agent";
 
-function decodeJWT(token: string): any {
-  try {
-    const parts = token.split(".");
-    if (parts.length !== 3) {
-      throw new Error("Invalid JWT format");
-    }
-    return JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
-  } catch (error) {
-    throw new Error(`Failed to decode JWT: ${error}`);
+// Whether the dashboard service issued this token: its signature is the 
HMAC-SHA256
+// of the first two segments under the shared secret, as JwtAuth.scala writes 
it. The
+// header's own `alg` is never consulted, so a token cannot choose a weaker 
check.
+function isSignedByTexera(token: string): boolean {
+  const parts = token.split(".");
+  if (parts.length !== 3) {
+    return false;
   }
+  const expected = createHmac("sha256", 
env.AUTH_JWT_SECRET).update(`${parts[0]}.${parts[1]}`).digest();
+  const actual = Buffer.from(parts[2], "base64url");
+  return actual.length === expected.length && timingSafeEqual(actual, 
expected);
 }
 
-export function extractUserFromToken(token: string): UserInfo {
-  const payload = decodeJWT(token);
-  return {
-    uid: payload.userId,
-    name: payload.sub,
-    email: payload.email || "",
-    role: payload.role || "REGULAR",
-  };
-}
-
-function isTokenExpired(token: string): boolean {
+// The user a login token names, or undefined unless the dashboard service 
signed it, it has
+// not expired, and it carries a whole-number user id. Anyone can write a 
token's claims; only
+// the dashboard service can sign them, so the claims are read only after the 
signature holds.
+export function verifyToken(token: string | undefined): UserInfo | undefined {
+  if (!token || !isSignedByTexera(token)) {
+    return undefined;
+  }
+  let claims: any;
   try {
-    const payload = decodeJWT(token);
-    if (!payload.exp) return false;
-    return Date.now() >= payload.exp * 1000;
+    claims = JSON.parse(Buffer.from(token.split(".")[1], 
"base64url").toString("utf-8"));
   } catch {
-    return true;
+    return undefined;
   }
-}
-
-export function validateToken(token: string): boolean {
-  return !isTokenExpired(token);
+  // `exp` is a UNIX second count. A token without one never expires.
+  if (claims?.exp && Date.now() >= claims.exp * 1000) {
+    return undefined;
+  }
+  if (!Number.isInteger(claims?.userId)) {
+    return undefined;
+  }
+  return {
+    uid: claims.userId,
+    name: claims.sub,
+    email: claims.email || "",
+    role: claims.role || "REGULAR",
+  };
 }
 
 export function extractBearerToken(header: string | undefined): string | 
undefined {
diff --git a/agent-service/src/api/test-token.ts 
b/agent-service/src/api/test-token.ts
new file mode 100644
index 0000000000..edce84ad56
--- /dev/null
+++ b/agent-service/src/api/test-token.ts
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Login tokens for tests, signed the way the dashboard service signs one 
(JwtAuth.scala):
+// HS256 over the first two segments, with the shared secret unless a test 
names another.
+
+import { createHmac } from "node:crypto";
+import { env } from "../config/env";
+
+/** One base64url segment of a token, holding `value` as JSON. */
+export function encodeSegment(value: Record<string, unknown>): string {
+  return Buffer.from(JSON.stringify(value), "utf-8").toString("base64url");
+}
+
+/** A token carrying `claims`, signed with `secret`. */
+export function signTestToken(claims: Record<string, unknown>, secret: string 
= env.AUTH_JWT_SECRET): string {
+  const signed = `${encodeSegment({ alg: "HS256", typ: "JWT" 
})}.${encodeSegment(claims)}`;
+  return `${signed}.${createHmac("sha256", 
secret).update(signed).digest("base64url")}`;
+}
+
+/** A REGULAR user's login token, an hour from expiry. */
+export function mintTestToken(userId = 1, secret: string = 
env.AUTH_JWT_SECRET): string {
+  return signTestToken(
+    {
+      sub: "tester",
+      userId,
+      email: "[email protected]",
+      role: "REGULAR",
+      exp: Math.floor(Date.now() / 1000) + 3600,
+    },
+    secret
+  );
+}
diff --git a/agent-service/src/config/env.ts b/agent-service/src/config/env.ts
index 3513286b14..94e1884168 100644
--- a/agent-service/src/config/env.ts
+++ b/agent-service/src/config/env.ts
@@ -19,7 +19,7 @@
 
 import { z } from "zod";
 
-const EnvSchema = z.object({
+export const EnvSchema = z.object({
   PORT: z.coerce.number().default(3001),
   API_PREFIX: z.string().default("/api"),
   TEXERA_SERVICE_LOG_LEVEL: z
@@ -33,6 +33,22 @@ const EnvSchema = z.object({
   WORKFLOW_COMPILING_SERVICE_ENDPOINT: 
z.string().url().default("http://localhost:9090";),
   WORKFLOW_EXECUTION_SERVICE_ENDPOINT: 
z.string().url().default("http://localhost:8085";),
   EXECUTION_ENDPOINT_TEMPLATE: z.string().optional(),
+
+  // The secret the dashboard service signs login tokens with (HS256). The same
+  // variable overrides it there, and the default here is the one in
+  // common/config/src/main/resources/auth.conf, so the two agree unless a
+  // deployment sets it for one service and not the other. It is read the way
+  // AuthConfig.scala reads it: lowercased, since the dashboard service signs 
with
+  // the lowercased value, and never "random", which there makes each process
+  // invent its own key that no other service can know.
+  AUTH_JWT_SECRET: z
+    .string()
+    .min(1)
+    .default("8a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d")
+    .transform(secret => secret.toLowerCase())
+    .refine(secret => secret !== "random", {
+      message: "AUTH_JWT_SECRET cannot be 'random': set it to the secret the 
dashboard service signs login tokens with",
+    }),
 });
 
 export const env = EnvSchema.parse(process.env);
diff --git a/agent-service/src/server.spec.ts b/agent-service/src/server.spec.ts
index 84e979e289..be66e4f3f3 100644
--- a/agent-service/src/server.spec.ts
+++ b/agent-service/src/server.spec.ts
@@ -20,33 +20,33 @@
 import { beforeEach, describe, expect, spyOn, test } from "bun:test";
 import { buildApp, start, _resetAgentStoreForTests, _getAgentForTests } from 
"./server";
 import { WorkflowSystemMetadata } from "./agent/util/workflow-system-metadata";
+import { mintTestToken } from "./api/test-token";
 import { env } from "./config/env";
 import { ConsoleMessageType, OperatorState } from "./types/execution";
 
 const API = env.API_PREFIX;
 const app = buildApp();
 
-function mintTestToken(): string {
-  const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" 
})).toString("base64url");
-  const payload = Buffer.from(
-    JSON.stringify({
-      sub: "tester",
-      userId: 1,
-      email: "[email protected]",
-      role: "REGULAR",
-      exp: Math.floor(Date.now() / 1000) + 3600,
-    })
-  ).toString("base64url");
-  return `${header}.${payload}.test-signature`;
-}
-
 const TOKEN = mintTestToken();
+const OTHER_USER_TOKEN = mintTestToken(2);
+// TOKEN's claims under a signature the dashboard service did not make.
+const FORGED_TOKEN = mintTestToken(1, "not-the-secret");
 
 function url(path: string): string {
   return `http://localhost${path}`;
 }
 
-async function postJson(path: string, body: unknown, headers: Record<string, 
string> = {}): Promise<Response> {
+// Every agent route needs a user, so the helpers below act as TOKEN's user
+// unless a test names another token, or null for none.
+function bearer(token: string | null): Record<string, string> {
+  return token ? { Authorization: `Bearer ${token}` } : {};
+}
+
+async function postJson(
+  path: string,
+  body: unknown,
+  headers: Record<string, string> = bearer(TOKEN)
+): Promise<Response> {
   return app.handle(
     new Request(url(path), {
       method: "POST",
@@ -57,25 +57,25 @@ async function postJson(path: string, body: unknown, 
headers: Record<string, str
 }
 
 async function createAgent(body: Record<string, unknown> = {}, token: string | 
null = TOKEN): Promise<Response> {
-  return postJson(`${API}/agents`, { modelType: "m", ...body }, token ? { 
Authorization: `Bearer ${token}` } : {});
+  return postJson(`${API}/agents`, { modelType: "m", ...body }, bearer(token));
 }
 
-async function patchJson(path: string, body: unknown): Promise<Response> {
+async function patchJson(path: string, body: unknown, token: string | null = 
TOKEN): Promise<Response> {
   return app.handle(
     new Request(url(path), {
       method: "PATCH",
-      headers: { "Content-Type": "application/json" },
+      headers: { "Content-Type": "application/json", ...bearer(token) },
       body: JSON.stringify(body),
     })
   );
 }
 
-async function getJson(path: string): Promise<Response> {
-  return app.handle(new Request(url(path)));
+async function getJson(path: string, token: string | null = TOKEN): 
Promise<Response> {
+  return app.handle(new Request(url(path), { headers: bearer(token) }));
 }
 
-async function del(path: string): Promise<Response> {
-  return app.handle(new Request(url(path), { method: "DELETE" }));
+async function del(path: string, token: string | null = TOKEN): 
Promise<Response> {
+  return app.handle(new Request(url(path), { method: "DELETE", headers: 
bearer(token) }));
 }
 
 async function readJson<T = unknown>(res: Response): Promise<T> {
@@ -167,6 +167,80 @@ describe(`GET ${API}/agents`, () => {
     expect(body.agents).toHaveLength(2);
     expect(body.agents.map(a => a.name).sort()).toEqual(["one", "two"]);
   });
+
+  test("lists each user only their own agents", async () => {
+    await createAgent({ name: "mine" });
+    await createAgent({ name: "theirs" }, OTHER_USER_TOKEN);
+
+    const names = async (token: string) =>
+      (await readJson<{ agents: { name: string }[] }>(await 
getJson(`${API}/agents`, token))).agents.map(a => a.name);
+    expect(await names(TOKEN)).toEqual(["mine"]);
+    expect(await names(OTHER_USER_TOKEN)).toEqual(["theirs"]);
+  });
+
+  test("rejects a request without a token", async () => {
+    const res = await getJson(`${API}/agents`, null);
+    expect(res.status).toBe(401);
+  });
+
+  test("rejects a token the dashboard service did not sign, and lists it 
nothing", async () => {
+    await createAgent({ name: "mine" });
+
+    const res = await getJson(`${API}/agents`, FORGED_TOKEN);
+    expect(res.status).toBe(401);
+    expect(await readJson<unknown>(res)).toEqual({ error: "Invalid or expired 
token" });
+  });
+});
+
+// An agent answers only to the user who created it. For anyone else every 
route
+// that names it gives the answer for an agent that does not exist.
+describe("an agent created by another user", () => {
+  // Every row names its body, `undefined` for none. Given a row shorter than 
the test's parameter
+  // list, Bun fills the missing place with a `done` callback: the request 
then carries a JSON
+  // content type, and the test can time out waiting for a callback that 
nobody calls.
+  const ROUTES: [method: string, path: string, body: unknown][] = [
+    ["GET", "", undefined],
+    ["DELETE", "", undefined],
+    ["GET", "/react-steps", undefined],
+    ["GET", "/operator-results", undefined],
+    ["POST", "/steps-by-operators", { operatorIds: [] }],
+    ["GET", "/system-info", undefined],
+    ["POST", "/stop", {}],
+    ["POST", "/clear", {}],
+    ["GET", "/operator-types", undefined],
+    ["GET", "/settings", undefined],
+    ["PATCH", "/settings", { maxSteps: 3 }],
+  ];
+
+  function request(method: string, path: string, body: unknown, token: string 
| null): Promise<Response> {
+    return app.handle(
+      new Request(url(path), {
+        method,
+        headers: { ...(body === undefined ? {} : { "Content-Type": 
"application/json" }), ...bearer(token) },
+        body: body === undefined ? undefined : JSON.stringify(body),
+      })
+    );
+  }
+
+  test.each(ROUTES)("%s /:id%s is not found, and needs a signed token", async 
(method, path, body) => {
+    const id = (await readJson<{ id: string }>(await createAgent())).id;
+    const settingsBefore = _getAgentForTests(id)!.getSettings().maxSteps;
+
+    const asOther = await request(method, `${API}/agents/${id}${path}`, body, 
OTHER_USER_TOKEN);
+    expect(asOther.status).toBe(404);
+    expect((await readJson<{ error: string }>(asOther)).error).toBe("Agent not 
found");
+
+    const withoutToken = await request(method, `${API}/agents/${id}${path}`, 
body, null);
+    expect(withoutToken.status).toBe(401);
+
+    // The owner's own claims, forged: the user id in a token counts only once 
it is signed.
+    const forged = await request(method, `${API}/agents/${id}${path}`, body, 
FORGED_TOKEN);
+    expect(forged.status).toBe(401);
+
+    // None of the calls reached the agent: it is still there for its owner, 
unchanged.
+    expect((await getJson(`${API}/agents/${id}`)).status).toBe(200);
+    expect(_getAgentForTests(id)!.getSettings().maxSteps).toBe(settingsBefore);
+  });
 });
 
 describe(`GET ${API}/agents/:id`, () => {
diff --git a/agent-service/src/server.ts b/agent-service/src/server.ts
index f3775e8895..1ce80c955a 100644
--- a/agent-service/src/server.ts
+++ b/agent-service/src/server.ts
@@ -22,7 +22,7 @@ import { cors } from "@elysiajs/cors";
 import { createOpenAI } from "@ai-sdk/openai";
 import { TexeraAgent } from "./agent/texera-agent";
 import { getBackendConfig } from "./api/backend-api";
-import { extractBearerToken, extractUserFromToken, validateToken } from 
"./api/auth-api";
+import { extractBearerToken, verifyToken } from "./api/auth-api";
 import { retrieveWorkflow } from "./api/workflow-api";
 import { WorkflowSystemMetadata } from "./agent/util/workflow-system-metadata";
 import { env } from "./config/env";
@@ -37,6 +37,7 @@ import type {
   UpdateAgentSettingsRequest,
   AgentSettingsApi,
   ReActStep,
+  UserInfo,
 } from "./types/agent";
 import { AgentState, OperatorResultSerializationMode } from "./types/agent";
 import type { WsClientCommand, WsServerEvent } from "./types/ws";
@@ -48,6 +49,7 @@ let agentCounter = 0;
 
 async function createAgentInstance(
   modelType: string,
+  owner: UserInfo,
   delegateConfig: AgentDelegateConfig,
   customName?: string
 ): Promise<{ agentId: string; agent: TexeraAgent }> {
@@ -70,6 +72,7 @@ async function createAgentInstance(
     agentId,
     agentName: customName || "Bob",
     userToken: delegateConfig.userToken,
+    ownerUid: owner.uid,
   });
 
   await agent.initialize();
@@ -97,7 +100,7 @@ async function createAgentInstance(
   }
 
   agentStore.set(agentId, agent);
-  log.info({ agentId, userId: delegateConfig.userInfo?.uid }, "created agent");
+  log.info({ agentId, userId: owner.uid }, "created agent");
 
   return { agentId, agent };
 }
@@ -137,8 +140,17 @@ function getAgentInfo(agentId: string, agent: 
TexeraAgent): AgentInfo {
   };
 }
 
-function getAgent(agentId: string): TexeraAgent {
-  const agent = agentStore.get(agentId);
+// An agent answers only to the user who created it. To anyone else it does not
+// exist, so a caller cannot tell another user's agent from an id never issued.
+function ownedAgent(agentId: string | undefined, user: UserInfo | undefined): 
TexeraAgent | undefined {
+  const agent = agentId === undefined ? undefined : agentStore.get(agentId);
+  return agent && user && agent.ownerUid === user.uid ? agent : undefined;
+}
+
+// The agent a route names, for its owner only. Routes reach agents only 
through here,
+// so none can serve one without checking who is asking.
+function getAgent(agentId: string, user: UserInfo): TexeraAgent {
+  const agent = ownedAgent(agentId, user);
   if (!agent) {
     throw new Error("Agent not found");
   }
@@ -168,40 +180,46 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
     set.status = ERROR_STATUS[errorMessage] ?? 500;
     return { error: errorMessage || "Internal server error" };
   })
-  .get("/", () => {
-    const agentList = Array.from(agentStore.entries()).map(([id, agent]) => 
getAgentInfo(id, agent));
+  // Every agent route acts as the user in the request's bearer token, which
+  // travels in the Authorization header, never in the payload. A route that
+  // names an agent gets it from getAgent, which serves only its owner.
+  .derive(({ headers }) => {
+    const userToken = extractBearerToken(headers.authorization);
+    if (!userToken) {
+      throw new Error("Authorization header with a Bearer token is required");
+    }
+    const user = verifyToken(userToken);
+    if (!user) {
+      throw new Error("Invalid or expired token");
+    }
+    return { userToken, user };
+  })
+  .get("/", ({ user }) => {
+    const agentList = Array.from(agentStore.entries())
+      .filter(([, agent]) => agent.ownerUid === user.uid)
+      .map(([id, agent]) => getAgentInfo(id, agent));
     return { agents: agentList };
   })
 
   .post(
     "/",
-    async ({ body, headers }) => {
+    async ({ body, userToken, user }) => {
       const { modelType, name, workflowId, computingUnitId, settings } = body 
as CreateAgentRequest;
 
       if (!modelType) {
         throw new Error("modelType is required");
       }
 
-      // The agent always calls the LLM gateway as the delegating user, so an
-      // agent without a user token would be unable to generate anything. The
-      // token travels in the Authorization header, never in the payload.
-      const userToken = extractBearerToken(headers.authorization);
-      if (!userToken) {
-        throw new Error("Authorization header with a Bearer token is 
required");
-      }
-      if (!validateToken(userToken)) {
-        throw new Error("Invalid or expired token");
-      }
-
-      const userInfo = extractUserFromToken(userToken);
+      // The agent always calls the LLM gateway as the delegating user, so it
+      // keeps that user's token.
       const delegateConfig: AgentDelegateConfig = {
         userToken,
-        userInfo,
+        userInfo: user,
         workflowId,
         computingUnitId,
       };
 
-      const { agentId, agent } = await createAgentInstance(modelType, 
delegateConfig, name);
+      const { agentId, agent } = await createAgentInstance(modelType, user, 
delegateConfig, name);
 
       if (settings) {
         log.info(
@@ -250,8 +268,8 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
     }
   )
 
-  .get("/:id", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     return {
       ...getAgentInfo(id, agent),
       workflow: agent.getWorkflowState().getWorkflowContent(),
@@ -259,32 +277,27 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
     };
   })
 
-  .delete("/:id", ({ params: { id }, set }) => {
-    const agent = agentStore.get(id);
-    if (!agent) {
-      set.status = 404;
-      return { error: "Agent not found" };
-    }
-
+  .delete("/:id", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     agent.destroy();
     agentStore.delete(id);
     return { deleted: true };
   })
 
-  .get("/:id/react-steps", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id/react-steps", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     return { steps: agent.getReActSteps(), state: agent.getState() };
   })
 
-  .get("/:id/operator-results", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id/operator-results", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     return { results: getOperatorResultSummaries(agent) };
   })
 
   .post(
     "/:id/steps-by-operators",
-    ({ params: { id }, body }) => {
-      const agent = getAgent(id);
+    ({ params: { id }, body, user }) => {
+      const agent = getAgent(id, user);
       const { operatorIds } = body;
       return { steps: agent.getReActStepsByOperatorIds(operatorIds || []) };
     },
@@ -295,33 +308,33 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
     }
   )
 
-  .get("/:id/system-info", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id/system-info", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     return agent.getSystemInfo();
   })
 
-  .post("/:id/stop", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .post("/:id/stop", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     agent.stop();
     // Report the resulting state: STOPPING mid-run, unchanged when idle.
     return { status: agent.getState() };
   })
 
-  .post("/:id/clear", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .post("/:id/clear", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     agent.clearHistory();
     return { status: "cleared" };
   })
 
-  .get("/:id/operator-types", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id/operator-types", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     const metadataStore = agent.getMetadataStore();
     const allTypes = metadataStore.getAllOperatorTypes();
     return Object.entries(allTypes).map(([type, description]) => ({ type, 
description }));
   })
 
-  .get("/:id/settings", ({ params: { id } }) => {
-    const agent = getAgent(id);
+  .get("/:id/settings", ({ params: { id }, user }) => {
+    const agent = getAgent(id, user);
     const agentSettings = agent.getSettings();
     return {
       maxOperatorResultCharLimit: agentSettings.maxOperatorResultCharLimit,
@@ -337,8 +350,8 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
 
   .patch(
     "/:id/settings",
-    ({ params: { id }, body }) => {
-      const agent = getAgent(id);
+    ({ params: { id }, body, user }) => {
+      const agent = getAgent(id, user);
       const settings = body as UpdateAgentSettingsRequest;
 
       log.info(
@@ -410,6 +423,14 @@ function sendEventToClient(ws: { send(data: string): void 
}, event: WsServerEven
   ws.send(JSON.stringify(event));
 }
 
+// The agent a socket may use: the one in its path, when the token in its query
+// is the owner's. A browser cannot set headers on a WebSocket, so the token
+// arrives as `access-token`, as it does on the workflow websocket.
+function socketAgent(ws: { data: unknown }): TexeraAgent | undefined {
+  const { params, query } = ws.data as { params?: { id?: string }; query?: 
Record<string, string | undefined> };
+  return ownedAgent(params?.id, verifyToken(query?.["access-token"]));
+}
+
 // Broadcast a server event to every client attached to the agent.
 function broadcastToAgentClients(agentId: string, event: WsServerEvent): void {
   const agent = agentStore.get(agentId);
@@ -442,7 +463,7 @@ export function buildApp() {
         const agentId = (ws.data as any).params?.id;
         wsLog.info({ agentId }, "client connected");
 
-        const agent = agentStore.get(agentId);
+        const agent = socketAgent(ws);
         if (!agent) {
           sendEventToClient(ws, new WsServerErrorEvent("Agent not found"));
           ws.close();
@@ -456,7 +477,7 @@ export function buildApp() {
 
       async message(ws, messageData) {
         const agentId = (ws.data as any).params?.id;
-        const agent = agentStore.get(agentId);
+        const agent = socketAgent(ws);
 
         if (!agent) {
           sendEventToClient(ws, new WsServerErrorEvent("Agent not found"));
diff --git a/agent-service/src/server.ws.spec.ts 
b/agent-service/src/server.ws.spec.ts
index cf372bcf03..a5da445301 100644
--- a/agent-service/src/server.ws.spec.ts
+++ b/agent-service/src/server.ws.spec.ts
@@ -25,6 +25,7 @@
 
 import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } 
from "bun:test";
 import { buildApp, _resetAgentStoreForTests, _getAgentForTests } from 
"./server";
+import { mintTestToken } from "./api/test-token";
 import { env } from "./config/env";
 import { AgentState } from "./types/agent";
 
@@ -34,21 +35,10 @@ let app: ReturnType<typeof buildApp>;
 let port: number;
 const openSockets: WebSocket[] = [];
 
-function mintTestToken(): string {
-  const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" 
})).toString("base64url");
-  const payload = Buffer.from(
-    JSON.stringify({
-      sub: "tester",
-      userId: 1,
-      email: "[email protected]",
-      role: "REGULAR",
-      exp: Math.floor(Date.now() / 1000) + 3600,
-    })
-  ).toString("base64url");
-  return `${header}.${payload}.test-signature`;
-}
-
 const TOKEN = mintTestToken();
+const OTHER_USER_TOKEN = mintTestToken(2);
+// TOKEN's claims under a signature the dashboard service did not make.
+const FORGED_TOKEN = mintTestToken(1, "not-the-secret");
 
 async function createAgent(): Promise<string> {
   const res = await app.handle(
@@ -112,8 +102,10 @@ function collect(ws: WebSocket): Collector {
   };
 }
 
-function connect(agentId: string): { ws: WebSocket; messages: Collector } {
-  const ws = new 
WebSocket(`ws://localhost:${port}${API}/agents/${agentId}/react`);
+// A browser cannot set headers on a WebSocket, so the token rides in the 
query.
+function connect(agentId: string, token: string | null = TOKEN): { ws: 
WebSocket; messages: Collector } {
+  const query = token ? `?access-token=${token}` : "";
+  const ws = new 
WebSocket(`ws://localhost:${port}${API}/agents/${agentId}/react${query}`);
   openSockets.push(ws);
   return { ws, messages: collect(ws) };
 }
@@ -170,6 +162,46 @@ describe(`WS ${API}/agents/:id/react`, () => {
     expect(err.error).toBe("Agent not found");
   });
 
+  // An agent answers only to its owner: the answer for anyone else is the one 
for
+  // an agent that does not exist, and the socket never joins the agent's 
clients.
+  test.each([
+    ["another user's token", OTHER_USER_TOKEN],
+    ["the owner's claims under a forged signature", FORGED_TOKEN],
+    ["no token", null],
+    ["a token that is not a JWT", "not-a-jwt"],
+  ])("refuses a socket carrying %s", async (_label, token) => {
+    const id = await createAgent();
+    const { ws, messages } = connect(id, token);
+    const closed = new Promise<void>(resolve => ws.addEventListener("close", 
() => resolve(), { once: true }));
+
+    const err = await messages.waitFor(m => m.type === "WsServerErrorEvent");
+    expect(err.error).toBe("Agent not found");
+    await closed;
+    expect(_getAgentForTests(id)!.getClients().size).toBe(0);
+  });
+
+  test("ignores a prompt sent on a socket that does not belong to the owner", 
async () => {
+    const id = await createAgent();
+    const agent = _getAgentForTests(id)!;
+    let ran = false;
+    (agent as any).sendMessage = async () => {
+      ran = true;
+      return { response: "", messages: [], usage: {}, stopped: false };
+    };
+
+    const { ws, messages } = connect(id, OTHER_USER_TOKEN);
+    // Send as soon as the socket opens, before the server's close reaches the 
client.
+    ws.addEventListener(
+      "open",
+      () => ws.send(JSON.stringify({ type: "WsClientPromptCommand", content: 
"run as the owner" })),
+      { once: true }
+    );
+    await new Promise<void>(resolve => ws.addEventListener("close", () => 
resolve(), { once: true }));
+    await messages.waitFor(m => m.type === "WsServerErrorEvent");
+
+    expect(ran).toBe(false);
+  });
+
   test("a stop command mid-run broadcasts a STOPPING status frame", async () 
=> {
     const id = await createAgent();
     (_getAgentForTests(id)! as any).state = "GENERATING";
diff --git a/bin/k8s/templates/base/agent-service/agent-service-deployment.yaml 
b/bin/k8s/templates/base/agent-service/agent-service-deployment.yaml
index 4732bae1fa..de0645eb8b 100644
--- a/bin/k8s/templates/base/agent-service/agent-service-deployment.yaml
+++ b/bin/k8s/templates/base/agent-service/agent-service-deployment.yaml
@@ -59,6 +59,14 @@ spec:
             # computing unit id at request time.
             - name: EXECUTION_ENDPOINT_TEMPLATE
               value: http://computing-unit-{cuid}.{{ 
.Values.workflowComputingUnitPool.name }}-svc.{{ 
.Values.workflowComputingUnitPool.namespace }}.svc.cluster.local:{{ 
.Values.workflowComputingUnitPool.service.port }}
+            # The secret the dashboard service signs login tokens with: the 
agent
+            # service verifies every token with it, so it must be the same 
value.
+            {{- range .Values.texeraEnvVars }}
+            {{- if eq .name "AUTH_JWT_SECRET" }}
+            - name: {{ .name }}
+              value: "{{ .value }}"
+            {{- end }}
+            {{- end }}
           # The service loads operator metadata from the dashboard service on
           # startup, so gate readiness on its health endpoint before the 
gateway
           # routes traffic here. /api/healthcheck needs no auth.
diff --git a/frontend/src/app/workspace/service/agent/agent.service.spec.ts 
b/frontend/src/app/workspace/service/agent/agent.service.spec.ts
index e9aa92ec14..b4e8bda867 100644
--- a/frontend/src/app/workspace/service/agent/agent.service.spec.ts
+++ b/frontend/src/app/workspace/service/agent/agent.service.spec.ts
@@ -26,6 +26,7 @@ import { NotificationService } from 
"../../../common/service/notification/notifi
 import { WorkflowPersistService } from 
"../../../common/service/workflow-persist/workflow-persist.service";
 import { ComputingUnitStatusService } from 
"../../../common/service/computing-unit/computing-unit-status/computing-unit-status.service";
 import { WarehouseService } from 
"../../../common/service/warehouse/warehouse.service";
+import { TOKEN_KEY } from "../../../common/service/user/auth.service";
 import { DashboardWorkflowComputingUnit } from 
"../../../common/type/workflow-computing-unit";
 import { Workflow } from "../../../common/type/workflow";
 import { commonTestProviders } from "../../../common/testing/test-utils";
@@ -498,6 +499,22 @@ describe("AgentService", () => {
         expect(FakeWebSocket.instances.length).toBe(1);
       });
 
+      it("sends the signed-in user's token in the websocket query, where the 
agent service reads it", () => {
+        // The agent service opens the socket only for the agent's owner; a 
browser cannot set
+        // headers on a WebSocket, so the token has to travel in the URL.
+        localStorage.setItem(TOKEN_KEY, "header.payload.signature+/=");
+        try {
+          seedAgent("agent-1");
+          service.activateAgent("agent-1");
+
+          const url = new URL(FakeWebSocket.latest().url);
+          expect(url.pathname).toBe("/api/agents/agent-1/react");
+          
expect(url.searchParams.get("access-token")).toBe("header.payload.signature+/=");
+        } finally {
+          localStorage.removeItem(TOKEN_KEY);
+        }
+      });
+
       it("closes the socket and recreates stopPolling$ on deactivate, then 
reconnects on activate", () => {
         seedAgent("agent-1");
         service.activateAgent("agent-1");
diff --git a/frontend/src/app/workspace/service/agent/agent.service.ts 
b/frontend/src/app/workspace/service/agent/agent.service.ts
index e452895af8..3bccc6475f 100644
--- a/frontend/src/app/workspace/service/agent/agent.service.ts
+++ b/frontend/src/app/workspace/service/agent/agent.service.ts
@@ -41,6 +41,7 @@ import { AgentState, ReActStep, ModelMessage } from 
"./agent-types";
 import { Workflow, WorkflowContent } from "../../../common/type/workflow";
 import { ComputingUnitStatusService } from 
"../../../common/service/computing-unit/computing-unit-status/computing-unit-status.service";
 import { WarehouseService } from 
"../../../common/service/warehouse/warehouse.service";
+import { AuthService } from "../../../common/service/user/auth.service";
 import type { WebOutputMode } from "../../types/execute-workflow.interface";
 import type { SchemaAttribute } from 
"../../types/workflow-compiling.interface";
 
@@ -458,9 +459,14 @@ export class AgentService {
    * Start WebSocket connection for real-time ReActSteps updates
    */
   private startStatePolling(agentId: string, tracking: AgentStateTracking): 
void {
-    // Build WebSocket URL
+    // Build WebSocket URL. The agent service opens the socket only for the 
agent's owner, and a
+    // browser cannot set headers on a WebSocket, so the user's token rides in 
the query, as it
+    // does on the workflow websocket.
     const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
-    const wsUrl = 
`${wsProtocol}//${window.location.host}${this.AGENT_API_BASE}/agents/${agentId}/react`;
+    const token = AuthService.getAccessToken();
+    const wsUrl =
+      
`${wsProtocol}//${window.location.host}${this.AGENT_API_BASE}/agents/${agentId}/react`
 +
+      (token !== null ? `?access-token=${encodeURIComponent(token)}` : "");
 
     const ws = new WebSocket(wsUrl);
     tracking.websocket = ws;

Reply via email to