mailer: Task 5 review fixes (Fable P1-1, P2-1..P2-3, P3s)
P1-1: one strict header-block validator (headerBlock) ahead of both the
From check and the stripping, so the mailer and SES cannot read
different fields. A block is refused 400 when it has a bare CR, a NUL or
any other control byte or DEL (a tab only as whitespace in a value or a
continuation), or a line that is neither a continuation nor a printable
field name immediately followed by ":" ("From :", "From\t:", a leading
continuation, no colon). The reviewer's cases, and more, are in
TestHygieneStripsHeaders, TestOneFromRefusesMalformedHeaderBlocks and
TestMailerPolicyRefusesBeforeSES.
P1-1 (§9.0): every send names ConfigurationSetName. A domain with no set
in the mail region is refused 403 FROM_NOT_ALLOWED, with a log line,
rather than sent through the account's set: a verified identity has no
set only on a deployment with no SNS topic, where the account's set does
not exist and a send through it fails outright. The follow-up list says
Task 6's door should refuse such a deployment up front.
P2-1: the cap slot is released only on a definite SES refusal (an API
error); a cancelled, timed-out or lost call keeps it.
P2-2: only S3's AccessDenied code reads as absent. Any other 403, and a
credential error from S3 or SES (InvalidAccessKeyId,
SignatureDoesNotMatch, RequestTimeTooSkewed, ExpiredToken and kin), is
503, and a credential error fails health until a call succeeds.
P2-3: one sender holds at most two of the box's four in-flight sends;
the next is 429 RATE, Retry-After 1.
P3: the unit sets GOMEMLIMIT=288MiB with MemoryHigh=320M and
MemoryMax=384M (four 10 MiB sends peak near 190 MiB live); the domain
body-versus-key check is pinned; SES gets the parsed recipient
addresses; the rate token is taken before the cap's fsynced write and
refunded on a cap refusal; the key-load ALERT is logged at most once a
minute.
Census: claims updated, overlay re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+547
−95
docs/superpowers/notes/census-claims-platform-mail-submission.tsv+1 −1docs/superpowers/notes/census-proposal-platform-mail-submission.md+1 −1docs/superpowers/plans/2026-11-13-platform-mail-submission.md+3 −0internal/host/units/carlos-mailer.service+5 −2internal/host/units_isolation_test.go+3 −1internal/mailer/harness_test.go+35 −0internal/mailer/hygiene.go+66 −11internal/mailer/hygiene_test.go+49 −2internal/mailer/policy.go+40 −20internal/mailer/rate.go+10 −0internal/mailer/send.go+97 −20internal/mailer/send_test.go+161 −20internal/mailer/ses.go+30 −5internal/mailer/store.go+41 −7internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv+4 −4
CI failed — run details
diff --git a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv| index 42fe13fa6..6c297a21e 100644 |
| --- a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| +++ b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| @@ -27,7 +27,7 @@ internal/host/units/carlos-instance-tty@.service:external Task 3: InaccessiblePa |
| internal/host/units/carlos-instance@.service:external Task 3: InaccessiblePaths= gains -/run/carlos-mailer -/etc/carlos-mailer (optional). Only hides more; no read added. |
| internal/host/units/carlos-mailer-arm.path:external Task 3, new: [Path] PathExists=/etc/carlos-mailer/keys, Unit=carlos-mailer.socket, WantedBy=multi-user.target; enabled and armed by bootstrap like every .path. PID 1 watches a path in a root-owned 0750 root:carlos-mailer directory only root (the operator) writes; it starts a socket unit and reads nothing. |
| internal/host/units/carlos-mailer.socket:external Task 3, new: ConditionPathExists=/etc/carlos-mailer/keys, ListenStream=/run/carlos-mailer/mailer.sock, SocketUser=carlos, SocketGroup=carlos, SocketMode=0600, Accept=no; not enabled, started only by the arming path. PID 1 binds a socket in a root-owned directory, as carlos-instance-control.socket does in /run/carlos-control. No read added. |
| -internal/host/units/carlos-mailer.service:external Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths. No root process reads anything new; the mailer reads its own key file and state. |
| +internal/host/units/carlos-mailer.service:external Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths; Environment=GOMEMLIMIT=288MiB with MemoryHigh=320M and MemoryMax=384M for four 10 MiB sends (review round 1, Task 5 P3). No root process reads anything new; the mailer reads its own key file and state. |
| internal/status/snapshot.go:CollectBox Task 3: copies Probes.MailerArmed into BoxMetrics.MailerArmed (json mailer_armed, omitempty; private, like Layout) and counts it in the condition that builds Metrics; the same 28 sites, no read added. |
| # |
| # Task 4 (the verb at both bind sites, CARLOS_MAIL agent-owned). |
diff --git a/docs/superpowers/notes/census-proposal-platform-mail-submission.md b/docs/superpowers/notes/census-proposal-platform-mail-submission.md| index 6751dbaf5..a9359af23 100644 |
| --- a/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| +++ b/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| @@ -72,6 +72,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/mailsubmit/forward.go:SocketForwarder.Send`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| - new `internal/mailsubmit/verb.go:Mount`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen |
| -Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `48a56f8c1dabee1185118dfba64782556ebd0e57189273ec3e5ea343234e16da`. |
| +Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `72c38da53c18da24c7ba8b4d11f0b7d48f52b133674291683315c163fe57d603`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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 3118fc3f7..fd9948415 100644 |
| --- a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| +++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| @@ -627,3 +627,6 @@ Out of scope, so no card: `internal/mail` and `internal/console` (both outside ` |
| - 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. |
| +- (Build, Task 3 review P3) An environment *allowlist* for `carlos-mailer.service`. systemd cannot express one over `EnvironmentFile=`, so the unit unsets every credential a `host.env` may carry by name instead (`TestMailerUnitShape` pins the list). An allowlist would need the mailer to be handed a file of its own. |
| +- (Build, Task 5 review P1-1) A mailer send always names a configuration set, and a domain with none is refused (`403 FROM_NOT_ALLOWED`). A verified identity has no set only on a deployment with no SNS topic, where the account's set does not exist either. So **a deployment without event ingest cannot use submission**: Task 6's switch door should refuse it up front, with that reason, rather than let every send be refused. |
| +- (Build) `carlos system apply` restarts the relay and instance-control after a binary update, but not `carlos-mailer.service`, which keeps running the old binary until it exits. Root's hourly `ensureSystemUnits` does not install the mailer units either. The isolation probe does not yet check that `/run/carlos-mailer` is unreachable from an instance. |
diff --git a/internal/host/units/carlos-mailer.service b/internal/host/units/carlos-mailer.service| index 8658de588..b5cf1b67b 100644 |
| --- a/internal/host/units/carlos-mailer.service |
| +++ b/internal/host/units/carlos-mailer.service |
| @@ -62,5 +62,8 @@ MemoryDenyWriteExecute=yes |
| SystemCallFilter=@system-service |
| SystemCallErrorNumber=EPERM |
| SystemCallArchitectures=native |
| -MemoryHigh=160M |
| -MemoryMax=256M |
| +# Four 10 MiB sends peak near 190 MiB live (internal/mailer maxInFlight); |
| +# GOMEMLIMIT makes the collector work hard well before MemoryHigh. |
| +Environment=GOMEMLIMIT=288MiB |
| +MemoryHigh=320M |
| +MemoryMax=384M |
diff --git a/internal/host/units_isolation_test.go b/internal/host/units_isolation_test.go| index 3d12a5581..fff9b54a5 100644 |
| --- a/internal/host/units_isolation_test.go |
| +++ b/internal/host/units_isolation_test.go |
| @@ -753,7 +753,9 @@ func TestMailerUnitShape(t *testing.T) { |
| "RestrictSUIDSGID=yes", |
| "MemoryDenyWriteExecute=yes", |
| "SystemCallFilter=@system-service", |
| - "MemoryMax=256M", |
| + "Environment=GOMEMLIMIT=288MiB", |
| + "MemoryHigh=320M", |
| + "MemoryMax=384M", |
| } { |
| if !slices.Contains(svc, want) { |
| t.Errorf("carlos-mailer.service lacks %q", want) |
diff --git a/internal/mailer/harness_test.go b/internal/mailer/harness_test.go| index 947b73c4c..1ec083785 100644 |
| --- a/internal/mailer/harness_test.go |
| +++ b/internal/mailer/harness_test.go |
| @@ -255,3 +255,38 @@ func (h *harness) want(got sent, status int, code string) { |
| h.t.Fatalf("got %d %+v (Retry-After %q), want %d %s", got.status, got.ans, got.retryAfter, status, code) |
| } |
| } |
| + |
| +// addApp puts a route on this box and a switched app sender for app, at |
| +// host. The harness's domain record must list the app. |
| +func (h *harness) addApp(app, host string) { |
| + h.t.Helper() |
| + rec := defaultRecord() |
| + rec.App, rec.Host = app, host |
| + putJSON(h.t, h.store, provision.RecordKey(tAcct, app, host), rec) |
| + putJSON(h.t, h.store, mailwire.SenderKey(tAcct, app, mailwire.SenderAppID), defaultSender()) |
| +} |
| + |
| +// forApp is a request mutator sending as app from host. |
| +func forApp(app, host string) func(*mailsubmit.SendRequest) { |
| + return func(r *mailsubmit.SendRequest) { r.App, r.Host = app, host } |
| +} |
| + |
| +// sendWithin is send for a request that must be answered at once (a |
| +// refusal at a limit): if it is still waiting after 3 s it was let through |
| +// to a blocked SES, and the test fails rather than hangs. |
| +func (h *harness) sendWithin(req mailsubmit.SendRequest) sent { |
| + h.t.Helper() |
| + done := make(chan sent, 1) |
| + go func() { done <- h.send(req) }() |
| + select { |
| + case got := <-done: |
| + return got |
| + case <-time.After(3 * time.Second): |
| + if h.ses.block != nil { |
| + close(h.ses.block) |
| + h.ses.block = nil |
| + } |
| + h.t.Fatal("a send that should have been refused at once reached SES") |
| + return sent{} |
| + } |
| +} |
diff --git a/internal/mailer/hygiene.go b/internal/mailer/hygiene.go| index 20ed5e8da..cb84cece9 100644 |
| --- a/internal/mailer/hygiene.go |
| +++ b/internal/mailer/hygiene.go |
| @@ -28,6 +28,62 @@ func splitHeader(raw []byte) (header, body []byte, ok bool) { |
| return nil, nil, false |
| } |
| +// errHeaderSyntax is a header block the mailer will not interpret: one |
| +// that SES might read differently from the mailer's own checks. |
| +var errHeaderSyntax = errors.New("mailer: malformed header block") |
| + |
| +// headerBlock is raw's header block, split from the body and checked |
| +// strictly (review round 1, Task 5 P1-1). It is the one parse both the From |
| +// check (oneFrom) and the header hygiene (StripHeaders) read, so the two, |
| +// and SES after them, cannot disagree about which fields a message has. |
| +// |
| +// A header block is refused when it has: |
| +// - a bare CR (one not immediately before LF): a reader that splits on CR |
| +// would see fields this one does not; |
| +// - a NUL or any other control byte, or DEL; a tab is allowed only as |
| +// whitespace in a field's value or a continuation; |
| +// - a line that is neither a continuation (leading space or tab, never |
| +// the first line) nor a field name of printable ASCII (RFC 5322 ftext, |
| +// 33-126 without the colon) immediately followed by ":". So "From :" |
| +// and "From\t:", which a lenient reader takes as From and net/mail |
| +// keys as "From ", are refused rather than guessed at. |
| +func headerBlock(raw []byte) ([]byte, error) { |
| + header, _, ok := splitHeader(raw) |
| + if !ok { |
| + return nil, errNoSeparator |
| + } |
| + first := true |
| + for i := 0; i < len(header); { |
| + j := bytes.IndexByte(header[i:], '\n') |
| + line := bytes.TrimSuffix(header[i:i+j], []byte{'\r'}) |
| + i += j + 1 |
| + value := line |
| + if line[0] == ' ' || line[0] == '\t' { |
| + if first { |
| + return nil, errHeaderSyntax |
| + } |
| + } else { |
| + c := bytes.IndexByte(line, ':') |
| + if c <= 0 { |
| + return nil, errHeaderSyntax |
| + } |
| + for _, b := range line[:c] { |
| + if b < 33 || b > 126 { |
| + return nil, errHeaderSyntax |
| + } |
| + } |
| + value = line[c+1:] |
| + } |
| + for _, b := range value { |
| + if (b < 0x20 && b != '\t') || b == 0x7f { |
| + return nil, errHeaderSyntax |
| + } |
| + } |
| + first = false |
| + } |
| + return header, nil |
| +} |
| + |
| // strippedField reports whether a header field of this name never reaches |
| // SES (design §5, Header hygiene): Bcc, and every X-SES-* field. SMTP |
| // honours X-SES-TENANT, X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS, and |
| @@ -39,16 +95,16 @@ func strippedField(name string) bool { |
| } |
| // StripHeaders removes every header field named Bcc or starting X-SES-, |
| -// case-insensitively, together with its folded continuation lines. A |
| -// field's name is what precedes its colon, with any whitespace before the |
| -// colon ignored (RFC 5322's obsolete syntax allows it, and a reader that |
| -// honours "Bcc :" must not see one). Only the header block is touched: the |
| -// body, and the line separating it, are returned byte for byte, and so is |
| -// every other header line. A message with no separator is an error. |
| +// case-insensitively, together with its folded continuation lines. Only |
| +// the header block is touched: the body, and the line separating it, are |
| +// returned byte for byte, and so is every other header line. A message |
| +// with no separator, or one whose header block headerBlock refuses, is an |
| +// error: there is no field name with whitespace before its colon left to |
| +// guess at. |
| func StripHeaders(raw []byte) ([]byte, error) { |
| - header, _, ok := splitHeader(raw) |
| - if !ok { |
| - return nil, errNoSeparator |
| + header, err := headerBlock(raw) |
| + if err != nil { |
| + return nil, err |
| } |
| out := make([]byte, 0, len(raw)) |
| dropping := false |
| @@ -65,8 +121,7 @@ func StripHeaders(raw []byte) ([]byte, error) { |
| } |
| dropping = false |
| if c := bytes.IndexByte(line, ':'); c > 0 { |
| - name := strings.TrimRight(string(line[:c]), " \t") |
| - if strippedField(name) { |
| + if strippedField(string(line[:c])) { |
| dropping = true |
| continue |
| } |
diff --git a/internal/mailer/hygiene_test.go b/internal/mailer/hygiene_test.go| index 58b0c1dcb..95e482f49 100644 |
| --- a/internal/mailer/hygiene_test.go |
| +++ b/internal/mailer/hygiene_test.go |
| @@ -19,7 +19,6 @@ func TestHygieneStripsHeaders(t *testing.T) { |
| " folded on two lines\r\n" + |
| "X-SES-CONFIGURATION-SET: theirs\r\n" + |
| "x-ses-message-tags: account=victim, app=x\r\n" + |
| - "Bcc : spaced@example.org\r\n" + |
| "bCc:\r\n" + |
| " d@example.org\r\n" + |
| "X-Sesame: kept\r\n" + |
| @@ -41,7 +40,7 @@ func TestHygieneStripsHeaders(t *testing.T) { |
| if string(got) != want { |
| t.Fatalf("stripped:\n%q\nwant:\n%q", got, want) |
| } |
| - for _, gone := range []string{"a@example.org", "b@example.org", "c@example.org", "d@example.org", "spaced@", "theirs", "victim", "other"} { |
| + for _, gone := range []string{"a@example.org", "b@example.org", "c@example.org", "d@example.org", "theirs", "victim", "other"} { |
| if strings.Contains(string(got[:strings.Index(string(got), "\r\n\r\n")]), gone) { |
| t.Errorf("%q survived in the header block", gone) |
| } |
| @@ -61,9 +60,57 @@ func TestHygieneStripsHeaders(t *testing.T) { |
| } |
| } |
| + // A header block the mailer and SES might read differently is refused |
| + // before any stripping (review round 1, Task 5 P1-1). |
| + for name, bad := range map[string]string{ |
| + "space before the colon": "From: a@b.example.com\r\nBcc : h@x.example\r\n\r\nbody\r\n", |
| + "tab before the colon": "From: a@b.example.com\r\nX-SES-TENANT\t: v\r\n\r\nbody\r\n", |
| + "a bare CR": "From: a@b.example.com\r\nSubject: s\rBcc: h@x.example\r\n\r\nbody\r\n", |
| + "bare CRs hiding X-SES-*": "From: a@b.example.com\r\nSubject: s\rX-SES-CONFIGURATION-SET: other\rX-SES-TENANT: carlos-victim\rBcc: h@x\r\n\r\nbody\r\n", |
| + "a NUL in a value": "From: a@b.example.com\r\nSubject: s\x00Bcc: h@x\r\n\r\nbody\r\n", |
| + "a control byte": "From: a@b.example.com\r\nSubject: s\x0bx\r\n\r\nbody\r\n", |
| + "DEL": "From: a@b.example.com\r\nSubject: s\x7f\r\n\r\nbody\r\n", |
| + "a line with no colon": "From: a@b.example.com\r\nBcc h@x.example\r\n\r\nbody\r\n", |
| + "a continuation first": " Bcc: h@x.example\r\nFrom: a@b.example.com\r\n\r\nbody\r\n", |
| + "a non-ASCII field name": "From: a@b.example.com\r\nB\xc3\xa7c: h@x.example\r\n\r\nbody\r\n", |
| + "an empty field name": "From: a@b.example.com\r\n: h@x.example\r\n\r\nbody\r\n", |
| + } { |
| + if got, err := StripHeaders([]byte(bad)); err == nil { |
| + t.Errorf("%s: accepted, stripped to %q", name, got) |
| + } |
| + } |
| + // A tab is whitespace in a value and in a continuation; a UTF-8 |
| + // subject is not a control byte. |
| + ok := "From: a@b.example.com\r\nSubject:\ttabbed \xc3\xa9t\xc3\xa9\r\n\tcontinued\r\n\r\nbody\r\n" |
| + if got, err := StripHeaders([]byte(ok)); err != nil || string(got) != ok { |
| + t.Fatalf("a well-formed block was refused or changed: %q %v", got, err) |
| + } |
| + |
| // Nothing to strip: byte for byte. |
| clean := "From: a@b.example.com\r\n\r\n\x00binary\xff body\r\n" |
| if got, err := StripHeaders([]byte(clean)); err != nil || string(got) != clean { |
| t.Fatalf("clean message changed: %q %v", got, err) |
| } |
| } |
| + |
| +// The From check reads the same strict header block as the stripping |
| +// (review round 1, Task 5 P1-1), on its own: each of these is refused by |
| +// oneFrom itself, not only later by StripHeaders. |
| +func TestOneFromRefusesMalformedHeaderBlocks(t *testing.T) { |
| + const from = "hello@docs.example.com" |
| + for name, raw := range map[string]string{ |
| + "From : after From": "From: " + from + "\r\nFrom : ceo@victim.example\r\n\r\nb\r\n", |
| + "From<tab>: after": "From: " + from + "\r\nFrom\t: ceo@victim.example\r\n\r\nb\r\n", |
| + "a bare CR": "From: " + from + "\r\nSubject: s\rFrom: ceo@victim.example\r\n\r\nb\r\n", |
| + "a NUL": "From: " + from + "\r\nSubject: s\x00\r\n\r\nb\r\n", |
| + "no colon": "From: " + from + "\r\nnot a field\r\n\r\nb\r\n", |
| + "continuation first": " x\r\nFrom: " + from + "\r\n\r\nb\r\n", |
| + } { |
| + if got, ok := oneFrom([]byte(raw), from); ok { |
| + t.Errorf("%s: oneFrom admitted %q", name, got) |
| + } |
| + } |
| + if got, ok := oneFrom([]byte("From: Docs <"+from+">\r\nSubject: s\r\n\r\nb\r\n"), from); !ok || got != from { |
| + t.Fatalf("a well-formed message: %q %v", got, ok) |
| + } |
| +} |
diff --git a/internal/mailer/policy.go b/internal/mailer/policy.go| index 1b6e57610..65c2a1aa9 100644 |
| --- a/internal/mailer/policy.go |
| +++ b/internal/mailer/policy.go |
| @@ -40,7 +40,8 @@ type decision struct { |
| retryAfter string |
| sender *mailwire.SenderView |
| - from string // the bare From address |
| + from string // the bare From address |
| + to []string // the parsed envelope recipients |
| configSet string |
| counterKey string |
| day string |
| @@ -111,9 +112,12 @@ func readJSON[T any](ctx context.Context, m *Mailer, key string) (*T, error) { |
| // 5. that address's domain is one the sender was granted, whose domain |
| // record lists the app and is verified in the mail region, else 403 |
| // FROM_NOT_ALLOWED; |
| -// 6. a slot of the sender's daily cap is reserved, else 429 CAP_REACHED; |
| -// 7. a token of the sender's rate is taken, else 429 RATE, and the slot |
| -// is given back. |
| +// 6. a token of the sender's rate is taken, else 429 RATE; |
| +// 7. a slot of the sender's daily cap is reserved, else 429 CAP_REACHED, |
| +// and the token is given back. |
| +// |
| +// Steps 6 and 7 are in the reverse of the plan's order (review round 1, |
| +// Task 5 P3): the rate is checked before the cap's fsynced write. |
| // |
| // A store error at any step is 503 MAILER_UNAVAILABLE, never an admit. |
| func (m *Mailer) admit(ctx context.Context, req mailsubmit.SendRequest) decision { |
| @@ -174,35 +178,51 @@ func (m *Mailer) admit(ctx context.Context, req mailsubmit.SendRequest) decision |
| if region == nil || region.Status != mailwire.DomainStatusVerified || region.IdentityARN == "" { |
| return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| } |
| - |
| - // 6. The per-box daily cap (decision 9, §4.1 (a)): messages, not |
| - // recipients, as the console counts Send events. |
| - limit := sender.Grant.DailyCap |
| - if limit <= 0 { |
| - limit = mailwire.DefaultDailyCap |
| + // Every send names a configuration set (§9.0: an absent parameter lets |
| + // a header choose one, and the set is what carries the events that |
| + // count and attribute the send). A verified identity has none only on a |
| + // deployment with no SNS topic, where the account's set |
| + // (mail.ConfigSetName) does not exist either, and a send through a |
| + // missing set fails outright. So the send is refused rather than made |
| + // without one (review round 1, Task 5 P1-1). |
| + if region.ConfigSet == "" { |
| + m.logf("mailer: %s/%s: domain %s has no configuration set in %s (no event destination on this deployment); submission refused", req.Account, req.App, domain, m.mailRegion) |
| + return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| } |
| + |
| // The sender is the app sender, read from its own key (decision 5): |
| // the key and the tag name it by that id, never by the body's. |
| key := req.Account + "/" + req.App + "/" + mailwire.SenderAppID |
| day := Day(now) |
| + |
| + // 6. The per-sender rate (G9), before the cap's fsynced write, so a |
| + // sender over its rate costs the box no disk write (review round 1, |
| + // Task 5 P3). |
| + if ok, wait := m.buckets.Take(key, now); !ok { |
| + d := refuse(http.StatusTooManyRequests, mailsubmit.CodeRate) |
| + d.retryAfter = strconv.Itoa(max(1, int(math.Ceil(wait.Seconds())))) |
| + return d |
| + } |
| + |
| + // 7. The per-box daily cap (decision 9, §4.1 (a)): messages, not |
| + // recipients, as the console counts Send events. A refusal gives the |
| + // rate token back: a capped sender is not also rate-limited. |
| + limit := sender.Grant.DailyCap |
| + if limit <= 0 { |
| + limit = mailwire.DefaultDailyCap |
| + } |
| reserved, err := m.counter.Reserve(key, day, limit) |
| if err != nil { |
| + m.buckets.Refund(key) |
| m.logf("mailer: cap counter for %s: %v", key, err) |
| return unavailable |
| } |
| if !reserved { |
| + m.buckets.Refund(key) |
| d := refuse(http.StatusTooManyRequests, mailsubmit.CodeCapReached) |
| d.retryAfter = secondsToMidnight(now) |
| return d |
| } |
| - |
| - // 7. The per-sender rate (G9). A refused take gives the slot back. |
| - if ok, wait := m.buckets.Take(key, now); !ok { |
| - m.counter.Release(key, day) |
| - d := refuse(http.StatusTooManyRequests, mailsubmit.CodeRate) |
| - d.retryAfter = strconv.Itoa(max(1, int(math.Ceil(wait.Seconds())))) |
| - return d |
| - } |
| return decision{sender: sender, from: from, configSet: region.ConfigSet, counterKey: key, day: day} |
| } |
| @@ -246,8 +266,8 @@ func oneFrom(raw []byte, envelopeFrom string) (string, bool) { |
| if err != nil || !strings.Contains(want.Address, "@") { |
| return "", false |
| } |
| - header, _, ok := splitHeader(raw) |
| - if !ok { |
| + header, err := headerBlock(raw) |
| + if err != nil { |
| return "", false |
| } |
| msg, err := mail.ReadMessage(bytes.NewReader(append(append([]byte(nil), header...), "\r\n"...))) |
diff --git a/internal/mailer/rate.go b/internal/mailer/rate.go| index 7ab2a77f0..4487819be 100644 |
| --- a/internal/mailer/rate.go |
| +++ b/internal/mailer/rate.go |
| @@ -54,3 +54,13 @@ func (b *Buckets) Take(key string, now time.Time) (ok bool, wait time.Duration) |
| } |
| return false, time.Duration((1 - bk.tokens) / b.rate * float64(time.Second)) |
| } |
| + |
| +// Refund gives back one token of key's bucket, up to the burst: a message |
| +// that took a token and was then refused for another reason. |
| +func (b *Buckets) Refund(key string) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + if bk, ok := b.buckets[key]; ok { |
| + bk.tokens = math.Min(b.burst, bk.tokens+1) |
| + } |
| +} |
diff --git a/internal/mailer/send.go b/internal/mailer/send.go| index 9f6b3de9a..09e57c4b8 100644 |
| --- a/internal/mailer/send.go |
| +++ b/internal/mailer/send.go |
| @@ -21,8 +21,23 @@ import ( |
| // maxInFlight is how many sends the mailer runs at once; above it the |
| // answer is 503 MAILER_UNAVAILABLE at once, which the app retries. |
| +// |
| +// Memory (review round 1, Task 5 P3): one 10 MiB message peaks at about |
| +// 48 MiB in this process (the 14 MiB request body, the decoded raw, its |
| +// stripped copy, and the SDK's base64 request body), so four are about |
| +// 190 MiB live. carlos-mailer.service sets GOMEMLIMIT=288MiB under |
| +// MemoryHigh=320M and MemoryMax=384M, so the collector works hard well |
| +// before the kernel throttles or kills. |
| const maxInFlight = 4 |
| +// perSenderInFlight is how many of those one sender may hold (review round |
| +// 1, Task 5 P2-3), so one app cannot take every slot on the box. Above it |
| +// the answer is 429 RATE, Retry-After 1. |
| +const perSenderInFlight = 2 |
| + |
| +// alertEvery is the least time between two key-load ALERT lines. |
| +const alertEvery = time.Minute |
| + |
| // Options configure a Mailer. |
| type Options struct { |
| // Scope is this box's scope, by the agent's rule (host.BoxScopeFromEnv). |
| @@ -56,9 +71,14 @@ type Mailer struct { |
| buckets *Buckets |
| sem chan struct{} |
| - routes routeCache |
| - senders viewCache[mailwire.SenderView] |
| - domains viewCache[mailwire.DomainView] |
| + cred *credState |
| + |
| + senderMu sync.Mutex |
| + inflight map[string]int // per account/app |
| + lastAlert time.Time // under mu |
| + routes routeCache |
| + senders viewCache[mailwire.SenderView] |
| + domains viewCache[mailwire.DomainView] |
| mu sync.Mutex |
| ses SES |
| @@ -72,7 +92,8 @@ func New(ctx context.Context, o Options) (*Mailer, error) { |
| return nil, errors.New("mailer: keys, counter, clients and mail region are required") |
| } |
| m := &Mailer{scope: o.Scope, mailRegion: o.MailRegion, keys: o.Keys, counter: o.Counter, clients: o.Clients, |
| - logf: o.Logf, now: o.Now, buckets: NewBuckets(), sem: make(chan struct{}, maxInFlight)} |
| + logf: o.Logf, now: o.Now, buckets: NewBuckets(), sem: make(chan struct{}, maxInFlight), |
| + cred: &credState{}, inflight: map[string]int{}} |
| if m.logf == nil { |
| m.logf = func(string, ...any) {} |
| } |
| @@ -96,7 +117,9 @@ func (m *Mailer) buildClients(ctx context.Context) error { |
| return fmt.Errorf("mailer: build clients: %w", err) |
| } |
| m.mu.Lock() |
| - m.ses, m.store = ses, newAbsentOnDeniedStore(store, m.logf) |
| + wrapped := newAbsentOnDeniedStore(store, m.logf) |
| + wrapped.cred = m.cred |
| + m.ses, m.store = ses, wrapped |
| m.mu.Unlock() |
| return nil |
| } |
| @@ -129,18 +152,51 @@ func (m *Mailer) refreshKeys(ctx context.Context) error { |
| } |
| m.mu.Lock() |
| m.broken = err |
| + alert := err != nil && (m.lastAlert.IsZero() || m.now().Sub(m.lastAlert) >= alertEvery) |
| + if alert { |
| + m.lastAlert = m.now() |
| + } |
| m.mu.Unlock() |
| if err != nil { |
| - m.logf("mailer: ALERT: key file changed and did not load; refusing every send until it does: %v", err) |
| + if alert { |
| + m.logf("mailer: ALERT: key file changed and did not load; refusing every send until it does: %v", err) |
| + } |
| return err |
| } |
| m.logf("mailer: key file changed; clients rebuilt over key %s", m.keys.Newest().ID) |
| return nil |
| } |
| -// Healthy is GET /v1/health's answer: the key file loads and the clients |
| -// are built. |
| -func (m *Mailer) Healthy() error { return m.refreshKeys(context.Background()) } |
| +// Healthy is GET /v1/health's answer: the key file loads, the clients are |
| +// built, and the last AWS call did not reject the key itself. |
| +func (m *Mailer) Healthy() error { |
| + if err := m.refreshKeys(context.Background()); err != nil { |
| + return err |
| + } |
| + if err := m.cred.current(); err != nil { |
| + return fmt.Errorf("mailer: AWS refuses the mailer's key: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// takeSender takes one of a sender's in-flight slots, or reports none free. |
| +func (m *Mailer) takeSender(key string) bool { |
| + m.senderMu.Lock() |
| + defer m.senderMu.Unlock() |
| + if m.inflight[key] >= perSenderInFlight { |
| + return false |
| + } |
| + m.inflight[key]++ |
| + return true |
| +} |
| + |
| +func (m *Mailer) giveSender(key string) { |
| + m.senderMu.Lock() |
| + defer m.senderMu.Unlock() |
| + if m.inflight[key]--; m.inflight[key] <= 0 { |
| + delete(m.inflight, key) |
| + } |
| +} |
| // ServeHTTP is POST /v1/send: one stamped message from the agent, answered |
| // synchronously with SES's result or the coded refusal (design §4). |
| @@ -153,16 +209,28 @@ func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| var req mailsubmit.SendRequest |
| - if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mailsubmit.MaxBody)).Decode(&req); err != nil || !validRequest(req) { |
| + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mailsubmit.MaxBody)).Decode(&req); err != nil { |
| + answer(w, http.StatusBadRequest, mailsubmit.Answer{Code: mailsubmit.CodeBadRequest}, "") |
| + return |
| + } |
| + to, ok := validRequest(req) |
| + if !ok { |
| answer(w, http.StatusBadRequest, mailsubmit.Answer{Code: mailsubmit.CodeBadRequest}, "") |
| return |
| } |
| + sender := req.Account + "/" + req.App |
| + if !m.takeSender(sender) { |
| + answer(w, http.StatusTooManyRequests, mailsubmit.Answer{Code: mailsubmit.CodeRate}, "1") |
| + return |
| + } |
| + defer m.giveSender(sender) |
| ctx := r.Context() |
| if err := m.refreshKeys(ctx); err != nil { |
| answer(w, http.StatusServiceUnavailable, mailsubmit.Answer{Code: mailsubmit.CodeMailerUnavailable}, "") |
| return |
| } |
| d := m.admit(ctx, req) |
| + d.to = to |
| if !d.admitted() { |
| m.logf("mailer: %s/%s %s: %d %s", req.Account, req.App, req.Host, d.status, d.code) |
| answer(w, d.status, mailsubmit.Answer{Code: d.code}, d.retryAfter) |
| @@ -175,8 +243,13 @@ func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| out, err := m.sesNow().SendEmail(ctx, sendInput(req, d, stripped)) |
| + m.cred.note(err) |
| if err != nil { |
| - m.counter.Release(d.counterKey, d.day) |
| + // Only a definite refusal gives the slot back (review round 1, |
| + // Task 5 P2-1): a cancelled or lost call may have been sent. |
| + if definiteRefusal(err) { |
| + m.counter.Release(d.counterKey, d.day) |
| + } |
| status, code, retryAfter := sesRefusal(err) |
| m.logf("mailer: %s/%s %s: SES refused: %d %s: %v", req.Account, req.App, req.Host, status, code, err) |
| answer(w, status, mailsubmit.Answer{Code: code}, retryAfter) |
| @@ -189,22 +262,26 @@ func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // validRequest is the stamped request's shape: names the bucket keys can |
| // be built from, a from, 1 to 50 recipients that each parse as one |
| -// address, and a raw message within the limit. The agent checked most of |
| -// it; the mailer does not rely on that. |
| -func validRequest(req mailsubmit.SendRequest) bool { |
| +// address with no display name, and a raw message within the limit. The |
| +// agent checked most of it; the mailer does not rely on that. It returns |
| +// the parsed recipient addresses, which are what SES is given (review |
| +// round 1, Task 5 P3), never the strings as they came. |
| +func validRequest(req mailsubmit.SendRequest) ([]string, bool) { |
| if !release.ValidAccount(req.Account) || !release.ValidApp(req.App) || !validHost(req.Host) { |
| - return false |
| + return nil, false |
| } |
| if req.From == "" || len(req.To) == 0 || len(req.To) > mailsubmit.MaxRecipients || len(req.Raw) == 0 || len(req.Raw) > mailsubmit.MaxRaw { |
| - return false |
| + return nil, false |
| } |
| - for _, to := range req.To { |
| - a, err := mail.ParseAddress(to) |
| + to := make([]string, 0, len(req.To)) |
| + for _, raw := range req.To { |
| + a, err := mail.ParseAddress(raw) |
| if err != nil || a.Name != "" || !strings.Contains(a.Address, "@") { |
| - return false |
| + return nil, false |
| } |
| + to = append(to, a.Address) |
| } |
| - return true |
| + return to, true |
| } |
| // validHost is a hostname a record key may be built from: no path |
diff --git a/internal/mailer/send_test.go b/internal/mailer/send_test.go| index c5a2df081..c91018ffb 100644 |
| --- a/internal/mailer/send_test.go |
| +++ b/internal/mailer/send_test.go |
| @@ -13,6 +13,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/aws" |
| sesv2types "github.com/aws/aws-sdk-go-v2/service/sesv2/types" |
| "github.com/aws/smithy-go" |
| + smithyhttp "github.com/aws/smithy-go/transport/http" |
| "github.com/carlosframework/platform/internal/mailsubmit" |
| "github.com/carlosframework/platform/internal/mailwire" |
| @@ -113,6 +114,25 @@ func TestMailerPolicyRefusesBeforeSES(t *testing.T) { |
| {"no domain record", []harnessOpt{func(c *harnessCfg) { c.domain = nil }}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| {"no grant", []harnessOpt{sender(func(s map[string]any) { delete(s, "grant") })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| {"From: is not from", nil, func(r *mailsubmit.SendRequest) { r.Raw = []byte(message("other@docs.example.com")) }, 400, mailsubmit.CodeBadRequest}, |
| + {"From : before a real From (review P1-1)", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nFrom : ceo@victim.example\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"From<tab>: before a real From", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nFrom\t: ceo@victim.example\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"a bare CR hiding a From", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nSubject: s\rFrom: ceo@victim.example\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"bare CRs hiding X-SES-* and Bcc", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nSubject: s\rX-SES-CONFIGURATION-SET: other\rX-SES-TENANT: carlos-victim\rBcc: h@x\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"a NUL in the header block", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nSubject: s\x00\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"verified, but with no configuration set", []harnessOpt{domain(func(d map[string]any) { |
| + d["regions"] = map[string]any{tRegion: map[string]any{"identity_arn": "arn:x", "status": "verified"}} |
| + })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"a domain record whose body names another domain", []harnessOpt{domain(func(d map[string]any) { d["domain"] = "other.example.com" })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| {"two From: fields", nil, func(r *mailsubmit.SendRequest) { |
| r.Raw = []byte("From: " + tFrom + "\r\nFROM: evil@other.example.com\r\n\r\nbody\r\n") |
| }, 400, mailsubmit.CodeBadRequest}, |
| @@ -195,7 +215,8 @@ func TestSendInputShape(t *testing.T) { |
| raw := "From: Docs <" + tFrom + ">\r\nTo: Header <header@example.org>\r\nBcc: hidden@example.org\r\nX-SES-TENANT: other\r\nSubject: hi\r\n\r\nbody\r\n" |
| req := h.request(func(r *mailsubmit.SendRequest) { |
| r.Raw = []byte(raw) |
| - r.To = []string{"env1@example.org", "env2@example.org"} |
| + // SES is given the parsed addresses, not these strings. |
| + r.To = []string{"<env1@example.org>", " env2@example.org "} |
| }) |
| if got := h.send(req); got.status != 200 || got.ans.MessageID != "ses-1" { |
| t.Fatalf("send: %+v", got) |
| @@ -240,17 +261,17 @@ func TestSendInputShape(t *testing.T) { |
| } |
| } |
| - // With a TenantARN, the account's tenant; with no config set, none. |
| + // With a TenantARN, the account's tenant; the configuration set is |
| + // always passed (a domain without one is refused before SES). |
| h = newHarness(t, func(c *harnessCfg) { |
| c.sender["tenant_arn"] = "arn:aws:ses:eu-west-1:1:tenant/carlos-abcxyz/x" |
| - c.domain["regions"] = map[string]any{tRegion: map[string]any{"identity_arn": "arn:x", "status": "verified"}} |
| }) |
| if got := h.send(h.request()); got.status != 200 { |
| t.Fatalf("send: %+v", got) |
| } |
| in = h.ses.last() |
| - if aws.ToString(in.TenantName) != mailwire.TenantName(tAcct) || in.ConfigurationSetName != nil { |
| - t.Errorf("TenantName %q ConfigurationSetName %v", aws.ToString(in.TenantName), in.ConfigurationSetName) |
| + if aws.ToString(in.TenantName) != mailwire.TenantName(tAcct) || aws.ToString(in.ConfigurationSetName) != "carlos-"+tAcct { |
| + t.Errorf("TenantName %q ConfigurationSetName %q", aws.ToString(in.TenantName), aws.ToString(in.ConfigurationSetName)) |
| } |
| } |
| @@ -291,8 +312,9 @@ func TestRateBucket(t *testing.T) { |
| } |
| } |
| -// SES's answers map onto the verb's codes, and a send SES did not take |
| -// gives its cap slot back. |
| +// SES's answers map onto the verb's codes. A send SES definitely refused |
| +// gives its cap slot back; one whose outcome is unknown (cancelled, timed |
| +// out, a lost connection) keeps it (review round 1, Task 5 P2-1). |
| func TestMailerSESErrorsMap(t *testing.T) { |
| key := tAcct + "/" + tApp + "/app" |
| for name, c := range map[string]struct { |
| @@ -300,13 +322,16 @@ func TestMailerSESErrorsMap(t *testing.T) { |
| status int |
| code string |
| ra string |
| + slots int |
| }{ |
| - "rejected": {&sesv2types.MessageRejected{Message: aws.String("x")}, 400, mailsubmit.CodeRejected, ""}, |
| - "too many": {&sesv2types.TooManyRequestsException{Message: aws.String("x")}, 429, mailsubmit.CodeRate, "1"}, |
| - "throttling": {&smithy.GenericAPIError{Code: "ThrottlingException"}, 429, mailsubmit.CodeRate, "1"}, |
| - "sending paused": {&sesv2types.SendingPausedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, ""}, |
| - "suspended": {&sesv2types.AccountSuspendedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, ""}, |
| - "anything else": {errors.New("connection reset"), 503, mailsubmit.CodeMailerUnavailable, ""}, |
| + "rejected": {&sesv2types.MessageRejected{Message: aws.String("x")}, 400, mailsubmit.CodeRejected, "", 0}, |
| + "too many": {&sesv2types.TooManyRequestsException{Message: aws.String("x")}, 429, mailsubmit.CodeRate, "1", 0}, |
| + "throttling": {&smithy.GenericAPIError{Code: "ThrottlingException"}, 429, mailsubmit.CodeRate, "1", 0}, |
| + "sending paused": {&sesv2types.SendingPausedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, "", 0}, |
| + "suspended": {&sesv2types.AccountSuspendedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, "", 0}, |
| + "lost": {errors.New("connection reset"), 503, mailsubmit.CodeMailerUnavailable, "", 1}, |
| + "cancelled": {context.Canceled, 503, mailsubmit.CodeMailerUnavailable, "", 1}, |
| + "timed out": {context.DeadlineExceeded, 503, mailsubmit.CodeMailerUnavailable, "", 1}, |
| } { |
| t.Run(name, func(t *testing.T) { |
| h := newHarness(t) |
| @@ -316,8 +341,8 @@ func TestMailerSESErrorsMap(t *testing.T) { |
| if got.retryAfter != c.ra { |
| t.Fatalf("Retry-After %q, want %q", got.retryAfter, c.ra) |
| } |
| - if n := h.m.counter.Count(key, Day(h.now)); n != 0 { |
| - t.Fatalf("the slot was not released: %d", n) |
| + if n := h.m.counter.Count(key, Day(h.now)); n != c.slots { |
| + t.Fatalf("%d slots held after the send, want %d", n, c.slots) |
| } |
| }) |
| } |
| @@ -339,6 +364,7 @@ func TestMailerReadsAccessDeniedAsAbsent(t *testing.T) { |
| "domain denied": {"accounts/" + tAcct + "/email/domains/", denied, 403, mailsubmit.CodeFromNotAllowed}, |
| "sender store down": {"apps/" + tAcct + "/" + tApp + "/email/senders/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| "record store down": {"apps/" + tAcct + "/" + tApp + "/instances/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| + "a bare 403, no code": {"apps/" + tAcct + "/" + tApp + "/email/senders/", bare403(), 503, mailsubmit.CodeMailerUnavailable}, |
| "domain store down": {"accounts/" + tAcct + "/email/domains/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| } { |
| t.Run(name, func(t *testing.T) { |
| @@ -356,6 +382,114 @@ func TestMailerReadsAccessDeniedAsAbsent(t *testing.T) { |
| } |
| } |
| +// A rejected key is not an absence (review round 1, Task 5 P2-2): every |
| +// credential answer is 503 and fails health until a call succeeds. |
| +func TestMailerCredentialErrorsFailHealth(t *testing.T) { |
| + for _, code := range []string{"InvalidAccessKeyId", "SignatureDoesNotMatch", "RequestTimeTooSkewed", "ExpiredToken"} { |
| + t.Run(code, func(t *testing.T) { |
| + fs := &failingStore{prefix: "apps/" + tAcct + "/" + tApp + "/email/senders/", err: &smithy.GenericAPIError{Code: code}} |
| + h := newHarness(t, func(cfg *harnessCfg) { |
| + cfg.store = func(s release.Store) release.Store { fs.Store = s; return fs } |
| + }) |
| + h.want(h.send(h.request()), 503, mailsubmit.CodeMailerUnavailable) |
| + if h.ses.n() != 0 || h.m.Healthy() == nil { |
| + t.Fatalf("SES %d, healthy %v", h.ses.n(), h.m.Healthy()) |
| + } |
| + fs.err = nil |
| + h.now = h.now.Add(time.Minute) |
| + if got := h.send(h.request()); got.status != 200 || h.m.Healthy() != nil { |
| + t.Fatalf("after the key works again: %+v %v", got, h.m.Healthy()) |
| + } |
| + }) |
| + } |
| + // The same from SES itself. |
| + h := newHarness(t) |
| + h.ses.err = &smithy.GenericAPIError{Code: "InvalidClientTokenId"} |
| + h.want(h.send(h.request()), 503, mailsubmit.CodeMailerUnavailable) |
| + if h.m.Healthy() == nil { |
| + t.Fatal("healthy after SES rejected the key") |
| + } |
| +} |
| + |
| +func bare403() error { |
| + return &smithyhttp.ResponseError{Response: &smithyhttp.Response{Response: &http.Response{StatusCode: 403}}, Err: errors.New("forbidden")} |
| +} |
| + |
| +// One sender holds at most perSenderInFlight of the box's sends; the next |
| +// is 429 RATE at once, and another app still gets through (review round 1, |
| +// Task 5 P2-3). |
| +func TestMailerPerSenderInFlight(t *testing.T) { |
| + h := newHarness(t, func(c *harnessCfg) { c.domain["apps"] = []string{tApp, "sheets"} }) |
| + h.addApp("sheets", "s.docs.example.com") |
| + h.ses.block = make(chan struct{}) |
| + var wg sync.WaitGroup |
| + for i := 0; i < perSenderInFlight; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); h.send(h.request()) }() |
| + } |
| + deadline := time.Now().Add(5 * time.Second) |
| + for h.ses.n() < perSenderInFlight && time.Now().Before(deadline) { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + got := h.sendWithin(h.request()) |
| + h.want(got, 429, mailsubmit.CodeRate) |
| + if got.retryAfter != "1" { |
| + t.Fatalf("Retry-After %q", got.retryAfter) |
| + } |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + h.send(h.request(forApp("sheets", "s.docs.example.com"))) |
| + }() |
| + for h.ses.n() < perSenderInFlight+1 && time.Now().Before(deadline) { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if h.ses.n() != perSenderInFlight+1 { |
| + t.Fatalf("another app was held up: %d sends reached SES", h.ses.n()) |
| + } |
| + close(h.ses.block) |
| + wg.Wait() |
| +} |
| + |
| +// The rate is taken before the cap's write, and a capped send gives its |
| +// token back: with a cap of 1 and the clock frozen, every send after the |
| +// first is CAP_REACHED, never RATE (review round 1, Task 5 P3). |
| +func TestMailerCapRefusalRefundsTheToken(t *testing.T) { |
| + h := newHarness(t, func(c *harnessCfg) { c.sender["grant"] = map[string]any{"domains": []string{tDomain}, "daily_cap": 1} }) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("first send: %+v", got) |
| + } |
| + for i := 0; i < 2*Burst; i++ { |
| + h.want(h.send(h.request()), 429, mailsubmit.CodeCapReached) |
| + } |
| +} |
| + |
| +// The key-load ALERT is logged at most once a minute. |
| +func TestMailerKeyAlertIsRateLimited(t *testing.T) { |
| + h := newHarness(t) |
| + removeFile(t, h.keyPath) |
| + for i := 0; i < 5; i++ { |
| + h.send(h.request()) |
| + } |
| + count := func() int { |
| + n := 0 |
| + for _, l := range h.logs.lines { |
| + if strings.Contains(l, "ALERT") { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + if count() != 1 { |
| + t.Fatalf("%d ALERT lines in a burst, want 1", count()) |
| + } |
| + h.now = h.now.Add(alertEvery) |
| + h.send(h.request()) |
| + if count() != 2 { |
| + t.Fatalf("%d ALERT lines a minute later, want 2", count()) |
| + } |
| +} |
| + |
| // failingStore answers err for every key under prefix. |
| type failingStore struct { |
| release.Store |
| @@ -364,20 +498,27 @@ type failingStore struct { |
| } |
| func (f *failingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| - if strings.HasPrefix(key, f.prefix) { |
| + if f.err != nil && strings.HasPrefix(key, f.prefix) { |
| return nil, "", f.err |
| } |
| return f.Store.Get(ctx, key) |
| } |
| -// At most four sends in flight; the fifth is 503 at once. |
| +// At most maxInFlight sends in flight on the box; the next is 503 at once. |
| +// Two senders fill the box at perSenderInFlight each; a third is refused. |
| func TestMailerConcurrencyLimit(t *testing.T) { |
| - h := newHarness(t) |
| + h := newHarness(t, func(c *harnessCfg) { c.domain["apps"] = []string{tApp, "sheets", "slides"} }) |
| + h.addApp("sheets", "s.docs.example.com") |
| + h.addApp("slides", "l.docs.example.com") |
| h.ses.block = make(chan struct{}) |
| var wg sync.WaitGroup |
| for i := 0; i < maxInFlight; i++ { |
| + mut := forApp(tApp, tHost) |
| + if i%2 == 1 { |
| + mut = forApp("sheets", "s.docs.example.com") |
| + } |
| wg.Add(1) |
| - go func() { defer wg.Done(); h.send(h.request()) }() |
| + go func() { defer wg.Done(); h.send(h.request(mut)) }() |
| } |
| deadline := time.Now().Add(5 * time.Second) |
| for h.ses.n() < maxInFlight && time.Now().Before(deadline) { |
| @@ -386,7 +527,7 @@ func TestMailerConcurrencyLimit(t *testing.T) { |
| if h.ses.n() != maxInFlight { |
| t.Fatalf("%d sends in flight, want %d", h.ses.n(), maxInFlight) |
| } |
| - h.want(h.send(h.request()), 503, mailsubmit.CodeMailerUnavailable) |
| + h.want(h.sendWithin(h.request(forApp("slides", "l.docs.example.com"))), 503, mailsubmit.CodeMailerUnavailable) |
| close(h.ses.block) |
| wg.Wait() |
| } |
diff --git a/internal/mailer/ses.go b/internal/mailer/ses.go| index a046f7731..6a8911ec9 100644 |
| --- a/internal/mailer/ses.go |
| +++ b/internal/mailer/ses.go |
| @@ -55,23 +55,23 @@ func AWSClients(mailRegion, deployRegion, bucket string) func(context.Context, K |
| // sendInput is the SendEmail call for an admitted, stripped message: the |
| // raw content, the envelope as an explicit Destination (never the |
| -// headers), the domain's configuration set when it has one, the account's |
| +// headers), the domain's configuration set (always: admit refuses a domain |
| +// with none), the account's |
| // tenant only when the sender has one, and the three attribution tags the |
| // console believes from the mailer alone (decision 6). |
| func sendInput(req mailsubmit.SendRequest, d decision, stripped []byte) *sesv2.SendEmailInput { |
| in := &sesv2.SendEmailInput{ |
| FromEmailAddress: aws.String(d.from), |
| - Destination: &sesv2types.Destination{ToAddresses: append([]string(nil), req.To...)}, |
| + Destination: &sesv2types.Destination{ToAddresses: append([]string(nil), d.to...)}, |
| Content: &sesv2types.EmailContent{Raw: &sesv2types.RawMessage{Data: stripped}}, |
| + // Always set: admit refuses a domain with no set (§9.0). |
| + ConfigurationSetName: aws.String(d.configSet), |
| EmailTags: []sesv2types.MessageTag{ |
| {Name: aws.String(mailwire.TagAccount), Value: aws.String(req.Account)}, |
| {Name: aws.String(mailwire.TagApp), Value: aws.String(req.App)}, |
| {Name: aws.String(mailwire.TagSender), Value: aws.String(mailwire.SenderAppID)}, |
| }, |
| } |
| - if d.configSet != "" { |
| - in.ConfigurationSetName = aws.String(d.configSet) |
| - } |
| if d.sender.TenantARN != "" { |
| in.TenantName = aws.String(mailwire.TenantName(req.Account)) |
| } |
| @@ -102,3 +102,28 @@ func sesRefusal(err error) (status int, code, retryAfter string) { |
| } |
| return http.StatusServiceUnavailable, mailsubmit.CodeMailerUnavailable, "" |
| } |
| + |
| +// definiteRefusal reports whether SES answered the call with an error, so |
| +// the message was certainly not accepted and its cap slot can be given |
| +// back. A cancelled or timed-out call, or a transport failure, may have |
| +// been accepted before the answer was lost: its slot is kept (review round |
| +// 1, Task 5 P2-1), so an unknown send counts against the cap. |
| +func definiteRefusal(err error) bool { |
| + var apiErr smithy.APIError |
| + return errors.As(err, &apiErr) |
| +} |
| + |
| +// credentialCodes are the AWS answers that mean the mailer's key itself is |
| +// not working: no retry fixes them, and the box must say so (review round |
| +// 1, Task 5 P2-2). |
| +var credentialCodes = map[string]bool{ |
| + "InvalidAccessKeyId": true, "SignatureDoesNotMatch": true, "RequestTimeTooSkewed": true, |
| + "ExpiredToken": true, "ExpiredTokenException": true, "InvalidClientTokenId": true, |
| + "UnrecognizedClientException": true, "IncompleteSignature": true, "MissingAuthenticationToken": true, |
| +} |
| + |
| +// credentialError reports whether err is one of credentialCodes. |
| +func credentialError(err error) bool { |
| + var apiErr smithy.APIError |
| + return errors.As(err, &apiErr) && credentialCodes[apiErr.ErrorCode()] |
| +} |
diff --git a/internal/mailer/store.go b/internal/mailer/store.go| index f2aada785..5bc9f0901 100644 |
| --- a/internal/mailer/store.go |
| +++ b/internal/mailer/store.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| - "net/http" |
| "os" |
| "path" |
| "sync" |
| @@ -31,6 +30,9 @@ type absentOnDeniedStore struct { |
| release.Store |
| logf func(string, ...any) |
| now func() time.Time |
| + // cred is told of every read: a credential error, or a success that |
| + // clears one. Nil tells nothing. |
| + cred *credState |
| mu sync.Mutex |
| logged map[string]time.Time |
| @@ -45,6 +47,7 @@ func newAbsentOnDeniedStore(s release.Store, logf func(string, ...any)) *absentO |
| func (s *absentOnDeniedStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| body, etag, err := s.Store.Get(ctx, key) |
| + s.cred.note(err) |
| if err != nil && accessDenied(err) { |
| s.noteDenied(key, err) |
| return nil, "", fmt.Errorf("mailer: %s: access denied, read as absent: %w", key, os.ErrNotExist) |
| @@ -53,15 +56,46 @@ func (s *absentOnDeniedStore) Get(ctx context.Context, key string) ([]byte, stri |
| } |
| // accessDenied is S3's answer to a GET the caller may not make, or to a |
| -// missing key the caller may not list: the AccessDenied code, or a bare |
| -// 403 from an S3-compatible store. |
| +// missing key the caller may not list: the AccessDenied code, and nothing |
| +// else (review round 1, Task 5 P2-2). Every other 403 (a bad or expired |
| +// key, a skewed clock, a bare 403 with no code) is an error the caller |
| +// answers 503, and a credential one fails the mailer's health. |
| func accessDenied(err error) bool { |
| var apiErr smithy.APIError |
| - if errors.As(err, &apiErr) && apiErr.ErrorCode() == "AccessDenied" { |
| - return true |
| + return errors.As(err, &apiErr) && apiErr.ErrorCode() == "AccessDenied" |
| +} |
| + |
| +// credState is the mailer's last word on its own key: the last credential |
| +// error any AWS call answered, until a call succeeds. Healthy reports it, |
| +// so a box whose key stopped working reports the mailer not armed. |
| +type credState struct { |
| + mu sync.Mutex |
| + err error |
| +} |
| + |
| +// note records one call's outcome: a credential error sets the state, a |
| +// success clears it, and any other error leaves it. |
| +func (c *credState) note(err error) { |
| + if c == nil { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + switch { |
| + case err == nil: |
| + c.err = nil |
| + case credentialError(err): |
| + c.err = err |
| + } |
| +} |
| + |
| +func (c *credState) current() error { |
| + if c == nil { |
| + return nil |
| } |
| - var httpErr interface{ HTTPStatusCode() int } |
| - return errors.As(err, &httpErr) && httpErr.HTTPStatusCode() == http.StatusForbidden |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.err |
| } |
| func (s *absentOnDeniedStore) noteDenied(key string, err error) { |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index fae0d9942..a1e5284f6 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -204,4 +204,4 @@ plan14-root-reads-static-site-geo-962.tsv 5e8a72175700a3e60c1e283b133c1ee25e36f2 |
| plan14-root-reads-member-backups-drill-nodb.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063 |
| plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063 |
| plan14-root-reads-member-backups-2b.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063 |
| -plan14-root-reads-platform-mail-submission.tsv 48a56f8c1dabee1185118dfba64782556ebd0e57189273ec3e5ea343234e16da |
| +plan14-root-reads-platform-mail-submission.tsv 72c38da53c18da24c7ba8b4d11f0b7d48f52b133674291683315c163fe57d603 |
diff --git a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv| index d1f2d3278..7832a4b79 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| @@ -21,7 +21,7 @@ |
| @legacy bce32b49d764738f9b80e81a4b6473b446149bb1e62062886297d1431cc4cc4e internal/activator/backend_exec.go ExecBackend.mailSubmits legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: the CARLOS_MAIL rule. Reads rt.App, rt.Host, rt.Provisioned and RouteAccount(rt) from the agent's own registry row, and asks b.MailSwitch (the agent's cache of the console-written app sender record, internal/host/mailswitch.go: one bounded Get of apps/<acct>/<app>/email/senders/app.json through the agent's deploy store). Logs once per host at error level for an unprovisioned route of a switched app. Agent, not root; no file read. registry:App@213,registry:App@526,registry:Host@317,registry:Host@511,registry:Provisioned@246,whole:Route@185 cfd7494b38dc64c2710233dbc2da850eb7b89fc9aecfa648cd7affd5e9a354d0 |
| @legacy d6700cb69f36e6e7cb8fdf4f4b747269ba9bf6545143e4dd943acedc018bc4b1 internal/host/mailerreport.go mailerArmed legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: the agent's MailerArmed probe. Stats the constant socket path and dials it for GET /v1/health with a 2 s timeout; true only on a 200. Runs in the agent as carlos, never as root; the path is a constant, in a root-owned 0750 root:carlos directory nothing a tenant or an app can write. Answers a bool into the private status block. file:Stat@72 6fd83d5c27429d06864d02a141f7036c2f3e1e8e89366ad6d2a232d417420052 |
| @legacy 85d678c6a608ff70b7a60141d0efde911544f4b7aa9a7d9508f0e13cf2b7e724 internal/host/units/carlos-mailer-arm.path external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: [Path] PathExists=/etc/carlos-mailer/keys, Unit=carlos-mailer.socket, WantedBy=multi-user.target; enabled and armed by bootstrap like every .path. PID 1 watches a path in a root-owned 0750 root:carlos-mailer directory only root (the operator) writes; it starts a socket unit and reads nothing. file:external@0 6b28c6282ee930560f859f20c752c65f0e550412b9c6ffb1fc10c292a3941a2a |
| -@legacy 2e9ea18fa4d1aa973bb5394fcc21385c5883dc605f5f6bb7aec8c7d7c2976ac1 internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths. No root process reads anything new; the mailer reads its own key file and state. file:external@0 05014587b16352f1a0ecddc63ce2ea95732cadf7b284f3c8c7bb2b82b95ec922 |
| +@legacy 32524609e5d66b8b235d4575ac82e8e30b33b63e7e7d65bc181a95eb7572a535 internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths; Environment=GOMEMLIMIT=288MiB with MemoryHigh=320M and MemoryMax=384M for four 10 MiB sends (review round 1, Task 5 P3). No root process reads anything new; the mailer reads its own key file and state. file:external@0 4c0f0138683659416f50fbcfdbf18df6592ae03531538e2d98f9f2392659c7cb |
| @legacy 486f70ac08ac5f675d91dc3b7bddf949c908db227e4596af5706df846c4fb32f internal/host/units/carlos-mailer.socket external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: ConditionPathExists=/etc/carlos-mailer/keys, ListenStream=/run/carlos-mailer/mailer.sock, SocketUser=carlos, SocketGroup=carlos, SocketMode=0600, Accept=no; not enabled, started only by the arming path. PID 1 binds a socket in a root-owned directory, as carlos-instance-control.socket does in /run/carlos-control. No read added. file:external@0 275aae364c39e89bdf3d76d7e66aea9cf65b398ac0c16c087db353cfd5140c34 |
| @legacy 6124a227150c2055499a081f370c0d3211decfc51a16ff34a0449493b2a94cb3 internal/mailer/counter.go Counter.loadLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads the day's counts file from the mailer's own state directory; a body that does not decode is renamed aside, logged loudly, and the day restarts at zero (the per-box bound §4.1 (a) accepts). carlos-mailer only. file:ReadFile@142 a317a61e58c996133e1ae96045932c927052cb5f44720fb90193ae45abbe2d1b |
| @legacy 66171fc9229872bbf17d3f26e75389dbacb7171bbd7ff08f5c820b60140e2ebf internal/mailer/counter.go Counter.writeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: writes the day's counts durably (temp file in the same directory, fsync, rename, directory fsync) before a send. carlos-mailer only, in its own state directory. file:CreateTemp@118,file:Open@489 40cb38a8252e6c90bd21efdfafc7bbcb9b66b04a10bf9c2154f5796e1bff4820 |
| @@ -56,7 +56,7 @@ internal/activator/backend_exec.go ExecBackend.controlMount legacy accepted-lega |
| internal/activator/backend_exec.go ExecBackend.mailSubmits legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: the CARLOS_MAIL rule. Reads rt.App, rt.Host, rt.Provisioned and RouteAccount(rt) from the agent's own registry row, and asks b.MailSwitch (the agent's cache of the console-written app sender record, internal/host/mailswitch.go: one bounded Get of apps/<acct>/<app>/email/senders/app.json through the agent's deploy store). Logs once per host at error level for an unprovisioned route of a switched app. Agent, not root; no file read. registry:App@213,registry:App@526,registry:Host@317,registry:Host@511,registry:Provisioned@246,whole:Route@185 cfd7494b38dc64c2710233dbc2da850eb7b89fc9aecfa648cd7affd5e9a354d0 |
| internal/host/mailerreport.go mailerArmed legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: the agent's MailerArmed probe. Stats the constant socket path and dials it for GET /v1/health with a 2 s timeout; true only on a 200. Runs in the agent as carlos, never as root; the path is a constant, in a root-owned 0750 root:carlos directory nothing a tenant or an app can write. Answers a bool into the private status block. file:Stat@72 6fd83d5c27429d06864d02a141f7036c2f3e1e8e89366ad6d2a232d417420052 |
| internal/host/units/carlos-mailer-arm.path external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: [Path] PathExists=/etc/carlos-mailer/keys, Unit=carlos-mailer.socket, WantedBy=multi-user.target; enabled and armed by bootstrap like every .path. PID 1 watches a path in a root-owned 0750 root:carlos-mailer directory only root (the operator) writes; it starts a socket unit and reads nothing. file:external@0 6b28c6282ee930560f859f20c752c65f0e550412b9c6ffb1fc10c292a3941a2a |
| -internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths. No root process reads anything new; the mailer reads its own key file and state. file:external@0 05014587b16352f1a0ecddc63ce2ea95732cadf7b284f3c8c7bb2b82b95ec922 |
| +internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment= of every credential a host.env may carry (CARLOS_SECRETS_KEY, CARLOS_RELEASE_KEY, the tunnel, service, sidecar and DNS tokens, the alert webhook, CARLOS_ADMIN_TOKEN, CARLOS_INSTANCE_KEY, AWS keys and profiles; review round 1 Task 3 P3), AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths; Environment=GOMEMLIMIT=288MiB with MemoryHigh=320M and MemoryMax=384M for four 10 MiB sends (review round 1, Task 5 P3). No root process reads anything new; the mailer reads its own key file and state. file:external@0 4c0f0138683659416f50fbcfdbf18df6592ae03531538e2d98f9f2392659c7cb |
| internal/host/units/carlos-mailer.socket external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: ConditionPathExists=/etc/carlos-mailer/keys, ListenStream=/run/carlos-mailer/mailer.sock, SocketUser=carlos, SocketGroup=carlos, SocketMode=0600, Accept=no; not enabled, started only by the arming path. PID 1 binds a socket in a root-owned directory, as carlos-instance-control.socket does in /run/carlos-control. No read added. file:external@0 275aae364c39e89bdf3d76d7e66aea9cf65b398ac0c16c087db353cfd5140c34 |
| internal/mailer/counter.go Counter.loadLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads the day's counts file from the mailer's own state directory; a body that does not decode is renamed aside, logged loudly, and the day restarts at zero (the per-box bound §4.1 (a) accepts). carlos-mailer only. file:ReadFile@142 a317a61e58c996133e1ae96045932c927052cb5f44720fb90193ae45abbe2d1b |
| internal/mailer/counter.go Counter.writeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: writes the day's counts durably (temp file in the same directory, fsync, rename, directory fsync) before a send. carlos-mailer only, in its own state directory. file:CreateTemp@118,file:Open@489 40cb38a8252e6c90bd21efdfafc7bbcb9b66b04a10bf9c2154f5796e1bff4820 |
| @@ -72,10 +72,10 @@ internal/activator/prepare.go ExecBackend.listenControl legacy accepted-legacy a |
| @coverage internal/activator 2fe6860f1b7ef4f5644e17f59fe3cf75759ec2ffe597994c1478edd0512cbc38 |
| @coverage internal/host 0a61b32acb9b181dcc50356db2370ebabe81a66e12096a07526764d0216c792e |
| @coverage internal/host/demo_units 3a34238356068c6176879f3ee189c81af8e08bfcc0246c5feba80d7169f7af6a |
| -@coverage internal/host/units 691c24cbe981fb8961915598f2a8585d1ccf8368a8eb3b6a58f8c7a2834fe886 |
| +@coverage internal/host/units 2c461db671018e87f2d21b0640999d1ef37ed21e3381a34ee7d403ba575a8d8a |
| @coverage internal/hostenv 6c96c4abe8548fe3cf12d3a220de3e2917c3edfa5320b1662ea76bdf364d24b5 |
| @coverage internal/instancectl 50d4d80f1f1a86bbed67676f4e439eb79a08bb546ea85ff01a3b433925b9d984 |
| -@coverage internal/mailer 985199bf5324887938514750668eaa8eb099b1b3be0734c7de77c7fddd4230b1 |
| +@coverage internal/mailer 36bb8e0cd052a8cac07ffc96803a8187ef7ebf7861136700077c51e78cc7c99e |
| @coverage internal/mailsubmit 519123e15891e0802427595306d8caca1fd7f4f861ae1a2ec70e1c10f012e263 |
| @coverage internal/mailwire 58b9cbb8a003ed11feb1c0352c5c23992fe532da895471ec76045528ab12e077 |
| @coverage internal/moves 9390702695d308a327f5572f4ff5967718141c5d385dff7671ff1e2c825ef407 |