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

"Send mail from this AWS account" makes the SES identity, its DKIM records and the mail key in order, once #18210

opened this

Closed 7h 37m ago

scout/forge:scout/18135-send-mail-from-this-aws-account-makes-th → main 11 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +706 −16
docs/design/audit.md +1
@@ -189,6 +189,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
189189 - `/settings/passkeys` — `pages/passkeys.ts` · my passkeys · `/settings/password` · none seen.
190190 - `/settings/confirms` — `pages/confirms.ts` · what the forge's agent asked to do and waits for my yes · the terminal's Confirms (y) · none seen.
191191 - `/settings/secrets` — `pages/secrets.ts` · secrets apps may read · none · none seen.
192 - `/settings/secrets/aws-mail` — `pages/secrets.ts` (`awsMailPage`) · send mail from this AWS account: the SES identity, its DKIM records and the mail key, in order · `/settings/secrets` · none seen.
192193 - `/settings/subscriptions` — `pages/subscriptions.ts` (624 lines) · the model subscriptions the crew spends from, with spend tables (`pages/spend.ts`) · `/board/returns` · none seen.
193194 - `/settings/accounts` — `pages/accounts.ts` · every account on the forge · `/settings/people` · none seen.
194195 - `/settings/people` — `pages/people.ts` · people and their roles · `/settings/accounts`, `/settings/crew` · none seen.
docs/features/aws-mail.md added +19
@@ -0,0 +1,19 @@
1 ---
2 topic: Every setting, by topic
3 row: Send mail from this AWS account: SES identity, DKIM records and the mail key, in order, once
4 ---
5 # Send mail from this AWS account
6
7 One confirm makes, in order, an SES identity for a sending subdomain with DKIM, its three DKIM
8 CNAME records in the Cloudflare account the forge holds, then a send-only IAM user
9 (`forge-mail-send`, `ses:SendRawEmail` from that identity alone) whose SMTP credential is sealed
10 as the forge's mail key. The secret is never shown. A second run makes nothing new: what stands is
11 kept, and once the forge holds a mail key no second access key is made. Needs an AWS account and
12 a Cloudflare account that allow writes.
13
14 - **Page**: Settings → Secrets → "Send mail from this AWS account"
15 (`/settings/secrets/aws-mail`, `src/web/pages/secrets.ts`): name the subdomain, read the plan, confirm.
16 - **Terminal** (`src/tui/screens/secrets.ts`): `w`, the subdomain, then the same plan to confirm
17 (when one account of each kind allows writes; with more, use the page).
18 - The steps are `src/cloud/ses_setup.ts`, the action `src/actions/ses_setup.ts`;
19 `test/ses-setup.test.ts` runs it against a recorded AWS and Cloudflare.
src/actions/dns_record.ts +1 −1
@@ -20,7 +20,7 @@ import { net } from "./pinned.ts";
2020 * Open `account`'s (`cloudflare/<name>`) token and hand `go` a gated fetch; the token stays in this
2121 * scope.
2222 */
23 async function withCloudflare<T>(app: App, actor: User | undefined, account: string, writes: boolean, purpose: string, go: (f: typeof fetch, token: string) => Promise<T>): Promise<Result<T, string>> {
23 export async function withCloudflare<T>(app: App, actor: User | undefined, account: string, writes: boolean, purpose: string, go: (f: typeof fetch, token: string) => Promise<T>): Promise<Result<T, string>> {
2424 const name = account.startsWith("cloudflare/") ? account.slice("cloudflare/".length) : "";
2525 const a = name === "" ? undefined : getCloudAccount(app.db, "cloudflare", name);
2626 if (a === undefined) return err(NO_ACCOUNT);
src/actions/ses_setup.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * "Send mail from this AWS account" (#18135), the action behind the secrets page and the terminal:
3 * an admin names the AWS account (writes allowed), the Cloudflare account that holds the DNS, and a
4 * sending subdomain; `cloud/ses_setup.ts` makes the identity, the DKIM records and the mail key in
5 * that order. Both tokens are opened for this one run, every call goes through the audited, gated
6 * fetch, and the SMTP credential goes from AWS's answer to the sealed store without being returned.
7 */
8
9 import type { App } from "../app.ts";
10 import { awsKey } from "../cloud/aws_call.ts";
11 import { accountCall } from "../cloud/aws_read.ts";
12 import { gatedFetch } from "../cloud/gate.ts";
13 import { sesInputWords, setupSes, upsertCname, type SesRun } from "../cloud/ses_setup.ts";
14 import { getCloudAccount, listCloudAccounts, NO_ACCOUNT, READ_ONLY, secretNameOf } from "../core/cloud_account.ts";
15 import { resolveMailKey } from "../core/mail_key.ts";
16 import { resolveSecrets } from "../core/secret_store.ts";
17 import type { User } from "../core/users.ts";
18 import { err, type Result } from "../kernel/result.ts";
19 import { withCloudflare } from "./dns_record.ts";
20 import { net } from "./pinned.ts";
21 import { setMailKey } from "./secrets.ts";
22
23 /** The names of the accounts that can do this: AWS ones and Cloudflare ones that allow writes. */
24 export function mailAccounts(app: App): { readonly aws: readonly string[]; readonly dns: readonly string[] } {
25 const named = (provider: string): string[] => listCloudAccounts(app.db).filter((a) => a.provider === provider && a.writeAllowed).map((a) => a.name);
26 return { aws: named("aws"), dns: named("cloudflare") };
27 }
28
29 interface SesAsk {
30 readonly aws: string;
31 readonly dns: string;
32 readonly domain: string;
33 readonly region: string;
34 }
35
36 /**
37 * Make the sending subdomain ready and seal the forge's mail key; a second run makes nothing new.
38 */
39 export async function sendMailFromAws(app: App, actor: User | undefined, ask: SesAsk): Promise<Result<SesRun, string>> {
40 if (actor?.isAdmin !== true) return err("not_found");
41 const bad = sesInputWords(ask.domain, ask.region);
42 if (bad !== undefined) return err(bad);
43 const account = getCloudAccount(app.db, "aws", ask.aws);
44 if (account === undefined) return err(NO_ACCOUNT);
45 if (!account.writeAllowed) return err(READ_ONLY);
46 const secret = secretNameOf("aws", ask.aws);
47 const value = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: actor.id, run: "mail:ses" })[secret];
48 const key = value === undefined ? undefined : awsKey(value);
49 if (key === undefined) return err("The AWS credential is not ACCESS_KEY_ID:SECRET_ACCESS_KEY.");
50 const f = gatedFetch(app.db, { provider: "aws", account: ask.aws }, "mail:ses", net.fetch) as typeof fetch;
51 const call = accountCall(f, key, true);
52 return withCloudflare(app, actor, `cloudflare/${ask.dns}`, true, "ses-dkim", (cf, token) =>
53 setupSes(
54 {
55 call,
56 cname: (host, target) => upsertCname(cf, token, host, target),
57 keyHeld: () => resolveMailKey(app.db, {}) === "forge",
58 seal: (url, from) => setMailKey(app, actor, "forge", "", url, from).ok,
59 },
60 ask.domain,
61 ask.region,
62 ),
63 );
64 }
src/cloud/aws_call.ts +21 −9
@@ -43,9 +43,9 @@ const READS = /^(Describe|List|Get)[A-Z][A-Za-z]*$/;
4343
4444 /**
4545 * The only writes: mail setup and its undo. Exact `service:Operation`; a write not here is refused.
46 * SES's own writes (CreateEmailIdentity, PutAccountDetails, DeleteEmailIdentity) are REST in SES v2
47 * (`POST /v2/email/identities` and so on), which this transport cannot sign yet (GET and POST
48 * only); they are listed here when it can, not before. IAM is the query protocol and is real.
46 * SES v2 is REST: CreateEmailIdentity is `POST /v2/email/identities` with a JSON body (`post`,
47 * `operation`), held to that one path and one domain name (#18135). The others (PutAccountDetails,
48 * DeleteEmailIdentity) are listed when something calls them. IAM is the query protocol.
4949 */
5050 const WRITES: ReadonlySet<string> = new Set([
5151 "iam:CreateUser",
@@ -54,6 +54,7 @@ const WRITES: ReadonlySet<string> = new Set([
5454 "iam:DeleteUser",
5555 "iam:DeleteUserPolicy",
5656 "iam:DeleteAccessKey",
57 "ses:CreateEmailIdentity",
5758 ]);
5859
5960 /** The send-only user's policy: ses:SendRawEmail from the one identity, nothing else. */
@@ -82,7 +83,8 @@ function sendOnly(doc: string | undefined): boolean {
8283 export type AwsAsk =
8384 | { readonly action: string; readonly version: string; readonly params?: Readonly<Record<string, string>> }
8485 | { readonly target: string; readonly json: "1.0" | "1.1"; readonly body: unknown }
85 | { readonly path: string; readonly query?: Readonly<Record<string, string>> };
86 | { readonly path: string; readonly query?: Readonly<Record<string, string>>; readonly post?: undefined; readonly operation?: undefined }
87 | { readonly path: string; readonly post: unknown; readonly operation: string; readonly query?: undefined }
8688
8789 /** AWS answered, and refused: its status and its own code for why ("UnauthorizedOperation"). */
8890 export class AwsRefused extends Error {
@@ -118,18 +120,26 @@ function codeOf(text: string): string {
118120 */
119121 export async function awsCall(f: Fetch, key: AwsKey, service: AwsService, region: string, ask: AwsAsk, writes = false): Promise<string> {
120122 if (!AWS_REGION.test(region)) throw new Error("not an AWS region");
121 const operation = "action" in ask ? ask.action : "target" in ask ? (ask.target.split(".").at(-1) ?? "") : "GetRest";
122 if (!READS.test(operation)) {
123 const posts = "path" in ask && ask.post !== undefined;
124 const operation = "action" in ask ? ask.action : "target" in ask ? (ask.target.split(".").at(-1) ?? "") : posts ? ask.operation : "GetRest";
125 // A POST to a path is never a read, whatever its operation is called: it must be a listed write.
126 if (posts || !READS.test(operation)) {
123127 if (!WRITES.has(`${service}:${operation}`)) throw new Error(`${operation} is not a read: the forge only reads AWS`);
124128 if (!writes) throw new Error(`${operation} is a write: this AWS account is read-only`);
125129 if (service === "iam" && operation === "PutUserPolicy" && !("action" in ask && sendOnly(ask.params?.["PolicyDocument"])))
126130 throw new Error("PutUserPolicy allows only ses:SendRawEmail from one identity");
127131 }
132 if (posts) {
133 const b = ask.post;
134 const domain = typeof b === "object" && b !== null && Object.keys(b).length === 1 ? (b as { EmailIdentity?: unknown }).EmailIdentity : undefined;
135 if (service !== "ses" || operation !== "CreateEmailIdentity" || ask.path !== "/v2/email/identities" || typeof domain !== "string" || !/^[a-z0-9.-]{3,253}$/.test(domain))
136 throw new Error("CreateEmailIdentity makes one identity, named by a domain");
137 }
128138 if (service === "iam" && region !== "us-east-1") throw new Error("iam is signed for us-east-1 only");
129139 const host = HOST[service](region);
130140 const form = "action" in ask ? queryText({ ...ask.params, Action: ask.action, Version: ask.version }) : "";
131141 const r = {
132 method: "path" in ask ? ("GET" as const) : ("POST" as const),
142 method: "path" in ask && !posts ? ("GET" as const) : ("POST" as const),
133143 host,
134144 path: "path" in ask ? ask.path : "/",
135145 query: "path" in ask ? (ask.query ?? {}) : {},
@@ -138,8 +148,10 @@ export async function awsCall(f: Fetch, key: AwsKey, service: AwsService, region
138148 ? { "content-type": "application/x-www-form-urlencoded" }
139149 : "target" in ask
140150 ? { "content-type": `application/x-amz-json-${ask.json}`, "x-amz-target": ask.target }
141 : {},
142 body: "target" in ask ? JSON.stringify(ask.body) : form,
151 : posts
152 ? { "content-type": "application/json" }
153 : {},
154 body: "target" in ask ? JSON.stringify(ask.body) : posts ? JSON.stringify(ask.post) : form,
143155 service,
144156 region,
145157 };
src/cloud/ses_setup.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * "Send mail from this AWS account" (#18135): one sending subdomain made ready in order — the SES
3 * identity with DKIM, its three DKIM CNAME records in the DNS account the forge holds, then the
4 * send-only IAM user whose SMTP credential is sealed as the forge's mail key. Every call is passed
5 * in (`SesDeps`), so a recorded AWS and DNS drive it in a test; this module opens nothing and
6 * seals through `seal`. Asking twice makes nothing new: an identity that stands is kept, a record
7 * that reads right is kept, and once the forge holds a mail key no second access key is made. The
8 * secret access key is turned into the SMTP password here and goes straight to `seal`; it is in no
9 * step, no error and no log.
10 */
11
12 import { createHmac } from "node:crypto";
13 import { AwsRefused, sendOnlyPolicy, type AwsAsk } from "./aws_call.ts";
14 import { at, items, parseXml, val } from "./aws_xml.ts";
15 import { cloudflare, CF_ID, zoneOf, type Fetch } from "./providers.ts";
16
17 /** What setup needs of the world. */
18 interface SesDeps {
19 readonly call: (service: "ses" | "iam" | "sts", region: string, ask: AwsAsk) => Promise<string>;
20 /** Make or keep one CNAME record; "made", "kept", or a sentence for why not. */
21 readonly cname: (host: string, value: string) => Promise<"made" | "kept" | { readonly why: string }>;
22 /** Whether the forge already holds a mail key. */
23 readonly keyHeld: () => boolean;
24 /** Seal the pair as the forge's mail key. */
25 readonly seal: (url: string, from: string) => boolean;
26 }
27
28 interface SesStep {
29 readonly what: string;
30 readonly done: "made" | "kept";
31 }
32 export type SesRun = { readonly ok: true; readonly steps: readonly SesStep[] } | { readonly ok: false; readonly why: string; readonly steps: readonly SesStep[] };
33
34 const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
35 const DOMAIN = new RegExp(`^(?=.{4,200}$)${LABEL}(?:\\.${LABEL}){2,}$`);
36 const SES_REGION = /^[a-z]{2}(-[a-z]+){1,3}-\d{1,2}$/;
37 const USER = "forge-mail-send";
38 const POLICY = "send-from-one-identity";
39 const HOME = "us-east-1";
40
41 /** Why a sending subdomain or region cannot be used, in a sentence; undefined when it can. */
42 export function sesInputWords(domain: string, region: string): string | undefined {
43 if (!DOMAIN.test(domain)) return "A sending subdomain is a name like mail.example.com, under a domain you own.";
44 if (!SES_REGION.test(region)) return "An AWS region reads like us-east-1.";
45 return undefined;
46 }
47
48 /** What confirming will make, in order, one sentence each: the page and the terminal show these. */
49 export const sesPlanWords = (domain: string, region: string): readonly string[] => [
50 `An Amazon SES identity for ${domain} in ${region}, with DKIM.`,
51 `Its three DKIM CNAME records, in the DNS account this forge already holds.`,
52 `The IAM user ${USER}, allowed only to send from that identity, and its SMTP credential, sealed as this forge's mail key (sent as forge@${domain}). The secret is never shown.`,
53 ];
54
55 /** The SMTP password AWS derives from an IAM secret access key (signature v4, `SendRawEmail`). */
56 export function smtpPassword(secret: string, region: string): string {
57 const h = (k: Buffer | string, s: string): Buffer => createHmac("sha256", k).update(s).digest();
58 const key = h(h(h(h(`AWS4${secret}`, "11111111"), region), "ses"), "aws4_request");
59 return Buffer.concat([Buffer.from([4]), h(key, "SendRawEmail")]).toString("base64");
60 }
61
62 const refusedAs = (e: unknown, code: string): boolean => e instanceof AwsRefused && e.code === code;
63 const failure = (e: unknown): string => (e instanceof AwsRefused ? e.message : e instanceof Error ? e.message.slice(0, 120) : "failed");
64
65 const iam = (action: string, params: Record<string, string>): AwsAsk => ({ action, version: "2010-05-08", params });
66
67 export async function setupSes(deps: SesDeps, domain: string, region: string): Promise<SesRun> {
68 const steps: SesStep[] = [];
69 const stop = (why: string): SesRun => ({ ok: false, why, steps });
70 const bad = sesInputWords(domain, region);
71 if (bad !== undefined) return stop(bad);
72 try {
73 // 1. The identity.
74 const path = `/v2/email/identities/${domain}`;
75 let said: string;
76 try {
77 said = await deps.call("ses", region, { path });
78 steps.push({ what: `SES identity ${domain}`, done: "kept" });
79 } catch (e) {
80 if (!(e instanceof AwsRefused && e.status === 404)) throw e;
81 said = await deps.call("ses", region, { path: "/v2/email/identities", post: { EmailIdentity: domain }, operation: "CreateEmailIdentity" });
82 steps.push({ what: `SES identity ${domain}`, done: "made" });
83 }
84 const tokens = ((JSON.parse(said) as { DkimAttributes?: { Tokens?: unknown } }).DkimAttributes?.Tokens ?? []) as unknown[];
85 if (!Array.isArray(tokens) || tokens.length === 0 || !tokens.every((t) => typeof t === "string" && /^[a-z0-9]{10,64}$/.test(t)))
86 return stop(`SES gave ${domain} no DKIM tokens: this identity does not use Easy DKIM.`);
87 // 2. The records.
88 for (const t of tokens as string[]) {
89 const made = await deps.cname(`${t}._domainkey.${domain}`, `${t}.dkim.amazonses.com`);
90 if (typeof made !== "string") return stop(made.why);
91 steps.push({ what: `DNS CNAME ${t.slice(0, 6)}…._domainkey.${domain}`, done: made });
92 }
93 // 3. The key.
94 if (deps.keyHeld()) {
95 steps.push({ what: `the forge's mail key (made earlier; its policy covers only the identity it was made for, which may not be ${domain})`, done: "kept" });
96 return { ok: true, steps };
97 }
98 const who = await deps.call("sts", HOME, { action: "GetCallerIdentity", version: "2011-06-15" });
99 const account = val(parseXml(who), "GetCallerIdentityResult/Account");
100 if (!/^\d{12}$/.test(account)) return stop("AWS did not say which account this is.");
101 try {
102 await deps.call("iam", HOME, iam("CreateUser", { UserName: USER }));
103 steps.push({ what: `IAM user ${USER}`, done: "made" });
104 } catch (e) {
105 if (!refusedAs(e, "EntityAlreadyExists")) throw e;
106 steps.push({ what: `IAM user ${USER}`, done: "kept" });
107 }
108 await deps.call("iam", HOME, iam("PutUserPolicy", { UserName: USER, PolicyName: POLICY, PolicyDocument: sendOnlyPolicy(`arn:aws:ses:${region}:${account}:identity/${domain}`) }));
109 // IAM allows two keys per user. At that limit the keys are leftovers of a run whose secret was
110 // lost (the secret is shown once), so they are removed to let this one make its own.
111 const held = items(parseXml(await deps.call("iam", HOME, iam("ListAccessKeys", { UserName: USER }))), "ListAccessKeysResult/AccessKeyMetadata").map((k) => val(k, "AccessKeyId"));
112 if (held.length >= 2) for (const AccessKeyId of held) await deps.call("iam", HOME, iam("DeleteAccessKey", { UserName: USER, AccessKeyId }));
113 const made = parseXml(await deps.call("iam", HOME, iam("CreateAccessKey", { UserName: USER })));
114 const id = val(made, "CreateAccessKeyResult/AccessKey/AccessKeyId");
115 const secret = val(made, "CreateAccessKeyResult/AccessKey/SecretAccessKey");
116 if (!at(made, "CreateAccessKeyResult") || id === "" || secret === "") return stop("AWS made an access key but did not hand it over whole.");
117 const url = `smtps://${encodeURIComponent(id)}:${encodeURIComponent(smtpPassword(secret, region))}@email-smtp.${region}.amazonaws.com:465`;
118 const drop = (): Promise<string> => deps.call("iam", HOME, iam("DeleteAccessKey", { UserName: USER, AccessKeyId: id }));
119 // Another run (a double click, the terminal) may have sealed while this one waited on AWS.
120 if (deps.keyHeld()) {
121 await drop();
122 steps.push({ what: "the forge's mail key (another run sealed it first)", done: "kept" });
123 return { ok: true, steps };
124 }
125 if (!deps.seal(url, `forge@${domain}`)) {
126 await drop().catch(() => "");
127 return stop("The mail key could not be sealed; the access key just made was removed.");
128 }
129 steps.push({ what: "the forge's mail key (the secret is not shown)", done: "made" });
130 return { ok: true, steps };
131 } catch (e) {
132 return stop(failure(e));
133 }
134 }
135
136 /**
137 * A CNAME at Cloudflare: kept when one reads right, changed when the name has another, made
138 * otherwise. DNS only, never proxied. A sentence when it cannot be.
139 */
140 export async function upsertCname(f: Fetch, token: string, host: string, target: string): Promise<"made" | "kept" | { readonly why: string }> {
141 const no = (why: string): { why: string } => ({ why: why.split(token).join("…").slice(0, 160) });
142 try {
143 const zone = await zoneOf(f, token, host);
144 if (typeof zone === "string") return no(zone);
145 const found = await cloudflare(f, token, "GET", `/zones/${zone.id}/dns_records?name=${encodeURIComponent(host)}&per_page=20`);
146 if (found.status !== 200) return no(`Cloudflare answered ${found.status} listing the records of ${zone.name}`);
147 const rows: { id?: unknown; type?: unknown; content?: unknown; proxied?: unknown }[] = found.body?.result ?? [];
148 if (rows.some((r) => r?.type !== "CNAME")) return no(`${host} already has a record that is not a CNAME`);
149 const mine = rows[0];
150 if (mine !== undefined && !CF_ID.test(String(mine.id))) return no("Cloudflare gave a record without an id");
151 if (mine !== undefined && mine.content === target && mine.proxied === false) return "kept";
152 const body = { type: "CNAME", name: host, content: target, ttl: 300, proxied: false, comment: "DKIM for Amazon SES, written by the forge" };
153 const r = mine === undefined ? await cloudflare(f, token, "POST", `/zones/${zone.id}/dns_records`, body) : await cloudflare(f, token, "PATCH", `/zones/${zone.id}/dns_records/${String(mine.id)}`, body);
154 if (r.status === 401 || r.status === 403) return no(`the token cannot edit DNS records in ${zone.name}`);
155 return r.status === 200 || r.status === 201 ? "made" : no(`Cloudflare answered ${r.status} writing ${host}`);
156 } catch (e) {
157 return no(`Cloudflare could not be reached: ${e instanceof Error ? e.message : "failed"}`);
158 }
159 }
160
161 /** What a run came to, in a sentence: each step "made" or "kept", then why it stopped if it did. */
162 export function runWords(r: SesRun): string {
163 const done = r.steps.map((s) => `${s.what}: ${s.done}`).join("; ");
164 return r.ok ? (r.steps.every((s) => s.done === "kept") ? `Nothing new to make. ${done}.` : `${done}.`) : `${done === "" ? "" : `${done}. `}Stopped: ${r.why}`;
165 }
src/http/lazy_lists.ts +2
@@ -96,6 +96,8 @@ export const SETTINGS_ROUTES = [
9696 ["GET", "/settings/secrets"],
9797 ["POST", "/settings/secrets"],
9898 ["POST", "/settings/secrets/delete"],
99 ["GET", "/settings/secrets/aws-mail"],
100 ["POST", "/settings/secrets/aws-mail"],
99101 ["GET", "/settings/devices"],
100102 ["POST", "/settings/devices"],
101103 ["POST", "/settings/devices/delete"],
src/http/marks/settings.json +1
@@ -69,6 +69,7 @@
6969 "/settings/subscriptions/:id/budget": "admin",
7070 "/settings/secrets": "admin",
7171 "/settings/secrets/delete": "admin",
72 "/settings/secrets/aws-mail": "admin",
7273 "/settings/devices": "admin",
7374 "/settings/devices/delete": "admin",
7475 "/settings/devices/grant": "admin",
src/http/settings_routes.ts +3 −1
@@ -53,7 +53,7 @@ import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-setting
5353 import { featureAccept, featurePage, featureRun, featureSave, featuresPage, featureSwitch } from "../web/pages/features.ts";
5454 import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts";
5555 import { deviceCap, deviceDeclare, deviceGrant, devicesPage, deviceRemove, deviceRevoke } from "../web/settings/devices.ts";
56 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
56 import { awsMailPage, awsMailSet, secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
5757 import {
5858 backupsClear,
5959 backupsDestination,
@@ -250,6 +250,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
250250 router.add("GET", "/settings/secrets", secretsPage);
251251 router.add("POST", "/settings/secrets", secretSet);
252252 router.add("POST", "/settings/secrets/delete", secretDelete);
253 router.add("GET", "/settings/secrets/aws-mail", awsMailPage);
254 router.add("POST", "/settings/secrets/aws-mail", awsMailSet);
253255 router.add("GET", "/settings/devices", devicesPage);
254256 router.add("POST", "/settings/devices", deviceDeclare);
255257 router.add("POST", "/settings/devices/delete", deviceRemove);
src/tui/screens/aws_mail.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * "Send mail from this AWS account" in the terminal (#18135), reached by `w` on the secrets
3 * screen: the sending subdomain, then the same plan the page shows (`sesPlanWords`) to confirm,
4 * then the run (`actions/ses_setup.ts`) and what it came to in one line. With more than one AWS or
5 * Cloudflare account that allows writes the page is where to choose.
6 */
7
8 import { mailAccounts, sendMailFromAws } from "../../actions/ses_setup.ts";
9 import { runWords, sesInputWords, sesPlanWords } from "../../cloud/ses_setup.ts";
10 import type { Ctx, Screen } from "../app/app.ts";
11 import type { Session } from "../session.ts";
12 import { confirmScreen, later, promptScreen } from "./common.ts";
13
14 const REGION = "us-east-1";
15
16 /** Begin the flow over `parent`; `note` is told what to say on the parent's top line. */
17 export function startAwsMail(f: Session, ctx: Ctx, parent: Screen, note: (text: string) => void): void {
18 const accounts = mailAccounts(f.app);
19 if (accounts.aws.length === 0 || accounts.dns.length === 0)
20 return note("Attach an AWS account and a Cloudflare account that allow writes first.");
21 if (accounts.aws.length !== 1 || accounts.dns.length !== 1)
22 return note("More than one account allows writes: pick them on the page, /settings/secrets/aws-mail.");
23 const [aws, dns] = [accounts.aws[0]!, accounts.dns[0]!];
24 ctx.push(
25 promptScreen(ctx, parent, {
26 title: "Send mail from this AWS account",
27 label: "sending subdomain, like mail.example.com",
28 onSubmit: (raw) => {
29 const domain = raw.trim().toLowerCase();
30 const bad = sesInputWords(domain, REGION);
31 if (bad !== undefined) return bad;
32 return later(ctx, () =>
33 confirmScreen(ctx, parent, {
34 title: "Make these, in order?",
35 body: [...sesPlanWords(domain, REGION), `AWS account ${aws}, DNS at ${dns}. Asking again makes nothing new.`],
36 actions: [
37 { label: "Make them", variant: "default" },
38 { label: "Cancel", variant: "ghost" },
39 ],
40 selected: 1,
41 onChoose: (choice) => {
42 if (choice !== 0) return;
43 note("Working…");
44 void sendMailFromAws(f.app, f.user, { aws, dns, domain, region: REGION }).then((done) => note(done.ok ? runWords(done.value) : done.error));
45 },
46 }),
47 );
48 },
49 }),
50 );
51 }
src/tui/screens/secrets.ts +6
@@ -17,6 +17,7 @@ import { truncate } from "../term/width.ts";
1717 import type { Session } from "../session.ts";
1818 import { fill, len, split } from "../ui/layout.ts";
1919 import { confirmScreen, drawList, later, ListState, promptScreen } from "./common.ts";
20 import { startAwsMail } from "./aws_mail.ts";
2021 import type { PaletteEntry } from "./entries.ts";
2122
2223 /** The action's refusals in this screen's words. */
@@ -68,6 +69,7 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen {
6869 binding(["s"], "other place"),
6970 binding(["m"], "set mail key here"),
7071 binding(["u"], "remove mail key here"),
72 binding(["w"], "send mail from an AWS account"),
7173 binding(["esc"], "back"),
7274 ],
7375 render(area, s) {
@@ -174,6 +176,10 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen {
174176 ),
175177 }),
176178 );
179 else if (e.key === "w") startAwsMail(f, ctx, screen, (text) => {
180 note = text;
181 ctx.invalidate();
182 });
177183 else if (e.key === "u")
178184 ctx.push(
179185 confirmScreen(ctx, screen, {
src/web/pages/secrets.ts +83 −2
@@ -9,6 +9,8 @@
99
1010 import { sshOn } from "../../settings/ssh.ts";
1111 import type { SecretUse } from "../../core/app_secrets.ts";
12 import { mailAccounts, sendMailFromAws } from "../../actions/ses_setup.ts";
13 import { runWords, sesInputWords, sesPlanWords } from "../../cloud/ses_setup.ts";
1214 import { listSecrets, mailKeyLine, putSecret, removeSecret, secretUses } from "../../actions/secrets.ts";
1315 import type { Ctx } from "../../http/context.ts";
1416 import {
@@ -21,11 +23,11 @@ import {
2123 type SecretName,
2224 type SecretScope,
2325 } from "../../core/secret_store.ts";
24 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
26 import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
2527 import { field, readForm } from "../form.ts";
2628 import { html, when, type Html } from "../html.ts";
2729 import { flashTo, page } from "../layout.ts";
28 import { btn, row, time } from "../ui.ts";
30 import { btn, row, rowList, time } from "../ui.ts";
2931 import { accountSections } from "./origins.ts";
3032
3133 const ERRORS: Record<string, string> = {
@@ -98,6 +100,7 @@ export function secretsCard(
98100 return html`<section class="settings-block">
99101 <h2>Secrets</h2>
100102 <p class="muted small">Sealed values the forge hands to a run by name; the narrowest place wins.${mailLine === undefined ? "" : html` ${mailLine}`}</p>
103 ${scope === "forge" ? html`<p class="small"><a href="/settings/secrets/aws-mail">Send mail from this AWS account</a></p>` : ""}
101104 ${when(
102105 rows.length > 0,
103106 () =>
@@ -236,3 +239,81 @@ export async function secretDelete(ctx: Ctx): Promise<Response> {
236239 },
237240 );
238241 }
242
243 const REGION_DEFAULT = "us-east-1";
244
245 /** A select of account names; the one name alone is just chosen. */
246 const accountSelect = (name: string, label: string, names: readonly string[], chosen: string): Html =>
247 html`<label class="small">${label}
248 <select class="input" name="${name}" required>
249 ${names.map((n) => html`<option value="${n}"${n === chosen ? " selected" : ""}>${n}</option>`)}
250 </select>
251 </label>`;
252
253 // GET /settings/secrets/aws-mail: what will be made, and one button that makes it
254 export function awsMailPage(ctx: Ctx): Response {
255 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
256 const denied = requireAdmin(ctx);
257 if (denied) return denied;
258 const q = ctx.url.searchParams;
259 const domain = (q.get("domain") ?? "").trim().toLowerCase();
260 const region = (q.get("region") ?? REGION_DEFAULT).trim();
261 const accounts = timePhase(ctx.request, "accounts", () => mailAccounts(ctx.app));
262 const bad = domain === "" ? undefined : sesInputWords(domain, region);
263 const ready = domain !== "" && bad === undefined;
264 const missing =
265 accounts.aws.length === 0
266 ? "Attach an AWS account that allows writes first (Cloud accounts)."
267 : accounts.dns.length === 0
268 ? "Attach a Cloudflare account that allows writes first: it holds the DNS for the DKIM records."
269 : undefined;
270 const body =
271 missing !== undefined
272 ? html`<p class="muted">${missing}</p>`
273 : html`<form class="edit-row mt" method="get" action="/settings/secrets/aws-mail">
274 <input class="input" type="text" name="domain" value="${domain}" placeholder="mail.example.com" aria-label="Sending subdomain" autocomplete="off" spellcheck="false" required />
275 <input class="input" type="text" name="region" value="${region}" aria-label="AWS region" autocomplete="off" spellcheck="false" required />
276 ${btn("Show what will be made", { size: "sm" })}
277 </form>
278 ${when(bad !== undefined, () => html`<p class="muted small">${bad ?? ""}</p>`)}
279 ${when(
280 ready,
281 () => html`<section class="settings-block">
282 <h2>This will make, in order</h2>
283 ${rowList(sesPlanWords(domain, region).map((w) => row({ title: w })), { bare: true })}
284 <p class="muted small">Asking again makes nothing new.</p>
285 <form class="edit-row" method="post" action="/settings/secrets/aws-mail">
286 <input type="hidden" name="domain" value="${domain}" />
287 <input type="hidden" name="region" value="${region}" />
288 ${accountSelect("aws", "AWS account", accounts.aws, accounts.aws[0] ?? "")}
289 ${accountSelect("dns", "DNS account (Cloudflare)", accounts.dns, accounts.dns[0] ?? "")}
290 ${btn("Make them", { variant: "primary", size: "sm" })}
291 </form>
292 </section>`,
293 )}`;
294 const rendering = performance.now();
295 const response = page({
296 ctx,
297 title: "Send mail from this AWS account",
298 body: html`${pageHead("Send mail from this AWS account", { sub: "Makes the SES identity, its DKIM records and this forge's mail key, in that order." })}
299 ${settingsLayout(accountSections("secrets", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
300 });
301 notePhase(ctx.request, "render", performance.now() - rendering);
302 return response;
303 }
304
305 // POST /settings/secrets/aws-mail
306 export async function awsMailSet(ctx: Ctx): Promise<Response> {
307 const denied = requireAdmin(ctx);
308 if (denied) return denied;
309 const form = await readForm(ctx, "admin");
310 if (form instanceof Response) return form;
311 const done = await sendMailFromAws(ctx.app, ctx.auth.user, {
312 aws: field(form, "aws"),
313 dns: field(form, "dns"),
314 domain: field(form, "domain").trim().toLowerCase(),
315 region: field(form, "region").trim(),
316 });
317 const failed = !done.ok || !done.value.ok;
318 return flashTo(ctx, "/settings/secrets", failed ? { tone: "danger", message: done.ok ? runWords(done.value) : done.error } : { message: runWords(done.value) });
319 }
test/aws-writes.test.ts +18 −3
@@ -32,9 +32,24 @@ describe("named writes", () => {
3232 await expect(awsCall(never, KEY, service, "us-east-1", ask, false)).rejects.toThrow("read-only");
3333 });
3434 }
35 test("SES writes are not listed until REST can send them", async () => {
36 const ses = { target: "SimpleEmailService.CreateEmailIdentity", json: "1.1" as const, body: {} };
37 await expect(awsCall(never, KEY, "ses", "us-east-1", ses, true)).rejects.toThrow("CreateEmailIdentity is not a read");
35 test("CreateEmailIdentity is one POST to the identities path, for one domain, on a writable account", async () => {
36 const make = (post: unknown, path = "/v2/email/identities") => ({ path, post, operation: "CreateEmailIdentity" });
37 let seen: { url: string; method: string; body: string } | undefined;
38 const spy = async (url: string, init?: RequestInit): Promise<Response> => {
39 seen = { url, method: String(init?.method), body: String(init?.body) };
40 return new Response("{}");
41 };
42 await awsCall(spy, KEY, "ses", "us-east-1", make({ EmailIdentity: "mail.example.com" }), true);
43 expect(seen).toEqual({ url: "https://email.us-east-1.amazonaws.com/v2/email/identities", method: "POST", body: '{"EmailIdentity":"mail.example.com"}' });
44 await expect(awsCall(never, KEY, "ses", "us-east-1", make({ EmailIdentity: "mail.example.com" }))).rejects.toThrow("read-only");
45 for (const bad of [make({ EmailIdentity: "[email protected]" }), make({ EmailIdentity: "x.example.com", Tags: [] }), make({ EmailIdentity: "x.example.com" }, "/v2/email/account")])
46 await expect(awsCall(never, KEY, "ses", "us-east-1", bad, true)).rejects.toThrow("one identity");
47 });
48 test("a POST is a listed write whatever its operation is called", async () => {
49 const post = { path: "/v2/email/identities", post: { EmailIdentity: "mail.example.com" }, operation: "ListFoo" };
50 await expect(awsCall(never, KEY, "ses", "us-east-1", post)).rejects.toThrow("not a read");
51 await expect(awsCall(never, KEY, "ses", "us-east-1", post, true)).rejects.toThrow("not a read");
52 await expect(awsCall(never, KEY, "s3", "us-east-1", { path: "/x", post: {}, operation: "GetThing" }, true)).rejects.toThrow("not a read");
3853 });
3954 test("iam is signed for us-east-1 only", async () => {
4055 await expect(awsCall(never, KEY, "iam", "eu-west-1", iam("CreateUser"), true)).rejects.toThrow("us-east-1");
test/ses-setup.test.ts added +271
@@ -0,0 +1,271 @@
1 /**
2 * "Send mail from this AWS account" (#18135) against a recorded AWS and Cloudflare: the identity,
3 * the DKIM records and the mail key are made in that order, a second run makes nothing new, and
4 * neither the SMTP password, the secret access key nor the DNS token is in a step, an error, the
5 * page or a log line.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { net } from "../src/actions/pinned.ts";
14 import { mailAccounts, sendMailFromAws } from "../src/actions/ses_setup.ts";
15 import { resolveMailKey } from "../src/core/mail_key.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { resolveSecrets, setSecret } from "../src/core/secret_store.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { runWords, setupSes, smtpPassword } from "../src/cloud/ses_setup.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { createForgeApp } from "../src/tui/forge.ts";
22 import { secretsScreen } from "../src/tui/screens/secrets.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
24 import { settleApp } from "./helpers/tui.ts";
25 import { pollUntil } from "./helpers/poll.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const SECRET_KEY = "wJalrXUtnFEMI-K7MDENG-bPxRfiCYEXAMPLEKEY";
31 const CF_TOKEN = "cf-token-plantedvalue-91";
32 const ZONE = "a".repeat(32);
33 const TOKENS = ["abcdefghij1", "klmnopqrst2", "uvwxyzabcd3"];
34 const DOMAIN = "mail.example.com";
35
36 let dir = "";
37 let app: App;
38 let servers: Servers;
39 let admin: User;
40 const log: string[] = [];
41 const said: string[] = [];
42 /** What the recorded AWS holds now. */
43 const aws = { identity: false, user: false, keys: 0, stale: 0 };
44 /** The recorded Cloudflare's CNAME records by name. */
45 const records = new Map<string, string>();
46
47 const xml = (body: string): Response => new Response(body);
48 async function recorded(url: string | URL | Request, init?: RequestInit): Promise<Response> {
49 const u = new URL(String(url));
50 const method = init?.method ?? "GET";
51 const body = String(init?.body ?? "");
52 const track = (s: string): void => void log.push(s);
53 if (u.host === "api.cloudflare.com") {
54 expect((init?.headers as Record<string, string>).authorization).toBe(`Bearer ${CF_TOKEN}`);
55 if (u.pathname === "/client/v4/zones") return Response.json({ result: u.searchParams.get("name") === "example.com" ? [{ id: ZONE, name: "example.com" }] : [] });
56 if (u.pathname === `/client/v4/zones/${ZONE}/dns_records` && method === "GET") {
57 const name = u.searchParams.get("name") ?? "";
58 return Response.json({ result: records.has(name) ? [{ id: "b".repeat(32), type: "CNAME", name, content: records.get(name), proxied: false }] : [] });
59 }
60 if (u.pathname === `/client/v4/zones/${ZONE}/dns_records` && method === "POST") {
61 const b = JSON.parse(body) as { name: string; content: string; type: string };
62 expect(b.type).toBe("CNAME");
63 records.set(b.name, b.content);
64 track(`dns ${b.name}`);
65 return Response.json({ result: { id: "b".repeat(32) } });
66 }
67 return new Response("{}", { status: 404 });
68 }
69 if (u.host === `email.us-east-1.amazonaws.com`) {
70 if (u.pathname === `/v2/email/identities/${DOMAIN}` && method === "GET")
71 return aws.identity ? Response.json({ DkimAttributes: { Tokens: TOKENS } }) : new Response('{"__type":"NotFoundException"}', { status: 404 });
72 if (u.pathname === "/v2/email/identities" && method === "POST") {
73 expect(JSON.parse(body)).toEqual({ EmailIdentity: DOMAIN });
74 aws.identity = true;
75 track("identity");
76 return Response.json({ DkimAttributes: { Tokens: TOKENS } });
77 }
78 }
79 if (u.host === "sts.amazonaws.com") return xml("<GetCallerIdentityResponse><GetCallerIdentityResult><Account>123456789012</Account></GetCallerIdentityResult></GetCallerIdentityResponse>");
80 if (u.host === "iam.amazonaws.com") {
81 const action = new URLSearchParams(body).get("Action");
82 if (action === "CreateUser") {
83 if (aws.user) return new Response("<ErrorResponse><Error><Code>EntityAlreadyExists</Code></Error></ErrorResponse>", { status: 409 });
84 aws.user = true;
85 track("user");
86 return xml("<CreateUserResponse><CreateUserResult/></CreateUserResponse>");
87 }
88 if (action === "PutUserPolicy") {
89 expect(new URLSearchParams(body).get("PolicyDocument")).toContain(`arn:aws:ses:us-east-1:123456789012:identity/${DOMAIN}`);
90 track("policy");
91 return xml("<PutUserPolicyResponse/>");
92 }
93 if (action === "ListAccessKeys") return xml(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata>${"<member><AccessKeyId>AKIAOLD</AccessKeyId></member>".repeat(aws.stale)}</AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`);
94 if (action === "DeleteAccessKey") {
95 track(`delete ${new URLSearchParams(body).get("AccessKeyId")}`);
96 return xml("<DeleteAccessKeyResponse/>");
97 }
98 if (action === "CreateAccessKey") {
99 aws.keys++;
100 track("key");
101 return xml(`<CreateAccessKeyResponse><CreateAccessKeyResult><AccessKey><AccessKeyId>AKIASENDONLY</AccessKeyId><SecretAccessKey>${SECRET_KEY}</SecretAccessKey></AccessKey></CreateAccessKeyResult></CreateAccessKeyResponse>`);
102 }
103 }
104 return new Response("{}", { status: 404 });
105 }
106
107 const ask = { aws: "main", dns: "dns", domain: DOMAIN, region: "us-east-1" };
108
109 beforeAll(async () => {
110 dir = mkdtempSync(join(tmpdir(), "forge-ses-"));
111 app = createApp({ dataDir: dir, port: 0 });
112 servers = await serve(app);
113 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
114 if (!made.ok) throw new Error(made.error);
115 admin = made.value;
116 app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('aws', 'main', '', 1)");
117 app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('cloudflare', 'dns', '', 1)");
118 app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('aws', 'ro', '', 0)");
119 setSecret(app.db, dir, "forge", "", "CLOUD_AWS_MAIN", `AKIAFORGE:${SECRET_KEY}x`);
120 setSecret(app.db, dir, "forge", "", "CLOUD_CLOUDFLARE_DNS", CF_TOKEN);
121 net.fetch = recorded as typeof net.fetch;
122 });
123 afterAll(async () => {
124 servers.stop();
125 app.close();
126 await rm(dir, { recursive: true, force: true });
127 });
128
129 describe("send mail from this AWS account", () => {
130 test("makes the identity, the records, then the key, in that order", async () => {
131 expect(resolveMailKey(app.db, {})).toBeUndefined();
132 const done = await sendMailFromAws(app, admin, ask);
133 if (!done.ok || !done.value.ok) throw new Error("not made");
134 said.push(runWords(done.value));
135 expect(log).toEqual(["identity", ...TOKENS.map((t) => `dns ${t}._domainkey.${DOMAIN}`), "user", "policy", "key"]);
136 expect(done.value.steps.every((s) => s.done === "made")).toBe(true);
137 expect(records.get(`${TOKENS[0]}._domainkey.${DOMAIN}`)).toBe(`${TOKENS[0]}.dkim.amazonses.com`);
138 expect(resolveMailKey(app.db, {})).toBe("forge");
139 const opened = resolveSecrets(app.db, dir, app.bus, ["MAIL_SMTP_URL", "MAIL_FROM"], { actor: admin.id });
140 expect(opened["MAIL_FROM"]).toBe(`forge@${DOMAIN}`);
141 const url = new URL(opened["MAIL_SMTP_URL"]!);
142 expect(url.protocol + url.hostname + url.port).toBe("smtps:email-smtp.us-east-1.amazonaws.com465");
143 expect(decodeURIComponent(url.password)).toBe(smtpPassword(SECRET_KEY, "us-east-1"));
144 });
145
146 test("a second run makes nothing new", async () => {
147 log.length = 0;
148 const done = await sendMailFromAws(app, admin, ask);
149 if (!done.ok || !done.value.ok) throw new Error("not run");
150 said.push(runWords(done.value));
151 expect(log).toEqual([]);
152 expect(aws.keys).toBe(1);
153 expect(done.value.steps.every((s) => s.done === "kept")).toBe(true);
154 expect(runWords(done.value)).toContain("Nothing new to make");
155 });
156
157 test("the SMTP password follows AWS's derivation", () => {
158 // 4 (version) + a 32-byte HMAC, base64: 44 characters; stable for one key and region.
159 const p = smtpPassword("secret", "us-east-1");
160 expect(Buffer.from(p, "base64").length).toBe(33);
161 expect(Buffer.from(p, "base64")[0]).toBe(4);
162 expect(smtpPassword("secret", "eu-west-1")).not.toBe(p);
163 });
164
165 test("refusals are sentences: not an admin, a read-only account, a bad name", async () => {
166 expect(await sendMailFromAws(app, undefined, ask)).toEqual({ ok: false, error: "not_found" });
167 const ro = await sendMailFromAws(app, admin, { ...ask, aws: "ro" });
168 expect(ro.ok ? "" : ro.error).toContain("read-only");
169 const bad = await sendMailFromAws(app, admin, { ...ask, domain: "not a name" });
170 expect(bad.ok ? "" : bad.error).toContain("sending subdomain");
171 expect(mailAccounts(app)).toEqual({ aws: ["main"], dns: ["dns"] });
172 });
173
174 test("the confirm page says what will be made, and the terminal says the same", async () => {
175 const r = await fetch(`${servers.url}/settings/secrets/aws-mail?domain=${DOMAIN}`, { headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` } });
176 const page = await r.text();
177 expect(r.status).toBe(200);
178 expect(page).toContain("An Amazon SES identity for mail.example.com");
179 expect(page).toContain("DKIM CNAME records");
180 expect(page).toContain("sealed as this forge&#39;s mail key");
181 expect(page).toContain('action="/settings/secrets/aws-mail"');
182 said.push(page);
183 // A stranger is shown none of it.
184 expect(await (await fetch(`${servers.url}/settings/secrets/aws-mail?domain=${DOMAIN}`)).text()).not.toContain("An Amazon SES identity");
185 });
186
187 test("the terminal shows the same plan, and w then a confirm runs it", async () => {
188 log.length = 0;
189 const { app: tui, session } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin }, { terminal: headlessTerminal(160, 32), exitHooks: false });
190 tui.start();
191 await settleApp(tui);
192 tui.push(secretsScreen(session, tui.ctx));
193 await settleApp(tui);
194 const key = async (k: string): Promise<void> => {
195 tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
196 await settleApp(tui);
197 };
198 await key("w");
199 for (const ch of DOMAIN) tui.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
200 await key("enter");
201 const frame = tui.screen.toText();
202 said.push(frame);
203 expect(frame).toContain("An Amazon SES identity for mail.example.com");
204 await key("left");
205 await key("enter");
206 await pollUntil(async () => {
207 await settleApp(tui);
208 return tui.screen.toText().includes("Nothing new");
209 }, "the screen says nothing new to make");
210 const after = tui.screen.toText();
211 said.push(after);
212 expect(after).toContain("Nothing new to make");
213 expect(log).toEqual([]);
214 tui.stop();
215 });
216
217 test("no step, answer, page or log holds the SMTP password, the secret key or the token", () => {
218 const password = smtpPassword(SECRET_KEY, "us-east-1");
219 const all = JSON.stringify([said, log]);
220 for (const secret of [password, encodeURIComponent(password), SECRET_KEY, CF_TOKEN]) expect(all).not.toContain(secret);
221 });
222 });
223
224 describe("the access key is never left over", () => {
225 /** A recorded AWS that only the key steps reach; `held` flips as another run seals. */
226 function world(opts: { stale?: number; held?: () => boolean; seal?: boolean }) {
227 const calls: string[] = [];
228 const deps: Parameters<typeof setupSes>[0] = {
229 call: async (service, _region, a) => {
230 if ("path" in a && a.post === undefined) return JSON.stringify({ DkimAttributes: { Tokens: TOKENS } });
231 const action = "action" in a ? a.action : service;
232 calls.push(action === "DeleteAccessKey" && "params" in a ? `delete ${a.params?.["AccessKeyId"]}` : action);
233 if (action === "GetCallerIdentity") return "<R><GetCallerIdentityResult><Account>123456789012</Account></GetCallerIdentityResult></R>";
234 if (action === "ListAccessKeys") return `<R><ListAccessKeysResult><AccessKeyMetadata>${"<member><AccessKeyId>AKIAOLD</AccessKeyId></member>".repeat(opts.stale ?? 0)}</AccessKeyMetadata></ListAccessKeysResult></R>`;
235 if (action === "CreateAccessKey") return `<R><CreateAccessKeyResult><AccessKey><AccessKeyId>AKIANEW</AccessKeyId><SecretAccessKey>${SECRET_KEY}</SecretAccessKey></AccessKey></CreateAccessKeyResult></R>`;
236 return "<R/>";
237 },
238 cname: async () => "kept",
239 keyHeld: opts.held ?? (() => false),
240 seal: () => opts.seal !== false,
241 };
242 return { deps, calls };
243 }
244 test("a seal that fails removes the key just made", async () => {
245 const w = world({ seal: false });
246 const r = await setupSes(w.deps, DOMAIN, "us-east-1");
247 expect(r.ok).toBe(false);
248 expect(w.calls.at(-1)).toBe("delete AKIANEW");
249 });
250 test("two keys already on the user are leftovers: removed before a new one is made", async () => {
251 const w = world({ stale: 2 });
252 expect((await setupSes(w.deps, DOMAIN, "us-east-1")).ok).toBe(true);
253 expect(w.calls.filter((c) => c.startsWith("delete"))).toEqual(["delete AKIAOLD", "delete AKIAOLD"]);
254 expect(w.calls.indexOf("CreateAccessKey")).toBeGreaterThan(w.calls.lastIndexOf("delete AKIAOLD"));
255 const one = world({ stale: 1 });
256 await setupSes(one.deps, DOMAIN, "us-east-1");
257 expect(one.calls.some((c) => c.startsWith("delete"))).toBe(false);
258 });
259 test("a run that lost the race to seal removes its key and keeps the winner's", async () => {
260 let n = 0;
261 const w = world({ held: () => ++n > 1 });
262 const r = await setupSes(w.deps, DOMAIN, "us-east-1");
263 expect(r.ok).toBe(true);
264 expect(w.calls.at(-1)).toBe("delete AKIANEW");
265 expect(runWords(r)).toContain("another run sealed it first");
266 });
267 test("a kept key says it covers only the identity it was made for", async () => {
268 const r = await setupSes(world({ held: () => true }).deps, DOMAIN, "us-east-1");
269 expect(runWords(r)).toContain("may not be");
270 });
271 });

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

Keyboard shortcuts

Docs