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
3 changes: 2 additions & 1 deletion docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,8 @@ skip membership checks, so relaygate checks each one itself:
| `POST /v1/channels/:name/leave`, `/mute`, `/unmute` | self |
| `POST /v1/channels/:name/messages` | `w` on the channel (classifier as usual) |
| `GET /v1/messages/:id`, `/replies`, `/reactions`; `POST .../read`; `DELETE .../reactions/:emoji` | `r` on the message's channel; a DM message only for its two participants |
| `POST /v1/messages/:id/replies`, `/reactions` | `w` on the message's channel; refused under a DM (answer with `POST /v1/dm`) |
| `POST /v1/messages/:id/replies` | `w` on the message's channel; under a DM, only a participant, decided as `POST /v1/dm` to the other participant (`w` on `relaycast:inbox/<other>`) |
| `POST /v1/messages/:id/reactions` | `w` on the message's channel; refused under a DM |
| `POST /v1/dm` | `w` on `relaycast:inbox/<to>` |
| `GET /v1/dm/conversations`, `GET /v1/dm/:cid/messages` | the caller's own 1:1 conversations (group DMs aren't proxied) |
| `GET /v1/search`, `GET /v1/inbox` | filtered: channel hits the caller may read, DM hits it wrote |
Expand Down
32 changes: 30 additions & 2 deletions src/relaycast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,23 @@ export function mountRelaycast(app: Hono<Env>, deps: Deps, upstream: RelaycastUp
return res.status === 200;
};

/**
* The other participant of a 1:1 DM the caller is in, from Relaycast's own participant list (GET
* /v1/dm/conversations lists only the caller's conversations, unpaged, with their participants). Undefined when the
* caller isn't in it; an upstream failure is returned as is, so a rate limit or outage isn't mistaken for a refusal.
*/
const dmCounterpart = async (c: Ctx, me: string, conversationId: string | undefined): Promise<string | undefined | UpstreamResponse> => {
if (!conversationId || !DM_ID.test(conversationId)) return undefined;
const res = await forward(c, "GET", "/v1/dm/conversations");
if (res.status !== 200) return res;
const conv = asArray(dataOf(res.body)).find((x) => x.id === conversationId && x.type === "1:1");
if (!conv) return undefined;
const names = asArray(conv.participants).map((p) => p.agent_name).filter((n): n is string => typeof n === "string" && n !== "");
const others = names.filter((n) => n !== me);
// Exactly the caller and one other agent.
return names.includes(me) && others.length === 1 ? others[0] : undefined;
};

const MSG_ID = /^[A-Za-z0-9_-]{1,128}$/;

// --- self ------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -525,10 +542,21 @@ export function mountRelaycast(app: Hono<Env>, deps: Deps, upstream: RelaycastUp
const where = await messageStream(c, messageId);
if ("status" in where) return pass(c, where);
if ("authorOnly" in where) {
// A DM message (or a thread under it) is readable by id only by the two participants. Writes into DM threads
// aren't modelled (which inbox would they go to?), so they are refused; answer with POST /v1/dm.
// A DM message (or a thread under it) is readable by id only by the two participants. A thread reply under a
// DM is a DM to the other participant, so it is decided exactly as POST /v1/dm to them: w on their inbox.
// Other writes into DM threads (reactions) aren't modelled and are refused.
// Reading a DM is reading your own inbox, so the inbox's read bit (and any ceiling) applies too.
const me = c.get("agent").name;
if (op === "w" && action === "thread.reply") {
const other = await dmCounterpart(c, me, where.conversationId);
if (typeof other === "object") return pass(c, other);
if (!other) {
audit(c, action, op, `relaycast:message/${messageId}`, "deny", "mode", "dm_reply_not_participant");
return denied(c, op, `relaycast:message/${messageId}`);
}
const refused = await gateWrite(c, action, inboxStream(other), writeContent(body!));
return refused ?? handler(c, messageId, body);
}
const mine =
op === "r" &&
canRead(deps, c.get("principal"), inboxStream(me)) &&
Expand Down
10 changes: 9 additions & 1 deletion test/fakes/relaycast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function fakeRelaycast() {
const deliveries: Array<Record<string, unknown> & { agent: string }> = [];
const failed: Array<{ id: string; body: unknown }> = [];
let channelsDown = false;
let conversationsDown = false;
const app = new Hono();
const who = (auth: string) => [...agents.entries()].find(([, a]) => `Bearer ${a.token}` === auth)?.[0];
const pairOf = (a: string, b: string) => [a, b].sort().join("~");
Expand Down Expand Up @@ -110,7 +111,13 @@ export function fakeRelaycast() {
const me = who(c.req.header("authorization")!)!;
const ids = new Set(messages.filter((m) => m.channel_id.startsWith("dmch_") && m.channel_id.slice(5).split("~").includes(me)).map((m) => `dm_${m.channel_id.slice(5)}`));
// Shapes as in Relaycast's engine (engine/dm.ts): 1:1 conversations are type "1:1", group DMs "group".
return c.json({ ok: true, data: [...ids].map((id) => ({ id, type: "1:1" })).concat([{ id: "gdm_1", type: "group" }]) });
if (conversationsDown) return c.json({ ok: false, error: { code: "rate_limited" } }, 429, { "retry-after": "7" });
return c.json({
ok: true,
data: [...ids]
.map((id) => ({ id, type: "1:1", participants: id.slice(3).split("~").map((n) => ({ agent_id: `up_${n}`, agent_name: n })) }))
.concat([{ id: "gdm_1", type: "group", participants: [] }]),
});
});
app.get("/v1/search", (c) =>
c.json({
Expand Down Expand Up @@ -157,6 +164,7 @@ export function fakeRelaycast() {
calls,
revokeUpstreamTokens: () => (revokeAll = true),
setChannelsDown: (v: boolean) => (channelsDown = v),
setConversationsDown: (v: boolean) => (conversationsDown = v),
};
}

50 changes: 49 additions & 1 deletion test/relaycast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,58 @@ describe("Relaycast proxy: the pit rules", () => {
expect((await h.call("GET", `/v1/messages/${id}`, pit)).status).toBe(200);
expect((await h.call("GET", `/v1/messages/${id}`, local)).status).toBe(200);
expect((await h.call("GET", `/v1/messages/${id}`, guest)).status).toBe(403);
// Writes into a DM thread aren't modelled.
// A thread reply under the DM is a DM back to local-a: the pit may not write local-a's inbox.
expect((await h.call("POST", `/v1/messages/${id}/replies`, pit, { text: "x" })).status).toBe(403);
});

it("a thread reply under a DM is a DM to the other participant", async () => {
const h = harness();
const a = await h.token(KEYS.local, "local-a");
const b = await h.token(KEYS.local, "local-b");
const c = await h.token(KEYS.local, "local-c");
const pit = await h.token(KEYS.pit, "pit-a");
const lastAudit = () => h.store.recentAudit(1)[0];

// local B answers local A's DM in its thread: decided as w on A's inbox, and forwarded.
const dm = await h.call("POST", "/v1/dm", a, { to: "local-b", text: "ping" });
const id = dm.body.data.message.id;
const reply = await h.call("POST", `/v1/messages/${id}/replies`, b, { text: "pong", from: "local-z" });
expect(reply.status).toBe(201);
expect(lastAudit()).toMatchObject({ action: "thread.reply", decision: "allow", resource_id: "relaycast:inbox/local-a" });
const sent = h.up.calls.filter((x) => x.method === "POST" && x.path === `/v1/messages/${id}/replies`);
expect(sent).toHaveLength(1);
expect(sent[0].body).not.toHaveProperty("from");
expect((sent[0].body as any).data.relaygate.agent).toBe("local-b");
// A, replying under its own message, writes to B's inbox.
expect((await h.call("POST", `/v1/messages/${id}/replies`, a, { text: "again" })).status).toBe(201);
expect(lastAudit()).toMatchObject({ decision: "allow", resource_id: "relaycast:inbox/local-b" });

// Someone outside the conversation can't reply into it, even in the same group.
expect((await h.call("POST", `/v1/messages/${id}/replies`, c, { text: "butting in" })).status).toBe(403);
expect(lastAudit()).toMatchObject({ decision: "deny", reason: "dm_reply_not_participant" });

// A pit agent replying to a local agent's DM is refused by the local inbox's mode.
const toPit = await h.call("POST", "/v1/dm", a, { to: "pit-a", text: "review?" });
expect((await h.call("POST", `/v1/messages/${toPit.body.data.message.id}/replies`, pit, { text: "ok" })).status).toBe(403);
expect(lastAudit()).toMatchObject({ decision: "deny", resource_id: "relaycast:inbox/local-a", reason: "mode:660+acl:22:r:prefix" });
// The sender may follow up under its own DM before the recipient has written anything.
const fresh = await h.call("POST", "/v1/dm", b, { to: "local-c", text: "first" });
expect((await h.call("POST", `/v1/messages/${fresh.body.data.message.id}/replies`, b, { text: "follow-up" })).status).toBe(201);
expect(lastAudit()).toMatchObject({ decision: "allow", resource_id: "relaycast:inbox/local-c" });
// An upstream rate limit on the participant lookup is passed back, not turned into a refusal.
h.up.setConversationsDown(true);
const limited = await h.app.request(`/v1/messages/${id}/replies`, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${b}` },
body: JSON.stringify({ text: "later" }),
});
expect(limited.status).toBe(429);
expect(limited.headers.get("retry-after")).toBe("7");
h.up.setConversationsDown(false);
// Other writes into a DM thread stay unmodelled.
expect((await h.call("POST", `/v1/messages/${id}/reactions`, b, { emoji: "x" })).status).toBe(403);
});

it("filters search, channel lists, the inbox and the agent list", async () => {
const h = harness();
const local = await h.token(KEYS.local, "local-a");
Expand Down
Loading