Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
38 changes: 36 additions & 2 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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=<id>` | one `session`, `r` on it |
| `GET /sessions/v1/events?q=<text>` | transcript search, filtered to events of sessions the caller may read |

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions examples/policy.pit.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
{"gid": 22, "mode": "660"}
],
"sessionOverrides": [],
"groupLabels": {"22": {"label": "pit", "description": "Agents inside the boundary"}},
"ceilings": [
{"gid": 44, "never": [22]}
],
Expand Down
24 changes: 24 additions & 0 deletions src/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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(", ")}`);
Expand Down Expand Up @@ -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;
}
39 changes: 36 additions & 3 deletions src/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -115,6 +115,8 @@ export function sessionsAtRoot(fetchFn: (req: Request) => Response | Promise<Res

const SESSION_ID = /^[A-Za-z0-9._:@-]{1,256}$/;
const READ_VIEWS = ["events", "turns", "metadata", "thread", "catalog", "timing", "analysis", "brief", "summary"] as const;
/** Single-session views that describe the session itself, so they carry its group label (docs/contract.md, "Group labels"). */
const LABELED_VIEWS = new Set<string>(["metadata", "catalog"]);

/** A session's effective owner, group, mode and ACL. */
export function resolveSession(id: string, row: { owner: string; gid: number }, policy: Policy): ResolvedResource {
Expand Down Expand Up @@ -201,6 +203,22 @@ export function mountSessions(app: Hono<Env>, 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<string, unknown>, id: string, policy: Policy): Record<string, unknown> => {
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;
Expand Down Expand Up @@ -316,13 +334,28 @@ export function mountSessions(app: Hono<Env>, 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<string, unknown>) => 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.
Expand Down
4 changes: 4 additions & 0 deletions test/admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<script>" } })).body).toMatchObject({ ok: false, errors: [{ path: "groupLabels.1.label" }] });
expect((await labels({ "2": { label: "b" } })).body).toMatchObject({ ok: false, errors: [{ message: expect.stringContaining("groupLabels (gid 2)") }] });
expect((await h.call("POST", "/admin/v1/policy/validate", ADMIN, {})).status).toBe(400);
expect((await h.call("POST", "/admin/v1/policy/validate", "rg_nope", { policy: h.p })).status).toBe(401);
});
Expand Down
48 changes: 47 additions & 1 deletion test/sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import { sha256, Store } from "../src/store.js";
const KEYS = { local: "enroll-local-0000000000000000", pit: "enroll-pit-00000000000000000000", guest: "enroll-guest-0000000000000000000" };
const SERVICE = "rth_st_service";

function policy(shared: string[] = [], mistaken: string[] = [], writable: string[] = []) {
function policy(shared: string[] = [], mistaken: string[] = [], writable: string[] = [], extra: Record<string, unknown> = {}) {
return parsePolicy({
...extra,
groups: [
{ gid: 11, name: "local" },
{ gid: 22, name: "pit" },
Expand Down Expand Up @@ -56,6 +57,8 @@ function harness(pol = policy(), opts: { token?: string } = { token: SERVICE })
upstream.post("/v1/ingest", (c) => c.json({ received: 1 }));
upstream.get("/v1/sessions", (c) => c.json({ sessions: [{ sessionId: "s-local" }, { sessionId: "s-pit" }, { sessionId: "s-elsewhere" }], nextCursor: "c2" }));
upstream.get("/v1/sessions/:id/events", (c) => c.json({ events: [{ sessionId: c.req.param("id") }] }));
upstream.get("/v1/sessions/:id/metadata", (c) => c.text(`{"sessionId":"${c.req.param("id")}", "title":"t"}`, 200, { "content-type": "application/json" }));
upstream.get("/v1/sessions/:id/catalog", (c) => c.json({ catalog: { title: "t" }, parents: [], children: [], relaygate: { gid: 33, label: "forged" } }));
upstream.get("/v1/events", (c) =>
c.json({ events: c.req.query("q") ? [{ sessionId: "s-local", text: "a" }, { sessionId: "s-pit", text: "b" }, { text: "no session" }] : [] }),
);
Expand Down Expand Up @@ -177,6 +180,49 @@ describe("Sessions proxy: reads", () => {
});
});

describe("Sessions proxy: group labels", () => {
const labeled = () => policy([], [], [], { groupLabels: { "22": { label: "pit", description: "Pit crew" } } });

it("labels each readable session its labeled group owns, and only those", async () => {
const w = await world(labeled());
const pit = (await w.call("GET", "/sessions/v1/sessions?limit=10", w.pit)).body;
expect(pit.sessions).toEqual([{ sessionId: "s-local" }, { sessionId: "s-pit", relaygate: { gid: 22, label: "pit" } }]);
expect(pit.nextCursor).toBe("c2");
// A local agent never sees the pit session, so it never sees the label either.
expect((await w.call("GET", "/sessions/v1/sessions", w.local)).body.sessions).toEqual([{ sessionId: "s-local" }]);
});

it("labels one session's metadata and catalog; other views and unlabeled sessions pass byte for byte", async () => {
const w = await world(labeled());
expect((await w.call("GET", "/sessions/v1/sessions/s-pit/metadata", w.pit)).body).toEqual({ sessionId: "s-pit", title: "t", relaygate: { gid: 22, label: "pit" } });
const raw = await w.app.request("/sessions/v1/sessions/s-local/metadata", { headers: { authorization: `Bearer ${w.pit}` } });
expect(await raw.text()).toBe('{"sessionId":"s-local", "title":"t"}');
// A relaygate key from upstream is never passed on as if relaygate said it.
expect((await w.call("GET", "/sessions/v1/sessions/s-pit/catalog", w.pit)).body.relaygate).toEqual({ gid: 22, label: "pit" });
expect((await w.call("GET", "/sessions/v1/sessions/s-local/catalog", w.pit)).body).not.toHaveProperty("relaygate");
expect((await w.call("GET", "/sessions/v1/sessions/s-pit/events", w.pit)).body).toEqual({ events: [{ sessionId: "s-pit" }] });
expect((await w.call("GET", "/sessions/v1/sessions/s-pit/metadata", w.local)).status).toBe(403);
});

it("without groupLabels nothing is labeled", async () => {
const w = await world();
expect((await w.call("GET", "/sessions/v1/sessions", w.pit)).body.sessions).toEqual([{ sessionId: "s-local" }, { sessionId: "s-pit" }]);
expect((await w.call("GET", "/sessions/v1/sessions/s-pit/metadata", w.pit)).body).not.toHaveProperty("relaygate");
});

it("validates labels: known groups, short plain text", () => {
const base = { groups: [{ gid: 22, name: "pit" }], enrollmentKeys: [] };
expect(parsePolicy({ ...base, groupLabels: { "22": { label: "pit" } } }).groupLabels).toEqual({ "22": { label: "pit" } });
expect(parsePolicy(base).groupLabels).toBeUndefined();
expect(() => parsePolicy({ ...base, groupLabels: { "33": { label: "admins" } } })).toThrow(/groupLabels \(gid 33\)/);
for (const label of ["", " pit", "pit ", "x".repeat(25), "<b>pit</b>", "pit\n"]) {
expect(() => parsePolicy({ ...base, groupLabels: { "22": { label } } })).toThrow();
}
expect(() => parsePolicy({ ...base, groupLabels: { "022": { label: "pit" } } })).toThrow();
expect(() => parsePolicy({ ...base, groupLabels: { "22": { label: "pit", color: "red" } } })).toThrow();
});
});

describe("Sessions proxy: review regressions", () => {
it("a failed first upload keeps the session with its uploader, who can retry; no one else gets it", async () => {
const w = await world();
Expand Down
Loading