plan: mail submission rev 2, Fable plan round 1 applied
Applies Fable 5.2's plan review of d18a916 (1 P1, 8 P2, 6 P3): - P1-1 new team environments get <P>_MAIL_FROM and no credential - P2-1 caller-class counts for the reap - P2-2 CARLOS_MAIL only for provisioned routes - P2-3 explicit regions via rootaws.LoadStaticConfig - P2-4 AccessDenied read as absent, no ListBucket - P2-5 the mailer_unarmed alert - P2-6 empty-token refusal - P2-7 Task 1 is in census scope via mail_cli.go - P2-8 Opus for Task 2 Cheap P3s are folded in; the rest are on a follow-up list. The plan maps each finding to its change. Rebased onto origin/main 8f8207719; the build branch is cut from there or later. Docs only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+166
−66
docs/superpowers/notes/census-plan-platform-mail-submission.md+26 −9docs/superpowers/plans/2026-11-13-platform-mail-submission.md+140 −57
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/notes/census-plan-platform-mail-submission.md b/docs/superpowers/notes/census-plan-platform-mail-submission.md| index ef7dc6ac4..51b06c916 100644 |
| --- a/docs/superpowers/notes/census-plan-platform-mail-submission.md |
| +++ b/docs/superpowers/notes/census-plan-platform-mail-submission.md |
| @@ -6,7 +6,15 @@ At build time `make census-card` is the authority on which units changed. The bu |
| make census-propose NAME=platform-mail-submission CLAIMS=docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| -That writes the real `census-proposal-platform-mail-submission.md`, its overlay and its chain line, with seals. Read sites and dispositions below are predictions. The recorded dispositions of existing units are whatever the chain holds at build time. |
| +That writes the real `census-proposal-platform-mail-submission.md`, its overlay and its chain line, with seals. **Each census-touching task (1, 3, 4, 5, 6 and 8) reruns it under the same NAME with the cumulative CLAIMS file**, so every push of the branch is green. |
| + |
| +**Rev 2** (after Fable round 1 on the plan; the base is `origin/main` `8f8207719`, and the build branch must be cut from it or later) makes six changes: |
| +- adds the Task 1 section (round 1 P2-7); |
| +- adds `rt.Provisioned` and the token rule to Task 4's units (P2-2, P2-6); |
| +- replaces Task 5's credentials constructor with `NewS3StoreFromConfig` over `rootaws.LoadStaticConfig` (P2-3); |
| +- adds `CARLOS_DEPLOYMENT_REGION` (P2-3); |
| +- adds the AccessDenied-as-absent read (P2-4); |
| +- drops the `s3:ListBucket` statement from Task 8 (P2-4). Read sites and dispositions below are predictions. The recorded dispositions of existing units are whatever the chain holds at build time. |
| Ruling `census-ruling-platform-mail-submission`. The independent reviewer approves or rejects every change below; nothing goes to the census owner (Paul, #280, 2026-10-26). The reviewer is from the other family than the author: Astra for a Claude author. |
| @@ -23,6 +31,14 @@ Every other change in scope runs as `carlos` (the agent) or as `carlos-mailer` ( |
| --- |
| +## Task 1: pause on the sender record (`mail_cli.go` only) |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `mail_cli.go` (the `carlos email status` printer and its reply type) | body | unchanged | The CLI reads the pause from the reply's new `pause` block (kind, since), and falls back to `provisioned.active` for an older console. Prints a line. API mode only, run by a person, not root. No read of box state | |
| + |
| +Envelopes re-pinned: `.`. |
| + |
| ## Task 3: mailer unit, user, socket, peer rule |
| | unit | change | read sites | what changed | |
| @@ -57,13 +73,13 @@ Envelopes re-pinned: `internal/host/units`, `internal/host`, `internal/instancec |
| |---|---|---|---| |
| | `internal/activator/backend_exec.go` `type ExecBackend` | body | unchanged | Two fields: `Mail mailsubmit.Forwarder` and `MailSwitch func(acct, app string) bool`. Declaration only | |
| | `internal/activator/backend_exec.go` `var agentOwnedNames` | body | unchanged | Gains `"CARLOS_MAIL"` | |
| -| `internal/activator/backend_exec.go` `ExecBackend.agentOwnedVars` | body | +whole:Route | Sets `CARLOS_MAIL=submit` when `haveControl`, `Mail != nil` and `MailSwitch(account, app)`. Strips it otherwise, including a tenant-supplied value from fileEnv. Reads `rt.App` and `RouteAccount(rt)`; the switch comes from the agent's cache of the console-written sender record. Only narrows what a tenant can set | |
| +| `internal/activator/backend_exec.go` `ExecBackend.agentOwnedVars` | body | +whole:Route | Sets `CARLOS_MAIL=submit` when `haveControl`, `rt.Provisioned`, `Mail != nil` and `MailSwitch(account, app)`; an unprovisioned route of a switched app is logged once and never told to submit. Strips it otherwise, including a tenant-supplied value from fileEnv. Reads `rt.App` and `RouteAccount(rt)`; the switch comes from the agent's cache of the console-written sender record. Only narrows what a tenant can set | |
| | `internal/activator/backend_exec.go` `seedVars` | body | unchanged | Also strips `CARLOS_MAIL` | |
| | `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom` | body | unchanged | The inline mount becomes `b.controlMount(rt, tokenReader, n)` | |
| | `internal/activator/backend_exec.go` `ExecBackend.controlMount` | new | +whole:Route | One mount composer for both bind sites. Timers and updates as today; `mailsubmit.Mount` under its own condition, `Mail != nil` | |
| | `internal/activator/prepare.go` `ExecBackend.listenControl` | body | unchanged | Calls `controlMount`, the same as the flat site | |
| | `internal/moves/envreport.go` `var AgentOwnedVars` | body | unchanged | Gains `"CARLOS_MAIL"`. Paired with `agentOwnedNames` by test | |
| -| `internal/mailsubmit/*` (every unit) | new | (0) | New package. `Mount` (`POST /v1/mail`: bearer, size and shape checks; stamps account, app and host from the route, never the body) and `SocketForwarder` (HTTP over `/run/carlos-mailer/mailer.sock`). Agent process | |
| +| `internal/mailsubmit/*` (every unit) | new | (0) | New package. `Mount` (`POST /v1/mail`: bearer by the existing verbs' rule, where an empty or unreadable token refuses everything and the compare is constant-time over SHA-256; size and shape checks; stamps account, app and host from the route, never the body) and `SocketForwarder` (HTTP over `/run/carlos-mailer/mailer.sock`). Agent process | |
| | `internal/mailwire/*` (every unit) | new | (0) | New package, first in the root binary here. Pure wire types and helpers: `Pause`, `Submission`, `SenderView`, key functions, tag names, `IsMailerCaller`, the tier default cap. No I/O | |
| | `internal/host/mailswitch.go` (every unit) | new | +1 bucket read | The agent's switch cache. A bounded `Get` of `apps/<acct>/<app>/email/senders/app.json` (console-written), decoded as `mailwire.SenderView`. Agent, not root | |
| | `internal/host/agent.go` `runAgent` | body | unchanged | Wires `eb.Mail`, `eb.MailSwitch` and the cache's refresh on the serial bump. Agent, not root | |
| @@ -74,10 +90,11 @@ Envelopes re-pinned: `internal/activator`, `internal/moves`, `internal/host`. Ne |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| -| `internal/mailer/{send,policy,hygiene,rate,counter,keys,routes,ses}.go` (every unit) | new | (n) | The mailer (uid `carlos-mailer`) reads its key file, its own state directory and, through its own IAM user, bucket objects (sender records, domain records, instance records). It calls SES `SendEmail`. Not root | |
| -| `internal/release/store.go` `NewS3StoreWithCredentials` | new | (0) | Constructor: `newS3Store` with an explicit credentials provider and IMDS disabled. No read in itself | |
| +| `internal/mailer/{send,policy,hygiene,rate,counter,keys,routes,ses}.go` (every unit) | new | (n) | The mailer (uid `carlos-mailer`) reads its key file, its own state directory and, through its own IAM user, bucket objects by key (sender records, domain records, instance records), with a denied read taken as absent. Absent always refuses. It calls SES `SendEmail`. Every AWS config comes from `rootaws.LoadStaticConfig` with an explicit region (`CARLOS_MAIL_REGION`, `CARLOS_DEPLOYMENT_REGION`); IMDS and shared config are off. Not root | |
| +| `internal/release/store.go` `NewS3StoreFromConfig` | new | (0) | Constructor: an `S3Store` over a caller-built `aws.Config`, with the same client options as `newS3Store`. No read in itself | |
| +| `internal/release/store.go` `newS3Store` | body | unchanged | Its client options (s3compat, checksums) move into one unexported helper that both constructors call. Behaviour unchanged | |
| | `internal/provision/reconcile.go` `BoxServesRecord` (and `type BoxScope`) | new | +whole:Record | Exported wrapper over the unchanged `inScope`, `ownsRecord` and `everywhereClass`, so the mailer's "on this box" is the reconciler's. Called only by the mailer | |
| -| `internal/hostenv/hostenv.go` `var Optional` | body | unchanged | Gains `CARLOS_MAIL_REGION`, which selects no box authority (an SES region) | |
| +| `internal/hostenv/hostenv.go` `var Optional` | body | unchanged | Gains `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`, which select no box authority (AWS regions for the mailer's clients) | |
| | `mailer_cli.go` `runMailerServe` | body | unchanged | Wires the pipeline; reads host env names listed in the plan | |
| Envelopes re-pinned: `internal/mailer`, `internal/release`, `internal/provision`, `internal/hostenv`, `.`. |
| @@ -99,10 +116,10 @@ Envelopes re-pinned: `internal/release`, `internal/activator`, `internal/host`, |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| -| `infra/modules/region-host/mailer.tf` `external` | new | (1) | `aws_iam_user.mailer`, `carlos-mailer-<region>` at path `/carlos-mailer/`, and `aws_iam_user_policy.mailer`: `ses:SendRawEmail` on `identity/*` and `configuration-set/carlos-*` in the mail region; `s3:GetObject` on `apps/*/*/email/senders/*`, `apps/*/*/instances/*` and `accounts/*/email/domains/*`; `s3:ListBucket` with an `s3:prefix` of `accounts/*/email/domains/*`. No access key resource (the key is never in state). The host role gains nothing. Nothing a box's root reads. References no sibling script, so `checkRootExecInputs` needs nothing | |
| -| `infra/modules/region-host/variables.tf` `external` | body | unchanged (1) | `variable "mailer"`, an object `{ses_region, ses_account_id}` defaulting to null, which means no resources | |
| +| `infra/modules/region-host/mailer.tf` `external` | new | (1) | `aws_iam_user.mailer`, `carlos-mailer-<region>` at path `/carlos-mailer/`, and `aws_iam_user_policy.mailer` with two statements: `ses:SendRawEmail` on `identity/*` and `configuration-set/carlos-*` in the mail region; `s3:GetObject` on `apps/*/*/email/senders/*`, `apps/*/*/instances/*` and `accounts/*/email/domains/*`. No `s3:ListBucket`, no write. No access key resource (the key is never in state). The host role gains nothing. Nothing a box's root reads. References no sibling script, so `checkRootExecInputs` needs nothing | |
| +| `infra/modules/region-host/variables.tf` `external` | body | unchanged (1) | `variable "mailer"`, an object `{ses_region, ses_account_id, deployment_bucket_region}` defaulting to null, which means no resources | |
| | `infra/modules/region-host/outputs.tf` `external` | body | unchanged (1) | `output "mailer_user_name"` | |
| -| the module's host.env parameter assembly (group boxes) `external` | body | unchanged (1) | Sets `CARLOS_MAIL_REGION` from `var.mailer.ses_region`. A value root writes into host.env from operator input, as every other parameter is | |
| +| the module's host.env parameter assembly (group boxes) `external` | body | unchanged (1) | Sets `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` from `var.mailer`. A value root writes into host.env from operator input, as every other parameter is | |
| | `infra/modules/region-host/tests/mailer.tftest.hcl` `external` | new | (1) | Plan-only runs under `mock_provider`: off by default, the exact policy, no access key, no SES on the host role, and the group host.env key. Test-only | |
| Envelopes re-pinned: `infra/modules/region-host`. |
diff --git a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md| index 0a043e6d9..075a50aa2 100644 |
| --- a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| +++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| @@ -12,7 +12,13 @@ |
| **Spec review history (carried, stopping rule 1):** round 1, 3 P1s (uid family ×2, attribution ×1); round 2, 1 P1 (attribution) and 6 P2s (uid ×2), so rule 2 applied to both families; round 3, no P1, review stopped. A fourth round on the design needs Paul's go. **This plan does not reopen the design.** The places where the spec cannot be built as written are listed in "Spec gaps" below, each with a recommended answer for Paul. None is fixed silently. |
| -**Plan review:** pending. One Astra round on this plan (brief from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`), stopping at the first round with no P1. Findings in the uid or attribution families count toward those families' existing two rounds: a third finding in either goes to Paul, not to a fix. |
| +**Plan review history (stopping rules apply):** |
| +- **Round 1:** Fable 5.2 reviewed rev 1 at `d18a916` and returned CHANGES REQUIRED: 1 P1, 8 P2, 6 P3. |
| + - P1-1 was in a new family, "a switched app's bundles lack `<P>_MAIL_FROM`". |
| + - P2-1 was in the attribution family. That is the family's third round counting the design's two, so this plan applies the fix the reviewer named and does not write a fix of its own (rule 2's third option: one place, a guard test). |
| +- **Rev 2** (this revision) applies all nine fixes and the P3s that were cheap to fold in, and lists the rest under "P3 follow-ups". The table at the end maps each finding to its change. |
| +- **Round 2** is scoped to the rev 2 diff. A round 3 needs Paul's go. |
| +- The plan was rebased onto `origin/main` `8f8207719` (#962, `internal/edge` only, touching nothing this plan changes). **The build branch must be cut from `8f8207719` or a later tip**, so the census chain it proposes against is current. |
| --- |
| @@ -24,8 +30,8 @@ Each gap names the task it blocks, the spec text, what the code shows, and a rec |
| |---|---|---|---|---| |
| | G1 | Task 1 | Decision 8 and test 8.13: "a cap pause lifts at the day roll; rate, **plan** and manual pauses do not" | `resumeStaleCapPause` (`internal/console/mailcounts.go:176-206`) lifts **cap and plan** pauses at the day roll, and `PauseKindPlan`'s own comment (`internal/mail/mail.go:84-86`) says it lifts like a cap pause. Decision 8 also says "keeping today's pause kinds" | Keep today's behaviour (cap **and plan** lift at the roll). Read test 8.13 as "rate, manual and per-instance do not". Changing plan pauses would be a billing change this design never argued for | |
| | G2 | Tasks 6, 7 | §4 "The retry queue stays in the app (rastrillo's existing mail queues)" | rastrillo has **no** mail queue. `mail.Sender.Send` is synchronous (`rastrillo/mail/mail.go:39,153`), and a grep for retry, backoff, outbox and queue in `mail/`, `auth/` and `jobs/` finds nothing | rastrillo's transport retries `503` a bounded number of times inside the caller's deadline and returns `429` as a typed error carrying `Retry-After`, never retrying it hot. Any queue is the app's own. Test 8.10 is met by the typed error plus the bounded retry | |
| -| G3 | Tasks 6, 7 | Decision 10: "When on, no `<P>_SMTP_*` is delivered anywhere"; test 8.1 | The five delivered variables include `<P>_SMTP_FROM` (`EnvNames`, `walk_environment.go:178`). With all five gone, a switched app has **no From address** to put in `from` and `From:` | Deliver one non-secret variable, `<P>_MAIL_FROM` (the sender's `Declared.From`), in place of the five, into the default bundle and every owned environment's bundle. Test 8.1 still holds: no `<P>_SMTP_*` and no AWS key | |
| -| G4 | Task 6 | Decision 10: "**Before §7.4's reap, `carlos email test --submit`** sends through the submit path per route, as proof" | Only the agent can reach an instance's control socket (round 3's own P3). The console has no path to make a route send | Gate the §7.4 reap on **event evidence** instead: at least 7 days since the switch, at least one Send event attributed to the mailer for the app, and no Send event attributed to the app-level IAM user (`carlos-mail-<acct>-<app>`) in the last 7 days. This proves every route stopped using SMTP, which is what the reap needs. `--submit` is left out of this plan | |
| +| G3 | Tasks 6, 7 | Decision 10: "When on, no `<P>_SMTP_*` is delivered anywhere"; test 8.1 | The five delivered variables include `<P>_SMTP_FROM` (`EnvNames`, `walk_environment.go:178`). With all five gone, a switched app has **no From address** to put in `from` and `From:` | Deliver one non-secret variable, `<P>_MAIL_FROM` (the sender's `Declared.From`), in place of the five. It goes into the default bundle and every owned environment's bundle: those that exist at the flip, **and every one created while the switch is on** (`mintOwnedEnvironmentMail` delivers it and mints nothing, round 1 P1-1). Releasing an environment removes it. Test 8.1 still holds: no `<P>_SMTP_*` and no AWS key | |
| +| G4 | Task 6 | Decision 10: "**Before §7.4's reap, `carlos email test --submit`** sends through the submit path per route, as proof" | Only the agent can reach an instance's control socket (round 3's own P3). The console has no path to make a route send | Gate the §7.4 reap on **event evidence** instead. The evidence is a per-app, per-day count of Send events **by caller class**, which Task 2 records (`mail_caller_sends`, round 1 P2-1): `mail_events` has no caller column, and every class resolves to sender `app`. The reap needs all three of these:<br>• at least 7 days since the switch;<br>• at least one `mailer` Send for the app;<br>• no `app_user` Send (`carlos-mail-<acct>-<app>`) in the last 7 days.<br>**What this proves:** the app-level SMTP key stopped being used. It does **not** prove that submit works on every route. A route that never sends proves nothing either way, and a route that cannot submit shows up as its app's own failures and the mailer's refusals, not here. `--submit` is left out of this plan | |
| | G5 | Task 8 | §5: the IAM policy is "conditioned on `ses:FromAddress` matching the platform's verified identities, or on `ses:TenantName`" | One fleet-wide user cannot carry a static `ses:FromAddress` list: identities are created at runtime by the console, per account. Terraform cannot enumerate them | `ses:SendRawEmail` on `arn:aws:ses:<mail_region>:<acct>:identity/*` and `configuration-set/carlos-*` only, with no From condition. The mailer's From check is the gate (as §5 already says); IAM bounds the account, region and resource types. Add the `ses:TenantName` `StringLike carlos-*` condition only once §9 item 3's backfill has landed (it would refuse every untenanted send). Round 3's P3 list already names this | |
| | G6 | Task 8, Task 9 | §5: key "armed by the operator by hand", and never through `user_data`, SSM or the bucket | Group-mode boxes are launched unattended by their Auto Scaling group (`group-init.sh.tftpl:312-338`). A new or replaced group box has **no key**, so its mailer never starts and every switched instance on it answers `503 MAILER_UNAVAILABLE` until someone arms it. Every automatic delivery path the spec rules out is one uid `carlos` can read | Ask Paul. Options: (a) switched apps run on fixed boxes only, refused by the door; (b) the box reports "mailer armed" in its status record, the door and an alert read it, and the operator arms each new box (a runbook step per scale event); (c) a separate design for unattended key delivery. This plan builds (b)'s report and alert (Task 3 step 6, Task 6 precondition) because it helps under every option | |
| | G7 | Task 6 | Decision 10: "**Adopting**, rolling back to, or pinning a build whose manifest lacks the declaration is refused" | Every person-facing change of what a route serves goes through a console door. A box's `carlos adopt` (root) also adopts channel heads that a direct-bucket promote (pinfra scripts) moved, without the console | Refuse at every console door that changes what a route serves (one shared check, and a guard test over the route table). At the box, log loudly and raise an event on adopt and on wake, as decision 10 already does for wake. A box-side adopt **refusal** would be new root authority, and the plan does not add it unless Paul asks | |
| @@ -38,7 +44,7 @@ Plan choices that are not gaps, for the plan reviewer (each resolves an item on |
| - **Cap unit** (P3): messages, not recipients, matching the console, which counts Send events (one per message). |
| - **Caller match** (P3): `ses:caller-identity` is the bare user name (§9.0). The mailer's IAM user lives under path `/carlos-mailer/`, outside the console's `/carlos-mail/` (`UserPath`, `policy.go:25`), so `SweepUserBoundaries` and every console reap can never reach it. |
| - **Three answers beyond §4's list**, all from the mailer through the agent: `403 {"code":"ROUTE_NOT_ON_BOX"}` (decision 4), `403 {"code":"SUBMISSION_OFF"}` (the app sender's switch is off: the mailer sends only for switched apps, which narrows §6's residual to switched apps), and `400 {"code":"REJECTED"}` (SES `MessageRejected`). |
| -- **The mailer's box facts** (region, pools, fleet label, bucket, S3 endpoint) come from `/etc/carlos/host.env` through systemd's `EnvironmentFile=`. PID 1 reads it as root, so the mailer user needs no read access. The unit sets `UnsetEnvironment=CARLOS_SECRETS_KEY`. The SES region comes from a new optional host.env key, `CARLOS_MAIL_REGION`, the same name and meaning as the console's. |
| +- **The mailer's box facts** (region, pools, fleet label, bucket, S3 endpoint) come from `/etc/carlos/host.env` through systemd's `EnvironmentFile=`. PID 1 reads it as root, so the mailer user needs no read access. The unit sets `UnsetEnvironment=CARLOS_SECRETS_KEY`. The AWS regions come from two new optional host.env keys (round 1 P2-3): `CARLOS_MAIL_REGION` (SES; the same name and meaning as the console's) and `CARLOS_DEPLOYMENT_REGION` (the deployment bucket). `CARLOS_REGION` is a placement label and is used only for "on this box". |
| - **The mailer is a verb of the one `carlos` binary** (`carlos mailer serve`), as `carlos relay serve` is. Its code imports a new small wire package, `internal/mailwire`, and never `internal/mail`. That keeps `internal/mail` (and its IAM and SES walks) out of the root binary and out of census scope (`go list -deps .` today has no `internal/mail`). |
| --- |
| @@ -59,7 +65,7 @@ Plan choices that are not gaps, for the plan reviewer (each resolves an item on |
| - **Wire-shape changes are additive** (AGENTS.md). The new sender fields (`pause`, `submission`) and the manifest field (`mail`) are `omitempty` pointers or strings. A record or manifest written before them must parse, and must mean what it meant. |
| - **When a storage shape changes, the consumer list is everything that parses it** (AGENTS.md). For the sender record that is, today: `internal/mail/{walk.go,walk_environment.go,mail.go}`, `internal/console/{apimail.go,appsettings.go,mailcounts.go,planmail.go,sesevents.go,teamcreds.go}`, `internal/console/templates/app_settings.html` and `mail_cli.go`. After this plan, it also includes `internal/mailwire`, `internal/mailer` and the agent's switch cache (`internal/host/mailswitch.go`). |
| - A new `carlos` command or subcommand needs its `docs/site/cli.md` heading and its `parity/parity.tsv` row in the same branch. Run `make parity-doc` and `go test . -run 'TestCLIProjection|TestParity'` after. |
| -- Census (AGENTS.md "The census"): overlay name `platform-mail-submission`, claims drafted in `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Tasks 3, 4, 5, 6 and 8 change in-scope files. Run `make census-card` at the end of each, and `make census-propose NAME=platform-mail-submission CLAIMS=<file>` once at the end (rerun with the same NAME after fixes). |
| +- Census (AGENTS.md "The census"): overlay name `platform-mail-submission`, claims drafted in `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Tasks **1** (`mail_cli.go`, package `.`), 3, 4, 5, 6 and 8 change in-scope files. Each of them ends with `make census-card` and `make census-propose NAME=platform-mail-submission CLAIMS=<cumulative file>`, rerun under the same NAME, so every push of the branch is green (round 1 P3). |
| - Local tests are targeted (`go test ./internal/<pkg>/ -run <Name>`). CI runs the full gate. Use the sandbox settings in AGENTS.md "Build & test". |
| - **No production change from this branch.** No AWS write, no `tofu apply`, no `carlos` command that changes state. The operator steps at the end are Paul's, with scoped approval (AGENTS.md "Production infrastructure needs scoped approval"). |
| - UI and copy: Task 6 has a UX pass, then a copy review, before its CLI output and refusals are built (AGENTS.md "Every UI change gets a UX pass"). |
| @@ -73,6 +79,7 @@ Plan choices that are not gaps, for the plan reviewer (each resolves an item on |
| 5. **`Bcc:` and `X-SES-*` in `raw`, including folded and mixed-case forms.** Never reach SES. Pinned in Task 5 (`TestHygieneStripsHeaders`). |
| 6. **A build without the declaration reaching a switched app.** Refused at every console door that changes what a route serves, naming "switch submission off first". Never refused at wake. Pinned in Task 6 (`TestSubmissionGateCoversEveryServeDoor`, `TestWakeNeverRefusedForUndeclaredBuild`). |
| 7. **A new unit line that fails every instance start fleet-wide.** Every added `InaccessiblePaths` entry is `-`-prefixed, and the set of units carrying it equals the set carrying `/run/carlos-control`. Pinned in Task 3 (`TestMailerPathsHiddenFromEveryTenantTemplate`). |
| +8. **A team environment created after the switch** gets `<P>_MAIL_FROM` and no credential, and loses it on release (round 1 P1-1). Pinned in Task 6 (`TestMintOwnedEnvironmentWhileSwitched`, gate 8.1's third case). |
| --- |
| @@ -80,8 +87,8 @@ Plan choices that are not gaps, for the plan reviewer (each resolves an item on |
| | Task | Title | Review under stopping rule 3 | Why | Implementer | Reviewer | |
| |---|---|---|---|---|---| |
| -| 1 | Pause on the sender record | **Own review** | Production storage (sender record shape in production buckets); the abuse brake | Opus | Astra | |
| -| 2 | `EmailTags` attribution and decision 6's guard | **Own review** | Security gate (attribution trust boundary); billing (counts feed caps and plan limits) | Sonnet | Astra | |
| +| 1 | Pause on the sender record | **Own review** + census | Production storage (sender record shape in production buckets); the abuse brake. Census: `mail_cli.go` is in package `.` (`census-base-scope.txt:1493`) | Opus | Astra | |
| +| 2 | `EmailTags` attribution, decision 6's guard, caller-class counts | **Own review** | Security gate in the attribution family (rule 2 applied twice at design time); billing (counts feed caps and plan limits) | **Opus** (round 1 P2-8) | Astra | |
| | 3 | Mailer unit, user, socket and peer rule | **Own review** + census | Security gate (peer rule); root (bootstrap's `privilegedPlan`, tmpfiles, sysusers); fleet-wide unit lines | Opus | Astra (census and security) | |
| | 4 | The verb at both bind sites, `CARLOS_MAIL` agent-owned | **Own review** + census | Security gate (route stamp, agent-owned variable) | Opus | Astra (census and security) | |
| | 5 | The mailer's SES send, hygiene, rate and cap | **Own review** + census | Security gate (From, pause, cap, box-local routes); production (SES) | Opus | Astra (census and security) | |
| @@ -143,8 +150,9 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - [ ] **Step 2: Run** `go test ./internal/mailwire/ ./internal/mail/ -run 'TestEffectivePause|TestSetSenderPausedWritesBoth|TestSenderView|TestMailwireKeys|TestAdditiveSenderShape' && go test ./internal/console/ -run TestPauseKindsSurvive`. Expected: build failure. |
| - [ ] **Step 3: Implement** to the interfaces. Change every consumer in the list above in the same commit. |
| - [ ] **Step 4: Run** the same commands, then `go test ./internal/mail/ ./internal/console/ -run 'Pause|Resume|Limit|PlanMail|EmailStatus'`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `mail: pause on the sender record, kinds kept`. |
| -- [ ] **Step 6: Review** (own review: production storage). Astra, with the consumer list and the additive-shape rule in the brief. |
| +- [ ] **Step 5: Census** (round 1 P2-7). `mail_cli.go` is in package `.`, which is in the root binary's scope (`internal/provision/testdata/census-base-scope.txt:1493`). Its status printer's change is a census unit. Run `make census-card`, write its claim (the Task 1 section of the census note), and run `make census-propose NAME=platform-mail-submission CLAIMS=<file>`, so this push is green. Every later census-touching task reruns it under the same NAME. |
| +- [ ] **Step 6: Commit** `mail: pause on the sender record, kinds kept`. |
| +- [ ] **Step 7: Review** (own review: production storage, and the census unit). Astra, with the consumer list and the additive-shape rule in the brief. |
| ### Task 2: `EmailTags` attribution, with decision 6's guard in `SenderOfCaller` |
| @@ -155,7 +163,8 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - Modify: `internal/mail/sender.go` (`SenderOfCaller` `:450-473`) |
| - Modify: `internal/mailwire/mailwire.go` (tag names, the mailer caller rule) |
| - Modify: `internal/console/sesevents.go` (`recordAndEnforceMail` `:500`) |
| -- Test: `internal/mail/events_test.go`, `internal/mail/sender_test.go`, `internal/console/sesevents_test.go` |
| +- Modify: `internal/console/store.go` (the schema list beside `mail_sender_counts` `:301-312`: one new table), `internal/console/mailcounts.go` (two store methods beside `RecordMailEvent` `:109`) |
| +- Test: `internal/mail/events_test.go`, `internal/mail/sender_test.go`, `internal/console/sesevents_test.go`, `internal/console/mailcounts_test.go` |
| **Interfaces:** |
| - `internal/mailwire`: |
| @@ -167,7 +176,16 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `func SenderOfCaller(ctx context.Context, s release.Store, caller string, tags map[string]string) (acct, app, sender string, ok bool)`. **The guard is the first statement:** |
| - if `mailwire.IsMailerCaller(caller)`: return the three tags when `release.ValidAccount`, `release.ValidApp` and `ValidSenderID` all hold; otherwise `("", "", "", false)` and log once per caller per minute ("mailer event without valid tags"). |
| - otherwise: today's body exactly, and `tags` is never read on this path. |
| -- `recordAndEnforceMail` passes `ev.Tags`. Nothing else in the console changes: a named result is counted once against the named sender, as today. |
| +- `recordAndEnforceMail` passes `ev.Tags`. A named result is counted once against the named sender, as today. |
| +- **Caller-class counts** (round 1 P2-1; Task 6's reap reads them; the attribution family's fix as the reviewer named it): |
| + - `func CallerClass(acct, app, caller string) string` in `internal/mail` returns: |
| + - `"mailer"` when `mailwire.IsMailerCaller(caller)`; |
| + - `"app_user"` when the caller's bare name (or a user ARN's last segment) equals `UserName(acct, app)` exactly; |
| + - `"other"` for everything else: `+s+` standalones, `+e+` environment users, and unknown callers. |
| + - A new table, additive (`CREATE TABLE IF NOT EXISTS`): `mail_caller_sends (account TEXT NOT NULL, app TEXT NOT NULL, day TEXT NOT NULL, class TEXT NOT NULL, sends INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (account, app, day, class))`. It is pruned with the same retention as `mail_sender_counts`. |
| + - `func (s *Store) RecordMailCallerSend(ctx context.Context, acct, app, day, class string) error` upserts `sends = sends + 1`. |
| + - `func (s *Store) MailCallerSends(ctx context.Context, acct, app, sinceDay string) (map[string]int64, error)` sums by class over `day >= sinceDay`. |
| + - `recordAndEnforceMail` calls `RecordMailCallerSend` for **Send** events only, and only on the named path (after the live check). The class is computed from `ev.Caller` and the **resolved** account and app, never from tags. A tag can name the app, but only the caller decides the class, so a forged tag can neither hide an `app_user` send nor fake a `mailer` one. |
| - [ ] **Step 1: Write the failing tests.** |
| - `TestParseEventKeepsTags`: a recorded Bounce event with `mail.tags` holding `account`, `app`, `sender` and `ses:caller-identity` yields `Tags` with exactly the three; an over-long value is cut as other fields are. |
| @@ -180,12 +198,15 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - caller `arn:aws:iam::123456789012:user/carlos-mail/carlos-mailer-eu-west-1`: `false` (wrong path). |
| - caller `someone-else` with tags: `false`. |
| - `TestRecordAndEnforceChargesCallerNotForgedTag` (console, fake store): an SMTP app's event with another app's tags increments the caller's counts and never the tagged app's; the same event from the mailer increments the tagged sender's. |
| - - `TestMailerNameNeverParsesAsApp`: `AppOfCaller("carlos-mailer-eu-west-1")` is false (an account sqid is at least 3 letters, so `er` never parses). |
| -- [ ] **Step 2: Run** `go test ./internal/mail/ -run 'TestParseEventKeepsTags|TestTagsBelievedOnlyFromMailer|TestMailerNameNeverParsesAsApp' && go test ./internal/console/ -run TestRecordAndEnforceChargesCallerNotForgedTag`. Expected: FAIL. |
| + - `TestMailerNameNeverParsesAsApp`: `AppOfCaller("carlos-mailer-eu-west-1")` is false. The reason: `carlos-mailer-…` does not start with `carlos-mail-` at all (the character after `mail` is `e`, not `-`), so the prefix cut fails before any account is parsed. Also pin the converse: `IsMailerCaller(UserName(acct, app))` is false for a table of valid accounts and apps (round 1 P3). |
| + - `TestCallerClass`: the mailer's bare name and user ARN give `mailer`; `carlos-mail-abc-docs` for (abc, docs) gives `app_user`; the same name for (abc, sheets) gives `other`; a `+s+` and a `+e+` name give `other`. |
| + - `TestMailCallerSendsCounts` (store): two `mailer` sends, one `app_user` send yesterday and one today, and an `other` send; `MailCallerSends(since=today)` gives `{mailer:2, app_user:1, other:1}`. Pruning removes days past retention. |
| + - `TestCallerClassIgnoresForgedTags` (console): an SMTP app's Send carrying the mailer's tags for itself is counted `app_user`; a Bounce adds nothing to `mail_caller_sends`. |
| +- [ ] **Step 2: Run** `go test ./internal/mail/ -run 'TestParseEventKeepsTags|TestTagsBelievedOnlyFromMailer|TestMailerNameNeverParsesAsApp|TestCallerClass' && go test ./internal/console/ -run 'TestRecordAndEnforceChargesCallerNotForgedTag|TestMailCallerSendsCounts|TestCallerClassIgnoresForgedTags'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** Update the two existing test callers of `SenderOfCaller` (`sender_test.go`, `walk_environment_test.go`) to pass `nil` tags. |
| - [ ] **Step 4: Run** the same commands, then `go test ./internal/mail/ ./internal/console/ -run 'Caller|SESEvents|RecordMail'`. Expected: PASS. **Watch the guard test fail** once, by moving the guard below the `AppOfCaller` branch, and then restore it (AGENTS.md: a policy change is not done until its test has been watched to fail). |
| -- [ ] **Step 5: Commit** `mail: believe SES tags only from the mailer's principal`. |
| -- [ ] **Step 6: Review** (own review: security gate and billing). Astra. The brief names the attribution family and its two prior rounds. |
| +- [ ] **Step 5: Commit** `mail: believe SES tags only from the mailer; count sends by caller class`. |
| +- [ ] **Step 6: Review** (own review: security gate and billing). Astra. The brief names the attribution family, its two design rounds and this plan's round 1 P2-1. Under stopping rule 2, a further finding in this family goes to Paul as a choice, not to a fourth fix. |
| ### Task 3: The mailer unit, its user, its socket and the peer rule |
| @@ -211,7 +232,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - Units (exact): |
| - `carlos-mailer-arm.path`: `[Path] PathExists=/etc/carlos-mailer/keys`, `Unit=carlos-mailer.socket`; `[Install] WantedBy=multi-user.target`. Bootstrap already arms every `.path` (`armedUnits`, `bootstrap.go:233-242`), so the operator's only step is writing the key. |
| - `carlos-mailer.socket`: `ConditionPathExists=/etc/carlos-mailer/keys`, `ListenStream=/run/carlos-mailer/mailer.sock`, `SocketUser=carlos`, `SocketGroup=carlos`, `SocketMode=0600`, `Accept=no`. Same shape as `carlos-instance-control.socket:11-14`. |
| - - `carlos-mailer.service`: `Requires=carlos-mailer.socket`, `ConditionPathExists=/etc/carlos-mailer/keys`, `EnvironmentFile=-/etc/carlos/host.env`, `UnsetEnvironment=CARLOS_SECRETS_KEY`, `Environment=AWS_EC2_METADATA_DISABLED=true`, `ExecStart=/opt/carlos/carlos mailer serve`, `User=carlos-mailer`, `Group=carlos-mailer`, `StateDirectory=carlos-mailer`, `StateDirectoryMode=0700`, `IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128`, then the relay's hardening block (`carlos-relay.service:20-43`) with `ProtectSystem=strict`, `ProtectProc=invisible`, `RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX`, `MemoryMax=256M`. No `ReadWritePaths` beyond the state directory. |
| + - `carlos-mailer.service`: `Requires=carlos-mailer.socket`, `ConditionPathExists=/etc/carlos-mailer/keys`, `EnvironmentFile=-/etc/carlos/host.env`, `UnsetEnvironment=CARLOS_SECRETS_KEY`, `Environment=AWS_EC2_METADATA_DISABLED=true`, `ExecStart=/opt/carlos/carlos mailer serve`, `Restart=always`, `RestartSec=5`, `User=carlos-mailer`, `Group=carlos-mailer`, `StateDirectory=carlos-mailer`, `StateDirectoryMode=0700`, `IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128`, then the relay's hardening block (`carlos-relay.service:20-43`) with `ProtectSystem=strict`, `ProtectProc=invisible`, `RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX`, `MemoryMax=256M`. No `ReadWritePaths` beyond the state directory. |
| - tmpfiles gains `d /run/carlos-mailer 0750 root carlos -` and `d /etc/carlos-mailer 0750 root carlos-mailer -`. sysusers gains `u carlos-mailer - "CARLOS mailer" - /usr/sbin/nologin`, ordered before the group line. `privilegedPlan` gains `useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos-mailer`, guarded like `carlos` (`:788-793`). System apply already runs sysusers before tmpfiles (`systemapply.go:1568`). |
| - Box status: `Metrics.MailerArmed` is true when `/run/carlos-mailer/mailer.sock` exists **and** `GET /v1/health` answers 200 within 2 s. The agent cannot stat the key itself: `/etc/carlos-mailer` is `0750 root:carlos-mailer`, which uid `carlos` cannot traverse, by §5's rule. The socket exists only once the `.path` unit has seen the key, so it is the right proxy. An alert rule `mailer_unarmed@<box>` fires when a box hosts a route of a switched app and reports `MailerArmed=false` (wired in Task 6, once the switch exists). |
| @@ -226,7 +247,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - [ ] **Step 2: Run** `go test ./internal/host/ -run 'TestMailer|TestTmpfilesMailer|TestSysusersCreatesMailer|TestPrivilegedPlanCreatesMailer|TestCmdTemplateEqualsSeed|TestBoxReportsMailerArmed' && go test ./internal/mailer/ && go test . -run TestMailerServe`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** Then `go test . -run TestCLIProjection -update`, add the parity row and the `docs/site/cli.md` heading, and run `make parity-doc`. |
| - [ ] **Step 4: Run** the same commands, then `go test ./internal/host/ -run 'Units|Bootstrap|Isolation'`, `go test . -run 'TestCLIProjection|TestParity'` and `go test ./internal/docsite/`. Expected: PASS. Cross-build: `GOOS=darwin go build ./...`, `GOOS=windows go build ./...`. |
| -- [ ] **Step 5: Census card.** Run `make census-card`, and check its units against the Task 3 section of `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Add any unit it names that the plan did not. |
| +- [ ] **Step 5: Census card.** Run `make census-card`, and check its units against the Task 3 section of `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Add any unit it names that the plan did not. Rerun `make census-propose NAME=platform-mail-submission` with the cumulative CLAIMS file, so every push of the branch is green (round 1 P3). |
| - [ ] **Step 6: Verify on a dev box** (paul-mbp devbox or the dev deployment; not production). `systemctl show -p MainPID --value carlos-edge.service` succeeds as user `carlos-mailer` under the unit's hardening. **The peer rule depends on it.** If D-Bus is refused, stop and report: do not loosen the hardening without a review. |
| - [ ] **Step 7: Commit** `mailer: unit, user, socket and the agent-only peer rule`. |
| - [ ] **Step 8: Review** (own review: security gate and root). Astra reviews the card and the diff. |
| @@ -254,14 +275,16 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `internal/mailsubmit/verb.go`: |
| - `type Forwarder interface { Send(ctx context.Context, req SendRequest) (status int, ans Answer, retryAfter string, err error) }` |
| - `func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, error), fwd Forwarder)` registers `POST /v1/mail`. It checks, in order: |
| - 1. the bearer against `tokenReader()` with `subtle.ConstantTimeCompare`, else `401`; |
| + 1. the bearer, by the existing verbs' rule (`instanceupdates/control.go:37-45`, `schedule/control.go:81-90`): `want, err := tokenReader()`; if `err != nil || want == ""`, answer `401` whatever the request carries (round 1 P2-6). Otherwise compare the SHA-256 of the `Authorization` header with that of `"Bearer " + want`, using `subtle.ConstantTimeCompare`; a mismatch is `401`; |
| 2. `http.MaxBytesReader(MaxBody)`, the JSON shape, base64 `raw`, at most `MaxRaw`, 1 to 50 recipients, a non-empty `from`, else `400 BAD_REQUEST`. |
| It then stamps `Account: release.RouteAccount(rt), App: rt.App, Host: rt.Host` from `rt`, **never from the body**, forwards, and copies the mailer's status, answer and `Retry-After`. A dial or transport error is `503 MAILER_UNAVAILABLE`. The From-header comparison and hygiene are the mailer's (Task 5), so the policy lives in one place. |
| - `internal/mailsubmit/forward.go`: `type SocketForwarder struct { Path string; Timeout time.Duration }` (defaults `MailerSocket`, 60 s). It does an HTTP POST over a fresh unix dial per call. |
| - `internal/activator`: |
| - `ExecBackend` gains `Mail mailsubmit.Forwarder` (nil means the verb is not mounted) and `MailSwitch func(acct, app string) bool` (nil means off). |
| - One mount composer replaces the two copies: `func (b *ExecBackend) controlMount(rt registry.Route, tokenReader func() (string, error), gen uint64) func(*http.ServeMux)`. It returns nil only when `Timers`, `UpdatesReader` and `Mail` are all nil, and mounts the mail verb **under its own condition** (`b.Mail != nil`), never under the `Timers`/`UpdatesReader` one. Both bind sites call it: `spawnChildFrom` (flat) and `listenControl` (nested and rootfs, via `prepare.go:162`). |
| - - `agentOwnedNames` gains `"CARLOS_MAIL"`. `agentOwnedVars` sets `CARLOS_MAIL=submit` when `haveControl && b.Mail != nil && b.MailSwitch != nil && b.MailSwitch(release.RouteAccount(rt), rt.App)`, and **strips** it otherwise. That covers every launch path that composes through it: flat, unit, rootfs, `rootfsenv.go:50` and `claim_snapshot.go:224` (where `haveControl` is false, so it is stripped). |
| + - `agentOwnedNames` gains `"CARLOS_MAIL"`. `agentOwnedVars` sets `CARLOS_MAIL=submit` when `haveControl && rt.Provisioned && b.Mail != nil && b.MailSwitch != nil && b.MailSwitch(release.RouteAccount(rt), rt.App)`, and **strips** it otherwise. |
| + - **`rt.Provisioned` is in the rule** (round 1 P2-2; the reviewer offered two fixes, and this plan takes the agent-side one). A route with no instance record (a hand-made `carlos route` row) is invisible to the door, and the mailer would answer it `403 ROUTE_NOT_ON_BOX` every time. The door-side alternative would need a host-to-app map in the box report that does not exist (`RouteVersions` is keyed by host alone). So such a route is never told it can submit. |
| + - The residual, stated: an unprovisioned route of a switched app has neither channel (its bundle lost the SMTP variables), so rastrillo refuses at boot. That is decision 11's loud failure. At spawn the agent also logs at error level, once per host, "route has no instance record, so it cannot submit mail for switched app <app>". The remedy is a record (adoption) or switching off. That covers every launch path that composes through it: flat, unit, rootfs, `rootfsenv.go:50` and `claim_snapshot.go:224` (where `haveControl` is false, so it is stripped). |
| - `seedVars` strips `CARLOS_MAIL` along with the two control-channel variables. |
| - `internal/moves`: `AgentOwnedVars` gains `"CARLOS_MAIL": true`. `TestAgentOwnedVarsAreMovesBoxOwned` pins the pair. |
| - `internal/host/mailswitch.go`: |
| @@ -277,14 +300,16 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `TestMailVerbLimits`: `raw` of `MaxRaw+1` decoded bytes, 51 recipients, 0 recipients, bad base64, and a body over `MaxBody` are each `400 BAD_REQUEST`, with no forward. |
| - `TestMailVerbPassesThroughAnswers`: a fake forwarder returning `429 CAP_REACHED` with `Retry-After: 3600` reaches the client byte for byte; a forwarder error is `503 MAILER_UNAVAILABLE`. |
| - `TestMailVerbMountedAtBothBindSites`: a flat spawn (`spawnChildFrom`) and a nested `listenControl` both serve `POST /v1/mail` when `Mail != nil` and `Timers == nil && UpdatesReader == nil`, and neither serves it when `Mail == nil`. |
| - - `TestCarlosMailFollowsTheBind` (**test 8.7**), table over `agentOwnedVars`: switch on with `haveControl` gives `CARLOS_MAIL=submit` (with the forwarder stubbed to fail, so mailer health is ignored); switch on without control strips it; switch off strips a tenant-supplied `CARLOS_MAIL=submit` from `fileEnv`. |
| + - `TestCarlosMailFollowsTheBind` (**test 8.7**), table over `agentOwnedVars`: switch on with `haveControl` and `Provisioned` gives `CARLOS_MAIL=submit` (with the forwarder stubbed to fail, so mailer health is ignored); switch on without control strips it; switch on with control on a route that is **not** `Provisioned` strips it and logs once; switch off strips a tenant-supplied `CARLOS_MAIL=submit` from `fileEnv`. |
| + - `TestMailVerbRefusesEmptyToken` (round 1 P2-6): a token reader answering `""`, and one answering an error, each give `401` to a request carrying `Authorization: Bearer ` (empty) and to one carrying any token. The forwarder is never called. |
| + - `TestMailerSidePackagesDoNotImportMail` (round 1 P3): walking `internal/mailer`, `internal/mailsubmit`, `internal/mailwire` and `internal/host` with `go/build` (repo-internal imports, recursively) never reaches `internal/mail`, `internal/console` or `aws-sdk-go-v2/service/iam`. This keeps `internal/mail` out of the root binary (the census-scope reason in "Plan choices"). |
| - `TestSeedVarsStripCarlosMail`. |
| - `TestAgentOwnedVarsAreMovesBoxOwned` (existing) updated: the pair still matches. |
| - `TestMailSwitchCache`: a hit, a miss read, a refresh flipping a value, and a read error with no cache answering false. |
| -- [ ] **Step 2: Run** `go test ./internal/mailsubmit/ && go test ./internal/activator/ -run 'TestMailVerb|TestCarlosMail|TestSeedVarsStrip|TestAgentOwnedVars' && go test ./internal/host/ -run TestMailSwitchCache`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/mailsubmit/ && go test ./internal/activator/ -run 'TestMailVerb|TestCarlosMail|TestSeedVarsStrip|TestAgentOwnedVars' && go test ./internal/host/ -run 'TestMailSwitchCache|TestMailerSidePackagesDoNotImportMail'`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** the same commands, then `go test ./internal/activator/ -run 'Control|Schedule|Updates|AgentOwned|Spawn'` and `go test ./internal/moves/`. Expected: PASS. Cross-build darwin and windows (the mailsubmit dialer must compile there; it is never reached). |
| -- [ ] **Step 5: Census card**, as Task 3 step 5. |
| +- [ ] **Step 5: Census card**, as Task 3 step 5, and rerun `make census-propose NAME=platform-mail-submission` so this push is green (round 1 P3). |
| - [ ] **Step 6: Commit** `activator: POST /v1/mail on the control socket; CARLOS_MAIL agent-owned`. |
| - [ ] **Step 7: Review** (own review: security gate). Astra reviews the card and the diff. |
| @@ -295,23 +320,31 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| **Files:** |
| - Create: `internal/mailer/send.go`, `internal/mailer/policy.go`, `internal/mailer/hygiene.go`, `internal/mailer/rate.go`, `internal/mailer/counter.go`, `internal/mailer/keys.go`, `internal/mailer/routes.go`, `internal/mailer/ses.go`, with tests beside each |
| - Modify: `mailer_cli.go` (wire the pipeline) |
| -- Modify: `internal/release/store.go` (one constructor) |
| +- Modify: `internal/release/store.go` (one constructor; `newS3Store`'s client options factored out, unchanged) |
| - Modify: `internal/provision/reconcile.go` (one exported predicate) |
| -- Modify: `internal/hostenv/hostenv.go` (`Optional` gains `CARLOS_MAIL_REGION`) |
| +- Modify: `internal/hostenv/hostenv.go` (`Optional` gains `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`) |
| +- Modify: `internal/mailwire/mailwire.go` (`DomainView` and its decode pin, `TenantName`, the tier default cap; round 1 P3) |
| +- Modify: `internal/console/mailcounts.go` (`TierCap("")` reads `mailwire`'s default; round 1 P3) |
| **Interfaces:** |
| -- `internal/release`: `func NewS3StoreWithCredentials(ctx context.Context, bucket, region string, creds aws.CredentialsProvider) (*S3Store, error)` builds `newS3Store` with `awsconfig.WithCredentialsProvider(creds)` and IMDS disabled (`awsconfig.WithEC2IMDSClientEnableState(imds.ClientDisabled)`). It also honours `CARLOS_S3_ENDPOINT` and `CARLOS_S3_QUIRKS` as `newS3Store` does. |
| +- **Regions and credentials** (round 1 P2-3). IMDS is off, so the default chain would find no region, and `CARLOS_REGION` is a placement label, not an AWS region. The mailer names both regions explicitly, from host.env through the unit's `EnvironmentFile=`: |
| + - `CARLOS_MAIL_REGION`: the SES region, the same value as the console's; |
| + - `CARLOS_DEPLOYMENT_REGION`: the deployment bucket's AWS region. |
| + Both are new optional host.env keys. `carlos mailer serve` refuses to start without either, with one journal line naming the missing key. |
| + Every AWS config the mailer builds comes from `rootaws.LoadStaticConfig(ctx, keyID, secret, awsconfig.WithRegion(<region>))` (`internal/rootaws/config.go:45`). That function already refuses `AWS_PROFILE`, empties the shared config files and disables IMDS. The mailer never calls `LoadDefaultConfig`. |
| +- `internal/release`: `func NewS3StoreFromConfig(cfg aws.Config, bucket string) *S3Store` builds the client with the same options `newS3Store` applies today: `s3compat.Options()` and the checksum settings, which honour `CARLOS_S3_ENDPOINT` and `CARLOS_S3_QUIRKS`. Those options move into one unexported helper that both call; neither body's behaviour changes. |
| +- **A missing object reads as absent, not as an error** (round 1 P2-4). The mailer's IAM user has no `s3:ListBucket`, so S3 answers a missing key with `403 AccessDenied`, not `404`, and `s3NotFound` (`store.go:887-896`) does not fold that. The mailer's three reads (sender, instance and domain records) go through `func readAbsentOnDenied(ctx, s release.Store, key string) ([]byte, string, error)`. It maps `os.ErrNotExist` **and** an `AccessDenied` API error to "absent". Absent always refuses (`SUBMISSION_OFF`, `ROUTE_NOT_ON_BOX` or `FROM_NOT_ALLOWED`), so the mapping cannot admit anything. A denied read is logged as such, at most once a minute per prefix, so a broken policy is visible and is not mistaken for a real absence. Domain records are read by `mailwire.DomainKey(acct, domain)` for each `Grant.Domains` entry, never listed, so no List grant is needed. |
| - `internal/provision`: `type BoxScope struct { Region string; Pools []string; FleetBox string }` and `func BoxServesRecord(b BoxScope, rec Record) bool`. It returns exactly `ReconcileConfig{Region: b.Region, Pools: b.Pools, FleetBox: b.FleetBox}.inScope(rec.Region, rec.Pool, everywhereClass(rec)) && …ownsRecord(rec) && !rec.Retired`. It is built from the **same unexported predicates**, which do not change, so "on this box" means what the reconciler means. Where `FleetBox` is set the check is exact; otherwise it is region and pool (decision 4, §6). |
| - `internal/mailer/keys.go`: the key file format is up to two lines of `<access-key-id> <secret-access-key> <created RFC 3339>`; `#` comments and blank lines are skipped. |
| - `func LoadKeys(path string) ([]Key, error)` refuses a file that is not mode `0640`, not owned by root, or not group `carlos-mailer`, and refuses more than two keys. |
| - - `type KeyProvider struct` implements `aws.CredentialsProvider` with the **newest** `created`. It re-reads the file when its mtime changes, so rotation needs no restart (§5 Rotation). |
| + - `type KeyFile struct` holds the loaded keys. `func (k *KeyFile) Newest() Key` returns the key with the **newest** `created`. `func (k *KeyFile) Changed() bool` reports an mtime change, after which the mailer reloads the file and rebuilds its clients, so rotation needs no restart (§5 Rotation). |
| - `internal/mailer/routes.go`: `func (m *Mailer) routeHere(ctx, acct, app, host string) (bool, error)` reads `provision.RecordKey(acct, app, host)` through `provision.GetRecord` (which refuses a body that disagrees with its key) and returns `provision.BoxServesRecord(m.scope, rec)`. It caches answers for 30 s; a negative answer is cached for 5 s. |
| - `internal/mailer/policy.go`: `func (m *Mailer) admit(ctx, req mailsubmit.SendRequest) (decision, error)`. Before any SES call, in this order: |
| 1. `routeHere`, else `403 ROUTE_NOT_ON_BOX` (**test 8.4**). |
| 2. The app sender (`mailwire.SenderKey(acct, app, "app")`, decoded as `SenderView`, cached 2 s by etag). Absent, or `Submission` off, gives `403 SUBMISSION_OFF`. |
| 3. `EffectivePause() != nil` gives `429 PAUSED`, with `Retry-After` set to the seconds to the next UTC midnight for `cap`/`plan`, and 3600 otherwise. |
| 4. Parse `raw`'s header block. Exactly one `From:` whose address (net/mail) equals `req.From`, case-insensitively, else `400 BAD_REQUEST` (§4 "`from` ≠ `From:`"). |
| - 5. The From domain must exactly equal one of `Grant.Domains` whose domain record (`mailwire.DomainKey`) has `Regions[CARLOS_MAIL_REGION].Status == "verified"`, else `403 FROM_NOT_ALLOWED`. The rule matches `SendPolicyJSON`'s `*@<domain>` (`policy.go:171-180`), with the domain compared exactly. |
| + 5. The From domain must exactly equal one of `Grant.Domains` whose domain record (`mailwire.DomainKey`, decoded as `mailwire.DomainView`: `Domain`, `Apps`, `Regions[r].{Status, ConfigSet, IdentityARN}`) lists the app and has `Regions[CARLOS_MAIL_REGION].Status == "verified"`, else `403 FROM_NOT_ALLOWED`. The rule matches `SendPolicyJSON`'s `*@<domain>` (`policy.go:171-180`), with the domain compared exactly. |
| 6. The cap: `counter.Reserve(sender, day, cap)`, where `cap = Grant.DailyCap`, or the tier default when it is 0. At the cap it is `429 CAP_REACHED`, with `Retry-After` to the next UTC midnight. |
| 7. The rate: `bucket.Take(sender)`, else `429 RATE` with `Retry-After = ceil(seconds to the next token)`, at least 1. A refused take releases the step-6 reservation. |
| The tier default cap moves from `internal/console`'s `TierCap("")` to a constant in `internal/mailwire`, which both import, so the two cannot disagree. |
| @@ -321,7 +354,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `Reserve` increments and writes with temp file, fsync and rename before the send. `Release` decrements on a send that SES did not accept. |
| - Files older than 3 days are removed at start. |
| - A corrupt file is moved aside, logged, and the day restarts from 0. That is the per-box bound §4.1 (a) accepts, and it is logged loudly. |
| -- `internal/mailer/ses.go`: `type SES interface { SendEmail(ctx, *sesv2.SendEmailInput, ...func(*sesv2.Options)) (*sesv2.SendEmailOutput, error) }`. The real client is `sesv2.NewFromConfig` in `CARLOS_MAIL_REGION` with `KeyProvider`. The input is: |
| +- `internal/mailer/ses.go`: `type SES interface { SendEmail(ctx, *sesv2.SendEmailInput, ...func(*sesv2.Options)) (*sesv2.SendEmailOutput, error) }`. The real client is `sesv2.NewFromConfig` over `rootaws.LoadStaticConfig` with the newest key and `CARLOS_MAIL_REGION`. The S3 store is rebuilt over the same key in `CARLOS_DEPLOYMENT_REGION`. When the key file changes, both clients are rebuilt. The input is: |
| - `FromEmailAddress: req.From`; |
| - `Destination.ToAddresses: req.To` (the envelope); |
| - `Content.Raw.Data`: the stripped raw; |
| @@ -330,7 +363,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `EmailTags`: `account`, `app`, `sender`. |
| SES errors map as follows: `MessageRejected` is `400 REJECTED`; `TooManyRequests` and throttling are `429 RATE` with `Retry-After: 1`; `SendingPaused`, `AccountSuspended` and any other error are `503 MAILER_UNAVAILABLE`. A refusal releases the reservation. |
| - `POST /v1/send` is served under Task 3's peer rule. Concurrency is at most 4 sends in flight (a semaphore); above that the answer is `503 MAILER_UNAVAILABLE`. |
| -- `carlos mailer serve` reads `CARLOS_DEPLOYMENT_BUCKET`, `CARLOS_MAIL_REGION`, `CARLOS_REGION`, `CARLOS_POOLS` (`provision.ParseBoxPools`) and the fleet identity variables (`CARLOS_FLEET`, `CARLOS_FLEET_BOX`, `CARLOS_TUNNEL_NAME`, with the agent's resolution rule). It refuses to start, with one line, without the bucket, the mail region or a loadable key. |
| +- `carlos mailer serve` reads `CARLOS_DEPLOYMENT_BUCKET`, `CARLOS_DEPLOYMENT_REGION`, `CARLOS_MAIL_REGION`, `CARLOS_REGION` (placement only), `CARLOS_POOLS` (`provision.ParseBoxPools`) and the fleet identity variables (`CARLOS_FLEET`, `CARLOS_FLEET_BOX`, `CARLOS_TUNNEL_NAME`, with the agent's resolution rule). It refuses to start, with one line, without the bucket, either region or a loadable key. The unit then restarts it every 5 s (`Restart=always`, `RestartSec=5`). The socket stays up, so the agent's dial answers `503 MAILER_UNAVAILABLE`, and the box reports `MailerArmed=false` because `/v1/health` fails. That is the stated failure behaviour (round 1 P3). |
| - [ ] **Step 1: Write the failing tests** (fake SES recording calls, in-memory `release.Store`, temp state directory): |
| - `TestMailerRefusesRouteNotOnBox` (**test 8.4**): a record in another region, in another pool, labelled for another fleet box, retired, absent, or with a body naming another host. Each is `403 ROUTE_NOT_ON_BOX`, with no SES call. |
| @@ -340,13 +373,17 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `TestCounterDurableAcrossRestart`: reserve 2, reopen, reserve 1 more against cap 3, and the 4th is refused; a refused SES send releases its slot; a corrupt file restarts at 0 and is logged. |
| - `TestRateBucket`: 20 in a burst, then `429 RATE` with `Retry-After: 1`, and after 500 ms one more is admitted. |
| - `TestKeysFile`: a mode or owner other than `0640 root:carlos-mailer` is refused (a test seam for the owner check); three keys are refused; the newest wins; an mtime change reloads. |
| - - `TestMailerNeverUsesIMDS`: building the SES and S3 clients with `KeyProvider` makes no call to a fake IMDS endpoint set through `AWS_EC2_METADATA_SERVICE_ENDPOINT`. |
| + - `TestMailerNeverUsesIMDS`: building the SES and S3 clients makes no call to a fake IMDS endpoint set through `AWS_EC2_METADATA_SERVICE_ENDPOINT`, and the configs carry exactly the two named regions. |
| + - `TestMailerRefusesWithoutRegion` (round 1 P2-3): `carlos mailer serve` with `CARLOS_MAIL_REGION` unset, and again with `CARLOS_DEPLOYMENT_REGION` unset, exits non-zero naming the key, before it serves anything. |
| + - `TestMailerReadsAccessDeniedAsAbsent` (round 1 P2-4): a fake store answering `AccessDenied` for the sender gives `403 SUBMISSION_OFF`, for the instance record `403 ROUTE_NOT_ON_BOX`, and for a domain record `403 FROM_NOT_ALLOWED`. None reaches SES, and each logs the denial. Any other store error gives `503 MAILER_UNAVAILABLE`. |
| + - `TestDomainViewDecodesMailDomain` (round 1 P3): a fully populated `mail.DomainRecord`, marshalled and decoded as `mailwire.DomainView`, keeps every field the view names. Lives in `internal/mail`'s tests, which can import both. |
| + - `TestTierDefaultCapShared`: `internal/console`'s `TierCap("")` equals `mailwire.DefaultDailyCap`. |
| - `TestBoxServesRecordMatchesReconciler`: for a table of records and box scopes, `BoxServesRecord` agrees with what a reconcile pass would mint (reuse the reconcile test fixtures). |
| - - `TestHostEnvAllowsMailRegion`: `CARLOS_MAIL_REGION` passes `Assemble` and `AssembleGroup`. |
| -- [ ] **Step 2: Run** `go test ./internal/mailer/ && go test ./internal/provision/ -run TestBoxServesRecord && go test ./internal/hostenv/ -run TestHostEnvAllowsMailRegion && go test ./internal/release/ -run NewS3StoreWithCredentials`. Expected: FAIL. |
| + - `TestHostEnvAllowsMailRegion`: `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` pass `Assemble` and `AssembleGroup`. |
| +- [ ] **Step 2: Run** `go test ./internal/mailer/ && go test ./internal/provision/ -run TestBoxServesRecord && go test ./internal/hostenv/ -run TestHostEnvAllowsMailRegion && go test ./internal/release/ -run NewS3StoreFromConfig && go test ./internal/mail/ -run TestDomainViewDecodesMailDomain && go test ./internal/console/ -run TestTierDefaultCapShared`. Expected: FAIL. |
| - [ ] **Step 3: Implement** to the interfaces. |
| - [ ] **Step 4: Run** the same commands. Expected: PASS. Cross-build darwin and windows. |
| -- [ ] **Step 5: Census card**, as Task 3 step 5. The mailer's read of `/etc/carlos-mailer/keys` is **not** a root read (it runs as `carlos-mailer`), but the code is in the root binary, so its units are `new`. |
| +- [ ] **Step 5: Census card**, as Task 3 step 5, and rerun `census-propose` under the same NAME. The mailer's read of `/etc/carlos-mailer/keys` is **not** a root read (it runs as `carlos-mailer`), but the code is in the root binary, so its units are `new`. |
| - [ ] **Step 6: Commit** `mailer: policy before the send, hygiene, rate, per-box cap, SES`. |
| - [ ] **Step 7: Review** (own review: security gate and production). Astra reviews the card and the diff. |
| @@ -358,7 +395,8 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - Modify: `internal/release/release.go` (`type Manifest` `:47`, the manifest validation `:446-470`) |
| - Modify: `cli.go` (`runShip` `:2464`, the `--mail` flag), `ship_stateless.go`'s neighbour for the echo check, `internal/console/apicli.go` (`handleAPIShip` `:2126`: accept, store and echo `mail`) |
| - Create: `internal/console/apisubmission.go`, `internal/console/apisubmission_test.go` |
| -- Modify: `internal/console/routedecls.go` (one row beside `:1224`), `internal/console/apimail.go` (status reply gains `submission`), `internal/console/teamcreds.go` (`mintOwnedEnvironmentMail` `:50`) |
| +- Modify: `internal/console/routedecls.go` (one row beside `:1224`), `internal/console/apimail.go` (status reply gains `submission`), `internal/console/teamcreds.go` (`mintOwnedEnvironmentMail` `:50`, `reapOwnedEnvironmentCredentials` `:90`) |
| +- Modify: `internal/console/alertsignals.go` (a new signal function beside `heartbeatBoxSignals` `:397`; the rule's kind and level in `alertRuleKind` `:472` and `alertRuleLevel` `:485`), `internal/console/alertengine_pass.go` (call it in the pass), the alert copy (`alertRuleCopy`, `alertengine_pass.go:485`, and its approved rows) (round 1 P2-5). All of this is in `internal/console`, outside census scope; nothing lands in `internal/alerting`. |
| - Modify: `internal/mail/walk.go` (`claimUnserializedEnable` `:761`, `claimUnserializedRotate` `:1031`, `claimUnserializedSetSenderPaused` relaxed for switched senders), `internal/mail/walk_environment.go` (`claimUnserializedEnableEnvironment`), `internal/mail/sweep.go` (the §7.4 reap) |
| - Create: `internal/mail/submission.go`, `internal/mail/submission_test.go` |
| - Modify: the console doors that change what a route serves. Step 1 enumerates them; at least `handleAPIPromote` (`apicli.go:909`), `handleAPIRollback` (`:1312`), `handleAPIInstanceChannel`, `handleAPIUpdatesPut`, `handleAPIUpdatesInstall` and `handleAPIUpdatesPolicy`. |
| @@ -374,40 +412,53 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task |
| - `func SwitchOn(ctx, s, p Provisioner, seal, d Deployment, acct, app, actor string, now time.Time) (*Record, error)`, under the claim-mail wrappers like every walk. It sets `Submission{On: true, At: now, By: actor}` on the app sender. It removes the five `<P>_SMTP_*` from the default bundle and from every owned environment's bundle, and writes `<P>_MAIL_FROM` (G3) into each. It runs `ReapEnvironment` for each owned environment's user. It **keeps** the app-level user and key (the overlap week), still governed by pause. |
| - `func SwitchOff(…)`: clears `Submission.On`, removes `<P>_MAIL_FROM`, and calls `Enable` (re-mint and re-deliver), then `EnableEnvironment` for each owned environment. |
| - `claimUnserializedEnable` and `claimUnserializedEnableEnvironment` deliver nothing while switched: `Enable` refreshes the policy only, and `EnableEnvironment` returns `ErrSubmissionOn`. `Rotate` refuses with `ErrSubmissionOn`. |
| - - `mintOwnedEnvironmentMail` checks `Submission.On` **explicitly** and returns nil, rather than relying on `Provisioned == nil`. |
| + - **New owned environments while switched** (round 1 P1-1). `mintOwnedEnvironmentMail` (`teamcreds.go:50`, reached from `teamenv.go:235` and the adopt and fork doors) checks `Submission.On` **explicitly**, rather than relying on `Provisioned == nil`. When the switch is on, it mints **no** IAM user and no key. It calls `mail.DeliverMailFromIn(ctx, s, acct, app, env)`, which writes `<P>_MAIL_FROM` (the app sender's `Declared.From`) into that environment's bundle and nothing else. A bundle does not inherit from the default, so without this a team environment created after the flip would boot with no From, and Task 7's `FromCarlos` would refuse it. |
| + - `func DeliverMailFromIn(ctx, s release.Store, acct, app, env string) error` is idempotent and writes the one variable through `appconfig.ApplyEnvironment`. That makes it a known walk for guard 18 (`TestApplyCallersAreTheKnownWalks`): add it to that test's list in the same commit. |
| + - **Release** (`reapOwnedEnvironmentCredentials` → `ReapEnvironment`) also unsets `<P>_MAIL_FROM` from the environment's bundle, beside the five it unsets today (`unsetSMTPEnvIn`, `walk_environment.go:171-196`). It does this whether or not the record names an environment user, because a switched app's environments have none. |
| - `claimUnserializedSetSenderPaused` accepts a switched sender with `Provisioned == nil`, and writes only `Pause`. |
| - `internal/mail/sweep.go`: `ReapAppUserAfterSubmission` reaps the app-level user and key only (never the identity: senders spec #147), sets `Submission.AppUserReapedAt`, and clears `Provisioned`. It runs only when **all** of the following hold (G4): |
| - the switch has been on for at least 7 days; |
| - - the console has logged at least one Send event for the app attributed to the mailer; |
| - - none attributed to `carlos-mail-<acct>-<app>` in the last 7 days. |
| - It reads the console's message log through a function argument, so `internal/mail` stays free of the console. |
| + - `MailCallerSends(acct, app, since = the switch day)["mailer"] >= 1`; |
| + - `MailCallerSends(acct, app, since = today − 7)["app_user"] == 0`. |
| + It reads Task 2's caller-class counts (`Store.MailCallerSends`, round 1 P2-1) through a function argument, `func(acct, app, sinceDay string) (map[string]int64, error)`, so `internal/mail` stays free of the console. A read error skips the reap for that pass. As G4 says, this proves the SMTP key stopped being used, not that every route can submit. |
| - The door, `POST /api/cli/apps/{account}/{app}/email/submission` with body `{"on": bool}`, `Kind: kindCLI`, `Allow: svcrole.Allow(svcrole.Admin)` (the authority `email enable` has). On `on: true` it checks, in order, and each failure is `409` with the remedy: |
| 1. the app's mail is declared and enabled; |
| 2. **every route** of the app (every instance record, owned environments included) has a fresh `StagedVersion` (the box join, `apiinstances.go:1075-1095`) whose manifest has `Mail == "submit"`. A route with no fresh report is refused as "cannot confirm", by name; |
| 3. every channel those routes follow has a head whose manifest has `Mail == "submit"`, so a wake cannot adopt an undeclared head; |
| 4. G8: if the app sender has a `TenantARN`, the provisioner confirms that its identity and configuration set are associated with the tenant; |
| 5. G6 (b): every box that reports one of the app's routes reports `MailerArmed`. |
| +- **The `mailer_unarmed` alert** (round 1 P2-5), in `internal/console/alertsignals.go`: |
| + - `func mailerUnarmedSignals(boxes []status.Box, switched map[string]bool, now time.Time, sig *alertSignals)`. |
| + - `switched` is the set of hosts that belong to a switched app's instance records. The pass builds it from the app senders whose `Submission.On` is set and their instance records, both read through `engineReads.get`, so unchanged objects are not re-read. |
| + - For every fresh box (not `status.BoxStale`) whose `Metrics.RouteVersions` names a host in `switched` while `Metrics.MailerArmed` is false, it adds signal `mailer_unarmed` keyed by the box label, value 1. Every other fresh box gets value 0, so an open incident clears on its own. A stale box adds nothing; the heartbeat rule already covers it. |
| + - `alertRuleKind("mailer_unarmed")` is the box kind and `alertRuleLevel` is warning. The copy row is drafted in step 0. |
| + - `alertengine_pass.go` calls it beside `heartbeatBoxSignals` and passes `sig.cover("mailer_unarmed", unread)`, so a box whose snapshot was unreadable is unknown, not clear. |
| A flat route is **not** a refusal (decision 7, test 8.8). It then calls `mail.SwitchOn`, bumps the serial, and requests an app-wide restart through the existing restart-gen path (`handleAPIRestart`, `apicli.go:1582`). Running instances then respawn with `CARLOS_MAIL`. Until they do, they send over SMTP on the kept app-level key. `on: false` calls `mail.SwitchOff`, bumps the serial and requests the restart. |
| - **The precondition holds while on** (decision 10, test 8.12): `func (s *Server) submissionBuildRefusal(ctx, acct, app, version string) *doorRefusal` returns `409` "this build does not declare `--mail submit`, and email submission is on for <app>: switch submission off first (carlos email submission off --app <app>), or ship with --mail submit". Every door from step 1's enumeration calls it before it writes. Waking is never refused. Instead, at spawn, when `MailSwitch` is on and the staged manifest's `Mail != "submit"`, the agent logs at error level and emits an instance event, once per (host, version). The adopt pass does the same when it adopts such a head (G7). |
| - The status reply and `carlos email status` gain a Submission block: on or off, since when, whether the app-level user is kept or reaped, and the boxes not armed. |
| -- [ ] **Step 0: UX pass, then copy review** (AGENTS.md). Mock the CLI output of `email submission on|off` and the status block, and the five precondition refusals and the build refusal, at 80 columns. Lead with the state. Draft IDs `PMS-C1`.. in `platform-mail-submission-copy.json`. Run the copy-review skill, and apply Paul's edits verbatim. `TestApprovedPlatformMailSubmissionCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`). **Paul's step.** |
| +- [ ] **Step 0: UX pass, then copy review** (AGENTS.md). Mock the CLI output of `email submission on|off` and the status block, the five precondition refusals, the build refusal, and the `mailer_unarmed` alert's title and body, at 80 columns. Lead with the state. Draft IDs `PMS-C1`.. in `platform-mail-submission-copy.json`. Run the copy-review skill, and apply Paul's edits verbatim. `TestApprovedPlatformMailSubmissionCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`). **Paul's step.** |
| - [ ] **Step 1: Enumerate the serve doors.** Grep `routedecls.go` for every handler that writes a channel pointer, an instance's channel, an update pin or policy, or a rollback, and list them in `submissionServeDoors` (a slice of route patterns). Write `TestSubmissionGateCoversEveryServeDoor`. It drives each listed door against a switched app with an undeclared build and expects the refusal. It also fails if a route declaration whose handler calls a known pointer, channel or pin writer is missing from the list. That second check is the second-door guard (AGENTS.md "a rule stated as an absence"). |
| - [ ] **Step 2: Write the failing tests.** |
| - `TestManifestMailField`: `""` and `"submit"` valid, `"smtp"` refused; a manifest without the key parses as `""` and marshals byte-identically to before (the `Label` rule). |
| - `TestShipMailFlagEcho`: `carlos ship --mail submit` sends it and refuses a console that does not echo it. |
| - - `TestSwitchedAppRendersNoCredential` (**test 8.1**, golden): after `SwitchOn`, `appconfig.RenderEnv` (`materialize.go:37`) for the default environment and an owned one holds no `<P>_SMTP_*`, no `AWS_*` key, and does hold `<P>_MAIL_FROM`. |
| + - `TestSwitchedAppRendersNoCredential` (**test 8.1**, golden), three cases. In each, `appconfig.RenderEnv` (`materialize.go:37`) holds no `<P>_SMTP_*` and no `AWS_*` key, and does hold `<P>_MAIL_FROM`: |
| + - the default environment after `SwitchOn`; |
| + - an owned environment that existed at the flip; |
| + - **an owned environment created after the flip**, through the real door path (`teamenv.go:235` → `mintOwnedEnvironmentCredentials`) (round 1 P1-1). |
| - `TestSubmissionDoorPreconditions` (**test 8.8**): an undeclared route build, an undeclared channel head, an unassociated tenant, an unarmed box and an unreported route each refuse with their copy row. A flat route does not refuse. All declared gives `200`, the serial bumped and the restart requested. |
| - `TestSubmissionGateCoversEveryServeDoor` and `TestWakeNeverRefusedForUndeclaredBuild` (**test 8.12**): the doors refuse with "switch submission off first"; a spawn with the switch on and an undeclared staged manifest starts, and logs and emits the event once. |
| - `TestSwitchOffReMints`: `SwitchOff` restores the five variables through `Enable` in the default and owned bundles, and removes `<P>_MAIL_FROM`. |
| - - `TestEnableRotateWhileSwitched`: `Enable` delivers nothing, `Rotate` and `EnableEnvironment` return `ErrSubmissionOn`, and `mintOwnedEnvironmentMail` is a no-op. |
| + - `TestEnableRotateWhileSwitched`: `Enable` delivers nothing; `Rotate` and `EnableEnvironment` return `ErrSubmissionOn`. |
| + - `TestMintOwnedEnvironmentWhileSwitched` (round 1 P1-1): while switched, `mintOwnedEnvironmentMail` makes **no** `EnsureUser` or `MintKey` call on the fake provisioner, writes no caller index entry, and delivers exactly `<P>_MAIL_FROM` into the new bundle. Releasing that environment removes `<P>_MAIL_FROM`, and its bundle then holds none of the six names. |
| + - `TestMailerUnarmedSignal` (round 1 P2-5): an unarmed fresh box hosting a switched app's route signals 1; the same box armed signals 0; an unarmed box hosting only unswitched routes signals 0; a stale box adds nothing; an unreadable box is covered as unknown. |
| - `TestPauseSwitchedSenderWithoutProvisioned`: after the reap, `SetSenderPaused` writes `Pause` and no key call is made. |
| - - `TestReapAppUserAfterSubmission`: refused at 6 days; refused with a recent SMTP-attributed Send; refused with no mailer-attributed Send; done otherwise (user and keys deleted, identity kept, caller index entry removed, `AppUserReapedAt` set). |
| + - `TestReapAppUserAfterSubmission` (with a fake `MailCallerSends`): refused at 6 days; refused with an `app_user` send inside the last 7 days; refused with no `mailer` send since the switch; refused on a read error; done otherwise (user and keys deleted, identity kept, caller index entry removed, `AppUserReapedAt` set). An `other` send (a standalone credential) does not block it. |
| - Guard tests 17 and 19 (`TestOwnedEnvironmentReceivesItsOwnPlatformCredentials` `teamcreds_test.go:101`, `TestReleaseReapsAndRevokingTheCredentialDoesNot` `:232`) gain a switched-app case: the owned environment holds no mail credential, and releasing it reaps nothing that is not there. |
| -- [ ] **Step 3: Run** `go test ./internal/release/ -run TestManifestMailField && go test ./internal/mail/ -run 'Switch|Submission|Reap|EnableRotateWhileSwitched|PauseSwitched' && go test ./internal/console/ -run 'Submission|Switched|OwnedEnvironment|ReleaseReaps' && go test ./internal/activator/ -run TestWakeNeverRefused && go test . -run 'TestShipMailFlag|TestApprovedPlatformMailSubmissionCopy'`. Expected: FAIL. |
| +- [ ] **Step 3: Run** `go test ./internal/release/ -run TestManifestMailField && go test ./internal/mail/ -run 'Switch|Submission|Reap|EnableRotateWhileSwitched|PauseSwitched' && go test ./internal/console/ -run 'Submission|Switched|OwnedEnvironment|ReleaseReaps|MintOwnedEnvironmentWhileSwitched|MailerUnarmedSignal|ApplyCallersAreTheKnownWalks' && go test ./internal/activator/ -run TestWakeNeverRefused && go test . -run 'TestShipMailFlag|TestApprovedPlatformMailSubmissionCopy'`. Expected: FAIL. |
| - [ ] **Step 4: Implement**, then the CLI projection, parity row `email-submission email gap email submission on ; email submission off …`, the `docs/site/cli.md` heading, and `make parity-doc`. |
| - [ ] **Step 5: Run** the same commands, then `go test . -run 'TestCLIProjection|TestParity'`, `go test ./internal/docsite/` and `go test ./internal/console/ -run 'Promote|Rollback|Channel|Updates|Ship|Email'`. Expected: PASS. |
| -- [ ] **Step 6: Census card** (the manifest field and validation, the ship flag, and the activator and host log sites). |
| +- [ ] **Step 6: Census card** (the manifest field and validation, the ship flag, and the activator and host log sites), and rerun `census-propose` under the same NAME. |
| - [ ] **Step 7: Commit** `email: per-app submission switch, its door and its preconditions`. |
| - [ ] **Step 8: Review** (own review: security gate and production storage). Astra. |
| @@ -455,27 +506,27 @@ The unit install itself is Task 3 (bootstrap and system apply carry the units, s |
| **Files:** |
| - Create: `infra/modules/region-host/mailer.tf`, `infra/modules/region-host/tests/mailer.tftest.hcl` |
| - Modify: `infra/modules/region-host/variables.tf`, `infra/modules/region-host/outputs.tf`, `infra/modules/region-host/README.md` |
| -- Create: `docs/mailer-runbook.md` (arming, rotation, a new group box, disarming) |
| +- Create: `docs/mailer-runbook.md` (arming, rotation, a new group box, disarming, and the name rule below) |
| **Interfaces (module inputs and outputs):** |
| -- `variable "mailer"`: `object({ ses_region = string, ses_account_id = string })`, default `null`. Null means no resources: every deployment that has not switched mail submission on. |
| +- `variable "mailer"`: `object({ ses_region = string, ses_account_id = string, deployment_bucket_region = string })`, default `null`. Null means no resources: every deployment that has not switched mail submission on. |
| - With it set (`count = var.mailer == null ? 0 : 1`): |
| - `aws_iam_user.mailer`: name `carlos-mailer-${data.aws_region.current.name}`, path `/carlos-mailer/`, tags. **No `aws_iam_access_key`**: the key never enters tofu state; the operator creates it (runbook). |
| - - `aws_iam_user_policy.mailer`, name `carlos-mailer`. Three statements: |
| + - `aws_iam_user_policy.mailer`, name `carlos-mailer`. Two statements: |
| 1. `ses:SendRawEmail` on `arn:aws:ses:${ses_region}:${ses_account_id}:identity/*` and `…:configuration-set/carlos-*`, with no condition (G5). |
| 2. `s3:GetObject` on `${deployment_bucket_arn}/apps/*/*/email/senders/*`, `${deployment_bucket_arn}/apps/*/*/instances/*` and `${deployment_bucket_arn}/accounts/*/email/domains/*`. |
| - 3. `s3:ListBucket` on `${deployment_bucket_arn}` with `StringLike s3:prefix accounts/*/email/domains/*` (`grantedDomains` lists, `walk.go:654-679`). |
| - No `s3:PutObject`, no `s3:DeleteObject`, no IAM action, no `ses:SendEmail`. If the deployment bucket is SSE-KMS, add `kms:Decrypt` on its key, conditioned on `kms:ViaService` S3, and say so in the README. |
| + **No `s3:ListBucket`** (round 1 P2-4): the mailer reads domain records by key, one per granted domain, and never lists. A missing object therefore answers `403`, which Task 5 reads as absent, and absent always refuses. No `s3:PutObject`, no `s3:DeleteObject`, no IAM action, no `ses:SendEmail`. If the deployment bucket is SSE-KMS, add `kms:Decrypt` on its key, conditioned on `kms:ViaService` S3, and say so in the README. |
| - `output "mailer_user_name"`. |
| - The host role gains **nothing** (decision 2). The test asserts it. |
| -- `CARLOS_MAIL_REGION` (Task 5's host.env key) is set from `var.mailer.ses_region` where the module assembles host.env parameters for group boxes. Fixed boxes get it from their operator-written host.env (runbook). |
| +- `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` (Task 5's host.env keys) are set from `var.mailer.ses_region` and `var.mailer.deployment_bucket_region` where the module assembles host.env parameters for group boxes. Fixed boxes get them from their operator-written host.env (runbook, operator step 6). |
| +- **The runbook's name rule** (round 1 P3). `IsMailerCaller` believes any bare name `carlos-mailer-*`. Per §9.0, SES reports an assumed role by its **role** name, bare, so a role named `carlos-mailer-x` would be believed too. Creating one needs IAM authority in the SES account, which only operators hold. The runbook states: no IAM user or role named `carlos-mailer-*` may exist in that account except this module's users, and the account's operators check that with `aws iam list-roles` / `list-users` after any IAM change. An SCP or permissions boundary that refuses `iam:CreateRole` on `carlos-mailer-*` is a follow-up for Paul. |
| - §9 item 4 (the IMDS gate): no change. The group gate admits uid 0 and `carlos` only (`group-init.sh.tftpl:104-117`), so `carlos-mailer` is refused by nft as well as by its unit's `IPAddressDeny`. The fixed-box gate is `scripts/harden-host.sh` in the infra repo. Confirming that it allowlists rather than denylists is an operator check (below), not a change here. |
| - [ ] **Step 1: Write the failing runs** (`command = plan`, mock provider, as `console_mail.tftest.hcl`): |
| - `mailer_off_by_default`: no `aws_iam_user.mailer`. |
| - - `mailer_on`: the user's name and path; the policy's three statements exactly (actions, resources, condition); no access key resource anywhere in the module. |
| + - `mailer_on`: the user's name and path; the policy's two statements exactly (actions, resources); **no `s3:ListBucket` and no `s3:Put*`**; no access key resource anywhere in the module. |
| - `host_role_has_no_ses_from_mailer`: with `mailer` set, the host role's rendered policies contain no `ses:SendRawEmail` (the console's `ses:SendEmail` for `console_mail_from` is untouched). |
| - - `group_host_env_has_mail_region`: a group box's host.env parameters carry `CARLOS_MAIL_REGION`. |
| + - `group_host_env_has_mail_region`: a group box's host.env parameters carry `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`. |
| - [ ] **Step 2: Run** from `infra/modules/region-host`: `tofu init -backend=false && tofu test -filter=tests/mailer.tftest.hcl`. Expected: the new runs fail. |
| - [ ] **Step 3: Implement**, and write `docs/mailer-runbook.md`: the operator steps below in full, with exact commands. |
| - [ ] **Step 4: Run** the same, and `tofu test` for the whole module. Expected: all pass. |
| @@ -506,13 +557,17 @@ Nothing below is done by the plan's implementers. Each production change needs P |
| 1. **Before Task 6 starts (rulings):** rule on G1-G9. G3 (the From variable), G4 (the reap gate) and G6 (group boxes) change what is built. Confirm or correct G9's rate. |
| 2. **Before Task 6 starts (facts):** §9 item 3, whether the tenant association backfill has landed. If any Oficina app sender has a `TenantARN`, the control-plane role needs `ses:ListTenantResources` (G8). That policy is outside this repo. §9 item 2: the Oficina boxes' layout (information only). |
| 3. **Copy review** for Task 6 step 0. |
| -4. **After the platform merge: release and roll.** Cut a platform release. Push its tag to the GitHub mirror (AGENTS.md "Deploy reality"). Roll the platform binary to the fleet through the usual canary then stable channel. The roll installs the three mailer units, the `carlos-mailer` user and the two directories on every box. The units stay inactive (no key). |
| +4. **After the platform merge: release and roll.** |
| + - Cut a platform release and push its tag to the GitHub mirror (AGENTS.md "Deploy reality"). |
| + - Roll the platform binary to the fleet through the usual canary, then stable, channel. The roll installs the three mailer units, the `carlos-mailer` user and the two directories on every box. The units stay inactive, because there is no key yet. |
| + - **Deploy the console and restart it**, then check `curl /api/version` reports the new build. The console must attribute mailer events (Task 2) before any mailer send, and must accept `ship --mail` (Task 6) before any app ships with it (round 1 P3). |
| + - **Update your own `carlos` CLI** to the release before any `carlos ship --mail submit` or `carlos email submission`. An old CLI does not know the flag. |
| 5. **Scoped approval, then the IAM user** for each region that hosts Oficina instances, in the deployment that hosts them (the flagship, `carloku-infrastructure`, whose account ran §9.0's spike: confirm). Bump every `?ref=` to the new tag, set `mailer = { ses_region = "eu-west-1", ses_account_id = "<acct>" }` on the region-host module, then `tofu init -upgrade`, a read plan, and `tofu apply`. It creates one IAM user and one inline policy per region, at no cost. Then, still under the approval: `aws iam create-access-key --user-name carlos-mailer-<region>`. Keep the secret only in your terminal, never in a file in a repo, SSM, the bucket or `user_data`. |
| 6. **Arm each box that hosts the apps' routes** (fixed boxes, and each current group box): |
| - open an interactive Session Manager shell, **not** Run Command (a Run Command parameter is stored and listable); |
| - check that session logging will not record the secret; |
| - - `sudo install -m 0640 -o root -g carlos-mailer /dev/stdin /etc/carlos-mailer/keys`, paste `<key-id> <secret> <created RFC 3339>`, then Ctrl-D; |
| - - on a fixed box, add `CARLOS_MAIL_REGION=<ses region>` to `/etc/carlos/host.env` if it is not there. |
| + - **first**, on a fixed box, add `CARLOS_MAIL_REGION=<ses region>` and `CARLOS_DEPLOYMENT_REGION=<bucket region>` to `/etc/carlos/host.env` if they are not there (a group box has them from the module). The key goes in second, because the key is what starts the unit (round 1 P3). If the key goes in first, the mailer refuses to start and restarts every 5 s, the agent answers `503 MAILER_UNAVAILABLE`, and the box reports not armed until the regions are added (`systemctl restart carlos-mailer.service` then picks them up); |
| + - `stty -echo; sudo install -m 0640 -o root -g carlos-mailer /dev/stdin /etc/carlos-mailer/keys; stty echo`, paste `<key-id> <secret> <created RFC 3339>`, then Ctrl-D. The `stty -echo` keeps the secret off the terminal and out of any session transcript. |
| The `.path` unit starts the socket. Check `systemctl is-active carlos-mailer.socket` and, after the first send, `journalctl -u carlos-mailer`. `carlos email status` shows the box as armed. |
| On a fixed box, also check the IMDS gate allowlists uids and so refuses `carlos-mailer` (`nft list ruleset`, against `scripts/harden-host.sh`). |
| 7. **New or replaced group boxes** (G6, pending the ruling): until a ruling, each one needs step 6. The `mailer_unarmed@<box>` alert names it. |
| @@ -523,6 +578,34 @@ Nothing below is done by the plan's implementers. Each production change needs P |
| ## Census cards |
| -Drafted, pre-build, in `docs/superpowers/notes/census-plan-platform-mail-submission.md`, with one section per task that changes in-scope files (Tasks 3, 4, 5, 6 and 8), in the census-proposal card format, with the CLAIMS text for each unit. At build time, `make census-card` is the authority on which units changed: the builder reconciles the draft against it, writes the CLAIMS file, and runs `make census-propose NAME=platform-mail-submission CLAIMS=<file>`. That writes the real `census-proposal-platform-mail-submission.md`. |
| +Drafted, pre-build, in `docs/superpowers/notes/census-plan-platform-mail-submission.md`, with one section per task that changes in-scope files (Tasks 1, 3, 4, 5, 6 and 8), in the census-proposal card format, with the CLAIMS text for each unit. At build time, `make census-card` is the authority on which units changed: the builder reconciles the draft against it, writes the CLAIMS file, and runs `make census-propose NAME=platform-mail-submission CLAIMS=<file>`. That writes the real `census-proposal-platform-mail-submission.md`. |
| -Out of scope, so no card: Tasks 1 and 2 (`internal/mail`, `internal/console`, both outside `go list -deps .` today), the console halves of Task 6, rastrillo (Task 7), Markdown under `infra/` and `docs/`. |
| +Out of scope, so no card: `internal/mail` and `internal/console` (both outside `go list -deps .` today, and `TestMailerSidePackagesDoNotImportMail` keeps them out), so all of Task 2 and Task 1 apart from `mail_cli.go`; the console halves of Task 6, including the `mailer_unarmed` alert; rastrillo (Task 7); Markdown under `infra/` and `docs/`. **Task 1 is in scope through `mail_cli.go`** (package `.`, `census-base-scope.txt:1493`; round 1 P2-7). |
| + |
| +--- |
| + |
| +## Round 1 findings → changes (rev 2) |
| + |
| +| Finding | Change in this revision | |
| +|---|---| |
| +| **P1-1** a team environment created after switch-on has no From | G3 now covers environments created while switched. Task 6: `mintOwnedEnvironmentMail` delivers `<P>_MAIL_FROM` via `DeliverMailFromIn` and mints nothing; release unsets it; guard 18's walk list gains it. Tests: `TestMintOwnedEnvironmentWhileSwitched` (replaces "is a no-op"), and gate 8.1's golden gains "owned environment created after the flip" | |
| +| **P2-1** G4's gate cannot be computed | Task 2: `CallerClass`, table `mail_caller_sends`, `Store.RecordMailCallerSend` / `MailCallerSends`, tests `TestCallerClass`, `TestMailCallerSendsCounts`, `TestCallerClassIgnoresForgedTags`. Task 6's reap reads `MailCallerSends`. G4 states what the gate proves and what it does not | |
| +| **P2-2** a route with no instance record | Agent-side choice: `CARLOS_MAIL` only when `rt.Provisioned` (Task 4), with a stated residual and a loud log; tested in `TestCarlosMailFollowsTheBind` | |
| +| **P2-3** no stated AWS region | Task 5: `CARLOS_MAIL_REGION` and new `CARLOS_DEPLOYMENT_REGION`, every config from `rootaws.LoadStaticConfig`, `release.NewS3StoreFromConfig`; `TestMailerRefusesWithoutRegion`. Task 8 sets both for group boxes | |
| +| **P2-4** missing objects answer 403 | Task 5: `readAbsentOnDenied`, with absent always refusing and denials logged; `TestMailerReadsAccessDeniedAsAbsent`. Task 8: the `s3:ListBucket` grant is dropped (domains are read by key) | |
| +| **P2-5** the alert has no task | Task 6: `mailerUnarmedSignals` in `internal/console/alertsignals.go`, called from `alertengine_pass.go`, rule kind, level and copy; `TestMailerUnarmedSignal`. In `internal/console`, so no census row | |
| +| **P2-6** empty or unreadable token | Task 4: the existing verbs' `err != nil \|\| want == ""` rule, with a SHA-256 constant-time compare; `TestMailVerbRefusesEmptyToken` | |
| +| **P2-7** Task 1 changes `mail_cli.go` | Task 1 is "+ census", with a census step; Global Constraints, the census section and the census note's Task 1 section are corrected | |
| +| **P2-8** Task 2 is a security gate | Task 2's implementer is Opus | |
| +| P3 operator step 6 | Regions before the key; the unit's failure behaviour is stated (Task 5, operator step 6); `stty -echo` | |
| +| P3 operator step 4 | The console deployed, restarted and version-checked, and Paul's CLI updated, before `ship --mail` | |
| +| P3 Task 2 test reason | Corrected: `carlos-mailer-` never matches the `carlos-mail-` prefix; the converse is pinned too | |
| +| P3 Task 5 file list | `internal/mailwire` (`DomainView` with `TestDomainViewDecodesMailDomain`, the tier default cap) and `mailcounts.go` added | |
| +| P3 role named `carlos-mailer-*` | Task 8 runbook name rule; an SCP or boundary is on the follow-up list | |
| +| P3 census propose per task | Every census-touching task reruns `census-propose` under the same NAME | |
| +| P3 import guard | `TestMailerSidePackagesDoNotImportMail` (Task 4) | |
| + |
| +### P3 follow-up list (does not start a round) |
| + |
| +- An SCP or permissions boundary in the SES account refusing `iam:CreateRole` and `iam:CreateUser` on `carlos-mailer-*`, so the name rule is enforced rather than only stated. |
| +- The door-side answer to P2-2 (a host-to-app map in the box report), if hand-made routes of switched apps turn out to exist. |