mail: believe SES tags only from the mailer; count sends by caller class
Platform mail submission plan, Task 2 (decision 6, guard test 8.11, §9.0, gap G4; round 1 P2-1, round 2 P2-A). Event gains Tags: the first value of the account, app and sender tags in mail.tags, cleaned and bounded like every other field. SenderOfCaller takes them, and its first statement is decision 6's guard: only when the caller is the mailer's own principal (mailwire.IsMailerCaller, the bare name carlos-mailer-<region> or its IAM user ARN under /carlos-mailer/) are the tags believed, and only when all three are valid. Every other caller keeps today's resolution and its tags are never read: any SMTP-credentialed tenant can set them with X-SES-MESSAGE-TAGS (§9.0). mail.CallerClass classes a caller as mailer, app_user (exactly the app's UserName) or other, from the caller alone. recordAndEnforceMail counts each Send on the named path in a new additive table, mail_caller_sends (Store.RecordMailCallerSend / MailCallerSends), which the switch's reap will read. The table joins mailAppTables with the day-string case in mailAppTimeColumn, so it moves with a rename or an account move and is forgotten with a purged app, and it has a row in the store gate's table map. Like mail_sender_counts, it is not pruned. Mutation-checked: believing tags before or regardless of the caller, a loosened IsMailerCaller, a guard without account validation, a class taken from a tag, counting non-Send events, and leaving the table out of mailAppTables or mailAppTimeColumn each fail a test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+659
−14
internal/console/claim_mail_sql_test.go+3 −0internal/console/mailcounts.go+42 −0internal/console/mailcounts_test.go+102 −0internal/console/mailevents.go+11 −4internal/console/sesevents.go+18 −1internal/console/sesevents_test.go+90 −0internal/console/store.go+17 −0internal/console/store_gate.go+1 −0internal/console/store_gate_test.go+3 −1internal/mail/events.go+22 −0internal/mail/events_test.go+59 −0internal/mail/sender.go+105 −1internal/mail/sender_test.go+112 −4internal/mail/walk_environment_test.go+2 −2internal/mailwire/mailwire.go+39 −1internal/mailwire/mailwire_test.go+33 −0
CI failed — run details
diff --git a/internal/console/claim_mail_sql_test.go b/internal/console/claim_mail_sql_test.go| index bd3cf0a00..df5c0615b 100644 |
| --- a/internal/console/claim_mail_sql_test.go |
| +++ b/internal/console/claim_mail_sql_test.go |
| @@ -29,6 +29,9 @@ func TestMailSQLWritersRefuseWithoutPermit(t *testing.T) { |
| if err := s.RecordMailEvent(ctx, "bab", "titogo", mail.SenderAppID, "2026-10-07", mail.EventSend); err == nil { |
| t.Fatal("RecordMailEvent wrote without a permit") |
| } |
| + if err := s.RecordMailCallerSend(ctx, "bab", "titogo", "2026-10-07", mail.CallerClassMailer); err == nil { |
| + t.Fatal("RecordMailCallerSend wrote without a permit") |
| + } |
| if err := s.SetMailEventHook(ctx, "bab", "titogo", "/mail/events", "a@b", now); err == nil { |
| t.Fatal("SetMailEventHook wrote without a permit") |
| } |
diff --git a/internal/console/mailcounts.go b/internal/console/mailcounts.go| index 48c2cb0bf..a852bd35c 100644 |
| --- a/internal/console/mailcounts.go |
| +++ b/internal/console/mailcounts.go |
| @@ -125,6 +125,48 @@ ON CONFLICT(account, app, sender, day) DO UPDATE SET %s = %s + 1`, col, col, col |
| }) |
| } |
| +// RecordMailCallerSend counts one Send event for (acct, app, day) under its |
| +// caller class (mail.CallerClass). The class is computed by the caller of |
| +// this function from the event's caller identity alone; this store method |
| +// takes it as given and validates only that it is one of the three. |
| +func (s *Store) RecordMailCallerSend(ctx context.Context, acct, app, day, class string) error { |
| + switch class { |
| + case mail.CallerClassMailer, mail.CallerClassAppUser, mail.CallerClassOther: |
| + default: |
| + return fmt.Errorf("console: unknown mail caller class %q", class) |
| + } |
| + // A write of acct/app's row alone, under that app's permit |
| + // (claim_mail_sql.go), like RecordMailEvent. |
| + return s.withMailAppSQL(ctx, acct, app, "sql.RecordMailCallerSend", func(v *Store) error { |
| + _, err := v.db.ExecContext(ctx, `INSERT INTO mail_caller_sends (account, app, day, class, sends) |
| +VALUES (?, ?, ?, ?, 1) |
| +ON CONFLICT(account, app, day, class) DO UPDATE SET sends = sends + 1`, acct, app, day, class) |
| + return err |
| + }) |
| +} |
| + |
| +// MailCallerSends sums an app's Send events by caller class over every UTC |
| +// day on or after sinceDay (a YYYY-MM-DD string, compared as one). A class |
| +// with no sends is absent from the map, and a quiet app is an empty map. |
| +func (s *Store) MailCallerSends(ctx context.Context, acct, app, sinceDay string) (map[string]int64, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT class, COALESCE(SUM(sends), 0) FROM mail_caller_sends |
| +WHERE account = ? AND app = ? AND day >= ? GROUP BY class`, acct, app, sinceDay) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + out := map[string]int64{} |
| + for rows.Next() { |
| + var class string |
| + var n int64 |
| + if err := rows.Scan(&class, &n); err != nil { |
| + return nil, err |
| + } |
| + out[class] = n |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| // MailCounts returns one sender's counts for one UTC day. An EMPTY sender |
| // reads every sender the app has, which is what the status reply's |
| // unchanged top-level figures mean and what a roll-up of an app in |
diff --git a/internal/console/mailcounts_test.go b/internal/console/mailcounts_test.go| index ad369d19c..383a13a93 100644 |
| --- a/internal/console/mailcounts_test.go |
| +++ b/internal/console/mailcounts_test.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "path/filepath" |
| + "reflect" |
| "strings" |
| "testing" |
| "time" |
| @@ -901,3 +902,104 @@ func TestPauseKindsSurvive(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// mail_caller_sends (gap G4): sums by class from a day on, refuses a class |
| +// it does not know, and travels with the app on a rename and on a move to |
| +// another account, so the switch's reap cannot see "no app_user sends" |
| +// because the history stayed behind under the old name (round 2 P2-A). |
| +// |
| +// The plan also asks that pruning remove days past retention "with the same |
| +// retention as mail_sender_counts". mail_sender_counts has no retention: no |
| +// code prunes it. mail_caller_sends follows it, so nothing prunes it either, |
| +// and that is pinned here: an old day is still summed when asked for. |
| +func TestMailCallerSendsCounts(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + ctx := context.Background() |
| + now := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| + today := now.Format("2006-01-02") |
| + yesterday := now.AddDate(0, 0, -1).Format("2006-01-02") |
| + longAgo := now.AddDate(-1, 0, 0).Format("2006-01-02") |
| + for _, app := range []string{"docs", "renaming", "moving"} { |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, app, "bill@tito.io", now.AddDate(-2, 0, 0)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + record := func(app, day, class string) { |
| + t.Helper() |
| + if err := fx.st.RecordMailCallerSend(ctx, release.OpsAccount, app, day, class); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + sends := func(acct, app, since string) map[string]int64 { |
| + t.Helper() |
| + got, err := fx.st.MailCallerSends(ctx, acct, app, since) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return got |
| + } |
| + |
| + record("docs", today, mail.CallerClassMailer) |
| + record("docs", today, mail.CallerClassMailer) |
| + record("docs", yesterday, mail.CallerClassAppUser) |
| + record("docs", today, mail.CallerClassAppUser) |
| + record("docs", today, mail.CallerClassOther) |
| + record("docs", longAgo, mail.CallerClassAppUser) |
| + if got, want := sends(release.OpsAccount, "docs", today), (map[string]int64{"mailer": 2, "app_user": 1, "other": 1}); !reflect.DeepEqual(got, want) { |
| + t.Errorf("since today = %v, want %v", got, want) |
| + } |
| + if got, want := sends(release.OpsAccount, "docs", yesterday), (map[string]int64{"mailer": 2, "app_user": 2, "other": 1}); !reflect.DeepEqual(got, want) { |
| + t.Errorf("since yesterday = %v, want %v", got, want) |
| + } |
| + if got, want := sends(release.OpsAccount, "docs", longAgo), (map[string]int64{"mailer": 2, "app_user": 3, "other": 1}); !reflect.DeepEqual(got, want) { |
| + t.Errorf("since a year ago = %v, want %v (nothing prunes it, like mail_sender_counts)", got, want) |
| + } |
| + if got := sends(release.OpsAccount, "quiet", today); len(got) != 0 { |
| + t.Errorf("an app with no sends = %v, want empty", got) |
| + } |
| + if err := fx.st.RecordMailCallerSend(ctx, release.OpsAccount, "docs", today, "tagged"); err == nil { |
| + t.Error("an unknown class was recorded") |
| + } |
| + |
| + // A rename carries the history to the new name and leaves none behind. |
| + record("renaming", yesterday, mail.CallerClassAppUser) |
| + if err := fx.st.RenameAppIn(OpsAccountID, "renaming", "renamed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := sends(release.OpsAccount, "renamed", yesterday); got[mail.CallerClassAppUser] != 1 { |
| + t.Errorf("after a rename the new name has %v, want app_user:1", got) |
| + } |
| + if got := sends(release.OpsAccount, "renaming", yesterday); len(got) != 0 { |
| + t.Errorf("after a rename the old name still has %v", got) |
| + } |
| + |
| + // So does a move to another account, keyed by the new sqid. |
| + record("moving", yesterday, mail.CallerClassAppUser) |
| + if err := fx.st.CreateAccount(99, "dest", "Destination", "bill@tito.io", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.MoveApp("moving", OpsAccountID, 99); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := sends("dest", "moving", yesterday); got[mail.CallerClassAppUser] != 1 { |
| + t.Errorf("after a move the new account has %v, want app_user:1", got) |
| + } |
| + if got := sends(release.OpsAccount, "moving", yesterday); len(got) != 0 { |
| + t.Errorf("after a move the old account still has %v", got) |
| + } |
| + |
| + // And a purged app's rows go with it. |
| + tx, err := fx.st.db.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := forgetMailApp(ctx, tx, release.OpsAccount, "docs"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := sends(release.OpsAccount, "docs", longAgo); len(got) != 0 { |
| + t.Errorf("a forgotten app still has %v", got) |
| + } |
| +} |
diff --git a/internal/console/mailevents.go b/internal/console/mailevents.go| index a6b0d65da..db314757f 100644 |
| --- a/internal/console/mailevents.go |
| +++ b/internal/console/mailevents.go |
| @@ -110,7 +110,13 @@ func mailNoticeKey(notice string, ev mail.Event, now time.Time) string { |
| // case in mailAppTimeColumn and carryMailApp below. mail_counts is |
| // deliberately not here: nothing writes it any more and |
| // DropLegacyMailCounts removes it whole. |
| -var mailAppTables = []string{"mail_events", "mail_event_hooks", "mail_event_deliveries", "mail_sender_counts"} |
| +// |
| +// mail_caller_sends joins on the same terms as mail_sender_counts (a day |
| +// string, its own case in mailAppTimeColumn). It has to travel with a |
| +// rename or a move: the switch's reap asks it whether the app-level user |
| +// sent in the last seven days, and history left under the old name would |
| +// answer "no" for an app whose key is still in use. |
| +var mailAppTables = []string{"mail_events", "mail_event_hooks", "mail_event_deliveries", "mail_sender_counts", "mail_caller_sends"} |
| // execer is what carryMailApp and forgetMailApp need from a transaction. |
| type execer interface { |
| @@ -186,15 +192,16 @@ func forgetMailApp(ctx context.Context, tx execer, sqid, app string) error { |
| } |
| // mailAppTimeColumn is the column that says when a row came to be. Most are |
| -// unix seconds; mail_sender_counts keys on a UTC date string, which compares |
| -// correctly against another ISO date and against nothing else. |
| +// unix seconds; mail_sender_counts and mail_caller_sends key on a UTC date |
| +// string, which compares correctly against another ISO date and against |
| +// nothing else. |
| func mailAppTimeColumn(table string) string { |
| switch table { |
| case "mail_events": |
| return "received_at" |
| case "mail_event_hooks": |
| return "set_at" |
| - case "mail_sender_counts": |
| + case "mail_sender_counts", "mail_caller_sends": |
| return "day" |
| } |
| return "created_at" |
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go| index 25d197b67..91ed6d084 100644 |
| --- a/internal/console/sesevents.go |
| +++ b/internal/console/sesevents.go |
| @@ -497,7 +497,12 @@ func (s *Server) recordAndEnforceMail(ctx context.Context, ev mail.Event, notice |
| // shares it, the caller names the one sender that actually sent. The |
| // resolver parses before it reads, so an app enabled before senders |
| // existed still resolves with no index entry of its own. |
| - callerAcct, callerApp, callerSender, named := mail.SenderOfCaller(ctx, s.cfg.Releases, ev.Caller) |
| + // |
| + // The event's account/app/sender tags are passed, and SenderOfCaller |
| + // believes them only when the caller is the box-local mailer's own |
| + // principal (platform mail submission decision 6). From any other |
| + // caller they are ignored: any SMTP-credentialed tenant can set them. |
| + callerAcct, callerApp, callerSender, named := mail.SenderOfCaller(ctx, s.cfg.Releases, ev.Caller, ev.Tags) |
| if named { |
| // The COUNT is gated on the app being live, exactly as the log row |
| // already is (recordMailMessage, sesevents.go:558). A caller name |
| @@ -534,6 +539,18 @@ func (s *Server) recordAndEnforceMail(ctx context.Context, ev mail.Event, notice |
| 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. |
| + 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 _, 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 d26a02233..16bf5ada9 100644 |
| --- a/internal/console/sesevents_test.go |
| +++ b/internal/console/sesevents_test.go |
| @@ -31,6 +31,7 @@ import ( |
| "net/http" |
| "net/http/httptest" |
| "os" |
| + "reflect" |
| "strings" |
| "testing" |
| "time" |
| @@ -832,3 +833,92 @@ func TestRecordAndEnforceMailSkipsAPerInstanceAppInTheDomainFallback(t *testing. |
| t.Errorf("jb-site's log got a row from a per-instance app sender's skipped domain fallback: %+v", got) |
| } |
| } |
| + |
| +// Guard test 8.11 end to end (decision 6): an SMTP-credentialed app's |
| +// event carrying ANOTHER app's account/app/sender tags is counted against |
| +// the caller, and the tagged app is never charged. The same event from the |
| +// mailer's principal is counted against the tagged sender. |
| +func TestRecordAndEnforceChargesCallerNotForgedTag(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + for _, app := range []string{"forger", "victim"} { |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, app, "bill@tito.io", now.Add(-time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + day := now.UTC().Format("2006-01-02") |
| + bounces := func(app string) int { |
| + t.Helper() |
| + c, err := fx.st.MailCounts(ctx, release.OpsAccount, app, "", day) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c.Bounces |
| + } |
| + forged := map[string]string{"account": release.OpsAccount, "app": "victim", "sender": mail.SenderAppID} |
| + |
| + ev := bounceTo("ann@example.com", "m-forged", now) |
| + ev.Caller = mail.UserName(release.OpsAccount, "forger") |
| + ev.Tags = forged |
| + fx.srv.recordAndEnforceMail(ctx, ev, "sns-forged") |
| + if got := bounces("forger"); got != 1 { |
| + t.Errorf("forger bounces = %d, want 1: the caller is charged", got) |
| + } |
| + if got := bounces("victim"); got != 0 { |
| + t.Errorf("victim bounces = %d, want 0: a forged tag charged another app", got) |
| + } |
| + |
| + mailer := bounceTo("bob@example.com", "m-mailer", now) |
| + mailer.Caller = "carlos-mailer-eu-west-1" |
| + mailer.Tags = forged |
| + fx.srv.recordAndEnforceMail(ctx, mailer, "sns-mailer") |
| + if got := bounces("victim"); got != 1 { |
| + t.Errorf("victim bounces = %d after the mailer's event, want 1: the mailer's tags name the sender", got) |
| + } |
| + if got := bounces("forger"); got != 1 { |
| + t.Errorf("forger bounces = %d after the mailer's event, want it unchanged at 1", got) |
| + } |
| +} |
| + |
| +// The caller class is the caller's, never the tag's: an SMTP app's Send |
| +// carrying the mailer's tags for itself is still an app_user send, which is |
| +// what the switch's reap needs to see. A Bounce adds nothing to the |
| +// caller-class counts, and neither does a send that resolves to no app. |
| +func TestCallerClassIgnoresForgedTags(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) |
| + } |
| + 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) { |
| + t.Helper() |
| + ev := mail.Event{Type: typ, Domain: "lgc.li", MessageID: msg, At: now, SentAt: now, Caller: caller, Tags: selfTags} |
| + fx.srv.recordAndEnforceMail(ctx, ev, "sns-"+msg) |
| + } |
| + |
| + 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) |
| + got, err := fx.st.MailCallerSends(ctx, release.OpsAccount, "docs", day) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(got) != 1 || got[mail.CallerClassAppUser] != 1 { |
| + t.Fatalf("caller sends = %v, want {app_user:1}: one app-user Send, classed by its caller whatever its tags say; a Bounce and an unnamed send add nothing", got) |
| + } |
| + |
| + send("carlos-mailer-eu-west-1", "m-mailer", mail.EventSend) |
| + send(mail.StandaloneUserName(release.OpsAccount, "docs", "laptop"), "m-laptop", mail.EventSend) |
| + got, err = fx.st.MailCallerSends(ctx, release.OpsAccount, "docs", day) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[string]int64{mail.CallerClassAppUser: 1, mail.CallerClassMailer: 1, mail.CallerClassOther: 1} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("caller sends = %v, want %v", got, want) |
| + } |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index d14a28835..e97e71d52 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -309,6 +309,23 @@ func (s *Store) migrate() error { |
| rejects INTEGER NOT NULL DEFAULT 0, |
| deliveries INTEGER NOT NULL DEFAULT 0, |
| PRIMARY KEY (account, app, sender, day) |
| +);`, |
| + // Send events per app and UTC day by CALLER CLASS (platform mail |
| + // submission, gap G4): "mailer" (the box-local mailer), "app_user" |
| + // (the app's own app-level IAM user) or "other". mail_sender_counts |
| + // cannot answer it: every class resolves to sender "app". The |
| + // switch's reap reads it to see that the app-level SMTP key has |
| + // stopped being used. The class comes from the caller alone, never |
| + // from a tag (mail.CallerClass). Keyed like mail_sender_counts, by |
| + // the account sqid, with the same day string, and it joins every |
| + // app-keyed mail list beside it (mailAppTables, the store gate). |
| + `CREATE TABLE IF NOT EXISTS mail_caller_sends ( |
| + account TEXT NOT NULL, |
| + app TEXT NOT NULL, |
| + day TEXT NOT NULL, -- UTC YYYY-MM-DD |
| + class TEXT NOT NULL, -- mail.CallerClass: mailer | app_user | other |
| + sends INTEGER NOT NULL DEFAULT 0, |
| + PRIMARY KEY (account, app, day, class) |
| );`, |
| // What happened to each message, per (account, app) — one row per |
| // recipient per SES notification (mailevents.go). The counts above |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index b55cf4e94..b966ed5b9 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -232,6 +232,7 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "pending_confirms": {Account: "account_id", App: "app", Via: &claimSQLVia{Parent: "pending_changes", ChildCol: "change_id", ParentCol: "id"}}, |
| "mail_counts": {Sqid: "account", App: "app"}, |
| "mail_sender_counts": {Sqid: "account", App: "app"}, |
| + "mail_caller_sends": {Sqid: "account", App: "app"}, |
| "mail_events": {Sqid: "account", App: "app"}, |
| "pdf_renders": {Sqid: "account", App: "app"}, |
| "mail_event_hooks": {Sqid: "account", App: "app"}, |
diff --git a/internal/console/store_gate_test.go b/internal/console/store_gate_test.go| index 9bc483331..52689e264 100644 |
| --- a/internal/console/store_gate_test.go |
| +++ b/internal/console/store_gate_test.go |
| @@ -174,6 +174,8 @@ VALUES ('acct7', 'blog', 'n', 'r', 'm', 'Bounce', 1, 1)`) |
| requireDenied(t, "mail_events", err) |
| _, err = s.db.Exec(`INSERT INTO mail_sender_counts (account, app, sender, day) VALUES ('acct7', 'blog', 's', '2026-01-01')`) |
| requireDenied(t, "mail_sender_counts", err) |
| + _, err = s.db.Exec(`INSERT INTO mail_caller_sends (account, app, day, class) VALUES ('acct7', 'blog', '2026-01-01', 'mailer')`) |
| + requireDenied(t, "mail_caller_sends", err) |
| }) |
| t.Run("app-scoped token", func(t *testing.T) { |
| _, err := s.db.Exec(`INSERT INTO cli_tokens (token_hash, address, created_at, expires_at, kind, account_id, app) VALUES ('h1', 'a', 1, 0, 'app', 7, 'blog')`) |
| @@ -718,7 +720,7 @@ func TestClaimSQLTableCensus(t *testing.T) { |
| } |
| } |
| for _, name := range []string{"apps", "owners", "audit", "cli_tokens", "door_keys", "door_key_revisions", "app_policy_revisions", "pending_changes", "pending_confirms", |
| - "mail_counts", "mail_sender_counts", "mail_events", "mail_event_hooks", "mail_event_deliveries"} { |
| + "mail_counts", "mail_sender_counts", "mail_caller_sends", "mail_events", "mail_event_hooks", "mail_event_deliveries"} { |
| if sp, ok := present[name]; !ok || sp.NonApp != "" { |
| t.Errorf("%s must be present and gated", name) |
| } |
diff --git a/internal/mail/events.go b/internal/mail/events.go| index 4fb9b62a7..9316dd7dc 100644 |
| --- a/internal/mail/events.go |
| +++ b/internal/mail/events.go |
| @@ -10,6 +10,8 @@ import ( |
| "time" |
| "unicode" |
| "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/mailwire" |
| ) |
| const ( |
| @@ -39,6 +41,14 @@ type Event struct { |
| // names the one app that actually sent. Empty when SES did not say; |
| // AppOfCaller reads it back. |
| Caller string |
| + // Tags is the first value of each of the mailer's attribution tags |
| + // (mailwire.TagAccount, TagApp, TagSender) in mail.tags, cleaned and |
| + // bounded like every other field, and nil when none is present. ANY |
| + // sender can set these (an X-SES-MESSAGE-TAGS header is honoured when |
| + // the EmailTags parameter is absent, design §9.0), so nothing may |
| + // believe them except SenderOfCaller, and only for the mailer's own |
| + // principal (decision 6). |
| + Tags map[string]string |
| // Destination is who the message was addressed to (mail.destination). |
| Destination []string |
| // Outcomes is what this event says about each recipient it concerns: |
| @@ -240,6 +250,18 @@ func readLogFields(body []byte, eventType string, ev *Event) { |
| if ids := envelope.Mail.Tags["ses:caller-identity"]; len(ids) > 0 { |
| ev.Caller = cleanField(ids[0], maxDiagnosticLen) |
| } |
| + for _, name := range []string{mailwire.TagAccount, mailwire.TagApp, mailwire.TagSender} { |
| + vs := envelope.Mail.Tags[name] |
| + if len(vs) == 0 { |
| + continue |
| + } |
| + if v := cleanField(vs[0], maxDiagnosticLen); v != "" { |
| + if ev.Tags == nil { |
| + ev.Tags = map[string]string{} |
| + } |
| + ev.Tags[name] = v |
| + } |
| + } |
| for _, to := range envelope.Mail.Destination { |
| if to = cleanField(to, maxAddressLen); to != "" { |
| ev.Destination = append(ev.Destination, to) |
diff --git a/internal/mail/events_test.go b/internal/mail/events_test.go| index 34143db3e..3d80c32a5 100644 |
| --- a/internal/mail/events_test.go |
| +++ b/internal/mail/events_test.go |
| @@ -411,3 +411,62 @@ func TestAPerRecipientEventThatNamesNobodyIsNotWidened(t *testing.T) { |
| t.Errorf("a bounce naming nobody was widened to %+v", rs) |
| } |
| } |
| + |
| +// §9.0: the mailer's EmailTags arrive in mail.tags on Send, Delivery, Bounce |
| +// and Complaint, beside SES's own ses:* tags. Event.Tags keeps the first |
| +// value of exactly the three attribution tags, cleaned and cut like every |
| +// other field; it is nil when none is present. |
| +func TestParseEventKeepsTags(t *testing.T) { |
| + long := strings.Repeat("a", maxDiagnosticLen+50) |
| + body := []byte(`{ |
| + "eventType": "Bounce", |
| + "mail": { |
| + "timestamp": "2026-11-13T08:00:00.000Z", |
| + "source": "noreply@docs.bds.oncarlos.com", |
| + "messageId": "m-1", |
| + "tags": { |
| + "ses:caller-identity": ["carlos-mailer-eu-west-1"], |
| + "ses:operation": ["SendRawEmail"], |
| + "account": ["bds", "second"], |
| + "app": ["docs\u0007"], |
| + "sender": ["` + long + `"], |
| + "forged": ["yes"] |
| + } |
| + }, |
| + "bounce": {"bounceType": "Permanent", "bouncedRecipients": [{"emailAddress": "bounce@simulator.amazonses.com"}]} |
| +}`) |
| + ev, err := ParseEvent(body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ev.Caller != "carlos-mailer-eu-west-1" { |
| + t.Fatalf("Caller = %q", ev.Caller) |
| + } |
| + if len(ev.Tags) != 3 { |
| + t.Fatalf("Tags = %#v, want exactly account, app and sender", ev.Tags) |
| + } |
| + if ev.Tags["account"] != "bds" { |
| + t.Errorf("account = %q, want the first value", ev.Tags["account"]) |
| + } |
| + // cleanField replaces a control character rather than keeping it; the |
| + // result is not a valid app name, so SenderOfCaller refuses it. |
| + if ev.Tags["app"] != "docs " { |
| + t.Errorf("app = %q, want the control character replaced", ev.Tags["app"]) |
| + } |
| + if got := ev.Tags["sender"]; len(got) != maxDiagnosticLen { |
| + t.Errorf("sender is %d bytes, want it cut to %d", len(got), maxDiagnosticLen) |
| + } |
| + for _, k := range []string{"forged", "ses:caller-identity", "ses:operation"} { |
| + if _, ok := ev.Tags[k]; ok { |
| + t.Errorf("Tags kept %q", k) |
| + } |
| + } |
| + |
| + plain, err := ParseEvent([]byte(`{"eventType":"Send","mail":{"source":"a@lgc.li","tags":{"ses:caller-identity":["carlos-mail-beb-jb-book"]}}}`)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if plain.Tags != nil { |
| + t.Fatalf("an event with no attribution tags has Tags %#v, want nil", plain.Tags) |
| + } |
| +} |
diff --git a/internal/mail/sender.go b/internal/mail/sender.go| index c5992eedd..9c1a69359 100644 |
| --- a/internal/mail/sender.go |
| +++ b/internal/mail/sender.go |
| @@ -23,6 +23,7 @@ import ( |
| "os" |
| "regexp" |
| "strings" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/mailwire" |
| @@ -480,6 +481,18 @@ func claimUnserializedResolveSenderNames(ctx context.Context, s release.Store, a |
| // SenderOfCaller resolves the IAM identity SES stamps on an event |
| // (mail.tags["ses:caller-identity"]) to the sender that owns it. |
| // |
| +// 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. |
| +// 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 |
| +// complaints to another app. For every other caller, tags is never read and |
| +// the resolution below is unchanged. |
| +// |
| // PARSE FIRST, in two steps, and the order is load-bearing. AppOfCaller |
| // answers for carlos-mail-<acct>-<app> and its +s+ standalones, which is |
| // every sender that exists today, and it costs nothing. Only a slugged +i+ |
| @@ -491,7 +504,16 @@ func claimUnserializedResolveSenderNames(ctx context.Context, s release.Store, a |
| // |
| // An unreadable index entry is logged and answers "unknown", which puts the |
| // event back on the domain-wide fallback rather than dropping it. |
| -func SenderOfCaller(ctx context.Context, s release.Store, caller string) (string, string, string, bool) { |
| +func SenderOfCaller(ctx context.Context, s release.Store, caller string, tags map[string]string) (string, string, string, bool) { |
| + // Decision 6's guard. Nothing above it, and nothing below it reads tags. |
| + if mailwire.IsMailerCaller(caller) { |
| + acct, app, sender := tags[mailwire.TagAccount], tags[mailwire.TagApp], tags[mailwire.TagSender] |
| + if release.ValidAccount(acct) && release.ValidApp(app) && ValidSenderID(sender) { |
| + return acct, app, sender, true |
| + } |
| + logMailerUntagged(caller, time.Now()) |
| + return "", "", "", false |
| + } |
| if acct, app, ok := AppOfCaller(caller); ok { |
| return acct, app, SenderAppID, true |
| } |
| @@ -516,6 +538,88 @@ func SenderOfCaller(ctx context.Context, s release.Store, caller string) (string |
| return idx.Account, idx.App, idx.Sender, true |
| } |
| +// mailerUntagged rate-limits the one log line a mailer event without valid |
| +// tags earns: once per caller per minute. The mailer always tags its sends, |
| +// so the line means something is wrong with the mailer or with SES, and a |
| +// burst of events must not flood the log with it. |
| +var mailerUntagged struct { |
| + sync.Mutex |
| + last map[string]time.Time |
| +} |
| + |
| +func logMailerUntagged(caller string, now time.Time) { |
| + mailerUntagged.Lock() |
| + if mailerUntagged.last == nil { |
| + mailerUntagged.last = map[string]time.Time{} |
| + } |
| + if at, ok := mailerUntagged.last[caller]; ok && now.Sub(at) < time.Minute { |
| + mailerUntagged.Unlock() |
| + return |
| + } |
| + // Keep the map to the callers seen in the last minute. |
| + for c, at := range mailerUntagged.last { |
| + if now.Sub(at) >= time.Minute { |
| + delete(mailerUntagged.last, c) |
| + } |
| + } |
| + mailerUntagged.last[caller] = now |
| + mailerUntagged.Unlock() |
| + log.Printf("mail: mailer event without valid tags from %s; not attributed by tag", caller) |
| +} |
| + |
| +// The caller classes of a Send event (CallerClass), counted per app and day |
| +// in the console's mail_caller_sends. |
| +const ( |
| + CallerClassMailer = "mailer" |
| + CallerClassAppUser = "app_user" |
| + CallerClassOther = "other" |
| +) |
| + |
| +// CallerClass classifies the IAM identity that sent a message, for the app |
| +// the event was resolved to. It is decided from the caller alone, never from |
| +// tags: a forged tag can name an app, but it can neither hide an app-level |
| +// user's send nor pass one off as the mailer's. |
| +// |
| +// - "mailer": the box-local mailer (mailwire.IsMailerCaller); |
| +// - "app_user": the app's own app-level IAM user, UserName(acct, app) |
| +// exactly, by bare name or by an IAM user ARN's last segment; |
| +// - "other": everything else, including +s+ standalones, +e+ owned |
| +// environment users and callers CARLOS never minted. |
| +func CallerClass(acct, app, caller string) string { |
| + if mailwire.IsMailerCaller(caller) { |
| + return CallerClassMailer |
| + } |
| + if !release.ValidAccount(acct) || !release.ValidApp(app) { |
| + return CallerClassOther |
| + } |
| + if name, ok := callerUserName(caller); ok && name == UserName(acct, app) { |
| + return CallerClassAppUser |
| + } |
| + return CallerClassOther |
| +} |
| + |
| +// callerUserName is the IAM user name a caller identity names: the bare |
| +// name itself, or an IAM USER ARN's last path segment, by AppOfCaller's |
| +// rule. Anything else (an assumed-role ARN, a path without an ARN) names no |
| +// user. |
| +func callerUserName(caller string) (string, bool) { |
| + if strings.HasPrefix(caller, "arn:") { |
| + i := strings.Index(caller, ":user/") |
| + if i < 0 || !strings.HasPrefix(caller, "arn:aws") || strings.Count(caller[:i], ":") != 4 { |
| + return "", false |
| + } |
| + name := caller[i+len(":user/"):] |
| + if j := strings.LastIndex(name, "/"); j >= 0 { |
| + name = name[j+1:] |
| + } |
| + return name, true |
| + } |
| + if strings.Contains(caller, "/") { |
| + return "", false |
| + } |
| + return caller, true |
| +} |
| + |
| func PutCallerIndex(ctx context.Context, s release.Store, iamUser, acct, app, sender string, now time.Time) error { |
| if _, enabled := s.(ClaimMailStore); !enabled { |
| return claimUnserializedPutCallerIndex(ctx, s, iamUser, acct, app, sender, now) |
diff --git a/internal/mail/sender_test.go b/internal/mail/sender_test.go| index 90c90c26d..92759884d 100644 |
| --- a/internal/mail/sender_test.go |
| +++ b/internal/mail/sender_test.go |
| @@ -265,7 +265,7 @@ func TestSenderOfCallerParsesBeforeItReads(t *testing.T) { |
| StandaloneUserName("bag", "harbourmail", "laptop"), |
| "arn:aws:iam::123456789012:user/carlos-mail/carlos-mail-bag-harbourmail", |
| } { |
| - acct, app, sender, ok := SenderOfCaller(ctx, s, caller) |
| + acct, app, sender, ok := SenderOfCaller(ctx, s, caller, nil) |
| if !ok || acct != "bag" || app != "harbourmail" || sender != SenderAppID { |
| t.Errorf("SenderOfCaller(%q) = %q %q %q %v", caller, acct, app, sender, ok) |
| } |
| @@ -273,7 +273,7 @@ func TestSenderOfCallerParsesBeforeItReads(t *testing.T) { |
| // A name nobody CARLOS minted stays unknown, and costs no read. |
| for _, caller := range []string{"", "someone-else", "carlos-mail-bag-harbourmail+s+"} { |
| - if _, _, _, ok := SenderOfCaller(ctx, s, caller); ok { |
| + if _, _, _, ok := SenderOfCaller(ctx, s, caller, nil); ok { |
| t.Errorf("SenderOfCaller(%q) claimed to know it", caller) |
| } |
| } |
| @@ -283,13 +283,13 @@ func TestSenderOfCallerParsesBeforeItReads(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if _, _, _, ok := SenderOfCaller(ctx, s, names.IAMUser); ok { |
| + if _, _, _, ok := SenderOfCaller(ctx, s, names.IAMUser, nil); ok { |
| t.Fatal("a slugged name resolved before it was ever indexed") |
| } |
| if err := PutCallerIndex(ctx, s, names.IAMUser, "bag", "harbourmail", "book.example.com", now); err != nil { |
| t.Fatal(err) |
| } |
| - acct, app, sender, ok := SenderOfCaller(ctx, s, names.IAMUser) |
| + acct, app, sender, ok := SenderOfCaller(ctx, s, names.IAMUser, nil) |
| if !ok || acct != "bag" || app != "harbourmail" || sender != "book.example.com" { |
| t.Fatalf("SenderOfCaller(slug) = %q %q %q %v", acct, app, sender, ok) |
| } |
| @@ -512,3 +512,111 @@ func TestAdditiveSenderShape(t *testing.T) { |
| t.Fatalf("old shape lost the record: %+v", old) |
| } |
| } |
| + |
| +// GUARD TEST 8.11 (decision 6): a tag is believed only from the mailer's |
| +// own principal. Any SMTP-credentialed tenant can set account/app/sender |
| +// tags with an X-SES-MESSAGE-TAGS header, and §9.0 confirmed SES honours it, |
| +// so a tag from any other caller must change nothing. Every row names the |
| +// tags it carries; only the mailer rows may answer with them. |
| +func TestTagsBelievedOnlyFromMailer(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + now := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| + |
| + // An owned environment's budgeted (hashed) name resolves through the |
| + // caller index alone. |
| + envUser := EnvironmentUserName("abc", "docs", strings.Repeat("t", 60)) |
| + if !strings.Contains(envUser, "+e+") || strings.HasPrefix(envUser, UserName("abc", "docs")) { |
| + t.Fatalf("expected a hashed environment name, got %q", envUser) |
| + } |
| + if err := PutCallerIndex(ctx, s, envUser, "abc", "docs", SenderAppID, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + victim := map[string]string{"account": "xyz", "app": "sheets", "sender": SenderAppID} |
| + mailerTags := map[string]string{"account": "xyz", "app": "sheets", "sender": SenderAppID} |
| + type want struct { |
| + acct, app, sender string |
| + ok bool |
| + } |
| + for _, c := range []struct { |
| + name string |
| + caller string |
| + tags map[string]string |
| + want want |
| + }{ |
| + {"an app user's forged tags are ignored", "carlos-mail-abc-docs", victim, want{"abc", "docs", SenderAppID, true}}, |
| + {"an app user's ARN with forged tags", "arn:aws:iam::123456789012:user/carlos-mail/carlos-mail-abc-docs", victim, want{"abc", "docs", SenderAppID, true}}, |
| + {"a standalone's forged tags are ignored", StandaloneUserName("abc", "docs", "laptop"), victim, want{"abc", "docs", SenderAppID, true}}, |
| + {"an indexed environment user's forged tags are ignored", envUser, victim, want{"abc", "docs", SenderAppID, true}}, |
| + {"the mailer's valid tags", "carlos-mailer-eu-west-1", mailerTags, want{"xyz", "sheets", SenderAppID, true}}, |
| + {"the mailer's user ARN with valid tags", "arn:aws:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1", mailerTags, want{"xyz", "sheets", SenderAppID, true}}, |
| + {"the mailer with no tags", "carlos-mailer-eu-west-1", nil, want{}}, |
| + {"the mailer with a tag missing", "carlos-mailer-eu-west-1", map[string]string{"account": "xyz", "app": "sheets"}, want{}}, |
| + {"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{}}, |
| + {"someone else with tags", "someone-else", mailerTags, want{}}, |
| + {"no caller with tags", "", mailerTags, want{}}, |
| + } { |
| + acct, app, sender, ok := SenderOfCaller(ctx, s, c.caller, c.tags) |
| + if got := (want{acct, app, sender, ok}); got != c.want { |
| + t.Errorf("%s: SenderOfCaller(%q, %v) = %+v, want %+v", c.name, c.caller, c.tags, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// The mailer's name never parses as an app user's: carlos-mailer-… does |
| +// not start with carlos-mail- followed by an account (the character after |
| +// "mail" is "e", not "-"), so the prefix cut fails before any account is |
| +// read. And the converse: no app user's name is the mailer's. |
| +func TestMailerNameNeverParsesAsApp(t *testing.T) { |
| + for _, caller := range []string{ |
| + "carlos-mailer-eu-west-1", |
| + mailwire.MailerUserName("us-east-1"), |
| + "arn:aws:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1", |
| + } { |
| + if acct, app, ok := AppOfCaller(caller); ok { |
| + t.Errorf("AppOfCaller(%q) = %q %q, want no app", caller, acct, app) |
| + } |
| + } |
| + for _, acct := range []string{"a", "abc", "bds", "zzzzzzzz"} { |
| + for _, app := range []string{"docs", "er", "er-eu-west-1", "mailer", "x-1"} { |
| + if !release.ValidAccount(acct) || !release.ValidApp(app) { |
| + continue |
| + } |
| + for _, name := range []string{UserName(acct, app), StandaloneUserName(acct, app, "laptop"), EnvironmentUserName(acct, app, "team")} { |
| + if mailwire.IsMailerCaller(name) { |
| + t.Errorf("IsMailerCaller(%q) for app %s/%s", name, acct, app) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// The caller class is the caller's, for the app the event resolved to. |
| +func TestCallerClass(t *testing.T) { |
| + for _, c := range []struct { |
| + acct, app, caller, want string |
| + }{ |
| + {"abc", "docs", "carlos-mailer-eu-west-1", CallerClassMailer}, |
| + {"abc", "docs", "arn:aws:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1", CallerClassMailer}, |
| + {"abc", "docs", "carlos-mail-abc-docs", CallerClassAppUser}, |
| + {"abc", "docs", "arn:aws:iam::123456789012:user/carlos-mail/carlos-mail-abc-docs", CallerClassAppUser}, |
| + {"abc", "sheets", "carlos-mail-abc-docs", CallerClassOther}, |
| + {"abc", "docs", StandaloneUserName("abc", "docs", "laptop"), CallerClassOther}, |
| + {"abc", "docs", EnvironmentUserName("abc", "docs", "team"), CallerClassOther}, |
| + {"abc", "docs", "arn:aws:sts::123456789012:assumed-role/x/carlos-mail-abc-docs", CallerClassOther}, |
| + {"abc", "docs", "arn:aws:sts::123456789012:assumed-role/x/carlos-mailer-eu-west-1", CallerClassOther}, |
| + {"abc", "docs", "someone-else", CallerClassOther}, |
| + {"abc", "docs", "", CallerClassOther}, |
| + {"", "", "carlos-mail--", CallerClassOther}, |
| + } { |
| + if got := CallerClass(c.acct, c.app, c.caller); got != c.want { |
| + t.Errorf("CallerClass(%q, %q, %q) = %q, want %q", c.acct, c.app, c.caller, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/internal/mail/walk_environment_test.go b/internal/mail/walk_environment_test.go| index cf275482b..c9c9be7bf 100644 |
| --- a/internal/mail/walk_environment_test.go |
| +++ b/internal/mail/walk_environment_test.go |
| @@ -234,14 +234,14 @@ func TestEnvironmentUserNameFitsIAMAtTheMaxima(t *testing.T) { |
| ctx := context.Background() |
| s := release.NewDirStore(t.TempDir()) |
| name := EnvironmentUserName(acct, app, "team") |
| - if _, _, _, ok := SenderOfCaller(ctx, s, name); ok { |
| + if _, _, _, ok := SenderOfCaller(ctx, s, name, nil); ok { |
| t.Fatal("an unindexed budgeted name resolved") |
| } |
| if err := PutCallerIndex(ctx, s, name, acct, app, SenderAppID, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| for _, caller := range []string{name, "arn:aws:iam::123456789012:user/carlos-mail/" + name} { |
| - gotAcct, gotApp, sender, ok := SenderOfCaller(ctx, s, caller) |
| + gotAcct, gotApp, sender, ok := SenderOfCaller(ctx, s, caller, nil) |
| if !ok || gotAcct != acct || gotApp != app || sender != SenderAppID { |
| t.Errorf("SenderOfCaller(%q) = %q, %q, %q, %v", caller, gotAcct, gotApp, sender, ok) |
| } |
diff --git a/internal/mailwire/mailwire.go b/internal/mailwire/mailwire.go| index 12b459e31..38a22529e 100644 |
| --- a/internal/mailwire/mailwire.go |
| +++ b/internal/mailwire/mailwire.go |
| @@ -9,7 +9,10 @@ |
| // internal/mail defines its constants from these so there is one definition. |
| package mailwire |
| -import "time" |
| +import ( |
| + "regexp" |
| + "time" |
| +) |
| // The pause kinds (decision 8, kept from internal/mail's Provisioned.PauseKind). |
| // A manual (operator) pause carries the empty kind. |
| @@ -118,3 +121,38 @@ func SenderKey(acct, app, id string) string { |
| func DomainKey(acct, domain string) string { |
| return "accounts/" + acct + "/email/domains/" + domain + ".json" |
| } |
| + |
| +// The SES EmailTags the mailer puts on every send (decision 6). The console |
| +// believes them only from the mailer's own principal (IsMailerCaller). |
| +const ( |
| + TagAccount = "account" |
| + TagApp = "app" |
| + TagSender = "sender" |
| +) |
| + |
| +// The mailer's IAM user: one per region, carlos-mailer-<region>, under its |
| +// own path. The path is outside the console's /carlos-mail/ (internal/mail's |
| +// UserPath), so no console sweep or reap can ever reach it. |
| +const ( |
| + MailerUserPath = "/carlos-mailer/" |
| + MailerUserPrefix = "carlos-mailer-" |
| +) |
| + |
| +// MailerUserName is the mailer's IAM user name in one region. |
| +func MailerUserName(region string) string { return MailerUserPrefix + region } |
| + |
| +var ( |
| + mailerBareRe = regexp.MustCompile(`^carlos-mailer-[a-z0-9-]{1,48}$`) |
| + mailerARNRe = regexp.MustCompile(`^arn:aws:iam::[0-9]{12}:user/carlos-mailer/(carlos-mailer-[a-z0-9-]{1,48})$`) |
| +) |
| + |
| +// 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 |
| +// asks before a tag is believed. |
| +func IsMailerCaller(caller string) bool { |
| + return mailerBareRe.MatchString(caller) || mailerARNRe.MatchString(caller) |
| +} |
diff --git a/internal/mailwire/mailwire_test.go b/internal/mailwire/mailwire_test.go| index 8891d785f..dc69ff6e2 100644 |
| --- a/internal/mailwire/mailwire_test.go |
| +++ b/internal/mailwire/mailwire_test.go |
| @@ -71,3 +71,36 @@ func TestEffectivePauseLegacyRecordView(t *testing.T) { |
| t.Fatal("a nil view is paused") |
| } |
| } |
| + |
| +// The mailer's principal, by bare name and by user ARN under its own path, |
| +// and nothing else. |
| +func TestIsMailerCaller(t *testing.T) { |
| + if got := MailerUserName("eu-west-1"); got != "carlos-mailer-eu-west-1" { |
| + t.Fatalf("MailerUserName = %q", got) |
| + } |
| + for caller, want := range map[string]bool{ |
| + "carlos-mailer-eu-west-1": true, |
| + "carlos-mailer-us-east-1": true, |
| + "arn:aws:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1": true, |
| + "carlos-mailer-": false, |
| + "carlos-mailer-EU-WEST-1": false, |
| + "carlos-mailer-eu_west_1": false, |
| + "carlos-mailer-" + "a123456789012345678901234567890123456789012345678": false, // 49 characters after the prefix |
| + "carlos-mail-abc-docs": false, |
| + "x-carlos-mailer-eu-west-1": false, |
| + "carlos-mailer-eu-west-1/x": false, |
| + "arn:aws:sts::123456789012:assumed-role/x/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::123456789012:user/carlos-mail/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::123456789012:user/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::123456789012:user/carlos-mailer/x/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::12345678901:user/carlos-mailer/carlos-mailer-eu-west-1": false, |
| + "arn:aws-cn:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::123456789012:role/carlos-mailer/carlos-mailer-eu-west-1": false, |
| + "arn:aws:iam::123456789012:user/carlos-mailer/carlos-mailer-eu-west-1\n": false, |
| + "": false, |
| + } { |
| + if got := IsMailerCaller(caller); got != want { |
| + t.Errorf("IsMailerCaller(%q) = %v, want %v", caller, got, want) |
| + } |
| + } |
| +} |