Mail queue rounds 3-4, and a refused Keymail sign-in gets the door, not bare text
- The queue now matches Slides' after Astra's rounds 3 and 4: only a log pump writes to the logger, the worker and close use logf (never blocks), close never waits on the pump, and the limit is stated: a write blocked inside the logger can only finish or die with the process. TestMailQueueCloseIsBoundedWithAStalledLogger asserts that with the sink still stalled, then after release. TestMain fails the run if a queue worker or pump outlives the tests. - Docs already sent every Keymail address to Keymail, so a non-admitted one that Keymail verified hit rastrillo's bare-text 403. doorOnRefusal renders the door with "That address can't sign in to Docs" in the refusal's own 403, marked through the request context, never a query. The OAuth integration test's refused case now requires it, and that /signin?err=refused says nothing; it failed before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+311
−20
internal/docs/app.go+2 −2internal/docs/auth.go+6 −0internal/docs/auth_keymail_test.go+13 −0internal/docs/auth_navigation.go+74 −0internal/docs/mailqueue.go+104 −12internal/docs/mailqueue_test.go+111 −6internal/docs/render.go+1 −0
CI passed — run details
diff --git a/internal/docs/app.go b/internal/docs/app.go| index c122cff..548e0b7 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -603,8 +603,8 @@ func New(cfg Config) (*App, error) { |
| // the menu was open cannot turn the click into a sign-in loop. |
| r.Post("/appearance", chrome.HandleAppearance) |
| r.Post("/signin", h.beginSignin(authPlugin.Begin)) |
| - r.Get("/auth/callback", localAuthGuard(home, authPlugin.Callback)) |
| - r.Get("/auth/verify", localAuthGuard(home, authPlugin.Verify)) |
| + r.Get("/auth/callback", localAuthGuard(home, doorOnRefusal(authPlugin.Callback, h.signin))) |
| + r.Get("/auth/verify", localAuthGuard(home, doorOnRefusal(authPlugin.Verify, h.signin))) |
| // The published document, and the only route here no session guards. |
| // It is authorized by the token in its own path (links.go) rather |
| // than by who is asking — which is what a capability is, and why it |
diff --git a/internal/docs/auth.go b/internal/docs/auth.go| index f7e6e48..9661838 100644 |
| --- a/internal/docs/auth.go |
| +++ b/internal/docs/auth.go |
| @@ -512,6 +512,12 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| default: |
| form.Error = rastrillo.T(r, "docs.signin.error.unknown") |
| } |
| + if refusedHere(r) { |
| + // Keymail or a link verified the address and the allowlist |
| + // does not hold it, in this very response (doorOnRefusal). |
| + // Never from the query. The form is the way on. |
| + form.Error = rastrillo.T(r, "docs.signin.error.refused") |
| + } |
| data.Form = form |
| } |
| data.Frame = h.frame(r, frameOptions{titleParts: []string{page}, signinPage: true}) |
diff --git a/internal/docs/auth_keymail_test.go b/internal/docs/auth_keymail_test.go| index 769897c..ee9883c 100644 |
| --- a/internal/docs/auth_keymail_test.go |
| +++ b/internal/docs/auth_keymail_test.go |
| @@ -214,6 +214,19 @@ func keymailOAuthChild(t *testing.T) { |
| } |
| callback := request("GET", "/auth/callback?"+url.Values{"state": {state}, "code": {"one-code"}}.Encode(), "") |
| allowed := tc.admitted && tc.returned == "" && !tc.badState && !tc.badPKCE |
| + if !tc.admitted && tc.returned == "" && !tc.badState && !tc.badPKCE { |
| + // A verified address the allowlist refuses gets the door, |
| + // rendered in the refusal's own 403 — not rastrillo's bare |
| + // text, and not a query anybody could type. |
| + body := callback.Body.String() |
| + if callback.Code != http.StatusForbidden || !strings.Contains(body, `name="address"`) || !strings.Contains(body, "docs.signin.error.refused") && !strings.Contains(body, "can’t sign in to Docs") { |
| + t.Fatalf("refused OAuth: %d, want the door with the refusal in a 403:\n%s", callback.Code, body) |
| + } |
| + spoof := request("GET", "/signin?err=refused", "") |
| + if strings.Contains(spoof.Body.String(), "can’t sign in to Docs") { |
| + t.Fatal("anybody can show the refusal by visiting /signin?err=refused") |
| + } |
| + } |
| home := request("GET", "/", "") |
| if allowed { |
| if callback.Code != 303 || home.Code != 200 { |
diff --git a/internal/docs/auth_navigation.go b/internal/docs/auth_navigation.go| index b2e828a..3cb31d6 100644 |
| --- a/internal/docs/auth_navigation.go |
| +++ b/internal/docs/auth_navigation.go |
| @@ -5,6 +5,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/estilo.git/sky" |
| "bytes" |
| + "context" |
| "net/http" |
| "net/url" |
| "strings" |
| @@ -94,3 +95,76 @@ func (w *signinResponse) Write(p []byte) (int, error) { |
| } |
| return w.body.Write(p) |
| } |
| + |
| +// authRefusal is the bare-text body rastrillo/auth's admit() writes, |
| +// with a 403, when a verified address is not admitted. rastrillo at the |
| +// version pinned here has no hook to render anything else, so |
| +// doorOnRefusal recognises this exact answer; |
| +// TestKeymailOAuthActualIntegration pins it, so a bump that changes the |
| +// sentence fails loudly. |
| +const authRefusal = "This address is verified but not admitted here." |
| + |
| +// doorOnRefusal wraps rastrillo's Callback and Verify, the handlers that |
| +// end in admission, and turns its bare-text refusal into the sign-in |
| +// door, rendered in the refusal's own 403 by door (h.signin) with the |
| +// refusal marked on the request context (refusedHere). Every other |
| +// answer, cookies included, passes through untouched. |
| +// |
| +// Rendered, not redirected to ?err=refused: a query parameter is |
| +// something anybody can type, and the sentence means "you proved this |
| +// address and it is not admitted". Only someone who has just verified |
| +// the address reaches it, so it is no oracle. Remove it when rastrillo |
| +// has a refusal hook (feat/auth-refused-hook) and the pin is bumped. |
| +func doorOnRefusal(next, door http.HandlerFunc) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + rec := &signinResponse{header: make(http.Header)} |
| + next(rec, r) |
| + if rec.status == http.StatusForbidden && strings.TrimSpace(rec.body.String()) == authRefusal { |
| + for _, c := range rec.header.Values("Set-Cookie") { |
| + w.Header().Add("Set-Cookie", c) |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + door(&forcedStatus{ResponseWriter: w, status: http.StatusForbidden}, |
| + r.WithContext(context.WithValue(r.Context(), refusedKey{}, true))) |
| + return |
| + } |
| + for name, values := range rec.header { |
| + for _, v := range values { |
| + w.Header().Add(name, v) |
| + } |
| + } |
| + if rec.status == 0 { |
| + rec.status = http.StatusOK |
| + } |
| + w.WriteHeader(rec.status) |
| + _, _ = w.Write(rec.body.Bytes()) |
| + } |
| +} |
| + |
| +// refusedKey marks a request doorOnRefusal is answering with the door. |
| +type refusedKey struct{} |
| + |
| +// refusedHere reports whether r is a refusal doorOnRefusal is rendering. |
| +func refusedHere(r *http.Request) bool { |
| + v, _ := r.Context().Value(refusedKey{}).(bool) |
| + return v |
| +} |
| + |
| +// forcedStatus answers with status whatever status the page writes. |
| +type forcedStatus struct { |
| + http.ResponseWriter |
| + status int |
| + wrote bool |
| +} |
| + |
| +func (f *forcedStatus) WriteHeader(int) { |
| + if !f.wrote { |
| + f.wrote = true |
| + f.ResponseWriter.WriteHeader(f.status) |
| + } |
| +} |
| + |
| +func (f *forcedStatus) Write(p []byte) (int, error) { |
| + f.WriteHeader(f.status) |
| + return f.ResponseWriter.Write(p) |
| +} |
diff --git a/internal/docs/mailqueue.go b/internal/docs/mailqueue.go| index d9e1cc5..60de5a2 100644 |
| --- a/internal/docs/mailqueue.go |
| +++ b/internal/docs/mailqueue.go |
| @@ -38,11 +38,19 @@ import ( |
| // surfaced: a failure only a permitted address can reach is the oracle |
| // again. |
| // |
| +// Nothing but the log pump ever writes to the logger. The worker and |
| +// close hand their lines to logf, which never blocks: a buffered |
| +// channel, and a counted drop when it is full. A stalled log sink can |
| +// therefore hold only the pump's one write — never a request, never the |
| +// worker, never close (Astra on #20, round 3). The pump ends when the |
| +// worker does. |
| +// |
| // 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 |
| +// is abandoned and counted, 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. |
| +// worker outlives close; that is counted in stuck and logged, best |
| +// effort, too. |
| type mailQueue struct { |
| next mail.Sender |
| admits func(to string) bool |
| @@ -63,6 +71,24 @@ type mailQueue struct { |
| ctx context.Context // cancelled when close gives up waiting |
| cancel context.CancelFunc |
| done chan struct{} |
| + |
| + logMu sync.RWMutex // logf reads logsClosed; the worker's exit sets it |
| + logsClosed bool |
| + logs chan logLine // to the pump; logf never blocks on it |
| + unlogged atomic.Int64 // lines handed over and not yet written |
| + lostLogs atomic.Int64 // lines logf could not hand over |
| + stuck atomic.Bool // close gave up on a worker that ignored cancellation |
| + |
| + // refusedLog, when set, is the line the worker logs (through logf, |
| + // with a running count and never the address) for each link it |
| + // refuses. |
| + refusedLog string |
| + refusals atomic.Int64 |
| +} |
| + |
| +type logLine struct { |
| + msg string |
| + args []any |
| } |
| type mailJob struct { |
| @@ -75,9 +101,16 @@ const ( |
| mailSendTimeout = time.Minute |
| mailDrainTimeout = 30 * time.Second |
| mailAbandonGrace = 5 * time.Second |
| + mailLogDepth = 32 |
| ) |
| func newMailQueue(next mail.Sender, admits func(string) bool, gate func(context.Context) bool, logger *slog.Logger) *mailQueue { |
| + return newMailQueueLogging(next, admits, gate, logger, "") |
| +} |
| + |
| +// newMailQueueLogging is newMailQueue with refusedLog set (see the |
| +// field). |
| +func newMailQueueLogging(next mail.Sender, admits func(string) bool, gate func(context.Context) bool, logger *slog.Logger, refusedLog string) *mailQueue { |
| if logger == nil { |
| logger = slog.Default() |
| } |
| @@ -85,7 +118,8 @@ func newMailQueue(next mail.Sender, admits func(string) bool, gate func(context. |
| 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{})} |
| + done: make(chan struct{}), logs: make(chan logLine, mailLogDepth), refusedLog: refusedLog} |
| + go q.pump() |
| go q.run() |
| return q |
| } |
| @@ -114,8 +148,51 @@ func (q *mailQueue) Send(ctx context.Context, to, subject, body string) error { |
| return nil |
| } |
| +// logf hands one error line to the pump. It never blocks: when the |
| +// pump is behind, the line is counted in lostLogs instead. |
| +func (q *mailQueue) logf(msg string, args ...any) { |
| + q.logMu.RLock() |
| + defer q.logMu.RUnlock() |
| + if q.logsClosed { |
| + q.lostLogs.Add(1) |
| + return |
| + } |
| + q.unlogged.Add(1) |
| + select { |
| + case q.logs <- logLine{msg: msg, args: args}: |
| + default: |
| + q.unlogged.Add(-1) |
| + q.lostLogs.Add(1) |
| + } |
| +} |
| + |
| +// pump is the only goroutine that writes to the logger. It ends when |
| +// the worker closes logs on its way out. |
| +// |
| +// Its limit, stated rather than engineered around: a write blocked |
| +// inside the logger (a stalled sink) cannot be interrupted from Go. It |
| +// can only finish, or die with the process. Closing logs does not reach |
| +// it mid-write, so a stalled sink leaves this one goroutine behind |
| +// until the sink moves. Nothing else waits on it: not Send, not the |
| +// worker, not close. |
| +func (q *mailQueue) pump() { |
| + for l := range q.logs { |
| + if n := q.lostLogs.Swap(0); n > 0 { |
| + q.logger.Error("docs: sign-in mail log lines lost to a slow log sink", "count", n) |
| + } |
| + q.logger.Error(l.msg, l.args...) |
| + q.unlogged.Add(-1) |
| + } |
| +} |
| + |
| func (q *mailQueue) run() { |
| defer close(q.done) |
| + defer func() { // after the last logf below; ends the pump |
| + q.logMu.Lock() |
| + q.logsClosed = true |
| + close(q.logs) |
| + q.logMu.Unlock() |
| + }() |
| abandoned := 0 |
| for job := range q.jobs { |
| q.reportDrops() |
| @@ -128,7 +205,7 @@ func (q *mailQueue) run() { |
| } |
| q.reportDrops() |
| if abandoned > 0 { |
| - q.logger.Error("docs: sign-in links abandoned at shutdown", "count", abandoned) |
| + q.logf("docs: sign-in links abandoned at shutdown", "count", abandoned) |
| } |
| } |
| @@ -136,7 +213,7 @@ func (q *mailQueue) run() { |
| // 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) |
| + q.logf("docs: sign-in mail queue full; links dropped", "count", n) |
| } |
| } |
| @@ -145,28 +222,39 @@ func (q *mailQueue) reportDrops() { |
| 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)) |
| + q.logf("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. |
| + if q.refusedLog != "" { |
| + q.logf(q.refusedLog, "stage", "signin.gate", "refusals_since_boot", q.refusals.Add(1)) |
| + } |
| 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) |
| + q.logf("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() } |
| +// wait blocks until every link queued so far has been sent or refused, |
| +// and every line logged about them has been written. Tests use it to |
| +// read the mailer, and the log, afterwards. |
| +func (q *mailQueue) wait() { |
| + q.pending.Wait() |
| + for q.unlogged.Load() > 0 { |
| + time.Sleep(time.Millisecond) |
| + } |
| +} |
| // 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). |
| +// worker (see the type's comment). It never waits on the log pump: |
| +// shutdown deliberately does not wait for a write blocked inside the |
| +// logger, which can only finish or die with the process (see pump). |
| func (q *mailQueue) close() { |
| q.mu.Lock() |
| if q.closed { |
| @@ -186,6 +274,10 @@ func (q *mailQueue) close() { |
| select { |
| case <-q.done: |
| case <-time.After(mailAbandonGrace): |
| - q.logger.Error("docs: sign-in mail worker ignored cancellation; left running") |
| + // Counted, not written: logging here could hang close on the |
| + // very sink that may be the trouble. The worker is still running, |
| + // so logf is still safe to call, and never blocks. |
| + q.stuck.Store(true) |
| + q.logf("docs: sign-in mail worker ignored cancellation; left running") |
| } |
| } |
diff --git a/internal/docs/mailqueue_test.go b/internal/docs/mailqueue_test.go| index 400bd1d..57623a5 100644 |
| --- a/internal/docs/mailqueue_test.go |
| +++ b/internal/docs/mailqueue_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "fmt" |
| "log/slog" |
| + "os" |
| "runtime" |
| "strings" |
| "sync" |
| @@ -75,15 +76,21 @@ func TestMailQueueSendNeverBlocksWhenFull(t *testing.T) { |
| <-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. |
| + // The drops are the worker's to log, through the pump, once the |
| + // sink is free. |
| free() |
| q.close() |
| - mu.Lock() |
| - defer mu.Unlock() |
| - for _, m := range msgs { |
| - if strings.Contains(m, "links dropped") { |
| - return |
| + deadline := time.Now().Add(2 * time.Second) |
| + for time.Now().Before(deadline) { |
| + mu.Lock() |
| + for _, m := range msgs { |
| + if strings.Contains(m, "links dropped") { |
| + mu.Unlock() |
| + return |
| + } |
| } |
| + mu.Unlock() |
| + time.Sleep(5 * time.Millisecond) |
| } |
| t.Fatalf("no drop was logged with twice the queue's depth sent; the log has %q", msgs) |
| } |
| @@ -178,3 +185,101 @@ func TestMailQueueCloseIsBoundedAndStopsTheWorker(t *testing.T) { |
| t.Fatalf("%d goroutines after close, %d before: the queue leaked", n, baseline) |
| } |
| } |
| + |
| +// mailWorkers counts goroutines running a sign-in mail queue's worker |
| +// or log pump — the targeted leak check (goleak's idea, without the |
| +// dependency) TestMain runs after the package's tests. |
| +func mailWorkers() int { |
| + buf := make([]byte, 1<<22) |
| + stacks := string(buf[:runtime.Stack(buf, true)]) |
| + return strings.Count(stacks, "(*mailQueue).run(") + strings.Count(stacks, "(*mailQueue).pump(") |
| +} |
| + |
| +// TestMailQueueCloseIsBoundedWithAStalledLogger: close reports through |
| +// nothing that can block, and never waits on the log pump. With the log |
| +// sink stalled — every write hangs — and a relay that never answers but |
| +// honours cancellation, and WHILE THE SINK IS STILL STALLED: |
| +// |
| +// - close returns within its bound; |
| +// - the mail worker has exited; |
| +// - at most the one log pump remains, blocked in its write. |
| +// |
| +// A write blocked inside the logger cannot be interrupted from Go; it |
| +// can only finish or die with the process, and shutdown deliberately |
| +// does not wait for it. So only once the sink is released must the pump |
| +// exit and the goroutine count return to its baseline (Astra on #20, |
| +// rounds 3 and 4). The test fails if close waited on the pump, or if |
| +// the pump could hold the worker. |
| +func TestMailQueueCloseIsBoundedWithAStalledLogger(t *testing.T) { |
| + waitFor := func(cond func() bool) bool { |
| + deadline := time.Now().Add(2 * time.Second) |
| + for !cond() && time.Now().Before(deadline) { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + return cond() |
| + } |
| + // Baselines, not zero: another test's queue may still be shutting |
| + // down beside this one. |
| + baseline, workers := runtime.NumGoroutine(), mailWorkers() |
| + release := make(chan struct{}) |
| + var once sync.Once |
| + free := func() { once.Do(func() { close(release) }) } |
| + t.Cleanup(free) |
| + var mu sync.Mutex |
| + var msgs []string |
| + honours := funcSender(func(ctx context.Context, _ string) error { |
| + <-ctx.Done() |
| + return ctx.Err() |
| + }) |
| + q := newMailQueue(honours, everyone, nil, slog.New(stuckHandler{release, &mu, &msgs})) |
| + q.drainTimeout = 50 * time.Millisecond |
| + for i := 0; i < 2*mailQueueDepth; i++ { // drops too, so there is plenty to log |
| + _ = q.Send(context.Background(), fmt.Sprintf("p%d@example.test", i), "s", "b") |
| + } |
| + closed := make(chan struct{}) |
| + go func() { q.close(); close(closed) }() |
| + select { |
| + case <-closed: |
| + case <-time.After(2 * time.Second): |
| + free() |
| + <-closed |
| + t.Fatal("close hung on a stalled log sink") |
| + } |
| + |
| + // The sink is still stalled. |
| + select { |
| + case <-q.done: |
| + default: |
| + t.Fatal("the worker was still running after close, held by the stalled log sink") |
| + } |
| + if !waitFor(func() bool { return runtime.NumGoroutine() <= baseline+1 }) { |
| + t.Fatalf("%d goroutines with the sink stalled, %d before: more than the one blocked log pump remains", runtime.NumGoroutine(), baseline) |
| + } |
| + if n := mailWorkers(); n > workers+1 { |
| + t.Fatalf("%d mail queue goroutines with the sink stalled, %d before: want at most the log pump more", n, workers) |
| + } |
| + |
| + // Released, the pump finishes its write and exits. |
| + free() |
| + if !waitFor(func() bool { return mailWorkers() <= workers && runtime.NumGoroutine() <= baseline }) { |
| + t.Fatalf("after release: %d mail queue goroutines, %d goroutines against %d before", mailWorkers(), runtime.NumGoroutine(), baseline) |
| + } |
| +} |
| + |
| +// TestMain fails the run if any sign-in mail queue worker or log pump |
| +// outlives the package's tests: every app a test builds is closed in its |
| +// cleanup (NewForTestWith). |
| +func TestMain(m *testing.M) { |
| + code := m.Run() |
| + if code == 0 { |
| + deadline := time.Now().Add(5 * time.Second) |
| + for mailWorkers() > 0 && time.Now().Before(deadline) { |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if n := mailWorkers(); n > 0 { |
| + fmt.Fprintf(os.Stderr, "FAIL: %d sign-in mail queue goroutines still running after the tests\n", n) |
| + code = 1 |
| + } |
| + } |
| + os.Exit(code) |
| +} |
diff --git a/internal/docs/render.go b/internal/docs/render.go| index fd82cfe..0488cb7 100644 |
| --- a/internal/docs/render.go |
| +++ b/internal/docs/render.go |
| @@ -287,6 +287,7 @@ var Catalog = rastrillo.Catalog{ |
| "docs.signin.error.address": "That doesn’t look like an email address.", |
| "docs.signin.error.expired": "That link has expired or was already used. Enter your email to get a new one.", |
| "docs.signin.error.unknown": "We couldn’t sign you in. Enter your email to get a new link.", |
| + "docs.signin.error.refused": "That address can’t sign in to Docs. Use a different address, or ask whoever runs this team to add it.", |
| // docs.signout.label is the sign-out control's text — both its |
| // button label and its accessible name. It lives in the shell |