From 91b7223fb1dd2bb65266317a8e7d0ef3562bb275 Mon Sep 17 00:00:00 2001 From: Jiadong Bai <43344272+bobbai00@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:13:07 -0800 Subject: [PATCH] feat(agent-service): scope agents to their verified owner Any caller could list every user's agents and read or drive any of them: the agent list was not per user, routes and the websocket looked an agent up by id alone, and the one token check, at creation, only decoded the token. The service now verifies a token's HS256 signature with the secret the dashboard service signs it with (AUTH_JWT_SECRET, defaulting to auth.conf's value as the backend does) before trusting its claims. Each agent records the user who created it. Every /agents route requires the token, the list returns the caller's agents only, and a route or websocket naming another user's agent answers as for an agent that does not exist. The frontend sends the token in the agent websocket's query, as the workflow websocket does, and the Kubernetes chart passes the secret to the service. --- 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 | 48 +++++++- agent-service/src/api/auth-api.ts | 19 ++- agent-service/src/config/env.ts | 8 +- agent-service/src/server.spec.ts | 109 ++++++++++++++++-- agent-service/src/server.ts | 85 +++++++++----- agent-service/src/server.ws.spec.ts | 58 +++++++++- .../agent-service-deployment.yaml | 8 ++ .../service/agent/agent.service.spec.ts | 17 +++ .../workspace/service/agent/agent.service.ts | 10 +- 12 files changed, 329 insertions(+), 54 deletions(-) diff --git a/agent-service/.env.example b/agent-service/.env.example index 605f157ca0c..ec578986874 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 a1644921cfe..7b39bb93557 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"); }); }); @@ -403,6 +410,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 555cc2730ff..5c7356388bc 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 { @@ -89,6 +91,7 @@ export class TexeraAgent { readonly agentName: string; readonly modelType: string; readonly createdAt: Date; + readonly ownerUid: number; private state: AgentStateEnum = AgentStateEnum.AVAILABLE; private workflowState: WorkflowState; @@ -135,6 +138,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 0037790ffc4..057c61ac11c 100644 --- a/agent-service/src/api/auth-api.spec.ts +++ b/agent-service/src/api/auth-api.spec.ts @@ -18,16 +18,22 @@ */ import { describe, expect, test } from "bun:test"; +import { createHmac } from "node:crypto"; +import { readFileSync } from "node:fs"; import { createAuthHeaders, extractBearerToken, extractUserFromToken, validateToken } from "./auth-api"; +import { env, EnvSchema } from "../config/env"; + +function segment(value: Record): string { + return Buffer.from(JSON.stringify(value), "utf-8").toString("base64url"); +} /** - * 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. + * Builds a token carrying the given payload, signed the way the dashboard service signs one: + * HS256 over the first two segments, with the shared secret unless a test names another. */ -function tokenWith(payload: Record): string { - const encoded = Buffer.from(JSON.stringify(payload), "utf-8").toString("base64"); - return `header.${encoded}.signature`; +function tokenWith(payload: Record, secret: string = env.AUTH_JWT_SECRET): string { + const signed = `${segment({ alg: "HS256" })}.${segment(payload)}`; + return `${signed}.${createHmac("sha256", secret).update(signed).digest("base64url")}`; } /** `exp` is a UNIX second count, so expiries are built in seconds throughout. */ @@ -101,6 +107,36 @@ describe("validateToken", () => { // and reject it. A far-future second count must still validate. expect(validateToken(tokenWith({ exp: nowInSeconds() + 3600 }))).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 forged = tokenWith({ userId: 1, sub: "texera", role: "ADMIN", exp: nowInSeconds() + 60 }, "not-the-secret"); + + expect(validateToken(forged)).toBe(false); + }); + + test("rejects a token whose claims were edited after it was signed", () => { + const [header, , signature] = tokenWith({ userId: 2, sub: "bob", exp: nowInSeconds() + 60 }).split("."); + const edited = segment({ userId: 1, sub: "bob", exp: nowInSeconds() + 60 }); + + expect(validateToken(`${header}.${edited}.${signature}`)).toBe(false); + }); + + 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 unsigned = `${segment({ alg: "none" })}.${segment({ userId: 1, sub: "texera", exp: nowInSeconds() + 60 })}.`; + + expect(validateToken(unsigned)).toBe(false); + }); + + 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]); + }); }); describe("extractBearerToken", () => { diff --git a/agent-service/src/api/auth-api.ts b/agent-service/src/api/auth-api.ts index 4a166269c74..35b17d8af13 100644 --- a/agent-service/src/api/auth-api.ts +++ b/agent-service/src/api/auth-api.ts @@ -17,6 +17,8 @@ * 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"; @@ -53,8 +55,23 @@ function isTokenExpired(token: string): boolean { } } +// 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); +} + +// A token's claims can be trusted only when this holds: anyone can write the claims, +// only the dashboard service can sign them. export function validateToken(token: string): boolean { - return !isTokenExpired(token); + return isSignedByTexera(token) && !isTokenExpired(token); } export function extractBearerToken(header: string | undefined): string | undefined { diff --git a/agent-service/src/config/env.ts b/agent-service/src/config/env.ts index 3513286b149..ab7b3e00624 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,12 @@ 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. + AUTH_JWT_SECRET: z.string().min(1).default("8a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d"), }); export const env = EnvSchema.parse(process.env); diff --git a/agent-service/src/server.spec.ts b/agent-service/src/server.spec.ts index 2b42f5dc7e6..39a9df34098 100644 --- a/agent-service/src/server.spec.ts +++ b/agent-service/src/server.spec.ts @@ -18,6 +18,7 @@ */ import { beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { createHmac } from "node:crypto"; import { buildApp, start, _resetAgentStoreForTests, _getAgentForTests } from "./server"; import { WorkflowSystemMetadata } from "./agent/util/workflow-system-metadata"; import { env } from "./config/env"; @@ -26,27 +27,42 @@ import { ConsoleMessageType, OperatorState } from "./types/execution"; const API = env.API_PREFIX; const app = buildApp(); -function mintTestToken(): string { +// Signed as the dashboard service signs a login token, unless a test names another secret. +function mintTestToken(userId = 1, secret: string = env.AUTH_JWT_SECRET): string { const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"); const payload = Buffer.from( JSON.stringify({ sub: "tester", - userId: 1, + userId, email: "tester@example.com", role: "REGULAR", exp: Math.floor(Date.now() / 1000) + 3600, }) ).toString("base64url"); - return `${header}.${payload}.test-signature`; + const signature = createHmac("sha256", secret).update(`${header}.${payload}`).digest("base64url"); + return `${header}.${payload}.${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 = {}): Promise { +// 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 { + return token ? { Authorization: `Bearer ${token}` } : {}; +} + +async function postJson( + path: string, + body: unknown, + headers: Record = bearer(TOKEN) +): Promise { return app.handle( new Request(url(path), { method: "POST", @@ -57,25 +73,25 @@ async function postJson(path: string, body: unknown, headers: Record = {}, token: string | null = TOKEN): Promise { - 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 { +async function patchJson(path: string, body: unknown, token: string | null = TOKEN): Promise { 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 { - return app.handle(new Request(url(path))); +async function getJson(path: string, token: string | null = TOKEN): Promise { + return app.handle(new Request(url(path), { headers: bearer(token) })); } -async function del(path: string): Promise { - return app.handle(new Request(url(path), { method: "DELETE" })); +async function del(path: string, token: string | null = TOKEN): Promise { + return app.handle(new Request(url(path), { method: "DELETE", headers: bearer(token) })); } async function readJson(res: Response): Promise { @@ -167,6 +183,77 @@ 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(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", () => { + const ROUTES: [method: string, path: string, body?: unknown][] = [ + ["GET", ""], + ["DELETE", ""], + ["GET", "/react-steps"], + ["GET", "/operator-results"], + ["POST", "/steps-by-operators", { operatorIds: [] }], + ["GET", "/system-info"], + ["POST", "/stop", {}], + ["POST", "/clear", {}], + ["GET", "/operator-types"], + ["GET", "/settings"], + ["PATCH", "/settings", { maxSteps: 3 }], + ]; + + function request(method: string, path: string, body: unknown, token: string | null): Promise { + 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 02981e02ad6..ff287599d20 100644 --- a/agent-service/src/server.ts +++ b/agent-service/src/server.ts @@ -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(); @@ -145,6 +148,22 @@ function getAgent(agentId: string): TexeraAgent { return agent; } +// The user a token identifies, or undefined when it is missing, malformed or expired. +function userOfToken(token: string | undefined): UserInfo | undefined { + if (!token || !validateToken(token)) { + return undefined; + } + const user = extractUserFromToken(token); + return typeof user.uid === "number" ? user : undefined; +} + +// 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; +} + // Status codes for handler-thrown errors; anything unlisted is a 500. const ERROR_STATUS: Record = { "Agent not found": 404, @@ -168,40 +187,51 @@ 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 is served only to that agent's owner. + .derive(({ headers, params }) => { + const userToken = extractBearerToken(headers.authorization); + if (!userToken) { + throw new Error("Authorization header with a Bearer token is required"); + } + const user = userOfToken(userToken); + if (!user) { + throw new Error("Invalid or expired token"); + } + // Routes without a path parameter carry no `params` at all. + const agentId = (params as { id?: string } | undefined)?.id; + if (agentId !== undefined && !ownedAgent(agentId, user)) { + throw new Error("Agent not found"); + } + 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( @@ -259,13 +289,8 @@ 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 } }) => { + const agent = getAgent(id); agent.destroy(); agentStore.delete(id); return { deleted: true }; @@ -409,6 +434,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 }; + return ownedAgent(params?.id, userOfToken(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); @@ -441,7 +474,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(); @@ -455,7 +488,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 cbb1ffb8ebd..7629096f806 100644 --- a/agent-service/src/server.ws.spec.ts +++ b/agent-service/src/server.ws.spec.ts @@ -24,6 +24,7 @@ // perform WS upgrades. import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { createHmac } from "node:crypto"; import { buildApp, _resetAgentStoreForTests, _getAgentForTests } from "./server"; import { env } from "./config/env"; @@ -33,21 +34,26 @@ let app: ReturnType; let port: number; const openSockets: WebSocket[] = []; -function mintTestToken(): string { +// Signed as the dashboard service signs a login token, unless a test names another secret. +function mintTestToken(userId = 1, secret: string = env.AUTH_JWT_SECRET): string { const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"); const payload = Buffer.from( JSON.stringify({ sub: "tester", - userId: 1, + userId, email: "tester@example.com", role: "REGULAR", exp: Math.floor(Date.now() / 1000) + 3600, }) ).toString("base64url"); - return `${header}.${payload}.test-signature`; + const signature = createHmac("sha256", secret).update(`${header}.${payload}`).digest("base64url"); + return `${header}.${payload}.${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 { const res = await app.handle( @@ -111,8 +117,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) }; } @@ -169,6 +177,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(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(resolve => ws.addEventListener("close", () => resolve(), { once: true })); + await messages.waitFor(m => m.type === "WsServerErrorEvent"); + + expect(ran).toBe(false); + }); + test("a stop command broadcasts a STOPPING status frame", async () => { const id = await createAgent(); const { ws, messages } = connect(id); 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 4732bae1fa4..de0645eb8b5 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 c11bcd97cc0..1b5cef0bbfd 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 4692d7beb7a..a61a97cb3a0 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;