diff --git a/docs/contract.md b/docs/contract.md index 66e597f..7635c0a 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -129,6 +129,25 @@ A DM is a write to the recipient's **inbox**, a stream owned by the recipient. Whether A may DM B is therefore decided by B's inbox mode, and whether B may answer is decided by A's inbox mode. +An inbox id, `relaycast:inbox/`, resolves like any stream: an operator +override for the exact id, then a registered stream, then the longest matching +prefix default. When none of those places it and an agent with that name is +registered, the inbox follows that agent: it is owned by the agent, takes the +agent's group, and gets the mode, ACL and classify flag of the policy's +`inboxDefaults` entry for that group, or `660` with no ACL when the group has +no entry (so its own group may message it and no one else). A name no agent +has is still refused as an unknown stream, and so is a relay-control user's +`ctl:` identity (it holds no token to read an inbox with). Audit reasons for such an inbox end +in `:agent-inbox`. + +``` +"inboxDefaults": [{"gid": 11, "mode": "660", "acl": [{"gid": 22, "perm": "r"}]}] +``` + +`inboxDefaults` names each group at most once. A derived inbox counts for +messaging and reading, not for the agent directory below: it doesn't by itself +show the agent to anyone. + ### The agent directory Who appears in `GET /v1/agents` (and `GET /v1/agents/:name`) is, by default, @@ -240,8 +259,14 @@ names. Stream ids for inboxes carry the agent's name, so the prefix defaults only place an inbox in the right group if names do. In this deployment each enrollment key has its own name prefix (`local-`, `pit-`, `slack-`, `guest-`) -and inbox defaults are per prefix, with no catch-all: an inbox that matches no -prefix is refused rather than defaulting into the wrong group. +and inbox defaults are per prefix. Agents a person's desktop enrols (through +`controlPrincipals`) are named by their harness (`cursor-…`, `claude-…`), so no +prefix covers them; their inboxes follow the registered agent instead (see +"Resources" above): its own group, with `inboxDefaults` for gid 11 mirroring the +`local-` rule. There is still no catch-all: an inbox whose name no prefix +covers and no registered agent has is refused rather than defaulting into the +wrong group, and a gid-22 agent never gets `w` on a gid-11 inbox unless the +policy grants it. The `slack:` and `kb:` rows are prefix defaults this deployment configures. relaygate itself has no notion of Slack or knowledge bases. diff --git a/examples/policy.pit.json b/examples/policy.pit.json index 3cc9b19..601d46d 100644 --- a/examples/policy.pit.json +++ b/examples/policy.pit.json @@ -22,6 +22,9 @@ {"prefix": "kb:", "gid": 22, "mode": "660", "classify": true} ], "streamOverrides": [], + "inboxDefaults": [ + {"gid": 11, "mode": "660", "acl": [{"gid": 22, "perm": "r"}]} + ], "sessionDefaults": [ {"gid": 11, "mode": "660", "acl": [{"gid": 22, "perm": "r"}]}, {"gid": 22, "mode": "660"} diff --git a/src/app.ts b/src/app.ts index 2a4e038..c2fa1a8 100644 --- a/src/app.ts +++ b/src/app.ts @@ -120,20 +120,48 @@ export interface ResolvedStream extends Guarded { id: string; classify: boolean; acl: AclEntry[]; - source: "override" | "registered" | "prefix"; + source: "override" | "registered" | "prefix" | "agent-inbox"; } -/** Operator override, then the registered stream, then the longest matching prefix default. */ -export function resolveStream(id: string, store: Pick | undefined, policy: Policy): ResolvedStream | undefined { +const INBOX_PREFIX = "relaycast:inbox/"; + +/** + * Operator override, then the registered stream, then the longest matching prefix default, then (for + * `relaycast:inbox/` only, unless `agentInboxes` is false) the inbox of the registered agent with that name. + */ +export function resolveStream( + id: string, + store: (Pick & Partial>) | undefined, + policy: Policy, + opts: { agentInboxes?: boolean } = {}, +): ResolvedStream | undefined { const override = policy.streamOverrides.find((o) => o.id === id); if (override) return { id, owner: null, gid: override.gid, mode: override.mode, classify: override.classify, acl: override.acl, source: "override" }; const row = store?.stream(id); if (row) return { id, owner: row.owner, gid: row.gid, mode: row.mode, classify: row.classify, acl: row.acl, source: "registered" }; const prefix = longestPrefix(id, policy); if (prefix) return { id, owner: null, gid: prefix.gid, mode: prefix.mode, classify: prefix.classify, acl: prefix.acl, source: "prefix" }; + if (opts.agentInboxes !== false) return agentInbox(id, store, policy); return undefined; } +/** + * The inbox of a registered agent that no operator rule places: owned by the agent, in the agent's group, with that + * group's `inboxDefaults` entry (or `660` and no ACL). A name no agent has, and a relay-control user's synthetic + * `ctl:` identity, stay unknown. + */ +export function agentInbox(id: string, store: Partial> | undefined, policy: Policy): ResolvedStream | undefined { + if (!id.startsWith(INBOX_PREFIX)) return undefined; + const name = id.slice(INBOX_PREFIX.length); + // Only agents that hold a relaygate token can read an inbox: a relay-control user's synthetic `ctl:` identity + // (keyId `control`, which owns that user's sessions) has none, so it is never a DM recipient through this rule. + if (name.toLowerCase().startsWith("ctl:")) return undefined; + const agent = store?.agentByName?.(name); + if (!agent || agent.keyId === "control") return undefined; + const def = policy.inboxDefaults.find((d) => d.gid === agent.gid); + return { id, owner: agent.id, gid: agent.gid, mode: def?.mode ?? "660", classify: def?.classify ?? false, acl: def?.acl ?? [], source: "agent-inbox" }; +} + export function longestPrefix(id: string, policy: Policy) { return policy.streamDefaults .filter((d) => id.startsWith(d.prefix)) diff --git a/src/explain.ts b/src/explain.ts index c4e77a7..078c4f2 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -166,7 +166,7 @@ export function explain(policy: Policy, store: Pick`) of a registered agent whose name matches no stream override + * or prefix default, by the agent's group. Such an inbox is owned by the agent and takes its group; a group without + * an entry gets `660` and no ACL (its own group may message it, no one else). + */ + inboxDefaults: z.array(z.object({ gid: Gid, mode: Mode, classify: z.boolean().default(false), acl: AclSchema })).default([]), /** * Per-session changes, e.g. sharing one session with a guest: `{"id": "...", "acl": [{"gid": , "perm": "r"}]}`. * An override can't move a session to another group: its owning group is what ceilings are checked against. @@ -182,6 +188,7 @@ export function parsePolicy(raw: unknown): Policy { x.acl.map((e) => ({ where: `${x.where} acl`, gid: e.gid })), ), ...policy.sessionDefaults.flatMap((d) => [d.gid, ...d.acl.map((e) => e.gid)].map((gid) => ({ where: `session default for ${d.gid}`, gid }))), + ...policy.inboxDefaults.flatMap((d) => [d.gid, ...d.acl.map((e) => e.gid)].map((gid) => ({ where: `inbox default for ${d.gid}`, gid }))), ...policy.sessionOverrides.flatMap((o) => o.acl.map((e) => ({ where: `session override ${o.id}`, gid: e.gid })), ), @@ -193,6 +200,9 @@ export function parsePolicy(raw: unknown): Policy { if (unknown.length > 0) { throw new Error(`policy names groups it doesn't define: ${unknown.map((u) => `${u.where} (gid ${u.gid})`).join(", ")}`); } + const inboxGids = policy.inboxDefaults.map((d) => d.gid); + const twice = inboxGids.find((gid, i) => inboxGids.indexOf(gid) !== i); + if (twice !== undefined) throw new Error(`inboxDefaults has more than one entry for gid ${twice}`); // `device:`, `launch:` and `control` mark agents relaygate enrols from relay-control identities; no policy key may use them. for (const k of policy.enrollmentKeys) { if (k.id === "control" || k.id.startsWith("device:") || k.id.startsWith("launch:")) { diff --git a/src/relaycast.ts b/src/relaycast.ts index ce70a90..0d80faa 100644 --- a/src/relaycast.ts +++ b/src/relaycast.ts @@ -351,7 +351,9 @@ export function mountRelaycast(app: Hono, deps: Deps, upstream: RelaycastUp // Visibility only: `r` on the agent's directory entry shows it, and grants nothing else. const entry = directoryEntry(name, deps.policy()); if (entry && check(principal, entry, "r", ceilings).allowed) return true; - const stream = resolveStream(inboxStream(name), store, deps.policy()); + // Operator rules only: an inbox placed by its registered agent (no prefix default) lets that agent be messaged, + // but doesn't by itself show it in the directory. + const stream = resolveStream(inboxStream(name), store, deps.policy(), { agentInboxes: false }); if (!stream) return false; return check(principal, stream, "w", ceilings).allowed || check(principal, stream, "r", ceilings).allowed; }; diff --git a/test/agent-inbox.test.ts b/test/agent-inbox.test.ts new file mode 100644 index 0000000..0558ddc --- /dev/null +++ b/test/agent-inbox.test.ts @@ -0,0 +1,186 @@ +import { Hono } from "hono"; +import { describe, expect, it } from "vitest"; +import { createApp, resolveStream } from "../src/app.js"; +import { RuleClassifier } from "../src/classifier.js"; +import { ControlAuth } from "../src/control.js"; +import { explain } from "../src/explain.js"; +import { parsePolicy } from "../src/policy.js"; +import { RelaycastUpstream } from "../src/relaycast.js"; +import { SecretBox, sha256, Store } from "../src/store.js"; +import { fakeRelaycast, WORKSPACE_KEY } from "./fakes/relaycast.js"; + +// Desktop agents enrol with a person's device token and are named by their harness (cursor-, claude-, codex-), so no +// streamDefaults prefix covers their inboxes: the inbox follows the registered agent that owns the name. + +const SECRET = "introspect-secret"; +const PIT_KEY = "enroll-pit-00000000000000000000"; +const DEVICES: Record> = { + sh_at_one: { active: true, principal_type: "desktop-user", sub: "u-one", org: "org-1", workspace: "ws-1", role: "member", scopes: ["cli:auth"], exp: 4_102_444_800 }, + sh_at_two: { active: true, principal_type: "desktop-user", sub: "u-two", org: "org-1", workspace: "ws-1", role: "member", scopes: ["cli:auth"], exp: 4_102_444_800 }, +}; + +function rawPolicy(extra: Record = {}) { + return { + groups: [ + { gid: 11, name: "local" }, + { gid: 22, name: "pit" }, + { gid: 44, name: "guest" }, + ], + enrollmentKeys: [{ id: "pit", gid: 22, sha256: sha256(PIT_KEY), namePrefix: "pit-" }], + controlPrincipals: [{ match: { orgIds: ["org-1"] }, gid: 11 }], + streamDefaults: [ + { prefix: "relaycast:inbox/local-", gid: 11, mode: "660", acl: [{ gid: 22, perm: "r" }, { gid: 44, perm: "r" }] }, + { prefix: "relaycast:inbox/pit-", gid: 22, mode: "660" }, + ], + ...extra, + }; +} + +function harness(extra: Record = {}) { + const pol = parsePolicy(rawPolicy(extra)); + const control = new Hono(); + control.post("/introspect", async (c) => c.json(DEVICES[(await c.req.json()).token] ?? { active: false })); + const store = new Store(":memory:"); + const up = fakeRelaycast(); + const relaycast = new RelaycastUpstream({ url: "http://relaycast.test", workspaceKey: WORKSPACE_KEY, box: new SecretBox("s".repeat(32)), fetch: up.fetchFn }, store); + const controlAuth = new ControlAuth( + { introspectUrl: "http://control.test/introspect", introspectSecret: SECRET, audience: "https://history.example.test", fetch: (async (i: RequestInfo | URL, init?: RequestInit) => control.fetch(new Request(i, init))) as typeof fetch }, + store, + ); + const app = createApp({ store, policy: () => pol, classifier: () => new RuleClassifier([]), relaycast, control: controlAuth }); + const call = async (method: string, path: string, token: string, body?: unknown) => { + const res = await app.request(path, { + method, + headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + return { status: res.status, body: (await res.json()) as Record }; + }; + const enrol = async (credential: string, name: string) => { + const r = await call("POST", "/v1/register", credential, { name, recovery: "recovery-proof-0123456789" }); + expect(r.status).toBe(200); + return String(r.body.token); + }; + const dm = (token: string, to: string) => call("POST", "/v1/dm", token, { to, text: "hi" }); + /** POST /v1/check, with the audited reason (the response carries only the decision). */ + const check = async (token: string, op: "r" | "w", id: string) => { + const r = await call("POST", "/v1/check", token, { op, resource: { kind: "stream", id }, ...(op === "w" ? { content: "hi" } : {}) }); + const row = store.recentAudit(1)[0]; + return { status: r.status, decision: row?.decision, reason: row?.reason }; + }; + return { pol, store, call, enrol, dm, check }; +} + +describe("an unplaced inbox follows its registered agent", () => { + it("two device-enrolled local agents named cursor-x and claude-y can DM each other and read their own inboxes", async () => { + const h = harness(); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + const claude = await h.enrol("sh_at_two", "claude-y"); + expect(h.store.agentByName("cursor-x")!.keyId).toBe("device:u-one"); + expect((await h.dm(cursor, "claude-y")).status).toBe(201); + expect((await h.dm(claude, "cursor-x")).status).toBe(201); + // An agent's own inbox: the owner digit applies. + expect((await h.call("GET", "/v1/dm/conversations", claude)).body.data.length).toBe(1); + expect(await h.check(cursor, "w", "relaycast:inbox/claude-y")).toEqual({ status: 200, decision: "allow", reason: "mode:660:agent-inbox" }); + }); + + it("a pit agent (gid 22) can't DM them, and they can't DM the pit without a rule saying so", async () => { + const h = harness(); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + const pit = await h.enrol(PIT_KEY, "pit-a"); + expect((await h.dm(pit, "cursor-x")).status).toBe(403); + expect((await h.dm(cursor, "pit-a")).status).toBe(403); + // Even with inboxDefaults mirroring local- (22 may read), the pit never gets w on a gid-11 inbox. + const m = harness({ inboxDefaults: [{ gid: 11, mode: "660", acl: [{ gid: 22, perm: "r" }, { gid: 44, perm: "r" }] }] }); + await m.enrol("sh_at_one", "cursor-x"); + const pit2 = await m.enrol(PIT_KEY, "pit-a"); + expect((await m.dm(pit2, "cursor-x")).status).toBe(403); + expect(await m.check(pit2, "w", "relaycast:inbox/cursor-x")).toEqual({ status: 403, decision: "deny", reason: "mode:660+acl:22:r:agent-inbox" }); + expect(await m.check(pit2, "r", "relaycast:inbox/cursor-x")).toEqual({ status: 200, decision: "allow", reason: "mode:660+acl:22:r:agent-inbox" }); + }); + + it("inboxDefaults sets mode, ACL and classify by the agent's group", () => { + const pol = parsePolicy(rawPolicy({ inboxDefaults: [{ gid: 11, mode: "640", classify: true, acl: [{ gid: 22, perm: "w" }] }] })); + const store = new Store(":memory:"); + const a = store.createAgent("codex-z", 11, "device:u-one", undefined); + expect(resolveStream("relaycast:inbox/codex-z", store, pol)).toEqual({ + id: "relaycast:inbox/codex-z", + owner: a.id, + gid: 11, + mode: "640", + classify: true, + acl: [{ gid: 22, perm: "w" }], + source: "agent-inbox", + }); + }); + + it("explicit streamDefaults and overrides still win", async () => { + const h = harness({ + streamDefaults: [ + ...rawPolicy().streamDefaults, + { prefix: "relaycast:inbox/claude-", gid: 22, mode: "660" }, + ], + streamOverrides: [{ id: "relaycast:inbox/cursor-x", gid: 11, mode: "600" }], + inboxDefaults: [{ gid: 11, mode: "666" }], + }); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + const claude = await h.enrol("sh_at_two", "claude-y"); + // claude- is a pit prefix here: the local agent can't write it, whatever its own group. + expect((await h.dm(cursor, "claude-y")).status).toBe(403); + // cursor-x has an override with no group write. + expect((await h.dm(claude, "cursor-x")).status).toBe(403); + expect(resolveStream("relaycast:inbox/cursor-x", h.store, h.pol)?.source).toBe("override"); + expect(resolveStream("relaycast:inbox/claude-y", h.store, h.pol)?.source).toBe("prefix"); + }); + + it("a name no agent has stays unknown_stream, and only inbox ids are derived", async () => { + const h = harness(); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + expect(await h.check(cursor, "w", "relaycast:inbox/claude-nobody")).toEqual({ status: 403, decision: "deny", reason: "unknown_stream" }); + expect((await h.dm(cursor, "claude-nobody")).status).toBe(403); + expect(resolveStream("relaycast:channel/cursor-x", h.store, h.pol)).toBeUndefined(); + expect(resolveStream("relaycast:agent/cursor-x", h.store, h.pol)).toBeUndefined(); + }); + + it("a relay-control user's synthetic ctl: identity is never a DM recipient through this rule", async () => { + const h = harness(); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + // What a Sessions upload by a Control-only user creates: an agent row with no token, in the user's group. + const ctl = h.store.ensureControlAgent("u-two", 11); + expect(ctl).toMatchObject({ name: "ctl:u-two", keyId: "control", gid: 11 }); + expect(resolveStream("relaycast:inbox/ctl:u-two", h.store, h.pol)).toBeUndefined(); + expect(await h.check(cursor, "w", "relaycast:inbox/ctl:u-two")).toEqual({ status: 403, decision: "deny", reason: "unknown_stream" }); + expect((await h.dm(cursor, "ctl:u-two")).status).toBe(403); + expect(h.store.upstreamAgent(ctl.id)).toBeUndefined(); + }); + + it("directory visibility is unchanged: a derived inbox doesn't show the agent", async () => { + const h = harness(); + const cursor = await h.enrol("sh_at_one", "cursor-x"); + await h.enrol("sh_at_two", "claude-y"); + const pit = await h.enrol(PIT_KEY, "pit-a"); + const names = async (t: string) => (await h.call("GET", "/v1/agents", t)).body.data.map((a: any) => a.name).sort(); + expect(await names(cursor)).toEqual(["cursor-x"]); + expect(await names(pit)).toEqual(["pit-a"]); + expect((await h.call("GET", "/v1/agents/claude-y", cursor)).status).toBe(404); + }); + + it("explain reports the derived inbox", () => { + const pol = parsePolicy(rawPolicy()); + const store = new Store(":memory:"); + store.createAgent("cursor-x", 11, "device:u-one", undefined); + store.createAgent("claude-y", 11, "device:u-two", undefined); + const e = explain(pol, store, { as: { agent: "cursor-x" }, op: "w", resource: { kind: "stream", id: "relaycast:inbox/claude-y" } }); + expect(e).toMatchObject({ decision: "allow", reason: "mode:660:agent-inbox" }); + }); +}); + +describe("policy: inboxDefaults", () => { + it("must name defined groups, once each", () => { + expect(() => parsePolicy(rawPolicy({ inboxDefaults: [{ gid: 99, mode: "660" }] }))).toThrow(/inbox default for 99/); + expect(() => parsePolicy(rawPolicy({ inboxDefaults: [{ gid: 11, mode: "660", acl: [{ gid: 99, perm: "r" }] }] }))).toThrow(/inbox default for 11 \(gid 99\)/); + expect(() => parsePolicy(rawPolicy({ inboxDefaults: [{ gid: 11, mode: "660" }, { gid: 11, mode: "600" }] }))).toThrow(/more than one entry for gid 11/); + expect(() => parsePolicy(rawPolicy({ inboxDefaults: [{ gid: 11, mode: "661" }] }))).toThrow(); + expect(parsePolicy(rawPolicy()).inboxDefaults).toEqual([]); + }); +});