From e196af46f0f58149e5af223fe4874eed52df07c2 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 16 Nov 2026 14:03:02 -0800 Subject: [PATCH] feat(sessions): groupLabels policy map annotates readable sessions with their group's label An optional `groupLabels` map in the policy ({"22": {"label": "pit"}}) gives groups a display label. Session lists, and the metadata and catalog views of one session, then carry `relaygate: {gid, label}` for each readable session a labeled group owns, so a dashboard can badge them. Labels grant nothing; no defaults; unlabeled sessions and other views pass unchanged (single-session views byte for byte); an upstream `relaygate` key is dropped. Validated by the loader and POST /admin/v1/policy/validate (known gids, 1-24 plain characters). Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++++ docs/contract.md | 38 +++++++++++++++++++++++++++++-- examples/policy.pit.json | 1 + src/policy.ts | 24 ++++++++++++++++++++ src/sessions.ts | 39 +++++++++++++++++++++++++++++--- test/admin.test.ts | 4 ++++ test/sessions.test.ts | 48 +++++++++++++++++++++++++++++++++++++++- 7 files changed, 153 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 18907cf..c45f88b 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,11 @@ canary; outside agents try every way to get it; the audit log is the evidence) is in [docs/acceptance-pit.md](docs/acceptance-pit.md), with the driver and the inside test agent in `scripts/acceptance/`. +To badge sessions by group in a dashboard, give groups display labels in the +policy (`"groupLabels": {"22": {"label": "pit"}}`); readable sessions those +groups own then carry `relaygate: {"gid": 22, "label": "pit"}` in session lists, +metadata and catalog reads. See "Group labels" in the contract. + Example policies with their cases: `examples/policy.pit.json` (with a guest) and `examples/policy.double-pit.json` (two groups: laptops outside the regulated boundary, cloud agents inside it). diff --git a/docs/contract.md b/docs/contract.md index f4dc210..6a1c824 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -636,8 +636,8 @@ strong as the network rule that Sessions accepts traffic from relaygate alone | `POST /sessions/v1/delivery/sessions/selection` | `w` on every session it names (choosing what syncs) | | `POST /sessions/v1/auth/token/revoke`, `GET /sessions/healthz` | no principal needed (revoking is always safe) | | `POST /sessions/v1/ingest` | `w` on every session the batch names; all or nothing. Each record gets a `relaygate:agent:` tag (client `relaygate:` tags are dropped) and, where it names one, `sessionOwner` set to the agent | -| `GET /sessions/v1/sessions` | filtered to sessions the caller may read; the cursor passes through | -| `GET /sessions/v1/sessions/:id/{events,turns,metadata,thread,catalog,timing,analysis,brief}` | `r` on the session | +| `GET /sessions/v1/sessions` | filtered to sessions the caller may read; the cursor passes through; labeled sessions carry `relaygate` (see "Group labels") | +| `GET /sessions/v1/sessions/:id/{events,turns,metadata,thread,catalog,timing,analysis,brief}` | `r` on the session; `metadata` and `catalog` of a labeled session carry `relaygate` | | `GET /sessions/v1/events?session=` | one `session`, `r` on it | | `GET /sessions/v1/events?q=` | transcript search, filtered to events of sessions the caller may read | @@ -655,6 +655,40 @@ run headless on Linux servers, so their sessions come from a headless uploader on that server, authenticated with the agent's `rg_` token, not from the desktop app. +### Group labels + +A deployment can name its groups for people reading sessions, so a dashboard +can badge, say, every session the pit group owns. Labels are display only: +they grant nothing and change no decision. No group has a label unless the +policy gives it one. + +``` +"groupLabels": {"22": {"label": "pit", "description": "Agents inside the boundary"}} +``` + +Keys are gids in decimal, each one a group the policy defines. `label` is 1 to +24 characters (letters, digits, space, `.`, `_`, `-`; it starts with a letter +or digit and doesn't end in a space); `description` is optional, at most 200 +characters, and is not sent to readers. Both the loader and +`POST /admin/v1/policy/validate` refuse anything else. + +On reads that pass the check, relaygate adds the owning group and its label to +each session a labeled group owns: + +- every session in `GET /sessions/v1/sessions`; +- the top-level object of `GET /sessions/v1/sessions/:id/metadata` and `.../catalog`. + +``` +{"sessionId": "...", ..., "relaygate": {"gid": 22, "label": "pit"}} +``` + +Nothing else changes: a session whose group has no label gets no `relaygate` +key, other views are untouched, and a single-session view without a label +passes byte for byte. The owner is never named. A `relaygate` key that comes +from Sessions itself is dropped, so a reader can trust that only relaygate +wrote it. A caller only ever sees the label of a session it may read, and a +session that never came through relaygate has no owning group, so no label. + ## Control principals Some callers hold only relay-control credentials: the desktop app uploads diff --git a/examples/policy.pit.json b/examples/policy.pit.json index 1e40352..3cc9b19 100644 --- a/examples/policy.pit.json +++ b/examples/policy.pit.json @@ -27,6 +27,7 @@ {"gid": 22, "mode": "660"} ], "sessionOverrides": [], + "groupLabels": {"22": {"label": "pit", "description": "Agents inside the boundary"}}, "ceilings": [ {"gid": 44, "never": [22]} ], diff --git a/src/policy.ts b/src/policy.ts index 9bac976..7039025 100644 --- a/src/policy.ts +++ b/src/policy.ts @@ -122,6 +122,24 @@ export const PolicySchema = z.object({ }) .strict() .optional(), + /** + * Display labels for groups, keyed by gid in decimal (e.g. `{"22": {"label": "pit"}}`). relaygate adds + * `relaygate: {"gid", "label"}` to each readable session a group with a label owns, so a dashboard can badge it. + * Display only: a label grants nothing. No group has a label unless the policy gives it one. + */ + groupLabels: z + .record( + z.string().regex(/^(0|[1-9][0-9]*)$/, "groupLabels keys are gids in decimal"), + z + .object({ + label: z + .string() + .regex(/^[A-Za-z0-9](?:[A-Za-z0-9 ._-]{0,22}[A-Za-z0-9._-])?$/, "label is 1-24 characters: A-Z, a-z, 0-9, space, '.', '_' and '-', starting with a letter or digit and not ending in a space"), + description: z.string().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u, "description has no control characters").optional(), + }) + .strict(), + ) + .optional(), /** Who may read Sessions aggregates that span every session (per-person usage, activity, digests). */ sessionAggregates: z.object({ gids: z.array(Gid).default([]) }).default({ gids: [] }), /** Per group, the groups whose resources it may never touch, whatever the mode or ACL says. */ @@ -170,6 +188,7 @@ export function parsePolicy(raw: unknown): Policy { ...policy.controlPrincipals.flatMap((rule, i) => [rule.gid, ...rule.groups].map((gid) => ({ where: `control principal rule ${i}`, gid }))), ...policy.sessionAggregates.gids.map((gid) => ({ where: "sessionAggregates", gid })), ...policy.ceilings.flatMap((c) => [c.gid, ...c.never].map((gid) => ({ where: `ceiling for ${c.gid}`, gid }))), + ...Object.keys(policy.groupLabels ?? {}).map((key) => ({ where: "groupLabels", gid: Number(key) })), ].filter((r) => !gids.has(r.gid)); if (unknown.length > 0) { throw new Error(`policy names groups it doesn't define: ${unknown.map((u) => `${u.where} (gid ${u.gid})`).join(", ")}`); @@ -227,3 +246,8 @@ export function keyUsable(key: EnrollmentKey, now: number): boolean { export function loadPolicyFile(path: string): Policy { return parsePolicy(JSON.parse(readFileSync(path, "utf8"))); } + +/** The display label a policy gives a group, if any (see `groupLabels`). */ +export function groupLabel(policy: Policy, gid: number): string | undefined { + return policy.groupLabels?.[String(gid)]?.label; +} diff --git a/src/sessions.ts b/src/sessions.ts index 080f1eb..2669c9e 100644 --- a/src/sessions.ts +++ b/src/sessions.ts @@ -4,7 +4,7 @@ import { bodyLimit } from "hono/body-limit"; import { decideResource, type Deps, type Env, type ResolvedResource } from "./app.js"; import { matchControlRule, takeReaderKind } from "./control.js"; import { check, type AclEntry, type Op } from "./mode.js"; -import type { Policy } from "./policy.js"; +import { groupLabel, type Policy } from "./policy.js"; import { deny } from "./relaycast.js"; import type { Agent } from "./store.js"; @@ -115,6 +115,8 @@ export function sessionsAtRoot(fetchFn: (req: Request) => Response | Promise(["metadata", "catalog"]); /** A session's effective owner, group, mode and ACL. */ export function resolveSession(id: string, row: { owner: string; gid: number }, policy: Policy): ResolvedResource { @@ -201,6 +203,22 @@ export function mountSessions(app: Hono, deps: Deps, cfg: SessionsConfig): return `${u.pathname.replace(/^\/sessions/, "")}${u.search}`; }; + /** + * The owning group's display label for a session, as `relaygate: {gid, label}` (docs/contract.md, "Group labels"). + * Only for sessions relaygate owns whose group the policy labels; never names the owner. + */ + const annotation = (id: string, policy: Policy): { gid: number; label: string } | undefined => { + const row = store.session(id); + const label = row && groupLabel(policy, row.gid); + return row && label ? { gid: row.gid, label } : undefined; + }; + /** A session object with relaygate's annotation set, and any upstream `relaygate` key dropped (only relaygate says it). */ + const annotate = (s: Record, id: string, policy: Policy): Record => { + const { relaygate: _forged, ...rest } = s; + const a = annotation(id, policy); + return a ? { ...rest, relaygate: a } : rest; + }; + const canRead = (c: Ctx, id: string): boolean => { const row = store.session(id); if (!row) return false; @@ -316,13 +334,28 @@ export function mountSessions(app: Hono, deps: Deps, cfg: SessionsConfig): const res = await upstream(c, cfg.readUrl, "GET", upstreamPath(c)); if (res instanceof Response || res.status !== 200) return pass(res); const page = json(res) ?? {}; - const sessions = (Array.isArray(page.sessions) ? page.sessions : []).filter((s: any) => typeof s?.sessionId === "string" && canRead(c, s.sessionId)); + const policy = deps.policy(); + const sessions = (Array.isArray(page.sessions) ? page.sessions : []) + .filter((s: any) => typeof s?.sessionId === "string" && canRead(c, s.sessionId)) + .map((s: Record) => annotate(s, s.sessionId as string, policy)); audit(c, "session.list", "r", null, "allow", "mode", `filtered:${sessions.length}`); return pass(res, { ...page, sessions }); }); for (const view of READ_VIEWS) { - app.get(`/sessions/v1/sessions/:id/${view}`, async (c) => gateRead(c, c.req.param("id")) ?? pass(await upstream(c, cfg.readUrl, "GET", upstreamPath(c)))); + app.get(`/sessions/v1/sessions/:id/${view}`, async (c) => { + const id = c.req.param("id"); + const refused = gateRead(c, id); + if (refused) return refused; + const res = await upstream(c, cfg.readUrl, "GET", upstreamPath(c)); + if (!LABELED_VIEWS.has(view) || res instanceof Response || res.status !== 200) return pass(res); + // One session's metadata and catalog carry its group label; otherwise the body passes byte for byte. + const body = json(res); + if (!body || typeof body !== "object" || Array.isArray(body)) return pass(res); + const policy = deps.policy(); + if (!("relaygate" in body) && !annotation(id, policy)) return pass(res); + return pass(res, annotate(body, id, policy)); + }); } // Events inside one session (gated), or a workspace transcript search (`q`), filtered to readable sessions. diff --git a/test/admin.test.ts b/test/admin.test.ts index 2317412..0ab7dd4 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -103,6 +103,10 @@ describe("admin API for relay-control (R2)", () => { expect(unknownGid.body).toMatchObject({ ok: false, errors: [{ message: expect.stringContaining("gid 9") }] }); const reserved = await h.call("POST", "/admin/v1/policy/validate", ADMIN, { policy: { groups: [{ gid: 1, name: "a" }], enrollmentKeys: [{ id: "device:u1", gid: 1, sha256: sha256("x") }] } }); expect(reserved.body.ok).toBe(false); + const labels = (groupLabels: unknown) => h.call("POST", "/admin/v1/policy/validate", ADMIN, { policy: { groups: [{ gid: 1, name: "a" }], enrollmentKeys: [], groupLabels } }); + expect((await labels({ "1": { label: "pit", description: "Pit crew" } })).body.ok).toBe(true); + expect((await labels({ "1": { label: "