diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 87b19a9c19..19683f4245 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -34,6 +34,34 @@ // POST /api//fleet/send {body, to, kind?, sender?}: one // inbound row per recipient // +// Per-agent credentials and bootstrap enrollment (#14368, design §4.5): +// the routes above also answer to a per-agent credential in place of +// the fleet token (/fleet//...). A credential is a random +// value whose SHA-256 hash alone is stored (fleet_credential, the +// notes-token model); it acts only as its own agent — hello/inbox/ack +// for its own name (scope "inbox"), send with from_addr fixed to +// agent: (scope "send") — and every refusal is the usual +// plain 404. The owner mints single-use, expiring bootstrap tokens +// bound at mint time to a name, kind and groups (enroll_token, hash +// only): +// +// POST /api//enroll-tokens {agent, kind?, groups?, +// notes_identity?, ttl_seconds?}: +// mints a bootstrap token; the +// value is returned once, here +// POST /api//enroll-tokens/revoke {bootstrap_token | token_hash}: +// revokes an unused bootstrap token +// POST /enroll/exchange {bootstrap_token, agent}: burns +// the token, registers the mailbox +// (and the notes identity, when +// minted with one) and returns the +// agent's fleet credential and +// notes token, once +// POST /api//fleet/credentials/revoke {agent}: revokes every +// live fleet credential of an agent +// POST /api//notes-tokens/revoke {identity}: revokes an +// identity's notes token(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. kind is @@ -58,6 +86,7 @@ import { MIN_TOKEN_LENGTH, matchTokenPath, safeEqual, tokenConfigured } from "./auth.js"; import { InputError, MAX_BODY, MAX_SENDER } from "./messages.js"; +import { normalizeNoteIdentity, noteTokenHash } from "./notes.js"; import { relay, replyAddress } from "./relay.js"; export const FLEET_KINDS = ["message", "command"]; @@ -294,6 +323,30 @@ export function fleetSchema(sql) { const cols = sql.exec("PRAGMA table_info(fleet_message)").toArray(); if (!cols.some((c) => c.name === "from_addr")) sql.exec("ALTER TABLE fleet_message ADD COLUMN from_addr TEXT"); sql.exec("CREATE INDEX IF NOT EXISTS fleet_message_mailbox ON fleet_message (agent, direction, read_at)"); + // Per-agent credentials (#14368): only the SHA-256 hash of a credential + // is stored, never the value. scopes is a JSON array drawn from + // CREDENTIAL_SCOPES; revoked_at is the per-agent kill switch. + sql.exec(`CREATE TABLE IF NOT EXISTS fleet_credential ( + token_hash TEXT PRIMARY KEY, + agent TEXT NOT NULL, + scopes TEXT NOT NULL DEFAULT '[]', + created TEXT NOT NULL, + revoked_at 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). + sql.exec(`CREATE TABLE IF NOT EXISTS enroll_token ( + token_hash TEXT PRIMARY KEY, + agent TEXT NOT NULL, + kind TEXT NOT NULL, + groups TEXT NOT NULL DEFAULT '[]', + notes_identity TEXT, + expires_at TEXT NOT NULL, + used_at TEXT, + revoked_at TEXT, + created TEXT NOT NULL + )`); } const rows = (cursor) => cursor.toArray().map((r) => ({ ...r })); @@ -516,6 +569,235 @@ export async function fleetCall(stub, op, args) { return out; } +// ---- per-agent credentials and bootstrap enrollment (#14368) ---- + +export const CREDENTIAL_SCOPES = ["inbox", "send"]; +export const ENROLL_DEFAULT_TTL_SECONDS = 24 * 3600; +export const ENROLL_MIN_TTL_SECONDS = 60; +export const ENROLL_MAX_TTL_SECONDS = 7 * 24 * 3600; + +/** A fresh credential value: 32 random bytes, base64url (43 chars). Only its hash is stored. */ +export function randomTokenValue() { + const b = new Uint8Array(32); + crypto.getRandomValues(b); + return b64url(b); +} + +// Storage for credentials and enroll tokens (Durable Object sql; the +// test MemoryStore mirrors these semantics). Hash-only throughout: no +// function here ever sees a token value, only its SHA-256 hex. + +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) + .toArray()[0]; + return r ? { agent: r.agent, scopes: JSON.parse(r.scopes) } : null; +} + +export function fleetCredentialPutSql(sql, { token_hash, agent, scopes, created }) { + sql.exec( + "INSERT INTO fleet_credential (token_hash, agent, scopes, created) VALUES (?, ?, ?, ?)", + token_hash, + agent, + JSON.stringify(scopes), + created, + ); + return { agent, scopes: [...scopes] }; +} + +/** Revokes every live credential of the agent; returns how many. */ +export function fleetCredentialRevokeSql(sql, agent, now) { + return sql + .exec( + "UPDATE fleet_credential SET revoked_at = ? WHERE agent = ? AND revoked_at IS NULL RETURNING token_hash", + now, + agent, + ) + .toArray().length; +} + +export function enrollTokenMintSql(sql, row) { + sql.exec( + `INSERT INTO enroll_token (token_hash, agent, kind, groups, notes_identity, expires_at, created) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + row.token_hash, + row.agent, + row.kind, + JSON.stringify(row.groups), + row.notes_identity, + row.expires_at, + row.created, + ); + return { + agent: row.agent, + kind: row.kind, + groups: [...row.groups], + notes_identity: row.notes_identity, + expires_at: row.expires_at, + created: row.created, + }; +} + +export function enrollTokenGetSql(sql, token_hash) { + const r = sql.exec("SELECT * FROM enroll_token WHERE token_hash = ?", token_hash).toArray()[0]; + return r + ? { + agent: r.agent, + kind: r.kind, + groups: JSON.parse(r.groups), + notes_identity: r.notes_identity, + expires_at: r.expires_at, + used_at: r.used_at, + revoked_at: r.revoked_at, + created: r.created, + } + : null; +} + +/** + * Burns a bootstrap token: one UPDATE that only lands when the token + * exists, names this agent, and is unused, unrevoked and unexpired — + * so a token can never be claimed twice. Returns the bound mint record. + */ +export function enrollTokenClaimSql(sql, token_hash, agent, now) { + const claimed = sql + .exec( + `UPDATE enroll_token SET used_at = ? + WHERE token_hash = ? AND agent = ? AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ? + RETURNING agent, kind, groups, notes_identity`, + now, + token_hash, + agent, + now, + ) + .toArray(); + if (!claimed.length) return null; + const r = claimed[0]; + return { agent: r.agent, kind: r.kind, groups: JSON.parse(r.groups), notes_identity: r.notes_identity }; +} + +/** Revokes an unused bootstrap token; false when it was used, revoked or unknown. */ +export function enrollTokenRevokeSql(sql, token_hash, now) { + return ( + sql + .exec( + "UPDATE enroll_token SET revoked_at = ? WHERE token_hash = ? AND used_at IS NULL AND revoked_at IS NULL RETURNING token_hash", + now, + token_hash, + ) + .toArray().length > 0 + ); +} + +/** Validates a bootstrap mint body; the token is bound to what this returns. */ +export function normalizeEnrollMint(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + const ttl = data.ttl_seconds === undefined || data.ttl_seconds === null ? ENROLL_DEFAULT_TTL_SECONDS : data.ttl_seconds; + if (!Number.isInteger(ttl) || ttl < ENROLL_MIN_TTL_SECONDS || ttl > ENROLL_MAX_TTL_SECONDS) { + throw new InputError(`ttl_seconds must be an integer between ${ENROLL_MIN_TTL_SECONDS} and ${ENROLL_MAX_TTL_SECONDS}`); + } + return { + agent: normalizeName(data.agent), + kind: + data.kind === undefined || data.kind === null || data.kind === "" ? "agent" : normalizeName(data.kind, "kind"), + groups: normalizeGroups(data.groups) ?? [], + notes_identity: + data.notes_identity === undefined || data.notes_identity === null || data.notes_identity === "" + ? null + : normalizeNoteIdentity(data.notes_identity), + ttl_seconds: ttl, + }; +} + +/** + * Mints a bootstrap token for the owner. The value exists only in this + * return value; the store receives its SHA-256 hash. + */ +export async function mintEnrollToken(store, data, nowMs = Date.now()) { + const m = normalizeEnrollMint(data); + const value = randomTokenValue(); + const created = new Date(nowMs).toISOString(); + const expires_at = new Date(nowMs + m.ttl_seconds * 1000).toISOString(); + await store.enrollTokenMint({ + token_hash: await noteTokenHash(value), + agent: m.agent, + kind: m.kind, + groups: m.groups, + notes_identity: m.notes_identity, + expires_at, + created, + }); + return { + agent: m.agent, + kind: m.kind, + groups: m.groups, + notes_identity: m.notes_identity, + expires_at, + bootstrap_token: value, + }; +} + +/** + * Exchanges a bootstrap token for the agent's working credentials. + * Every failure — wrong, used, expired or revoked token, or a name + * that isn't the name the token was minted for — returns null, and the + * route answers the plain 404 every wrong token gets on this Worker. + * On success the credential values are returned here, once; the store + * keeps only their hashes. The token is burned before any credential + * is minted, so a failure mid-exchange costs a re-mint, never a + * second use. + */ +export async function exchangeEnrollToken(store, data, now = new Date().toISOString()) { + if (!data || typeof data !== "object" || Array.isArray(data)) return null; + if (typeof data.bootstrap_token !== "string" || data.bootstrap_token.length < 32 || data.bootstrap_token.length > 512) { + return null; + } + let agent; + try { + agent = normalizeName(data.agent); + } catch { + return null; + } + const claimed = await store.enrollTokenClaim(await noteTokenHash(data.bootstrap_token), agent, now); + if (!claimed) return null; + const fleetValue = randomTokenValue(); + await store.fleetCredentialPut({ + token_hash: await noteTokenHash(fleetValue), + agent, + scopes: [...CREDENTIAL_SCOPES], + created: now, + }); + await store.fleet("hello", { agent, groups: claimed.groups }); + let notesToken = null; + if (claimed.notes_identity) { + notesToken = randomTokenValue(); + await store.noteRegister({ + identity: claimed.notes_identity, + token_hash: await noteTokenHash(notesToken), + can_send: true, + can_inbox: true, + }); + } + return { + agent, + kind: claimed.kind, + groups: claimed.groups, + notes_identity: claimed.notes_identity, + fleet_token: fleetValue, + notes_token: notesToken, + }; +} + +/** The hash a revoke call names: a bootstrap value to hash, or a stored hash itself. */ +async function enrollRevokeHash(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + if (typeof data.bootstrap_token === "string" && data.bootstrap_token.length >= 32 && data.bootstrap_token.length <= 512) { + return noteTokenHash(data.bootstrap_token); + } + if (typeof data.token_hash === "string" && /^[0-9a-f]{64}$/.test(data.token_hash)) return data.token_hash; + throw new InputError("give bootstrap_token or token_hash"); +} + // ---- HTTP ---- const json = (data, status = 200) => @@ -585,23 +867,52 @@ export function commandForAgent(m) { return { ...m, sender: null, from_addr: null }; } -async function agentRoute(request, store, what, url, delivered) { +/** The credential's own name when raw names it (normalized), else null. */ +function credOwnName(raw, cred) { + try { + return normalizeName(raw) === cred.agent ? cred.agent : null; + } catch { + return null; + } +} + +/** + * Agent routes. With the shared fleet token (cred null) any agent name + * may be named, as before. With a per-agent credential the request may + * act only as that agent, within its scopes; anything else is the + * plain 404 a wrong token gets, so a credential learns nothing about + * other agents' mailboxes. + */ +async function agentRoute(request, store, what, url, delivered, cred = null) { + const scoped = (scope) => !cred || cred.scopes.includes(scope); if (what === "hello") { if (request.method !== "POST") return notAllowed("POST"); - return json(await store.fleet("hello", await readJson(request))); + const d = await readJson(request); + if (cred && (!scoped("inbox") || credOwnName(d.agent, cred) === null)) return notFound(); + return json(await store.fleet("hello", d)); } if (what === "inbox") { if (request.method !== "GET") return notAllowed("GET"); + if (cred && (!scoped("inbox") || credOwnName(url.searchParams.get("agent"), cred) === null)) return notFound(); const out = await store.fleet("inbox", query(url)); return json({ ...out, messages: out.messages.map(commandForAgent) }); } if (what === "ack") { if (request.method !== "POST") return notAllowed("POST"); - return json(await store.fleet("ack", await readJson(request))); + const d = await readJson(request); + if (cred && (!scoped("inbox") || credOwnName(d.agent, cred) === null)) return notFound(); + return json(await store.fleet("ack", d)); } if (what === "send") { if (request.method !== "POST") return notAllowed("POST"); - return json(await agentSend(store, await readJson(request), delivered), 201); + 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; + } + return json(await agentSend(store, d, delivered), 201); } return notFound(); } @@ -626,26 +937,72 @@ async function ownerRoute(request, store, what, url, delivered) { } /** - * Handles /fleet// and /api//fleet/; - * returns null for any other path so the caller routes it as before. A - * wrong token is a plain 404, like everywhere else. + * Handles /fleet//, + * /api//fleet/, the owner's credential and enroll-token + * routes, and POST /enroll/exchange; returns null for any other path + * so the caller routes it as before. A wrong token — shared, credential + * or bootstrap — is a plain 404, like everywhere else. */ export async function handleFleet(request, env, url, getStore, deliveredFor = () => () => {}) { const parts = url.pathname.split("/").filter(Boolean); try { + if (parts[0] === "enroll") { + if (parts.length !== 2 || parts[1] !== "exchange") return notFound(); + if (request.method !== "POST") return notAllowed("POST"); + let data = null; + try { + data = await readJson(request); + } catch { + return notFound(); + } + const out = await exchangeEnrollToken(getStore(), data); + return out ? json(out, 201) : notFound(); + } if (parts[0] === "fleet") { if (parts.length !== 3) return notFound(); - const expected = await fleetToken(env); - if (!expected || !safeEqual(parts[1], expected)) return notFound(); const store = getStore(); - return await agentRoute(request, store, parts[2], url, deliveredFor(store)); + const expected = await fleetToken(env); + if (expected && safeEqual(parts[1], expected)) { + return await agentRoute(request, store, parts[2], url, deliveredFor(store)); + } + // A per-agent credential: looked up by hash, bound to one agent. + if (parts[1].length < MIN_TOKEN_LENGTH || parts[1].length > 512) return notFound(); + const cred = await store.fleetCredentialAuth(await noteTokenHash(parts[1])); + if (!cred) return notFound(); + return await agentRoute(request, store, parts[2], url, deliveredFor(store), cred); } - if (parts[0] === "api" && parts[2] === "fleet") { + if (parts[0] === "api") { const m = matchTokenPath(url.pathname, env); if (!m || m.role !== "owner") return null; // not ours: the caller 404s - if (parts.length !== 4) return notFound(); const store = getStore(); - return await ownerRoute(request, store, parts[3], url, deliveredFor(store)); + if (parts[2] === "fleet") { + if (parts.length === 4) return await ownerRoute(request, store, parts[3], url, deliveredFor(store)); + if (parts.length === 5 && parts[3] === "credentials" && parts[4] === "revoke") { + if (request.method !== "POST") return notAllowed("POST"); + const agent = normalizeName((await readJson(request)).agent); + return json({ agent, revoked: await store.fleetCredentialRevoke(agent) }); + } + return notFound(); + } + if (parts[2] === "enroll-tokens") { + if (parts.length === 3) { + if (request.method !== "POST") return notAllowed("POST"); + return json(await mintEnrollToken(store, await readJson(request)), 201); + } + if (parts.length === 4 && parts[3] === "revoke") { + if (request.method !== "POST") return notAllowed("POST"); + const hash = await enrollRevokeHash(await readJson(request)); + return json({ revoked: await store.enrollTokenRevoke(hash) }); + } + return notFound(); + } + if (parts[2] === "notes-tokens" && parts.length === 4 && parts[3] === "revoke") { + if (request.method !== "POST") return notAllowed("POST"); + const identity = normalizeNoteIdentity((await readJson(request)).identity); + return json({ identity, revoked: await store.noteRevoke(identity) }); + } + if (parts[2] === "enroll-tokens" || parts[2] === "notes-tokens") return notFound(); + return null; // another /api area: the caller routes it } } catch (err) { if (err instanceof InputError) return json({ error: err.message }, 400); diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index a5899d9a70..e9fc2f3870 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -9,7 +9,18 @@ // Worker secret ACCESS_TOKEN; it is never in git. import { DurableObject } from "cloudflare:workers"; import { OAUTH_CLIENT_IDLE, OAUTH_MAX_CLIENTS, OAUTH_MAX_EVENTS, OAUTH_PENDING_GRACE, OAUTH_REG_PER_SOURCE, ackSelector, normalizeChannel, normalizeNew, normalizeQuery } from "./messages.js"; -import { fleetCall, fleetOp, fleetSchema } from "./fleet.js"; +import { + enrollTokenClaimSql, + enrollTokenGetSql, + enrollTokenMintSql, + enrollTokenRevokeSql, + fleetCall, + fleetCredentialAuthSql, + fleetCredentialPutSql, + fleetCredentialRevokeSql, + fleetOp, + fleetSchema, +} from "./fleet.js"; import { route } from "./routes.js"; export class MessageStore extends DurableObject { @@ -108,6 +119,42 @@ export class MessageStore extends DurableObject { return fleetOp(this.sql, op, args); } + // Per-agent credentials and bootstrap enroll tokens (#14368): the + // store only ever sees SHA-256 hashes, never a token value. + + fleetCredentialAuth(token_hash) { + return fleetCredentialAuthSql(this.sql, token_hash); + } + + fleetCredentialPut(rec) { + return fleetCredentialPutSql(this.sql, rec); + } + + fleetCredentialRevoke(agent) { + return fleetCredentialRevokeSql(this.sql, agent, new Date().toISOString()); + } + + enrollTokenMint(row) { + return enrollTokenMintSql(this.sql, row); + } + + enrollTokenGet(token_hash) { + return enrollTokenGetSql(this.sql, token_hash); + } + + enrollTokenClaim(token_hash, agent, now) { + return enrollTokenClaimSql(this.sql, token_hash, agent, now); + } + + enrollTokenRevoke(token_hash) { + return enrollTokenRevokeSql(this.sql, token_hash, new Date().toISOString()); + } + + /** Deletes an identity's notes token(s); returns how many were revoked. */ + noteRevoke(identity) { + return this.sql.exec("DELETE FROM note_token WHERE identity = ? RETURNING token_hash", identity).toArray().length; + } + /** Stores a new client; false when the table is full of clients worth keeping. */ oauthClientAdd(id, meta) { const now = Math.floor(Date.now() / 1000); @@ -452,6 +499,7 @@ function storeFor(env) { wakeHooks: () => stub.wakeHooks(), wakeClaim: (address, now, max) => stub.wakeClaim(address, now, max), noteRegister: (reg) => stub.noteRegister(reg), + noteRevoke: (identity) => stub.noteRevoke(identity), noteAuth: (token_hash) => stub.noteAuth(token_hash), noteIdentities: () => stub.noteIdentities(), noteDeliver: (delivery) => stub.noteDeliver(delivery), @@ -459,6 +507,13 @@ function storeFor(env) { noteAck: (identity, sel) => stub.noteAck(identity, sel), noteSignal: (identity) => stub.noteSignal(identity), fleet: (op, args) => fleetCall(stub, op, args), + fleetCredentialAuth: (token_hash) => stub.fleetCredentialAuth(token_hash), + fleetCredentialPut: (rec) => stub.fleetCredentialPut(rec), + fleetCredentialRevoke: (agent) => stub.fleetCredentialRevoke(agent), + enrollTokenMint: (row) => stub.enrollTokenMint(row), + enrollTokenGet: (token_hash) => stub.enrollTokenGet(token_hash), + enrollTokenClaim: (token_hash, agent, now) => stub.enrollTokenClaim(token_hash, agent, now), + enrollTokenRevoke: (token_hash) => stub.enrollTokenRevoke(token_hash), }; } diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index 3d4e99c0cd..88f3263cea 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -185,6 +185,58 @@ export class MemoryStore { this.noteTokens = new Map(); this.noteRows = []; this.noteNextId = 1; + this.fleetCredentials = new Map(); + this.enrollTokens = new Map(); + } + // Per-agent fleet credentials + bootstrap enroll tokens (fleet.js, + // #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] }; + } + async fleetCredentialRevoke(agent) { + let n = 0; + for (const c of this.fleetCredentials.values()) { + if (c.agent === agent && !c.revoked_at) { + c.revoked_at = this.now(); + n++; + } + } + return n; + } + async enrollTokenMint(row) { + this.enrollTokens.set(row.token_hash, { ...row, groups: [...row.groups], used_at: null, revoked_at: null }); + return { agent: row.agent, kind: row.kind, groups: [...row.groups], notes_identity: row.notes_identity, expires_at: row.expires_at, created: row.created }; + } + async enrollTokenGet(token_hash) { + const r = this.enrollTokens.get(token_hash); + return r ? { ...r, groups: [...r.groups] } : null; + } + async enrollTokenClaim(token_hash, agent, now) { + const r = this.enrollTokens.get(token_hash); + if (!r || r.agent !== agent || r.used_at || r.revoked_at || !(r.expires_at > now)) return null; + r.used_at = now; + return { agent: r.agent, kind: r.kind, groups: [...r.groups], notes_identity: r.notes_identity }; + } + async enrollTokenRevoke(token_hash) { + const r = this.enrollTokens.get(token_hash); + if (!r || r.used_at || r.revoked_at) return false; + r.revoked_at = this.now(); + return true; + } + async noteRevoke(identity) { + let n = 0; + for (const [hash, t] of this.noteTokens) { + if (t.identity === identity) { + this.noteTokens.delete(hash); + n++; + } + } + return n; } // Class/name notes (notes.js), same semantics as the Durable Object. async noteRegister({ identity, token_hash, can_send, can_inbox }) { diff --git a/pkgs/message-bridge/worker/src/notes.js b/pkgs/message-bridge/worker/src/notes.js index cb3d4971aa..977595aaeb 100644 --- a/pkgs/message-bridge/worker/src/notes.js +++ b/pkgs/message-bridge/worker/src/notes.js @@ -24,6 +24,7 @@ const RESERVED_SIGNAL_CLASSES = new Set([ ".well-known", "api", "authorize", + "enroll", "fleet", "healthz", "mcp", diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 7020fca956..bd8f412f97 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -29,6 +29,23 @@ // never the token or path, wake.js) // POST /api//wake-hooks JSON {address, url, token?} sets one; // {address, url: null} removes it +// POST /fleet//hello|inbox|ack|send fleet mailboxes (fleet.js); +// the token is the shared fleet token +// or one agent's own credential +// (#14368), which acts only as itself +// POST /api//enroll-tokens owner: mint a bootstrap enroll +// token bound to a name/kind/groups; +// the value is returned once +// POST /api//enroll-tokens/revoke owner: revoke an unused +// bootstrap token +// POST /enroll/exchange {bootstrap_token, agent}: burn the +// token, register the mailbox (and +// notes identity), return the agent's +// fleet credential + notes token once +// POST /api//fleet/credentials/revoke owner: revoke an agent's +// fleet credential(s) +// POST /api//notes-tokens/revoke owner: revoke an identity's +// notes token(s) // POST /notes/register owner Bearer token; registers a // class/name identity + token hash // POST /notes/send identity Bearer token; {to, note}, diff --git a/pkgs/message-bridge/worker/test/credentials.test.mjs b/pkgs/message-bridge/worker/test/credentials.test.mjs new file mode 100644 index 0000000000..326f6b170d --- /dev/null +++ b/pkgs/message-bridge/worker/test/credentials.test.mjs @@ -0,0 +1,322 @@ +// Per-agent fleet credentials + bootstrap enroll tokens (src/fleet.js, +// #14368): routed end to end through route(). Fleet mailboxes run the +// real fleetOp SQL on node:sqlite (as in fleet.test.mjs); credentials, +// enroll tokens and notes run on MemoryStore, which mirrors the Durable +// Object's hash-only semantics. A second block drives the sql helpers +// directly to prove hash-only storage and the claim predicate. +// 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 { + enrollTokenClaimSql, + enrollTokenGetSql, + enrollTokenMintSql, + enrollTokenRevokeSql, + exchangeEnrollToken, + fleetCall, + fleetCredentialAuthSql, + fleetCredentialPutSql, + fleetCredentialRevokeSql, + fleetOp, + fleetSchema, + fleetToken, + mintEnrollToken, +} 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 DREW_NOTES = "d".repeat(40); // fixture notes token for user/drew +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 bearer = (token) => ({ authorization: `Bearer ${token}`, "content-type": "application/json" }); + const api = { + mint: (body) => post(`/api/${TOKEN}/enroll-tokens`, body), + revokeEnroll: (body) => post(`/api/${TOKEN}/enroll-tokens/revoke`, body), + revokeCred: (body) => post(`/api/${TOKEN}/fleet/credentials/revoke`, body), + revokeNotes: (body) => post(`/api/${TOKEN}/notes-tokens/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 exchange = (bootstrap_token, agent) => post(`/enroll/exchange`, { bootstrap_token, agent }); + const as = (cred) => ({ + hello: (body) => post(`/fleet/${cred}/hello`, body), + inbox: (qs) => call(`/fleet/${cred}/inbox?${new URLSearchParams(qs)}`), + ack: (body) => post(`/fleet/${cred}/ack`, body), + send: (body) => post(`/fleet/${cred}/send`, body), + }); + /** Mints and exchanges in one go; returns the exchange body. */ + const enroll = async (mintBody) => { + const mint = await api.mint(mintBody); + assert.equal(mint.status, 201, JSON.stringify(mintBody)); + const m = await mint.json(); + const ex = await exchange(m.bootstrap_token, mintBody.agent); + assert.equal(ex.status, 201, `exchange for ${mintBody.agent}`); + return { mint: m, creds: await ex.json() }; + }; + return { store, call, post, bearer, ft, api, exchange, as, enroll }; +} + +test("exchange: a bootstrap token provisions working fleet + notes credentials, once", async () => { + const h = await harness(); + + // Minting is owner-only: the fleet token and junk both 404. + assert.equal((await h.post(`/api/${h.ft}/enroll-tokens`, { agent: "felix-1" })).status, 404); + assert.equal((await h.post(`/api/nope/enroll-tokens`, { agent: "felix-1" })).status, 404); + + const mintRes = await h.api.mint({ agent: "Felix-1", kind: "muse", groups: ["muse"], notes_identity: "muse/felix-1" }); + assert.equal(mintRes.status, 201); + const mint = await mintRes.json(); + assert.match(mint.bootstrap_token, VALUE); + assert.equal(mint.agent, "felix-1", "names normalize at mint time"); + assert.deepEqual(mint.groups, ["muse"]); + assert.ok(mint.expires_at > new Date().toISOString()); + + // A name that isn't the minted name is refused — and does not burn the token. + assert.equal((await h.exchange(mint.bootstrap_token, "other-1")).status, 404); + assert.equal((await h.exchange("z".repeat(43), "felix-1")).status, 404, "unknown token"); + + const exRes = await h.exchange(mint.bootstrap_token, "felix-1"); + assert.equal(exRes.status, 201); + const creds = await exRes.json(); + assert.match(creds.fleet_token, VALUE); + assert.match(creds.notes_token, VALUE); + assert.notEqual(creds.fleet_token, creds.notes_token); + assert.equal(creds.kind, "muse"); + assert.deepEqual(creds.groups, ["muse"]); + + // Single use: the same bootstrap token never works twice. + assert.equal((await h.exchange(mint.bootstrap_token, "felix-1")).status, 404); + + // The exchange registered the mailbox with the bound groups. + const agents = (await (await h.api.agents()).json()).agents; + assert.deepEqual( + agents.map((a) => [a.name, a.groups]), + [["felix-1", ["muse"]]], + ); + + // The returned fleet credential works: hello, inbox, ack for its own name. + const cred = h.as(creds.fleet_token); + assert.equal((await cred.hello({ agent: "felix-1" })).status, 200); + await h.api.send({ body: "first task", to: "agent:felix-1", kind: "command" }); + const inbox = await (await cred.inbox({ agent: "felix-1" })).json(); + assert.equal(inbox.messages.length, 1); + assert.equal(inbox.messages[0].body, "first task"); + assert.equal(inbox.messages[0].sender, null, "commands stay sender-stripped"); + const ack = await cred.ack({ agent: "felix-1", ids: [inbox.messages[0].id] }); + assert.equal((await ack.json()).acked, 1); + + // The returned notes token opens that identity's inbox. + await h.call("/notes/register", { + method: "POST", + headers: h.bearer(TOKEN), + body: JSON.stringify({ identity: "user/drew", token: DREW_NOTES }), + }); + const noteSend = await h.call("/notes/send", { + method: "POST", + headers: h.bearer(DREW_NOTES), + body: JSON.stringify({ to: "muse/felix-1", note: "welcome aboard" }), + }); + assert.equal(noteSend.status, 201); + const notes = await (await h.call("/notes/inbox", { headers: h.bearer(creds.notes_token) })).json(); + assert.equal(notes.identity, "muse/felix-1"); + assert.deepEqual( + notes.notes.map((n) => n.note), + ["welcome aboard"], + ); + + // Without a notes identity at mint time, no notes token comes back. + const plain = await h.enroll({ agent: "plain-1" }); + assert.equal(plain.creds.notes_token, null); + assert.equal(plain.creds.notes_identity, null); +}); + +test("a credential acts only as its own agent, and cannot forge a sender", async () => { + const h = await harness(); + const a = await h.enroll({ agent: "felix-1", groups: ["muse"] }); + const b = await h.enroll({ agent: "other-1" }); + const credA = h.as(a.creds.fleet_token); + const credB = h.as(b.creds.fleet_token); + + await h.api.send({ body: "for other only", to: "agent:other-1" }); + + // Every route naming the other agent is a plain 404 for A's credential. + assert.equal((await credA.inbox({ agent: "other-1" })).status, 404); + assert.equal((await credA.hello({ agent: "other-1" })).status, 404); + assert.equal((await credA.ack({ agent: "other-1", ids: [1] })).status, 404); + assert.equal((await credA.send({ agent: "other-1", body: "spoof" })).status, 404); + // ...while B reads its own inbox fine, and A never saw the row. + assert.equal((await (await credB.inbox({ agent: "other-1" })).json()).messages.length, 1); + assert.equal((await (await credA.inbox({ agent: "felix-1" })).json()).messages.length, 0); + + // A sends to B claiming to be Drew: the row is stamped as A regardless. + const sent = await credA.send({ agent: "felix-1", body: "hello from a", to: "agent:other-1", sender: "drew" }); + assert.equal(sent.status, 201); + const rows = (await (await h.api.messages({ agent: "other-1", direction: "inbound" })).json()).messages; + const fromA = rows.find((m) => m.body === "hello from a"); + assert.equal(fromA.from_addr, "agent:felix-1"); + assert.equal(fromA.sender, "felix-1"); + + // A credential opens no owner route. + assert.equal((await h.call(`/api/${a.creds.fleet_token}/fleet/agents`)).status, 404); + assert.equal((await h.post(`/api/${a.creds.fleet_token}/enroll-tokens`, { agent: "x-1" })).status, 404); +}); + +test("scopes gate a credential's routes", async () => { + const h = await harness(); + await h.enroll({ agent: "scoped-1" }); + const inboxOnly = `fixture-inbox-only-${"i".repeat(24)}`; + const sendOnly = `fixture-send-only-${"s".repeat(26)}`; + await h.store.fleetCredentialPut({ + token_hash: await noteTokenHash(inboxOnly), + agent: "scoped-1", + scopes: ["inbox"], + created: new Date().toISOString(), + }); + await h.store.fleetCredentialPut({ + token_hash: await noteTokenHash(sendOnly), + agent: "scoped-1", + scopes: ["send"], + created: new Date().toISOString(), + }); + assert.equal((await h.as(inboxOnly).inbox({ agent: "scoped-1" })).status, 200); + assert.equal((await h.as(inboxOnly).send({ agent: "scoped-1", body: "x" })).status, 404, "no send scope"); + assert.equal((await h.as(sendOnly).inbox({ agent: "scoped-1" })).status, 404, "no inbox scope"); + assert.equal((await h.as(sendOnly).hello({ agent: "scoped-1" })).status, 404, "hello rides the inbox scope"); + assert.equal((await h.as(sendOnly).send({ agent: "scoped-1", body: "report" })).status, 201); +}); + +test("revoking a credential or notes token stops it at once; the shared token is unaffected", async () => { + const h = await harness(); + const a = await h.enroll({ agent: "felix-1", notes_identity: "muse/felix-1" }); + const b = await h.enroll({ agent: "other-1" }); + const credA = h.as(a.creds.fleet_token); + assert.equal((await credA.hello({ agent: "felix-1" })).status, 200); + + const rev = await h.api.revokeCred({ agent: "felix-1" }); + assert.deepEqual(await rev.json(), { agent: "felix-1", revoked: 1 }); + assert.equal((await credA.hello({ agent: "felix-1" })).status, 404); + assert.equal((await credA.inbox({ agent: "felix-1" })).status, 404); + assert.equal((await credA.send({ agent: "felix-1", body: "x" })).status, 404); + assert.deepEqual(await (await h.api.revokeCred({ agent: "felix-1" })).json(), { agent: "felix-1", revoked: 0 }); + + // Other agents and the shared fleet token keep working. + assert.equal((await h.as(b.creds.fleet_token).hello({ agent: "other-1" })).status, 200); + assert.equal((await h.as(h.ft).inbox({ agent: "felix-1" })).status, 200, "shared token still reads any mailbox"); + + // Notes token revocation is by identity and just as immediate. + assert.equal((await h.call("/notes/inbox", { headers: h.bearer(a.creds.notes_token) })).status, 200); + const rn = await h.api.revokeNotes({ identity: "muse/felix-1" }); + assert.deepEqual(await rn.json(), { identity: "muse/felix-1", revoked: 1 }); + assert.equal((await h.call("/notes/inbox", { headers: h.bearer(a.creds.notes_token) })).status, 404); +}); + +test("bootstrap tokens expire and can be revoked while unused", async () => { + const h = await harness(); + + // Expiry: backdate the stored row (hash-keyed) past its deadline. + const m1 = await (await h.api.mint({ agent: "late-1", ttl_seconds: 60 })).json(); + const hash1 = await noteTokenHash(m1.bootstrap_token); + h.store.enrollTokens.get(hash1).expires_at = "2000-01-01T00:00:00.000Z"; + assert.equal((await h.exchange(m1.bootstrap_token, "late-1")).status, 404); + + // Revocation by value, then by hash; a used token can't be revoked. + const m2 = await (await h.api.mint({ agent: "rev-1" })).json(); + assert.deepEqual(await (await h.api.revokeEnroll({ bootstrap_token: m2.bootstrap_token })).json(), { revoked: true }); + assert.equal((await h.exchange(m2.bootstrap_token, "rev-1")).status, 404); + assert.deepEqual(await (await h.api.revokeEnroll({ bootstrap_token: m2.bootstrap_token })).json(), { revoked: false }); + + const m3 = await (await h.api.mint({ agent: "rev-2" })).json(); + const hash3 = await noteTokenHash(m3.bootstrap_token); + assert.deepEqual(await (await h.api.revokeEnroll({ token_hash: hash3 })).json(), { revoked: true }); + + const used = await h.enroll({ agent: "used-1" }); + assert.deepEqual(await (await h.api.revokeEnroll({ bootstrap_token: used.mint.bootstrap_token })).json(), { + revoked: false, + }); + + // Mint input is checked. + assert.equal((await h.api.mint({ agent: "bad name" })).status, 400); + assert.equal((await h.api.mint({ agent: "ok-1", ttl_seconds: 10 })).status, 400); + assert.equal((await h.api.mint({ agent: "ok-1", notes_identity: "not-an-identity" })).status, 400); +}); + +test("sql store: hash-only storage and the claim predicate", async () => { + const sql = sqlite(); + fleetSchema(sql); + fleetSchema(sql); // idempotent + const noteRegs = []; + const store = { + enrollTokenMint: (row) => enrollTokenMintSql(sql, row), + enrollTokenGet: (hash) => enrollTokenGetSql(sql, hash), + enrollTokenClaim: (hash, agent, now) => enrollTokenClaimSql(sql, hash, agent, now), + enrollTokenRevoke: (hash) => enrollTokenRevokeSql(sql, hash, new Date().toISOString()), + fleetCredentialPut: (rec) => fleetCredentialPutSql(sql, rec), + fleetCredentialAuth: (hash) => fleetCredentialAuthSql(sql, hash), + fleetCredentialRevoke: (agent) => fleetCredentialRevokeSql(sql, agent, new Date().toISOString()), + fleet: (op, args) => fleetOp(sql, op, args), + noteRegister: (reg) => noteRegs.push(reg), + }; + + const mint = await mintEnrollToken(store, { agent: "sql-1", kind: "muse", groups: ["muse"], notes_identity: "muse/sql-1" }); + const row = enrollTokenGetSql(sql, await noteTokenHash(mint.bootstrap_token)); + assert.equal(row.agent, "sql-1"); + assert.equal(row.used_at, null); + + // Wrong name cannot claim, and the failed claim leaves the token usable. + assert.equal(await exchangeEnrollToken(store, { bootstrap_token: mint.bootstrap_token, agent: "sql-2" }), null); + const out = await exchangeEnrollToken(store, { bootstrap_token: mint.bootstrap_token, agent: "sql-1" }); + assert.ok(out); + assert.equal(await exchangeEnrollToken(store, { bootstrap_token: mint.bootstrap_token, agent: "sql-1" }), null, "single use"); + assert.equal(enrollTokenRevokeSql(sql, await noteTokenHash(mint.bootstrap_token), new Date().toISOString()), false, "used tokens can't be revoked"); + + // Hash-only: no stored row, in either table, contains any token value, + // and the stored hashes are exactly the SHA-256 of the values. + const credRows = sql.exec("SELECT * FROM fleet_credential").toArray(); + assert.equal(credRows.length, 1); + assert.equal(credRows[0].token_hash, await noteTokenHash(out.fleet_token)); + assert.deepEqual(JSON.parse(credRows[0].scopes), ["inbox", "send"]); + const dump = JSON.stringify([credRows, sql.exec("SELECT * FROM enroll_token").toArray(), noteRegs]); + for (const value of [mint.bootstrap_token, out.fleet_token, out.notes_token]) { + assert.ok(!dump.includes(value), "a token value must never reach the store"); + } + 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.equal(fleetCredentialRevokeSql(sql, "sql-1", new Date().toISOString()), 1); + assert.equal(fleetCredentialAuthSql(sql, await noteTokenHash(out.fleet_token)), null); + + // Expired tokens cannot be claimed. + const stale = await mintEnrollToken(store, { agent: "sql-9", ttl_seconds: 60 }, Date.now() - 120_000); + assert.equal(await exchangeEnrollToken(store, { bootstrap_token: stale.bootstrap_token, agent: "sql-9" }), null); +});