carlos / platform Public

mail: Task 2 review fixes (Fable P2-1, P3-1..P3-4, plan text)

- P2-1: the trust boundary is a name. SES reports a bare name, and a role
  or a user under any path has the same one, so IsMailerCaller's bare
  match believes any principal in the SES account named carlos-mailer-*.
  The comments in mailwire and SenderOfCaller and the guard test's rows
  now say so; only the ARN forms are pinned to the mailer's user and
  path. The plan's Task 2 interface and Task 8 name rule say the same
  (no user under any path, nor role, may take the prefix). Pinning the
  match to MailerUserName(region) for configured regions is not done:
  SenderOfCaller has no deployment config, and threading regions in
  changes the planned interface.
- P3-1: TestCallerClassIgnoresForgedTags seeds docs on the events'
  domain, so "an unnamed send adds nothing" is checked against a send
  the domain fallback really charged.
- P3-2: guard test rows for Carlos-Mailer-eu-west-1 and
  carlos-mailer-eu-west-1/x.
- P3-3: TestClaimSESDoorDomainFallbackOnTheGate keeps the SES door's
  unnamed path covered on the claims-on console, now that the door's
  claim fixture sends a named Send.
- P3-4: the caller-class count is recorded before, and independently
  of, the per-sender count (TestCallerSendRecordedWhenTheSenderCountFails,
  watched to fail with the old order).
- Plan text: neither mail_caller_sends nor mail_sender_counts is pruned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 12738d3deb14cb893f916e453c41e64ee418761d parent ce3b599
6 files changed, +119 −21
  • docs/superpowers/plans/2026-11-13-platform-mail-submission.md +3 −3
  • internal/console/sesevents.go +9 −6
  • internal/console/sesevents_test.go +78 −0
  • internal/mail/sender.go +6 −4
  • internal/mail/sender_test.go +10 −3
  • internal/mailwire/mailwire.go +13 −5

CI passed — run details

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 c6a5de03d..3118fc3f7 100644
--- a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md
+++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md
@@ -176,7 +176,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task
- `const TagAccount = "account"`, `TagApp = "app"`, `TagSender = "sender"`.
- `const MailerUserPath = "/carlos-mailer/"`, `MailerUserPrefix = "carlos-mailer-"`.
- `func MailerUserName(region string) string` returns `"carlos-mailer-" + region`.
- - `func IsMailerCaller(caller string) bool`: true for a bare name matching `^carlos-mailer-[a-z0-9-]{1,48}$`, or for an IAM **user** ARN `arn:aws:iam::<12 digits>:user/carlos-mailer/<that name>`. False for every other shape: an assumed-role ARN, a different path, a `carlos-mail-…` name.
+ - `func IsMailerCaller(caller string) bool`: true for a bare name matching `^carlos-mailer-[a-z0-9-]{1,48}$`, or for an IAM **user** ARN `arn:aws:iam::<12 digits>:user/carlos-mailer/<that name>`. False for every other shape: an assumed-role ARN, a different path, a `carlos-mail-…` name. **The trust boundary is a name** (Task 2 review P2-1): SES reports the bare name, and a role or a user under any path has the same bare name, so the bare match believes any principal in the SES account named `carlos-mailer-*`. Only the ARN forms are pinned to the user and path. Task 8's name rule is what keeps the boundary.
- `Event` gains `Tags map[string]string`, holding only the first value of `account`, `app` and `sender` from `mail.tags`, each through `cleanField` with the existing length bound.
- `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").
@@ -187,7 +187,7 @@ Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task
- `"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`, and it joins every list an app-keyed mail table joins (files above).
+ - 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))`. Neither it nor `mail_sender_counts` is pruned: no code prunes `mail_sender_counts`, and this table follows it (build note, Task 2 review). It joins every list an app-keyed mail table joins (files above).
- `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.
@@ -526,7 +526,7 @@ The unit install itself is Task 3 (bootstrap and system apply carry the units, s
- `output "mailer_user_name"`.
- The host role gains **nothing** (decision 2). The test asserts it.
- `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.
+- **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 same holds for an IAM **user** of that name under any path, since SES reports a user by its bare name whatever its path (Task 2 review P2-1): the trust boundary is any principal in the SES account named `carlos-mailer-*`. The runbook states: no IAM user (under any path) 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`):
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go
index 91ed6d084..b808a9359 100644
--- a/internal/console/sesevents.go
+++ b/internal/console/sesevents.go
@@ -535,22 +535,25 @@ func (s *Server) recordAndEnforceMail(ctx context.Context, ev mail.Event, notice
// note: a sibling app on the same domain is no longer charged for
// this send, which is the intent, but a tenant watching its own
// numbers will see them move.
- if err := s.store.RecordMailEvent(ctx, callerAcct, callerApp, callerSender, day, ev.Type); err != nil {
- log.Printf("console: ses events: recording %s for %s/%s/%s -> %v", ev.Type, callerAcct, callerApp, callerSender, err)
- return
- }
// The caller-class count (gap G4): Send events only, on this
// named path only. The class is the CALLER's (mail.CallerClass
// reads ev.Caller and the resolved app, never a tag), so a
// forged tag can neither hide an app-level user's send nor pass
- // one off as the mailer's. A failed write is logged and the
- // limits still run: the cap matters more than this count.
+ // one off as the mailer's. It is recorded first, whatever the
+ // per-sender count below does: the switch's reap reads it as
+ // "the app-level key was used", and a send lost here would let
+ // the reap pass early. A failed write here is logged and the
+ // count and the limits still run: the cap matters more.
if ev.Type == mail.EventSend {
class := mail.CallerClass(callerAcct, callerApp, ev.Caller)
if err := s.store.RecordMailCallerSend(ctx, callerAcct, callerApp, day, class); err != nil {
log.Printf("console: ses events: recording a %s send for %s/%s -> %v", class, callerAcct, callerApp, err)
}
}
+ if err := s.store.RecordMailEvent(ctx, callerAcct, callerApp, callerSender, day, ev.Type); err != nil {
+ log.Printf("console: ses events: recording %s for %s/%s/%s -> %v", ev.Type, callerAcct, callerApp, callerSender, err)
+ return
+ }
if _, reason, err := s.enforceMailLimits(ctx, callerAcct, callerApp, callerSender, at); err != nil {
log.Printf("console: ses events: enforcing limits for %s/%s/%s -> %v", callerAcct, callerApp, callerSender, err)
} else if reason != "" {
diff --git a/internal/console/sesevents_test.go b/internal/console/sesevents_test.go
index 16bf5ada9..7715d79d0 100644
--- a/internal/console/sesevents_test.go
+++ b/internal/console/sesevents_test.go
@@ -892,6 +892,18 @@ func TestCallerClassIgnoresForgedTags(t *testing.T) {
if _, err := fx.st.CreateAppIn(OpsAccountID, "docs", "bill@tito.io", now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
+ // docs is on the events' sending domain, so an unnamed send reaches it
+ // through the domain fallback (and is counted there, checked below):
+ // "adds nothing to the caller-class counts" is then a real claim.
+ if _, err := mail.PutDomain(ctx, fx.rel, release.OpsAccount, &mail.DomainRecord{
+ Domain: "lgc.li", Kind: mail.KindCustom, Apps: []string{"docs"},
+ Regions: map[string]*mail.RegionState{"eu-west-1": {
+ IdentityARN: "arn:aws:ses:eu-west-1:1:identity/lgc.li", Status: mail.StatusVerified,
+ }},
+ CreatedAt: now,
+ }, ""); err != nil {
+ t.Fatal(err)
+ }
day := now.UTC().Format("2006-01-02")
selfTags := map[string]string{"account": release.OpsAccount, "app": "docs", "sender": mail.SenderAppID}
send := func(caller, msg string, typ string) {
@@ -903,6 +915,9 @@ func TestCallerClassIgnoresForgedTags(t *testing.T) {
send(mail.UserName(release.OpsAccount, "docs"), "m-app-user", mail.EventSend)
send(mail.UserName(release.OpsAccount, "docs"), "m-app-user-bounce", mail.EventBounce)
send("someone-else", "m-unnamed", mail.EventSend)
+ if c, err := fx.st.MailCounts(ctx, release.OpsAccount, "docs", "", day); err != nil || c.Sends != 2 {
+ t.Fatalf("docs sends = %+v, %v; want 2: the app user's and the unnamed one through the domain fallback", c, err)
+ }
got, err := fx.st.MailCallerSends(ctx, release.OpsAccount, "docs", day)
if err != nil {
t.Fatal(err)
@@ -922,3 +937,66 @@ func TestCallerClassIgnoresForgedTags(t *testing.T) {
t.Fatalf("caller sends = %v, want %v", got, want)
}
}
+
+// The SES door's domain fallback on the gated (claims-on) console: an event
+// that names no caller is charged to every app on its sending domain, under
+// each app's own SQL permit, and adds nothing to the caller-class counts.
+// The door's claim fixture now sends a named Send (to reach
+// mail_caller_sends), so this keeps the unnamed path covered on the gate.
+func TestClaimSESDoorDomainFallbackOnTheGate(t *testing.T) {
+ cx := newClaimCase(t)
+ cx.srv.snsVerify = func(snsEnvelope) error { return nil }
+ cx.emailProvisioned(t)
+ resp := sesPost(t, cx.consoleFixture, `{"Type":"Notification","TopicArn":"arn:aws:sns:eu-west-1:1:carlos-mail",`+
+ `"Message":"{\"eventType\":\"Delivery\",\"mail\":{\"source\":\"hello@`+claimMailDomain+`\",`+
+ `\"timestamp\":\"`+time.Now().UTC().Format(time.RFC3339)+`\",`+
+ `\"messageId\":\"claim-fallback-message\",\"destination\":[\"claim@example.com\"]},`+
+ `\"delivery\":{\"recipients\":[\"claim@example.com\"]}}",`+
+ `"SigningCertURL":"https://sns.eu-west-1.amazonaws.com/x.pem","Signature":"x"}`)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ ctx := context.Background()
+ day := time.Now().UTC().Format("2006-01-02")
+ c, err := cx.st.MailCounts(ctx, "bab", "titogo", "", day)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c.Deliveries != 1 {
+ t.Fatalf("titogo deliveries = %d, want 1 through the domain fallback", c.Deliveries)
+ }
+ got, err := cx.st.MailCallerSends(ctx, "bab", "titogo", day)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("an unnamed event wrote caller-class counts: %v", got)
+ }
+}
+
+// The caller-class count does not depend on the per-sender count: with
+// mail_sender_counts unwritable, a named Send is still recorded by class, so
+// the switch's reap cannot see "no app-user sends" because the other write
+// failed (Fable Task 2 P3-4).
+func TestCallerSendRecordedWhenTheSenderCountFails(t *testing.T) {
+ fx := newConsoleFixture(t)
+ ctx := context.Background()
+ now := time.Now()
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "docs", "bill@tito.io", now.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.Exec(`DROP TABLE mail_sender_counts`); err != nil {
+ t.Fatal(err)
+ }
+ ev := mail.Event{Type: mail.EventSend, Domain: "lgc.li", MessageID: "m-1", At: now, SentAt: now,
+ Caller: mail.UserName(release.OpsAccount, "docs")}
+ fx.srv.recordAndEnforceMail(ctx, ev, "sns-1")
+ got, err := fx.st.MailCallerSends(ctx, release.OpsAccount, "docs", now.UTC().Format("2006-01-02"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got[mail.CallerClassAppUser] != 1 {
+ t.Fatalf("caller sends = %v, want app_user:1 though the per-sender count failed", got)
+ }
+}
diff --git a/internal/mail/sender.go b/internal/mail/sender.go
index 9c1a69359..a145062a3 100644
--- a/internal/mail/sender.go
+++ b/internal/mail/sender.go
@@ -483,10 +483,12 @@ func claimUnserializedResolveSenderNames(ctx context.Context, s release.Store, a
//
// THE CALLER DECIDES WHETHER A TAG IS BELIEVED, and that check is the
// first statement (platform mail submission decision 6, guard test 8.11).
-// Only the box-local mailer's own principal (mailwire.IsMailerCaller:
-// carlos-mailer-<region>, by bare name or by its user ARN under
-// /carlos-mailer/) sends for many apps, so only its events are attributed
-// by their account, app and sender tags, and only when all three are valid.
+// Only the box-local mailer (mailwire.IsMailerCaller: carlos-mailer-<region>,
+// by bare name or by its user ARN under /carlos-mailer/) sends for many
+// apps, so only its events are attributed by their account, app and sender
+// tags, and only when all three are valid. The bare name is all SES reports,
+// so the boundary is any principal in the SES account named
+// carlos-mailer-*, user or role, under any path (IsMailerCaller's comment).
// Any SMTP-credentialed tenant can set the same tags with an
// X-SES-MESSAGE-TAGS header (§9.0 confirmed SES honours it), so believing a
// tag from any other caller would let a tenant charge its bounces and
diff --git a/internal/mail/sender_test.go b/internal/mail/sender_test.go
index 92759884d..d66fa2338 100644
--- a/internal/mail/sender_test.go
+++ b/internal/mail/sender_test.go
@@ -556,9 +556,16 @@ func TestTagsBelievedOnlyFromMailer(t *testing.T) {
{"the mailer with an invalid account", "carlos-mailer-eu-west-1", map[string]string{"account": "XYZ!", "app": "sheets", "sender": SenderAppID}, want{}},
{"the mailer with an invalid app", "carlos-mailer-eu-west-1", map[string]string{"account": "xyz", "app": "../sheets", "sender": SenderAppID}, want{}},
{"the mailer with an invalid sender", "carlos-mailer-eu-west-1", map[string]string{"account": "xyz", "app": "sheets", "sender": "a/b"}, want{}},
- {"an assumed role named like the mailer", "arn:aws:sts::123456789012:assumed-role/x/carlos-mailer-eu-west-1", mailerTags, want{}},
- {"the mailer's name under the console's path", "arn:aws:iam::123456789012:user/carlos-mail/carlos-mailer-eu-west-1", mailerTags, want{}},
- {"the mailer's name under no path", "arn:aws:iam::123456789012:user/carlos-mailer-eu-west-1", mailerTags, want{}},
+ // The ARN forms are pinned to the mailer's user and path. The BARE
+ // name is not: SES reports a role, or a user under any path, by the
+ // same bare name, so the trust boundary for the bare form is "any
+ // principal in the SES account named carlos-mailer-*" (the runbook's
+ // name rule keeps it). Only the ARN rows below can refuse them.
+ {"an assumed-role ARN named like the mailer", "arn:aws:sts::123456789012:assumed-role/x/carlos-mailer-eu-west-1", mailerTags, want{}},
+ {"a user ARN of the mailer's name under the console's path", "arn:aws:iam::123456789012:user/carlos-mail/carlos-mailer-eu-west-1", mailerTags, want{}},
+ {"a user ARN of the mailer's name under no path", "arn:aws:iam::123456789012:user/carlos-mailer-eu-west-1", mailerTags, want{}},
+ {"the mailer's name in the wrong case", "Carlos-Mailer-eu-west-1", mailerTags, want{}},
+ {"the mailer's name with a path after it", "carlos-mailer-eu-west-1/x", mailerTags, want{}},
{"someone else with tags", "someone-else", mailerTags, want{}},
{"no caller with tags", "", mailerTags, want{}},
} {
diff --git a/internal/mailwire/mailwire.go b/internal/mailwire/mailwire.go
index 38a22529e..3ee81f735 100644
--- a/internal/mailwire/mailwire.go
+++ b/internal/mailwire/mailwire.go
@@ -147,12 +147,20 @@ var (
)
// IsMailerCaller reports whether an SES event's caller identity
-// (mail.tags["ses:caller-identity"]) is the mailer's own principal: the bare
-// user name SES reports (§9.0), or that user's IAM USER ARN under the
-// mailer's path. Every other shape is false: an assumed-role ARN (named by
-// whoever assumes the role), a user under another path, and every
-// carlos-mail-… app user name. This is the one test decision 6's guard
+// (mail.tags["ses:caller-identity"]) names the mailer: a bare name
+// carlos-mailer-<region>, or an IAM USER ARN of that name under the
+// mailer's path /carlos-mailer/. This is the one test decision 6's guard
// asks before a tag is believed.
+//
+// THE TRUST BOUNDARY IS A NAME, NOT A PRINCIPAL. SES reports the bare name
+// (§9.0), and the bare name of an IAM user under ANY path, or of an assumed
+// ROLE, looks exactly the same. So a bare match believes any principal in
+// the SES account named carlos-mailer-*, user or role, whatever its path.
+// Only the ARN forms are pinned: an assumed-role ARN, a user ARN under
+// another path, and every carlos-mail-… app user name are false. What keeps
+// the boundary is that nothing else in the SES account may take that name
+// prefix, which only the account's IAM operators can do; the mailer runbook
+// states the rule (plan Task 8).
func IsMailerCaller(caller string) bool {
return mailerBareRe.MatchString(caller) || mailerARNRe.MatchString(caller)
}