Public: anyone can read this; the crew can change it.

Mail relay call: child asks parent to send, with from-domain allowlist and per-scope rate limit #17367

opened this

Merged 34h 28m ago, live in production

torque/forge:torque/17335-mail-relay-call-child-asks-parent-to-sen → main 0 commits fork

  • Merged. torque/17335-mail-relay-call-child-asks-parent-to-sen was merged into main as f62ca8c.

Review

Sign in to review this change.
10 files changed +439 −16
src/actions/mail.ts +19 −2
@@ -20,6 +20,7 @@
2020 import type { App } from "../app.ts";
2121 import {
2222 holdSend,
23 sentForScope,
2324 recipientKey,
2425 releaseSend,
2526 sentSince,
@@ -51,15 +52,31 @@ export function mayMail(app: App, to: string, now = Date.now()): boolean {
5152 return sentSince(app.db, from, recipientKey(app.config.dataDir, to)) < RECIPIENT_DAILY;
5253 }
5354
54 /** Send through the caps: "sent", "capped" when a cap holds it, "failed" when the mailer did. */
55 /** What one child may send in a day through this forge's key, on top of the caps above. */
56 export const SCOPE_DAILY = 20;
57
58 /**
59 * Send through the caps: "sent", "capped" when a cap holds it, "failed" when
60 * the mailer did. With `scope` (a child's name, `spawn/mail_relay.ts`) the
61 * message also counts against that scope's own `SCOPE_DAILY`, so a noisy
62 * child spends its own allowance, not its siblings'.
63 */
5564 export async function sendCapped(
5665 app: App,
5766 mailer: Mailer,
5867 mail: Mail,
5968 now = Date.now(),
69 scope = "",
6070 ): Promise<"sent" | "capped" | "failed"> {
71 if (scope !== "" && sentForScope(app.db, since(now), scope) >= SCOPE_DAILY)
72 return "capped";
6173 if (!mayMail(app, mail.to, now)) return "capped";
62 const held = holdSend(app.db, recipientKey(app.config.dataDir, mail.to), new Date(now).toISOString());
74 const held = holdSend(
75 app.db,
76 recipientKey(app.config.dataDir, mail.to),
77 new Date(now).toISOString(),
78 scope,
79 );
6380 const delivered = await mailer(mail).catch(() => false);
6481 if (!delivered) {
6582 releaseSend(app.db, held);
src/actions/verify.ts +4 −1
@@ -21,6 +21,7 @@ import { handoverOwner, spendHandover } from "../core/edge_handover.ts";
2121 import { getUserById, isActive, type User } from "../core/users.ts";
2222 import type { Mailer } from "../kernel/mail.ts";
2323 import { resolveMailKey, sendWithMailKey } from "../core/mail_key.ts";
24 import { hasParent, relayMailer } from "../spawn/mail_relay.ts";
2425 import { mayMail, sendCapped } from "./mail.ts";
2526 import { err, ok, type Result } from "../kernel/result.ts";
2627 import { requireUser } from "./access.ts";
@@ -81,7 +82,9 @@ export function mailerOf(
8182 if (app.config.mailer !== undefined) return app.config.mailer;
8283 // The store's audit names who a read was for: the person mailed.
8384 const who = { ...whose, actor: forUser.id };
84 if (resolveMailKey(app.db, who, app.config.mail) === undefined) return undefined;
85 if (resolveMailKey(app.db, who, app.config.mail) === undefined)
86 // No key here: a forge a parent hosts asks the parent to send (`spawn/mail_relay.ts`).
87 return hasParent(app) ? relayMailer(app) : undefined;
8588 return async (mail) =>
8689 (
8790 await sendWithMailKey(app.db, app.config.dataDir, app.bus, who, mail, app.config.mail)
src/core/mail_key.ts +9 −2
@@ -68,11 +68,18 @@ export async function sendWithMailKey(
6868 who: MailAsker,
6969 mail: Mail,
7070 platform?: MailConfig | undefined,
71 /**
72 * Send as this address instead of the key's own `MAIL_FROM` (a relayed message, already checked
73 * against its allowlist).
74 */
75 asFrom?: string | undefined,
7176 ): Promise<{ scope: MailScope; sent: boolean } | undefined> {
7277 const scope = resolveMailKey(db, who, platform);
7378 if (scope === undefined) return undefined;
7479 if (scope === "platform") {
75 return platform === undefined ? undefined : { scope, sent: await sendMail(platform, mail) };
80 if (platform === undefined) return undefined;
81 const config = asFrom === undefined ? platform : { ...platform, from: asFrom };
82 return { scope, sent: await sendMail(config, mail) };
7683 }
7784 const opened = resolveSecrets(db, dataDir, bus, MAIL_KEY_NAMES, {
7885 actor: who.actor,
@@ -84,5 +91,5 @@ export async function sendWithMailKey(
8491 const url = opened["MAIL_SMTP_URL"];
8592 const from = opened["MAIL_FROM"];
8693 if (url === undefined || from === undefined) return { scope, sent: false };
87 return { scope, sent: await sendMail({ url, from }, mail) };
94 return { scope, sent: await sendMail({ url, from: asFrom ?? from }, mail) };
8895 }
src/core/mail_log.ts +20 −6
@@ -47,13 +47,16 @@ export function recipientKey(dataDir: string, address: string): string {
4747 }
4848
4949 /** Hold a place for a message about to go; returns its row, to release if it fails. */
50 export function holdSend(db: Database, recipient: string, at: string): string {
50 export function holdSend(
51 db: Database,
52 recipient: string,
53 at: string,
54 scope = "",
55 ): string {
5156 const row = id();
52 db.query("INSERT INTO mail_sent (id, recipient, at) VALUES (?1, ?2, ?3)").run(
53 row,
54 recipient,
55 at,
56 );
57 db.query(
58 "INSERT INTO mail_sent (id, recipient, at, scope) VALUES (?1, ?2, ?3, ?4)",
59 ).run(row, recipient, at, scope);
5760 return row;
5861 }
5962
@@ -62,6 +65,17 @@ export function releaseSend(db: Database, row: string): void {
6265 db.query("DELETE FROM mail_sent WHERE id = ?1").run(row);
6366 }
6467
68 /** Messages sent for one requesting scope (a child's name) since `since`. */
69 export function sentForScope(db: Database, since: string, scope: string): number {
70 return (
71 db
72 .query<{ n: number }, [string, string]>(
73 "SELECT COUNT(*) AS n FROM mail_sent WHERE scope = ?1 AND at > ?2",
74 )
75 .get(scope, since)?.n ?? 0
76 );
77 }
78
6579 /** Messages sent since `since`, to anyone or to one recipient. */
6680 export function sentSince(
6781 db: Database,
src/core/migration-pins/20261202000000-mail-relay-scope.pin added +1
@@ -0,0 +1,1 @@
1 fcc1e7ac2dc21161129e2fc392733c38e522e6825f52f41268c8aab4d0de83d2
src/core/migrations/20261202000000-mail-relay-scope.ts added +7
@@ -0,0 +1,7 @@
1 // Mail relay (#17335, part 2 of #15872): each message a parent sends for a child is counted under
2 // the child's scope, so one noisy app spends its own daily allowance. Additive: a column with a
3 // default and one index. (A kept per-child from-domain list is part 3 of #15872, #17336.)
4 export default `
5 ALTER TABLE mail_sent ADD COLUMN scope TEXT NOT NULL DEFAULT '';
6 CREATE INDEX IF NOT EXISTS mail_sent_scope ON mail_sent(scope, at);
7 `;
src/generated/migrations.ts +2
@@ -460,6 +460,7 @@ import m455 from "../core/migrations/20261201190000-working-edit.ts";
460460 import m456 from "../core/migrations/20261201190200-dep-accept.ts";
461461 import m457 from "../core/migrations/20261201190500-runner-machine.ts";
462462 import m458 from "../core/migrations/20261201200000-cloud-projects.ts";
463 import m459 from "../core/migrations/20261202000000-mail-relay-scope.ts";
463464
464465 /** Each migration file's name and its default export, in name order. */
465466 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -922,4 +923,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
922923 ["20261201190200-dep-accept.ts", m456],
923924 ["20261201190500-runner-machine.ts", m457],
924925 ["20261201200000-cloud-projects.ts", m458],
926 ["20261202000000-mail-relay-scope.ts", m459],
925927 ];
src/spawn/beat-door.ts +14 −5
@@ -2,11 +2,12 @@
22 * The one door a cell child has to its parent: a loopback listener that
33 * answers `POST /api/v1/heartbeat`, `POST /api/v1/broker/origins` (a signed ask to
44 * broker an origin sign-in, `spawn/origin_broker.ts`), `POST /api/v1/reach` (a signed ask
5 * to be let through to one more host, `spawn/child_reach.ts`), and the lent model endpoint
6 * (`spawn/model_door.ts`: `POST /v1/messages`, `GET /api/v1/credit`), and nothing else. The child's cell relays
7 * only this port in, so untrusted child code never reaches the parent's web
8 * surface, and since the door never asks who the client is, no forwarding
9 * header it sends counts for anything.
5 * to be let through to one more host, `spawn/child_reach.ts`), `POST /api/v1/mail` (a signed ask to
6 * send a message on this forge's key, `spawn/mail_relay.ts`), and the lent model endpoint
7 * (`spawn/model_door.ts`: `POST /v1/messages`, `GET /api/v1/credit`), and nothing else. The child's
8 * cell relays only this port in, so untrusted child code never reaches the parent's web surface,
9 * and since the door never asks who the client is, no forwarding header it sends counts for
10 * anything.
1011 */
1112
1213 import type { App } from "../app.ts";
@@ -16,6 +17,7 @@ import { beatAnswer, receiveBeat, SIGNATURE_HEADER } from "./heartbeat.ts";
1617 import { answerBrokerCall, CALL_BODY_MAX } from "./origin_broker.ts";
1718 import { BROKER_CALL } from "./origin_broker_wire.ts";
1819 import { answerReachCall, REACH_BODY_MAX, REACH_CALL, type ReachDeps } from "./child_reach.ts";
20 import { answerMailCall, MAIL_BODY_MAX, MAIL_CALL } from "./mail_relay.ts";
1921 import { creditAnswer, lendModel, MODEL_BODY_MAX, type ModelDeps } from "./model_door.ts";
2022
2123 const MAX_BODY = 1024;
@@ -62,6 +64,13 @@ async function answerBeat(app: App, deps: { readonly model?: ModelDeps; readonly
6264 const bytes = await readCapped(req, REACH_BODY_MAX);
6365 return bytes === undefined ? refused : answerReachCall(app, new TextDecoder().decode(bytes), shown, deps.reach);
6466 }
67 if (req.method === "POST" && path === MAIL_CALL) {
68 // Signed and small, like the reach call: no signature, no read.
69 const shown = req.headers.get(SIGNATURE_HEADER);
70 if (shown === null) return refused;
71 const bytes = await readCapped(req, MAIL_BODY_MAX);
72 return bytes === undefined ? refused : answerMailCall(app, new TextDecoder().decode(bytes), shown);
73 }
6574 if (req.method !== "POST" || path !== "/api/v1/heartbeat") return refused;
6675 // A beat is signed and small: no signature, no read; then at most MAX_BODY bytes, counted as they arrive.
6776 const signature = req.headers.get(SIGNATURE_HEADER);
src/spawn/mail_relay.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * The mail relay call (#17335, part 2 of #15872; `docs/MAIL-RELAY.md`). A
3 * child holds no sending key, so it asks its parent to send, over the signed
4 * door it already has (`signed_call.ts`, as `child_reach.ts` does for egress):
5 * `POST /api/v1/mail` on the beat door with `{ to, subject, text, from }`.
6 *
7 * The parent opens its own key (`core/mail_key.ts`) and answers
8 * `{ ok: true, result: "sent" | "capped" | "failed" }`, or `{ ok: false,
9 * error }` for `from_domain` (the `from` is not on the child's allowlist,
10 * default: its own hostname), `bad_message`, `slow_down` or `no_key`. Two
11 * limits hold a relayed message besides the forge's own caps
12 * (`actions/mail.ts`): the from-domain allowlist (a child sends as its own
13 * hostname; a kept list per child is #17336), and `SCOPE_DAILY` messages a
14 * day per child. The key is in neither the call nor the answer.
15 */
16
17 import { existsSync } from "node:fs";
18 import { join } from "node:path";
19 import type { App } from "../app.ts";
20 import { childNamed } from "../actions/spawn.ts";
21 import { sendCapped } from "../actions/mail.ts";
22 import { resolveMailKey, sendWithMailKey } from "../core/mail_key.ts";
23 import type { Mail, Mailer } from "../kernel/mail.ts";
24 import { callParent } from "../origins/broker.ts";
25 import { signedCall } from "./signed_call.ts";
26
27 /** Where a child calls this forge to send mail: on the beat door only. */
28 export const MAIL_CALL = "/api/v1/mail";
29 export const MAIL_BODY_MAX = 16 * 1024;
30 const TEXT_MAX = 8 * 1024;
31 const SUBJECT_MAX = 200;
32 const ADDRESS = /^[^\s<>@,;:"\\]+@([^\s<>@,;:"\\]+)$/;
33 const ONE_LINE = /^[^\r\n]*$/;
34
35 export type RelayResult = "sent" | "capped" | "failed";
36
37 const reply = (body: Record<string, unknown>): Response =>
38 Response.json(body, { headers: { "cache-control": "no-store" } });
39
40 /** The domain of an address in `ADDRESS` form, lowercased; undefined when it is not one. */
41 function domainOf(address: unknown): string | undefined {
42 if (typeof address !== "string" || address.length > 254) return undefined;
43 const m = ADDRESS.exec(address);
44 return m?.[1]?.toLowerCase().replace(/\.$/, "");
45 }
46
47 /**
48 * One signed call from a child: send this message on the key this forge holds.
49 * A bad name, signature or time is a 404; a good one answers 200.
50 */
51 export async function answerMailCall(
52 app: App,
53 raw: string,
54 signature: string | null,
55 now: number = Date.now(),
56 ): Promise<Response> {
57 const call = await signedCall(app, raw, signature, now);
58 if (call === undefined) return new Response("no such door", { status: 404 });
59 const child = await childNamed(app, call.name);
60 if (child === undefined) return new Response("no such door", { status: 404 });
61 const { to, subject, text, from } = call.fields;
62 if (
63 typeof to !== "string" ||
64 domainOf(to) === undefined ||
65 typeof subject !== "string" ||
66 subject.length > SUBJECT_MAX ||
67 !ONE_LINE.test(subject) ||
68 typeof text !== "string" ||
69 text.length > TEXT_MAX
70 )
71 return reply({ ok: false, error: "bad_message" });
72 const fromDomain = domainOf(from);
73 if (typeof from !== "string" || fromDomain === undefined)
74 return reply({ ok: false, error: "bad_message" });
75 let own = "";
76 try {
77 own = new URL(child.url).hostname.toLowerCase();
78 } catch {
79 // a child with no usable address is allowed nothing
80 }
81 if (fromDomain !== own) return reply({ ok: false, error: "from_domain" });
82 const who = { actor: `relay:${child.name}` };
83 if (
84 app.config.mailer === undefined &&
85 resolveMailKey(app.db, who, app.config.mail) === undefined
86 )
87 return reply({ ok: false, error: "no_key" });
88 const mail: Mail = { to, subject, text };
89 const mailer: Mailer =
90 app.config.mailer ??
91 (async (m) => {
92 const done = await sendWithMailKey(
93 app.db,
94 app.config.dataDir,
95 app.bus,
96 who,
97 m,
98 app.config.mail,
99 from,
100 );
101 return done?.sent === true;
102 });
103 const result: RelayResult = await sendCapped(app, mailer, mail, now, child.name);
104 return reply({ ok: true, result });
105 }
106
107 /** Whether this forge is a child that can ask a parent (its `parent.json` exists). */
108 export const hasParent = (app: App): boolean =>
109 existsSync(join(app.config.dataDir, "parent.json"));
110
111 /** The address a child sends as: its own hostname, the default its parent allows. */
112 function ownAddress(app: App): string {
113 let host = "localhost";
114 try {
115 if (app.config.url !== undefined) host = new URL(app.config.url).hostname;
116 } catch {
117 // keep the default
118 }
119 return `forge@${host}`;
120 }
121
122 /** A mailer that asks the parent to send; true only when the parent answered `sent`. */
123 export function relayMailer(
124 app: App,
125 fetcher: (url: string, init?: RequestInit) => Promise<Response> = fetch,
126 ): Mailer {
127 return async (mail) => {
128 const res = await callParent(
129 app,
130 "mail",
131 { to: mail.to, subject: mail.subject, text: mail.text, from: ownAddress(app) },
132 fetcher,
133 15_000,
134 MAIL_CALL,
135 );
136 return res.ok && res.value["result"] === "sent";
137 };
138 }
test/mail-relay.test.ts added +225
@@ -0,0 +1,225 @@
1 /**
2 * The mail relay call (#17335): a child asks its parent to send, on the
3 * signed door. Refused from-domain, refused over the daily limit, and the
4 * key in neither the call nor the answer.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { beatKeyOf, childDirOf, childNamed } from "../src/actions/spawn.ts";
12 import { SCOPE_DAILY } from "../src/actions/mail.ts";
13 import { mailerOf } from "../src/actions/verify.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { sentForScope } from "../src/core/mail_log.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, getUserByName } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import type { Mail } from "../src/kernel/mail.ts";
20 import { openBeatDoor, parentLocal, type BeatDoor } from "../src/spawn/beat-door.ts";
21 import { firstBoot } from "../src/spawn/first-boot.ts";
22 import { answerMailCall, MAIL_BODY_MAX, MAIL_CALL, relayMailer } from "../src/spawn/mail_relay.ts";
23 import { signWith } from "../src/spawn/origin_broker_wire.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 const SECRET_URL = "smtps://user:[email protected]:465";
29 let dir = "";
30 let parent: App;
31 let child: App;
32 let servers: Servers;
33 let door: BeatDoor;
34 let host = "";
35 let sibling: App;
36 let siblingHost = "";
37 const sent: Mail[] = [];
38 const wire: string[] = [];
39
40 /** The child's own door fetch, recording what crosses the wire both ways. */
41 const spy = async (input: string, init?: RequestInit): Promise<Response> => {
42 wire.push(String(init?.body ?? ""));
43 const res = await fetch(input, init);
44 wire.push(await res.clone().text());
45 return res;
46 };
47
48 beforeAll(async () => {
49 dir = await mkdtemp(join(tmpdir(), "forge-mail-relay-"));
50 parent = createApp({
51 dataDir: dir,
52 url: "https://forge.test",
53 port: 0,
54 mailer: async (m) => (sent.push(m), true),
55 mail: { url: SECRET_URL, from: "[email protected]" },
56 });
57 const a = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", isAdmin: true });
58 if (!a.ok) throw new Error("user");
59 const repo = await createRepo(parent, a.value, { name: "bakery" });
60 if (!repo.ok) throw new Error("repo");
61 servers = await serve(parent);
62 door = openBeatDoor(parent);
63 const token = createToken(parent.db, getUserByName(parent.db, "alice")!.id, "rw", "rw").token;
64 const spawnChild = async (name: string): Promise<{ app: App; host: string }> => {
65 const made = await fetch(`${servers.url}/api/v1/forges`, {
66 method: "POST",
67 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
68 body: JSON.stringify({ name, apps: ["alice/bakery"], dryRun: false }),
69 });
70 if (made.status !== 201) throw new Error(`spawn ${made.status}`);
71 const { bodyId } = (await made.json()) as { bodyId: string };
72 const h = new URL((await childNamed(parent, name))!.url).hostname;
73 const app = createApp({ dataDir: childDirOf(parent, bodyId), url: `https://${h}`, port: 0 });
74 await firstBoot(app);
75 const file = join(app.config.dataDir, "parent.json");
76 const doc = JSON.parse(await readFile(file, "utf8"));
77 await writeFile(file, JSON.stringify({ ...doc, upstream: parentLocal(door.port) }));
78 return { app, host: h };
79 };
80 const first = await spawnChild("maria");
81 child = first.app;
82 host = first.host;
83 const second = await spawnChild("carlos");
84 sibling = second.app;
85 siblingHost = second.host;
86 }, 30_000);
87
88 afterAll(async () => {
89 door.close();
90 servers.stop();
91 child.close();
92 sibling.close();
93 parent.close();
94 await rm(dir, { recursive: true, force: true });
95 });
96
97 /** One real signed mail call to the beat door, as `name`, with `fields` over a good message. */
98 const ask = async (fields: Record<string, unknown>, name = "maria"): Promise<Response> => {
99 const raw = JSON.stringify({
100 op: "mail",
101 name,
102 at: Date.now(),
103 to: "[email protected]",
104 subject: "s",
105 text: "t",
106 from: `forge@${name === "maria" ? host : siblingHost}`,
107 ...fields,
108 });
109 const key = (await beatKeyOf(parent, name))!;
110 return fetch(`http://127.0.0.1:${door.port}${MAIL_CALL}`, {
111 method: "POST",
112 headers: { "x-forge-signature": signWith(key, raw) },
113 body: raw,
114 });
115 };
116
117 const mail = (to: string): Mail => ({ to, subject: "Hello", text: "A link: https://x.test/v" });
118
119 test("a child sends through its parent, as its own hostname", async () => {
120 sent.length = 0;
121 const ok = await relayMailer(child, spy)(mail("[email protected]"));
122 expect(ok).toBe(true);
123 expect(sent.map((m) => m.to)).toEqual(["[email protected]"]);
124 expect(sentForScope(parent.db, "1970-01-01", "maria")).toBe(1);
125 });
126
127 test("with no key of its own, a child's mailer is the relay", () => {
128 expect(mailerOf(child, { id: "u" })).toBeDefined();
129 });
130
131 test("a from-domain not on the child's allowlist is refused from_domain, and nothing is sent", async () => {
132 sent.length = 0;
133 const call = (from: string) => ask({ from });
134 const bad = await call("[email protected]");
135 expect(await bad.json()).toEqual({ ok: false, error: "from_domain" });
136 expect(sent).toEqual([]);
137 const good = await call(`forge@${host}`);
138 expect(((await good.json()) as any).result).toBe("sent");
139 });
140
141 test("a child over its daily limit is capped, and a sibling is not", async () => {
142 sent.length = 0;
143 const mailer = relayMailer(child, spy);
144 let last = true;
145 for (let i = 0; i < SCOPE_DAILY + 2; i++) last = await mailer(mail(`p${i}@elsewhere.test`));
146 expect(last).toBe(false);
147 expect(sentForScope(parent.db, "1970-01-01", "maria")).toBe(SCOPE_DAILY);
148 expect(sent.length).toBeLessThan(SCOPE_DAILY);
149 // a second real child, signed under its own name, still has its allowance
150 sent.length = 0;
151 const other = await ask({ to: "[email protected]" }, "carlos");
152 expect(await other.json()).toEqual({ ok: true, result: "sent" });
153 expect(sent.map((m) => m.to)).toEqual(["[email protected]"]);
154 expect(sentForScope(parent.db, "1970-01-01", "carlos")).toBe(1);
155 expect(await relayMailer(sibling, spy)(mail("[email protected]"))).toBe(true);
156 });
157
158 test("a call with a bad signature is a 404", async () => {
159 const raw = JSON.stringify({ op: "mail", name: "maria", at: Date.now() });
160 const res = await fetch(`http://127.0.0.1:${door.port}${MAIL_CALL}`, { method: "POST", headers: { "x-forge-signature": "0".repeat(64) }, body: raw });
161 expect(res.status).toBe(404);
162 });
163
164 test("the key is in neither the call nor the answer", () => {
165 expect(wire.length).toBeGreaterThan(2);
166 for (const w of wire) {
167 expect(w).not.toContain("hunter2");
168 expect(w).not.toContain("smtp.example.com");
169 }
170 });
171
172 test("a message that is not well formed is refused bad_message, and nothing is sent", async () => {
173 sent.length = 0;
174 const bad: Record<string, unknown>[] = [
175 { to: "not-an-address" },
176 { to: 5 },
177 { subject: "one\ntwo" },
178 { subject: "s".repeat(201) },
179 { text: "t".repeat(8 * 1024 + 1) },
180 { from: "no-at-sign" },
181 ];
182 for (const fields of bad)
183 expect(await (await ask(fields)).json()).toEqual({ ok: false, error: "bad_message" });
184 expect(sent).toEqual([]);
185 });
186
187 test("a body past the byte cap never reaches the sender", async () => {
188 sent.length = 0;
189 const big = JSON.stringify({ op: "mail", name: "maria", at: Date.now(), text: "x".repeat(MAIL_BODY_MAX) });
190 const key = (await beatKeyOf(parent, "maria"))!;
191 const res = await fetch(`http://127.0.0.1:${door.port}${MAIL_CALL}`, {
192 method: "POST",
193 headers: { "x-forge-signature": signWith(key, big) },
194 body: big,
195 });
196 expect(res.status).not.toBe(200);
197 expect(sent).toEqual([]);
198 });
199
200 test("a parent with no key of any scope answers no_key", async () => {
201 const { mailer: _m, mail: _k, ...bare } = parent.config;
202 const keyless: App = { ...parent, config: bare };
203 const raw = JSON.stringify({
204 op: "mail",
205 name: "carlos",
206 at: Date.now(),
207 to: "[email protected]",
208 subject: "s",
209 text: "t",
210 from: `forge@${siblingHost}`,
211 });
212 const key = (await beatKeyOf(parent, "carlos"))!;
213 const res = await answerMailCall(keyless, raw, signWith(key, raw));
214 expect(await res.json()).toEqual({ ok: false, error: "no_key" });
215 });
216
217 test("a forge with no parent and no key has no mailer", async () => {
218 const lone = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-mail-lone-")), port: 0 });
219 try {
220 expect(mailerOf(lone, { id: "u" })).toBeUndefined();
221 } finally {
222 lone.close();
223 await rm(lone.config.dataDir, { recursive: true, force: true });
224 }
225 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs