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
22 changes: 21 additions & 1 deletion docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,26 @@ 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.

### The agent directory

Who appears in `GET /v1/agents` (and `GET /v1/agents/:name`) is, by default,
the agents a caller could message or whose inbox it may read. To let a group
see agents beyond that, without any right to message them, the operator grants
`r` on their directory entries, `relaycast:agent/<name>`. Only `r` is ever
checked on an entry: it shows the agent's name, status, persona and card, and
nothing else (DMs still need `w` on `relaycast:inbox/<name>`). For example, the
pit sees every agent on the relay while local agents' view is unchanged:

```
"streamDefaults": [{"prefix": "relaycast:agent/", "gid": 22, "mode": "040"}, ...]
```

Entries are operator policy only: an override for the exact id, or a prefix
default that itself starts with `relaycast:agent/`. A broader default (such as
`relaycast:`) and registered stream rows never count, and `PUT
/v1/streams/{id}` refuses every `relaycast:agent/` id, so an agent can't show
itself, or anyone else, to another group. Ceilings apply as usual.

### Registering streams and prefix defaults

The owning component registers a stream with its `gid`, `mode` and `classify`.
Expand Down Expand Up @@ -500,7 +520,7 @@ skip membership checks, so relaygate checks each one itself:
| Route | Check |
|---|---|
| `GET /v1/agent`, `POST /v1/agents/heartbeat`, `/disconnect` | self |
| `GET /v1/agents`, `GET /v1/agents/:name` | answered with the workspace key, filtered to agents whose inbox the caller may write or read |
| `GET /v1/agents`, `GET /v1/agents/:name` | answered with the workspace key, filtered to agents whose inbox the caller may write or read, or whose directory entry `relaycast:agent/<name>` it may read |
| `GET /v1/channels` | filtered to channels the caller may read |
| `POST /v1/channels` | `w` on `relaycast:channel/<name>` |
| `GET /v1/channels/:name`, `/messages`; `POST .../join` | `r` on the channel |
Expand Down
4 changes: 3 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono, type Context } from "hono";
import { z } from "zod";
import { ClassifierUnavailable, type Classifier } from "./classifier.js";
import { allGroups, check, inGroup, type AclEntry, type Guarded, type Op, type Principal } from "./mode.js";
import { deny as proxyDeny, mountRelaycast, type RelaycastUpstream } from "./relaycast.js";
import { AGENT_ENTRY_PREFIX, deny as proxyDeny, mountRelaycast, type RelaycastUpstream } from "./relaycast.js";
import { mountNodeToken } from "./realtime.js";
import { adoptSessions, mountSessions, sessionsCors, type SessionsConfig } from "./sessions.js";
import { ControlUnavailable, controlPrincipal, controlTokenKind, matchControlRule, type ControlAuth } from "./control.js";
Expand Down Expand Up @@ -657,6 +657,8 @@ export function createApp(deps: Deps) {
return deny(c, 403, "relaygate_denied", { op: "w", resource: id });
};
if (policy.streamOverrides.some((o) => o.id === id)) return refuse("operator_override");
// Agent directory entries are operator policy: an agent registering one could show any agent to any group.
if (id.startsWith(AGENT_ENTRY_PREFIX)) return refuse("agent_directory_operator_only");
if (!inGroup(principal, gid)) return refuse("gid_not_own_group");
const prefix = longestPrefix(id, policy);
if (!prefix || !inGroup(principal, prefix.gid)) return refuse("prefix_not_own_group");
Expand Down
33 changes: 30 additions & 3 deletions src/relaycast.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Context, Hono } from "hono";
import { decide, provenance, resolveStream, type Deps, type Env } from "./app.js";
import { decide, longestPrefix, provenance, resolveStream, type Deps, type Env, type ResolvedStream } from "./app.js";
import { check, type Op, type Principal } from "./mode.js";
import type { Policy } from "./policy.js";
import type { Agent, SecretBox, Store } from "./store.js";

/**
Expand Down Expand Up @@ -172,6 +173,28 @@ const dataOf = (body: unknown): unknown => (body && typeof body === "object" &&

export const channelStream = (name: string) => `relaycast:channel/${name}`;
export const inboxStream = (agentName: string) => `relaycast:inbox/${agentName}`;
/**
* An agent's entry in the agent directory (GET /v1/agents, /v1/agents/:name). Only `r` is ever checked on it: it
* lets a group see the agent (name, status, persona, card) without any right to message it or read its inbox.
* Operator policy only: agents can't register these ids (PUT /v1/streams refuses them).
*/
export const AGENT_ENTRY_PREFIX = "relaycast:agent/";
export const agentEntry = (agentName: string) => `${AGENT_ENTRY_PREFIX}${agentName}`;

/**
* An agent's directory entry, from operator policy only: an override for the exact id, else the longest prefix
* default under `relaycast:agent/`. Registered stream rows never count (an agent could have registered one before
* PUT /v1/streams refused these ids), and neither does a broader default such as `relaycast:`, so visibility only
* widens when the operator writes a directory rule.
*/
export function directoryEntry(agentName: string, policy: Policy): ResolvedStream | undefined {
const id = agentEntry(agentName);
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 prefix = longestPrefix(id, policy);
if (!prefix || !prefix.prefix.startsWith(AGENT_ENTRY_PREFIX)) return undefined;
return { id, owner: null, gid: prefix.gid, mode: prefix.mode, classify: prefix.classify, acl: prefix.acl, source: "prefix" };
}

/** Relaycast stores DMs as hidden channels named dm-<pair>; they are never addressed as channels through relaygate. */
export const isDmChannelName = (name: string) => name.startsWith("dm-") || name.startsWith("dmch_");
Expand Down Expand Up @@ -318,14 +341,18 @@ export function mountRelaycast(app: Hono<Env>, deps: Deps, upstream: RelaycastUp
app.post("/v1/agents/disconnect", async (c) => pass(c, await forward(c, "POST", "/v1/agents/disconnect", (await jsonBody(c)) ?? {})));

// --- agents (Relaycast refuses agent tokens here; relaygate answers with the workspace key, filtered) -------
// An agent sees the agents it could message or whose inbox it may read, and nothing else.
// An agent sees the agents it could message, whose inbox it may read, or whose directory entry
// (relaycast:agent/<name>) it may read, and nothing else.
const visibleAgent = (c: Ctx, name: unknown) => {
if (typeof name !== "string") return false;
if (name === c.get("agent").name) return true;
const principal = c.get("principal");
const ceilings = deps.policy().ceilings;
// 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());
if (!stream) return false;
const ceilings = deps.policy().ceilings;
return check(principal, stream, "w", ceilings).allowed || check(principal, stream, "r", ceilings).allowed;
};
app.get("/v1/agents", async (c) => {
Expand Down
76 changes: 71 additions & 5 deletions test/relaycast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ import { RelaycastUpstream } from "../src/relaycast.js";
import { SecretBox, sha256, Store } from "../src/store.js";
import { fakeRelaycast, WORKSPACE_KEY } from "./fakes/relaycast.js";

const KEYS = { local: "enroll-local-0000000000000000", pit: "enroll-pit-00000000000000000000", guest: "enroll-guest-0000000000000000000" };

function policy(): Policy {
const KEYS = {
local: "enroll-local-0000000000000000",
pit: "enroll-pit-00000000000000000000",
guest: "enroll-guest-0000000000000000000",
editor: "enroll-editor-000000000000000000",
};

function policy(extraDefaults: Array<Record<string, unknown>> = []): Policy {
return parsePolicy({
groups: [
{ gid: 11, name: "local" },
Expand All @@ -25,6 +30,8 @@ function policy(): Policy {
{ id: "local", gid: 11, sha256: sha256(KEYS.local), namePrefix: "local-" },
{ id: "pit", gid: 22, sha256: sha256(KEYS.pit), namePrefix: "pit-" },
{ id: "vendor", gid: 44, sha256: sha256(KEYS.guest), namePrefix: "guest-", guest: true, expiresAt: "2099-01-01T00:00:00Z" },
// A local agent whose inbox no default covers (an editor agent named after its person).
{ id: "editor", gid: 11, sha256: sha256(KEYS.editor), namePrefix: "editor-" },
],
streamDefaults: [
{ prefix: "relaycast:channel/", gid: 11, mode: "660", acl: [{ gid: 22, perm: "r" }] },
Expand All @@ -33,16 +40,21 @@ function policy(): Policy {
{ prefix: "relaycast:inbox/local-", gid: 11, mode: "660", acl: [{ gid: 22, perm: "r" }] },
{ prefix: "relaycast:inbox/pit-", gid: 22, mode: "660", acl: [{ gid: 11, perm: "w" }] },
{ prefix: "relaycast:inbox/guest-", gid: 44, mode: "660", acl: [{ gid: 11, perm: "w" }] },
...extraDefaults,
],
ceilings: [{ gid: 44, never: [22] }],
classifier: { rules: [{ id: "ssn", pattern: "\\b\\d{3}-\\d{2}-\\d{4}\\b" }] },
});
}

function harness(model: Classifier = { classify: async () => ({ decision: "allow", reason: "ok" }) }, url = "http://relaycast.test") {
function harness(
model: Classifier = { classify: async () => ({ decision: "allow", reason: "ok" }) },
url = "http://relaycast.test",
extraDefaults: Array<Record<string, unknown>> = [],
) {
const store = new Store(":memory:");
const upstreamFake = fakeRelaycast();
const pol = policy();
const pol = policy(extraDefaults);
const relaycast = new RelaycastUpstream({ url, workspaceKey: WORKSPACE_KEY, box: new SecretBox("s".repeat(32)), fetch: upstreamFake.fetchFn }, store);
const classifier = new ChainClassifier([new RuleClassifier(pol.classifier.rules), model]);
const deps: Deps = { store, policy: () => pol, classifier: () => classifier, relaycast };
Expand Down Expand Up @@ -283,6 +295,60 @@ describe("Relaycast proxy: the pit rules", () => {
expect((await h.call("GET", "/v1/agents/pit-a", guest)).status).toBe(404);
});

it("r on an agent's directory entry (relaycast:agent/<name>) shows it, and grants nothing else", async () => {
const names = async (h: ReturnType<typeof harness>, token: string) =>
(await h.call("GET", "/v1/agents", token)).body.data.map((a: any) => a.name).sort();
// Without a directory grant, an agent whose inbox no default covers is invisible to the pit.
const before = harness();
const pit0 = await before.token(KEYS.pit, "pit-a");
await before.token(KEYS.editor, "editor-dana");
expect(await names(before, pit0)).not.toContain("editor-dana");
expect((await before.call("GET", "/v1/agents/editor-dana", pit0)).status).toBe(404);

// The pit (22) sees every agent: group read on the whole directory, nothing for anyone else.
const h = harness(undefined, undefined, [{ prefix: "relaycast:agent/", gid: 22, mode: "040" }]);
const local = await h.token(KEYS.local, "local-a");
const pit = await h.token(KEYS.pit, "pit-a");
const guest = await h.token(KEYS.guest, "guest-a");
await h.token(KEYS.editor, "editor-dana");
expect(await names(h, pit)).toEqual(["editor-dana", "guest-a", "local-a", "pit-a"]);
expect((await h.call("GET", "/v1/agents/editor-dana", pit)).status).toBe(200);
// Seeing is not messaging: the editor's inbox stays closed to the pit, and so does a local one.
expect((await h.call("POST", "/v1/dm", pit, { to: "editor-dana", text: "hi" })).status).toBe(403);
expect((await h.call("POST", "/v1/dm", pit, { to: "local-a", text: "hi" })).status).toBe(403);
// Other groups see exactly what they saw before.
expect(await names(h, local)).toEqual(["guest-a", "local-a", "pit-a"]);
expect(await names(h, guest)).toEqual(["guest-a"]);
// Agents can't register directory entries to show themselves (or anyone) to another group.
expect((await h.call("PUT", `/v1/streams/${encodeURIComponent("relaycast:agent/pit-a")}`, pit, { mode: "666" })).status).toBe(403);
});

it("only a directory rule widens visibility: a broader default or a registered row never does", async () => {
// A broad relaycast: default that would allow r doesn't count for directory entries (inboxes keep their own rule).
const broad = harness(undefined, undefined, [
{ prefix: "relaycast:", gid: 22, mode: "040" },
{ prefix: "relaycast:inbox/", gid: 11, mode: "660" },
]);
const pit = await broad.token(KEYS.pit, "pit-a");
await broad.token(KEYS.editor, "editor-dana");
expect((await broad.call("GET", "/v1/agents", pit)).body.data.map((a: any) => a.name)).not.toContain("editor-dana");
expect((await broad.call("GET", "/v1/agents/editor-dana", pit)).status).toBe(404);

// A stream row registered for a directory id (before registration was refused) is ignored.
const legacy = harness();
const pit2 = await legacy.token(KEYS.pit, "pit-a");
await legacy.token(KEYS.editor, "editor-dana");
legacy.store.putStream({ id: "relaycast:agent/editor-dana", owner: legacy.store.agentByName("pit-a")!.id, gid: 22, mode: "666", classify: false, acl: [] });
expect((await legacy.call("GET", "/v1/agents/editor-dana", pit2)).status).toBe(404);

// An exact operator override does count.
const exact = harness();
exact.deps.policy().streamOverrides.push({ id: "relaycast:agent/editor-dana", gid: 22, mode: "040", classify: false, acl: [] } as never);
const pit3 = await exact.token(KEYS.pit, "pit-a");
await exact.token(KEYS.editor, "editor-dana");
expect((await exact.call("GET", "/v1/agents/editor-dana", pit3)).status).toBe(200);
});

it("lists only 1:1 DM conversations", async () => {
const h = harness();
const local = await h.token(KEYS.local, "local-a");
Expand Down
Loading