diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 17622e9b36..afa5c30c19 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -29,7 +29,10 @@ name: pm-console-edge deploy # itself, or are published by the host. Three secrets are optional, put # there by the host's scripts/expose.py --edge-direct (off by default): # GITHUB_TOKEN and QUEUE_TOKEN, which let it act itself while the laptop -# is away, and EDGE_DIRECT, the opt-in that must read `on`. It has no +# is away, and EDGE_DIRECT, the opt-in that must read `on`. A fourth, +# BRIDGE_TOKEN, is uploaded in the same pass when the vault holds it: +# the PM stack's own bridge credential, which the Worker presents to +# the message-bridge Worker over its service binding (#14373). It has no # route here either. The host's pm-stack/console/scripts/expose.py sends # the hostname through it once it answers its health check, and # `expose.py --edge off` takes the hostname off it again, which is the diff --git a/pkgs/fleet/hosted-worker/package.json b/pkgs/fleet/hosted-worker/package.json index d3271f6872..3c0bedc379 100644 --- a/pkgs/fleet/hosted-worker/package.json +++ b/pkgs/fleet/hosted-worker/package.json @@ -13,7 +13,7 @@ "cli": "node --experimental-transform-types cli.ts", "dev": "wrangler dev", "smoke": "node --experimental-transform-types smoke/smoke.mjs", - "test": "node --experimental-transform-types --test test/auth.test.ts test/tenancy.test.ts test/capabilities.test.ts test/doors.test.ts test/sessions.test.ts test/session-parity.test.ts test/stamp-sig.test.ts test/stamping.test.ts test/github.test.ts test/query.test.ts test/query-cli.test.ts test/queue.test.ts test/ingestion.test.ts test/sync.test.ts test/sync-cli.test.ts test/direct-read.test.ts test/cli.test.ts", + "test": "node --experimental-transform-types --test test/auth.test.ts test/tenancy.test.ts test/capabilities.test.ts test/doors.test.ts test/sessions.test.ts test/session-parity.test.ts test/stamp-sig.test.ts test/stamping.test.ts test/github.test.ts test/query.test.ts test/query-cli.test.ts test/queue.test.ts test/ingestion.test.ts test/sync.test.ts test/sync-cli.test.ts test/direct-read.test.ts test/cli.test.ts test/bridge.test.ts", "typecheck": "tsc --noEmit" }, "type": "module", diff --git a/pkgs/fleet/hosted-worker/src/auth.ts b/pkgs/fleet/hosted-worker/src/auth.ts index a855bafc70..a55e3e6048 100644 --- a/pkgs/fleet/hosted-worker/src/auth.ts +++ b/pkgs/fleet/hosted-worker/src/auth.ts @@ -32,6 +32,7 @@ // hosted-worker posture: internal context is never // client-controlled). +import type { BridgeSurface } from "./bridge.ts"; import type { HostedConfig } from "./config.ts"; import { FailClosed } from "./errors.ts"; import type { @@ -112,6 +113,11 @@ export interface AuthDeps { * over the rotation. Absent → the project-sync route fails * closed with 503, like unconfigured auth. */ githubProjects?: GitHubProjectSurface; + /** Bridge surface (#14373, src/bridge.ts): the bridge door's path + * to the message bridge over its service binding, presenting the + * PM credential. Absent → the bridge door fails closed with 503, + * like unconfigured auth. */ + bridge?: BridgeSurface; } export async function sha256Hex(text: string): Promise { diff --git a/pkgs/fleet/hosted-worker/src/bridge.ts b/pkgs/fleet/hosted-worker/src/bridge.ts new file mode 100644 index 0000000000..e936a3d9ef --- /dev/null +++ b/pkgs/fleet/hosted-worker/src/bridge.ts @@ -0,0 +1,181 @@ +// Bridge door engine (#14373; design §4.8): the hosted door's path +// to the message bridge, shared with the PM console's edge Worker. +// +// The PM service API (this door) and the console's edge both speak to +// the bridge Worker over a service binding, presenting the PM stack's +// own bridge credential — minted on the bridge for the purpose, held +// as a Worker secret by name (BRIDGE_PM_TOKEN), never in code or +// config. Sends go out as service:pm-stack, so the bridge's log tells +// PM-originated rows apart from owner-sent (from_addr null) and +// agent-sent (agent:) ones; the agents list and the message log +// are read with the credential's read scope. Revoking the credential +// on the bridge stops this door's sends at the bridge: the door +// answers 502 naming the refusal, and nothing falls back to a +// machine's fleet binary — the laptop-local services keep their own +// route, untouched by this door. + +import type { AuthDeps } from "./auth.ts"; +import { FailClosed } from "./errors.ts"; + +/** The bridge surface this door calls: the three operations the PM + * stack's hosted path uses. Behind an interface so tests stand in + * their own bridge, as with every door's dependency. */ +export interface BridgeSurface { + /** One message or command to agents, a group, or all. Returns the + * bridge's delivery record (the rows it stored). */ + send(input: BridgeSendInput): Promise; + /** The registered agents, their groups, last seen, unread counts. */ + agents(): Promise; + /** The fleet message log, newest or oldest first. */ + messages(query: BridgeMessagesQuery): Promise; +} + +export interface BridgeSendInput { + to: string[]; + body: string; + kind: "message" | "command"; +} + +export interface BridgeMessagesQuery { + limit?: number; + order?: "asc" | "desc"; +} + +/** The name the PM stack's bridge credential is bound to: the bridge + * fixes a credential's sends to its own name, and this door's sends + * go out under it, as service:pm-stack. */ +export const BRIDGE_AGENT = "pm-stack"; +/** Where the bridge is asked, over its service binding: the binding + * answers for the bridge Worker whatever host the address names. */ +const BRIDGE_BASE = "https://bridge.internal"; + +/** A service binding's fetch shape (a Fetcher in the Workers + * runtime; a stand-in in tests). */ +export interface BridgeBinding { + fetch(request: Request): Promise; +} + +/** The bridge over its service binding, presenting the PM credential + * in the path (the bridge's own way: /fleet//...). */ +export class BindingBridgeSurface implements BridgeSurface { + constructor( + private binding: BridgeBinding, + private token: string, + ) {} + + private async call(method: string, path: string, body?: unknown): Promise { + let res: Response; + try { + res = await this.binding.fetch( + new Request(`${BRIDGE_BASE}${path}`, { + method, + headers: { + "user-agent": "fleet-hosted", + ...(body === undefined ? {} : { "content-type": "application/json" }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), + ); + } catch (e) { + throw new FailClosed(502, "bridge_unreachable", `the bridge could not be reached: ${(e as Error).message}`); + } + if (res.status === 404) { + // The bridge's one answer to a token it does not know: the PM + // credential is unknown or revoked. Said plainly, because that + // is the error the operator acts on (mint a new one). + throw new FailClosed( + 502, + "bridge_credential_refused", + "the bridge turned the PM credential away (unknown or revoked); nothing was sent", + ); + } + if (!res.ok) { + throw new FailClosed(502, "bridge_failed", `the bridge answered http ${res.status}`); + } + try { + return await res.json(); + } catch { + throw new FailClosed(502, "bridge_failed", "the bridge answered with no JSON body"); + } + } + + async send(input: BridgeSendInput): Promise { + return this.call("POST", `/fleet/${this.token}/send`, { + agent: BRIDGE_AGENT, + to: input.to, + body: input.body, + kind: input.kind, + }); + } + + async agents(): Promise { + return this.call("GET", `/fleet/${this.token}/agents`); + } + + async messages(query: BridgeMessagesQuery): Promise { + const params = new URLSearchParams(); + if (query.limit !== undefined) params.set("limit", String(query.limit)); + if (query.order !== undefined) params.set("order", query.order); + const qs = params.toString(); + return this.call("GET", `/fleet/${this.token}/messages${qs === "" ? "" : `?${qs}`}`); + } +} + +/** The door's bridge, or the door fails closed: no binding or no + * credential configured is a 503, like every door's missing + * dependency. */ +export function bridgeSurfaceFrom(deps: AuthDeps): BridgeSurface { + if (!deps.bridge) { + throw new FailClosed( + 503, + "bridge_unconfigured", + "the bridge door is not configured (no BRIDGE service binding or BRIDGE_PM_TOKEN)", + ); + } + return deps.bridge; +} + +const TARGET = /^(all|(agent:|group:)?[A-Za-z0-9][A-Za-z0-9._-]{0,63})$/; + +/** A send as the console's own validation shapes it: one to fifty + * targets, a text of at most 16,000 characters, a kind of message + * (the default) or command. */ +export function parseBridgeSendRequest(raw: unknown): BridgeSendInput { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + throw new FailClosed(400, "invalid_body", "send body must be a JSON object"); + } + const { to, body, kind } = raw as { to?: unknown; body?: unknown; kind?: unknown }; + if (!Array.isArray(to) || to.length === 0 || to.length > 50) { + throw new FailClosed(400, "invalid_body", "to: one to fifty targets"); + } + for (const t of to) { + if (typeof t !== "string" || !TARGET.test(t)) { + throw new FailClosed(400, "invalid_body", `to: not a target: ${JSON.stringify(t)?.slice(0, 80)}`); + } + } + if (typeof body !== "string" || body.trim() === "" || body.length > 16_000) { + throw new FailClosed(400, "invalid_body", "body: required, at most 16000 characters"); + } + if (kind !== undefined && kind !== "message" && kind !== "command") { + throw new FailClosed(400, "invalid_body", "kind: message or command"); + } + return { to: to as string[], body, kind: kind ?? "message" }; +} + +/** The log read's query: a limit of at most 200 (the bridge's own + * cap), an order of asc (its default) or desc. */ +export function parseBridgeMessagesQuery(url: URL): BridgeMessagesQuery { + const out: BridgeMessagesQuery = {}; + const limit = url.searchParams.get("limit"); + if (limit !== null && limit !== "") { + const n = Number(limit); + if (!Number.isInteger(n) || n < 1) throw new FailClosed(400, "invalid_query", "limit: a positive whole number"); + out.limit = Math.min(n, 200); + } + const order = url.searchParams.get("order"); + if (order !== null && order !== "") { + if (order !== "asc" && order !== "desc") throw new FailClosed(400, "invalid_query", "order: asc or desc"); + out.order = order; + } + return out; +} diff --git a/pkgs/fleet/hosted-worker/src/capabilities.ts b/pkgs/fleet/hosted-worker/src/capabilities.ts index a7fe3e9207..e846a520ca 100644 --- a/pkgs/fleet/hosted-worker/src/capabilities.ts +++ b/pkgs/fleet/hosted-worker/src/capabilities.ts @@ -28,6 +28,10 @@ // queue door (#12589) made the `queue` domain available, and the // ingestion door (#12590) and the sync door (#12591) are live — // every component-C door has landed, and the document says so. +// The bridge door (#14373) then wired the `bridge` domain to the +// message bridge over its service binding, with the PM stack's own +// credential: the PM service API and the console's edge share that +// one send path, and the domain reports available for it. import { SERVICE_NAME, type HostedConfig } from "./config.ts"; @@ -90,6 +94,12 @@ export const HOSTED_DOORS: HostedDoor[] = [ fillingIssue: "#12591", state: "live", }, + { + id: "bridge", + routes: ["POST /v1/bridge/send", "GET /v1/bridge/agents", "GET /v1/bridge/messages"], + fillingIssue: "#14373", + state: "live", + }, ]; interface NativeDomain { @@ -169,6 +179,8 @@ const NATIVE_DOMAINS: NativeDomain[] = [ aliases: [], capabilities: ["bridge"], hosted: "already-hosted", + fillingIssue: "#14373", + available: true, }, { name: "agent", diff --git a/pkgs/fleet/hosted-worker/src/config.ts b/pkgs/fleet/hosted-worker/src/config.ts index 9d99b86d38..c5510b70ad 100644 --- a/pkgs/fleet/hosted-worker/src/config.ts +++ b/pkgs/fleet/hosted-worker/src/config.ts @@ -78,6 +78,16 @@ export interface HostedEnv { /** Direct-read TTL cap in seconds (#12592): a token's requested * lifetime may not exceed it. Defaults to 3600 when unset. */ DIRECT_READ_MAX_TTL_SECONDS?: string; + /** The message bridge, by service binding (#14373): the bridge + * door calls it with the PM credential below. A binding, not a + * value: present when the deployed shape carries it (wrangler.toml + * declares it; local dev and tests inject their own or none). */ + BRIDGE?: { fetch(request: Request): Promise }; + /** The PM stack's bridge credential (#14373): minted on the bridge + * for service:pm-stack, held as a Worker secret. A secret, + * referenced by name only; never logged. Absent or short → the + * bridge door fails closed (503). */ + BRIDGE_PM_TOKEN?: string; } /** Stamp signing key material: the parsed key, bytes only. */ @@ -142,6 +152,12 @@ export interface HostedConfig { * (valid) DB ids / mint material are set. Independent of auth, * like the stamp material. */ directRead: DirectReadConfig | null; + /** The PM bridge credential (#14373), or null when unset or too + * short to be one — the bridge door then fails closed (503). The + * value is held only to be presented to the bridge; it is never + * logged or reported. Independent of auth, like the webhook + * secret. */ + bridge: { token: string } | null; } /** Stamp key ids name a key inside the stamp_sig value, so they may @@ -256,9 +272,19 @@ export function configFromEnv(env: HostedEnv): HostedConfig { webhookSecret: env.GITHUB_WEBHOOK_SECRET && env.GITHUB_WEBHOOK_SECRET !== "" ? env.GITHUB_WEBHOOK_SECRET : null, ingestionRepos: parseIngestionRepos(env.INGESTION_REPOS), directRead: parseDirectReadConfig(env), + bridge: parseBridgeConfig(env), }; } +/** The PM bridge credential (#14373): present only when the secret + * is set and long enough to be a bridge credential (the bridge's own + * minimum is 32 characters); anything shorter is treated as unset, + * so a truncated paste fails closed instead of sending garbage. */ +function parseBridgeConfig(env: HostedEnv): { token: string } | null { + const token = env.BRIDGE_PM_TOKEN?.trim(); + return token && token.length >= 32 ? { token } : null; +} + /** The sweeper's repo scope: comma-separated owner/name entries. * A malformed entry is dropped, not fatal — the residue is a * smaller scope, and an all-malformed value parses to the empty diff --git a/pkgs/fleet/hosted-worker/src/router.ts b/pkgs/fleet/hosted-worker/src/router.ts index 43d0f4a100..b2ac537088 100644 --- a/pkgs/fleet/hosted-worker/src/router.ts +++ b/pkgs/fleet/hosted-worker/src/router.ts @@ -18,6 +18,7 @@ import { assertCallerTenancy, authenticate, authorizeRoute, type AuthDeps, type import { buildCapabilitiesDocument } from "./capabilities.ts"; import { FailClosed } from "./errors.ts"; import { buildHealthDocument } from "./health.ts"; +import { routes as bridgeRoutes } from "./routes/bridge.ts"; import { routes as ingestionRoutes } from "./routes/ingestion.ts"; import { routes as queryRoutes } from "./routes/query.ts"; import { routes as queueRoutes } from "./routes/queue.ts"; @@ -66,6 +67,7 @@ export const ROUTES: RouteDef[] = [ ...queueRoutes, ...ingestionRoutes, ...syncRoutes, + ...bridgeRoutes, ]; export async function dispatch(req: Request, deps: AuthDeps): Promise { diff --git a/pkgs/fleet/hosted-worker/src/routes/bridge.ts b/pkgs/fleet/hosted-worker/src/routes/bridge.ts new file mode 100644 index 0000000000..af2766c6cd --- /dev/null +++ b/pkgs/fleet/hosted-worker/src/routes/bridge.ts @@ -0,0 +1,67 @@ +// Bridge door (#14373; design §4.8). The PM stack's hosted path to +// the message bridge, over the same service binding and PM +// credential the console's edge Worker uses, so the PM service API +// and the console share one send path: +// +// POST /v1/bridge/send {to, body, kind?}: one message or +// command to agents, a group, or all, +// delivered by the bridge as +// service:pm-stack — no machine relays it. +// GET /v1/bridge/agents the registered agents, read at the edge. +// GET /v1/bridge/messages ?limit=&order=: the fleet message log. +// +// The engine (the binding client, the request shapes) is +// src/bridge.ts. Every handler refuses 503 before parsing when the +// binding or the credential is unconfigured, like every door's +// missing dependency. + +import type { AuthDeps, CallerContext } from "../auth.ts"; +import { bridgeSurfaceFrom, parseBridgeMessagesQuery, parseBridgeSendRequest } from "../bridge.ts"; +import { FailClosed } from "../errors.ts"; +import type { RouteDef } from "../router.ts"; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function caller(ctx: CallerContext | null): CallerContext { + if (!ctx) { + throw new FailClosed(401, "missing_token", "bridge routes require an authenticated caller"); + } + return ctx; +} + +async function jsonBody(req: Request): Promise { + try { + return await req.json(); + } catch { + throw new FailClosed(400, "invalid_body", "request body is not valid JSON"); + } +} + +async function send(req: Request, ctx: CallerContext | null, deps: AuthDeps): Promise { + caller(ctx); + const bridge = bridgeSurfaceFrom(deps); + const input = parseBridgeSendRequest(await jsonBody(req)); + return json(await bridge.send(input), 201); +} + +async function agents(_req: Request, ctx: CallerContext | null, deps: AuthDeps): Promise { + caller(ctx); + return json(await bridgeSurfaceFrom(deps).agents()); +} + +async function messages(req: Request, ctx: CallerContext | null, deps: AuthDeps): Promise { + caller(ctx); + const bridge = bridgeSurfaceFrom(deps); + return json(await bridge.messages(parseBridgeMessagesQuery(new URL(req.url)))); +} + +export const routes: RouteDef[] = [ + { method: "POST", path: "/v1/bridge/send", door: "bridge", handler: send }, + { method: "GET", path: "/v1/bridge/agents", door: "bridge", handler: agents }, + { method: "GET", path: "/v1/bridge/messages", door: "bridge", handler: messages }, +]; diff --git a/pkgs/fleet/hosted-worker/src/worker.ts b/pkgs/fleet/hosted-worker/src/worker.ts index 90f8e4d594..ded38bfc5e 100644 --- a/pkgs/fleet/hosted-worker/src/worker.ts +++ b/pkgs/fleet/hosted-worker/src/worker.ts @@ -13,6 +13,7 @@ // metadata DB behind the store interfaces and #12583's deploy. import type { AuthDeps } from "./auth.ts"; +import { BindingBridgeSurface } from "./bridge.ts"; import { configFromEnv, type HostedEnv } from "./config.ts"; import { AppRotationGitHubWriter, FixtureGitHubWriter } from "./github.ts"; import { ingestionDepsFrom, runIngestionSweep } from "./ingestion.ts"; @@ -67,6 +68,13 @@ function buildDeps(env: HostedEnv): AuthDeps { // implement GitHubItemSource, GitHubCommentSurface, // GitHubBodyEditor and GitHubProjectSurface over the same // rotation / recorded state. + // The bridge door's surface (#14373): the message bridge over its + // service binding, presenting the PM credential — the same binding + // and credential the console's edge Worker uses, so the PM service + // API and the console share one send path. Absent the binding or + // the credential, the door fails closed (503) per request. + const bridge = + config.bridge && env.BRIDGE ? new BindingBridgeSurface(env.BRIDGE, config.bridge.token) : undefined; return { config, sessions, @@ -78,6 +86,7 @@ function buildDeps(env: HostedEnv): AuthDeps { githubComments: githubWriter, githubEditor: githubWriter, githubProjects: githubWriter, + ...(bridge ? { bridge } : {}), }; } diff --git a/pkgs/fleet/hosted-worker/test/bridge.test.ts b/pkgs/fleet/hosted-worker/test/bridge.test.ts new file mode 100644 index 0000000000..824f8c0515 --- /dev/null +++ b/pkgs/fleet/hosted-worker/test/bridge.test.ts @@ -0,0 +1,163 @@ +// Bridge door tests (#14373). Oracle: design §4.8 — the PM service +// API and the console's edge share one bridge path: this door calls +// the bridge Worker over its service binding presenting the PM +// stack's own credential, sends go out as service:pm-stack, and the +// capability document resolves the bridge domain to that same +// binding. A revoked credential is the bridge's plain 404 and stops +// sends here with the refusal named; no binding or no credential is +// a 503 before anything is parsed, like every door's missing +// dependency. The bridge here is a stand-in binding that records +// every request; the credential in it is a fixture, never a real one. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { BindingBridgeSurface } from "../src/bridge.ts"; +import { buildCapabilitiesDocument } from "../src/capabilities.ts"; +import { configFromEnv } from "../src/config.ts"; +import { dispatch } from "../src/router.ts"; +import { bearerReq, makeHarness } from "./helpers.ts"; + +const h = await makeHarness(); +const token = await h.sign(h.rpPayload()); + +const PM_TOKEN = "p".repeat(43); + +/** The bridge binding, standing in: records requests, answers as the + * bridge does (its send/agents/messages shapes), and turns the + * credential away when `refuse` is set — the revoked case. */ +function fakeBridge(refuse = false) { + const calls: { method: string; url: string; body?: unknown }[] = []; + const binding = { + async fetch(request: Request): Promise { + const text = request.method === "POST" ? await request.text() : ""; + calls.push({ + method: request.method, + url: request.url, + ...(text === "" ? {} : { body: JSON.parse(text) }), + }); + if (refuse) return new Response("Not found\n", { status: 404 }); + if (request.url.endsWith("/send")) { + return Response.json({ messages: [], fleet: [{ id: 5, agent: "felix-1" }] }, { status: 201 }); + } + if (request.url.endsWith("/agents")) { + return Response.json({ agents: [{ name: "felix-1", groups: ["muse"] }] }); + } + return Response.json({ messages: [{ id: 5, body: "earlier" }] }); + }, + }; + return { calls, binding }; +} + +function bridgeDeps(refuse = false) { + const fake = fakeBridge(refuse); + return { deps: { ...h.deps, bridge: new BindingBridgeSurface(fake.binding, PM_TOKEN) }, calls: fake.calls }; +} + +test("send: the door delivers through the binding as pm-stack, and the bridge's record comes back", async () => { + const { deps, calls } = bridgeDeps(); + const res = await dispatch( + bearerReq("/v1/bridge/send", token, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ to: ["agent:felix-1", "group:muse"], body: "from the service", kind: "command" }), + }), + deps, + ); + assert.equal(res.status, 201); + assert.deepEqual(((await res.json()) as { fleet: unknown[] }).fleet, [{ id: 5, agent: "felix-1" }]); + assert.equal(calls.length, 1); + assert.equal(calls[0].method, "POST"); + assert.equal(calls[0].url, `https://bridge.internal/fleet/${PM_TOKEN}/send`); + assert.deepEqual(calls[0].body, { + agent: "pm-stack", + to: ["agent:felix-1", "group:muse"], + body: "from the service", + kind: "command", + }); +}); + +test("agents and messages: the pipeline reads go to the same binding with the same credential", async () => { + const { deps, calls } = bridgeDeps(); + const agents = await dispatch(bearerReq("/v1/bridge/agents", token), deps); + assert.equal(agents.status, 200); + assert.deepEqual(((await agents.json()) as { agents: unknown[] }).agents, [{ name: "felix-1", groups: ["muse"] }]); + const log = await dispatch(bearerReq("/v1/bridge/messages?limit=5&order=desc", token), deps); + assert.equal(log.status, 200); + assert.deepEqual(((await log.json()) as { messages: unknown[] }).messages, [{ id: 5, body: "earlier" }]); + assert.deepEqual( + calls.map((c) => `${c.method} ${c.url}`), + [ + `GET https://bridge.internal/fleet/${PM_TOKEN}/agents`, + `GET https://bridge.internal/fleet/${PM_TOKEN}/messages?limit=5&order=desc`, + ], + ); +}); + +test("a revoked PM credential stops sends at the door, with the refusal named", async () => { + const { deps } = bridgeDeps(true); + const res = await dispatch( + bearerReq("/v1/bridge/send", token, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ to: ["agent:felix-1"], body: "never sent" }), + }), + deps, + ); + assert.equal(res.status, 502); + const body = (await res.json()) as { error: string; message: string }; + assert.equal(body.error, "bridge_credential_refused"); + assert.match(body.message, /revoked/); +}); + +test("unconfigured: no bridge surface is a 503 before the body is read", async () => { + const res = await dispatch( + bearerReq("/v1/bridge/send", token, { method: "POST", body: "not json at all" }), + h.deps, + ); + assert.equal(res.status, 503); + assert.equal(((await res.json()) as { error: string }).error, "bridge_unconfigured"); +}); + +test("a bad send is a 400 of the door's own shaping, and never reaches the bridge", async () => { + const { deps, calls } = bridgeDeps(); + for (const body of [ + { to: [], body: "x" }, + { to: ["not a target!"], body: "x" }, + { to: ["agent:felix-1"], body: "" }, + { to: ["agent:felix-1"], body: "x", kind: "order" }, + ]) { + const res = await dispatch( + bearerReq("/v1/bridge/send", token, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }), + deps, + ); + assert.equal(res.status, 400, JSON.stringify(body)); + assert.equal(((await res.json()) as { error: string }).error, "invalid_body"); + } + assert.equal(calls.length, 0); +}); + +test("the credential config parses by name only: absent or short is unconfigured", () => { + assert.equal(configFromEnv({}).bridge, null); + assert.equal(configFromEnv({ BRIDGE_PM_TOKEN: "short" }).bridge, null); + assert.deepEqual(configFromEnv({ BRIDGE_PM_TOKEN: PM_TOKEN }).bridge, { token: PM_TOKEN }); +}); + +test("the capability resolves to the same binding: the bridge domain is available, filled by #14373", () => { + const doc = buildCapabilitiesDocument(h.deps.config) as { + capabilities: string[]; + domains: { name: string; available: boolean; filling_issue?: string }[]; + doors: { id: string; routes: string[]; state: string; filling_issue: string }[]; + }; + assert.ok(doc.capabilities.includes("bridge")); + const domain = doc.domains.find((d) => d.name === "bridge"); + assert.equal(domain?.available, true); + assert.equal(domain?.filling_issue, "#14373"); + const door = doc.doors.find((d) => d.id === "bridge"); + assert.equal(door?.state, "live"); + assert.equal(door?.filling_issue, "#14373"); + assert.deepEqual(door?.routes, ["POST /v1/bridge/send", "GET /v1/bridge/agents", "GET /v1/bridge/messages"]); +}); diff --git a/pkgs/fleet/hosted-worker/test/capabilities.test.ts b/pkgs/fleet/hosted-worker/test/capabilities.test.ts index bc00f03717..8dd20e9959 100644 --- a/pkgs/fleet/hosted-worker/test/capabilities.test.ts +++ b/pkgs/fleet/hosted-worker/test/capabilities.test.ts @@ -4,7 +4,8 @@ // hosted values. The document must be truthful: a domain reports // available only when its filling issue landed — the // hosted-transformed `gh` domain via the stamping door (#12585), -// and the `queue` domain via the queue door (#12589). +// the `queue` domain via the queue door (#12589), and the `bridge` +// domain via the bridge door (#14373). import assert from "node:assert/strict"; import { test } from "node:test"; @@ -24,7 +25,7 @@ test("health answers publicly with the hosted door's identity", async () => { }; assert.equal(body.status, "ok"); assert.equal(body.service, "fleet-hosted"); - assert.deepEqual(body.doors, ["stamping", "query", "queue", "ingestion", "sync"]); + assert.deepEqual(body.doors, ["stamping", "query", "queue", "ingestion", "sync", "bridge"]); assert.deepEqual(body.auth, { rp_configured: true, tenancy_configured: true }); }); @@ -64,6 +65,7 @@ test("capabilities mirrors the native shape with hosted values", async () => { assert.ok(Array.isArray(d.capabilities)); if (d.name === "gh") continue; // asserted below: landed by #12585 if (d.name === "queue") continue; // asserted below: landed by #12589 + if (d.name === "bridge") continue; // asserted below: landed by #14373 // Truth: no other business domain is available at this door yet. assert.equal(d.available, false, `${d.name} must not report available yet`); assert.equal(d.state, "not-in-build"); @@ -80,14 +82,20 @@ test("capabilities mirrors the native shape with hosted values", async () => { // available too, ahead of gh in the registry's domain order. assert.equal(byName.get("queue")?.available, true); assert.equal(byName.get("queue")?.state, "available"); - assert.deepEqual(doc.capabilities, ["queue", "gh"]); - assert.deepEqual(doc.compiled_capabilities, ["queue", "gh"]); + // #14373 wired the bridge domain to the message bridge over its + // service binding: available too, after gh in the registry's order. + assert.equal(byName.get("bridge")?.available, true); + assert.equal(byName.get("bridge")?.state, "available"); + assert.deepEqual(doc.capabilities, ["queue", "gh", "bridge"]); + assert.deepEqual(doc.compiled_capabilities, ["queue", "gh", "bridge"]); assert.equal(byName.get("queue")?.hosted, "hosted-front-door"); assert.equal(byName.get("queue")?.filling_issue, "#12589"); assert.equal(byName.get("secrets")?.hosted, "native-only"); assert.equal(byName.get("bridge")?.hosted, "already-hosted"); + assert.equal(byName.get("bridge")?.filling_issue, "#14373"); - // The component-C doors and the issues that fill them. + // The component-C doors and the issues that fill them, and the + // bridge door after them. assert.deepEqual( doc.doors.map((d) => [d.id, d.filling_issue]), [ @@ -96,6 +104,7 @@ test("capabilities mirrors the native shape with hosted values", async () => { ["queue", "#12589"], ["ingestion", "#12590"], ["sync", "#12591"], + ["bridge", "#14373"], ], ); const doorById = new Map(doc.doors.map((d) => [d.id, d])); @@ -105,4 +114,5 @@ test("capabilities mirrors the native shape with hosted values", async () => { assert.equal(doorById.get("ingestion")?.state, "live"); // #12591 landed the sync door: every component-C door is live. assert.equal(doorById.get("sync")?.state, "live"); + assert.equal(doorById.get("bridge")?.state, "live"); }); diff --git a/pkgs/fleet/hosted-worker/test/doors.test.ts b/pkgs/fleet/hosted-worker/test/doors.test.ts index 4b19b951a6..7f29dd1e02 100644 --- a/pkgs/fleet/hosted-worker/test/doors.test.ts +++ b/pkgs/fleet/hosted-worker/test/doors.test.ts @@ -17,7 +17,9 @@ // #12591 landed it — the table is now EMPTY: every component-C // door is live. The 501 test below iterates zero routes and // stands as the invariant's guard for any future skeleton door; -// the sync door's behaviour is covered by test/sync.test.ts. +// the sync door's behaviour is covered by test/sync.test.ts. The +// bridge door (#14373) joined DOOR_ROUTES live, never a stub; its +// behaviour is covered by test/bridge.test.ts. import assert from "node:assert/strict"; import { test } from "node:test"; @@ -35,6 +37,9 @@ const DOOR_ROUTES: { method: string; path: string; fillingIssue: string }[] = [ { method: "POST", path: "/v1/ingestion/github", fillingIssue: "#12590" }, { method: "POST", path: "/v1/sync/project", fillingIssue: "#12591" }, { method: "POST", path: "/v1/sync/queue-github", fillingIssue: "#12591" }, + { method: "POST", path: "/v1/bridge/send", fillingIssue: "#14373" }, + { method: "GET", path: "/v1/bridge/agents", fillingIssue: "#14373" }, + { method: "GET", path: "/v1/bridge/messages", fillingIssue: "#14373" }, ]; const STUB_ROUTES = DOOR_ROUTES.filter( @@ -44,7 +49,10 @@ const STUB_ROUTES = DOOR_ROUTES.filter( r.path !== "/v1/queue/health" && r.path !== "/v1/ingestion/github" && r.path !== "/v1/sync/project" && - r.path !== "/v1/sync/queue-github", + r.path !== "/v1/sync/queue-github" && + r.path !== "/v1/bridge/send" && + r.path !== "/v1/bridge/agents" && + r.path !== "/v1/bridge/messages", ); test("every door route refuses an unauthenticated request", async () => { diff --git a/pkgs/fleet/hosted-worker/wrangler.toml b/pkgs/fleet/hosted-worker/wrangler.toml index d073eb9c13..ece7bc216a 100644 --- a/pkgs/fleet/hosted-worker/wrangler.toml +++ b/pkgs/fleet/hosted-worker/wrangler.toml @@ -16,6 +16,15 @@ compatibility_date = "2025-06-01" [vars] RP_AUDIENCE = "fleet-hosted" +# The message bridge, by service binding (#14373): the bridge door +# calls it presenting the PM stack's bridge credential +# (BRIDGE_PM_TOKEN — a secret, set by name at deployment, never in +# this file). Declared here so the deployed shape carries it; the +# local-only posture above still applies. +[[services]] +binding = "BRIDGE" +service = "message-bridge" + # The ingestion sweeper's standing scope (#12590): the in-scope # repos the scheduled run re-scans (#9060 §16). Set per environment # at deployment; empty here (local only) means the scheduled sweep diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index 1a1636a772..58d84d2484 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -107,6 +107,9 @@ their mailbox, mark what they handled, and post replies and reports back | `GET /api//fleet/agents` | owner | registered agents, groups, last seen, unread counts | | `GET /api//fleet/messages` | owner | `agent`, `direction`, `kind`, `since_id`, `before_id`, `limit`, `order` | | `POST /api//fleet/send` | owner | `{body, to, kind?, sender?}`; `kind` is `message` (default) or `command` | +| `POST /api//fleet/credentials/mint` | owner | `{agent, scopes?, addr?}`: mint a credential for an agent or a service (below); the value is returned once, only its hash stored | +| `GET /fleet//agents` | credential (`read`) | the agents list, as the owner's | +| `GET /fleet//messages` | credential (`read`) | the fleet message log, as the owner's (`agent`, `direction`, `kind`, `since_id`, `before_id`, `limit`, `order`) | The **fleet token** opens only `/fleet/...`. It is derived from the access token (HMAC-SHA256 of `ACCESS_TOKEN` over the label @@ -124,6 +127,18 @@ as the user's word to any connector or agent; per-agent tokens would narrow that. An agent's inbox shows a command with `sender` and `from_addr` `null`, like one from central. +A credential can also be bound to a **service identity** (#14373): +minted with `addr: "service:"` (the name must be the +credential's own agent name), its sends go out from `service:` +instead of `agent:`, so the log tells a service's sends apart +from an agent's and from central's. The PM stack holds such a +credential — minted for `pm-stack`, scopes `send` + `read`, kept as a +Worker secret by name — and its console edge and hosted door call the +bridge over a service binding with it, so a message to an agent is +delivered with no machine relaying it. The `read` scope is never +minted for agents (enroll mints `inbox` + `send` only). Revoking the +agent's credentials on the bridge stops the service's sends there. + Commands reach agents by mailbox rather than by webhook. The event wake-ups below push to a callback URL; fleet agents have none (Muse lanes are cron-started runs in a sandbox with no inbound address), so they wait diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 64b2109f75..f72caf69ab 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -62,6 +62,36 @@ // POST /api//notes-tokens/revoke {identity}: revokes an // identity's notes token(s) // +// Service credentials (#14373, design §4.8): the owner can also mint a +// credential directly, with the scopes it names: +// +// POST /api//fleet/credentials/mint {agent, scopes?, addr?}: +// mints a credential outside the +// enroll flow; the value is +// returned once, here +// +// A credential minted with an `addr` sends as that address instead of +// agent:. The one addr form is service:, and the name +// must be the credential's own: it is how a platform service that is +// not an agent — the PM stack, from_addr service:pm-stack — holds a +// scoped credential of its own (send + the pipeline read below) +// instead of relaying through a machine's shared token. Provenance +// tells such rows apart from owner-sent (from_addr null) and +// agent-sent (agent:) ones in the owner's log; a command still +// reaches its agent with no sender, as every command does. +// +// A third scope, "read", opens the owner's two pipeline views to the +// credential that holds it, at the agent-side address: +// +// GET /fleet//agents the registered agents (the +// ownerRoute "agents" store op) +// GET /fleet//messages the fleet message log (the +// ownerRoute "messages" store op) +// +// Enroll-minted agent credentials never carry "read" (the exchange +// mints CREDENTIAL_SCOPES only): the pipeline stays the owner's and +// its services', not every agent's. +// // `to` names recipients as "agent:" (or a bare name), "group:" // (every registered agent in that group) or "all" (every registered // agent); a list or a comma-separated string mixes them. An agent name @@ -261,11 +291,13 @@ export function parseTargets(to) { return { agents, groups, all }; } -const FROM_ADDR = /^(channel:(claude|chatgpt)|agent:[a-z0-9][a-z0-9._-]{0,63})$/; +const FROM_ADDR = /^(channel:(claude|chatgpt)|(agent|service):[a-z0-9][a-z0-9._-]{0,63})$/; function normalizeFromAddr(v) { if (v === undefined || v === null) return null; - if (typeof v !== "string" || !FROM_ADDR.test(v)) throw new InputError("from_addr must be channel: or agent:"); + if (typeof v !== "string" || !FROM_ADDR.test(v)) { + throw new InputError("from_addr must be channel:, agent: or service:"); + } return v; } @@ -393,6 +425,10 @@ export function fleetSchema(sql) { created TEXT NOT NULL, revoked_at TEXT )`); + // Service credentials (#14373): the address a credential sends as, + // when it is not agent: (service:, its own name). + const credCols = sql.exec("PRAGMA table_info(fleet_credential)").toArray(); + if (!credCols.some((c) => c.name === "addr")) sql.exec("ALTER TABLE fleet_credential ADD COLUMN addr TEXT"); // Bootstrap enroll tokens (#14368): hash only, bound at mint time to // the agent name, kind and groups; single-use (used_at), expiring // (expires_at), revocable while unused (revoked_at). @@ -772,6 +808,10 @@ export async function fleetCall(stub, op, args) { // ---- per-agent credentials and bootstrap enrollment (#14368) ---- export const CREDENTIAL_SCOPES = ["inbox", "send"]; +/** Every scope a credential can hold. "read" (the owner's pipeline + * views, #14373) is minted directly by the owner only; the enroll + * exchange mints CREDENTIAL_SCOPES and never this. */ +export const MINT_SCOPES = ["inbox", "send", "read"]; export const ENROLL_DEFAULT_TTL_SECONDS = 24 * 3600; export const ENROLL_MIN_TTL_SECONDS = 60; export const ENROLL_MAX_TTL_SECONDS = 7 * 24 * 3600; @@ -789,20 +829,75 @@ export function randomTokenValue() { export function fleetCredentialAuthSql(sql, token_hash) { const r = sql - .exec("SELECT agent, scopes FROM fleet_credential WHERE token_hash = ? AND revoked_at IS NULL", token_hash) + .exec("SELECT agent, scopes, addr FROM fleet_credential WHERE token_hash = ? AND revoked_at IS NULL", token_hash) .toArray()[0]; - return r ? { agent: r.agent, scopes: JSON.parse(r.scopes) } : null; + return r ? { agent: r.agent, scopes: JSON.parse(r.scopes), addr: r.addr ?? null } : null; } -export function fleetCredentialPutSql(sql, { token_hash, agent, scopes, created }) { +export function fleetCredentialPutSql(sql, { token_hash, agent, scopes, created, addr = null }) { sql.exec( - "INSERT INTO fleet_credential (token_hash, agent, scopes, created) VALUES (?, ?, ?, ?)", + "INSERT INTO fleet_credential (token_hash, agent, scopes, created, addr) VALUES (?, ?, ?, ?, ?)", token_hash, agent, JSON.stringify(scopes), created, + addr, ); - return { agent, scopes: [...scopes] }; + return { agent, scopes: [...scopes], addr }; +} + +const SERVICE_ADDR = /^service:([a-z0-9][a-z0-9._-]{0,63})$/; + +/** + * Validates a direct credential mint body (the owner's service + * credentials, #14373). The addr, when given, is service: and + * the name is the credential's own agent name: a service speaks as + * itself, never as another principal. Default scopes follow the form: + * a service gets send + read (it has no mailbox of its own to read), + * an agent minted directly gets the enroll pair. + */ +export function normalizeMintCredential(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + const agent = normalizeName(data.agent); + let addr = null; + if (data.addr !== undefined && data.addr !== null && data.addr !== "") { + const m = typeof data.addr === "string" ? SERVICE_ADDR.exec(data.addr) : null; + if (!m) throw new InputError("addr must be service:"); + if (m[1] !== agent) throw new InputError("addr must name the credential's own agent (service:)"); + addr = data.addr; + } + let scopes; + if (data.scopes === undefined || data.scopes === null) { + scopes = addr ? ["send", "read"] : [...CREDENTIAL_SCOPES]; + } else { + if (!Array.isArray(data.scopes) || data.scopes.length === 0) { + throw new InputError(`scopes must be a non-empty list drawn from ${MINT_SCOPES.join(", ")}`); + } + scopes = []; + for (const s of data.scopes) { + if (!MINT_SCOPES.includes(s)) throw new InputError(`scopes must be drawn from ${MINT_SCOPES.join(", ")}`); + if (!scopes.includes(s)) scopes.push(s); + } + } + return { agent, addr, scopes }; +} + +/** + * Mints a credential directly for the owner, outside the enroll flow: + * how a platform service (the PM stack) gets its own. The value exists + * only in this return value; the store receives its SHA-256 hash. + */ +export async function mintFleetCredential(store, data, now = new Date().toISOString()) { + const m = normalizeMintCredential(data); + const value = randomTokenValue(); + await store.fleetCredentialPut({ + token_hash: await noteTokenHash(value), + agent: m.agent, + scopes: m.scopes, + addr: m.addr, + created: now, + }); + return { agent: m.agent, addr: m.addr, scopes: m.scopes, credential: value }; } /** Revokes every live credential of the agent; returns how many. */ @@ -1033,17 +1128,24 @@ const query = (url) => Object.fromEntries(url.searchParams.entries()); /** * An agent's send: to central as before, or (with to, or reply_to a row * another assistant or agent sent) through relay.js to any address. + * `fromAddr` is the sender address the credential fixes (a service + * credential's service:, #14373); without one the sender is + * agent:, as it has always been. */ -async function agentSend(store, d, delivered) { +async function agentSend(store, d, delivered, fromAddr = null) { if (d.broaden !== undefined && d.broaden !== null && (d.to === undefined || d.to === null || d.to === "")) { - // Broadening one of the agent's own earlier distributions: the + // Broadening one of the sender's own earlier distributions: the // store re-delivers its body to the matched-but-undelivered rest. + // from_addr is the credential's fixed address when there is one + // (agent:, or service: for a service credential), + // exactly as the relay path below passes it: the store lets only + // the distribution's original sender broaden it. const agent = normalizeName(d.agent); const out = await store.fleet("broaden", { batch: d.broaden, limit: d.limit, exclude: agent, - from_addr: `agent:${agent}`, + from_addr: fromAddr ?? `agent:${agent}`, }); delivered({ messages: [], fleet: out.messages }); return out; @@ -1064,7 +1166,7 @@ async function agentSend(store, d, delivered) { await store.fleet("origin", { agent, id: d.reply_to }); // must be a row to this agent } const out = await relay(store, { - from: `agent:${agent}`, + from: fromAddr ?? `agent:${agent}`, to: d.to, body: d.body, kind: d.kind, @@ -1129,12 +1231,24 @@ async function agentRoute(request, store, what, url, delivered, cred = null) { const d = await readJson(request); if (cred) { if (!scoped("send") || credOwnName(d.agent, cred) === null) return notFound(); - // from_addr is fixed by the relay to agent:; the - // sender label follows it, whatever the body claims. - d.sender = cred.agent; + // from_addr is fixed by the relay to the credential's address + // (agent:, or service: for a service credential, + // #14373); the sender label follows it, whatever the body claims. + d.sender = cred.addr ?? cred.agent; + return json(await agentSend(store, d, delivered, cred.addr ?? `agent:${cred.agent}`), 201); } return json(await agentSend(store, d, delivered), 201); } + // The owner's pipeline views, for a credential holding the "read" + // scope (a service credential, #14373): the same store ops the owner + // routes answer, nothing more. Enroll-minted agent credentials never + // hold the scope, and the shared fleet token does not open these. + if (what === "agents" || what === "messages") { + if (request.method !== "GET") return notAllowed("GET"); + if (!cred || !scoped("read")) return notFound(); + if (what === "agents") return json(await store.fleet("agents", {})); + return json(await store.fleet("messages", query(url))); + } return notFound(); } @@ -1208,6 +1322,10 @@ export async function handleFleet(request, env, url, getStore, deliveredFor = () const agent = normalizeName((await readJson(request)).agent); return json({ agent, revoked: await store.fleetCredentialRevoke(agent) }); } + if (parts.length === 5 && parts[3] === "credentials" && parts[4] === "mint") { + if (request.method !== "POST") return notAllowed("POST"); + return json(await mintFleetCredential(store, await readJson(request)), 201); + } return notFound(); } if (parts[2] === "enroll-tokens") { diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index 291afa7571..aca9e020ae 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -57,7 +57,9 @@ export function normalizeNew({ body, sender, direction, source, channel = "claud } let from = null; if (from_addr !== undefined && from_addr !== null) { - if (typeof from_addr !== "string" || !FROM_ADDR.test(from_addr)) throw new InputError("from_addr must be channel: or agent:"); + if (typeof from_addr !== "string" || !FROM_ADDR.test(from_addr)) { + throw new InputError("from_addr must be channel:, agent: or service:"); + } if (from_addr === `channel:${channel}`) throw new InputError("a connector can't send to its own channel"); if (direction !== "inbound" || (source !== "mcp" && source !== "fleet")) { throw new InputError("from_addr is only for messages a connector or an agent sends"); @@ -69,7 +71,7 @@ export function normalizeNew({ body, sender, direction, source, channel = "claud return { body, sender: s, direction, source, channel, kind: k, from_addr: from }; } -const FROM_ADDR = /^(channel:(claude|chatgpt)|agent:[a-z0-9][a-z0-9._-]{0,63})$/; +const FROM_ADDR = /^(channel:(claude|chatgpt)|(agent|service):[a-z0-9][a-z0-9._-]{0,63})$/; /** Validates a new message's kind; empty means "message". Throws InputError. */ export function normalizeKind(kind) { @@ -193,11 +195,17 @@ export class MemoryStore { // #14368), same semantics as the Durable Object: hashes only. async fleetCredentialAuth(token_hash) { const c = this.fleetCredentials.get(token_hash); - return c && !c.revoked_at ? { agent: c.agent, scopes: [...c.scopes] } : null; - } - async fleetCredentialPut({ token_hash, agent, scopes, created }) { - this.fleetCredentials.set(token_hash, { agent, scopes: [...scopes], created: created ?? this.now(), revoked_at: null }); - return { agent, scopes: [...scopes] }; + return c && !c.revoked_at ? { agent: c.agent, scopes: [...c.scopes], addr: c.addr ?? null } : null; + } + async fleetCredentialPut({ token_hash, agent, scopes, created, addr = null }) { + this.fleetCredentials.set(token_hash, { + agent, + scopes: [...scopes], + created: created ?? this.now(), + revoked_at: null, + addr, + }); + return { agent, scopes: [...scopes], addr }; } async fleetCredentialRevoke(agent) { let n = 0; diff --git a/pkgs/message-bridge/worker/src/relay.js b/pkgs/message-bridge/worker/src/relay.js index e1c8a8c1fc..a79ec15a95 100644 --- a/pkgs/message-bridge/worker/src/relay.js +++ b/pkgs/message-bridge/worker/src/relay.js @@ -30,7 +30,9 @@ // // Every row another assistant or agent sends records who sent it in // from_addr ("channel:claude", "agent:muse-3"), so the recipient can tell -// it from something Drew sent and answer it with reply_to. +// it from something Drew sent and answer it with reply_to. A platform +// service sends as service: ("service:pm-stack", #14373): not an +// agent and not Drew, and the owner's log tells the three apart. import { GLOB_SEGMENT, isGlob } from "./glob.js"; import { CHANNELS, CHANNEL_NAMES, InputError, MAX_BODY } from "./messages.js"; @@ -47,10 +49,13 @@ export function relayKind(kind) { throw new InputError("kind must be message or instruction"); } -/** The sender's own channel or agent name, from its address. */ +/** The sender's own channel or agent name, from its address. A + * service sender (service:, a platform service like the PM + * stack, #14373) counts as its own name here: it is never its own + * recipient, and a post to central lands under its name. */ function self(from) { const [type, name] = from.split(":"); - return { channel: type === "channel" ? name : null, agent: type === "agent" ? name : null }; + return { channel: type === "channel" ? name : null, agent: type === "agent" || type === "service" ? name : null }; } /** diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index be5300c630..0226e283b7 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -54,6 +54,14 @@ // fleet credential + notes token once // POST /api//fleet/credentials/revoke owner: revoke an agent's // fleet credential(s) +// POST /api//fleet/credentials/mint owner: mint a credential +// directly ({agent, scopes?, addr?}; +// addr service: + scope +// "read" is a service credential, +// #14373): the value is returned once +// GET /fleet//agents|messages the owner's pipeline +// views, for a credential holding +// the "read" scope (#14373) // POST /api//notes-tokens/revoke owner: revoke an identity's // notes token(s) // POST /notes/register owner Bearer token; registers a diff --git a/pkgs/message-bridge/worker/test/credentials.test.mjs b/pkgs/message-bridge/worker/test/credentials.test.mjs index 326f6b170d..5eedc56aaa 100644 --- a/pkgs/message-bridge/worker/test/credentials.test.mjs +++ b/pkgs/message-bridge/worker/test/credentials.test.mjs @@ -312,7 +312,7 @@ test("sql store: hash-only storage and the claim predicate", async () => { assert.equal(noteRegs[0].token_hash, await noteTokenHash(out.notes_token), "notes registration is hash-only too"); // The credential authenticates until revoked. - assert.deepEqual(fleetCredentialAuthSql(sql, await noteTokenHash(out.fleet_token)), { agent: "sql-1", scopes: ["inbox", "send"] }); + assert.deepEqual(fleetCredentialAuthSql(sql, await noteTokenHash(out.fleet_token)), { agent: "sql-1", scopes: ["inbox", "send"], addr: null }); assert.equal(fleetCredentialRevokeSql(sql, "sql-1", new Date().toISOString()), 1); assert.equal(fleetCredentialAuthSql(sql, await noteTokenHash(out.fleet_token)), null); diff --git a/pkgs/message-bridge/worker/test/service-credential.test.mjs b/pkgs/message-bridge/worker/test/service-credential.test.mjs new file mode 100644 index 0000000000..bcc12ad814 --- /dev/null +++ b/pkgs/message-bridge/worker/test/service-credential.test.mjs @@ -0,0 +1,212 @@ +// Service credentials (src/fleet.js, #14373, design §4.8): the owner +// mints a credential directly for a platform service that is not an +// agent — the PM stack — with an addr (service:) it +// sends as and the "read" scope for the owner's pipeline views. The +// PM console's edge Worker holds the value as a Worker secret and +// calls the bridge by service binding; these tests drive the same +// routes end to end through route(). Fleet mailboxes run the real +// fleetOp SQL on node:sqlite (as in fleet.test.mjs); credentials run +// on MemoryStore, which mirrors the Durable Object's hash-only +// semantics. A final block drives the sql helpers directly to prove +// hash-only storage with the addr column. All token values below are +// fixtures or values the Worker itself generated inside the test; +// nothing here is a real credential. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { + fleetCall, + fleetCredentialAuthSql, + fleetCredentialPutSql, + fleetOp, + fleetSchema, + fleetToken, + mintFleetCredential, +} from "../src/fleet.js"; +import { MemoryStore } from "../src/messages.js"; +import { noteTokenHash } from "../src/notes.js"; +import { route } from "../src/routes.js"; + +const TOKEN = "o".repeat(20) + "0123456789abcdefXYZ_-"; +const CHATGPT = "c".repeat(40); +const env = { ACCESS_TOKEN: TOKEN, CHATGPT_TOKEN: CHATGPT }; +const BASE = "https://bridge.example"; +const VALUE = /^[A-Za-z0-9_-]{43}$/; + +/** The Durable Object's sql.exec over node:sqlite. */ +function sqlite() { + const db = new DatabaseSync(":memory:"); + return { + exec(q, ...args) { + const out = db.prepare(q).all(...args); + return { toArray: () => out, one: () => out[0] }; + }, + }; +} + +async function harness() { + const sql = sqlite(); + fleetSchema(sql); + let clock = 0; + const stub = { fleet: (op, args) => fleetOp(sql, op, args, `2026-11-24T00:00:${String(clock++).padStart(2, "0")}Z`) }; + const store = new MemoryStore(); + store.fleet = (op, args) => fleetCall(stub, op, args); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const ft = await fleetToken(env); + const post = (path, body) => + call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const api = { + mintCred: (body) => post(`/api/${TOKEN}/fleet/credentials/mint`, body), + revokeCred: (body) => post(`/api/${TOKEN}/fleet/credentials/revoke`, body), + agents: () => call(`/api/${TOKEN}/fleet/agents`), + messages: (qs = {}) => call(`/api/${TOKEN}/fleet/messages?${new URLSearchParams(qs)}`), + send: (body) => post(`/api/${TOKEN}/fleet/send`, body), + }; + const as = (cred) => ({ + hello: (body) => post(`/fleet/${cred}/hello`, body), + inbox: (qs) => call(`/fleet/${cred}/inbox?${new URLSearchParams(qs)}`), + send: (body) => post(`/fleet/${cred}/send`, body), + agents: () => call(`/fleet/${cred}/agents`), + messages: (qs = {}) => call(`/fleet/${cred}/messages?${new URLSearchParams(qs)}`), + }); + /** Mints the PM stack's service credential; returns the mint body. */ + const mintPm = async (body = { agent: "pm-stack", addr: "service:pm-stack" }) => { + const res = await api.mintCred(body); + assert.equal(res.status, 201, JSON.stringify(body)); + return res.json(); + }; + return { store, call, post, ft, api, as, mintPm }; +} + +test("mint: a service credential is owner-minted, value once, with send + read by default", async () => { + const h = await harness(); + + // Minting is owner-only: the fleet token and junk both 404. + assert.equal((await h.post(`/api/${h.ft}/fleet/credentials/mint`, { agent: "pm-stack" })).status, 404); + assert.equal((await h.post(`/api/nope/fleet/credentials/mint`, { agent: "pm-stack" })).status, 404); + + const mint = await h.mintPm(); + assert.match(mint.credential, VALUE); + assert.equal(mint.agent, "pm-stack"); + assert.equal(mint.addr, "service:pm-stack"); + assert.deepEqual(mint.scopes, ["send", "read"]); + + // The addr must be service:. + for (const body of [ + { agent: "pm-stack", addr: "service:other" }, + { agent: "pm-stack", addr: "agent:pm-stack" }, + { agent: "pm-stack", addr: "pm-stack" }, + { agent: "pm-stack", scopes: ["send", "root"] }, + { agent: "pm-stack", scopes: [] }, + { agent: "pm-stack", scopes: "send" }, + ]) { + assert.equal((await h.api.mintCred(body)).status, 400, JSON.stringify(body)); + } +}); + +test("send: the PM credential delivers as service:pm-stack, told apart from owner and agent rows", async () => { + const h = await harness(); + const mint = await h.mintPm(); + const pm = h.as(mint.credential); + + // Agents register the ordinary way, and one sends a row of its own. + assert.equal((await h.post(`/fleet/${h.ft}/hello`, { agent: "felix-1", groups: ["muse"] })).status, 200); + assert.equal((await h.post(`/fleet/${h.ft}/hello`, { agent: "other-1" })).status, 200); + await h.post(`/fleet/${h.ft}/send`, { agent: "other-1", body: "agent row", to: "agent:felix-1" }); + // Central sends one with the owner token (from_addr null). + await h.api.send({ body: "owner row", to: "agent:felix-1" }); + // The PM stack sends a message and a command with its credential. + const sent = await pm.send({ agent: "pm-stack", body: "pm row", to: "agent:felix-1" }); + assert.equal(sent.status, 201, JSON.stringify(await sent.clone().json().catch(() => null))); + const commanded = await pm.send({ agent: "pm-stack", body: "pm command", to: ["agent:felix-1"], kind: "command" }); + assert.equal(commanded.status, 201); + + const rows = (await (await h.api.messages({ agent: "felix-1", direction: "inbound", order: "asc" })).json()).messages; + const byBody = Object.fromEntries(rows.map((m) => [m.body, m])); + assert.equal(byBody["owner row"].from_addr, null); + assert.equal(byBody["agent row"].from_addr, "agent:other-1"); + assert.equal(byBody["pm row"].from_addr, "service:pm-stack"); + assert.equal(byBody["pm row"].sender, "service:pm-stack"); + assert.equal(byBody["pm command"].from_addr, "service:pm-stack"); + assert.equal(byBody["pm command"].kind, "command"); + + // The agent's own inbox view: the command names no sender, as every + // command does; the message keeps the service's address. + const inbox = (await (await h.call(`/fleet/${h.ft}/inbox?agent=felix-1&unread_only=false`)).json()).messages; + const seen = Object.fromEntries(inbox.map((m) => [m.body, m])); + assert.equal(seen["pm command"].from_addr, null); + assert.equal(seen["pm command"].sender, null); + assert.equal(seen["pm row"].from_addr, "service:pm-stack"); +}); + +test("read: the pipeline views open to the read scope, and to nothing else", async () => { + const h = await harness(); + const mint = await h.mintPm(); + const pm = h.as(mint.credential); + await h.post(`/fleet/${h.ft}/hello`, { agent: "felix-1", groups: ["muse"] }); + await h.api.send({ body: "for felix", to: "agent:felix-1" }); + + const agents = await pm.agents(); + assert.equal(agents.status, 200); + assert.deepEqual( + (await agents.json()).agents.map((a) => a.name), + ["felix-1"], + ); + const log = await pm.messages({ limit: "10", order: "desc" }); + assert.equal(log.status, 200); + assert.equal((await log.json()).messages[0].body, "for felix"); + + // A send-only service credential reads nothing. + const sendOnly = await h.mintPm({ agent: "pm-stack", addr: "service:pm-stack", scopes: ["send"] }); + assert.equal((await h.as(sendOnly.credential).agents()).status, 404); + assert.equal((await h.as(sendOnly.credential).messages()).status, 404); + // The shared fleet token does not open the credential-side views. + assert.equal((await h.as(h.ft).agents()).status, 404); + // A credential with no read scope (an agent's own, via direct mint + // without one) reads nothing either — and cannot hello as the service. + const agentCred = await h.mintPm({ agent: "felix-1" }); + assert.deepEqual(agentCred.scopes, ["inbox", "send"]); + assert.equal(agentCred.addr, null); + assert.equal((await h.as(agentCred.credential).agents()).status, 404); + assert.equal((await pm.hello({ agent: "pm-stack" })).status, 404, "no inbox scope: no mailbox of its own"); + assert.equal((await pm.send({ agent: "felix-1", body: "spoof" })).status, 404, "a credential sends only as itself"); +}); + +test("revoke: revoking the PM credential stops its sends and reads at once, and nothing else", async () => { + const h = await harness(); + const mint = await h.mintPm(); + const pm = h.as(mint.credential); + await h.post(`/fleet/${h.ft}/hello`, { agent: "felix-1" }); + assert.equal((await pm.send({ agent: "pm-stack", body: "before", to: "agent:felix-1" })).status, 201); + + const revoked = await (await h.api.revokeCred({ agent: "pm-stack" })).json(); + assert.equal(revoked.revoked, 1); + assert.equal((await pm.send({ agent: "pm-stack", body: "after", to: "agent:felix-1" })).status, 404); + assert.equal((await pm.agents()).status, 404); + assert.equal((await pm.messages()).status, 404); + + // The agent's mailbox and the shared token are untouched. + const inbox = await h.call(`/fleet/${h.ft}/inbox?agent=felix-1&unread_only=false`); + assert.equal(inbox.status, 200); + assert.deepEqual( + (await inbox.json()).messages.map((m) => m.body), + ["before"], + ); +}); + +test("sql: the credential row stores the hash and the addr, never the value", async () => { + const sql = sqlite(); + fleetSchema(sql); + const store = { + fleetCredentialPut: (rec) => fleetCredentialPutSql(sql, rec), + }; + const mint = await mintFleetCredential(store, { agent: "pm-stack", addr: "service:pm-stack" }, "2026-11-24T00:00:00Z"); + const rows = sql.exec("SELECT * FROM fleet_credential").toArray(); + assert.equal(rows.length, 1); + assert.equal(rows[0].token_hash, await noteTokenHash(mint.credential)); + assert.equal(rows[0].addr, "service:pm-stack"); + assert.deepEqual(JSON.parse(rows[0].scopes), ["send", "read"]); + assert.ok(!JSON.stringify(rows).includes(mint.credential), "the value is nowhere in storage"); + const auth = fleetCredentialAuthSql(sql, await noteTokenHash(mint.credential)); + assert.deepEqual(auth, { agent: "pm-stack", scopes: ["send", "read"], addr: "service:pm-stack" }); +}); diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 8db00ea3b9..0518ff5562 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -20,8 +20,9 @@ With the switch on and both tokens there (the usual state; see | The board, the owner's prompts, pull requests, ranked issues, what is labelled as needing the owner | edge, read from GitHub and the queue store on each section's own interval | unchanged | | One pull request's page, the queue by state, roadmaps, bugs, intake, releases | edge, read when asked for | unchanged | | Ask, reply, close a prompt, comment, rank, move a task, merge, start a deploy, file a note, a bug or a change | edge, at once; never sent to a machine, so never done twice | unchanged | +| Messages to agents; the agents list and the message log | edge, through the bridge Worker on its service binding, under the PM stack's own bridge identity (`service:pm-stack`) | unchanged while the bridge holds that identity; without it, a message is held for a machine as before, and the lists are a machine's report | | The queue task of a prompt, a note or a bug filed at the edge | a machine: the edge files the issue and holds the task (`prompt.enqueue`, `triage.enqueue`) | held, filed once when one connects, dropped after a day and said so | -| Sessions (and what one of them is waiting on the owner for), questions, units, agents | a machine's report, kept at the edge | as of its last report, and the app says how old | +| Sessions (and what one of them is waiting on the owner for), questions, units | a machine's report, kept at the edge | as of its last report, and the app says how old | | Notifications: keys, subscriptions, sending | edge | unchanged; a reply to a prompt is noticed by the edge itself, which wakes each minute while a device is subscribed; one says the laptop has gone quiet | | Linked phones and the widget's summary | edge | unchanged | | Actions only a machine can do, safe to do late (answers, messages to agents, …) | a machine, relayed at once | held at the edge, run once when it is back, dropped after a day and said so | diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 47b1b414cb..0d93a8cc73 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -11,9 +11,18 @@ // are run, by the same code a machine runs: nothing here re-implements // their shapes. // +// The bridge is the edge's too, when it holds the PM stack's own +// bridge credential (#14373): `run` then turns `fleet bridge` argv +// into calls to the bridge Worker over its service binding, +// presenting that credential, so a message the owner sends from the +// app is delivered by the edge itself — as service:pm-stack, the +// bridge's name for the PM stack — and the agents list and message +// log are read there too. Without the credential and the binding, +// `fleet bridge` stays a machine's, exactly as before. +// // What stays a machine's: `fleet queue enqueue` (the fleet binary is -// not here), `fleet bridge`, `systemctl`, and anything that reads the -// dashboard or the decisions file, which live on a machine alone. +// not here), `systemctl`, and anything that reads the dashboard or +// the decisions file, which live on a machine alone. // A prompt, a note or a bug is filed at the edge and only its queue // task is held for a machine, as `prompt.enqueue` or `triage.enqueue`: // the issue is never filed twice. @@ -26,8 +35,11 @@ import { timed } from "../../src/timed.ts"; import { Work } from "../../src/work.ts"; import { memoryShelf, type Shelf, Trends } from "../../src/trends.ts"; -/** Sections the edge reads itself. */ -export const DIRECT_READ_SECTIONS = ["board", "prs", "priorities", "asks", "census", "done"] as const; +/** Sections the edge reads itself. `agents` is read through the + * bridge, so it is only the edge's while it holds the PM bridge + * credential (edge.ts `owned` says which of these are its, case by + * case); the rest are GitHub's and the queue store's. */ +export const DIRECT_READ_SECTIONS = ["board", "prs", "priorities", "asks", "census", "done", "agents"] as const; /** Actions the edge runs itself: each is one or a few calls to GitHub * or the queue store, and needs nothing a machine has. */ export const DIRECT_ACTIONS = [ @@ -54,7 +66,7 @@ export const DIRECT_ACTIONS = [ * before then: it is recorded as the 429 it would have been, and as * it was not sent it wrote nothing and GitHub answered nothing. */ export interface Outward { - to: "github" | "queue"; + to: "github" | "queue" | "bridge"; write: boolean; status: number; limited?: boolean; @@ -62,7 +74,7 @@ export interface Outward { unsent?: boolean; } -/** Which of the two each section this side reads is read from. */ +/** Which of them each section this side reads is read from. */ export const READ_FROM: Record<(typeof DIRECT_READ_SECTIONS)[number], Outward["to"][]> = { board: ["queue"], prs: ["github"], @@ -70,11 +82,23 @@ export const READ_FROM: Record<(typeof DIRECT_READ_SECTIONS)[number], Outward["t asks: ["github", "queue"], census: ["github"], done: ["queue", "github"], + agents: ["bridge"], }; export interface DirectSecrets { githubToken?: string; queueToken?: string; + /** The PM stack's own bridge credential (#14373): minted on the + * bridge for service:pm-stack, held here as a Worker secret (put + * there by scripts/expose.py --edge-direct, from the vault name it + * reads). With `bridgeFetch` it makes `fleet bridge` this side's: + * sends go out as service:pm-stack, and the agents list and the + * message log are read with its read scope. Absent either, the + * bridge stays a machine's. The value is never logged or returned. */ + bridgeToken?: string; + /** The bridge Worker's fetch: its service binding's, in the Worker. + * A stand-in in tests. */ + bridgeFetch?: Fetch; /** Told of every call made, as it is answered. */ seen?: (call: Outward) => void; /** Where GitHub's API and the queue store are, when a local run puts @@ -691,8 +715,126 @@ async function ghApi( return { code: 0, stdout: text, stderr: "" }; } +/** Where the bridge is asked, over its service binding: the binding + * answers for the bridge Worker whatever host the address names, as + * with the app's own files (worker.ts asks https://assets.internal). */ +const BRIDGE_BASE = "https://bridge.internal"; +/** How long the bridge has to answer a call, body and all. */ +const BRIDGE_ASK_MS = 20_000; +/** The name the PM stack's bridge credential is bound to (#14373): + * the bridge fixes a credential's sends to its own name, and this + * side's sends go out under it, as service:pm-stack. */ +export const BRIDGE_AGENT = "pm-stack"; + +/** One `fleet bridge` call as a call to the bridge Worker over its + * service binding, presenting the PM credential in the path (the + * bridge's own way: /fleet//...). The verbs the console's + * classes use — send, agents, log — and no others: anything else is + * refused as a machine's, like every verb this side does not carry. + * A failed call answers the way the fleet binary would: a non-zero + * code with the reason on stderr. The bridge's plain 404 for a wrong + * token is said plainly here — the credential unknown or revoked — + * because that is the console-side error the owner acts on (mint a + * new one; the laptop's own dispatch is untouched by it). */ +async function bridgeCall( + argv: string[], + opts: { stdin?: string } | undefined, + secrets: DirectSecrets, +): Promise { + const token = secrets.bridgeToken; + const fetchImpl = secrets.bridgeFetch; + if (!token || !fetchImpl) throw new OpError(502, "needs a machine"); + const [what, ...rest] = argv; + let method = "GET"; + let path = ""; + let body: string | undefined; + if (what === "agents") { + if (rest.length > 0) throw new OpError(502, "fleet bridge agents takes no arguments here"); + path = `/fleet/${token}/agents`; + } else if (what === "log") { + const query = new URLSearchParams(); + const names: Record = { + "--agent": "agent", + "--direction": "direction", + "--kind": "kind", + "--since-id": "since_id", + "--before-id": "before_id", + "--limit": "limit", + "--order": "order", + }; + for (let i = 0; i < rest.length; i += 2) { + const name = names[rest[i]]; + if (!name || rest[i + 1] === undefined) throw new OpError(502, `fleet bridge log: unexpected argument ${rest[i]}`); + query.set(name, rest[i + 1]); + } + const qs = query.toString(); + path = `/fleet/${token}/messages${qs === "" ? "" : `?${qs}`}`; + } else if (what === "send") { + const to: string[] = []; + let kind = "message"; + let useStdin = false; + for (let i = 0; i < rest.length; i++) { + const arg = rest[i]; + if (arg === "--to") { + const list = (rest[++i] ?? "").split(",").map((t) => t.trim()).filter(Boolean); + to.push(...list); + } else if (arg === "--command") kind = "command"; + else if (arg === "--kind") kind = rest[++i] ?? "message"; + else if (arg === "-") useStdin = true; + else throw new OpError(502, `fleet bridge send: unexpected argument ${arg}`); + } + if (to.length === 0) throw new OpError(502, "fleet bridge send: needs --to"); + if (!useStdin) throw new OpError(502, "fleet bridge send: the text comes on stdin here"); + method = "POST"; + path = `/fleet/${token}/send`; + body = JSON.stringify({ agent: BRIDGE_AGENT, to, body: opts?.stdin ?? "", kind }); + } else { + throw new OpError(502, "needs a machine"); + } + const write = method !== "GET"; + let res: Awaited>; + let text = ""; + try { + await timed(BRIDGE_ASK_MS, async (signal) => { + res = await fetchImpl(`${BRIDGE_BASE}${path}`, { + method, + headers: { + "user-agent": "pm-console-edge", + ...(body === undefined ? {} : { "content-type": "application/json" }), + }, + ...(body === undefined ? {} : { body }), + signal, + }); + // The answer is read as JSON and written back out, like GitHub's: + // the classes parse what the fleet binary would have printed. + try { + text = JSON.stringify(await res.json()); + } catch { + text = ""; + } + }); + } catch (error) { + secrets.seen?.({ to: "bridge", write, status: 0 }); + return { code: 1, stdout: "", stderr: `the bridge could not be reached: ${(error as Error).message}` }; + } + secrets.seen?.({ to: "bridge", write, status: res!.status }); + if (!res!.ok) { + if (res!.status === 404) { + return { + code: 1, + stdout: "", + stderr: "the bridge turned the PM credential away (unknown or revoked); nothing was sent", + }; + } + const why = text === "" || text === "null" ? `the bridge answered http ${res!.status}` : text; + return { code: 1, stdout: "", stderr: why }; + } + return { code: 0, stdout: text, stderr: "" }; +} + /** The edge's `run`: GitHub through REST, the queue token from its - * Worker secret, and everything else refused as a machine's. */ + * Worker secret, the bridge through its binding with the PM + * credential, and everything else refused as a machine's. */ export function edgeRun(config: Config, secrets: DirectSecrets, fetchImpl: Fetch): Run { const origin = (secrets.githubApi || GITHUB_API).replace(/\/+$/, ""); return async (argv, opts) => { @@ -716,6 +858,9 @@ export function edgeRun(config: Config, secrets: DirectSecrets, fetchImpl: Fetch } throw new OpError(502, `the edge has no secret named ${name ?? "?"}`); } + if (bin === config.fleetBin && verb === "bridge") { + return bridgeCall(rest, opts, secrets); + } throw new OpError(502, "needs a machine"); }; } @@ -825,6 +970,8 @@ export async function directRead(section: string, ops: Ops, work: Work): Promise return work.censusDirect(); case "done": return work.done(); + case "agents": + return ops.agents(); default: throw new Error(`not a section the edge reads itself: ${section}`); } diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index b25be49dea..d164b926d2 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -287,6 +287,12 @@ export interface EdgeOptions { enabled: boolean; githubToken?: string; queueToken?: string; + /** The PM stack's own bridge credential and the bridge Worker's + * service binding (#14373): with both, `message.send` and the + * agents/messages reads are this side's, done through the bridge + * as service:pm-stack. Either missing, they stay a machine's. */ + bridgeToken?: string; + bridgeFetch?: unknown; fetchImpl?: typeof fetch; /** Where GitHub's API and the queue store are, when a local run * puts stand-ins in their place. */ @@ -1485,9 +1491,19 @@ export class Edge { // ---- doing the core here ------------------------------------------------ - /** The kinds this side does itself when it does the core. */ + /** Whether this side holds the PM bridge credential and the bridge + * binding (#14373): the two together make the bridge this side's. */ + private bridgeReady(): boolean { + return Boolean(this.direct?.bridgeToken) && Boolean(this.direct?.bridgeFetch); + } + + /** The kinds this side does itself when it does the core. A message + * is this side's only with the bridge held (bridgeReady): without + * it the kind stays a machine's, as it was before the bridge path + * existed, and is held for one like any other. */ private kinds(): readonly string[] { - return this.direct?.kinds ?? DIRECT_ACTIONS; + const base = this.direct?.kinds ?? DIRECT_ACTIONS; + return this.bridgeReady() && !base.includes("message.send") ? [...base, "message.send"] : base; } /** A kind this side does itself when it does the core; any other is @@ -1529,7 +1545,11 @@ export class Edge { // repository: a machine that has not said which they are (one // from before it did) goes on reporting the list itself. Read // from no repositories it would be an empty list, and whole. - (name !== "census" || (cfg?.needsRepos.length ?? 0) > 0), + (name !== "census" || (cfg?.needsRepos.length ?? 0) > 0) && + // The agents list is the bridge's: read here only while this + // side holds the PM bridge credential (#14373). Without it a + // machine goes on reporting the list, as it did before. + (name !== "agents" || this.bridgeReady()), ); } @@ -1551,6 +1571,8 @@ export class Edge { const made = directClasses(cfg, { githubToken: this.direct?.githubToken, queueToken: this.direct?.queueToken, + bridgeToken: this.direct?.bridgeToken, + bridgeFetch: this.direct?.bridgeFetch as never, githubApi: this.direct?.githubApi, queueDb: this.direct?.queueDb, fetchImpl: this.direct?.fetchImpl as never, @@ -1725,6 +1747,13 @@ export class Edge { } const kinds: Record = {}; for (const name of DIRECT_READ_SECTIONS) { + // The agents section is the bridge's: with no PM bridge + // credential held there is no path here to prove, and the + // section is a machine's, as it was before (#14373). Every + // other section is checked even while it is a machine's for + // being refused: the check is how this side finds it can read + // the section itself again. + if (name === "agents" && !this.bridgeReady()) continue; try { await directRead(name, direct.ops, direct.work); kinds[name] = { ok: true }; @@ -2471,10 +2500,14 @@ export class Edge { await this.schedule(cfg); return res; } - // What needs only GitHub and the queue store is read here, by - // the code a machine would read it with. + // What needs only GitHub, the queue store and the bridge is + // read here, by the code a machine would read it with. The + // bridge's own read (the message log) is attempted only while + // this side holds the bridge credential: without it the log + // is a machine's to read, and the request goes to the host + // below as it did before. const mine = this.mine(cfg); - if (mine) { + if (mine && !(seg.length === 1 && seg[0] === "messages" && !this.bridgeReady())) { const from = this.outwardN; let read: unknown; try { diff --git a/pm-stack/console/edge/src/worker.ts b/pm-stack/console/edge/src/worker.ts index 3d9f269291..0987243246 100644 --- a/pm-stack/console/edge/src/worker.ts +++ b/pm-stack/console/edge/src/worker.ts @@ -23,6 +23,14 @@ interface Env { GITHUB_TOKEN?: string; QUEUE_TOKEN?: string; EDGE_DIRECT?: string; + /** The message bridge, by service binding (#14373), and the PM + * stack's own bridge credential: a Worker secret like the two + * tokens, put there by scripts/expose.py --edge-direct from the + * vault. With both, the edge sends the owner's messages itself, as + * service:pm-stack, and reads the agents list and the message log + * from the bridge; without either, those stay a machine's. */ + BRIDGE?: { fetch(request: Request): Promise }; + BRIDGE_TOKEN?: string; /** Local development only: where GitHub's API and the queue store * are, when they are stand-ins. Never set where this is deployed: the * Worker's tokens are sent to whatever these name. */ @@ -85,6 +93,13 @@ export class PmEdge extends DurableObject { enabled: env.EDGE_DIRECT === "on", githubToken: env.GITHUB_TOKEN, queueToken: env.QUEUE_TOKEN, + bridgeToken: env.BRIDGE_TOKEN, + // The binding's fetch, shaped as the fetch the classes take: + // not to be called as a method, like the platform's own. + bridgeFetch: env.BRIDGE + ? (url: string | URL | Request, init?: RequestInit) => + env.BRIDGE.fetch(new Request(url as string, init)) + : undefined, githubApi: env.GITHUB_API_ORIGIN, queueDb: env.QUEUE_DB_ORIGIN, fetchImpl: fetch, diff --git a/pm-stack/console/edge/wrangler.jsonc b/pm-stack/console/edge/wrangler.jsonc index 6dcab57992..ab6d0cc58a 100644 --- a/pm-stack/console/edge/wrangler.jsonc +++ b/pm-stack/console/edge/wrangler.jsonc @@ -27,13 +27,21 @@ "html_handling": "none", "not_found_handling": "none" }, + // The message bridge, called by service binding (#14373): the edge + // sends the owner's messages through it with the PM stack's own + // bridge credential, and reads the agents list and the message log + // from it, instead of waiting for a machine's fleet binary. + "services": [{ "binding": "BRIDGE", "service": "message-bridge" }], // One object holds the state: the copy of what the host last // reported, what is held for it, notification subscriptions and keys, // linked phones. Three secrets are optional, put there by // scripts/expose.py --edge-direct (off by default): GITHUB_TOKEN and // QUEUE_TOKEN, which let the Worker read and write GitHub and the // queue store itself while the laptop is away, and EDGE_DIRECT, the - // explicit opt-in that must read `on` for either to be used. + // explicit opt-in that must read `on` for either to be used. A fourth, + // BRIDGE_TOKEN, is the PM bridge credential the binding above is + // called with; expose.py uploads it in the same pass when the vault + // holds it, and without it the bridge verbs stay a machine's. "durable_objects": { "bindings": [{ "name": "PM", "class_name": "PmEdge" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PmEdge"] }] } diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index ac34f7f8b6..78c2cbfe8a 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -2594,6 +2594,7 @@ const REFUSED_SAID = { "read.asks": "reading your prompts", "read.census": "reading what needs you", "read.done": "reading what was finished", + "read.agents": "reading the agents list", }; /** What the edge says of doing the core itself, read from its public diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 9bf831e1e1..f00ef5bef5 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -123,6 +123,15 @@ # name the console's environment file may override. GITHUB_TOKEN_SECRET = "github.developing-today-code-automation" QUEUE_TOKEN_DEFAULT = "turso.fleet-queue-rw-token" +# The vault name of the PM stack's own bridge credential (#14373), +# minted on the message bridge for service:pm-stack and put in the +# vault by hand; the console's environment file may override the name, +# like the queue token's. The edge Worker presents it to the bridge +# over its service binding, so the owner's messages are delivered at +# the edge. It rides along with the direct tokens: a run that cannot +# read it leaves the bridge a machine's and says so, and never fails +# over it — its absence is a state (not minted yet), not an error. +BRIDGE_TOKEN_DEFAULT = "bridge.pm-stack-token" @contextlib.contextmanager @@ -281,7 +290,9 @@ def ensure_edge_direct( check: bool, ) -> None: """Upload the two tokens the edge Worker acts with, and its switch, - or turn the switch off and take the tokens away again. + or turn the switch off and take the tokens away again. The Worker's + bridge token (#14373) rides along in both directions when the vault + holds it; it is never one of the three the mode stands on. A secret is read by name through `fleet secrets get` and sent to Cloudflare's API as a Worker secret; it is never printed, written to @@ -324,10 +335,16 @@ def remember(mode: str) -> None: state.mkdir(parents=True, exist_ok=True, mode=0o700) marker.write_text(mode + "\n") + def bridge_name() -> str: + return ( + env_values(env).get("PM_CONSOLE_BRIDGE_TOKEN_NAME") + or BRIDGE_TOKEN_DEFAULT + ) + def take_tokens_away() -> None: """Off means the Worker holds nothing it could act with.""" names = held() - for name in ("GITHUB_TOKEN", "QUEUE_TOKEN"): + for name in ("GITHUB_TOKEN", "QUEUE_TOKEN", "BRIDGE_TOKEN"): if name in names: cf.change( f"edge direct: take {name} away from the Worker", @@ -350,6 +367,19 @@ def upload() -> None: put("GITHUB_TOKEN", github) put("QUEUE_TOKEN", queue) put("EDGE_DIRECT", "on") + # The bridge token rides along when the vault holds it; a + # vault without it is a state (not minted yet), said once + # here, and the mode stands on the three above regardless. + bridge = secret(bridge_name()) + if bridge: + put("BRIDGE_TOKEN", bridge) + else: + print( + "note: the edge Worker was not given its bridge token: " + f"{bridge_name()} is not readable here; the owner's " + "messages stay a machine's until it is, and the next " + "run tries again" + ) except SystemExit: # Part-way is not on. What did get there is taken away again, # so a failed attempt leaves the Worker holding nothing. @@ -374,6 +404,20 @@ def upload() -> None: ) if not check: upload() + return + # Nothing of the three is lost. The bridge token is given when + # the vault holds it and the Worker does not; a vault without + # it is left alone in silence — not a loss, and the timer's run + # is not made to say so every quarter hour. + try: + if "BRIDGE_TOKEN" not in held(): + bridge = secret(bridge_name()) + if bridge: + cf.changes.append("edge direct: give the Worker its bridge token") + if not check: + put("BRIDGE_TOKEN", bridge) + except SystemExit as error: + print(f"note: could not see what the Worker holds: {error}") return if wanted and choice is None: # Never told either way: on is how this is set up. Whether it can diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index f5530a36b7..aff2880d4d 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -641,6 +641,63 @@ def test_direct_mode_gives_the_worker_its_tokens_and_takes_them_away_again(self) self.assertEqual(account.changes, []) self.assertEqual(account.order, []) + def test_direct_mode_gives_the_worker_its_bridge_token_when_the_vault_holds_one(self): + account = Account() + marker = pathlib.Path(self.home) / ".local/state/pm-console/edge-direct" + path = f"/accounts/acc/workers/scripts/{expose.WORKER}/secrets" + secrets = { + expose.GITHUB_TOKEN_SECRET: "gh-test-value", + expose.QUEUE_TOKEN_DEFAULT: "queue-test-value", + expose.BRIDGE_TOKEN_DEFAULT: "bridge-test-value", + } + # Turning direct mode on uploads the bridge token as a fourth + # secret, after the three the mode stands on. + account.order.clear() + self.assertEqual( + run(account, self.home, "--edge-direct", "on", secrets=secrets), 0 + ) + self.assertEqual( + account.worker_secrets, + { + "GITHUB_TOKEN": "gh-test-value", + "QUEUE_TOKEN": "queue-test-value", + "EDGE_DIRECT": "on", + "BRIDGE_TOKEN": "bridge-test-value", + }, + ) + self.assertEqual(account.order, [f"PUT {path}"] * 4) + self.assertEqual(marker.read_text().strip(), "on") + # The bridge value is in nothing printed, said or written. + said = "\n".join(account.printed + account.changes) + self.assertNotIn("bridge-test-value", said) + for kept in pathlib.Path(self.home).rglob("*"): + if kept.is_file(): + self.assertNotIn("bridge-test-value", kept.read_text()) + # A timer's run changes nothing while the Worker holds it... + account.order.clear() + self.assertEqual(run(account, self.home, secrets=secrets), 0) + self.assertEqual(account.changes, []) + self.assertEqual(account.order, []) + # ...and gives it back, alone, when the Worker has lost it. + del account.worker_secrets["BRIDGE_TOKEN"] + account.order.clear() + self.assertEqual(run(account, self.home, secrets=secrets), 0) + self.assertEqual(account.worker_secrets["BRIDGE_TOKEN"], "bridge-test-value") + self.assertEqual(account.order, [f"PUT {path}"]) + # Off takes it away with the other tokens. + account.order.clear() + self.assertEqual(run(account, self.home, "--edge-direct", "off"), 0) + self.assertEqual(account.worker_secrets, {"EDGE_DIRECT": "off"}) + self.assertEqual( + account.order, + [ + f"PUT {path}", + f"DELETE {path}/GITHUB_TOKEN", + f"DELETE {path}/QUEUE_TOKEN", + f"DELETE {path}/BRIDGE_TOKEN", + ], + ) + def test_the_worker_is_given_its_tokens_unless_told_off(self): marker = pathlib.Path(self.home) / ".local/state/pm-console/edge-direct" path = f"/accounts/acc/workers/scripts/{expose.WORKER}/secrets" diff --git a/pm-stack/console/src/reads.ts b/pm-stack/console/src/reads.ts index 5a382f4381..9eb674d8cf 100644 --- a/pm-stack/console/src/reads.ts +++ b/pm-stack/console/src/reads.ts @@ -1,10 +1,11 @@ -// Reads that need nothing but GitHub and the queue store. +// Reads that need nothing but GitHub, the queue store and the bridge. // // They are answered by the same code wherever the app is served from: a // machine asks through the fleet binary, and Cloudflare asks GitHub's -// and the queue store's own APIs (edge/src/direct.ts). Neither needs the -// other for these. A read that does need a machine (its units, its -// agents, the dashboard's questions) is not here, and is asked of one. +// and the queue store's own APIs and the bridge Worker over its +// service binding (edge/src/direct.ts). Neither needs the other for +// these. A read that does need a machine (its units, the dashboard's +// questions) is not here, and is asked of one. import type { Ops } from "./ops.ts"; import type { Plan } from "./plan.ts"; import type { Trends } from "./trends.ts"; @@ -44,6 +45,13 @@ export async function platformRead( return plan.bugs(fresh); case "intake": return plan.intakeList(fresh); + // The bridge's message log (#14373). On a machine this address + // is answered by the server's own switch before this list is + // reached; at the edge it is this list, read through the PM + // bridge credential. (`agents` is a document section instead: + // edge/src/direct.ts reads it the same way.) + case "messages": + return ops.messages(query.get("limit")); case "trends": return trends ? trends.read(query.get("days"), fresh, query.get("end")) : undefined; } diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index 01bf8e73e1..6eae7fce16 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -169,6 +169,122 @@ describe("the edge's run: secrets and the laptop's verbs", () => { }); }); +describe("the edge's run: the bridge through its binding", () => { + // The bridge Worker, standing in: every call recorded, its answer + // set by the test. The credential is a fixture, never a real one. + function bridgeHarness() { + const calls: { url: string; init: { method: string; headers: Record; body?: string } }[] = []; + const answer: { ok: boolean; status: number; body: unknown } = { + ok: true, + status: 201, + body: { messages: [], fleet: [{ id: 7, agent: "felix-1" }] }, + }; + const bridgeFetch = (async ( + url: string, + init: { method: string; headers: Record; body?: string }, + ) => { + calls.push({ url: String(url), init }); + return { ok: answer.ok, status: answer.status, json: async () => answer.body }; + }) as unknown as Fetch; + const seen: Outward[] = []; + const secrets = { + githubToken: "gh-test", + queueToken: "queue-test", + bridgeToken: "pm-cred-test", + bridgeFetch, + seen: (call: Outward) => seen.push(call), + }; + const run = edgeRun(directConfig(edgeConfig), secrets, bridgeFetch); + return { calls, answer, run, seen, secrets, bridgeFetch }; + } + + test("a send becomes a POST to the bridge as pm-stack, the text on the body, never in the address", async () => { + const h = bridgeHarness(); + const out = await h.run(["fleet", "bridge", "send", "--to", "felix-1,group:muse", "--command", "-"], { + stdin: "do the thing", + }); + expect(h.calls).toHaveLength(1); + expect(h.calls[0].url).toBe("https://bridge.internal/fleet/pm-cred-test/send"); + expect(h.calls[0].init.method).toBe("POST"); + expect(JSON.parse(h.calls[0].init.body ?? "{}")).toEqual({ + agent: "pm-stack", + to: ["felix-1", "group:muse"], + body: "do the thing", + kind: "command", + }); + expect(out.code).toBe(0); + expect(JSON.parse(out.stdout)).toEqual({ messages: [], fleet: [{ id: 7, agent: "felix-1" }] }); + expect(h.seen).toEqual([{ to: "bridge", write: true, status: 201 }]); + }); + + test("a send without --command is a message; agents and the log are reads of the same binding", async () => { + const h = bridgeHarness(); + await h.run(["fleet", "bridge", "send", "--to", "all", "-"], { stdin: "hello" }); + expect(JSON.parse(h.calls[0].init.body ?? "{}").kind).toBe("message"); + h.answer.status = 200; + h.answer.body = { agents: [{ name: "felix-1" }] }; + const agents = await h.run(["fleet", "bridge", "agents"]); + expect(h.calls[1].url).toBe("https://bridge.internal/fleet/pm-cred-test/agents"); + expect(h.calls[1].init.method).toBe("GET"); + expect(JSON.parse(agents.stdout)).toEqual({ agents: [{ name: "felix-1" }] }); + h.answer.body = { messages: [{ id: 3 }] }; + const log = await h.run(["fleet", "bridge", "log", "--limit", "30", "--order", "desc"]); + expect(h.calls[2].url).toBe("https://bridge.internal/fleet/pm-cred-test/messages?limit=30&order=desc"); + expect(JSON.parse(log.stdout)).toEqual({ messages: [{ id: 3 }] }); + expect(h.seen.map((c) => [c.to, c.write, c.status])).toEqual([ + ["bridge", true, 201], + ["bridge", false, 200], + ["bridge", false, 200], + ]); + }); + + test("a credential the bridge no longer knows is said plainly, as a failed call", async () => { + const h = bridgeHarness(); + h.answer.ok = false; + h.answer.status = 404; + h.answer.body = null; + const out = await h.run(["fleet", "bridge", "send", "--to", "felix-1", "-"], { stdin: "hi" }); + expect(out.code).toBe(1); + expect(out.stderr).toContain("turned the PM credential away (unknown or revoked)"); + expect(h.seen).toEqual([{ to: "bridge", write: true, status: 404 }]); + }); + + test("without the credential, or without the binding, the bridge is still a machine's", async () => { + const h = bridgeHarness(); + const noToken = edgeRun(directConfig(edgeConfig), { bridgeFetch: h.bridgeFetch }, h.bridgeFetch); + await expect(noToken(["fleet", "bridge", "agents"])).rejects.toThrow(/needs a machine/); + const noBinding = edgeRun(directConfig(edgeConfig), { bridgeToken: "pm-cred-test" }, h.bridgeFetch); + await expect(noBinding(["fleet", "bridge", "agents"])).rejects.toThrow(/needs a machine/); + // And a bridge verb this side does not carry is a machine's too. + await expect(h.run(["fleet", "bridge", "inbox", "--agent", "felix-1"])).rejects.toThrow(/needs a machine/); + expect(h.calls).toHaveLength(0); + }); + + test("the classes send and read through the bridge unchanged", async () => { + const h = bridgeHarness(); + const { ops } = directClasses(edgeConfig, h.secrets); + const sent = await ops.send(["agent:felix-1"], "hello there", true); + expect(sent).toEqual({ to: ["agent:felix-1"], command: true }); + expect(JSON.parse(h.calls[0].init.body ?? "{}")).toEqual({ + agent: "pm-stack", + to: ["agent:felix-1"], + body: "hello there", + kind: "command", + }); + h.answer.status = 200; + h.answer.body = { agents: [{ name: "felix-1", groups: [] }] }; + expect(await ops.agents()).toEqual([{ name: "felix-1", groups: [] }]); + h.answer.body = { messages: [{ id: 1, body: "one" }] }; + expect(await ops.messages(5)).toEqual([{ id: 1, body: "one" }]); + expect(h.calls[2].url).toBe("https://bridge.internal/fleet/pm-cred-test/messages?limit=5&order=desc"); + }); + + test("the agents section is read by the class that reads it on the laptop", async () => { + const ops = { agents: async () => [{ name: "felix-1" }] }; + expect(await directRead("agents", ops as never, {} as never)).toEqual([{ name: "felix-1" }]); + }); +}); + describe("the direct classes", () => { test("the config the edge builds carries what the classes need and nothing it cannot use", () => { const config = directConfig(edgeConfig); @@ -516,6 +632,7 @@ describe("what this side notes of each call it makes", () => { asks: ["github", "queue"], census: ["github"], done: ["queue", "github"], + agents: ["bridge"], }); }); }); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 5b1445ccda..cf008d8b3f 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -70,7 +70,7 @@ const SECTION_NAMES = [ "more", ]; -async function setup(options: { direct?: boolean; kinds?: readonly string[] } = {}) { +async function setup(options: { direct?: boolean; kinds?: readonly string[]; bridge?: boolean } = {}) { const now = { t: START }; const clock = () => now.t; const access = await signer("k1"); @@ -666,6 +666,37 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[] } = } throw new Error(`unexpected GitHub call ${method} ${url}`); }; + /** The bridge, as the edge reaches it over its service binding + * (#14373): every call recorded, and the agents and the message log + * it answers with. `bridgeRefuses` makes its next answer the plain + * 404 of a credential the bridge no longer knows. */ + const bridgeCalls: { method: string; url: string; body?: string }[] = []; + const bridgeAgents = [ + { name: "lane-1", groups: ["muse"], first_seen: "2026-11-24T00:00:00Z", last_seen: "2026-11-24T01:00:00Z" }, + ]; + const bridgeLog = [ + { id: 3, agent: "lane-1", direction: "inbound", kind: "message", sender: "service:pm-stack", body: "earlier" }, + ]; + const bridgeRefuses = { on: false }; + const bridgeFetch = (async ( + url: string, + init: { method?: string; headers?: Record; body?: string }, + ) => { + const u = String(url); + const method = init?.method ?? "GET"; + bridgeCalls.push({ method, url: u, body: init?.body }); + if (bridgeRefuses.on) return { ok: false, status: 404, json: async () => JSON.parse("") }; + if (method === "POST" && u.endsWith("/send")) { + return { ok: true, status: 201, json: async () => ({ messages: [], fleet: [{ id: 9, agent: "lane-1" }] }) }; + } + if (method === "GET" && u.endsWith("/agents")) { + return { ok: true, status: 200, json: async () => ({ agents: bridgeAgents }) }; + } + if (method === "GET" && u.includes("/messages")) { + return { ok: true, status: 200, json: async () => ({ messages: bridgeLog }) }; + } + throw new Error(`unexpected bridge fetch ${method} ${u}`); + }) as never; /** The direct source, made to fail by a test that turns it on. */ const directDown = { on: false }; const directFetch = (async ( @@ -801,6 +832,7 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[] } = enabled: true, githubToken: "gh-test", queueToken: "queue-test", + ...(options.bridge ? { bridgeToken: "pm-cred-test", bridgeFetch } : {}), fetchImpl: asThePlatformFetch(directFetch) as typeof directFetch, ...(options.kinds ? { kinds: options.kinds } : {}), } @@ -1225,6 +1257,10 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[] } = access, edgeConfig, directDown, + bridgeCalls, + bridgeAgents, + bridgeLog, + bridgeRefuses, githubCalls, queueCalls, strays, @@ -3769,6 +3805,60 @@ describe("the edge does the core itself", () => { expect(later.doc.read.board).toBe(new Date(w.now.t).toISOString()); }); + test("a message is delivered by the edge through the bridge, with every machine away, and the agents and the log are read there", async () => { + const w = await setup({ direct: true, bridge: true }); + await w.hostReads(); + await w.link.now.once(); + w.hostSaw.length = 0; + // Every machine goes away: nothing can be relayed or held for one. + w.net.hostUp = false; + const sent = await w.act("message.send", { to: ["lane-1"], text: "from the edge" }); + expect(await sent.json()).toEqual({ ok: true, result: { to: ["lane-1"], command: false } }); + // The bridge was asked once, over its binding, as the PM stack. + expect(w.bridgeCalls).toHaveLength(1); + expect(w.bridgeCalls[0].method).toBe("POST"); + expect(w.bridgeCalls[0].url).toBe("https://bridge.internal/fleet/pm-cred-test/send"); + expect(JSON.parse(w.bridgeCalls[0].body ?? "{}")).toEqual({ + agent: "pm-stack", + to: ["lane-1"], + body: "from the edge", + kind: "message", + }); + // Nothing waits for a machine, and no machine was asked for anything. + const machines = (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + expect(machines.held).toEqual([]); + expect(w.ran).toEqual([]); + // The agents list is the bridge's, read here: the ops document + // shows the agent the bridge named, not the host's empty list. + const ops = (await (await w.browse("/console/api/doc/ops")).json()) as { agents: { name: string }[] }; + expect(ops.agents.map((a) => a.name)).toEqual(["lane-1"]); + // The message log is the bridge's too, at the address the app asks. + const log = (await (await w.browse("/console/api/messages?limit=15")).json()) as { body: string }[]; + expect(log.map((m) => m.body)).toEqual(["earlier"]); + expect(w.bridgeCalls.map((c) => `${c.method} ${c.url}`)).toEqual([ + "POST https://bridge.internal/fleet/pm-cred-test/send", + "GET https://bridge.internal/fleet/pm-cred-test/agents", + "GET https://bridge.internal/fleet/pm-cred-test/messages?limit=15&order=desc", + ]); + expect(w.hostSaw).not.toContain("GET /console/api/messages?limit=15"); + }); + + test("a bridge credential the bridge no longer knows stops the send here, with the reason said", async () => { + const w = await setup({ direct: true, bridge: true }); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + w.bridgeRefuses.on = true; + const sent = await w.act("message.send", { to: ["lane-1"], text: "never sent" }); + expect(sent.status).toBe(502); + expect(((await sent.json()) as { error: string }).error).toContain("turned the PM credential away"); + // It was not handed to a machine either: the refusal is the + // credential's, and a machine's own dispatch is another matter. + const machines = (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + expect(machines.held).toEqual([]); + expect(w.ran).toEqual([]); + }); + test("a section is read again when its own interval has passed, behind the answer and never in its way", async () => { const w = await primary(); await w.core(); diff --git a/pm-stack/platform/workers.json b/pm-stack/platform/workers.json index 1408fcc515..20b35e0122 100644 --- a/pm-stack/platform/workers.json +++ b/pm-stack/platform/workers.json @@ -7,7 +7,7 @@ "title": "PM console", "group": "platform", "path": "pm-stack/console/edge", - "does": "Serves the PM app, does the core itself (the board, prompts, pull requests, ranked issues, the plan) and holds what waits for a machine.", + "does": "Serves the PM app, does the core itself (the board, prompts, pull requests, ranked issues, the plan), sends messages to agents itself through the message bridge on a service binding (as service:pm-stack), and holds what waits for a machine.", "state": "in service", "deploy": "actions", "workflow": "pm-console-edge-deploy.yml",