From 09accecab58efccce8ca5d8e594933f4d5e7ddcd Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 17 Nov 2026 11:22:13 -0800 Subject: [PATCH] feat(control): hosted credential kind for relay-control's hosted MCP participants, fail closed relay-control enrols each hosted participant (a ChatGPT chat, a Cursor cloud agent, any MCP connector that joins through its hosted MCP endpoint) with a one-time hosted credential (sh_ht_, principal_type relay_hosted, a fixed agent_name and the connector's client). Until now those participants never went through relaygate on gate-only installs. - A hosted credential matches only controlPrincipals rules whose kinds list "hosted": the usual catch-all can never put one in the local group. No rule means 403 naming the rule to add (audit no_hosted_rule:). - match.clients (chatgpt, grok-bot, muse, cursor-cloud, mcp) narrows a rule; the policy is refused if a rule sets clients without the hosted kind. - Exactly the named agent; the rule's namePrefix applies; reserved prefixes don't (relay-control is the control plane they're reserved for). Single-use, never cached, only at /v1/register; 24 h tokens that refresh; key id hosted:, which no key or desktop can recover. - explain takes kind hosted with a client. - contract.md: "Hosted participants", per-client example rules, migration note. Co-Authored-By: Claude Opus 5.5 --- docs/contract.md | 80 +++++++++++++++- src/app.ts | 57 ++++++++---- src/control.ts | 36 ++++++-- src/explain.ts | 12 ++- src/hosted-clients.ts | 9 ++ src/policy.ts | 25 ++++- test/hosted.test.ts | 208 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 387 insertions(+), 40 deletions(-) create mode 100644 src/hosted-clients.ts create mode 100644 test/hosted.test.ts diff --git a/docs/contract.md b/docs/contract.md index 51a968d..c4109b6 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -458,8 +458,79 @@ streams named `node:/` and placed by prefix defaults like any stream. The check writes nothing. It never accepts a launch credential: introspecting one redeems it, and the node could no longer register. -Enrollment key ids `control`, `device:*` and `launch:*` are reserved, and an -enrollment key never recovers a desktop-enrolled or launched agent. +Enrollment key ids `control`, `device:*`, `launch:*` and `hosted:*` are +reserved, and an enrollment key never recovers a desktop-enrolled, launched or +hosted agent. + +### Hosted participants + +A hosted participant is an agent relay-control runs for a person's MCP +connector (a chat in ChatGPT, a Cursor cloud agent, any MCP client that joins +the relay through relay-control's hosted MCP endpoint, without Agent Relay +Desktop). On a gate-only install relay-control enrols each one here with a +one-time hosted credential (`sh_ht_…`, scope `relay:hosted:enrol`, +introspecting as `principal_type: "relay_hosted"` with the person, a fixed +`agent_name` and the `client` it belongs to): + +``` +POST /v1/register +Authorization: Bearer sh_ht_... +{"name": ""} + +200 {"agent_id", "gid", "token": "rg_...", "expires_at", "user_id"} +``` + +- `client` is one of `chatgpt`, `grok-bot`, `muse`, `cursor-cloud` or `mcp` (any + other MCP client). relay-control derives it from the connector's registered + OAuth redirect URIs, never from a name the client reports. An unknown or + missing client makes the credential invalid (`401`). +- **Fails closed.** A hosted credential matches only `controlPrincipals` rules + whose `kinds` lists `"hosted"`. A rule without `kinds`, such as the usual + catch-all `{"match": {"orgIds": [""]}, "gid": 11}`, never matches one. + With no matching rule, registration answers `403 relaygate_denied`. The + detail names the rule to add, and the audit reason is + `no_hosted_rule:`. A hosted participant can't silently land in the + group meant for people's desktops. +- `match.clients` narrows a rule to some clients. Only hosted credentials + carry a client, so a rule with `clients` must list `"hosted"` in `kinds` + (the policy is refused otherwise). +- The name must equal the credential's `agent_name`, and the rule's + `namePrefix` applies. `reservedNamePrefixes` don't apply: relay-control is + the control plane those names are reserved for. So an operator can reserve + `cursor-cloud-` against desktops and enrollment keys and still let hosted + Cursor agents enrol it. +- Like a launch credential, relay-control burns it on redemption. relaygate + never caches its introspection and accepts it only at `/v1/register` (never + on Sessions or `/v1/check`). A rejoin is a fresh credential naming the same + agent, and returns the same `agent_id`. The token lives 24 hours and renews + with `POST /v1/token/refresh`. +- The agent's key id is `hosted:`. `whoami` carries the person's + `user_id`, and no enrollment key or desktop can recover it. + +Example rules, one per client an operator allows (put them before any +catch-all; order only matters among rules that can match): + +``` +"controlPrincipals": [ + {"match": {"orgIds": [""], "kinds": ["hosted"], "clients": ["cursor-cloud"], "as": ["agent"]}, "gid": 22, "namePrefix": "cursor-cloud-"}, + {"match": {"orgIds": [""], "kinds": ["hosted"], "clients": ["chatgpt", "muse"], "as": ["agent"]}, "gid": 22}, + {"match": {"orgIds": [""], "kinds": ["hosted"], "clients": ["mcp"], "roles": ["owner", "admin"], "as": ["agent"]}, "gid": 22}, + ... + {"match": {"orgIds": [""]}, "gid": 11} +], +"reservedNamePrefixes": ["cursor-cloud-"] +``` + +Hosted participants run outside the company network, in someone else's cloud, +so the pit (gid 22) is the natural home: they may write into local inboxes +only as `inboxDefaults` allow, and never read local. + +**Migration.** Before this, relay-control registered hosted participants in +Relaycast directly with the workspace key, so on gate-only installs they +bypassed relaygate. Once relay-control enrols them here, an install whose +policy has no hosted rule refuses them. Each hosted participant's next +`join_relay` (or tool call) fails with the missing rule named, until the +operator adds rules like the ones above. ### Reserved names @@ -794,10 +865,11 @@ wins, and a user no rule matches is refused: "sessionAggregates": {"gids": [33]} ``` -`match` takes `kinds` (`device`, `read`, `launch`), `as`, `readerKinds`, `orgIds`, +`match` takes `kinds` (`device`, `read`, `launch`, `hosted`), `clients` (hosted +only, see "Hosted participants"), `as`, `readerKinds`, `orgIds`, `workspaceIds`, `roles`, `userIds` and `emails`. `as` says what the credential stands for: `agent` when it enrols an agent at `POST /v1/register` (a device or -launch credential), `person` everywhere else (Sessions uploads and reads, +launch or hosted credential), `person` everywhere else (Sessions uploads and reads, `/v1/check`, adoption). Rules without `as` match both. Put `as: ["person"]` on rules that grant more than an agent should have (admins), so the agents those people enrol land in an agent rule instead. diff --git a/src/app.ts b/src/app.ts index c2fa1a8..76c0ece 100644 --- a/src/app.ts +++ b/src/app.ts @@ -97,11 +97,12 @@ 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). + * registration, persisted as the agent's key id (`device:` / `launch:` / `hosted:`, 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:"]) { + for (const prefix of ["device:", "launch:", "hosted:"]) { if (agent.keyId.startsWith(prefix)) return agent.keyId.slice(prefix.length) || undefined; } return undefined; @@ -311,8 +312,9 @@ export function createApp(deps: Deps) { /** * POST /v1/register with a relay-control credential, identified by relay-control and grouped by - * controlPrincipals: a person's device token (their desktop's agents), or a one-time launch credential (one agent a - * person launched, whose name the credential fixes). + * controlPrincipals: a person's device token (their desktop's agents), a one-time launch credential (one agent a + * person launched, whose name the credential fixes), or a one-time hosted credential (one hosted MCP participant of a + * person's connector, whose name and client the credential fixes; it matches only rules naming the hosted kind). */ const registerWithDevice = async (c: Context, deviceToken: string) => { const control = deps.control!; @@ -329,11 +331,19 @@ export function createApp(deps: Deps) { return deny(c, status, error, extra); }; if (!identity) return refuse(401, "relaygate_unauthenticated", "control_credential_invalid"); - const launch = identity.kind === "launch"; - const needed = launch ? "relay:agent:enrol" : "cli:auth"; + const hosted = identity.kind === "hosted"; + // Both single-use credentials name exactly one agent and renew with /v1/token/refresh. + const launch = identity.kind === "launch" || hosted; + const needed = hosted ? "relay:hosted:enrol" : launch ? "relay:agent:enrol" : "cli:auth"; if (!identity.scopes.includes(needed)) return refuse(403, "relaygate_denied", `control_credential_no_${needed}`, { detail: `the credential needs ${needed}` }); const rule = matchControlRule(identity, policy, "agent"); - if (!rule) return refuse(403, "relaygate_denied", "no_control_rule", { detail: "no controlPrincipals rule matches this person" }); + if (!rule) { + return refuse(403, "relaygate_denied", hosted ? `no_hosted_rule:${identity.client}` : "no_control_rule", { + detail: hosted + ? `no controlPrincipals rule allows hosted ${identity.client} participants: add one with "kinds": ["hosted"] (and "clients": ["${identity.client}"])` + : "no controlPrincipals rule matches this person", + }); + } const parsed = RegisterBody.safeParse(await c.req.json().catch(() => null)); if (!parsed.success) return deny(c, 400, "relaygate_bad_request", { detail: parsed.error.issues[0]?.message }); const { name, recovery } = parsed.data; @@ -342,10 +352,16 @@ export function createApp(deps: Deps) { const binding = recovery === undefined ? null : sha256(recovery); if (!ownPerson && personPrefixed(name, policy)) return refuse(403, "relaygate_name_scope", "person_name_not_own", { detail: "this name is another person's identity" }); if (!ownPerson && rule.namePrefix && !name.startsWith(rule.namePrefix)) return refuse(403, "relaygate_name_scope", "name_scope"); - if (!ownPerson && reservedName(name, policy)) return refuse(403, "relaygate_name_scope", "name_reserved"); - // A launch credential enrols exactly the agent it names. - if (launch && name !== identity.agentName) return refuse(403, "relaygate_name_scope", "launch_name_mismatch", { detail: "name must equal the launch credential's agent_name" }); - const keyId = `${launch ? "launch" : "device"}:${identity.userId}`; + // Reserved prefixes are for names a control plane registers server-side: relay-control's hosted participants are + // exactly that, so a hosted credential may use one (its rule's namePrefix still applies). + if (!ownPerson && !hosted && reservedName(name, policy)) return refuse(403, "relaygate_name_scope", "name_reserved"); + // A launch or hosted credential enrols exactly the agent it names. + if (launch && name !== identity.agentName) { + return refuse(403, "relaygate_name_scope", hosted ? "hosted_name_mismatch" : "launch_name_mismatch", { + detail: `name must equal the ${hosted ? "hosted" : "launch"} credential's agent_name`, + }); + } + const keyId = `${hosted ? "hosted" : launch ? "launch" : "device"}:${identity.userId}`; // A desktop agent's token never outlives the device token behind it; a launched agent's is a flat 24 h (it renews // with /v1/token/refresh: the single-use launch credential's own short expiry doesn't apply to the agent). const expiresAt = launch ? now() + DEVICE_TOKEN_MAX_MS : Math.min(now() + DEVICE_TOKEN_MAX_MS, identity.expiresAt ?? Infinity); @@ -354,8 +370,8 @@ export function createApp(deps: Deps) { const existing = store.agentByName(name); if (existing) { - // Only the same person gets an existing name back: with the recovery proof, or (a relaunch) with a fresh - // single-use launch credential naming that very agent. + // Only the same person gets an existing name back: with the recovery proof, or (a relaunch or a hosted rejoin) + // with a fresh single-use credential of the same kind naming that very agent. // A person identity is one name across their computers: each computer's recovery proof rotates only its own token. const recovered = existing.keyId === keyId && @@ -373,7 +389,7 @@ export function createApp(deps: Deps) { } const agent = store.createAgent(name, rule.gid, keyId, recovery, false, rule.groups); const token = store.issueToken(agent.id, expiresAt, launch ? undefined : (binding ?? undefined)); - store.audit({ agentId: agent.id, action: "register", op: null, resourceKind: "agent", resourceId: name, decision: "allow", stage: "registration", reason: `device:${identity.userId}` }); + store.audit({ agentId: agent.id, action: "register", op: null, resourceKind: "agent", resourceId: name, decision: "allow", stage: "registration", reason: hosted ? `hosted:${identity.client}:${identity.userId}` : `device:${identity.userId}` }); await enrollUpstream(agent); return answer(agent.id, rule.gid, token); }; @@ -381,7 +397,7 @@ export function createApp(deps: Deps) { app.post("/v1/register", async (c) => { const key = bearer(c); const credentialKind = key && deps.control ? controlTokenKind(key) : undefined; - if (credentialKind === "device" || credentialKind === "launch") return registerWithDevice(c, key!); + if (credentialKind === "device" || credentialKind === "launch" || credentialKind === "hosted") return registerWithDevice(c, key!); const policy = deps.policy(); const matches: EnrollmentKey[] = key ? policy.enrollmentKeys.filter((k) => sameHash(k.sha256, sha256(key))) : []; const enrollment = matches.find((k) => keyUsable(k, now())); @@ -410,6 +426,7 @@ export function createApp(deps: Deps) { // A desktop-enrolled or launched agent belongs to its person: only their relay-control credential recovers it. !existing.keyId.startsWith("device:") && !existing.keyId.startsWith("launch:") && + !existing.keyId.startsWith("hosted:") && existing.gid === enrollment.gid && existing.guest === enrollment.guest && recovery !== undefined && @@ -612,7 +629,10 @@ export function createApp(deps: Deps) { if (refused) return refused; return next(); } - if (onSessions && !relaygateToken && deps.control && presented && controlTokenKind(presented)) { + // A hosted credential only ever enrols at /v1/register (introspecting it here would redeem it): it falls through to + // the rg_ check below and is refused. + const presentedKind = presented ? controlTokenKind(presented) : undefined; + if (onSessions && !relaygateToken && deps.control && presented && presentedKind && presentedKind !== "hosted") { const refused = await authenticateControl(c, presented); if (refused) return refused; return next(); @@ -648,10 +668,11 @@ export function createApp(deps: Deps) { if (deps.sessions?.corsOrigins?.length) app.use("/sessions/*", sessionsCors(deps.sessions)); app.use("/sessions/*", authenticate); - // Launched agents can't re-register (their launch credential is single-use): they refresh before expiry instead. + // Launched agents and hosted participants can't re-register (their credential is single-use): they refresh before + // expiry instead. app.post("/v1/token/refresh", (c) => { const agent = c.get("agent"); - if (!agent.keyId.startsWith("launch:")) { + if (!agent.keyId.startsWith("launch:") && !agent.keyId.startsWith("hosted:")) { return deny(c, 403, "relaygate_denied", { detail: agent.keyId.startsWith("device:") ? "re-register with your device token" : "this token doesn't expire", }); diff --git a/src/control.ts b/src/control.ts index 793ab34..2777df4 100644 --- a/src/control.ts +++ b/src/control.ts @@ -1,6 +1,8 @@ import type { Principal } from "./mode.js"; import type { Policy } from "./policy.js"; import { sha256, type Agent, type Store } from "./store.js"; +import { isHostedClient, type HostedClient } from "./hosted-clients.js"; +export { HOSTED_CLIENTS, type HostedClient } from "./hosted-clients.js"; /** * Principals that hold only relay-control credentials (docs/contract.md, "Control principals"): the desktop app @@ -27,10 +29,14 @@ export interface ControlConfig { export type ControlRole = "owner" | "admin" | "member"; +export type ControlKind = "device" | "read" | "launch" | "hosted"; + export interface ControlIdentity { - kind: "device" | "read" | "launch"; - /** Launch credentials only: the one agent name it may enrol. */ + kind: ControlKind; + /** Launch and hosted credentials only: the one agent name it may enrol. */ agentName?: string; + /** Hosted credentials only: which hosted MCP client the agent belongs to. */ + client?: HostedClient; userId: string; email?: string; orgId: string; @@ -74,9 +80,10 @@ const CACHE_MAX = 10_000; const MAX_READ_TOKEN_MS = 90 * 24 * 3600 * 1000; /** Which credential a bearer token is, by its prefix. */ -export function controlTokenKind(token: string): "device" | "read" | "launch" | undefined { +export function controlTokenKind(token: string): ControlKind | undefined { if (token.startsWith("sh_at_")) return "device"; if (token.startsWith("sh_lt_")) return "launch"; + if (token.startsWith("sh_ht_")) return "hosted"; if (token.startsWith("rth_at_read_") || token.startsWith("rth_st_read_")) return "read"; return undefined; } @@ -97,7 +104,7 @@ export class ControlAuth { async identify(token: string): Promise { const kind = controlTokenKind(token); if (kind === "read") return this.readToken(token); - if (kind === "device" || kind === "launch") return this.introspect(token, kind); + if (kind === "device" || kind === "launch" || kind === "hosted") return this.introspect(token, kind); return undefined; } @@ -110,7 +117,7 @@ export class ControlAuth { return { kind: "read", userId: row.userId, email, orgId: row.orgId, workspaceId: row.workspaceId ?? undefined, role: row.role ?? undefined, scopes: ["rth:read"], expiresAt: row.expiresAt ?? undefined, readerKind }; } - private async introspect(token: string, kind: "device" | "launch"): Promise { + private async introspect(token: string, kind: "device" | "launch" | "hosted"): Promise { const key = sha256(token); const hit = kind === "device" ? this.cache.get(key) : undefined; if (hit && hit.until > this.now()) return hit.identity; @@ -135,13 +142,17 @@ export class ControlAuth { throw new ControlUnavailable("introspection answer could not be read"); } if (!body || body.active !== true) return undefined; - // A device token is a person on their desktop; a launch credential is one agent a person launched. - const expected = kind === "device" ? "desktop-user" : "relay_launch"; + // A device token is a person on their desktop; a launch credential is one agent a person launched; a hosted + // credential is one hosted MCP participant a person's connector (ChatGPT, Cursor cloud agents, ...) joins with. + const expected = kind === "device" ? "desktop-user" : kind === "launch" ? "relay_launch" : "relay_hosted"; if (body.principal_type !== expected || typeof body.sub !== "string" || typeof body.org !== "string") return undefined; - if (kind === "launch" && (typeof body.agent_name !== "string" || !body.agent_name)) return undefined; + if (kind !== "device" && (typeof body.agent_name !== "string" || !body.agent_name)) return undefined; + // An unknown client is refused, never treated as a generic one: it would match rules meant for another client. + if (kind === "hosted" && !isHostedClient(body.client)) return undefined; const identity: ControlIdentity = { kind, - ...(kind === "launch" ? { agentName: body.agent_name as string } : {}), + ...(kind !== "device" ? { agentName: body.agent_name as string } : {}), + ...(kind === "hosted" ? { client: body.client as HostedClient } : {}), userId: body.sub, email: typeof body.email === "string" ? body.email : undefined, orgId: body.org, @@ -151,7 +162,7 @@ export class ControlAuth { expiresAt: typeof body.exp === "number" ? body.exp * 1000 : undefined, }; if (identity.email) this.store.rememberControlEmail(identity.userId, identity.email); - // Launch credentials are single-use (relay-control burns them): never answered from cache. + // Launch and hosted credentials are single-use (relay-control burns them): never answered from cache. if (kind === "device") { const until = Math.min(this.now() + (this.cfg.cacheMs ?? 15_000), identity.expiresAt ?? Infinity); this.remember(key, { identity, until }); @@ -201,7 +212,12 @@ export function matchControlRule(identity: ControlIdentity, policy: Policy, as: return policy.controlPrincipals.find((rule) => { const m = rule.match; if (m.as && !m.as.includes(as)) return false; + // Fails closed: a hosted credential matches only a rule that names the hosted kind, so a catch-all rule (no + // `kinds`) written for people and their desktops never takes a hosted MCP participant into its group. + if (identity.kind === "hosted" && !m.kinds?.includes("hosted")) return false; if (m.kinds && !m.kinds.includes(identity.kind)) return false; + // Only a hosted credential carries a client; any other credential matches no rule that sets `clients`. + if (m.clients && (!identity.client || !m.clients.includes(identity.client))) return false; // Fails closed: a read token minted without a reader_kind (an older relay-control) matches no readerKinds rule. if (m.readerKinds && (!identity.readerKind || !m.readerKinds.includes(identity.readerKind))) return false; if (m.orgIds && !m.orgIds.includes(identity.orgId)) return false; diff --git a/src/explain.ts b/src/explain.ts index 078c4f2..5d52529 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -4,6 +4,7 @@ import { resolveSession } from "./sessions.js"; import { allGroups, check, inGroup, type CheckStep, type Op, type Principal } from "./mode.js"; import { keyUsable, type Policy } from "./policy.js"; import { matchControlRule } from "./control.js"; +import { HOSTED_CLIENTS } from "./hosted-clients.js"; import type { Store } from "./store.js"; /** @@ -33,8 +34,10 @@ export const SubjectSchema = z.union([ email: z.string().min(3).optional(), role: z.enum(["owner", "admin", "member"]).optional(), workspaceId: z.string().min(1).optional(), - kind: z.enum(["device", "read", "launch"]).default("read"), + kind: z.enum(["device", "read", "launch", "hosted"]).default("read"), readerKind: z.enum(["browser", "device", "mcp"]).optional(), + /** kind hosted only: the hosted MCP client (default "mcp"). */ + client: z.enum(HOSTED_CLIENTS).optional(), as: z.enum(["person", "agent"]).optional(), }) .strict(), @@ -109,11 +112,12 @@ function resolveSubject(subject: Subject, policy: Policy, store: Pick` : `ctl:${p.userId}`; diff --git a/src/hosted-clients.ts b/src/hosted-clients.ts new file mode 100644 index 0000000..97c8ebf --- /dev/null +++ b/src/hosted-clients.ts @@ -0,0 +1,9 @@ +/** + * The hosted MCP clients relay-control enrols agents for with a one-time hosted credential (`sh_ht_`): the connector + * kind of the grant behind a hosted participant (docs/contract.md, "Hosted participants"). A leaf, so the policy + * schema and the control identity share it without importing each other. + */ +export const HOSTED_CLIENTS = ["chatgpt", "grok-bot", "muse", "cursor-cloud", "mcp"] as const; +export type HostedClient = (typeof HOSTED_CLIENTS)[number]; +export const isHostedClient = (v: unknown): v is HostedClient => + typeof v === "string" && (HOSTED_CLIENTS as readonly string[]).includes(v); diff --git a/src/policy.ts b/src/policy.ts index e73c434..9af72aa 100644 --- a/src/policy.ts +++ b/src/policy.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { z } from "zod"; +import { HOSTED_CLIENTS } from "./hosted-clients.js"; /** * The operator's policy. In production relay-control is the source of truth @@ -83,7 +84,16 @@ export const PolicySchema = z.object({ z.object({ match: z .object({ - kinds: z.array(z.enum(["device", "read", "launch"])).min(1).optional(), + /** + * Credential kinds the rule matches. A hosted credential (a hosted MCP participant) matches only rules + * that list "hosted" here: rules without `kinds` never match it. + */ + kinds: z.array(z.enum(["device", "read", "launch", "hosted"])).min(1).optional(), + /** + * Hosted credentials only: the hosted MCP client the participant belongs to. Every other credential + * matches no rule that sets this. + */ + clients: z.array(z.enum(HOSTED_CLIENTS)).min(1).optional(), /** * What the credential stands for here: "agent" when it enrols an agent at /v1/register (a device or launch * credential), "person" everywhere else (Sessions, /v1/check). Lets the same user read more as a person @@ -203,12 +213,19 @@ export function parsePolicy(raw: unknown): Policy { 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. + // `device:`, `launch:`, `hosted:` 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:")) { - throw new Error(`enrollment key id ${k.id} is reserved (control, device:*, launch:*)`); + if (k.id === "control" || k.id.startsWith("device:") || k.id.startsWith("launch:") || k.id.startsWith("hosted:")) { + throw new Error(`enrollment key id ${k.id} is reserved (control, device:*, launch:*, hosted:*)`); } } + // `clients` only selects hosted credentials: on a rule that can't match one it would silently match nothing. + policy.controlPrincipals.forEach((rule, i) => { + if (rule.match.clients && !rule.match.kinds?.includes("hosted")) { + throw new Error(`control principal rule ${i} sets clients but its kinds don't include "hosted"`); + } + }); // A key can't put an agent into a group its own ceiling forbids: the ceiling would always win, so it's a mistake. for (const k of policy.enrollmentKeys) { const mine = [k.gid, ...k.groups]; diff --git a/test/hosted.test.ts b/test/hosted.test.ts new file mode 100644 index 0000000..2c124ec --- /dev/null +++ b/test/hosted.test.ts @@ -0,0 +1,208 @@ +import { Hono } from "hono"; +import { describe, expect, it } from "vitest"; +import { createApp } from "../src/app.js"; +import { RuleClassifier } from "../src/classifier.js"; +import { ControlAuth, controlTokenKind, matchControlRule } from "../src/control.js"; +import { explain } from "../src/explain.js"; +import { parsePolicy } from "../src/policy.js"; +import { sha256, Store } from "../src/store.js"; + +const SECRET = "introspect-secret"; + +const hostedCredential = (client: string, agent: string, extra: Record = {}) => ({ + active: true, principal_type: "relay_hosted", sub: "u-member", email: "dev@example.test", org: "org-1", workspace: "ws-1", + role: "member", scopes: ["relay:hosted:enrol"], agent_name: agent, client, ...extra, +}); + +/** What relay-control answers, by credential. Hosted credentials are single-use; the fake doesn't burn them. */ +const CREDENTIALS: Record> = { + sh_at_member: { active: true, principal_type: "desktop-user", sub: "u-member", email: "dev@example.test", org: "org-1", workspace: "ws-1", role: "member", scopes: ["rth:sync", "rth:read", "cli:auth"], exp: 4_102_444_800 }, + sh_ht_cursor: hostedCredential("cursor-cloud", "cursor-cloud-0123456789"), + sh_ht_cursor_again: hostedCredential("cursor-cloud", "cursor-cloud-0123456789"), + sh_ht_chatgpt: hostedCredential("chatgpt", "assistant-notes"), + sh_ht_unknown_client: hostedCredential("some-future-client", "cursor-cloud-x"), + sh_ht_no_client: hostedCredential("cursor-cloud", "cursor-cloud-y", { client: undefined }), + sh_ht_noscope: hostedCredential("cursor-cloud", "cursor-cloud-z", { scopes: ["relay:agent:enrol"] }), + sh_ht_wrong_type: hostedCredential("cursor-cloud", "cursor-cloud-w", { principal_type: "relay_launch" }), + sh_ht_wrong_prefix: hostedCredential("cursor-cloud", "pit-notes"), +}; + +const base = { + groups: [ + { gid: 11, name: "local" }, + { gid: 22, name: "pit" }, + { gid: 33, name: "admins" }, + ], + enrollmentKeys: [{ id: "local", gid: 11, sha256: sha256("enroll-local-0000000000000000") }], + // Local inboxes take writes from the pit; nothing else of local's is open to it. + inboxDefaults: [{ gid: 11, mode: "660", acl: [{ gid: 22, perm: "w" }] }], + streamDefaults: [{ prefix: "local:", gid: 11, mode: "660", acl: [] }], + ceilings: [{ gid: 22, never: [33] }], + reservedNamePrefixes: ["cursor-cloud-"], +}; + +/** An operator who allowed only Cursor cloud agents, into the pit; the usual catch-all stays last. */ +const withCursorRule = () => + parsePolicy({ + ...base, + controlPrincipals: [ + { match: { orgIds: ["org-1"], kinds: ["hosted"], clients: ["cursor-cloud"], as: ["agent"] }, gid: 22, namePrefix: "cursor-cloud-" }, + { match: { orgIds: ["org-1"], roles: ["owner", "admin"] }, gid: 33 }, + { match: { orgIds: ["org-1"] }, gid: 11 }, + ], + }); + +/** An install that never configured hosted participants: only the catch-all. */ +const catchAllOnly = () => parsePolicy({ ...base, controlPrincipals: [{ match: { orgIds: ["org-1"] }, gid: 11 }] }); + +function harness(policy = withCursorRule()) { + const introspections: string[] = []; + const control = new Hono(); + control.post("/internal/v1/auth/introspect", async (c) => { + if (c.req.header("authorization") !== `Bearer ${SECRET}`) return c.json({ error: "unauthorized" }, 401); + const body = await c.req.json(); + introspections.push(body.token); + return c.json(CREDENTIALS[body.token] ?? { active: false, reason: "unknown" }); + }); + 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 app = createApp({ + store, + policy: () => policy, + classifier: () => new RuleClassifier([]), + control: new ControlAuth({ introspectUrl: "http://control.test/internal/v1/auth/introspect", introspectSecret: SECRET, audience: "https://history.example.test", fetch: toFetch(control) }, store), + sessions: { uploadUrl: "http://ingest.test", readUrl: "http://read.test", fetch: toFetch(new Hono()) }, + }); + const call = async (method: string, path: string, token?: string, body?: unknown) => { + const res = await app.request(path, { + method, + headers: { ...(body === undefined ? {} : { "content-type": "application/json" }), ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await res.text(); + let parsed: any = text; + try { + parsed = JSON.parse(text); + } catch { + /* not JSON */ + } + return { status: res.status, body: parsed }; + }; + return { store, call, introspections }; +} + +describe("hosted participants (relay-control hosted credentials)", () => { + it("sh_ht_ is the hosted kind", () => { + expect(controlTokenKind("sh_ht_abc")).toBe("hosted"); + expect(controlTokenKind("sh_lt_abc")).toBe("launch"); + }); + + it("fails closed: with only a catch-all rule, a hosted participant is refused, never put in gid 11", async () => { + const h = harness(catchAllOnly()); + const r = await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-0123456789" }); + expect(r.status).toBe(403); + expect(r.body.error).toBe("relaygate_denied"); + // The refusal names the missing rule, so an operator knows what to add. + expect(r.body.detail).toMatch(/"kinds": \["hosted"\]/); + expect(r.body.detail).toMatch(/cursor-cloud/); + expect(h.store.agentByName("cursor-cloud-0123456789")).toBeUndefined(); + const audit = h.store.auditSince(0, 50).find((row) => row.action === "register"); + expect(audit?.reason).toBe("no_hosted_rule:cursor-cloud"); + }); + + it("a rule without kinds, or with other kinds only, never matches a hosted credential", () => { + const policy = parsePolicy({ + ...base, + controlPrincipals: [ + { match: { orgIds: ["org-1"], kinds: ["device", "launch"] }, gid: 11 }, + { match: { orgIds: ["org-1"], as: ["agent"] }, gid: 11 }, + { match: {}, gid: 11 }, + ], + }); + const identity = { kind: "hosted" as const, client: "chatgpt" as const, userId: "u", orgId: "org-1", scopes: [] }; + expect(matchControlRule(identity, policy, "agent")).toBeUndefined(); + expect(matchControlRule(identity, policy, "person")).toBeUndefined(); + }); + + it("a matching rule enrols exactly the named agent into the operator's group (the pit)", async () => { + const h = harness(); + expect((await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-other" })).status).toBe(403); + const ok = await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-0123456789" }); + expect(ok.status).toBe(200); + expect(ok.body).toMatchObject({ gid: 22, user_id: "u-member" }); + expect(Date.parse(ok.body.expires_at)).toBeGreaterThan(Date.now() + 23 * 3600 * 1000); + expect(h.store.agentByName("cursor-cloud-0123456789")?.keyId).toBe("hosted:u-member"); + expect((await h.call("GET", "/v1/whoami", ok.body.token)).body).toMatchObject({ name: "cursor-cloud-0123456789", user_id: "u-member" }); + // A rejoin (a fresh credential naming the same agent) gets the same agent back, without a recovery proof. + const again = await h.call("POST", "/v1/register", "sh_ht_cursor_again", { name: "cursor-cloud-0123456789" }); + expect(again.body.agent_id).toBe(ok.body.agent_id); + }); + + it("clients scope a rule: a ChatGPT participant doesn't match the Cursor rule", async () => { + const h = harness(); + const r = await h.call("POST", "/v1/register", "sh_ht_chatgpt", { name: "assistant-notes" }); + expect(r.status).toBe(403); + expect(r.body.detail).toMatch(/chatgpt/); + }); + + it("refuses unknown or missing clients, the wrong scope, the wrong principal type and names outside the rule's prefix", async () => { + const h = harness(); + expect((await h.call("POST", "/v1/register", "sh_ht_unknown_client", { name: "cursor-cloud-x" })).status).toBe(401); + expect((await h.call("POST", "/v1/register", "sh_ht_no_client", { name: "cursor-cloud-y" })).status).toBe(401); + expect((await h.call("POST", "/v1/register", "sh_ht_noscope", { name: "cursor-cloud-z" })).status).toBe(403); + expect((await h.call("POST", "/v1/register", "sh_ht_wrong_type", { name: "cursor-cloud-w" })).status).toBe(401); + expect((await h.call("POST", "/v1/register", "sh_ht_wrong_prefix", { name: "pit-notes" })).status).toBe(403); + }); + + it("a reserved prefix stays closed to desktops and enrollment keys, and nobody else can take a hosted agent's name", async () => { + const h = harness(); + expect((await h.call("POST", "/v1/register", "sh_at_member", { name: "cursor-cloud-desk" })).status).toBe(403); + expect((await h.call("POST", "/v1/register", "enroll-local-0000000000000000", { name: "cursor-cloud-key" })).status).toBe(403); + await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-0123456789", recovery: "recovery-proof-0123456789" }); + expect((await h.call("POST", "/v1/register", "enroll-local-0000000000000000", { name: "cursor-cloud-0123456789", recovery: "recovery-proof-0123456789" })).status).toBe(403); + }); + + it("hosted participants refresh their token like launched agents", async () => { + const h = harness(); + const token = (await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-0123456789" })).body.token; + const refreshed = await h.call("POST", "/v1/token/refresh", token); + expect(refreshed.status).toBe(200); + expect((await h.call("GET", "/v1/whoami", token)).status).toBe(401); + expect((await h.call("GET", "/v1/whoami", refreshed.body.token)).status).toBe(200); + }); + + it("in the pit, a hosted participant writes a local inbox only as the policy allows and never reads local", async () => { + const h = harness(); + await h.call("POST", "/v1/register", "sh_at_member", { name: "desk-agent" }); + const token = (await h.call("POST", "/v1/register", "sh_ht_cursor", { name: "cursor-cloud-0123456789" })).body.token; + const check = (op: "r" | "w", id: string) => h.call("POST", "/v1/check", token, { op, resource: { kind: "stream", id }, content: "hello" }); + expect((await check("w", "relaycast:inbox/desk-agent")).body).toEqual({ decision: "allow" }); + expect((await check("r", "relaycast:inbox/desk-agent")).status).toBe(403); + expect((await check("r", "local:notes")).status).toBe(403); + expect((await check("w", "local:notes")).status).toBe(403); + }); + + it("a hosted credential is only for /v1/register: Sessions and /v1/check never introspect (redeem) it", async () => { + const h = harness(); + expect((await h.call("GET", "/sessions/v1/sessions/s-1/events", "sh_ht_cursor")).status).toBe(401); + expect((await h.call("POST", "/v1/check", "sh_ht_cursor", { op: "w", resource: { kind: "stream", id: "local:notes" }, content: "x" })).status).toBe(401); + expect(h.introspections).toEqual([]); + }); + + it("policy: clients need the hosted kind, and hosted:* key ids are reserved", () => { + expect(() => parsePolicy({ ...base, controlPrincipals: [{ match: { clients: ["chatgpt"] }, gid: 22 }] })).toThrow(/clients/); + expect(() => parsePolicy({ ...base, controlPrincipals: [{ match: { kinds: ["device"], clients: ["chatgpt"] }, gid: 22 }] })).toThrow(/clients/); + expect(() => parsePolicy({ ...base, controlPrincipals: [{ match: { clients: ["nope"] }, gid: 22 }] })).toThrow(); + expect(() => parsePolicy({ ...base, controlPrincipals: [], enrollmentKeys: [{ id: "hosted:u", gid: 11, sha256: sha256("x".repeat(32)) }] })).toThrow(/reserved/); + }); + + it("explain answers for a hosted participant", () => { + const policy = withCursorRule(); + const as = (client: "cursor-cloud" | "chatgpt") => ({ control: { userId: "u-member", orgId: "org-1", kind: "hosted" as const, client } }); + expect(explain(policy, undefined, { as: as("cursor-cloud"), op: "w", resource: { kind: "stream", id: "relaycast:inbox/x" } })).toMatchObject({ + subject: { gid: 22, group_names: ["pit"] }, + }); + const refused = explain(policy, undefined, { as: as("chatgpt"), op: "w", resource: { kind: "stream", id: "relaycast:inbox/x" } }) as any; + expect(JSON.stringify(refused)).toMatch(/no_control_rule/); + }); +});