oficina / docs Public

Send sign-in mail after the response, so its timing says nothing

Docs already chose the ceremony by domain and dropped mail to refused
addresses (admissionMailer), but it did that inside the request: a
permitted address waited for SMTP before its ?sent=1 and a refused one
did not. Astra measured the same shape on Slides at 252 ms against
0.35 ms (oficina/slides #20), forced posts included.

rauth's Mailer is now mailQueue (the queue Slides, Sheets, Calendar and
Calls carry): Send queues and returns at once without I/O, one worker
asks the allowlist (listAdmits: a failed grant lookup refuses, as
before) and only then sends, failures are logged and never answered,
drops are counted and logged by the worker, a panicking mailer is
recovered per message, and Close drains within a deadline, cancelling
what is left, before it closes the database the allowlist reads.

Tests: TestSigninNeverWaitsForTheMailer fails on origin/main; the queue
tests fail with each defect put back; TestAppCloseStopsTheMailWorker;
TestAdmissionMailerFailsClosed now drives the queue. Tests that read the
recorder wait for the queue first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ec851203b9e702fa1abe7453df650281cae9c9f0 parent d72b1d0
10 files changed, +524 −23
  • internal/docs/admission_test.go +4 −1
  • internal/docs/app.go +20 −3
  • internal/docs/auth.go +15 −18
  • internal/docs/auth_allowlist_test.go +2 −1
  • internal/docs/auth_keymail_test.go +2 −0
  • internal/docs/home_router_integration_test.go +4 −0
  • internal/docs/mailqueue.go +191 −0
  • internal/docs/mailqueue_test.go +180 −0
  • internal/docs/signin_timing_test.go +105 −0
  • internal/docs/testing.go +1 −0

CI passed — run details

diff --git a/internal/docs/admission_test.go b/internal/docs/admission_test.go
index 0620ac5..e7af3d0 100644
--- a/internal/docs/admission_test.go
+++ b/internal/docs/admission_test.go
@@ -3,6 +3,7 @@ package docs
import (
"context"
"errors"
+ "log/slog"
"net/http"
"net/http/httptest"
"testing"
@@ -152,12 +153,14 @@ func TestAdmissionMailerFailsClosed(t *testing.T) {
granted: func(string) (bool, error) { return false, errors.New("database is stalled") },
}
recorder := &recordingMailer{next: loggingMailerStub{}}
- sender := admissionMailer{next: recorder, list: list}
+ sender := newMailQueue(recorder, listAdmits(list), nil, slog.New(slog.DiscardHandler))
+ t.Cleanup(sender.close)
for _, address := range []string{"mallory@example.com", "alice@example.com"} {
if err := sender.Send(t.Context(), address, "subject", "body"); err != nil {
t.Fatal(err)
}
}
+ sender.wait()
if recorder.sends != 1 || recorder.lastTo != "alice@example.com" {
t.Fatalf("delivery count=%d recipient=%q", recorder.sends, recorder.lastTo)
}
diff --git a/internal/docs/app.go b/internal/docs/app.go
index c834041..c122cff 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -153,7 +153,8 @@ type Config struct {
// normalizeAddress) — a real config file has spaces after its
// commas, and people type capitals into an email field.
//
- // admissionMailer restricts email delivery, and rauth.Config.Authorize
+ // The sign-in mail queue restricts email delivery (mailqueue.go,
+ // listAdmits), and rauth.Config.Authorize
// checks verified identities before minting a session. Classification
// does not depend on admission, so an OAuth start cannot reveal membership.
//
@@ -280,6 +281,7 @@ type App struct {
store *Store
handlers *handlers
mailRecorder *recordingMailer // nil outside development; see auth.go
+ signinMail *mailQueue // sign-in links, sent after the response
}
// BootSchema is everything New applies at boot, in apply order.
@@ -460,7 +462,17 @@ func New(cfg Config) (*App, error) {
return nil, fmt.Errorf("docs: build renderer: %w", err)
}
- authPlugin, err := newAuthPlugin(cfg, d.Writer(), instanceKey, mailer, list, logger)
+ // Sign-in links go out after the response, from a worker that asks
+ // the allowlist first (mailqueue.go). Closed by Close, or below if
+ // New fails after this point.
+ signinMail := newMailQueue(mailer, listAdmits(list), nil, logger)
+ built := false
+ defer func() {
+ if !built {
+ signinMail.close()
+ }
+ }()
+ authPlugin, err := newAuthPlugin(cfg, d.Writer(), instanceKey, signinMail, list, logger)
if err != nil {
rt.Close(context.Background())
d.Close()
@@ -697,7 +709,8 @@ func New(cfg Config) (*App, error) {
mux := http.NewServeMux()
mux.Handle("/", r)
- return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder}, nil
+ built = true
+ return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder, signinMail: signinMail}, nil
}
// Store returns the app's document store — models.go's Document,
@@ -718,6 +731,10 @@ func (a *App) Handler() *http.ServeMux { return a.mux }
// module. NewForTest registers this as a t.Cleanup.
func (a *App) Close() error {
var errs []error
+ // First, while the database the allowlist reads is still open.
+ if a.signinMail != nil {
+ a.signinMail.close()
+ }
if a.core != nil {
if err := a.core.Close(context.Background()); err != nil {
errs = append(errs, err)
diff --git a/internal/docs/auth.go b/internal/docs/auth.go
index fa24870..f7e6e48 100644
--- a/internal/docs/auth.go
+++ b/internal/docs/auth.go
@@ -99,7 +99,7 @@ type recordingMailer struct {
mu sync.Mutex
next mail.Sender
// lastTo is recorded alongside lastBody, and it is not decoration.
- // admissionMailer leaves a refused address with exactly the 303 ?sent=1 a
+ // The mail queue leaves a refused address with exactly the 303 ?sent=1 a
// real one gets — deliberately, so the endpoint is not a membership
// oracle — so a caller that reads only lastBody cannot tell "a link
// was mailed to this address" from "somebody else's link is still
@@ -277,23 +277,20 @@ func resolveAllowlist(cfg Config) (allowlist, error) {
return allowlist{}, fmt.Errorf("docs: $DOCS_ALLOWED_ADDRESSES is empty and Env is %q, not %q — refusing to start with no allowlist configured: an instance-per-team app admitting nobody would look identical to one working correctly (see resolveAllowlist's own doc comment), so this refuses rather than boots quietly wrong; set $DOCS_ALLOWED_ADDRESSES to this team's address(es)", cfg.Env, "development")
}
-// admissionMailer restricts delivery without exposing membership through the
-// choice of sign-in ceremony. All addresses reach classification and the same
-// rate limits; only admitted addresses receive mail. Callback admission remains
-// authoritative, including for tokens minted before an address was removed.
-// The underlying flow stores an expiring token before Send; a suppressed token
-// is never delivered. A failed grant lookup suppresses delivery too.
-type admissionMailer struct {
- next mail.Sender
- list allowlist
-}
-
-func (m admissionMailer) Send(ctx context.Context, to, subject, body string) error {
- admitted, err := m.list.allows(to)
- if err != nil || !admitted {
- return nil
+// listAdmits is the sign-in mail queue's admission check (mailqueue.go):
+// list.allows, with a failed grant lookup refusing, as a refusal always
+// has here. It runs on the queue's worker, after the response: every
+// address reaches classification, the same rate limits and the same
+// enqueue, so neither POST /signin's answer nor its timing says who is
+// admitted (Astra on oficina/slides #20: a send inside the request made
+// a permitted address wait for SMTP, 252 ms against 0.35 ms). Callback
+// admission remains authoritative, including for tokens minted before
+// an address was removed; a token never delivered is never redeemed.
+func listAdmits(list allowlist) func(string) bool {
+ return func(to string) bool {
+ admitted, err := list.allows(to)
+ return err == nil && admitted
}
- return m.next.Send(ctx, to, subject, body)
}
// requireAdmission re-asks the front-door question on every request, and
@@ -416,7 +413,7 @@ func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.S
DB: writer,
Origin: cfg.Origin,
InstanceKey: instanceKey,
- Mailer: admissionMailer{next: mailer, list: list},
+ Mailer: mailer, // the sign-in mail queue (mailqueue.go)
Authorize: list.admits,
Logger: logger,
Subject: chrome.EmailSubject("Docs"),
diff --git a/internal/docs/auth_allowlist_test.go b/internal/docs/auth_allowlist_test.go
index 6b6c943..118a53d 100644
--- a/internal/docs/auth_allowlist_test.go
+++ b/internal/docs/auth_allowlist_test.go
@@ -59,7 +59,7 @@ func newAllowlistedTestApp(t *testing.T, allowed string) *App {
// uses to skip signin's own keymail classification (which would
// otherwise make a real outbound DNS/HTTPS call per address, per
// signin's own README, entirely beside the point of what these tests
-// check). force=1 selects email but does not bypass admissionMailer.
+// check). force=1 selects email but does not bypass the mail queue's admission check.
func postSignin(app *App, address string) *httptest.ResponseRecorder {
form := url.Values{"address": {address}, "force": {"1"}}
req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode()))
@@ -77,6 +77,7 @@ func postSignin(app *App, address string) *httptest.ResponseRecorder {
// back), which a test proving the ABSENCE of a send cannot use: there
// is no link to find in an empty body.
func lastMailBody(app *App) string {
+ app.signinMail.wait() // links are sent after the response
app.mailRecorder.mu.Lock()
defer app.mailRecorder.mu.Unlock()
return app.mailRecorder.lastBody
diff --git a/internal/docs/auth_keymail_test.go b/internal/docs/auth_keymail_test.go
index e360963..769897c 100644
--- a/internal/docs/auth_keymail_test.go
+++ b/internal/docs/auth_keymail_test.go
@@ -172,6 +172,7 @@ func keymailOAuthChild(t *testing.T) {
if rec.Code != 303 || rec.Header().Get("Location") != "/signin?sent=1" {
t.Fatalf("mail start: %d %s", rec.Code, rec.Header().Get("Location"))
}
+ app.signinMail.wait()
app.mailRecorder.mu.Lock()
sent := app.mailRecorder.sends
app.mailRecorder.mu.Unlock()
@@ -229,6 +230,7 @@ func keymailOAuthChild(t *testing.T) {
}
}
}
+ app.signinMail.wait()
app.mailRecorder.mu.Lock()
sent := app.mailRecorder.sends
app.mailRecorder.mu.Unlock()
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go
index 399903a..d5e3772 100644
--- a/internal/docs/home_router_integration_test.go
+++ b/internal/docs/home_router_integration_test.go
@@ -97,11 +97,15 @@ func routerRedirect(t *testing.T, rec *httptest.ResponseRecorder, want string) s
}
func (b *routerBrowser) localLink(t *testing.T, address string) string {
t.Helper()
+ b.f.app.signinMail.wait()
+ b.f.app.mailRecorder.mu.Lock()
before := b.f.app.mailRecorder.sends
+ b.f.app.mailRecorder.mu.Unlock()
rec := b.do("POST", "/signin", url.Values{"address": {address}, "force": {"1"}}.Encode())
if rec.Code != 303 || !strings.Contains(rec.Header().Get("Location"), "sent=1") {
t.Fatal("local mail begin failed", rec.Code)
}
+ b.f.app.signinMail.wait() // the link is sent after the response
b.f.app.mailRecorder.mu.Lock()
to, body, after := b.f.app.mailRecorder.lastTo, b.f.app.mailRecorder.lastBody, b.f.app.mailRecorder.sends
b.f.app.mailRecorder.mu.Unlock()
diff --git a/internal/docs/mailqueue.go b/internal/docs/mailqueue.go
new file mode 100644
index 0000000..d9e1cc5
--- /dev/null
+++ b/internal/docs/mailqueue.go
@@ -0,0 +1,191 @@
+package docs
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/mail"
+)
+
+// mailQueue is the sign-in mailer the auth plugin is given: Send queues
+// the link and returns at once, and one background worker decides
+// whether the address may have it and only then talks to SMTP.
+//
+// Both halves are the no-oracle guarantee, measured rather than
+// reasoned about. When the send ran inside the request, a permitted
+// address waited for the SMTP round trip before its `303 ?sent=1` and a
+// denied one did not: 252 ms against 0.35 ms (Astra on oficina/slides
+// #20). A response time is an answer like any other. So POST /signin
+// does the same synchronous work for every address — the auth plugin's
+// budgets, its link row, this enqueue — and the one admission-dependent
+// step, the send, happens after the response, where nobody can time it.
+//
+// The request path is Send, and Send does no I/O and never blocks: not
+// a send, not an admission check, not even a log line. Every address's
+// link is queued, permitted or not, so how full the queue is never
+// depends on admission either; the worker decides afterwards. A full
+// queue drops the link and counts it in an atomic; the worker logs the
+// count when it next runs. The person is answered exactly as when the
+// queue is empty, because a different answer for a full queue would be
+// one more thing to read. (Astra on #20, round 2.)
+//
+// The worker survives a panic in the mailer: it recovers per message,
+// logs, and keeps draining. Delivery failures are logged, never
+// surfaced: a failure only a permitted address can reach is the oracle
+// again.
+//
+// close drains what is queued within drainTimeout. Past it, the send
+// in flight is cancelled through its context, everything still queued
+// is abandoned with a log line, and close waits a short grace for the
+// worker to stop. A mailer that ignores its context is the only way a
+// worker outlives close, and that is logged too.
+type mailQueue struct {
+ next mail.Sender
+ admits func(to string) bool
+ // gate, when set, is read off the request's context at enqueue time
+ // and travels with the link; the worker sends only if it said yes.
+ gate func(context.Context) bool
+ logger *slog.Logger
+
+ drainTimeout time.Duration
+ sendTimeout time.Duration
+
+ mu sync.RWMutex // held for reading by Send, for writing by close
+ closed bool
+ jobs chan mailJob
+ dropped atomic.Int64
+ pending sync.WaitGroup
+
+ ctx context.Context // cancelled when close gives up waiting
+ cancel context.CancelFunc
+ done chan struct{}
+}
+
+type mailJob struct {
+ to, subject, body string
+ gated bool
+}
+
+const (
+ mailQueueDepth = 64
+ mailSendTimeout = time.Minute
+ mailDrainTimeout = 30 * time.Second
+ mailAbandonGrace = 5 * time.Second
+)
+
+func newMailQueue(next mail.Sender, admits func(string) bool, gate func(context.Context) bool, logger *slog.Logger) *mailQueue {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ q := &mailQueue{next: next, admits: admits, gate: gate, logger: logger,
+ drainTimeout: mailDrainTimeout, sendTimeout: mailSendTimeout,
+ jobs: make(chan mailJob, mailQueueDepth), ctx: ctx, cancel: cancel,
+ done: make(chan struct{})}
+ go q.run()
+ return q
+}
+
+// Send queues one link. It never blocks, never does I/O and never
+// fails: the request that called it answers the same way whatever
+// happens next.
+func (q *mailQueue) Send(ctx context.Context, to, subject, body string) error {
+ job := mailJob{to: to, subject: subject, body: body, gated: true}
+ if q.gate != nil {
+ job.gated = q.gate(ctx)
+ }
+ q.mu.RLock()
+ defer q.mu.RUnlock()
+ if q.closed {
+ q.dropped.Add(1)
+ return nil
+ }
+ q.pending.Add(1)
+ select {
+ case q.jobs <- job:
+ default:
+ q.pending.Done()
+ q.dropped.Add(1)
+ }
+ return nil
+}
+
+func (q *mailQueue) run() {
+ defer close(q.done)
+ abandoned := 0
+ for job := range q.jobs {
+ q.reportDrops()
+ if q.ctx.Err() != nil {
+ abandoned++
+ } else {
+ q.deliver(job)
+ }
+ q.pending.Done()
+ }
+ q.reportDrops()
+ if abandoned > 0 {
+ q.logger.Error("docs: sign-in links abandoned at shutdown", "count", abandoned)
+ }
+}
+
+// reportDrops logs the links Send had to drop since the last report.
+// Here, on the worker, so the request path never writes a log line.
+func (q *mailQueue) reportDrops() {
+ if n := q.dropped.Swap(0); n > 0 {
+ q.logger.Error("docs: sign-in mail queue full; links dropped", "count", n)
+ }
+}
+
+// deliver sends one link if it may go. A panic in the admission check
+// or the mailer is this message's failure, not the process's.
+func (q *mailQueue) deliver(job mailJob) {
+ defer func() {
+ if p := recover(); p != nil {
+ q.logger.Error("docs: sign-in mail worker recovered from a panic", "panic", fmt.Sprint(p))
+ }
+ }()
+ if !job.gated || !q.admits(job.to) {
+ // Not admitted: the link the auth plugin stored is never
+ // delivered, so it is never redeemed. No address in the log.
+ return
+ }
+ ctx, cancel := context.WithTimeout(q.ctx, q.sendTimeout)
+ defer cancel()
+ if err := q.next.Send(ctx, job.to, job.subject, job.body); err != nil {
+ q.logger.Error("docs: send sign-in link", "err", err)
+ }
+}
+
+// wait blocks until every link queued so far has been sent or refused.
+// Tests use it to read the mailer afterwards.
+func (q *mailQueue) wait() { q.pending.Wait() }
+
+// close stops taking links and drains what is queued, within
+// drainTimeout; then it cancels, abandons the rest, and stops the
+// worker (see the type's comment).
+func (q *mailQueue) close() {
+ q.mu.Lock()
+ if q.closed {
+ q.mu.Unlock()
+ return
+ }
+ q.closed = true
+ close(q.jobs)
+ q.mu.Unlock()
+ defer q.cancel()
+ select {
+ case <-q.done:
+ return
+ case <-time.After(q.drainTimeout):
+ }
+ q.cancel()
+ select {
+ case <-q.done:
+ case <-time.After(mailAbandonGrace):
+ q.logger.Error("docs: sign-in mail worker ignored cancellation; left running")
+ }
+}
diff --git a/internal/docs/mailqueue_test.go b/internal/docs/mailqueue_test.go
new file mode 100644
index 0000000..400bd1d
--- /dev/null
+++ b/internal/docs/mailqueue_test.go
@@ -0,0 +1,180 @@
+package docs
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// stuckHandler is a slog handler whose every write blocks until release
+// is closed: a log sink that has stalled, as a full pipe does. It
+// remembers what it was finally allowed to write.
+type stuckHandler struct {
+ release chan struct{}
+ mu *sync.Mutex
+ msgs *[]string
+}
+
+func (h stuckHandler) Enabled(context.Context, slog.Level) bool { return true }
+func (h stuckHandler) Handle(_ context.Context, r slog.Record) error {
+ <-h.release
+ h.mu.Lock()
+ *h.msgs = append(*h.msgs, r.Message)
+ h.mu.Unlock()
+ return nil
+}
+func (h stuckHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
+func (h stuckHandler) WithGroup(string) slog.Handler { return h }
+
+// funcSender adapts a function to mail.Sender.
+type funcSender func(ctx context.Context, to string) error
+
+func (f funcSender) Send(ctx context.Context, to, _, _ string) error { return f(ctx, to) }
+
+func everyone(string) bool { return true }
+
+// TestMailQueueSendNeverBlocksWhenFull: Send is the request path, so it
+// may not block or do I/O even when the queue is full — not even to log
+// the drop (Astra on oficina/slides #20, round 2, P1: a "queue full" log
+// line on a stalled sink held the request, and saturation is
+// admission-dependent). The worker is stuck on its first link and the
+// log sink is stuck too; twice the queue's depth of Sends must still
+// return at once, and the drops are logged by the worker afterwards.
+func TestMailQueueSendNeverBlocksWhenFull(t *testing.T) {
+ release := make(chan struct{})
+ var once sync.Once
+ free := func() { once.Do(func() { close(release) }) }
+ stuck := funcSender(func(ctx context.Context, _ string) error {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return nil
+ })
+ var mu sync.Mutex
+ var msgs []string
+ q := newMailQueue(stuck, everyone, nil, slog.New(stuckHandler{release, &mu, &msgs}))
+ t.Cleanup(func() { free(); q.close() })
+
+ done := make(chan struct{})
+ go func() {
+ for i := 0; i < 2*mailQueueDepth; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("p%d@example.test", i), "s", "b")
+ }
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ free()
+ <-done
+ t.Fatal("Send blocked with the queue full: the request path waited on the queue or the log")
+ }
+ // The drops are the worker's to log, once it is free to.
+ free()
+ q.close()
+ mu.Lock()
+ defer mu.Unlock()
+ for _, m := range msgs {
+ if strings.Contains(m, "links dropped") {
+ return
+ }
+ }
+ t.Fatalf("no drop was logged with twice the queue's depth sent; the log has %q", msgs)
+}
+
+// TestMailQueueQueuesEveryAddress: the queue's fill level must not
+// depend on admission, so Send queues a refused address's link exactly
+// as it queues a permitted one; only the worker asks.
+func TestMailQueueQueuesEveryAddress(t *testing.T) {
+ release := make(chan struct{})
+ stuck := funcSender(func(ctx context.Context, _ string) error {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return nil
+ })
+ var asked sync.Map
+ admits := func(to string) bool { asked.Store(to, true); return to == "first@example.test" }
+ q := newMailQueue(stuck, admits, nil, slog.New(slog.DiscardHandler))
+ t.Cleanup(func() { close(release); q.close() })
+ _ = q.Send(context.Background(), "first@example.test", "s", "b")
+ deadline := time.Now().Add(2 * time.Second)
+ for _, ok := asked.Load("first@example.test"); !ok && time.Now().Before(deadline); _, ok = asked.Load("first@example.test") {
+ time.Sleep(5 * time.Millisecond)
+ }
+ for i := 0; i < 5; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("refused%d@example.test", i), "s", "b")
+ }
+ if got := len(q.jobs); got != 5 {
+ t.Fatalf("queued %d refused links, want all 5: fill level must not depend on admission", got)
+ }
+}
+
+// TestMailQueueSurvivesAPanic: a panic in the mailer is that message's
+// failure; the worker recovers, logs, and sends the next one (Astra,
+// round 2, P2).
+func TestMailQueueSurvivesAPanic(t *testing.T) {
+ var mu sync.Mutex
+ var sent []string
+ calls := 0
+ s := funcSender(func(_ context.Context, to string) error {
+ mu.Lock()
+ defer mu.Unlock()
+ calls++
+ if calls == 1 {
+ panic("mailer exploded")
+ }
+ sent = append(sent, to)
+ return nil
+ })
+ q := newMailQueue(s, everyone, nil, slog.New(slog.DiscardHandler))
+ t.Cleanup(q.close)
+ _ = q.Send(context.Background(), "first@example.test", "s", "b")
+ _ = q.Send(context.Background(), "second@example.test", "s", "b")
+ q.wait()
+ mu.Lock()
+ defer mu.Unlock()
+ if len(sent) != 1 || sent[0] != "second@example.test" {
+ t.Fatalf("sent = %v, want the second link after the first panicked", sent)
+ }
+}
+
+// TestMailQueueCloseIsBoundedAndStopsTheWorker: close drains within its
+// deadline, then cancels the send in flight, abandons the rest, and the
+// worker is gone — no goroutine outlives close (Astra, round 2, P2).
+func TestMailQueueCloseIsBoundedAndStopsTheWorker(t *testing.T) {
+ baseline := runtime.NumGoroutine()
+ honours := funcSender(func(ctx context.Context, _ string) error {
+ <-ctx.Done() // a relay that never answers, but obeys cancellation
+ return ctx.Err()
+ })
+ q := newMailQueue(honours, everyone, nil, slog.New(slog.DiscardHandler))
+ q.drainTimeout = 50 * time.Millisecond
+ for i := 0; i < 3; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("p%d@example.test", i), "s", "b")
+ }
+ start := time.Now()
+ q.close()
+ if took := time.Since(start); took > 2*time.Second {
+ t.Fatalf("close took %v, want about its 50ms deadline", took)
+ }
+ select {
+ case <-q.done:
+ default:
+ t.Fatal("the worker was still running after close")
+ }
+ deadline := time.Now().Add(time.Second)
+ for runtime.NumGoroutine() > baseline && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if n := runtime.NumGoroutine(); n > baseline {
+ t.Fatalf("%d goroutines after close, %d before: the queue leaked", n, baseline)
+ }
+}
diff --git a/internal/docs/signin_timing_test.go b/internal/docs/signin_timing_test.go
new file mode 100644
index 0000000..bf2d2be
--- /dev/null
+++ b/internal/docs/signin_timing_test.go
@@ -0,0 +1,105 @@
+package docs
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// blockingMailer holds every Send until release is closed — an SMTP
+// relay that takes as long as the test likes.
+type blockingMailer struct {
+ release chan struct{}
+ mu sync.Mutex
+ to []string
+}
+
+func (m *blockingMailer) Send(_ context.Context, to, _, _ string) error {
+ <-m.release
+ m.mu.Lock()
+ m.to = append(m.to, to)
+ m.mu.Unlock()
+ return nil
+}
+
+func (m *blockingMailer) sent() []string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return append([]string(nil), m.to...)
+}
+
+// TestSigninNeverWaitsForTheMailer: when the send ran inside the
+// request (admissionMailer), a permitted address waited for SMTP before
+// its ?sent=1 and a refused one did not — Astra measured 252 ms against
+// 0.35 ms on Slides, which had the same shape — so the allowlist was
+// readable off a stopwatch. With the mailer blocked, every POST —
+// permitted, refused, and both with force=1 — must answer, and the
+// permitted links must then go out.
+func TestSigninNeverWaitsForTheMailer(t *testing.T) {
+ bm := &blockingMailer{release: make(chan struct{})}
+ app, err := NewForTestWith(t, Config{AllowedAddresses: "member@example.test", Mailer: bm})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var once sync.Once
+ free := func() { once.Do(func() { close(bm.release) }) }
+ t.Cleanup(free) // before the app's Close, which drains the queue
+
+ for _, form := range []url.Values{
+ {"address": {"member@example.test"}},
+ {"address": {"outsider@example.test"}},
+ {"address": {"member@example.test"}, "force": {"1"}},
+ {"address": {"outsider@example.test"}, "force": {"1"}},
+ } {
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ rec := httptest.NewRecorder()
+ app.Handler().ServeHTTP(rec, req)
+ done <- rec
+ }()
+ select {
+ case rec := <-done:
+ if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "sent=1") {
+ t.Errorf("POST %v: %d %q, want 303 ?sent=1", form, rec.Code, rec.Header().Get("Location"))
+ }
+ case <-time.After(2 * time.Second):
+ t.Errorf("POST %v waited on the mailer: the response time says the address is permitted", form)
+ free()
+ <-done
+ }
+ }
+
+ free()
+ deadline := time.Now().Add(5 * time.Second)
+ for len(bm.sent()) < 2 && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ time.Sleep(50 * time.Millisecond)
+ if got := bm.sent(); len(got) != 2 || got[0] != "member@example.test" || got[1] != "member@example.test" {
+ t.Fatalf("mail sent = %v, want two links, both to member@example.test", got)
+ }
+}
+
+// TestAppCloseStopsTheMailWorker: the app owns its queue, and Close
+// stops its worker.
+func TestAppCloseStopsTheMailWorker(t *testing.T) {
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := app.signinMail
+ _ = app.Close()
+ select {
+ case <-q.done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("the sign-in mail worker was still running after App.Close")
+ }
+}
diff --git a/internal/docs/testing.go b/internal/docs/testing.go
index 61104db..704e04c 100644
--- a/internal/docs/testing.go
+++ b/internal/docs/testing.go
@@ -118,6 +118,7 @@ func (a *App) TestSignIn(t *testing.T, address string) (string, error) {
return "", fmt.Errorf("docs: TestSignIn: POST /signin redirected to %q, want a %q outcome", loc, "?sent=1")
}
+ a.signinMail.wait() // the link is sent after the response (mailqueue.go)
a.mailRecorder.mu.Lock()
to, body, after := a.mailRecorder.lastTo, a.mailRecorder.lastBody, a.mailRecorder.sends
a.mailRecorder.mu.Unlock()