mailer: wait for a sender slot, prove the key, unset AWS_ACCESS_KEY
A third concurrent send for a sender waits up to 5 s, bound by the request's context, before 429. Health proves the key once with one GetObject: AccessDenied or absent proves the key and the clock; anything else leaves the mailer unarmed. The unit unsets AWS_ACCESS_KEY and AWS_SECRET_KEY too. A chain test drives verb, forwarder, mailer and a fake SES with rastrillo 1104469's real message bytes. Fable P2-7, P2-8, P3; Astra M1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+246
−23
internal/host/units/carlos-mailer.service+1 −1internal/host/units_isolation_test.go+1 −1internal/mailer/chain_test.go+77 −0internal/mailer/rate.go+2 −2internal/mailer/send.go+71 −19internal/mailer/send_test.go+70 −0internal/mailer/testdata/rastrillo-1104469-list.eml+15 −0internal/mailer/testdata/rastrillo-1104469-plain.eml+9 −0
diff --git a/internal/host/units/carlos-mailer.service b/internal/host/units/carlos-mailer.service| index b5cf1b67b..eed0c4ead 100644 |
| --- a/internal/host/units/carlos-mailer.service |
| +++ b/internal/host/units/carlos-mailer.service |
| @@ -29,7 +29,7 @@ ConditionPathExists=/etc/carlos-mailer/keys |
| [Service] |
| EnvironmentFile=-/etc/carlos/host.env |
| -UnsetEnvironment=CARLOS_SECRETS_KEY CARLOS_RELEASE_KEY CARLOS_TUNNEL_TOKEN CARLOS_SERVICE_TOKEN CARLOS_SIDECAR_TOKEN CARLOS_DNSIMPLE_TOKEN CARLOS_ALERT_WEBHOOK CARLOS_ADMIN_TOKEN CARLOS_INSTANCE_KEY AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE AWS_DEFAULT_PROFILE |
| +UnsetEnvironment=CARLOS_SECRETS_KEY CARLOS_RELEASE_KEY CARLOS_TUNNEL_TOKEN CARLOS_SERVICE_TOKEN CARLOS_SIDECAR_TOKEN CARLOS_DNSIMPLE_TOKEN CARLOS_ALERT_WEBHOOK CARLOS_ADMIN_TOKEN CARLOS_INSTANCE_KEY AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY AWS_SECRET_KEY AWS_SESSION_TOKEN AWS_PROFILE AWS_DEFAULT_PROFILE |
| Environment=AWS_EC2_METADATA_DISABLED=true |
| ExecStart=/opt/carlos/carlos mailer serve |
| Restart=always |
diff --git a/internal/host/units_isolation_test.go b/internal/host/units_isolation_test.go| index fff9b54a5..9deda0edd 100644 |
| --- a/internal/host/units_isolation_test.go |
| +++ b/internal/host/units_isolation_test.go |
| @@ -774,7 +774,7 @@ func TestMailerUnitShape(t *testing.T) { |
| } |
| for _, n := range []string{"CARLOS_SECRETS_KEY", "CARLOS_RELEASE_KEY", "CARLOS_TUNNEL_TOKEN", "CARLOS_SERVICE_TOKEN", "CARLOS_SIDECAR_TOKEN", |
| "CARLOS_DNSIMPLE_TOKEN", "CARLOS_ALERT_WEBHOOK", "CARLOS_ADMIN_TOKEN", "CARLOS_INSTANCE_KEY", |
| - "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"} { |
| + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"} { |
| if !unset[n] { |
| t.Errorf("carlos-mailer.service does not unset %s", n) |
| } |
diff --git a/internal/mailer/chain_test.go b/internal/mailer/chain_test.go| new file mode 100644 |
| index 000000000..61a78c4c0 |
| --- /dev/null |
| +++ b/internal/mailer/chain_test.go |
| @@ -0,0 +1,77 @@ |
| +package mailer |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// TestChainVerbToSESCarriesRastrilloMessages is the whole path once (Fable |
| +// P3): an instance's POST /v1/mail on its control socket (the agent's verb) |
| +// → the agent's SocketForwarder over a unix socket → the mailer → SES (the |
| +// fake), fed the bytes rastrillo 1104469's mail package builds |
| +// (testdata/rastrillo-1104469-*.eml, made by its submitMessage: a plain |
| +// message, and a list message with an RFC 2047 subject, Reply-To, |
| +// List-Id, a one-click unsubscribe and quoted-printable UTF-8). Each passes |
| +// headerBlock, and reaches SES byte for byte. |
| +func TestChainVerbToSESCarriesRastrilloMessages(t *testing.T) { |
| + h := newHarness(t) |
| + // A short directory: a unix socket's path is bounded (104 bytes on |
| + // macOS), and t.TempDir's can be longer. |
| + dir, err := os.MkdirTemp("", "mc") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = os.RemoveAll(dir) }) |
| + sock := filepath.Join(dir, "m.sock") |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{Handler: h.m} |
| + go func() { _ = srv.Serve(ln) }() |
| + t.Cleanup(func() { _ = srv.Close() }) |
| + |
| + mux := http.NewServeMux() |
| + rt := registry.Route{Host: tHost, Account: tAcct, App: tApp} |
| + mailsubmit.Mount(mux, rt, func() (string, error) { return "tok", nil }, |
| + mailsubmit.SocketForwarder{Path: sock}, func(string, string) bool { return true }) |
| + |
| + for name, to := range map[string]string{"plain": "x@example.org", "list": "ana@example.org"} { |
| + raw, err := os.ReadFile(filepath.Join("testdata", "rastrillo-1104469-"+name+".eml")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := headerBlock(raw); err != nil { |
| + t.Fatalf("%s: headerBlock refused rastrillo's message: %v", name, err) |
| + } |
| + body, _ := json.Marshal(map[string]any{"from": "noreply@docs.example.com", "to": []string{to}, |
| + "raw": base64.StdEncoding.EncodeToString(raw)}) |
| + req := httptest.NewRequest(http.MethodPost, "/v1/mail", strings.NewReader(string(body))) |
| + req.Header.Set("Authorization", "Bearer tok") |
| + w := httptest.NewRecorder() |
| + mux.ServeHTTP(w, req) |
| + var ans mailsubmit.Answer |
| + _ = json.Unmarshal(w.Body.Bytes(), &ans) |
| + if w.Code != http.StatusOK || ans.MessageID == "" { |
| + t.Fatalf("%s: %d %s", name, w.Code, w.Body.String()) |
| + } |
| + in := h.ses.last() |
| + if got := in.Content.Raw.Data; !bytes.Equal(got, raw) { |
| + t.Fatalf("%s: SES got other bytes than rastrillo built:\n%q\nwant\n%q", name, got, raw) |
| + } |
| + if d := in.Destination.ToAddresses; len(d) != 1 || d[0] != to { |
| + t.Fatalf("%s: SES destination %q", name, d) |
| + } |
| + } |
| +} |
diff --git a/internal/mailer/rate.go b/internal/mailer/rate.go| index 4487819be..27126b67a 100644 |
| --- a/internal/mailer/rate.go |
| +++ b/internal/mailer/rate.go |
| @@ -7,8 +7,8 @@ import ( |
| ) |
| // The per-sender token bucket (design §5, Rate; plan gap G9): two messages |
| -// a second, a burst of twenty, per sender per box. Paul to confirm against |
| -// the deployment's SES send rate. |
| +// a second, a burst of twenty, per sender per box. Ruled by Paul, |
| +// 2026-11-13: confirmed. |
| const ( |
| Rate = 2 |
| Burst = 20 |
diff --git a/internal/mailer/send.go b/internal/mailer/send.go| index 3bc01148a..dd45cf285 100644 |
| --- a/internal/mailer/send.go |
| +++ b/internal/mailer/send.go |
| @@ -7,6 +7,7 @@ import ( |
| "fmt" |
| "net/http" |
| "net/mail" |
| + "os" |
| "strings" |
| "sync" |
| "time" |
| @@ -31,10 +32,15 @@ import ( |
| 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. |
| +// 1, Task 5 P2-3), so one app cannot take every slot on the box. A send |
| +// above it waits for a slot, up to senderWait and no longer than its |
| +// request's context (Fable P2-7: three concurrent sends from one app are |
| +// ordinary), and only then is answered 429 RATE, Retry-After 1. |
| const perSenderInFlight = 2 |
| +// senderWait is how long a send waits for one of its sender's slots. |
| +var senderWait = 5 * time.Second |
| + |
| // alertEvery is the least time between two key-load ALERT lines. |
| const alertEvery = time.Minute |
| @@ -73,17 +79,19 @@ type Mailer struct { |
| sem chan struct{} |
| 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] |
| + senderMu sync.Mutex |
| + inflight map[string]int // per account/app |
| + senderFree chan struct{} // closed, and replaced, as a sender slot frees |
| + lastAlert time.Time // under mu |
| + routes routeCache |
| + senders viewCache[mailwire.SenderView] |
| + domains viewCache[mailwire.DomainView] |
| mu sync.Mutex |
| ses SES |
| store release.Store |
| - broken error // the key file changed and did not reload: refuse everything |
| + proved release.Store // the store whose key armProbe has proved |
| + broken error // the key file changed and did not reload: refuse everything |
| } |
| // New builds a Mailer and its clients over the newest key. |
| @@ -93,7 +101,7 @@ func New(ctx context.Context, o Options) (*Mailer, error) { |
| } |
| 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), |
| - cred: &credState{}, inflight: map[string]int{}} |
| + cred: &credState{}, inflight: map[string]int{}, senderFree: make(chan struct{})} |
| if m.logf == nil { |
| m.logf = func(string, ...any) {} |
| } |
| @@ -168,7 +176,8 @@ func (m *Mailer) refreshKeys(ctx context.Context) error { |
| } |
| // 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. |
| +// built, the last AWS call did not reject the key itself, and AWS has |
| +// accepted the key once (armProbe): "armed" means the key works. |
| func (m *Mailer) Healthy() error { |
| if err := m.refreshKeys(context.Background()); err != nil { |
| return err |
| @@ -176,18 +185,59 @@ func (m *Mailer) Healthy() error { |
| if err := m.cred.current(); err != nil { |
| return fmt.Errorf("mailer: AWS refuses the mailer's key: %w", err) |
| } |
| + return m.armProbe() |
| +} |
| + |
| +// armProbeKey is a key under the pattern the mailer may read (an instance |
| +// record), which no app has: its read answers absent, or AccessDenied, |
| +// which the store reads as absent. |
| +const armProbeKey = "apps/carlos-mailer-probe/arm-probe/instances/arm-probe.invalid.json" |
| + |
| +// armProbe proves the key on the first health check after the clients are |
| +// built (Fable P2-8): one read of armProbeKey. Absent, or AccessDenied (an |
| +// authorisation answer, given only to a signature AWS accepted at a sane |
| +// clock), proves both the key and the clock; anything else (a bad key, a |
| +// skewed clock, no network) is not armed, and the next check reads again. |
| +func (m *Mailer) armProbe() error { |
| + st := m.storeNow() |
| + m.mu.Lock() |
| + proved := st != nil && m.proved == st |
| + m.mu.Unlock() |
| + if proved { |
| + return nil |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if _, _, err := st.Get(ctx, armProbeKey); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return fmt.Errorf("mailer: AWS has not accepted the mailer's key yet: %w", err) |
| + } |
| + m.mu.Lock() |
| + m.proved = st |
| + m.mu.Unlock() |
| 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 |
| +func (m *Mailer) takeSender(ctx context.Context, key string) bool { |
| + wait := time.NewTimer(senderWait) |
| + defer wait.Stop() |
| + for { |
| + m.senderMu.Lock() |
| + if m.inflight[key] < perSenderInFlight { |
| + m.inflight[key]++ |
| + m.senderMu.Unlock() |
| + return true |
| + } |
| + free := m.senderFree |
| + m.senderMu.Unlock() |
| + select { |
| + case <-free: |
| + case <-wait.C: |
| + return false |
| + case <-ctx.Done(): |
| + return false |
| + } |
| } |
| - m.inflight[key]++ |
| - return true |
| } |
| func (m *Mailer) giveSender(key string) { |
| @@ -196,6 +246,8 @@ func (m *Mailer) giveSender(key string) { |
| if m.inflight[key]--; m.inflight[key] <= 0 { |
| delete(m.inflight, key) |
| } |
| + close(m.senderFree) |
| + m.senderFree = make(chan struct{}) |
| } |
| // ServeHTTP is POST /v1/send: one stamped message from the agent, answered |
| @@ -219,7 +271,7 @@ func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| sender := req.Account + "/" + req.App |
| - if !m.takeSender(sender) { |
| + if !m.takeSender(r.Context(), sender) { |
| answer(w, http.StatusTooManyRequests, mailsubmit.Answer{Code: mailsubmit.CodeRate}, "1") |
| return |
| } |
diff --git a/internal/mailer/send_test.go b/internal/mailer/send_test.go| index 54afb7c22..b680073da 100644 |
| --- a/internal/mailer/send_test.go |
| +++ b/internal/mailer/send_test.go |
| @@ -432,6 +432,10 @@ func TestMailerPerSenderInFlight(t *testing.T) { |
| for h.ses.n() < perSenderInFlight && time.Now().Before(deadline) { |
| time.Sleep(5 * time.Millisecond) |
| } |
| + // A third send waits for a slot (Fable P2-7) and, none freeing within |
| + // senderWait, is a 429. |
| + defer func(d time.Duration) { senderWait = d }(senderWait) |
| + senderWait = 200 * time.Millisecond |
| got := h.sendWithin(h.request()) |
| h.want(got, 429, mailsubmit.CodeRate) |
| if got.retryAfter != "1" { |
| @@ -669,3 +673,69 @@ func TestMailerRefusesEncodedHeaderInjection(t *testing.T) { |
| t.Fatalf("a clean encoded name: %+v", got) |
| } |
| } |
| + |
| +// Fable P2-7: a third concurrent send from one app waits for one of its two |
| +// slots and goes out when one frees, rather than a 429. |
| +func TestMailerThirdSendWaitsForASlot(t *testing.T) { |
| + h := newHarness(t) |
| + 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) |
| + } |
| + third := make(chan sent, 1) |
| + go func() { third <- h.send(h.request()) }() |
| + select { |
| + case got := <-third: |
| + t.Fatalf("the third send answered %+v while both slots were held", got) |
| + case <-time.After(300 * time.Millisecond): |
| + } |
| + if h.ses.n() != perSenderInFlight { |
| + t.Fatalf("%d sends reached SES with both slots held", h.ses.n()) |
| + } |
| + close(h.ses.block) |
| + got := <-third |
| + h.want(got, 200, "") |
| + wg.Wait() |
| +} |
| + |
| +// Fable P2-8: armed means the key works. The first health check reads |
| +// armProbeKey once: anything but absent (or AccessDenied, read as absent) |
| +// is not armed, and the next check reads again; once proved, the key is |
| +// not read for again until the clients are rebuilt. |
| +func TestMailerHealthProvesTheKey(t *testing.T) { |
| + fs := &failingStore{prefix: "apps/carlos-mailer-probe/", err: errors.New("dial tcp: i/o timeout")} |
| + var probes int |
| + h := newHarness(t, func(cfg *harnessCfg) { |
| + cfg.store = func(s release.Store) release.Store { fs.Store = s; return &countingStore{failingStore: fs, n: &probes} } |
| + }) |
| + if err := h.m.Healthy(); err == nil { |
| + t.Fatal("healthy while AWS had not accepted the key") |
| + } |
| + fs.err = &smithy.GenericAPIError{Code: "AccessDenied"} // the key and the clock are good |
| + if err := h.m.Healthy(); err != nil { |
| + t.Fatalf("not healthy after AccessDenied: %v", err) |
| + } |
| + before := probes |
| + if err := h.m.Healthy(); err != nil || probes != before { |
| + t.Fatalf("a proved key was read for again (%d -> %d): %v", before, probes, err) |
| + } |
| +} |
| + |
| +// countingStore counts reads of armProbeKey. |
| +type countingStore struct { |
| + *failingStore |
| + n *int |
| +} |
| + |
| +func (c *countingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == armProbeKey { |
| + *c.n++ |
| + } |
| + return c.failingStore.Get(ctx, key) |
| +} |
diff --git a/internal/mailer/testdata/rastrillo-1104469-list.eml b/internal/mailer/testdata/rastrillo-1104469-list.eml| new file mode 100644 |
| index 000000000..aee755e7f |
| --- /dev/null |
| +++ b/internal/mailer/testdata/rastrillo-1104469-list.eml |
| @@ -0,0 +1,15 @@ |
| +From: "Docs" <noreply@docs.example.com> |
| +To: ana@example.org |
| +Subject: =?utf-8?q?Caf=C3=A9_notes_=E2=80=94_weekly?= |
| +Date: Sat, 14 Nov 2026 09:00:00 +0000 |
| +Message-Id: <notes-42@docs.example.com> |
| +Reply-To: "Docs Team" <team@docs.example.com> |
| +List-Id: <notes.docs.example.com> |
| +List-Unsubscribe: <https://docs.example.com/u?x=1&y=2> |
| +List-Unsubscribe-Post: List-Unsubscribe=One-Click |
| +MIME-Version: 1.0 |
| +Content-Type: text/plain; charset=utf-8 |
| +Content-Transfer-Encoding: quoted-printable |
| + |
| +Hola, =C2=BFqu=C3=A9 tal? A long line with accents: =C3=A0=C3=A9=C3=AE=C3= |
| +=B5=C3=BC and an equals sign =3D here. |
diff --git a/internal/mailer/testdata/rastrillo-1104469-plain.eml b/internal/mailer/testdata/rastrillo-1104469-plain.eml| new file mode 100644 |
| index 000000000..72204dd25 |
| --- /dev/null |
| +++ b/internal/mailer/testdata/rastrillo-1104469-plain.eml |
| @@ -0,0 +1,9 @@ |
| +From: "Docs" <noreply@docs.example.com> |
| +To: x@example.org |
| +Subject: Your sign-in link |
| +Date: Sat, 14 Nov 2026 09:00:00 +0000 |
| +MIME-Version: 1.0 |
| +Content-Type: text/plain; charset=utf-8 |
| +Content-Transfer-Encoding: quoted-printable |
| + |
| +Open https://docs.example.com/signin?t=3Dabc within 15 minutes. |