Public: anyone can read this; the crew can change it.
Mail from the owner's AWS account: the forge sets up SES, its DNS records and the mail key in one confirmed step #18119
Merged 5h 18m ago, live in production
scout/forge:scout/18109-mail-from-the-owner-s-aws-account-the-fo → main 0 commits fork 5 threads · 5 unresolved
28 files
changed +1345
−202
- docs/features/mail-key.md
- src/actions/cloud.ts
- src/actions/mail_aws.ts
- src/actions/secrets.ts
- src/cloud/aws_call.ts
- src/cloud/aws_sign.ts
- src/cloud/dns_record.ts
- src/cloud/ses_setup.ts
- src/contract/openapi/routes/deleteApiV1MailAws.ts
- src/contract/openapi/routes/getApiV1MailAws.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1MailAws.ts
- src/contract/tags.ts
- src/core/event_audience.ts
- src/core/mail_aws.ts
- src/generated/marks.ts
- src/http/api.ts
- src/http/api/mail_aws.ts
- src/http/lazy_lists.ts
- src/http/marks/api-v1-mail-aws.json
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/tui/screens/secrets.ts
- src/web/pages/secrets.ts
- src/web/render/mail_aws_card.ts
- test/aws-writes.test.ts
- test/mail-aws-doors.test.ts
- test/mail-aws.test.ts
docs/features/mail-key.md +27
| @@ -21,3 +21,30 @@ says the scope and the sentence, never the key. Forge admins only. | ||
| 21 | 21 | - **MCP**: the `secrets` tool, `action: mail`, `mail_set` (`url`, `from`) or `mail_remove`. |
| 22 | 22 | |
| 23 | 23 | `test/mail-key-doors.test.ts` plants a key and searches every answer, page, screen and event. |
| 24 | ||
| 25 | ## Mail from your AWS account (#18109) | |
| 26 | ||
| 27 | One confirmed step sends the forge's mail through SES in an AWS account attached with writes | |
| 28 | allowed, instead of a mail provider. It makes, in this order: an SES identity for a sending | |
| 29 | subdomain with DKIM; the three DKIM CNAME records in an attached Cloudflare account (writes | |
| 30 | allowed) that holds the domain; an IAM user `forge-mail-…` whose only policy is sending as that | |
| 31 | domain; and seals that user's SMTP credential as the forge's mail key (never shown). Then it asks AWS | |
| 32 | to leave the SES sandbox. Each step is saved as it is made: run it again and nothing new is made. | |
| 33 | `src/cloud/aws_call.ts` still refuses every write but a named list (`WRITES`), and an IAM user it | |
| 34 | touches must be named `forge-mail-…`; the SES and IAM hosts are built by it, never taken from an answer. | |
| 35 | ||
| 36 | The mail key's line says the state: *waiting for DNS*, *in the sandbox* (mail reaches verified | |
| 37 | addresses only), *sending*, with sent, bounced and complaint counts from SES's last two weeks. It is | |
| 38 | the last look: "look again" reads AWS. | |
| 39 | ||
| 40 | - **Page**: Settings → Secrets, "Send mail from this AWS account" (one tick, worded as what will be made, confirms it); | |
| 41 | once set up: look again, send a test to your own proven address, undo. | |
| 42 | - **Terminal** (`src/tui/screens/secrets.ts`): `w` on the forge's place. | |
| 43 | - **API**: `GET /api/v1/mail-aws`; `POST` with `step` `set_up` (`aws`, `dns`, `domain`, `region`, | |
| 44 | `confirm: true`), `look` or `test`; `DELETE` with `confirm: true` undoes (without it, 422 and | |
| 45 | what it would remove): removes the key, the IAM user and its access keys, the identity and the | |
| 46 | records, and nothing else. An SES identity that was already there when set-up ran is adopted and | |
| 47 | left in place on undo, and undo says so. Admin-scope token. The terminal asks a second time before undo. | |
| 48 | ||
| 49 | `test/mail-aws.test.ts` runs it against a recorded AWS and Cloudflare. Not done: the outside hosts | |
| 50 | are not named in `forge.json` `egress`, as for every AWS read. |
src/actions/cloud.ts +1 −1
| @@ -90,7 +90,7 @@ export async function connectAccount( | ||
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | /** Open the sealed value for one named purpose, which the read event records. */ |
| 93 | function open(app: App, actor: User, secret: string, run: string): string | undefined { | |
| 93 | export function open(app: App, actor: User, secret: string, run: string): string | undefined { | |
| 94 | 94 | return resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { |
| 95 | 95 | actor: actor.id, |
| 96 | 96 | run, |
src/actions/mail_aws.ts added +219
| @@ -0,0 +1,219 @@ | ||
| 1 | /** | |
| 2 | * Send mail from the owner's AWS account (#18109): one confirmed step that makes an SES identity | |
| 3 | * for a sending domain, the DKIM records in the DNS account the forge holds, an IAM user that may | |
| 4 | * only send as that domain, and seals that user's SMTP credential as the forge's mail key; then | |
| 5 | * asks AWS to leave the sandbox. Each step is saved as it is made, so a second run makes nothing | |
| 6 | * new and an undo removes exactly what was made. The password is derived and sealed in one function | |
| 7 | * and never returned, shown or logged. The calls are `cloud/ses_setup.ts`'s, behind `awsCall`'s | |
| 8 | * named list. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { AWS_REGION, awsCall, awsKey } from "../cloud/aws_call.ts"; | |
| 13 | import type { Call } from "../cloud/aws_read.ts"; | |
| 14 | import { DNS_TTL, lookRecord, removeRecord, writeRecord, type DnsSpec } from "../cloud/dns_record.ts"; | |
| 15 | import { gatedFetch } from "../cloud/gate.ts"; | |
| 16 | import { dkimRecords, isMailDomain, makeIdentity, makeSender, readIdentity, readProduction, readStatistics, requestProduction, smtpUrl, takeDown } from "../cloud/ses_setup.ts"; | |
| 17 | import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts"; | |
| 18 | import { forgetMailAws, getMailAws, mailAwsWords, putMailAws, type MailAws, type MailAwsRecord } from "../core/mail_aws.ts"; | |
| 19 | import { sendWithMailKey } from "../core/mail_key.ts"; | |
| 20 | import { listSecretNames } from "../core/secret_store.ts"; | |
| 21 | import type { User } from "../core/users.ts"; | |
| 22 | import { emailVerified } from "../core/verify.ts"; | |
| 23 | import { isStandInEmail } from "../core/users.ts"; | |
| 24 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 25 | import { net, open } from "./cloud.ts"; | |
| 26 | import { removeMailKey, setMailKey } from "./secrets.ts"; | |
| 27 | ||
| 28 | export interface MailAwsAsk { | |
| 29 | /** The attached AWS account's name, and the Cloudflare account that holds the domain's zone. */ | |
| 30 | readonly aws: string; | |
| 31 | readonly dns: string; | |
| 32 | /** The sending subdomain: `mail.example.com`. */ | |
| 33 | readonly domain: string; | |
| 34 | readonly region: string; | |
| 35 | } | |
| 36 | ||
| 37 | const admin = (a: User | undefined): Result<User, string> => (a?.isAdmin ? ok(a) : err("not_found")); | |
| 38 | ||
| 39 | /** What the one confirm says, whole, before anything is made. */ | |
| 40 | export function mailAwsConfirm(ask: MailAwsAsk): string { | |
| 41 | return ( | |
| 42 | `Send mail from AWS account ${ask.aws}: this makes an SES identity for ${ask.domain} in ${ask.region} with DKIM, ` + | |
| 43 | `an IAM user that may only send from @${ask.domain}, three DKIM CNAME records in Cloudflare account ${ask.dns}, ` + | |
| 44 | `seals that user's SMTP credential as the forge's mail key (never shown), and asks AWS to leave the SES sandbox.` | |
| 45 | ); | |
| 46 | } | |
| 47 | ||
| 48 | /** What undo says, whole, before anything is removed. */ | |
| 49 | export function mailAwsUndoConfirm(m: MailAws): string { | |
| 50 | return ( | |
| 51 | `Undo mail from AWS: this deletes the forge's mail key, the IAM user ${m.user} and its access keys, ` + | |
| 52 | `${m.identityMade ? `the SES identity for ${m.domain}` : `no SES identity (${m.domain} was already in SES and stays)`}, ` + | |
| 53 | `and the ${m.records.length} DNS records it made in Cloudflare account ${m.dns}. Mail then goes by the platform's key, if any.` | |
| 54 | ); | |
| 55 | } | |
| 56 | ||
| 57 | interface Hands { | |
| 58 | readonly call: Call; | |
| 59 | readonly cf: ReturnType<typeof gatedFetch>; | |
| 60 | readonly token: string; | |
| 61 | } | |
| 62 | ||
| 63 | function hands(app: App, actor: User, ask: MailAwsAsk, purpose: string): Result<Hands, string> { | |
| 64 | if (!AWS_REGION.test(ask.region)) return err("That is not an AWS region."); | |
| 65 | const a = getCloudAccount(app.db, "aws", ask.aws); | |
| 66 | if (a === undefined) return err("No such AWS account is attached."); | |
| 67 | if (!a.writeAllowed) return err("That AWS account is read-only; allow writes on it first."); | |
| 68 | const d = getCloudAccount(app.db, "cloudflare", ask.dns); | |
| 69 | if (d === undefined) return err("No such Cloudflare account is attached."); | |
| 70 | if (!d.writeAllowed) return err("That Cloudflare account is read-only; allow writes on it first."); | |
| 71 | const key = awsKey(open(app, actor, secretNameOf("aws", ask.aws), `${purpose}:aws`) ?? ""); | |
| 72 | const token = open(app, actor, secretNameOf("cloudflare", ask.dns), `${purpose}:cloudflare`); | |
| 73 | if (key === undefined || token === undefined) return err("No such credential."); | |
| 74 | const aws = gatedFetch(app.db, { provider: "aws", account: ask.aws }, purpose, net.fetch); | |
| 75 | return ok({ call: (service, region, a) => awsCall(aws, key, service, region, a, true), cf: gatedFetch(app.db, { provider: "cloudflare", account: ask.dns }, purpose, net.fetch), token }); | |
| 76 | } | |
| 77 | ||
| 78 | const fresh = (ask: MailAwsAsk): MailAws => ({ | |
| 79 | ...ask, | |
| 80 | from: `forge@${ask.domain}`, | |
| 81 | user: `forge-mail-${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`, | |
| 82 | keyId: "", | |
| 83 | identity: false, | |
| 84 | identityMade: false, | |
| 85 | records: [], | |
| 86 | requested: false, | |
| 87 | state: "", | |
| 88 | sent: 0, | |
| 89 | bounces: 0, | |
| 90 | complaints: 0, | |
| 91 | lookedAt: null, | |
| 92 | }); | |
| 93 | ||
| 94 | /** The sentence for a thrown AWS or network failure; never its message, which could quote a key. */ | |
| 95 | const failed = (what: string, e: unknown): string => `${what}: ${e instanceof Error ? e.message.slice(0, 120) : "failed"}`; | |
| 96 | ||
| 97 | /** Read AWS again and keep what it says: verified or not, production or not, the counts. */ | |
| 98 | async function look(app: App, h: Hands, m: MailAws): Promise<MailAws> { | |
| 99 | const id = await readIdentity(h.call, m.region, m.domain); | |
| 100 | const production = id.verified ? await readProduction(h.call, m.region) : false; | |
| 101 | const stats = await readStatistics(h.call, m.region).catch(() => ({ sent: m.sent, bounces: m.bounces, complaints: m.complaints })); | |
| 102 | const next: MailAws = { ...m, ...stats, state: !id.verified ? "waiting" : production ? "sending" : "sandbox", lookedAt: new Date().toISOString() }; | |
| 103 | putMailAws(app.db, next); | |
| 104 | return next; | |
| 105 | } | |
| 106 | ||
| 107 | /** Make what is not yet made, in order: the identity, the records, the key, the request. */ | |
| 108 | export async function setUpMailAws(app: App, actor: User | undefined, ask: MailAwsAsk): Promise<Result<string, string>> { | |
| 109 | const who = admin(actor); | |
| 110 | if (!who.ok) return who; | |
| 111 | if (!isMailDomain(ask.domain)) return err("The sending domain is a host name such as mail.example.com."); | |
| 112 | const h = hands(app, who.value, ask, "mail_aws"); | |
| 113 | if (!h.ok) return h; | |
| 114 | let m = getMailAws(app.db); | |
| 115 | if (m !== undefined && (m.domain !== ask.domain || m.region !== ask.region || m.aws !== ask.aws || m.dns !== ask.dns)) return err("Mail is already set up from another place; undo that first."); | |
| 116 | if (m === undefined) { | |
| 117 | const held = new Set(listSecretNames(app.db, "forge", "").map((s) => s.name)); | |
| 118 | if (held.has("MAIL_SMTP_URL")) return err("The forge already has a mail key; remove it first."); | |
| 119 | m = fresh(ask); | |
| 120 | } | |
| 121 | try { | |
| 122 | let id; | |
| 123 | if (m.identity) id = await readIdentity(h.value.call, m.region, m.domain); | |
| 124 | else { | |
| 125 | const made = await makeIdentity(h.value.call, m.region, m.domain); | |
| 126 | id = made.state; | |
| 127 | m = { ...m, identityMade: made.created }; | |
| 128 | } | |
| 129 | m = { ...m, identity: true }; | |
| 130 | putMailAws(app.db, m); | |
| 131 | const records = [...m.records]; | |
| 132 | for (const [host, value] of dkimRecords(m.domain, id.tokens)) { | |
| 133 | const spec: DnsSpec = { type: "CNAME", host, value, ttl: DNS_TTL, priority: 0, weight: 0, port: 0 }; | |
| 134 | const kept = records.find((r) => r.host === host); | |
| 135 | if (kept !== undefined && (await lookRecord(h.value.cf, h.value.token, spec, kept)) === "") continue; | |
| 136 | const w = await writeRecord(h.value.cf, h.value.token, spec, kept); | |
| 137 | if (!w.ok) return err(w.why); | |
| 138 | if (kept === undefined) records.push({ host, zone: w.zone, record: w.record }); | |
| 139 | m = { ...m, records }; | |
| 140 | putMailAws(app.db, m); | |
| 141 | } | |
| 142 | if (m.keyId === "") { | |
| 143 | const k = await makeSender(h.value.call, m.user, m.domain, m.region); | |
| 144 | const set = setMailKey(app, who.value, "forge", "", smtpUrl(k.keyId, k.secret, m.region), m.from); | |
| 145 | if (!set.ok) { | |
| 146 | await takeDown(h.value.call, m.region, { user: m.user, domain: "" }).catch(() => undefined); | |
| 147 | return err("The mail key could not be sealed; the key AWS made was deleted."); | |
| 148 | } | |
| 149 | m = { ...m, keyId: k.keyId }; | |
| 150 | putMailAws(app.db, m); | |
| 151 | } | |
| 152 | if (!m.requested) { | |
| 153 | if (!(await readProduction(h.value.call, m.region).catch(() => false))) await requestProduction(h.value.call, m.region, m.domain).catch(() => undefined); | |
| 154 | m = { ...m, requested: true }; | |
| 155 | putMailAws(app.db, m); | |
| 156 | } | |
| 157 | m = await look(app, h.value, m); | |
| 158 | } catch (e) { | |
| 159 | return err(failed("AWS did not finish the setup (run it again to carry on)", e)); | |
| 160 | } | |
| 161 | app.bus.append({ kind: "mail_aws.set_up", actorId: who.value.id, payload: { domain: m.domain, state: m.state } }); | |
| 162 | return ok(mailAwsWords(m)); | |
| 163 | } | |
| 164 | ||
| 165 | /** Read AWS again: the page's "look again". */ | |
| 166 | export async function lookMailAws(app: App, actor: User | undefined): Promise<Result<string, string>> { | |
| 167 | const who = admin(actor); | |
| 168 | if (!who.ok) return who; | |
| 169 | const m = getMailAws(app.db); | |
| 170 | if (m === undefined) return err("Mail is not set up from an AWS account."); | |
| 171 | const h = hands(app, who.value, m, "mail_aws_look"); | |
| 172 | if (!h.ok) return h; | |
| 173 | try { | |
| 174 | return ok(mailAwsWords(await look(app, h.value, m))); | |
| 175 | } catch (e) { | |
| 176 | return err(failed("AWS could not be asked", e)); | |
| 177 | } | |
| 178 | } | |
| 179 | ||
| 180 | /** One message to the admin's own proven address, with the key in effect. */ | |
| 181 | export async function testMailAws(app: App, actor: User | undefined): Promise<Result<string, string>> { | |
| 182 | const who = admin(actor); | |
| 183 | if (!who.ok) return who; | |
| 184 | const u = who.value; | |
| 185 | if (isStandInEmail(u.email) || !emailVerified(app.db, u.id)) return err("Prove your own email address first: the test goes only there."); | |
| 186 | const sent = await sendWithMailKey(app.db, app.config.dataDir, app.bus, { actor: u.id }, { to: u.email, subject: "Test mail from your forge", text: "This is the test you asked for. Mail from this forge reaches you." }, app.config.mail); | |
| 187 | if (sent === undefined || !sent.sent) return err("The test did not go: the mail key's server refused it (in the SES sandbox, only verified addresses are reached)."); | |
| 188 | app.bus.append({ kind: "mail_aws.test", actorId: u.id, payload: {} }); | |
| 189 | return ok(`A test went to ${u.email}.`); | |
| 190 | } | |
| 191 | ||
| 192 | /** Remove the key, the user, the identity and the records this made, and nothing else. */ | |
| 193 | export async function undoMailAws(app: App, actor: User | undefined): Promise<Result<string, string>> { | |
| 194 | const who = admin(actor); | |
| 195 | if (!who.ok) return who; | |
| 196 | const m = getMailAws(app.db); | |
| 197 | if (m === undefined) return err("Mail is not set up from an AWS account."); | |
| 198 | const h = hands(app, who.value, m, "mail_aws_undo"); | |
| 199 | if (!h.ok) return h; | |
| 200 | if (m.keyId !== "") removeMailKey(app, who.value, "forge", ""); | |
| 201 | try { | |
| 202 | await takeDown(h.value.call, m.region, { user: m.user, domain: m.identityMade ? m.domain : "" }); | |
| 203 | } catch (e) { | |
| 204 | return err(failed("AWS did not remove everything (run undo again)", e)); | |
| 205 | } | |
| 206 | const left: MailAwsRecord[] = []; | |
| 207 | for (const r of m.records) { | |
| 208 | const gone = await removeRecord(h.value.cf, h.value.token, r); | |
| 209 | if (!gone.ok) left.push(r); | |
| 210 | } | |
| 211 | if (left.length > 0) { | |
| 212 | putMailAws(app.db, { ...m, keyId: "", identity: false, identityMade: false, records: left }); | |
| 213 | return err(`Cloudflare would not remove ${left.map((r) => r.host).join(", ")}.`); | |
| 214 | } | |
| 215 | forgetMailAws(app.db); | |
| 216 | app.bus.append({ kind: "mail_aws.undone", actorId: who.value.id, payload: { domain: m.domain } }); | |
| 217 | const identity = m.identityMade ? "the SES identity" : `nothing of the SES identity (${m.domain} was in SES before this set-up, so it stays)`; | |
| 218 | return ok(`Removed the mail key, the IAM user, ${identity} and ${m.records.length} DNS records.`); | |
| 219 | } |
src/actions/secrets.ts +5 −1
| @@ -16,6 +16,7 @@ import { getAppById, getAppByRepo } from "../core/apps.ts"; | ||
| 16 | 16 | import { readerFor } from "../git/read.ts"; |
| 17 | 17 | import { repoDir } from "../git/repos.ts"; |
| 18 | 18 | import type { Repo } from "../core/repos.ts"; |
| 19 | import { getMailAws, mailAwsWords } from "../core/mail_aws.ts"; | |
| 19 | 20 | import { MAIL_KEY_NAMES, resolveMailKey, type MailScope } from "../core/mail_key.ts"; |
| 20 | 21 | import { requireRepoAdmin } from "./access.ts"; |
| 21 | 22 | import { neededNames, needRows, type NeedRow, appsUsing, grantable, grantSecret, revokeGrant, usesOf, type SecretUse } from "../core/app_secrets.ts"; |
| @@ -94,10 +95,13 @@ export function mailKeyState( | ||
| 94 | 95 | const target = resolveTarget(app, scope, ref); |
| 95 | 96 | if (!target.ok) return target; |
| 96 | 97 | const won = resolveMailKey(app.db, mailAsker(app, target.value, ref), app.config.mail); |
| 98 | const aws = won === "forge" ? getMailAws(app.db) : undefined; | |
| 97 | 99 | return ok({ |
| 98 | 100 | inEffect: won ?? null, |
| 99 | 101 | line: |
| 100 | won === undefined | |
| 102 | aws?.keyId | |
| 103 | ? mailAwsWords(aws) | |
| 104 | : won === undefined | |
| 101 | 105 | ? "No mail key is set: no mail goes out." |
| 102 | 106 | : `Mail goes out with the ${won}'s key (the key itself is never shown).`, |
| 103 | 107 | }); |
src/cloud/aws_call.ts +22 −13
| @@ -29,25 +29,28 @@ const HOST = { | ||
| 29 | 29 | cloudformation: (r: string) => `cloudformation.${r}.amazonaws.com`, |
| 30 | 30 | ecs: (r: string) => `ecs.${r}.amazonaws.com`, |
| 31 | 31 | s3: (r: string) => `s3.${r}.amazonaws.com`, |
| 32 | ses: (r: string) => `email.${r}.amazonaws.com`, | |
| 33 | iam: () => "iam.amazonaws.com", | |
| 32 | 34 | sts: () => "sts.amazonaws.com", |
| 33 | 35 | route53: () => "route53.amazonaws.com", |
| 34 | 36 | ce: () => "ce.us-east-1.amazonaws.com", |
| 35 | ses: (r: string) => `email.${r}.amazonaws.com`, | |
| 36 | iam: () => "iam.amazonaws.com", | |
| 37 | 37 | } as const; |
| 38 | 38 | export type AwsService = keyof typeof HOST; |
| 39 | 39 | |
| 40 | 40 | /** A region's name: `us-east-1`, `ap-southeast-4`. */ |
| 41 | 41 | export const AWS_REGION = /^[a-z]{2}(-[a-z]+){1,3}-\d{1,2}$/; |
| 42 | 42 | const READS = /^(Describe|List|Get)[A-Z][A-Za-z]*$/; |
| 43 | /** The one name an IAM user the forge makes carries. */ | |
| 44 | export const MAIL_USER = /^forge-mail-[a-z0-9]{4,24}$/; | |
| 43 | 45 | |
| 44 | 46 | /** |
| 45 | 47 | * 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. | |
| 48 | * SES's own writes are REST in SES v2 (the `rest` ask); IAM's are the query protocol. | |
| 49 | 49 | */ |
| 50 | 50 | const WRITES: ReadonlySet<string> = new Set([ |
| 51 | "ses:CreateEmailIdentity", | |
| 52 | "ses:DeleteEmailIdentity", | |
| 53 | "ses:PutAccountDetails", | |
| 51 | 54 | "iam:CreateUser", |
| 52 | 55 | "iam:PutUserPolicy", |
| 53 | 56 | "iam:CreateAccessKey", |
| @@ -82,7 +85,8 @@ function sendOnly(doc: string | undefined): boolean { | ||
| 82 | 85 | export type AwsAsk = |
| 83 | 86 | | { readonly action: string; readonly version: string; readonly params?: Readonly<Record<string, string>> } |
| 84 | 87 | | { readonly target: string; readonly json: "1.0" | "1.1"; readonly body: unknown } |
| 85 | | { readonly path: string; readonly query?: Readonly<Record<string, string>> }; | |
| 88 | | { readonly path: string; readonly query?: Readonly<Record<string, string>> } | |
| 89 | | { readonly rest: "POST" | "DELETE"; readonly operation: string; readonly path: string; readonly body?: unknown }; | |
| 86 | 90 | |
| 87 | 91 | /** AWS answered, and refused: its status and its own code for why ("UnauthorizedOperation"). */ |
| 88 | 92 | export class AwsRefused extends Error { |
| @@ -118,28 +122,33 @@ function codeOf(text: string): string { | ||
| 118 | 122 | */ |
| 119 | 123 | export async function awsCall(f: Fetch, key: AwsKey, service: AwsService, region: string, ask: AwsAsk, writes = false): Promise<string> { |
| 120 | 124 | 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"; | |
| 125 | const operation = "action" in ask ? ask.action : "target" in ask ? (ask.target.split(".").at(-1) ?? "") : "rest" in ask ? ask.operation : "GetRest"; | |
| 122 | 126 | if (!READS.test(operation)) { |
| 123 | 127 | if (!WRITES.has(`${service}:${operation}`)) throw new Error(`${operation} is not a read: the forge only reads AWS`); |
| 124 | 128 | if (!writes) throw new Error(`${operation} is a write: this AWS account is read-only`); |
| 125 | 129 | if (service === "iam" && operation === "PutUserPolicy" && !("action" in ask && sendOnly(ask.params?.["PolicyDocument"]))) |
| 126 | 130 | throw new Error("PutUserPolicy allows only ses:SendRawEmail from one identity"); |
| 131 | if (service === "iam" && !("action" in ask && MAIL_USER.test(ask.params?.["UserName"] ?? ""))) | |
| 132 | throw new Error("the forge writes only the IAM user it made for mail"); | |
| 133 | if ("rest" in ask !== (service === "ses")) throw new Error(`${operation} is not asked of ${service}`); | |
| 127 | 134 | } |
| 128 | 135 | if (service === "iam" && region !== "us-east-1") throw new Error("iam is signed for us-east-1 only"); |
| 129 | 136 | const host = HOST[service](region); |
| 130 | 137 | const form = "action" in ask ? queryText({ ...ask.params, Action: ask.action, Version: ask.version }) : ""; |
| 131 | 138 | const r = { |
| 132 | method: "path" in ask ? ("GET" as const) : ("POST" as const), | |
| 139 | method: "rest" in ask ? ask.rest : "path" in ask ? ("GET" as const) : ("POST" as const), | |
| 133 | 140 | host, |
| 134 | path: "path" in ask ? ask.path : "/", | |
| 135 | query: "path" in ask ? (ask.query ?? {}) : {}, | |
| 141 | path: "rest" in ask || "path" in ask ? ask.path : "/", | |
| 142 | query: !("rest" in ask) && "path" in ask ? (ask.query ?? {}) : {}, | |
| 136 | 143 | headers: |
| 137 | 144 | "action" in ask |
| 138 | 145 | ? { "content-type": "application/x-www-form-urlencoded" } |
| 139 | 146 | : "target" in ask |
| 140 | 147 | ? { "content-type": `application/x-amz-json-${ask.json}`, "x-amz-target": ask.target } |
| 141 | : {}, | |
| 142 | body: "target" in ask ? JSON.stringify(ask.body) : form, | |
| 148 | : "rest" in ask | |
| 149 | ? { "content-type": "application/json" } | |
| 150 | : {}, | |
| 151 | body: "target" in ask ? JSON.stringify(ask.body) : "rest" in ask ? (ask.body === undefined ? "" : JSON.stringify(ask.body)) : form, | |
| 143 | 152 | service, |
| 144 | 153 | region, |
| 145 | 154 | }; |
| @@ -147,7 +156,7 @@ export async function awsCall(f: Fetch, key: AwsKey, service: AwsService, region | ||
| 147 | 156 | const res = await f(`https://${host}${r.path}${query === "" ? "" : `?${query}`}`, { |
| 148 | 157 | method: r.method, |
| 149 | 158 | headers: signV4(r, key, new Date()), |
| 150 | ...(r.method === "POST" ? { body: r.body } : {}), | |
| 159 | ...(r.method === "POST" || (r.method === "DELETE" && r.body !== "") ? { body: r.body } : {}), | |
| 151 | 160 | redirect: "error", |
| 152 | 161 | signal: AbortSignal.timeout(10_000), |
| 153 | 162 | }); |
src/cloud/aws_sign.ts +1 −1
src/cloud/dns_record.ts +9 −6
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { cloudflare, CF_ID, deleteARecord, zoneOf, type Fetch } from "./providers.ts"; |
| 11 | 11 | |
| 12 | export type DnsType = "A" | "SRV"; | |
| 12 | export type DnsType = "A" | "SRV" | "CNAME"; | |
| 13 | 13 | |
| 14 | 14 | /** |
| 15 | 15 | * What one record says, whatever its type: an SRV's `value` is its target host, and its port and |
| @@ -32,14 +32,17 @@ export const DNS_TTL = 60; | ||
| 32 | 32 | |
| 33 | 33 | const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"; |
| 34 | 34 | const HOST = new RegExp(`^(?=.{1,253}$)${LABEL}(?:\\.${LABEL})+$`); |
| 35 | /** A CNAME's own name may carry `_domainkey`-style labels. */ | |
| 36 | const CNAME_HOST = new RegExp(`^(?=.{1,253}$)_?${LABEL}(?:\\._?${LABEL})+$`); | |
| 35 | 37 | const SRV_HOST = new RegExp(`^_[a-z0-9-]{1,30}\\._(?:tcp|udp)\\.(?=.{1,200}$)${LABEL}(?:\\.${LABEL})+$`); |
| 36 | 38 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; |
| 37 | 39 | const inRange = (n: number, lo: number, hi: number): boolean => Number.isInteger(n) && n >= lo && n <= hi; |
| 38 | 40 | |
| 39 | 41 | /** Why a spec cannot be written, in a sentence; undefined when it can. */ |
| 40 | 42 | export function specWords(s: DnsSpec): string | undefined { |
| 41 | if (s.type !== "A" && s.type !== "SRV") return "A DNS record is an A or an SRV record."; | |
| 43 | if (s.type !== "A" && s.type !== "SRV" && s.type !== "CNAME") return "A DNS record is an A, a CNAME or an SRV record."; | |
| 42 | 44 | if (!inRange(s.ttl, 60, 86_400)) return "A DNS record's TTL is 60 to 86400 seconds."; |
| 45 | if (s.type === "CNAME") return !CNAME_HOST.test(s.host) ? `${s.host.slice(0, 80)} is not a host name.` : !HOST.test(s.value) ? `${s.value.slice(0, 80)} is not a host name for the CNAME to point at.` : undefined; | |
| 43 | 46 | if (s.type === "A") |
| 44 | 47 | return !HOST.test(s.host) ? `${s.host.slice(0, 80)} is not a host name.` : !IPV4.test(s.value) ? `${s.value.slice(0, 80)} is not an IPv4 address.` : undefined; |
| 45 | 48 | if (!SRV_HOST.test(s.host)) return `${s.host.slice(0, 80)} is not an SRV name: it reads _service._tcp.host or _service._udp.host.`; |
| @@ -50,15 +53,15 @@ export function specWords(s: DnsSpec): string | undefined { | ||
| 50 | 53 | } |
| 51 | 54 | |
| 52 | 55 | /** The record in a sentence: "SRV _minecraft._tcp.play.example.com → box.example.com:25565". */ |
| 53 | export const specWordsOf = (s: DnsSpec): string => (s.type === "A" ? `A ${s.host} → ${s.value}` : `SRV ${s.host} → ${s.value}:${s.port}`); | |
| 56 | export const specWordsOf = (s: DnsSpec): string => (s.type !== "SRV" ? `${s.type} ${s.host} → ${s.value}` : `SRV ${s.host} → ${s.value}:${s.port}`); | |
| 54 | 57 | |
| 55 | 58 | /** The same record, so a plan can tell a record that stands from one to change. */ |
| 56 | 59 | export const specKey = (s: DnsSpec): string => `${s.type} ${s.host} ${s.value} ${s.ttl} ${s.priority} ${s.weight} ${s.port}`; |
| 57 | 60 | |
| 58 | 61 | /** The body Cloudflare takes for a spec. */ |
| 59 | 62 | const bodyOf = (s: DnsSpec): Record<string, unknown> => |
| 60 | s.type === "A" | |
| 61 | ? { type: "A", name: s.host, content: s.value, ttl: s.ttl, proxied: false } | |
| 63 | s.type !== "SRV" | |
| 64 | ? { type: s.type, name: s.host, content: s.value, ttl: s.ttl, proxied: false } | |
| 62 | 65 | : { type: "SRV", name: s.host, ttl: s.ttl, data: { priority: s.priority, weight: s.weight, port: s.port, target: s.value } }; |
| 63 | 66 | |
| 64 | 67 | const clean = (say: string, token: string): string => (token === "" ? say : say.split(token).join("…")).slice(0, 160); |
| @@ -115,7 +118,7 @@ export async function lookRecord(f: Fetch, token: string, s: DnsSpec, at: { zone | ||
| 115 | 118 | const same = |
| 116 | 119 | x.type === s.type && |
| 117 | 120 | x.name === s.host && |
| 118 | (s.type === "A" ? x.content === s.value : x.data?.target === s.value && x.data?.port === s.port && x.data?.priority === s.priority && x.data?.weight === s.weight); | |
| 121 | (s.type !== "SRV" ? x.content === s.value : x.data?.target === s.value && x.data?.port === s.port && x.data?.priority === s.priority && x.data?.weight === s.weight); | |
| 119 | 122 | if (same) return ""; |
| 120 | 123 | const now = x.type === "SRV" ? `SRV → ${String(x.data?.target ?? "").slice(0, 80)}:${Number(x.data?.port) || 0}` : `${String(x.type ?? "").slice(0, 8)} → ${String(x.content ?? "").slice(0, 80)}`; |
| 121 | 124 | return `${specWordsOf(s)} was changed at Cloudflare: it now reads ${now}`; |
src/cloud/ses_setup.ts added +152
| @@ -0,0 +1,152 @@ | ||
| 1 | /** | |
| 2 | * Mail from the owner's AWS account (#18109): the SES and IAM calls, one concept, plain data in and | |
| 3 | * out. Every call goes through `awsCall`, whose named write list is the only door: an SES identity | |
| 4 | * for a sending domain (Easy DKIM), one IAM user `forge-mail-…` that may only send from it, that | |
| 5 | * user's key, and the request to leave the SES sandbox. The SMTP password is derived here from the | |
| 6 | * secret key and returned to the one caller that seals it; nothing here logs or throws a secret. | |
| 7 | */ | |
| 8 | ||
| 9 | import { createHmac } from "node:crypto"; | |
| 10 | import { AwsRefused, MAIL_USER, sendOnlyPolicy } from "./aws_call.ts"; | |
| 11 | import { items, parseXml, val } from "./aws_xml.ts"; | |
| 12 | import type { Call } from "./aws_read.ts"; | |
| 13 | ||
| 14 | const IAM = "2010-05-08"; | |
| 15 | const SES = "2010-12-01"; | |
| 16 | const TOKEN = /^[a-z0-9]{16,48}$/; | |
| 17 | const DOMAIN = /^(?=.{4,200}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/; | |
| 18 | ||
| 19 | export const isMailDomain = (d: string): boolean => DOMAIN.test(d); | |
| 20 | ||
| 21 | /** | |
| 22 | * The SMTP password SES derives from an IAM secret key (version 4 of its scheme): HMAC-SHA256 down | |
| 23 | * date, region, service, terminal and message, a version byte in front, base64. | |
| 24 | */ | |
| 25 | export function smtpPassword(secret: string, region: string): string { | |
| 26 | const h = (k: Buffer | string, m: string): Buffer => createHmac("sha256", k).update(m).digest(); | |
| 27 | const k = ["11111111", region, "ses", "aws4_request", "SendRawEmail"].reduce<Buffer | string>((key, m) => h(key, m), `AWS4${secret}`) as Buffer; | |
| 28 | return Buffer.concat([Buffer.from([4]), k]).toString("base64"); | |
| 29 | } | |
| 30 | ||
| 31 | /** `smtps://<key id>:<password>@email-smtp.<region>.amazonaws.com:465`, both escaped. */ | |
| 32 | export const smtpUrl = (keyId: string, secret: string, region: string): string => | |
| 33 | `smtps://${encodeURIComponent(keyId)}:${encodeURIComponent(smtpPassword(secret, region))}@email-smtp.${region}.amazonaws.com:465`; | |
| 34 | ||
| 35 | /** What AWS says of the identity: whether it may send, and the DKIM names to put in DNS. */ | |
| 36 | export interface IdentityState { | |
| 37 | readonly verified: boolean; | |
| 38 | readonly tokens: readonly string[]; | |
| 39 | } | |
| 40 | ||
| 41 | /** The CNAME records Easy DKIM wants for a domain: [name, target]. */ | |
| 42 | export const dkimRecords = (domain: string, tokens: readonly string[]): ReadonlyArray<readonly [string, string]> => | |
| 43 | tokens.map((t) => [`${t}._domainkey.${domain}`, `${t}.dkim.amazonses.com`] as const); | |
| 44 | ||
| 45 | function identityOf(text: string): IdentityState { | |
| 46 | const j = JSON.parse(text) as { VerifiedForSendingStatus?: unknown; DkimAttributes?: { Tokens?: unknown } }; | |
| 47 | const tokens = Array.isArray(j.DkimAttributes?.Tokens) ? j.DkimAttributes.Tokens.filter((t): t is string => typeof t === "string" && TOKEN.test(t)) : []; | |
| 48 | return { verified: j.VerifiedForSendingStatus === true, tokens }; | |
| 49 | } | |
| 50 | ||
| 51 | const path = (domain: string): string => `/v2/email/identities/${encodeURIComponent(domain)}`; | |
| 52 | ||
| 53 | export async function readIdentity(call: Call, region: string, domain: string): Promise<IdentityState> { | |
| 54 | return identityOf(await call("ses", region, { path: path(domain) })); | |
| 55 | } | |
| 56 | ||
| 57 | /** | |
| 58 | * Make the identity, or read the one that stands: asking twice makes one. `created` says whether | |
| 59 | * this call made it; an identity the owner already had is adopted and never to be deleted. | |
| 60 | */ | |
| 61 | export async function makeIdentity(call: Call, region: string, domain: string): Promise<{ state: IdentityState; created: boolean }> { | |
| 62 | try { | |
High (data loss). When AWS says the identity already exists, this adopts it, and |
||
| 63 | return { state: identityOf(await call("ses", region, { rest: "POST", operation: "CreateEmailIdentity", path: "/v2/email/identities", body: { EmailIdentity: domain } })), created: true }; | |
| 64 | } catch (e) { | |
| 65 | if (e instanceof AwsRefused && e.code === "AlreadyExistsException") return { state: await readIdentity(call, region, domain), created: false }; | |
| 66 | throw e; | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | /** Delete every access key the user holds: a key the forge's row does not know is an orphan. */ | |
| 71 | async function dropKeys(call: Call, user: string): Promise<void> { | |
| 72 | const x = parseXml(await call("iam", "us-east-1", { action: "ListAccessKeys", version: IAM, params: { UserName: user } })); | |
| 73 | for (const k of items(x, "ListAccessKeysResult/AccessKeyMetadata")) { | |
| 74 | const id = val(k, "AccessKeyId"); | |
| 75 | if (/^[A-Z0-9]{16,128}$/.test(id)) await call("iam", "us-east-1", { action: "DeleteAccessKey", version: IAM, params: { UserName: user, AccessKeyId: id } }); | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | /** Whether the account may send to anyone (production), or only to verified addresses. */ | |
| 80 | export async function readProduction(call: Call, region: string): Promise<boolean> { | |
| 81 | return (JSON.parse(await call("ses", region, { path: "/v2/email/account" })) as { ProductionAccessEnabled?: unknown }).ProductionAccessEnabled === true; | |
| 82 | } | |
| 83 | ||
| 84 | /** Ask to leave the sandbox, saying what the mail is for. */ | |
| 85 | export async function requestProduction(call: Call, region: string, domain: string): Promise<void> { | |
| 86 | await call("ses", region, { | |
| 87 | rest: "POST", | |
| 88 | operation: "PutAccountDetails", | |
| 89 | path: "/v2/email/account/details", | |
| 90 | body: { | |
| 91 | MailType: "TRANSACTIONAL", | |
| 92 | WebsiteURL: `https://${domain}`, | |
| 93 | ContactLanguage: "EN", | |
| 94 | UseCaseDescription: "Account verification and notification mail for a self-hosted forge: one message to a person who signed up or asked for it. Bounces and complaints are counted and acted on.", | |
| 95 | ProductionAccessEnabled: true, | |
| 96 | }, | |
| 97 | }); | |
| 98 | } | |
| 99 | ||
| 100 | /** Make the user, its send-only policy and its key; the secret leaves only in the return. */ | |
| 101 | export async function makeSender(call: Call, user: string, domain: string, region: string): Promise<{ keyId: string; secret: string }> { | |
| 102 | if (!MAIL_USER.test(user)) throw new Error("not the forge's mail user"); | |
| 103 | const account = val(parseXml(await call("sts", "us-east-1", { action: "GetCallerIdentity", version: "2011-06-15" })), "GetCallerIdentityResult/Account"); | |
| 104 | if (!/^\d{12}$/.test(account)) throw new Error("AWS did not say which account this is"); | |
| 105 | const policy = sendOnlyPolicy(`arn:aws:ses:${region}:${account}:identity/${domain}`); | |
| 106 | try { | |
| 107 | await call("iam", "us-east-1", { action: "CreateUser", version: IAM, params: { UserName: user } }); | |
| 108 | } catch (e) { | |
| 109 | if (!(e instanceof AwsRefused && e.code === "EntityAlreadyExists")) throw e; | |
| 110 | } | |
| 111 | await call("iam", "us-east-1", { action: "PutUserPolicy", version: IAM, params: { UserName: user, PolicyName: "send-mail", PolicyDocument: policy } }); | |
| 112 | // Only called while the row holds no key id, so any key the user has is one a crash left behind. | |
| 113 | await dropKeys(call, user); | |
| 114 | const x = parseXml(await call("iam", "us-east-1", { action: "CreateAccessKey", version: IAM, params: { UserName: user } })); | |
| 115 | const keyId = val(x, "CreateAccessKeyResult/AccessKey/AccessKeyId"); | |
| 116 | const secret = val(x, "CreateAccessKeyResult/AccessKey/SecretAccessKey"); | |
| 117 | if (keyId === "" || secret === "") throw new Error("AWS answered without a key"); | |
| 118 | return { keyId, secret }; | |
| 119 | } | |
| 120 | ||
| 121 | /** Sent, bounced and complained, over the last two weeks (SES keeps that long). */ | |
| 122 | export async function readStatistics(call: Call, region: string): Promise<{ sent: number; bounces: number; complaints: number }> { | |
| 123 | const x = parseXml(await call("ses", region, { action: "GetSendStatistics", version: SES })); | |
| 124 | let sent = 0; | |
| 125 | let bounces = 0; | |
| 126 | let complaints = 0; | |
| 127 | for (const p of items(x, "GetSendStatisticsResult/SendDataPoints")) { | |
| 128 | sent += Number(val(p, "DeliveryAttempts")) || 0; | |
| 129 | bounces += Number(val(p, "Bounces")) || 0; | |
| 130 | complaints += Number(val(p, "Complaints")) || 0; | |
| 131 | } | |
| 132 | return { sent, bounces, complaints }; | |
| 133 | } | |
| 134 | ||
| 135 | /** | |
| 136 | * Take down what `makeSender` and `makeIdentity` made; what is already gone is as good as gone. An | |
| 137 | * empty `domain` leaves the identity alone (it was not made here, or was never made). | |
| 138 | */ | |
| 139 | export async function takeDown(call: Call, region: string, made: { user: string; domain: string }): Promise<void> { | |
| 140 | if (!MAIL_USER.test(made.user)) throw new Error("not the forge's mail user"); | |
| 141 | const gone = async (run: () => Promise<unknown>): Promise<void> => { | |
| 142 | try { | |
| 143 | await run(); | |
| 144 | } catch (e) { | |
| 145 | if (!(e instanceof AwsRefused && (e.status === 404 || e.code === "NoSuchEntity" || e.code === "NotFoundException"))) throw e; | |
| 146 | } | |
| 147 | }; | |
| 148 | await gone(() => dropKeys(call, made.user)); | |
| 149 | await gone(() => call("iam", "us-east-1", { action: "DeleteUserPolicy", version: IAM, params: { UserName: made.user, PolicyName: "send-mail" } })); | |
| 150 | await gone(() => call("iam", "us-east-1", { action: "DeleteUser", version: IAM, params: { UserName: made.user } })); | |
| 151 | if (made.domain !== "") await gone(() => call("ses", region, { rest: "DELETE", operation: "DeleteEmailIdentity", path: path(made.domain) })); | |
| 152 | } |
src/contract/openapi/routes/deleteApiV1MailAws.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "delete", | |
| 5 | path: "/api/v1/mail-aws", | |
| 6 | summary: "Undo mail from the owner's AWS account", | |
| 7 | detail: "Removes the mail key, the IAM user, the SES identity and the DNS records the set-up made, and nothing else (`confirm: true`, admin scope, a site admin's)", | |
| 8 | auth: true, | |
| 9 | body: { confirm: "boolean" }, | |
| 10 | role: "admin", | |
| 11 | refusals: { unconfirmed: "without `confirm: true`; `say` names what undo would remove (422)", refused: "AWS or Cloudflare would not remove everything; `error` says what is left, and a second undo carries on (422)" }, | |
| 12 | refuses: [401, 403, 422], | |
| 13 | }; |
src/contract/openapi/routes/getApiV1MailAws.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/mail-aws", | |
| 6 | summary: "The state of mail sent from the owner's AWS account, in words", | |
| 7 | detail: "Whether the forge sends mail from an AWS account it set up (admin scope, a site admin's): `{ line, state, domain, confirm }`; state is waiting, sandbox or sending, from the last look; `confirm` says what a set-up would make", | |
| 8 | auth: true, | |
| 9 | role: "admin", | |
| 10 | refusals: {}, | |
| 11 | refuses: [401], | |
| 12 | }; |
src/contract/openapi/routes/index.ts +3
| @@ -11,6 +11,7 @@ export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1Conversati | ||
| 11 | 11 | export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts"; |
| 12 | 12 | export { route as deleteApiV1ForgeTemplatesId } from "./deleteApiV1ForgeTemplatesId.ts"; |
| 13 | 13 | export { route as deleteApiV1ForgesRecipesName } from "./deleteApiV1ForgesRecipesName.ts"; |
| 14 | export { route as deleteApiV1MailAws } from "./deleteApiV1MailAws.ts"; | |
| 14 | 15 | export { route as deleteApiV1MailKeyScope } from "./deleteApiV1MailKeyScope.ts"; |
| 15 | 16 | export { route as deleteApiV1OrgsOrgTeamsTeam } from "./deleteApiV1OrgsOrgTeamsTeam.ts"; |
| 16 | 17 | export { route as deleteApiV1OrgsOrgTeamsTeamMembersUsername } from "./deleteApiV1OrgsOrgTeamsTeamMembersUsername.ts"; |
| @@ -137,6 +138,7 @@ export { route as getApiV1HomeSlots } from "./getApiV1HomeSlots.ts"; | ||
| 137 | 138 | export { route as getApiV1HomeStrip } from "./getApiV1HomeStrip.ts"; |
| 138 | 139 | export { route as getApiV1Keeper } from "./getApiV1Keeper.ts"; |
| 139 | 140 | export { route as getApiV1KeeperPulse } from "./getApiV1KeeperPulse.ts"; |
| 141 | export { route as getApiV1MailAws } from "./getApiV1MailAws.ts"; | |
| 140 | 142 | export { route as getApiV1MailKeyScope } from "./getApiV1MailKeyScope.ts"; |
| 141 | 143 | export { route as getApiV1MaintenanceDuties } from "./getApiV1MaintenanceDuties.ts"; |
| 142 | 144 | export { route as getApiV1MaintenanceRuns } from "./getApiV1MaintenanceRuns.ts"; |
| @@ -402,6 +404,7 @@ export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClai | ||
| 402 | 404 | export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts"; |
| 403 | 405 | export { route as postApiV1GamesAgentSync } from "./postApiV1GamesAgentSync.ts"; |
| 404 | 406 | export { route as postApiV1Heartbeat } from "./postApiV1Heartbeat.ts"; |
| 407 | export { route as postApiV1MailAws } from "./postApiV1MailAws.ts"; | |
| 405 | 408 | export { route as postApiV1MaintenanceDutiesName } from "./postApiV1MaintenanceDutiesName.ts"; |
| 406 | 409 | export { route as postApiV1Migrate } from "./postApiV1Migrate.ts"; |
| 407 | 410 | export { route as postApiV1Orgs } from "./postApiV1Orgs.ts"; |
src/contract/openapi/routes/postApiV1MailAws.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/mail-aws", | |
| 6 | summary: "Set up, look at or test mail from the owner's AWS account", | |
| 7 | detail: | |
| 8 | "`step` set_up (with `aws`, `dns`, `domain`, `region` and `confirm: true`) makes an SES identity, its DKIM records in the Cloudflare account and an IAM user that may only send from it, seals that user's SMTP credential as the forge's mail key and asks AWS to leave the sandbox; a second run makes nothing new. `look` reads AWS again, `test` sends one message to the admin's own proven address (admin scope, a site admin's). The credential is never shown.", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | body: { step: "string", aws: "string", dns: "string", domain: "string", region: "string", confirm: "boolean" }, | |
| 12 | refusals: { unconfirmed: "set_up without `confirm: true` (422)", refused: "the step could not be done; `error` says why (422)" }, | |
| 13 | refuses: [401, 403, 422], | |
| 14 | }; |
src/contract/tags.ts +1
src/core/event_audience.ts +2
| @@ -325,6 +325,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 325 | 325 | kind === "forge.upstream" || |
| 326 | 326 | kind === "forge.updates_taken" || |
| 327 | 327 | kind === "cloud.write_allowed" || |
| 328 | // Mail set up from an AWS account is an admin's act (`actions/mail_aws.ts`, #18109). | |
| 329 | kind.startsWith("mail_aws.") || | |
| 328 | 330 | kind === "cloud.ceiling" || |
| 329 | 331 | // An admin acknowledging a resource as not the forge's (`cloud/watch.ts`, #16329). |
| 330 | 332 | kind === "cloud.watch_acknowledged" || |
src/core/mail_aws.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** | |
| 2 | * What the forge made to send mail from the owner's AWS account (#18109): one row, the names and | |
| 3 | * ids of the identity, the DKIM records and the IAM user, so a second run makes nothing new and | |
| 4 | * undo removes exactly these. The SMTP password is not here: it is the forge's sealed mail key. The | |
| 5 | * state is the last look at AWS, in words (`mailAwsWords`), so a page reads it without a call. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | ||
| 10 | export type MailAwsState = "" | "waiting" | "sandbox" | "sending"; | |
| 11 | ||
| 12 | export interface MailAwsRecord { | |
| 13 | readonly host: string; | |
| 14 | readonly zone: string; | |
| 15 | readonly record: string; | |
| 16 | } | |
| 17 | ||
| 18 | export interface MailAws { | |
| 19 | readonly aws: string; | |
| 20 | readonly dns: string; | |
| 21 | readonly region: string; | |
| 22 | readonly domain: string; | |
| 23 | readonly from: string; | |
| 24 | readonly user: string; | |
| 25 | /** Empty until the key is made. */ | |
| 26 | readonly keyId: string; | |
| 27 | readonly identity: boolean; | |
| 28 | /** Whether this set-up made the identity: undo deletes it only then. */ | |
| 29 | readonly identityMade: boolean; | |
| 30 | readonly records: readonly MailAwsRecord[]; | |
| 31 | readonly requested: boolean; | |
| 32 | readonly state: MailAwsState; | |
| 33 | readonly sent: number; | |
| 34 | readonly bounces: number; | |
| 35 | readonly complaints: number; | |
| 36 | readonly lookedAt: string | null; | |
| 37 | } | |
| 38 | ||
| 39 | interface Row { | |
| 40 | aws: string; | |
| 41 | dns: string; | |
| 42 | region: string; | |
| 43 | domain: string; | |
| 44 | from_addr: string; | |
| 45 | iam_user: string; | |
| 46 | key_id: string; | |
| 47 | identity: number; | |
| 48 | identity_made: number; | |
| 49 | records: string; | |
| 50 | requested: number; | |
| 51 | state: string; | |
| 52 | sent: number; | |
| 53 | bounces: number; | |
| 54 | complaints: number; | |
| 55 | looked_at: string | null; | |
| 56 | } | |
| 57 | ||
| 58 | const made = new WeakSet<Database>(); | |
| 59 | function table(db: Database): void { | |
| 60 | if (made.has(db)) return; | |
| 61 | db.run(`CREATE TABLE IF NOT EXISTS mail_aws ( | |
| 62 | id TEXT PRIMARY KEY CHECK (id = 'forge'), | |
| 63 | aws TEXT NOT NULL, | |
| 64 | dns TEXT NOT NULL, | |
| 65 | region TEXT NOT NULL, | |
| 66 | domain TEXT NOT NULL, | |
| 67 | from_addr TEXT NOT NULL, | |
| 68 | iam_user TEXT NOT NULL, | |
| 69 | key_id TEXT NOT NULL DEFAULT '', | |
| 70 | identity INTEGER NOT NULL DEFAULT 0, | |
| 71 | records TEXT NOT NULL DEFAULT '[]', | |
| 72 | requested INTEGER NOT NULL DEFAULT 0, | |
| 73 | state TEXT NOT NULL DEFAULT '', | |
| 74 | sent INTEGER NOT NULL DEFAULT 0, | |
| 75 | bounces INTEGER NOT NULL DEFAULT 0, | |
| 76 | complaints INTEGER NOT NULL DEFAULT 0, | |
| 77 | looked_at TEXT | |
| 78 | )`); | |
| 79 | if (!db.query<{ name: string }, []>("PRAGMA table_info(mail_aws)").all().some((c) => c.name === "identity_made")) db.run("ALTER TABLE mail_aws ADD COLUMN identity_made INTEGER NOT NULL DEFAULT 0"); | |
| 80 | made.add(db); | |
| 81 | } | |
| 82 | ||
| 83 | export function getMailAws(db: Database): MailAws | undefined { | |
| 84 | table(db); | |
| 85 | const r = db.query<Row, []>("SELECT * FROM mail_aws WHERE id = 'forge'").get(); | |
| 86 | return r === null | |
| 87 | ? undefined | |
| 88 | : { | |
| 89 | aws: r.aws, | |
| 90 | dns: r.dns, | |
| 91 | region: r.region, | |
| 92 | domain: r.domain, | |
| 93 | from: r.from_addr, | |
| 94 | user: r.iam_user, | |
| 95 | keyId: r.key_id, | |
| 96 | identity: r.identity === 1, | |
| 97 | identityMade: r.identity_made === 1, | |
| 98 | records: JSON.parse(r.records) as MailAwsRecord[], | |
| 99 | requested: r.requested === 1, | |
| 100 | state: r.state as MailAwsState, | |
| 101 | sent: r.sent, | |
| 102 | bounces: r.bounces, | |
| 103 | complaints: r.complaints, | |
| 104 | lookedAt: r.looked_at, | |
| 105 | }; | |
| 106 | } | |
| 107 | ||
| 108 | /** Write the row whole: a step's progress is saved as it is made. */ | |
| 109 | export function putMailAws(db: Database, m: MailAws): void { | |
| 110 | table(db); | |
| 111 | db.query( | |
| 112 | `INSERT OR REPLACE INTO mail_aws (id, aws, dns, region, domain, from_addr, iam_user, key_id, identity, identity_made, records, requested, state, sent, bounces, complaints, looked_at) | |
| 113 | VALUES ('forge', ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?16, ?9, ?10, ?11, ?12, ?13, ?14, ?15)`, | |
| 114 | ).run(m.aws, m.dns, m.region, m.domain, m.from, m.user, m.keyId, m.identity ? 1 : 0, JSON.stringify(m.records), m.requested ? 1 : 0, m.state, m.sent, m.bounces, m.complaints, m.lookedAt, m.identityMade ? 1 : 0); | |
| 115 | } | |
| 116 | ||
| 117 | export function forgetMailAws(db: Database): void { | |
| 118 | table(db); | |
| 119 | db.run("DELETE FROM mail_aws WHERE id = 'forge'"); | |
| 120 | } | |
| 121 | ||
| 122 | /** The state in words, for the mail key's line. */ | |
| 123 | export function mailAwsWords(m: MailAws): string { | |
| 124 | const counts = m.lookedAt === null ? "" : ` ${m.sent} sent, ${m.bounces} bounced, ${m.complaints} complaints in the last 14 days.`; | |
| 125 | switch (m.state) { | |
| 126 | case "waiting": | |
| 127 | return `Sending from AWS SES as ${m.domain}: waiting for DNS (AWS has not yet seen the DKIM records).${counts}`; | |
| 128 | case "sandbox": | |
| 129 | return `Sending from AWS SES as ${m.domain}: in the sandbox (mail reaches verified addresses only) until AWS answers the request for production access.${counts}`; | |
| 130 | case "sending": | |
| 131 | return `Sending from AWS SES as ${m.domain}: sending.${counts}`; | |
| 132 | default: | |
| 133 | return `Sending from AWS SES as ${m.domain}: not looked at yet.`; | |
| 134 | } | |
| 135 | } |
src/generated/marks.ts +168 −166
| @@ -49,172 +49,173 @@ import k44 from "../http/marks/api-v1-heartbeat.json"; | ||
| 49 | 49 | import k45 from "../http/marks/api-v1-here.json"; |
| 50 | 50 | import k46 from "../http/marks/api-v1-home.json"; |
| 51 | 51 | import k47 from "../http/marks/api-v1-keeper.json"; |
| 52 | import k48 from "../http/marks/api-v1-mail-key.json"; | |
| 53 | import k49 from "../http/marks/api-v1-maintenance.json"; | |
| 54 | import k50 from "../http/marks/api-v1-map.json"; | |
| 55 | import k51 from "../http/marks/api-v1-may.json"; | |
| 56 | import k52 from "../http/marks/api-v1-migrate.json"; | |
| 57 | import k53 from "../http/marks/api-v1-models.json"; | |
| 58 | import k54 from "../http/marks/api-v1-offers.json"; | |
| 59 | import k55 from "../http/marks/api-v1-openapi.json.json"; | |
| 60 | import k56 from "../http/marks/api-v1-orgs.json"; | |
| 61 | import k57 from "../http/marks/api-v1-packs.json"; | |
| 62 | import k58 from "../http/marks/api-v1-passport.json"; | |
| 63 | import k59 from "../http/marks/api-v1-places.json"; | |
| 64 | import k60 from "../http/marks/api-v1-plans.json"; | |
| 65 | import k61 from "../http/marks/api-v1-proof.json"; | |
| 66 | import k62 from "../http/marks/api-v1-reach.json"; | |
| 67 | import k63 from "../http/marks/api-v1-release.json"; | |
| 68 | import k64 from "../http/marks/api-v1-releases.json"; | |
| 69 | import k65 from "../http/marks/api-v1-repos.json"; | |
| 70 | import k66 from "../http/marks/api-v1-returns.json"; | |
| 71 | import k67 from "../http/marks/api-v1-runner.json"; | |
| 72 | import k68 from "../http/marks/api-v1-search.json"; | |
| 73 | import k69 from "../http/marks/api-v1-secrets.json"; | |
| 74 | import k70 from "../http/marks/api-v1-sessions.json"; | |
| 75 | import k71 from "../http/marks/api-v1-share.json"; | |
| 76 | import k72 from "../http/marks/api-v1-slash.json"; | |
| 77 | import k73 from "../http/marks/api-v1-start.json"; | |
| 78 | import k74 from "../http/marks/api-v1-status.json"; | |
| 79 | import k75 from "../http/marks/api-v1-telemetry.json"; | |
| 80 | import k76 from "../http/marks/api-v1-templates.json"; | |
| 81 | import k77 from "../http/marks/api-v1-thoughts.json"; | |
| 82 | import k78 from "../http/marks/api-v1-timers.json"; | |
| 83 | import k79 from "../http/marks/api-v1-tokens.json"; | |
| 84 | import k80 from "../http/marks/api-v1-usage.json"; | |
| 85 | import k81 from "../http/marks/api-v1-user.json"; | |
| 86 | import k82 from "../http/marks/api-v1-users.json"; | |
| 87 | import k83 from "../http/marks/api-v1-version.json"; | |
| 88 | import k84 from "../http/marks/api-v1.json"; | |
| 89 | import k85 from "../http/marks/api.json"; | |
| 90 | import k86 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 91 | import k87 from "../http/marks/apple-touch-icon.png.json"; | |
| 92 | import k88 from "../http/marks/apps.json"; | |
| 93 | import k89 from "../http/marks/archive.json"; | |
| 94 | import k90 from "../http/marks/asked.json"; | |
| 95 | import k91 from "../http/marks/asks.json"; | |
| 96 | import k92 from "../http/marks/assets.json"; | |
| 97 | import k93 from "../http/marks/audit.csv.json"; | |
| 98 | import k94 from "../http/marks/audit.json"; | |
| 99 | import k95 from "../http/marks/big.json"; | |
| 100 | import k96 from "../http/marks/board.json"; | |
| 101 | import k97 from "../http/marks/boards.json"; | |
| 102 | import k98 from "../http/marks/bring.json"; | |
| 103 | import k99 from "../http/marks/broker.json"; | |
| 104 | import k100 from "../http/marks/changelog.atom.json"; | |
| 105 | import k101 from "../http/marks/changelog.json"; | |
| 106 | import k102 from "../http/marks/claim.json"; | |
| 107 | import k103 from "../http/marks/client-clouds.json"; | |
| 108 | import k104 from "../http/marks/cloud.json"; | |
| 109 | import k105 from "../http/marks/cockpit.json"; | |
| 110 | import k106 from "../http/marks/contract.json"; | |
| 111 | import k107 from "../http/marks/contribute.json"; | |
| 112 | import k108 from "../http/marks/csp-report.json"; | |
| 113 | import k109 from "../http/marks/dash.json"; | |
| 114 | import k110 from "../http/marks/data.json"; | |
| 115 | import k111 from "../http/marks/dataset.json"; | |
| 116 | import k112 from "../http/marks/deploy-to.json"; | |
| 117 | import k113 from "../http/marks/design.json"; | |
| 118 | import k114 from "../http/marks/desk.json"; | |
| 119 | import k115 from "../http/marks/displays.json"; | |
| 120 | import k116 from "../http/marks/docs.json"; | |
| 121 | import k117 from "../http/marks/edge.json"; | |
| 122 | import k118 from "../http/marks/edition.json"; | |
| 123 | import k119 from "../http/marks/events.json"; | |
| 124 | import k120 from "../http/marks/explore.atom.json"; | |
| 125 | import k121 from "../http/marks/explore.json"; | |
| 126 | import k122 from "../http/marks/explore.json.json"; | |
| 127 | import k123 from "../http/marks/family.json"; | |
| 128 | import k124 from "../http/marks/favicon.ico.json"; | |
| 129 | import k125 from "../http/marks/feed.json"; | |
| 130 | import k126 from "../http/marks/feed.json.json"; | |
| 131 | import k127 from "../http/marks/first-admin.json"; | |
| 132 | import k128 from "../http/marks/fleet.json"; | |
| 133 | import k129 from "../http/marks/flow.json"; | |
| 134 | import k130 from "../http/marks/forge.json"; | |
| 135 | import k131 from "../http/marks/forges.json"; | |
| 136 | import k132 from "../http/marks/forks.json"; | |
| 137 | import k133 from "../http/marks/front.json"; | |
| 138 | import k134 from "../http/marks/funnel.json"; | |
| 139 | import k135 from "../http/marks/games.json"; | |
| 140 | import k136 from "../http/marks/go.json"; | |
| 141 | import k137 from "../http/marks/health.json"; | |
| 142 | import k138 from "../http/marks/home.json"; | |
| 143 | import k139 from "../http/marks/hooks.json"; | |
| 144 | import k140 from "../http/marks/icons.json"; | |
| 145 | import k141 from "../http/marks/infra.json"; | |
| 146 | import k142 from "../http/marks/join.json"; | |
| 147 | import k143 from "../http/marks/live.json"; | |
| 148 | import k144 from "../http/marks/llms-full.txt.json"; | |
| 149 | import k145 from "../http/marks/llms.txt.json"; | |
| 150 | import k146 from "../http/marks/login.json"; | |
| 151 | import k147 from "../http/marks/logout.json"; | |
| 152 | import k148 from "../http/marks/maintenance-json.json"; | |
| 153 | import k149 from "../http/marks/maintenance.json"; | |
| 154 | import k150 from "../http/marks/manifest.webmanifest.json"; | |
| 155 | import k151 from "../http/marks/map.json"; | |
| 156 | import k152 from "../http/marks/mcp.json"; | |
| 157 | import k153 from "../http/marks/measure.json"; | |
| 158 | import k154 from "../http/marks/metrics.json"; | |
| 159 | import k155 from "../http/marks/migrate.json"; | |
| 160 | import k156 from "../http/marks/new.json"; | |
| 161 | import k157 from "../http/marks/next.json"; | |
| 162 | import k158 from "../http/marks/notes.json"; | |
| 163 | import k159 from "../http/marks/now.json"; | |
| 164 | import k160 from "../http/marks/oauth.json"; | |
| 165 | import k161 from "../http/marks/oembed.json"; | |
| 166 | import k162 from "../http/marks/offers.json"; | |
| 167 | import k163 from "../http/marks/offline.json"; | |
| 168 | import k164 from "../http/marks/og.json"; | |
| 169 | import k165 from "../http/marks/openapi.json.json"; | |
| 170 | import k166 from "../http/marks/opensearch.xml.json"; | |
| 171 | import k167 from "../http/marks/organizations.json"; | |
| 172 | import k168 from "../http/marks/origins.json"; | |
| 173 | import k169 from "../http/marks/owner.atom.json"; | |
| 174 | import k170 from "../http/marks/owner.json"; | |
| 175 | import k171 from "../http/marks/packs.json"; | |
| 176 | import k172 from "../http/marks/peek.json"; | |
| 177 | import k173 from "../http/marks/pinned.json"; | |
| 178 | import k174 from "../http/marks/pipeline.json"; | |
| 179 | import k175 from "../http/marks/plugins.json"; | |
| 180 | import k176 from "../http/marks/pricing.json"; | |
| 181 | import k177 from "../http/marks/privacy.json"; | |
| 182 | import k178 from "../http/marks/r.json"; | |
| 183 | import k179 from "../http/marks/recover.json"; | |
| 184 | import k180 from "../http/marks/releases.json"; | |
| 185 | import k181 from "../http/marks/releases.json.json"; | |
| 186 | import k182 from "../http/marks/repos.json"; | |
| 187 | import k183 from "../http/marks/resilience.json"; | |
| 188 | import k184 from "../http/marks/review.json"; | |
| 189 | import k185 from "../http/marks/robots.txt.json"; | |
| 190 | import k186 from "../http/marks/root.json"; | |
| 191 | import k187 from "../http/marks/runs.json"; | |
| 192 | import k188 from "../http/marks/script-error.json"; | |
| 193 | import k189 from "../http/marks/search.json"; | |
| 194 | import k190 from "../http/marks/security.json"; | |
| 195 | import k191 from "../http/marks/settings.json"; | |
| 196 | import k192 from "../http/marks/sign-in.json"; | |
| 197 | import k193 from "../http/marks/signin.json"; | |
| 198 | import k194 from "../http/marks/signup.json"; | |
| 199 | import k195 from "../http/marks/sitemap.xml.json"; | |
| 200 | import k196 from "../http/marks/status.json"; | |
| 201 | import k197 from "../http/marks/support.json"; | |
| 202 | import k198 from "../http/marks/sw.js.json"; | |
| 203 | import k199 from "../http/marks/system.json"; | |
| 204 | import k200 from "../http/marks/tab.json"; | |
| 205 | import k201 from "../http/marks/tabforge.json"; | |
| 206 | import k202 from "../http/marks/talk.json"; | |
| 207 | import k203 from "../http/marks/tell.json"; | |
| 208 | import k204 from "../http/marks/templates.json"; | |
| 209 | import k205 from "../http/marks/templates.json.json"; | |
| 210 | import k206 from "../http/marks/terms.json"; | |
| 211 | import k207 from "../http/marks/theme.json"; | |
| 212 | import k208 from "../http/marks/toolbar-lab.js.json"; | |
| 213 | import k209 from "../http/marks/toolbar-lab.json"; | |
| 214 | import k210 from "../http/marks/traces.json"; | |
| 215 | import k211 from "../http/marks/verify.json"; | |
| 216 | import k212 from "../http/marks/welcome.json"; | |
| 217 | import k213 from "../http/marks/well-known.json"; | |
| 52 | import k48 from "../http/marks/api-v1-mail-aws.json"; | |
| 53 | import k49 from "../http/marks/api-v1-mail-key.json"; | |
| 54 | import k50 from "../http/marks/api-v1-maintenance.json"; | |
| 55 | import k51 from "../http/marks/api-v1-map.json"; | |
| 56 | import k52 from "../http/marks/api-v1-may.json"; | |
| 57 | import k53 from "../http/marks/api-v1-migrate.json"; | |
| 58 | import k54 from "../http/marks/api-v1-models.json"; | |
| 59 | import k55 from "../http/marks/api-v1-offers.json"; | |
| 60 | import k56 from "../http/marks/api-v1-openapi.json.json"; | |
| 61 | import k57 from "../http/marks/api-v1-orgs.json"; | |
| 62 | import k58 from "../http/marks/api-v1-packs.json"; | |
| 63 | import k59 from "../http/marks/api-v1-passport.json"; | |
| 64 | import k60 from "../http/marks/api-v1-places.json"; | |
| 65 | import k61 from "../http/marks/api-v1-plans.json"; | |
| 66 | import k62 from "../http/marks/api-v1-proof.json"; | |
| 67 | import k63 from "../http/marks/api-v1-reach.json"; | |
| 68 | import k64 from "../http/marks/api-v1-release.json"; | |
| 69 | import k65 from "../http/marks/api-v1-releases.json"; | |
| 70 | import k66 from "../http/marks/api-v1-repos.json"; | |
| 71 | import k67 from "../http/marks/api-v1-returns.json"; | |
| 72 | import k68 from "../http/marks/api-v1-runner.json"; | |
| 73 | import k69 from "../http/marks/api-v1-search.json"; | |
| 74 | import k70 from "../http/marks/api-v1-secrets.json"; | |
| 75 | import k71 from "../http/marks/api-v1-sessions.json"; | |
| 76 | import k72 from "../http/marks/api-v1-share.json"; | |
| 77 | import k73 from "../http/marks/api-v1-slash.json"; | |
| 78 | import k74 from "../http/marks/api-v1-start.json"; | |
| 79 | import k75 from "../http/marks/api-v1-status.json"; | |
| 80 | import k76 from "../http/marks/api-v1-telemetry.json"; | |
| 81 | import k77 from "../http/marks/api-v1-templates.json"; | |
| 82 | import k78 from "../http/marks/api-v1-thoughts.json"; | |
| 83 | import k79 from "../http/marks/api-v1-timers.json"; | |
| 84 | import k80 from "../http/marks/api-v1-tokens.json"; | |
| 85 | import k81 from "../http/marks/api-v1-usage.json"; | |
| 86 | import k82 from "../http/marks/api-v1-user.json"; | |
| 87 | import k83 from "../http/marks/api-v1-users.json"; | |
| 88 | import k84 from "../http/marks/api-v1-version.json"; | |
| 89 | import k85 from "../http/marks/api-v1.json"; | |
| 90 | import k86 from "../http/marks/api.json"; | |
| 91 | import k87 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 92 | import k88 from "../http/marks/apple-touch-icon.png.json"; | |
| 93 | import k89 from "../http/marks/apps.json"; | |
| 94 | import k90 from "../http/marks/archive.json"; | |
| 95 | import k91 from "../http/marks/asked.json"; | |
| 96 | import k92 from "../http/marks/asks.json"; | |
| 97 | import k93 from "../http/marks/assets.json"; | |
| 98 | import k94 from "../http/marks/audit.csv.json"; | |
| 99 | import k95 from "../http/marks/audit.json"; | |
| 100 | import k96 from "../http/marks/big.json"; | |
| 101 | import k97 from "../http/marks/board.json"; | |
| 102 | import k98 from "../http/marks/boards.json"; | |
| 103 | import k99 from "../http/marks/bring.json"; | |
| 104 | import k100 from "../http/marks/broker.json"; | |
| 105 | import k101 from "../http/marks/changelog.atom.json"; | |
| 106 | import k102 from "../http/marks/changelog.json"; | |
| 107 | import k103 from "../http/marks/claim.json"; | |
| 108 | import k104 from "../http/marks/client-clouds.json"; | |
| 109 | import k105 from "../http/marks/cloud.json"; | |
| 110 | import k106 from "../http/marks/cockpit.json"; | |
| 111 | import k107 from "../http/marks/contract.json"; | |
| 112 | import k108 from "../http/marks/contribute.json"; | |
| 113 | import k109 from "../http/marks/csp-report.json"; | |
| 114 | import k110 from "../http/marks/dash.json"; | |
| 115 | import k111 from "../http/marks/data.json"; | |
| 116 | import k112 from "../http/marks/dataset.json"; | |
| 117 | import k113 from "../http/marks/deploy-to.json"; | |
| 118 | import k114 from "../http/marks/design.json"; | |
| 119 | import k115 from "../http/marks/desk.json"; | |
| 120 | import k116 from "../http/marks/displays.json"; | |
| 121 | import k117 from "../http/marks/docs.json"; | |
| 122 | import k118 from "../http/marks/edge.json"; | |
| 123 | import k119 from "../http/marks/edition.json"; | |
| 124 | import k120 from "../http/marks/events.json"; | |
| 125 | import k121 from "../http/marks/explore.atom.json"; | |
| 126 | import k122 from "../http/marks/explore.json"; | |
| 127 | import k123 from "../http/marks/explore.json.json"; | |
| 128 | import k124 from "../http/marks/family.json"; | |
| 129 | import k125 from "../http/marks/favicon.ico.json"; | |
| 130 | import k126 from "../http/marks/feed.json"; | |
| 131 | import k127 from "../http/marks/feed.json.json"; | |
| 132 | import k128 from "../http/marks/first-admin.json"; | |
| 133 | import k129 from "../http/marks/fleet.json"; | |
| 134 | import k130 from "../http/marks/flow.json"; | |
| 135 | import k131 from "../http/marks/forge.json"; | |
| 136 | import k132 from "../http/marks/forges.json"; | |
| 137 | import k133 from "../http/marks/forks.json"; | |
| 138 | import k134 from "../http/marks/front.json"; | |
| 139 | import k135 from "../http/marks/funnel.json"; | |
| 140 | import k136 from "../http/marks/games.json"; | |
| 141 | import k137 from "../http/marks/go.json"; | |
| 142 | import k138 from "../http/marks/health.json"; | |
| 143 | import k139 from "../http/marks/home.json"; | |
| 144 | import k140 from "../http/marks/hooks.json"; | |
| 145 | import k141 from "../http/marks/icons.json"; | |
| 146 | import k142 from "../http/marks/infra.json"; | |
| 147 | import k143 from "../http/marks/join.json"; | |
| 148 | import k144 from "../http/marks/live.json"; | |
| 149 | import k145 from "../http/marks/llms-full.txt.json"; | |
| 150 | import k146 from "../http/marks/llms.txt.json"; | |
| 151 | import k147 from "../http/marks/login.json"; | |
| 152 | import k148 from "../http/marks/logout.json"; | |
| 153 | import k149 from "../http/marks/maintenance-json.json"; | |
| 154 | import k150 from "../http/marks/maintenance.json"; | |
| 155 | import k151 from "../http/marks/manifest.webmanifest.json"; | |
| 156 | import k152 from "../http/marks/map.json"; | |
| 157 | import k153 from "../http/marks/mcp.json"; | |
| 158 | import k154 from "../http/marks/measure.json"; | |
| 159 | import k155 from "../http/marks/metrics.json"; | |
| 160 | import k156 from "../http/marks/migrate.json"; | |
| 161 | import k157 from "../http/marks/new.json"; | |
| 162 | import k158 from "../http/marks/next.json"; | |
| 163 | import k159 from "../http/marks/notes.json"; | |
| 164 | import k160 from "../http/marks/now.json"; | |
| 165 | import k161 from "../http/marks/oauth.json"; | |
| 166 | import k162 from "../http/marks/oembed.json"; | |
| 167 | import k163 from "../http/marks/offers.json"; | |
| 168 | import k164 from "../http/marks/offline.json"; | |
| 169 | import k165 from "../http/marks/og.json"; | |
| 170 | import k166 from "../http/marks/openapi.json.json"; | |
| 171 | import k167 from "../http/marks/opensearch.xml.json"; | |
| 172 | import k168 from "../http/marks/organizations.json"; | |
| 173 | import k169 from "../http/marks/origins.json"; | |
| 174 | import k170 from "../http/marks/owner.atom.json"; | |
| 175 | import k171 from "../http/marks/owner.json"; | |
| 176 | import k172 from "../http/marks/packs.json"; | |
| 177 | import k173 from "../http/marks/peek.json"; | |
| 178 | import k174 from "../http/marks/pinned.json"; | |
| 179 | import k175 from "../http/marks/pipeline.json"; | |
| 180 | import k176 from "../http/marks/plugins.json"; | |
| 181 | import k177 from "../http/marks/pricing.json"; | |
| 182 | import k178 from "../http/marks/privacy.json"; | |
| 183 | import k179 from "../http/marks/r.json"; | |
| 184 | import k180 from "../http/marks/recover.json"; | |
| 185 | import k181 from "../http/marks/releases.json"; | |
| 186 | import k182 from "../http/marks/releases.json.json"; | |
| 187 | import k183 from "../http/marks/repos.json"; | |
| 188 | import k184 from "../http/marks/resilience.json"; | |
| 189 | import k185 from "../http/marks/review.json"; | |
| 190 | import k186 from "../http/marks/robots.txt.json"; | |
| 191 | import k187 from "../http/marks/root.json"; | |
| 192 | import k188 from "../http/marks/runs.json"; | |
| 193 | import k189 from "../http/marks/script-error.json"; | |
| 194 | import k190 from "../http/marks/search.json"; | |
| 195 | import k191 from "../http/marks/security.json"; | |
| 196 | import k192 from "../http/marks/settings.json"; | |
| 197 | import k193 from "../http/marks/sign-in.json"; | |
| 198 | import k194 from "../http/marks/signin.json"; | |
| 199 | import k195 from "../http/marks/signup.json"; | |
| 200 | import k196 from "../http/marks/sitemap.xml.json"; | |
| 201 | import k197 from "../http/marks/status.json"; | |
| 202 | import k198 from "../http/marks/support.json"; | |
| 203 | import k199 from "../http/marks/sw.js.json"; | |
| 204 | import k200 from "../http/marks/system.json"; | |
| 205 | import k201 from "../http/marks/tab.json"; | |
| 206 | import k202 from "../http/marks/tabforge.json"; | |
| 207 | import k203 from "../http/marks/talk.json"; | |
| 208 | import k204 from "../http/marks/tell.json"; | |
| 209 | import k205 from "../http/marks/templates.json"; | |
| 210 | import k206 from "../http/marks/templates.json.json"; | |
| 211 | import k207 from "../http/marks/terms.json"; | |
| 212 | import k208 from "../http/marks/theme.json"; | |
| 213 | import k209 from "../http/marks/toolbar-lab.js.json"; | |
| 214 | import k210 from "../http/marks/toolbar-lab.json"; | |
| 215 | import k211 from "../http/marks/traces.json"; | |
| 216 | import k212 from "../http/marks/verify.json"; | |
| 217 | import k213 from "../http/marks/welcome.json"; | |
| 218 | import k214 from "../http/marks/well-known.json"; | |
| 218 | 219 | |
| 219 | 220 | /** Each file of `http/marks/`, parsed, in name order. */ |
| 220 | 221 | export const MARK_FILES: readonly unknown[] = [ |
| @@ -432,4 +433,5 @@ export const MARK_FILES: readonly unknown[] = [ | ||
| 432 | 433 | k211, |
| 433 | 434 | k212, |
| 434 | 435 | k213, |
| 436 | k214, | |
| 435 | 437 | ]; |
src/http/api.ts +2
| @@ -391,6 +391,7 @@ import { promptRoutes } from "./api/prompts.ts"; | ||
| 391 | 391 | import { cloudRoutes } from "./api/cloud.ts"; |
| 392 | 392 | import { secretRoutes } from "./api/secrets.ts"; |
| 393 | 393 | import { mailKeyRoutes } from "./api/mail_key.ts"; |
| 394 | import { mailAwsRoutes } from "./api/mail_aws.ts"; | |
| 394 | 395 | import { drillRoutes } from "./api/drills.ts"; |
| 395 | 396 | import { featureRoutes } from "./api/features.ts"; |
| 396 | 397 | import { upstreamRoutes } from "./api/upstream.ts"; |
| @@ -3361,6 +3362,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 3361 | 3362 | |
| 3362 | 3363 | secretRoutes(router); |
| 3363 | 3364 | mailKeyRoutes(router); |
| 3365 | mailAwsRoutes(router); | |
| 3364 | 3366 | drillRoutes(router); |
| 3365 | 3367 | featureRoutes(router); |
| 3366 | 3368 |
src/http/api/mail_aws.ts added +50
| @@ -0,0 +1,50 @@ | ||
| 1 | /** | |
| 2 | * Mail from the owner's AWS account over the API (#18109): `GET /api/v1/mail-aws` says the state in | |
| 3 | * words, `POST` takes a `step` (set_up with `confirm: true`, look, test), `DELETE` undoes (with | |
| 4 | * `confirm: true`, as `set_up` has). The rules are `actions/mail_aws.ts`'s; an answer is a | |
| 5 | * sentence, never a credential. | |
| 6 | */ | |
| 7 | ||
| 8 | import { lookMailAws, mailAwsConfirm, mailAwsUndoConfirm, setUpMailAws, testMailAws, undoMailAws } from "../../actions/mail_aws.ts"; | |
| 9 | import { getMailAws, mailAwsWords } from "../../core/mail_aws.ts"; | |
| 10 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 11 | import type { Handler } from "../context.ts"; | |
| 12 | import { body, json, requireScope, str } from "../respond.ts"; | |
| 13 | import type { Router } from "../router.ts"; | |
| 14 | ||
| 15 | export function mailAwsRoutes(router: Router<Handler>): void { | |
| 16 | router.add("GET", "/api/v1/mail-aws", (ctx) => { | |
| 17 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 18 | const denied = requireScope(ctx, "admin"); | |
| 19 | if (denied) return denied; | |
| 20 | if (!ctx.auth.user?.isAdmin) return json({ error: "forbidden" }, 403); | |
| 21 | const m = getMailAws(ctx.app.db); | |
| 22 | return json({ line: m === undefined ? null : mailAwsWords(m), state: m?.state ?? null, domain: m?.domain ?? null, confirm: mailAwsConfirm({ aws: "<aws>", dns: "<dns>", domain: m?.domain ?? "<domain>", region: m?.region ?? "<region>" }) }); | |
| 23 | }); | |
| 24 | ||
| 25 | router.add("POST", "/api/v1/mail-aws", async (ctx) => { | |
| 26 | const denied = requireScope(ctx, "admin"); | |
| 27 | if (denied) return denied; | |
| 28 | const input = await body(ctx.request); | |
| 29 | const step = str(input.step); | |
| 30 | const ask = { aws: str(input.aws), dns: str(input.dns), domain: str(input.domain).toLowerCase(), region: str(input.region) }; | |
| 31 | if (step === "set_up" && input.confirm !== true) return json({ error: "unconfirmed", say: mailAwsConfirm(ask) }, 422); | |
| 32 | const done = step === "set_up" ? await setUpMailAws(ctx.app, ctx.auth.user, ask) : step === "look" ? await lookMailAws(ctx.app, ctx.auth.user) : step === "test" ? await testMailAws(ctx.app, ctx.auth.user) : undefined; | |
| 33 | if (done === undefined) return json({ error: "refused", say: "step is set_up, look or test" }, 422); | |
| 34 | if (!done.ok && done.error === "not_found") return json({ error: "forbidden" }, 403); | |
| 35 | return done.ok ? json({ ok: true, line: done.value }) : json({ error: "refused", say: done.error }, 422); | |
| 36 | }); | |
| 37 | ||
| 38 | router.add("DELETE", "/api/v1/mail-aws", async (ctx) => { | |
| 39 | const denied = requireScope(ctx, "admin"); | |
| 40 | if (denied) return denied; | |
| 41 | if (!ctx.auth.user?.isAdmin) return json({ error: "forbidden" }, 403); | |
| 42 | const set = getMailAws(ctx.app.db); | |
| 43 | if (set === undefined) return json({ error: "refused", say: "Mail is not set up from an AWS account." }, 422); | |
| 44 | const input = await body(ctx.request); | |
| 45 | if (input.confirm !== true) return json({ error: "unconfirmed", say: mailAwsUndoConfirm(set) }, 422); | |
| 46 | const done = await undoMailAws(ctx.app, ctx.auth.user); | |
| 47 | if (!done.ok && done.error === "not_found") return json({ error: "forbidden" }, 403); | |
| 48 | return done.ok ? json({ ok: true, line: done.value }) : json({ error: "refused", say: done.error }, 422); | |
| 49 | }); | |
| 50 | } |
src/http/lazy_lists.ts +5
| @@ -95,6 +95,8 @@ export const SETTINGS_ROUTES = [ | ||
| 95 | 95 | ["POST", "/settings/subscriptions/:id/budget"], |
| 96 | 96 | ["GET", "/settings/secrets"], |
| 97 | 97 | ["POST", "/settings/secrets"], |
| 98 | ["POST", "/settings/mail-aws"], | |
| 99 | ["POST", "/settings/mail-aws/undo"], | |
| 98 | 100 | ["POST", "/settings/secrets/delete"], |
| 99 | 101 | ["GET", "/settings/devices"], |
| 100 | 102 | ["POST", "/settings/devices"], |
| @@ -1686,6 +1688,9 @@ export const API_ROUTES = [ | ||
| 1686 | 1688 | ["GET", "/api/v1/mail-key/:scope"], |
| 1687 | 1689 | ["PUT", "/api/v1/mail-key/:scope"], |
| 1688 | 1690 | ["DELETE", "/api/v1/mail-key/:scope"], |
| 1691 | ["GET", "/api/v1/mail-aws"], | |
| 1692 | ["POST", "/api/v1/mail-aws"], | |
| 1693 | ["DELETE", "/api/v1/mail-aws"], | |
| 1689 | 1694 | ["GET", "/api/v1/admin/drills"], |
| 1690 | 1695 | ["GET", "/api/v1/features"], |
| 1691 | 1696 | ["GET", "/api/v1/features/:slug"], |
src/http/marks/api-v1-mail-aws.json added +4
src/http/marks/settings.json +2
| @@ -69,6 +69,8 @@ | ||
| 69 | 69 | "/settings/subscriptions/:id/budget": "admin", |
| 70 | 70 | "/settings/secrets": "admin", |
| 71 | 71 | "/settings/secrets/delete": "admin", |
| 72 | "/settings/mail-aws": "admin", | |
| 73 | "/settings/mail-aws/undo": "admin", | |
| 72 | 74 | "/settings/devices": "admin", |
| 73 | 75 | "/settings/devices/delete": "admin", |
| 74 | 76 | "/settings/devices/grant": "admin", |
src/http/settings_routes.ts +3 −1
| @@ -53,7 +53,7 @@ import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-setting | ||
| 53 | 53 | import { featureAccept, featurePage, featureRun, featureSave, featuresPage, featureSwitch } from "../web/pages/features.ts"; |
| 54 | 54 | import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts"; |
| 55 | 55 | import { deviceCap, deviceDeclare, deviceGrant, devicesPage, deviceRemove, deviceRevoke } from "../web/settings/devices.ts"; |
| 56 | import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts"; | |
| 56 | import { mailAwsDo, mailAwsUndo, secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts"; | |
| 57 | 57 | import { |
| 58 | 58 | backupsClear, |
| 59 | 59 | backupsDestination, |
| @@ -248,6 +248,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 248 | 248 | router.add("POST", "/settings/subscriptions/:id/budget", subscriptionBudget); |
| 249 | 249 | router.add("GET", "/settings/secrets", secretsPage); |
| 250 | 250 | router.add("POST", "/settings/secrets", secretSet); |
| 251 | router.add("POST", "/settings/mail-aws", mailAwsDo); | |
| 252 | router.add("POST", "/settings/mail-aws/undo", mailAwsUndo); | |
| 251 | 253 | router.add("POST", "/settings/secrets/delete", secretDelete); |
| 252 | 254 | router.add("GET", "/settings/devices", devicesPage); |
| 253 | 255 | router.add("POST", "/settings/devices", deviceDeclare); |
src/tui/screens/secrets.ts +61 −1
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | * the screen directly, sees and changes nothing. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { lookMailAws, mailAwsConfirm, mailAwsUndoConfirm, setUpMailAws, testMailAws, undoMailAws } from "../../actions/mail_aws.ts"; | |
| 12 | import { getMailAws } from "../../core/mail_aws.ts"; | |
| 11 | 13 | import { listSecrets, mailKeyLine, putSecret, removeMailKey, removeSecret, setMailKey } from "../../actions/secrets.ts"; |
| 12 | 14 | import { isSecretName, type SecretName } from "../../core/secret_store.ts"; |
| 13 | 15 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -68,6 +70,7 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen { | ||
| 68 | 70 | binding(["s"], "other place"), |
| 69 | 71 | binding(["m"], "set mail key here"), |
| 70 | 72 | binding(["u"], "remove mail key here"), |
| 73 | binding(["w"], "mail from AWS"), | |
| 71 | 74 | binding(["esc"], "back"), |
| 72 | 75 | ], |
| 73 | 76 | render(area, s) { |
| @@ -174,7 +177,64 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen { | ||
| 174 | 177 | ), |
| 175 | 178 | }), |
| 176 | 179 | ); |
| 177 | else if (e.key === "u") | |
| 180 | else if (e.key === "w" && place.scope === "forge") { | |
| 181 | const done = (r: { ok: true; value: string } | { ok: false; error: string }): void => { | |
| 182 | note = r.ok ? r.value : r.error; | |
| 183 | ctx.invalidate(); | |
| 184 | }; | |
| 185 | const set = getMailAws(f.app.db); | |
| 186 | if (set !== undefined) | |
| 187 | ctx.push( | |
| 188 | confirmScreen(ctx, screen, { | |
| 189 | title: "Mail from AWS", | |
| 190 | body: ["Look at AWS again, send a test to your own proven address, or undo (removes the key, the IAM user, the SES identity and the DNS records it made)."], | |
| 191 | actions: [{ label: "Look again" }, { label: "Send a test" }, { label: "Undo", variant: "danger" }, { label: "Cancel", variant: "ghost" }], | |
| 192 | selected: 3, | |
| 193 | onChoose: (choice) => { | |
| 194 | if (choice === 0) void lookMailAws(f.app, f.user).then(done); | |
| 195 | else if (choice === 1) void testMailAws(f.app, f.user).then(done); | |
| 196 | else if (choice === 2) | |
| 197 | later(ctx, () => | |
| 198 | confirmScreen(ctx, screen, { | |
| 199 | title: "Undo mail from AWS?", | |
| 200 | body: [mailAwsUndoConfirm(set)], | |
| 201 | actions: [{ label: "Undo it", variant: "danger" }, { label: "Cancel", variant: "ghost" }], | |
| 202 | selected: 1, | |
| 203 | width: 72, | |
| 204 | onChoose: (c2) => { | |
| 205 | if (c2 === 0) void undoMailAws(f.app, f.user).then(done); | |
| 206 | }, | |
| 207 | }), | |
| 208 | ); | |
| 209 | }, | |
| 210 | }), | |
| 211 | ); | |
| 212 | else | |
| 213 | ctx.push( | |
| 214 | promptScreen(ctx, screen, { | |
| 215 | title: "Send mail from an AWS account", | |
| 216 | label: "AWS account, Cloudflare account, sending domain, region (words, one space apart)", | |
| 217 | placeholder: "main edge mail.example.com us-east-1", | |
| 218 | onSubmit: (raw) => { | |
| 219 | const [aws = "", dns = "", domain = "", region = "us-east-1"] = raw.trim().split(/\s+/); | |
| 220 | const ask = { aws, dns, domain: domain.toLowerCase(), region }; | |
| 221 | later(ctx, () => | |
| 222 | confirmScreen(ctx, screen, { | |
| 223 | title: "Make all of this?", | |
| 224 | body: [mailAwsConfirm(ask)], | |
| 225 | actions: [{ label: "Make it" }, { label: "Cancel", variant: "ghost" }], | |
| 226 | selected: 1, | |
| 227 | width: 72, | |
| 228 | onChoose: (choice) => { | |
| 229 | if (choice === 0) void setUpMailAws(f.app, f.user, ask).then(done); | |
| 230 | }, | |
| 231 | }), | |
| 232 | ); | |
| 233 | return undefined; | |
| 234 | }, | |
| 235 | }), | |
| 236 | ); | |
| 237 | } else if (e.key === "u") | |
| 178 | 238 | ctx.push( |
| 179 | 239 | confirmScreen(ctx, screen, { |
| 180 | 240 | title: "Remove the mail key?", |
src/web/pages/secrets.ts +33 −1
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { sshOn } from "../../settings/ssh.ts"; |
| 11 | 11 | import type { SecretUse } from "../../core/app_secrets.ts"; |
| 12 | import { lookMailAws, setUpMailAws, testMailAws, undoMailAws } from "../../actions/mail_aws.ts"; | |
| 13 | import { mailAwsCard } from "../render/mail_aws_card.ts"; | |
| 12 | 14 | import { listSecrets, mailKeyLine, putSecret, removeSecret, secretUses } from "../../actions/secrets.ts"; |
| 13 | 15 | import type { Ctx } from "../../http/context.ts"; |
| 14 | 16 | import { |
| @@ -177,7 +179,7 @@ export function secretsPage(ctx: Ctx): Response { | ||
| 177 | 179 | body: html`<div class="page-head"><h1>Secrets</h1></div> |
| 178 | 180 | ${settingsLayout( |
| 179 | 181 | accountSections("secrets", { admin: true, ssh: sshOn(ctx.app.db) }), |
| 180 | html`${card} | |
| 182 | html`${card}${mailAwsCard(ctx.app)} | |
| 181 | 183 | <p class="muted small">${humanCheckLine(ctx)}</p>`, |
| 182 | 184 | "Account settings", |
| 183 | 185 | )}`, |
| @@ -236,3 +238,33 @@ export async function secretDelete(ctx: Ctx): Promise<Response> { | ||
| 236 | 238 | }, |
| 237 | 239 | ); |
| 238 | 240 | } |
| 241 | ||
| 242 | // POST /settings/mail-aws: set up, look at, test or undo mail from the owner's AWS account. | |
| 243 | export async function mailAwsDo(ctx: Ctx): Promise<Response> { | |
| 244 | const denied = requireAdmin(ctx); | |
| 245 | if (denied) return denied; | |
| 246 | const form = await readForm(ctx, "admin"); | |
| 247 | if (form instanceof Response) return form; | |
| 248 | const step = field(form, "step"); | |
| 249 | const done = | |
| 250 | step === "set_up" | |
| 251 | ? field(form, "confirm") === "1" | |
| 252 | ? await setUpMailAws(ctx.app, ctx.auth.user, { aws: field(form, "aws"), dns: field(form, "dns"), domain: field(form, "domain").trim().toLowerCase(), region: field(form, "region").trim() }) | |
| 253 | : { ok: false as const, error: "Tick the box to confirm what will be made." } | |
| 254 | : step === "look" | |
| 255 | ? await lookMailAws(ctx.app, ctx.auth.user) | |
| 256 | : step === "test" | |
| 257 | ? await testMailAws(ctx.app, ctx.auth.user) | |
| 258 | : { ok: false as const, error: "That is not a step." }; | |
| 259 | return flashTo(ctx, "/settings/secrets", done.ok ? { message: done.value } : { tone: "danger", message: done.error }); | |
| 260 | } | |
| 261 | ||
| 262 | // POST /settings/mail-aws/undo (reached through /-/confirm) | |
| 263 | export async function mailAwsUndo(ctx: Ctx): Promise<Response> { | |
| 264 | const denied = requireAdmin(ctx); | |
| 265 | if (denied) return denied; | |
| 266 | const form = await readForm(ctx, "admin"); | |
| 267 | if (form instanceof Response) return form; | |
| 268 | const done = await undoMailAws(ctx.app, ctx.auth.user); | |
| 269 | return flashTo(ctx, "/settings/secrets", done.ok ? { message: done.value } : { tone: "danger", message: done.error }); | |
| 270 | } |
src/web/render/mail_aws_card.ts added +47
| @@ -0,0 +1,47 @@ | ||
| 1 | /** | |
| 2 | * The mail key's AWS card (#18109), under Secrets: when mail is set up from an AWS account, its | |
| 3 | * state in words with look again, a test send and undo; otherwise the one form that sets it up, | |
| 4 | * with the confirm saying what it will make. Reads the stored state only, so the page makes no AWS | |
| 5 | * call. | |
| 6 | */ | |
| 7 | ||
| 8 | import { mailAwsConfirm } from "../../actions/mail_aws.ts"; | |
| 9 | import { listCloudAccounts } from "../../core/cloud_account.ts"; | |
| 10 | import { getMailAws, mailAwsWords } from "../../core/mail_aws.ts"; | |
| 11 | import type { App } from "../../app.ts"; | |
| 12 | import { html, type Html } from "../html.ts"; | |
| 13 | import { btn, confirmAction, field, selectField } from "../ui.ts"; | |
| 14 | ||
| 15 | const step = (name: string, label: string): Html => | |
| 16 | html`<form class="row-actions" method="post" action="/settings/mail-aws"><input type="hidden" name="step" value="${name}" />${btn(label, { size: "sm" })}</form>`; | |
| 17 | ||
| 18 | export function mailAwsCard(app: App): Html { | |
| 19 | const made = getMailAws(app.db); | |
| 20 | if (made !== undefined) | |
| 21 | return html`<section class="settings-block" id="mail-aws"> | |
| 22 | <h2>Mail from AWS</h2> | |
| 23 | <p class="muted small">${mailAwsWords(made)} The credential is sealed and never shown.</p> | |
| 24 | ${step("look", "Look again")} ${step("test", "Send a test to me")} ${confirmAction({ action: "/settings/mail-aws/undo", verb: "Undo" })} | |
| 25 | </section>`; | |
| 26 | const accounts = listCloudAccounts(app.db).filter((a) => a.writeAllowed); | |
| 27 | const pick = (provider: string) => accounts.filter((a) => a.provider === provider).map((a) => ({ value: a.name, label: a.name })); | |
| 28 | const aws = pick("aws"); | |
| 29 | const dns = pick("cloudflare"); | |
| 30 | if (aws.length === 0 || dns.length === 0) | |
| 31 | return html`<section class="settings-block" id="mail-aws"> | |
| 32 | <h2>Mail from AWS</h2> | |
| 33 | <p class="muted small">To send mail from your AWS account, attach an AWS account and a Cloudflare account that holds the domain, and allow writes on both, under Cloud accounts.</p> | |
| 34 | </section>`; | |
| 35 | return html`<section class="settings-block" id="mail-aws"> | |
| 36 | <h2>Send mail from this AWS account</h2> | |
| 37 | <form method="post" action="/settings/mail-aws"> | |
| 38 | <input type="hidden" name="step" value="set_up" /> | |
| 39 | ${selectField({ name: "aws", label: "AWS account", options: aws })} | |
| 40 | ${selectField({ name: "dns", label: "Cloudflare account (DNS)", options: dns })} | |
| 41 | ${field({ name: "domain", label: "Sending domain", placeholder: "mail.example.com", required: true, autocomplete: "off" })} | |
| 42 | ${field({ name: "region", label: "AWS region", value: "us-east-1", required: true, autocomplete: "off" })} | |
| 43 | ${field({ name: "confirm", type: "checkbox", value: "1", required: true, label: mailAwsConfirm({ aws: "the AWS account", dns: "the Cloudflare account", domain: "the sending domain", region: "the region" }) })} | |
| 44 | ${btn("Send mail from this AWS account", { variant: "primary", size: "sm" })} | |
| 45 | </form> | |
| 46 | </section>`; | |
| 47 | } |
test/aws-writes.test.ts +13 −11
| @@ -16,12 +16,12 @@ const ok = async (): Promise<Response> => new Response("<ok/>"); | ||
| 16 | 16 | |
| 17 | 17 | const iam = (action: string, params: Record<string, string> = {}) => ({ action, version: "2010-05-08", params }); |
| 18 | 18 | const LISTED: [string, "iam", Parameters<typeof awsCall>[4]][] = [ |
| 19 | ["CreateUser", "iam", iam("CreateUser", { UserName: "send" })], | |
| 20 | ["PutUserPolicy", "iam", iam("PutUserPolicy", { UserName: "send", PolicyName: "p", PolicyDocument: POLICY })], | |
| 21 | ["CreateAccessKey", "iam", iam("CreateAccessKey", { UserName: "send" })], | |
| 22 | ["DeleteUser", "iam", iam("DeleteUser", { UserName: "send" })], | |
| 23 | ["DeleteUserPolicy", "iam", iam("DeleteUserPolicy", { UserName: "send", PolicyName: "p" })], | |
| 24 | ["DeleteAccessKey", "iam", iam("DeleteAccessKey", { UserName: "send", AccessKeyId: "AKIA1" })], | |
| 19 | ["CreateUser", "iam", iam("CreateUser", { UserName: "forge-mail-send" })], | |
| 20 | ["PutUserPolicy", "iam", iam("PutUserPolicy", { UserName: "forge-mail-send", PolicyName: "p", PolicyDocument: POLICY })], | |
| 21 | ["CreateAccessKey", "iam", iam("CreateAccessKey", { UserName: "forge-mail-send" })], | |
| 22 | ["DeleteUser", "iam", iam("DeleteUser", { UserName: "forge-mail-send" })], | |
| 23 | ["DeleteUserPolicy", "iam", iam("DeleteUserPolicy", { UserName: "forge-mail-send", PolicyName: "p" })], | |
| 24 | ["DeleteAccessKey", "iam", iam("DeleteAccessKey", { UserName: "forge-mail-send", AccessKeyId: "AKIA1" })], | |
| 25 | 25 | ]; |
| 26 | 26 | |
| 27 | 27 | describe("named writes", () => { |
| @@ -32,15 +32,17 @@ describe("named writes", () => { | ||
| 32 | 32 | await expect(awsCall(never, KEY, service, "us-east-1", ask, false)).rejects.toThrow("read-only"); |
| 33 | 33 | }); |
| 34 | 34 | } |
| 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("SES writes are REST asks to ses only", async () => { | |
| 36 | const rest = { rest: "POST" as const, operation: "CreateEmailIdentity", path: "/v2/email/identities", body: {} }; | |
| 37 | expect(await awsCall(ok, KEY, "ses", "us-east-1", rest, true)).toBe("<ok/>"); | |
| 38 | await expect(awsCall(never, KEY, "ses", "us-east-1", rest)).rejects.toThrow("read-only"); | |
| 39 | await expect(awsCall(never, KEY, "iam", "us-east-1", rest, true)).rejects.toThrow("CreateEmailIdentity"); | |
| 38 | 40 | }); |
| 39 | 41 | test("iam is signed for us-east-1 only", async () => { |
| 40 | await expect(awsCall(never, KEY, "iam", "eu-west-1", iam("CreateUser"), true)).rejects.toThrow("us-east-1"); | |
| 42 | await expect(awsCall(never, KEY, "iam", "eu-west-1", iam("CreateUser", { UserName: "forge-mail-send" }), true)).rejects.toThrow("us-east-1"); | |
| 41 | 43 | }); |
| 42 | 44 | test("an account's call sends a write only when the account has writes allowed", async () => { |
| 43 | const ask = iam("CreateUser", { UserName: "send" }); | |
| 45 | const ask = iam("CreateUser", { UserName: "forge-mail-send" }); | |
| 44 | 46 | await expect(accountCall(never, KEY, false)("iam", "us-east-1", ask)).rejects.toThrow("read-only"); |
| 45 | 47 | expect(await accountCall(ok, KEY, true)("iam", "us-east-1", ask)).toBe("<ok/>"); |
| 46 | 48 | expect(await accountCall(ok, KEY, false)("iam", "us-east-1", iam("ListUsers"))).toBe("<ok/>"); |
test/mail-aws-doors.test.ts added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | /** | |
| 2 | * The doors of mail from AWS (#18109): the API asks for the confirm and answers admins only; the | |
| 3 | * card draws on Secrets. | |
| 4 | */ | |
| 5 | ||
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createToken } from "../src/core/tokens.ts"; | |
| 12 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 13 | import { forgetMailAws, getMailAws, putMailAws } from "../src/core/mail_aws.ts"; | |
| 14 | import { mailAwsCard } from "../src/web/render/mail_aws_card.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | describe("mail from AWS: doors", () => { | |
| 21 | let dataDir = ""; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let admin = ""; | |
| 25 | let bob = ""; | |
| 26 | const call = (method: string, token: string, body?: unknown) => | |
| 27 | fetch(`${servers.url}/api/v1/mail-aws`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dataDir = await mkdtemp(join(tmpdir(), "forge-mail-aws-doors-")); | |
| 31 | app = createApp({ dataDir, port: 0 }); | |
| 32 | servers = await serve(app); | |
| 33 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { | |
| 34 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 35 | if (!made.ok) throw new Error(made.error); | |
| 36 | } | |
| 37 | admin = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token; | |
| 38 | bob = createToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token; | |
| 39 | }, 30_000); | |
| 40 | ||
| 41 | afterAll(async () => { | |
| 42 | servers.stop(); | |
| 43 | app.close(); | |
| 44 | await rm(dataDir, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | ||
| 47 | test("GET says nothing is set up; set_up without confirm says what it would make and does nothing", async () => { | |
| 48 | const got = (await (await call("GET", admin)).json()) as { line: string | null }; | |
| 49 | expect(got.line).toBeNull(); | |
| 50 | const r = await call("POST", admin, { step: "set_up", aws: "main", dns: "edge", domain: "mail.example.com", region: "us-east-1" }); | |
| 51 | expect(r.status).toBe(422); | |
| 52 | expect(((await r.json()) as { say: string }).say).toContain("SES identity"); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a person who is not an admin gets 403 on every verb", async () => { | |
| 56 | for (const [m, b] of [["GET", undefined], ["POST", { step: "look" }], ["DELETE", undefined]] as const) expect((await call(m, bob, b)).status).toBe(403); | |
| 57 | }); | |
| 58 | ||
| 59 | test("DELETE without confirm says what undo would remove and removes nothing", async () => { | |
| 60 | putMailAws(app.db, { aws: "main", dns: "edge", region: "us-east-1", domain: "mail.example.com", from: "[email protected]", user: "forge-mail-abcdef123456", keyId: "", identity: true, identityMade: true, records: [], requested: false, state: "", sent: 0, bounces: 0, complaints: 0, lookedAt: null }); | |
| 61 | const r = await call("DELETE", admin); | |
| 62 | expect(r.status).toBe(422); | |
| 63 | const j = (await r.json()) as { error: string; say: string }; | |
| 64 | expect(j.error).toBe("unconfirmed"); | |
| 65 | expect(j.say).toContain("forge-mail-abcdef123456"); | |
| 66 | expect(getMailAws(app.db)).toBeDefined(); | |
| 67 | forgetMailAws(app.db); | |
| 68 | }); | |
| 69 | ||
| 70 | test("the card asks for accounts first, and never draws a secret", () => { | |
| 71 | expect(String(mailAwsCard(app))).toContain("attach an AWS account"); | |
| 72 | }); | |
| 73 | }); |
test/mail-aws.test.ts added +268
| @@ -0,0 +1,268 @@ | ||
| 1 | /** | |
| 2 | * Mail from the owner's AWS account (#18109), against a recorded AWS and Cloudflare: the identity, | |
| 3 | * the records and the key are made in that order, a second run makes nothing new, the state reads | |
| 4 | * "in the sandbox" until AWS answers production access, undo removes what was made, and the SMTP | |
| 5 | * password is in no answer, event or call the forge records. `awsCall`'s write list is held too. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, 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/cloud.ts"; | |
| 14 | import { lookMailAws, mailAwsConfirm, setUpMailAws, testMailAws, undoMailAws } from "../src/actions/mail_aws.ts"; | |
| 15 | import { mailKeyLine, putSecret, setMailKey } from "../src/actions/secrets.ts"; | |
| 16 | import { awsCall, awsKey } from "../src/cloud/aws_call.ts"; | |
| 17 | import { smtpPassword, smtpUrl } from "../src/cloud/ses_setup.ts"; | |
| 18 | import { recordVerified, secretNameOf, setWriteAllowed } from "../src/core/cloud_account.ts"; | |
| 19 | import { resolveMailKey } from "../src/core/mail_key.ts"; | |
| 20 | import { markVerified } from "../src/core/verify.ts"; | |
| 21 | import { getMailAws } from "../src/core/mail_aws.ts"; | |
| 22 | import { createUser, type User } from "../src/core/users.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | const SECRET = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; | |
| 28 | const PASSWORD = smtpPassword(SECRET, "us-east-1"); | |
| 29 | const TOKENS = ["aaaaaaaaaaaaaaaaaaaa1111", "bbbbbbbbbbbbbbbbbbbb2222", "cccccccccccccccccccc3333"]; | |
| 30 | const hex = (n: number): string => n.toString(16).padStart(32, "0"); | |
| 31 | ||
| 32 | const ask = { aws: "main", dns: "edge", domain: "mail.example.com", region: "us-east-1" }; | |
| 33 | ||
| 34 | describe("mail from an AWS account", () => { | |
| 35 | let dataDir = ""; | |
| 36 | let app: App; | |
| 37 | let admin: User; | |
| 38 | const calls: string[] = []; | |
| 39 | let verified = false; | |
| 40 | let production = false; | |
| 41 | let records = 0; | |
| 42 | let identityExists = false; | |
| 43 | const keys = new Set<string>(); | |
| 44 | const live = new Set<string>(); | |
| 45 | ||
| 46 | const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { "content-type": "application/json" } }); | |
| 47 | const xml = (b: string) => new Response(`<R>${b}</R>`, { status: 200 }); | |
| 48 | ||
| 49 | net.fetch = async (url, init) => { | |
| 50 | const u = new URL(url); | |
| 51 | const method = init?.method ?? "GET"; | |
| 52 | const body = typeof init?.body === "string" ? init.body : ""; | |
| 53 | if (u.host === "api.cloudflare.com") { | |
| 54 | calls.push(`cf ${method} ${u.pathname}`); | |
| 55 | if (u.pathname === "/client/v4/zones") return json({ result: u.searchParams.get("name") === "example.com" ? [{ id: hex(1), name: "example.com" }] : [] }); | |
| 56 | if (method === "POST") { | |
| 57 | records++; | |
| 58 | live.add(hex(100 + records)); | |
| 59 | return json({ result: { id: hex(100 + records) } }); | |
| 60 | } | |
| 61 | if (method === "DELETE") { | |
| 62 | live.delete(u.pathname.split("/").at(-1)!); | |
| 63 | return json({ result: {} }); | |
| 64 | } | |
| 65 | const i = Number.parseInt(u.pathname.split("/").at(-1)!, 16) - 100; | |
| 66 | return json({ result: { type: "CNAME", name: `${TOKENS[i - 1]}._domainkey.mail.example.com`, content: `${TOKENS[i - 1]}.dkim.amazonses.com` } }); | |
| 67 | } | |
| 68 | const action = /Action=([A-Za-z]+)/.exec(body)?.[1] ?? ""; | |
| 69 | calls.push(`aws ${u.host} ${method} ${action || u.pathname}`); | |
| 70 | if (u.pathname.startsWith("/v2/email/identities") && method === "POST" && identityExists) return json({ message: "exists", __type: "AlreadyExistsException" }, 400); | |
| 71 | if (u.pathname.startsWith("/v2/email/identities") && method === "POST") return json({ VerifiedForSendingStatus: false, DkimAttributes: { Tokens: TOKENS } }); | |
| 72 | if (u.pathname.startsWith("/v2/email/identities") && method === "GET") return json({ VerifiedForSendingStatus: verified, DkimAttributes: { Tokens: TOKENS } }); | |
| 73 | if (u.pathname.startsWith("/v2/email/identities") && method === "DELETE") return json({}); | |
| 74 | if (u.pathname === "/v2/email/account") return json({ ProductionAccessEnabled: production }); | |
| 75 | if (u.pathname === "/v2/email/account/details") return json({}); | |
| 76 | if (action === "ListAccessKeys") return xml(`<ListAccessKeysResult><AccessKeyMetadata>${[...keys].map((k) => `<member><AccessKeyId>${k}</AccessKeyId></member>`).join("")}</AccessKeyMetadata></ListAccessKeysResult>`); | |
| 77 | if (action === "GetCallerIdentity") return xml("<GetCallerIdentityResult><Account>123456789012</Account></GetCallerIdentityResult>"); | |
| 78 | if (action === "DeleteAccessKey") keys.delete(/AccessKeyId=([A-Z0-9]+)/.exec(body)?.[1] ?? ""); | |
| 79 | if (action === "CreateAccessKey") keys.add("AKIASMTPEXAMPLE01"); | |
| 80 | if (action === "CreateAccessKey") return xml(`<CreateAccessKeyResult><AccessKey><AccessKeyId>AKIASMTPEXAMPLE01</AccessKeyId><SecretAccessKey>${SECRET}</SecretAccessKey></AccessKey></CreateAccessKeyResult>`); | |
| 81 | if (action === "GetSendStatistics") return xml(`<GetSendStatisticsResult><SendDataPoints><member><DeliveryAttempts>10</DeliveryAttempts><Bounces>2</Bounces><Complaints>1</Complaints></member></SendDataPoints></GetSendStatisticsResult>`); | |
| 82 | return xml(""); | |
| 83 | }; | |
| 84 | ||
| 85 | beforeAll(async () => { | |
| 86 | dataDir = await mkdtemp(join(tmpdir(), "forge-mail-aws-")); | |
| 87 | app = createApp({ dataDir, port: 0 }); | |
| 88 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 89 | if (!made.ok) throw new Error(made.error); | |
| 90 | admin = made.value; | |
| 91 | putSecret(app, admin, "forge", "", secretNameOf("aws", "main"), `AKIAEXAMPLE:${SECRET}`); | |
| 92 | putSecret(app, admin, "forge", "", secretNameOf("cloudflare", "edge"), "cf-token-value-123"); | |
| 93 | for (const [p, n] of [["aws", "main"], ["cloudflare", "edge"]] as const) recordVerified(app.db, p, n, "ok"); | |
| 94 | }); | |
| 95 | ||
| 96 | afterAll(async () => { | |
| 97 | app.close(); | |
| 98 | await rm(dataDir, { recursive: true, force: true }); | |
| 99 | }); | |
| 100 | ||
| 101 | const nothingLeaks = (...said: string[]): void => { | |
| 102 | const events = JSON.stringify(app.db.query("SELECT * FROM event").all()); | |
| 103 | for (const text of [...said, events, calls.join("\n")]) expect(text).not.toContain(PASSWORD); | |
| 104 | for (const text of [...said, events]) expect(text).not.toContain(SECRET); | |
| 105 | }; | |
| 106 | ||
| 107 | test("the SMTP password is SES's: a version byte and 32 bytes, escaped in the URL", () => { | |
| 108 | const bytes = Buffer.from(PASSWORD, "base64"); | |
| 109 | expect(bytes.length).toBe(33); | |
| 110 | expect(bytes[0]).toBe(4); | |
| 111 | expect(smtpUrl("AKIA", SECRET, "us-east-1")).toBe(`smtps://AKIA:${encodeURIComponent(PASSWORD)}@email-smtp.us-east-1.amazonaws.com:465`); | |
| 112 | }); | |
| 113 | ||
| 114 | test("the forge writes only the named calls, and only for its own IAM user", async () => { | |
| 115 | const key = awsKey("AKIAEXAMPLE:secret")!; | |
| 116 | const f = async () => new Response("<R/>"); | |
| 117 | await expect(awsCall(f, key, "ec2", "us-east-1", { action: "RunInstances", version: "2016-11-15" })).rejects.toThrow("not a read"); | |
| 118 | await expect(awsCall(f, key, "iam", "us-east-1", { action: "CreateRole", version: "2010-05-08" })).rejects.toThrow("not a read"); | |
| 119 | await expect(awsCall(f, key, "iam", "us-east-1", { action: "DeleteUser", version: "2010-05-08", params: { UserName: "root-admin" } }, true)).rejects.toThrow("only the IAM user it made"); | |
| 120 | await expect(awsCall(f, key, "ec2", "us-east-1", { action: "CreateUser", version: "2010-05-08", params: { UserName: "forge-mail-abcd1234" } })).rejects.toThrow("not a read"); | |
| 121 | await awsCall(f, key, "iam", "us-east-1", { action: "CreateUser", version: "2010-05-08", params: { UserName: "forge-mail-abcd1234" } }, true); | |
| 122 | }); | |
| 123 | ||
| 124 | test("a read-only account is refused, and nothing is called", async () => { | |
| 125 | const r = await setUpMailAws(app, admin, ask); | |
| 126 | expect(r.ok).toBe(false); | |
| 127 | expect(calls).toEqual([]); | |
| 128 | setWriteAllowed(app.db, "aws", "main", true); | |
| 129 | setWriteAllowed(app.db, "cloudflare", "edge", true); | |
| 130 | }); | |
| 131 | ||
| 132 | test("the confirm says what will be made", () => { | |
| 133 | const say = mailAwsConfirm(ask); | |
| 134 | for (const word of ["SES identity", "mail.example.com", "IAM user", "DKIM", "Cloudflare", "mail key", "sandbox"]) expect(say).toContain(word); | |
| 135 | }); | |
| 136 | ||
| 137 | test("makes the identity, the records and the key in that order, and says it waits for DNS", async () => { | |
| 138 | const r = await setUpMailAws(app, admin, ask); | |
| 139 | expect(r.ok ? "" : r.error).toBe(""); | |
| 140 | const writes = calls.filter((c) => /POST \/v2\/email\/identities|cf POST|CreateAccessKey/.test(c)); | |
| 141 | expect(writes.map((c) => c.replace(/aws \S+ /, ""))).toEqual(["POST /v2/email/identities", "cf POST /client/v4/zones/" + hex(1) + "/dns_records", "cf POST /client/v4/zones/" + hex(1) + "/dns_records", "cf POST /client/v4/zones/" + hex(1) + "/dns_records", "POST CreateAccessKey"]); | |
| 142 | expect(resolveMailKey(app.db, {})).toBe("forge"); | |
| 143 | expect(getMailAws(app.db)?.state).toBe("waiting"); | |
| 144 | expect(mailKeyLine(app, admin)).toContain("waiting for DNS"); | |
| 145 | expect(calls.some((c) => c.endsWith("PutAccountDetails") || c.endsWith("/v2/email/account/details"))).toBe(true); | |
| 146 | nothingLeaks(r.ok ? r.value : r.error); | |
| 147 | }); | |
| 148 | ||
| 149 | test("a second run makes nothing new", async () => { | |
| 150 | calls.length = 0; | |
| 151 | const r = await setUpMailAws(app, admin, ask); | |
| 152 | expect(r.ok).toBe(true); | |
| 153 | expect(calls.filter((c) => /POST|PUT/.test(c) && !c.endsWith("GetSendStatistics"))).toEqual([]); | |
| 154 | expect(records).toBe(3); | |
| 155 | }); | |
| 156 | ||
| 157 | test("it says in the sandbox until AWS answers production access, then sending", async () => { | |
| 158 | verified = true; | |
| 159 | const a = await lookMailAws(app, admin); | |
| 160 | expect(a.ok && a.value).toContain("in the sandbox (mail reaches verified addresses only)"); | |
| 161 | expect(a.ok && a.value).toContain("10 sent, 2 bounced, 1 complaints"); | |
| 162 | expect(mailKeyLine(app, admin)).toContain("in the sandbox"); | |
| 163 | production = true; | |
| 164 | const b = await lookMailAws(app, admin); | |
| 165 | expect(b.ok && b.value).toContain("sending"); | |
| 166 | nothingLeaks(a.ok ? a.value : "", b.ok ? b.value : ""); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a test send needs the admin's own proven address", async () => { | |
| 170 | const r = await testMailAws(app, admin); | |
| 171 | expect(r.ok).toBe(false); | |
| 172 | }); | |
| 173 | ||
| 174 | test("a test send goes to the admin's proven address through the key in effect", async () => { | |
| 175 | const seen: string[] = []; | |
| 176 | const server = Bun.listen<{ buf: string; data: boolean }>({ | |
| 177 | hostname: "127.0.0.1", | |
| 178 | port: 0, | |
| 179 | socket: { | |
| 180 | open(sock) { | |
| 181 | sock.data = { buf: "", data: false }; | |
| 182 | sock.write("220 stub\r\n"); | |
| 183 | }, | |
| 184 | data(sock, chunk) { | |
| 185 | sock.data.buf += new TextDecoder().decode(chunk); | |
| 186 | for (;;) { | |
| 187 | if (sock.data.data) { | |
| 188 | const end = sock.data.buf.indexOf("\r\n.\r\n"); | |
| 189 | if (end === -1) return; | |
| 190 | seen.push(sock.data.buf.slice(0, end)); | |
| 191 | sock.data.buf = sock.data.buf.slice(end + 5); | |
| 192 | sock.data.data = false; | |
| 193 | sock.write("250 ok\r\n"); | |
| 194 | continue; | |
| 195 | } | |
| 196 | const nl = sock.data.buf.indexOf("\r\n"); | |
| 197 | if (nl === -1) return; | |
| 198 | const line = sock.data.buf.slice(0, nl); | |
| 199 | sock.data.buf = sock.data.buf.slice(nl + 2); | |
| 200 | if (line.startsWith("EHLO")) sock.write("250 hi\r\n"); | |
| 201 | else if (line.startsWith("AUTH PLAIN")) sock.write("235 ok\r\n"); | |
| 202 | else if (line === "DATA") { | |
| 203 | sock.data.data = true; | |
| 204 | sock.write("354 go\r\n"); | |
| 205 | } else if (line === "QUIT") sock.write("221 bye\r\n"); | |
| 206 | else sock.write("250 ok\r\n"); | |
| 207 | } | |
| 208 | }, | |
| 209 | }, | |
| 210 | }); | |
| 211 | try { | |
| 212 | markVerified(app.db, admin.id, new Date().toISOString()); | |
| 213 | expect(setMailKey(app, admin, "forge", "", `smtp://u:[email protected]:${server.port}`, "[email protected]").ok).toBe(true); | |
| 214 | const r = await testMailAws(app, admin); | |
| 215 | expect(r.ok ? r.value : r.error).toBe("A test went to [email protected]."); | |
| 216 | expect(seen.join("\n")).toContain("Test mail from your forge"); | |
| 217 | } finally { | |
| 218 | server.stop(true); | |
| 219 | } | |
| 220 | }); | |
| 221 | ||
| 222 | test("another place's setup is refused until undone; undo removes the key, the user, the identity and the records", async () => { | |
| 223 | expect((await setUpMailAws(app, admin, { ...ask, domain: "mail.other.com" })).ok).toBe(false); | |
| 224 | calls.length = 0; | |
| 225 | const r = await undoMailAws(app, admin); | |
| 226 | expect(r.ok).toBe(true); | |
| 227 | expect(calls.filter((c) => /DeleteAccessKey|DeleteUserPolicy|DeleteUser$|DELETE/.test(c)).length).toBe(7); | |
| 228 | expect(live.size).toBe(0); | |
| 229 | expect(getMailAws(app.db)).toBeUndefined(); | |
| 230 | expect(resolveMailKey(app.db, {})).toBeUndefined(); | |
| 231 | nothingLeaks(r.ok ? r.value : r.error); | |
| 232 | }); | |
| 233 | ||
| 234 | test("an identity the owner already had stays on undo, and a key a crash orphaned is deleted before a new one is made", async () => { | |
| 235 | identityExists = true; | |
| 236 | keys.add("AKIAORPHANEDKEY0001"); | |
| 237 | calls.length = 0; | |
| 238 | const set = await setUpMailAws(app, admin, ask); | |
| 239 | expect(set.ok ? "" : set.error).toBe(""); | |
| 240 | expect(getMailAws(app.db)?.identityMade).toBe(false); | |
| 241 | const order = calls.filter((c) => /DeleteAccessKey|CreateAccessKey/.test(c)).map((c) => c.replace(/aws \S+ POST /, "")); | |
| 242 | expect(order).toEqual(["DeleteAccessKey", "CreateAccessKey"]); | |
| 243 | expect([...keys]).toEqual(["AKIASMTPEXAMPLE01"]); | |
| 244 | calls.length = 0; | |
| 245 | const r = await undoMailAws(app, admin); | |
| 246 | expect(r.ok ? r.value : r.error).toContain("stays"); | |
| 247 | expect(calls.some((c) => c.includes("DELETE /v2/email/identities"))).toBe(false); | |
| 248 | expect(keys.size).toBe(0); | |
| 249 | identityExists = false; | |
| 250 | }); | |
| 251 | ||
| 252 | test("a failed seal rolls back without a call to a blank identity path", async () => { | |
| 253 | const m = await import("../src/cloud/ses_setup.ts"); | |
| 254 | const seen: string[] = []; | |
| 255 | await m.takeDown(async (_s, _r, a) => { | |
| 256 | seen.push("path" in a ? String(a.path) : "action" in a ? a.action : ""); | |
| 257 | return "<R/>"; | |
| 258 | }, "us-east-1", { user: "forge-mail-abcdef123456", domain: "" }); | |
| 259 | expect(seen.some((p) => p.startsWith("/v2/email/identities"))).toBe(false); | |
| 260 | }); | |
| 261 | ||
| 262 | test("a non-admin may do none of it", async () => { | |
| 263 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false }); | |
| 264 | if (!bob.ok) throw new Error(bob.error); | |
| 265 | expect((await setUpMailAws(app, bob.value, ask)).ok).toBe(false); | |
| 266 | expect((await undoMailAws(app, bob.value)).ok).toBe(false); | |
| 267 | }); | |
| 268 | }); |
new above
offline
The access key exists at AWS before
keyIdis saved at line 133. A crash or a failedputMailAwsbetween them orphans a key whose secret is lost. A rerun then makes a second key, and undo's DeleteUser fails on the leftover. Before making a key, list the user's keys and delete any the row does not know.