diff --git a/docs/contract.md b/docs/contract.md index 8d9c58c..66e597f 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -607,6 +607,30 @@ recipient knows who is asking and with what scope: relaygate removes any `relaygate` field the client sent, so it can't be forged. `GET /v1/whoami` returns the same card for the caller. +### Who am I + +``` +GET /v1/whoami +Authorization: Bearer rg_... + +200 {"agent_id": "ag_...", "name": "", "gid": 11, "groups": [], + "group_names": ["local"], "guest": false, + "user_id": "", + "relaygate": {"agent": "", "groups": ["local"]}} +``` + +It answers only for the caller's own token. `user_id` is present only for an +agent enrolled with a relay-control credential: for a device-enrolled agent +("Enrolling with a device token") the user the device token introspected as, +for a launched agent ("Launched agents") the launching person (the launch +credential's `sub`). It is the same `user_id` `POST /v1/register` returned, +recorded with the agent when it registered (so it survives a restart and +needs no introspection), and it doesn't change on re-registration or token +refresh, since only the same person gets the name back. An agent enrolled +with an enrollment key has no Control principal and no `user_id`. `guest: +true` appears on the `relaygate` card only for guests; `user_id` never does, +so it isn't stamped on what the agent sends. + ## Reads and lists A list or search returns only resources the caller may read. relaygate applies diff --git a/src/app.ts b/src/app.ts index 72cea72..2a4e038 100644 --- a/src/app.ts +++ b/src/app.ts @@ -95,6 +95,18 @@ export function sweepGuestKeys(store: Store, policy: Policy, now: number): strin }); } +/** + * The relay-control user behind a device- or launch-enrolled agent: the introspected `sub` its credential carried at + * registration, persisted as the agent's key id (`device:` / `launch:`, ids no policy key may use). + * Undefined for an agent enrolled with a key (or anything else): it has no Control principal. + */ +export function controlUserId(agent: Agent): string | undefined { + for (const prefix of ["device:", "launch:"]) { + if (agent.keyId.startsWith(prefix)) return agent.keyId.slice(prefix.length) || undefined; + } + return undefined; +} + /** The sender card stamped on everything relaygate forwards and returned by /v1/whoami. */ export function provenance(agent: Agent, principal: Principal, policy: Policy) { return { @@ -628,6 +640,8 @@ export function createApp(deps: Deps) { const policy = deps.policy(); const p = c.get("principal"); const agent = c.get("agent"); + // Self only: the caller's own Control user, never stamped on what it sends (the provenance card stays as it was). + const userId = controlUserId(agent); return c.json({ agent_id: p.agentId, name: agent.name, @@ -635,6 +649,7 @@ export function createApp(deps: Deps) { groups: p.groups, group_names: allGroups(p).map((g) => groupName(policy, g)), guest: isGuest(agent, policy), + ...(userId !== undefined ? { user_id: userId } : {}), relaygate: provenance(agent, p, policy), }); }); diff --git a/test/control.test.ts b/test/control.test.ts index 90e9142..fda0860 100644 --- a/test/control.test.ts +++ b/test/control.test.ts @@ -1,4 +1,7 @@ import { Hono } from "hono"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createApp } from "../src/app.js"; import { RuleClassifier } from "../src/classifier.js"; @@ -47,7 +50,7 @@ function policy() { }); } -function harness(opts: { controlDown?: boolean; internalSecret?: string; garbled?: boolean; ceilingOnAdmins?: boolean; policy?: ReturnType } = {}) { +function harness(opts: { controlDown?: boolean; internalSecret?: string; garbled?: boolean; ceilingOnAdmins?: boolean; policy?: ReturnType; store?: Store } = {}) { const introspections: Array> = []; const control = new Hono(); control.post("/internal/v1/auth/introspect", async (c) => { @@ -79,7 +82,7 @@ function harness(opts: { controlDown?: boolean; internalSecret?: string; garbled sessions.on("OPTIONS", "*", (c) => c.body(null, 204, { "access-control-allow-origin": "https://app.example.test", "access-control-allow-headers": "authorization" })); const toFetch = (app: Hono) => (async (input: RequestInfo | URL, init?: RequestInit) => app.fetch(new Request(input, init))) as typeof fetch; - const store = new Store(":memory:"); + const store = opts.store ?? new Store(":memory:"); const pol = opts.policy ? opts.policy : opts.ceilingOnAdmins ? parsePolicy({ ...policy(), ceilings: [{ gid: 33, never: [22] }] }) : policy(); const controlAuth = new ControlAuth({ introspectUrl: "http://control.test/internal/v1/auth/introspect", introspectSecret: SECRET, audience: AUD, fetch: toFetch(control) }, store); const app = createApp({ @@ -523,6 +526,63 @@ describe("SESSIONS_PORT: Sessions at the root of an internal listener", () => { }); }); +describe("GET /v1/whoami: the Control user behind the caller", () => { + it("a device-enrolled agent's whoami carries the device token's user", async () => { + const h = harness(); + const r = await h.call("POST", "/v1/register", "sh_at_member2", { name: "desk-w", recovery: "recovery-proof-0123456789" }); + const who = await h.call("GET", "/v1/whoami", r.body.token); + expect(who.status).toBe(200); + expect(who.body).toMatchObject({ agent_id: r.body.agent_id, name: "desk-w", user_id: "u-member2" }); + // Self only, and never on the provenance card relaygate stamps on what the agent sends. + expect(who.body.relaygate).not.toHaveProperty("user_id"); + }); + + it("a launched agent's whoami carries the launching person's user", async () => { + const h = harness(); + const r = await h.call("POST", "/v1/register", "sh_lt_launch", { name: "launched-1" }); + expect((await h.call("GET", "/v1/whoami", r.body.token)).body).toMatchObject({ name: "launched-1", user_id: "u-member" }); + // A refreshed token is the same agent, so the same person. + const refreshed = await h.call("POST", "/v1/token/refresh", r.body.token); + expect((await h.call("GET", "/v1/whoami", refreshed.body.token)).body).toMatchObject({ user_id: "u-member" }); + }); + + it("a key-enrolled agent's whoami has no user_id", async () => { + const h = harness(); + const r = await h.call("POST", "/v1/register", "enroll-local-0000000000000000", { name: "keyed-w" }); + const who = await h.call("GET", "/v1/whoami", r.body.token); + expect(who.status).toBe(200); + expect(who.body).not.toHaveProperty("user_id"); + }); + + it("each caller sees only its own user", async () => { + const h = harness(); + const a = await h.call("POST", "/v1/register", "sh_at_member", { name: "desk-a1" }); + const b = await h.call("POST", "/v1/register", "sh_at_member2", { name: "desk-b1" }); + expect((await h.call("GET", "/v1/whoami", a.body.token)).body.user_id).toBe("u-member"); + expect((await h.call("GET", "/v1/whoami", b.body.token)).body.user_id).toBe("u-member2"); + }); + + it("a persisted registration keeps its user_id across a restart", async () => { + const dir = mkdtempSync(join(tmpdir(), "relaygate-whoami-")); + try { + const path = join(dir, "relaygate.db"); + const before = harness({ store: new Store(path) }); + const desk = await before.call("POST", "/v1/register", "sh_at_member", { name: "desk-p", recovery: "recovery-proof-0123456789" }); + const launched = await before.call("POST", "/v1/register", "sh_lt_launch", { name: "launched-1" }); + const keyed = await before.call("POST", "/v1/register", "enroll-local-0000000000000000", { name: "keyed-p" }); + before.store.close(); + // A fresh process: new store on the same file, and no introspection behind the answer. + const after = harness({ store: new Store(path) }); + expect((await after.call("GET", "/v1/whoami", desk.body.token)).body).toMatchObject({ name: "desk-p", user_id: "u-member" }); + expect((await after.call("GET", "/v1/whoami", launched.body.token)).body).toMatchObject({ name: "launched-1", user_id: "u-member" }); + expect((await after.call("GET", "/v1/whoami", keyed.body.token)).body).not.toHaveProperty("user_id"); + expect(after.introspections).toHaveLength(0); + after.store.close(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); describe("an agent uploading with a person's device token as its Sessions credential", () => { // A headless uploader (e.g. the Slack app's agent host) sends the agent's rg_ token in X-Relaygate-Token and an