From 081485c8fdb90ea57dd414583bd3ab6d2ea42872 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 11:40:08 -0600 Subject: [PATCH 1/3] feat(pm-dispatch): authenticated read/status endpoints for tasks and sessions (#5555) --- pm-stack/dispatch/README.md | 25 ++++++- pm-stack/dispatch/install.sh | 4 +- pm-stack/dispatch/src/opencode.ts | 14 ++++ pm-stack/dispatch/src/server.ts | 98 ++++++++++++++++++++++++- pm-stack/dispatch/test/opencode.test.ts | 36 +++++++++ pm-stack/dispatch/test/server.test.ts | 91 ++++++++++++++++++++++- 6 files changed, 264 insertions(+), 4 deletions(-) diff --git a/pm-stack/dispatch/README.md b/pm-stack/dispatch/README.md index b80dd946c8..d4ea8a6f95 100644 --- a/pm-stack/dispatch/README.md +++ b/pm-stack/dispatch/README.md @@ -122,6 +122,25 @@ where the GitHub App is not installed, the attach is skipped with a `warnings` entry; the task is still enqueued and `issue_number` is still returned. +### `GET /v1/tasks/:id` — task status (issue #5555) + +Authenticated read of the queue task row dispatch (or a worker) +created: `{task_id, queue, title, status, worker_id, lane_id, repo, +kind, attempts, max_attempts, claimed_at, lease_until, created_at, +updated_at, completed_at, progress, result, last_error, dedupe_key}`. +The packet body and payload are NOT returned — this is a status +surface, not a packet dump; only the payload's `repo`/`kind` are +surfaced, and a task whose packet names a repo is readable only by +callers allowed for that repo (the same gate as the write routes). +Unknown id → `404`; non-numeric id → `400`; unauthenticated → `401`. + +### `GET /v1/sessions/:id` — session status (issue #5555) + +Authenticated read proxied from the OpenCode server: +`{session_id, title, directory, time}`. A session the OpenCode +server does not know → `404`; an OpenCode-side failure (server down, +auth) → `502`, never conflated with "session gone". + ### Why assignment is a direct PATCH The queue's `claim_repo_task` RPC claims the _next_ task in a queue — @@ -159,7 +178,11 @@ Every endpoint except `GET /health` requires `Authorization: Bearer …`: See `examples/dispatch-workflow.yml`. - **Static bearer secret**: `DISPATCH_API_TOKEN` (in the laptop's `~/secrets/dispatch.env`), compared in constant time — the shape a - repo stores as a GitHub Actions secret. + repo stores as a GitHub Actions secret. The vault home for the + value by name is Bitwarden **`pm-dispatch.api-token`** (filed + under issue #5555, verified byte-identical to the service's by + hash): a rotation updates the vault entry and + `~/secrets/dispatch.env` together. The caller identity (`{type:"bearer"}` or `{type:"oidc", repository, actor, workflow_ref}`) is recorded in the task payload. diff --git a/pm-stack/dispatch/install.sh b/pm-stack/dispatch/install.sh index 4871a2fc99..b0a44ead93 100755 --- a/pm-stack/dispatch/install.sh +++ b/pm-stack/dispatch/install.sh @@ -20,7 +20,9 @@ # DELETED legacy project's preserved key is # `supabase.muse-dev.service-role-key` — never use it; see code#5120.) # - NOT in sops: DISPATCH_API_TOKEN lives in ~/secrets/dispatch.env -# (mode 600, laptop-only), which the unit also reads. This script +# (mode 600, laptop-only), which the unit also reads. Its by-name +# vault home is Bitwarden `pm-dispatch.api-token` (issue #5555) — +# a rotation updates both places. This script # ensures that file exists and carries a generated # DISPATCH_API_TOKEN when one is absent. SUPABASE_URL / # SUPABASE_SERVICE_ROLE_KEY lines left in that file are stale: the diff --git a/pm-stack/dispatch/src/opencode.ts b/pm-stack/dispatch/src/opencode.ts index 6b572f4a91..1840de0cc5 100644 --- a/pm-stack/dispatch/src/opencode.ts +++ b/pm-stack/dispatch/src/opencode.ts @@ -94,4 +94,18 @@ export class OpenCodeClient { async listSessions(): Promise { return this.api("GET", "/api/session"); } + + /** Read one session's current state (issue #5555): the raw session + * object from the OpenCode server, or null when the server says the + * session does not exist (HTTP 404). Any other failure (server down, + * auth, non-JSON) stays an OpenCodeError so callers can tell "gone" + * apart from "unknown". */ + async getSession(sessionId: string): Promise { + try { + return await this.api("GET", `/api/session/${encodeURIComponent(sessionId)}`); + } catch (e) { + if (e instanceof OpenCodeError && e.message.includes("(HTTP 404)")) return null; + throw e; + } + } } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 24f5d06f38..4e041da5bf 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -5,6 +5,12 @@ // usually a GitHub issue. // POST /v1/tasks enqueue-only: a repo-task/v1 packet into the // Supabase queue, optionally with a GitHub issue. +// GET /v1/tasks/:id authenticated read: that task's status, +// worker and progress (issue #5555) — callers no +// longer cross domains into the queue store. +// GET /v1/sessions/:id authenticated read: that OpenCode session's +// existence/state, proxied from the OpenCode +// server (issue #5555). // GET /health unauthenticated {ok, version}, aggregator-style. // // Everything else requires auth (GitHub Actions OIDC or the static bearer @@ -39,7 +45,7 @@ import { } from "./launch_failure.ts"; import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; -import { OpenCodeClient } from "./opencode.ts"; +import { OpenCodeClient, OpenCodeError } from "./opencode.ts"; const cfg: Config = loadConfig(); const queue = cfg.supabaseServiceRoleKey ? new QueueClient(cfg.supabaseUrl, cfg.supabaseServiceRoleKey) : null; @@ -629,6 +635,86 @@ export async function verifyAttachTarget(args: { return { outcome: "verified" }; } +// --------------------------------------------------------------------------- +// GET /v1/tasks/:id and GET /v1/sessions/:id — read/status (issue #5555) +// --------------------------------------------------------------------------- + +/** The caller-facing view of a queue task row: identity, lifecycle and + * the fields a dispatch caller needs to answer "what happened to task + * N?" — status, worker, progress, result — without the packet body or + * payload internals (the payload can carry caller prompts verbatim; + * the read route is a status surface, not a packet dump). */ +export function taskStatusView(row: TaskRow): Record { + const payload = (row.payload ?? null) as Record | null; + return { + task_id: row.id, + queue: row.queue, + title: row.title ?? null, + status: row.status, + worker_id: row.worker_id ?? null, + lane_id: row.lane_id ?? null, + repo: payload && typeof payload.repo === "string" ? payload.repo : null, + kind: payload && typeof payload.kind === "string" ? payload.kind : null, + attempts: row.attempts ?? null, + max_attempts: row.max_attempts ?? null, + claimed_at: row.claimed_at ?? null, + lease_until: row.lease_until ?? null, + created_at: row.created_at ?? null, + updated_at: row.updated_at ?? null, + completed_at: row.completed_at ?? null, + progress: row.progress ?? null, + result: row.result ?? null, + last_error: row.last_error ?? null, + dedupe_key: row.dedupe_key, + }; +} + +/** The caller-facing view of an OpenCode session: existence plus the + * identifying/state fields the server reports. Unknown extra fields + * are not forwarded — the session object is another service's schema + * and this route promises a stable minimal shape. */ +export function sessionStatusView(raw: unknown): Record { + const obj = (typeof raw === "object" && raw !== null ? raw : {}) as Record; + return { + session_id: typeof obj.id === "string" ? obj.id : null, + title: typeof obj.title === "string" ? obj.title : null, + directory: + typeof obj.directory === "string" + ? obj.directory + : typeof (obj.location as Record | undefined)?.directory === "string" + ? ((obj.location as Record).directory as string) + : null, + time: typeof obj.time === "object" && obj.time !== null ? obj.time : null, + }; +} + +async function handleGetTask(caller: CallerIdentity, idSegment: string): Promise { + if (!/^\d+$/.test(idSegment)) throw new ValidationError("task id: must be a positive integer"); + const id = Number(idSegment); + if (!Number.isSafeInteger(id) || id <= 0) throw new ValidationError("task id: must be a positive integer"); + const row = await requireQueue().getTask(id); + if (!row) return json(404, { error: `task ${id} not found` }); + const view = taskStatusView(row); + // Same repo gate as the write routes: a task whose packet names a + // repo is only readable by callers allowed for that repo. + if (typeof view.repo === "string") assertCallerRepo(caller, view.repo, cfg.repoAllowlist); + return json(200, view); +} + +async function handleGetSession(idSegment: string): Promise { + const sessionId = decodeURIComponent(idSegment); + if (!sessionId.trim()) throw new ValidationError("session id: required"); + let raw: unknown; + try { + raw = await opencode.getSession(sessionId); + } catch (e) { + if (e instanceof OpenCodeError) return json(e.status, { error: e.message }); + throw e; + } + if (raw === null || raw === undefined) return json(404, { error: `session ${sessionId} not found` }); + return json(200, sessionStatusView(raw)); +} + // --------------------------------------------------------------------------- // Routing // --------------------------------------------------------------------------- @@ -650,6 +736,16 @@ export async function handler(req: Request): Promise { }); return path === "/v1/sessions" ? await handleSessions(req, caller) : await handleTasks(req, caller); } + const taskMatch = path.match(/^\/v1\/tasks\/([^/]+)$/); + const sessionMatch = path.match(/^\/v1\/sessions\/([^/]+)$/); + if (req.method === "GET" && (taskMatch || sessionMatch)) { + const caller = await authenticate(req, { + apiToken: cfg.apiToken, + oidcAudience: cfg.oidcAudience, + allowlist: cfg.repoAllowlist, + }); + return taskMatch ? await handleGetTask(caller, taskMatch[1]) : await handleGetSession(sessionMatch![1]); + } return json(404, { error: "not found" }); } catch (e) { if (e instanceof AuthError) return json(401, { error: e.message }); diff --git a/pm-stack/dispatch/test/opencode.test.ts b/pm-stack/dispatch/test/opencode.test.ts index 10595fd931..0060dcd3d1 100644 --- a/pm-stack/dispatch/test/opencode.test.ts +++ b/pm-stack/dispatch/test/opencode.test.ts @@ -102,3 +102,39 @@ describe("OpenCodeClient response body boundary (#7085)", () => { mode = "ok"; }); }); + +describe("OpenCodeClient.getSession (#5555)", () => { + let stub: ReturnType; + let stubUrl = ""; + beforeAll(() => { + stub = Bun.serve({ + port: 0, + fetch(req) { + const path = new URL(req.url).pathname; + if (path === "/api/session/ses_ok") return Response.json({ data: { id: "ses_ok", title: "t" } }); + if (path === "/api/session/ses_boom") return new Response("boom", { status: 500 }); + return new Response("nope", { status: 404 }); + }, + }); + stubUrl = `http://127.0.0.1:${stub.port}`; + }); + afterAll(() => { + stub.stop(true); + }); + + test("returns the session object on 200 (envelope unwrapped)", async () => { + const client = new OpenCodeClient(stubUrl, authFile("gs.json", JSON.stringify({ password: "pw" }))); + const raw = (await client.getSession("ses_ok")) as { id: string }; + expect(raw.id).toBe("ses_ok"); + }); + + test("returns null on 404 — the session does not exist", async () => { + const client = new OpenCodeClient(stubUrl, authFile("gs.json", JSON.stringify({ password: "pw" }))); + expect(await client.getSession("ses_missing")).toBeNull(); + }); + + test("a 500 stays an OpenCodeError — gone is not conflated with unknown", async () => { + const client = new OpenCodeClient(stubUrl, authFile("gs.json", JSON.stringify({ password: "pw" }))); + await expect(client.getSession("ses_boom")).rejects.toBeInstanceOf(OpenCodeError); + }); +}); diff --git a/pm-stack/dispatch/test/server.test.ts b/pm-stack/dispatch/test/server.test.ts index 7488107071..7fc9499ed2 100644 --- a/pm-stack/dispatch/test/server.test.ts +++ b/pm-stack/dispatch/test/server.test.ts @@ -52,7 +52,7 @@ function signOidc(repository: string): string { // (#5120), so the suite pins a fixture project (no service-role key: the // queue stays disabled, as these tests intend). process.env.SUPABASE_URL ??= "https://fixture.supabase.co"; -const { handler } = await import("../src/server.ts"); +const { handler, taskStatusView, sessionStatusView } = await import("../src/server.ts"); function sessionsRequest(token: string, body: Record): Request { return new Request("http://x/v1/sessions", { @@ -130,3 +130,92 @@ describe("POST /v1/sessions body cap is measured in UTF-8 bytes (issue #3010)", expect(res.status).toBe(502); }); }); + +describe("taskStatusView / sessionStatusView (#5555)", () => { + test("task view surfaces status/worker/progress and payload repo/kind, never the packet body", () => { + const view = taskStatusView({ + id: 42, + queue: "repo-health-code-pilot", + title: "Fix the thing", + status: "claimed", + worker_id: "repo-worker-code", + lane_id: "code-m", + attempts: 2, + max_attempts: 6, + claimed_at: "2026-11-09T00:00:00Z", + lease_until: "2026-11-09T01:00:00Z", + created_at: "2026-11-08T00:00:00Z", + updated_at: "2026-11-09T00:30:00Z", + completed_at: null, + progress: { stage: "executing" }, + result: null, + last_error: null, + dedupe_key: "repo-health:v1:fix:developing-today/code:issue:1", + payload: { repo: "developing-today/code", kind: "small_fix", prompt: "verbatim caller prompt" }, + body: "packet body text", + } as never); + expect(view.task_id).toBe(42); + expect(view.status).toBe("claimed"); + expect(view.worker_id).toBe("repo-worker-code"); + expect(view.progress).toEqual({ stage: "executing" }); + expect(view.repo).toBe("developing-today/code"); + expect(view.kind).toBe("small_fix"); + expect("body" in view).toBe(false); + expect("payload" in view).toBe(false); + expect(JSON.stringify(view)).not.toContain("verbatim caller prompt"); + }); + + test("task view without a payload reports null repo/kind", () => { + const view = taskStatusView({ id: 7, queue: "q", status: "queued", dedupe_key: "k" } as never); + expect(view.repo).toBeNull(); + expect(view.kind).toBeNull(); + expect(view.worker_id).toBeNull(); + }); + + test("session view picks id/title and the location directory", () => { + const view = sessionStatusView({ + id: "ses_1", + title: "work", + location: { directory: "/home/user/git/code" }, + time: { created: 1, updated: 2 }, + extra: "not forwarded", + }); + expect(view.session_id).toBe("ses_1"); + expect(view.directory).toBe("/home/user/git/code"); + expect(view.time).toEqual({ created: 1, updated: 2 }); + expect("extra" in view).toBe(false); + }); + + test("session view of a non-object payload yields null fields, not a throw", () => { + const view = sessionStatusView("nope"); + expect(view.session_id).toBeNull(); + expect(view.title).toBeNull(); + expect(view.directory).toBeNull(); + }); +}); + +describe("GET /v1/tasks/:id and /v1/sessions/:id read routes (#5555)", () => { + test("GET /v1/tasks/:id without auth is 401", async () => { + const res = await handler(new Request("http://x/v1/tasks/42")); + expect(res.status).toBe(401); + }); + + test("GET /v1/sessions/:id without auth is 401", async () => { + const res = await handler(new Request("http://x/v1/sessions/ses_1")); + expect(res.status).toBe(401); + }); + + test("GET /v1/tasks/:id with a non-numeric id is 400, before any queue access", async () => { + const token = signOidc("developing-today/code"); + const res = await handler(new Request("http://x/v1/tasks/abc", { headers: { authorization: `Bearer ${token}` } })); + expect(res.status).toBe(400); + }); + + test("GET /v1/tasks/:id authenticated reaches the queue (502 while unconfigured here)", async () => { + const token = signOidc("developing-today/code"); + const res = await handler(new Request("http://x/v1/tasks/42", { headers: { authorization: `Bearer ${token}` } })); + expect(res.status).toBe(502); + const body = (await res.json()) as { error: string }; + expect(body.error).toContain("queue unavailable"); + }); +}); From 3025e0326cf5098b033b7187bc0036f013d78d61 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 10 Nov 2026 23:48:26 -0600 Subject: [PATCH 2/3] fix(pm-dispatch): disposition CodeRabbit findings on the #5555 read routes - queue getTask throws QueueError on non-OK instead of returning null (an existing task no longer reads as 404 on a PostgREST 401/5xx); new findTaskBySessionId fails closed for the session repo gate - opencode api() wraps connection failures as OpenCodeError (routes answer the documented 502, not a raw 500) and records the upstream status on the error; getSession decides 404 from that status, never from message text - GET /v1/tasks/:id: an allowlist-denied task answers the same 404 as a missing one (no existence/repo leak to ID probes) - GET /v1/sessions/:id: caller-aware; malformed percent-encoding is a 400; dispatch-launched sessions are gated on their launching task repo being in the current allowlist, denied answers 404 - install.sh + README: token rotation restarts pm-dispatch.service; recovery from a lost dispatch.env restores the Bitwarden token before reinstalling - tests: opencode 500-with-404-text + connection failure, queue read-lookup failure mapping, malformed session id 400. Full suite 188 pass; tsc unchanged (4 pre-existing test-cast errors) --- pm-stack/dispatch/README.md | 9 ++++- pm-stack/dispatch/install.sh | 11 +++++- pm-stack/dispatch/src/opencode.ts | 43 +++++++++++++++++----- pm-stack/dispatch/src/queue.ts | 25 ++++++++++++- pm-stack/dispatch/src/server.ts | 49 ++++++++++++++++++++++--- pm-stack/dispatch/test/opencode.test.ts | 13 +++++++ pm-stack/dispatch/test/queue.test.ts | 37 +++++++++++++++++++ pm-stack/dispatch/test/server.test.ts | 6 +++ 8 files changed, 175 insertions(+), 18 deletions(-) diff --git a/pm-stack/dispatch/README.md b/pm-stack/dispatch/README.md index d4ea8a6f95..e4656cd2d3 100644 --- a/pm-stack/dispatch/README.md +++ b/pm-stack/dispatch/README.md @@ -182,7 +182,14 @@ Every endpoint except `GET /health` requires `Authorization: Bearer …`: value by name is Bitwarden **`pm-dispatch.api-token`** (filed under issue #5555, verified byte-identical to the service's by hash): a rotation updates the vault entry and - `~/secrets/dispatch.env` together. + `~/secrets/dispatch.env` together, and then restarts + `pm-dispatch.service` — the unit reads the env file only at + start, so without a restart the new token is rejected and the + old one stays valid. If `~/secrets/dispatch.env` is lost, + restore the token from this vault item before running + install.sh: a missing file makes the installer generate a fresh + token, desyncing the vault copy and every client (401s) until + they are updated to match. The caller identity (`{type:"bearer"}` or `{type:"oidc", repository, actor, workflow_ref}`) is recorded in the task payload. diff --git a/pm-stack/dispatch/install.sh b/pm-stack/dispatch/install.sh index b0a44ead93..21b26b977c 100755 --- a/pm-stack/dispatch/install.sh +++ b/pm-stack/dispatch/install.sh @@ -22,7 +22,16 @@ # - NOT in sops: DISPATCH_API_TOKEN lives in ~/secrets/dispatch.env # (mode 600, laptop-only), which the unit also reads. Its by-name # vault home is Bitwarden `pm-dispatch.api-token` (issue #5555) — -# a rotation updates both places. This script +# a rotation updates both places and then restarts +# pm-dispatch.service: the unit reads this file only at start, so +# without a restart the service keeps serving the old token and +# rejects the new one. Recovery: if ~/secrets/dispatch.env is +# lost, restore DISPATCH_API_TOKEN from the Bitwarden item BEFORE +# running this script — when the file is absent the script +# generates a fresh token, which silently desyncs from the vault +# copy and from every client holding the saved token (they get +# 401s) until the vault and the clients are updated to match. +# This script # ensures that file exists and carries a generated # DISPATCH_API_TOKEN when one is absent. SUPABASE_URL / # SUPABASE_SERVICE_ROLE_KEY lines left in that file are stale: the diff --git a/pm-stack/dispatch/src/opencode.ts b/pm-stack/dispatch/src/opencode.ts index 1840de0cc5..f507e282b5 100644 --- a/pm-stack/dispatch/src/opencode.ts +++ b/pm-stack/dispatch/src/opencode.ts @@ -7,6 +7,12 @@ import type { ModelRef } from "./validate.ts"; export class OpenCodeError extends Error { status = 502; + constructor( + message: string, + readonly httpStatus?: number, + ) { + super(message); + } } export class OpenCodeClient { @@ -44,17 +50,30 @@ export class OpenCodeClient { } private async api(method: string, path: string, body?: unknown): Promise { - const res = await fetch(`${this.baseUrl}${path}`, { - method, - headers: { - Authorization: await this.authHeader(), - "Content-Type": "application/json", - }, - body: body === undefined ? undefined : JSON.stringify(body), - }); + let res: Response; + try { + res = await fetch(`${this.baseUrl}${path}`, { + method, + headers: { + Authorization: await this.authHeader(), + "Content-Type": "application/json", + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch (e) { + // A connection failure (server down, refused) is an upstream + // failure, not a caller error: surface it as OpenCodeError so + // routes answer the documented 502 instead of a raw 500. + throw new OpenCodeError( + `opencode ${method} ${path} unreachable: ${e instanceof Error ? e.message : String(e)}`, + ); + } const text = await res.text(); if (!res.ok) { - throw new OpenCodeError(`opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`); + throw new OpenCodeError( + `opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`, + res.status, + ); } if (!text.trim()) return null; let parsed: unknown; @@ -104,7 +123,11 @@ export class OpenCodeClient { try { return await this.api("GET", `/api/session/${encodeURIComponent(sessionId)}`); } catch (e) { - if (e instanceof OpenCodeError && e.message.includes("(HTTP 404)")) return null; + // The 404 decision rides on the upstream status recorded by + // api(), never on message text: a 500 whose body happens to + // contain "(HTTP 404)" is a server failure, not a missing + // session. + if (e instanceof OpenCodeError && e.httpStatus === 404) return null; throw e; } } diff --git a/pm-stack/dispatch/src/queue.ts b/pm-stack/dispatch/src/queue.ts index 570dc79fa1..2c1af54f01 100644 --- a/pm-stack/dispatch/src/queue.ts +++ b/pm-stack/dispatch/src/queue.ts @@ -115,7 +115,30 @@ export class QueueClient { const res = await fetch(`${this.baseUrl}/rest/v1/tasks?id=eq.${id}&select=*`, { headers: this.headers(false), }); - if (!res.ok) return null; + // A failed lookup is not a missing task: returning null here made + // the read route report an existing task as 404 whenever PostgREST + // answered 401/5xx. Null is reserved for a successful empty result. + if (!res.ok) { + throw new QueueError(`task GET ${id} failed (HTTP ${res.status})`, res.status); + } + const rows = (await res.json()) as TaskRow[]; + return rows[0] ?? null; + } + + /** Session -> task lookup (issue #5555): the dispatch-launched task + * whose progress carries `session_id`, or null. Unlike the dedupe + * pre-check below, a lookup failure throws QueueError — this lookup + * backs the repo gate on GET /v1/sessions/:id, and a transient + * PostgREST failure must fail closed (the route answers 502), never + * read as "no task, so no gate". */ + async findTaskBySessionId(sessionId: string): Promise { + const res = await fetch( + `${this.baseUrl}/rest/v1/tasks?progress->>session_id=eq.${encodeURIComponent(sessionId)}&select=*&limit=1`, + { headers: this.headers(false) }, + ); + if (!res.ok) { + throw new QueueError(`task lookup by session failed (HTTP ${res.status})`, res.status); + } const rows = (await res.json()) as TaskRow[]; return rows[0] ?? null; } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 4e041da5bf..3801fa519e 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -696,13 +696,29 @@ async function handleGetTask(caller: CallerIdentity, idSegment: string): Promise if (!row) return json(404, { error: `task ${id} not found` }); const view = taskStatusView(row); // Same repo gate as the write routes: a task whose packet names a - // repo is only readable by callers allowed for that repo. - if (typeof view.repo === "string") assertCallerRepo(caller, view.repo, cfg.repoAllowlist); + // repo is only readable by callers allowed for that repo. A denied + // task answers exactly like a missing one — surfacing the auth + // error would confirm the id exists and leak the repo it names to + // an ID probe. + if (typeof view.repo === "string") { + try { + assertCallerRepo(caller, view.repo, cfg.repoAllowlist); + } catch (e) { + if (e instanceof AuthError) return json(404, { error: `task ${id} not found` }); + throw e; + } + } return json(200, view); } -async function handleGetSession(idSegment: string): Promise { - const sessionId = decodeURIComponent(idSegment); +async function handleGetSession(caller: CallerIdentity, idSegment: string): Promise { + let sessionId: string; + try { + sessionId = decodeURIComponent(idSegment); + } catch { + // A malformed percent-encoding is a bad request, not a 500. + throw new ValidationError("session id: malformed percent-encoding"); + } if (!sessionId.trim()) throw new ValidationError("session id: required"); let raw: unknown; try { @@ -712,6 +728,29 @@ async function handleGetSession(idSegment: string): Promise { throw e; } if (raw === null || raw === undefined) return json(404, { error: `session ${sessionId} not found` }); + // Repo gate, the task read's rule applied to sessions: a + // dispatch-launched session is bound to the queue task that + // launched it (progress.session_id), and that task's repo must be + // in the current allowlist for the session's status to be + // readable — removing a repo from the allowlist closes its + // sessions too. A denied session answers like a missing one: no + // title, no directory, no repo name. Sessions with no dispatch + // task carry no repo association in any record; a queue-less + // deployment (queue === null) can have no dispatch sessions at + // all, so the gate applies exactly when the record is reachable, + // and a failed lookup fails closed via QueueError (502). + if (queue) { + const task = await queue.findTaskBySessionId(sessionId); + const repo = task ? taskStatusView(task).repo : null; + if (typeof repo === "string") { + try { + assertCallerRepo(caller, repo, cfg.repoAllowlist); + } catch (e) { + if (e instanceof AuthError) return json(404, { error: `session ${sessionId} not found` }); + throw e; + } + } + } return json(200, sessionStatusView(raw)); } @@ -744,7 +783,7 @@ export async function handler(req: Request): Promise { oidcAudience: cfg.oidcAudience, allowlist: cfg.repoAllowlist, }); - return taskMatch ? await handleGetTask(caller, taskMatch[1]) : await handleGetSession(sessionMatch![1]); + return taskMatch ? await handleGetTask(caller, taskMatch[1]) : await handleGetSession(caller, sessionMatch![1]); } return json(404, { error: "not found" }); } catch (e) { diff --git a/pm-stack/dispatch/test/opencode.test.ts b/pm-stack/dispatch/test/opencode.test.ts index 0060dcd3d1..cd0839c8e2 100644 --- a/pm-stack/dispatch/test/opencode.test.ts +++ b/pm-stack/dispatch/test/opencode.test.ts @@ -113,6 +113,8 @@ describe("OpenCodeClient.getSession (#5555)", () => { const path = new URL(req.url).pathname; if (path === "/api/session/ses_ok") return Response.json({ data: { id: "ses_ok", title: "t" } }); if (path === "/api/session/ses_boom") return new Response("boom", { status: 500 }); + if (path === "/api/session/ses_fake404") + return new Response("(HTTP 404) mentioned by a failing upstream", { status: 500 }); return new Response("nope", { status: 404 }); }, }); @@ -137,4 +139,15 @@ describe("OpenCodeClient.getSession (#5555)", () => { const client = new OpenCodeClient(stubUrl, authFile("gs.json", JSON.stringify({ password: "pw" }))); await expect(client.getSession("ses_boom")).rejects.toBeInstanceOf(OpenCodeError); }); + + test("a 500 whose body mentions (HTTP 404) is not read as a missing session", async () => { + const client = new OpenCodeClient(stubUrl, authFile("gs.json", JSON.stringify({ password: "pw" }))); + await expect(client.getSession("ses_fake404")).rejects.toBeInstanceOf(OpenCodeError); + }); + + test("a connection failure is an OpenCodeError, not a raw fetch rejection", async () => { + // Port 1 on loopback is closed; fetch rejects before any response. + const client = new OpenCodeClient("http://127.0.0.1:1", authFile("gs.json", JSON.stringify({ password: "pw" }))); + await expect(client.getSession("ses_any")).rejects.toBeInstanceOf(OpenCodeError); + }); }); diff --git a/pm-stack/dispatch/test/queue.test.ts b/pm-stack/dispatch/test/queue.test.ts index 2792bfd2ac..ae5080df4a 100644 --- a/pm-stack/dispatch/test/queue.test.ts +++ b/pm-stack/dispatch/test/queue.test.ts @@ -8,6 +8,43 @@ import { QueueClient, QueueError } from "../src/queue.ts"; const realFetch = globalThis.fetch; +// Read-route lookups (issue #5555): a failed PostgREST lookup is an +// error, never a "not found" — getTask backs the task read route and +// findTaskBySessionId backs the session route's repo gate, so both +// fail closed with QueueError on a non-OK response and reserve null +// for a successful empty result. +describe("getTask / findTaskBySessionId failure mapping (#5555)", () => { + test("getTask throws QueueError on a non-OK response", async () => { + stubFetch(async () => new Response("unavailable", { status: 503 })); + const client = new QueueClient("http://queue.test", "test-key"); + await expect(client.getTask(42)).rejects.toBeInstanceOf(QueueError); + }); + + test("getTask returns null only for a successful empty result", async () => { + stubFetch(async () => Response.json([])); + const client = new QueueClient("http://queue.test", "test-key"); + expect(await client.getTask(42)).toBeNull(); + }); + + test("getTask returns the row on success", async () => { + stubFetch(async () => Response.json([{ id: 42, queue: "q", status: "queued", dedupe_key: "k" }])); + const client = new QueueClient("http://queue.test", "test-key"); + expect((await client.getTask(42))?.id).toBe(42); + }); + + test("findTaskBySessionId throws QueueError on a non-OK response (gate fails closed)", async () => { + stubFetch(async () => new Response("boom", { status: 500 })); + const client = new QueueClient("http://queue.test", "test-key"); + await expect(client.findTaskBySessionId("ses_1")).rejects.toBeInstanceOf(QueueError); + }); + + test("findTaskBySessionId returns the launching task on success", async () => { + stubFetch(async () => Response.json([{ id: 7, queue: "q", status: "claimed", dedupe_key: "k" }])); + const client = new QueueClient("http://queue.test", "test-key"); + expect((await client.findTaskBySessionId("ses_1"))?.id).toBe(7); + }); +}); + afterEach(() => { globalThis.fetch = realFetch; }); diff --git a/pm-stack/dispatch/test/server.test.ts b/pm-stack/dispatch/test/server.test.ts index 7fc9499ed2..e98835d0d9 100644 --- a/pm-stack/dispatch/test/server.test.ts +++ b/pm-stack/dispatch/test/server.test.ts @@ -211,6 +211,12 @@ describe("GET /v1/tasks/:id and /v1/sessions/:id read routes (#5555)", () => { expect(res.status).toBe(400); }); + test("GET /v1/sessions/:id with malformed percent-encoding is 400, before any upstream call", async () => { + const token = signOidc("developing-today/code"); + const res = await handler(new Request("http://x/v1/sessions/%ZZ", { headers: { authorization: `Bearer ${token}` } })); + expect(res.status).toBe(400); + }); + test("GET /v1/tasks/:id authenticated reaches the queue (502 while unconfigured here)", async () => { const token = signOidc("developing-today/code"); const res = await handler(new Request("http://x/v1/tasks/42", { headers: { authorization: `Bearer ${token}` } })); From fafcc12754c4ff92629bfd21d5fd951097374bd7 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 01:01:32 -0600 Subject: [PATCH 3/3] fix(pm-dispatch): keep session repo gate after the queue clears the live binding (#5555) Codex P2 on PR #8053: findTaskBySessionId matched only the live progress.session_id binding, which the queue removes on park/lease-expiry (migration-0023), un-gating a session whose repo left the allowlist. The queue preserves the cleared binding on the task row as progress.session_cleared; the lookup now falls back to that durable record (live binding first), still failing closed with QueueError on a lookup error. Also fix the pre-existing fetch-stub cast errors so bunx tsc --noEmit passes (acceptance for #5555). Tests: bun test 190 pass (2 new), tsc clean. --- pm-stack/dispatch/src/queue.ts | 29 +++++++++++++++++++--------- pm-stack/dispatch/src/server.ts | 4 +++- pm-stack/dispatch/test/auth.test.ts | 8 ++++---- pm-stack/dispatch/test/queue.test.ts | 21 +++++++++++++++++++- 4 files changed, 47 insertions(+), 15 deletions(-) diff --git a/pm-stack/dispatch/src/queue.ts b/pm-stack/dispatch/src/queue.ts index 2c1af54f01..5744dfe3f3 100644 --- a/pm-stack/dispatch/src/queue.ts +++ b/pm-stack/dispatch/src/queue.ts @@ -126,18 +126,29 @@ export class QueueClient { } /** Session -> task lookup (issue #5555): the dispatch-launched task - * whose progress carries `session_id`, or null. Unlike the dedupe - * pre-check below, a lookup failure throws QueueError — this lookup - * backs the repo gate on GET /v1/sessions/:id, and a transient + * bound to sessionId, or null. Two bindings are checked, live first: + * the current progress.session_id, and - when that binding has been + * cleared - the durable progress.session_cleared.session_id record + * the queue leaves on the task row when it clears a binding on park / + * lease expiry (opencode-claimant migration-0023). The cleared record + * is what keeps the session route repo gate attached to a session + * after its task unbinds: without it, removing the repo from the + * allowlist would silently un-gate a still-live session. Unlike the + * dedupe pre-check below, a lookup failure throws QueueError - this + * lookup backs the repo gate on GET /v1/sessions/:id, and a transient * PostgREST failure must fail closed (the route answers 502), never - * read as "no task, so no gate". */ + * read as no task, so no gate. */ async findTaskBySessionId(sessionId: string): Promise { - const res = await fetch( - `${this.baseUrl}/rest/v1/tasks?progress->>session_id=eq.${encodeURIComponent(sessionId)}&select=*&limit=1`, - { headers: this.headers(false) }, - ); + const live = await this.findTaskByProgressField('progress->>session_id', sessionId); + if (live) return live; + return this.findTaskByProgressField('progress->session_cleared->>session_id', sessionId); + } + + private async findTaskByProgressField(field: string, sessionId: string): Promise { + const url = this.baseUrl + '/rest/v1/tasks?' + field + '=eq.' + encodeURIComponent(sessionId) + '&select=*&limit=1'; + const res = await fetch(url, { headers: this.headers(false) }); if (!res.ok) { - throw new QueueError(`task lookup by session failed (HTTP ${res.status})`, res.status); + throw new QueueError('task lookup by session failed (HTTP ' + res.status + ')', res.status); } const rows = (await res.json()) as TaskRow[]; return rows[0] ?? null; diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 3801fa519e..c8bd25d497 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -730,7 +730,9 @@ async function handleGetSession(caller: CallerIdentity, idSegment: string): Prom if (raw === null || raw === undefined) return json(404, { error: `session ${sessionId} not found` }); // Repo gate, the task read's rule applied to sessions: a // dispatch-launched session is bound to the queue task that - // launched it (progress.session_id), and that task's repo must be + // launched it - by the live progress.session_id binding, or by + // the durable progress.session_cleared record the queue keeps + // after a park/lease-expiry unbinds it - and that task's repo must be // in the current allowlist for the session's status to be // readable — removing a repo from the allowlist closes its // sessions too. A denied session answers like a missing one: no diff --git a/pm-stack/dispatch/test/auth.test.ts b/pm-stack/dispatch/test/auth.test.ts index 984047d0a8..26c7a4d364 100644 --- a/pm-stack/dispatch/test/auth.test.ts +++ b/pm-stack/dispatch/test/auth.test.ts @@ -227,15 +227,15 @@ describe("JWKS body shape (#7565)", () => { resetJwksCacheForTests(); const originalFetch = globalThis.fetch; let calls = 0; - globalThis.fetch = async () => { + globalThis.fetch = (async () => { calls++; return { ok: true, json: async () => { throw new SyntaxError("Unexpected token < in JSON"); }, - } as Response; - }; + } as unknown as Response; + }) as unknown as typeof fetch; try { await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError); await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError); @@ -249,7 +249,7 @@ describe("JWKS body shape (#7565)", () => { test("fetchGithubJwks rejects a wrong-shape 200 body as AuthError", async () => { resetJwksCacheForTests(); const originalFetch = globalThis.fetch; - globalThis.fetch = async () => ({ ok: true, json: async () => ({}) }) as Response; + globalThis.fetch = (async () => ({ ok: true, json: async () => ({}) }) as unknown as Response) as unknown as typeof fetch; try { await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError); } finally { diff --git a/pm-stack/dispatch/test/queue.test.ts b/pm-stack/dispatch/test/queue.test.ts index ae5080df4a..ea48063b97 100644 --- a/pm-stack/dispatch/test/queue.test.ts +++ b/pm-stack/dispatch/test/queue.test.ts @@ -43,6 +43,25 @@ describe("getTask / findTaskBySessionId failure mapping (#5555)", () => { const client = new QueueClient("http://queue.test", "test-key"); expect((await client.findTaskBySessionId("ses_1"))?.id).toBe(7); }); + + test("findTaskBySessionId falls back to the cleared binding the queue preserves on the task row", async () => { + const urls: string[] = []; + globalThis.fetch = (async (...args: unknown[]) => { + urls.push(String(args[0])); + if (urls.length === 1) return Response.json([]); + return Response.json([{ id: 9, queue: "q", status: "parked", dedupe_key: "k" }]); + }) as unknown as typeof fetch; + const client = new QueueClient("http://queue.test", "test-key"); + expect((await client.findTaskBySessionId("ses_1"))?.id).toBe(9); + expect(urls[0]).toContain("progress->>session_id=eq.ses_1"); + expect(urls[1]).toContain("progress->session_cleared->>session_id=eq.ses_1"); + }); + + test("findTaskBySessionId throws QueueError when the cleared-binding lookup fails", async () => { + stubFetch(async (n) => (n === 1 ? Response.json([]) : new Response("boom", { status: 500 }))); + const client = new QueueClient("http://queue.test", "test-key"); + await expect(client.findTaskBySessionId("ses_1")).rejects.toBeInstanceOf(QueueError); + }); }); afterEach(() => { @@ -51,7 +70,7 @@ afterEach(() => { function stubFetch(handler: (call: number) => Promise) { let calls = 0; - globalThis.fetch = (async () => handler(++calls)) as typeof fetch; + globalThis.fetch = (async () => handler(++calls)) as unknown as typeof fetch; return () => calls; }