Docs mails sign-in links off the request path, and refuses at the door
Links are mailed by a bounded, non-blocking queue only to permitted addresses, so neither the answer nor its timing reveals the allowlist. A refused address sees the door inside the 403, not bare text. Tests are hermetic. Reviewed by GPT-6-Astra via Codex (#76). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from fix/keymail-signin into main.
14 files changed,
+1,067
−25
internal/docs/admission_test.go+4 −1internal/docs/app.go+22 −5internal/docs/auth.go+21 −18internal/docs/auth_allowlist_test.go+2 −1internal/docs/auth_keymail_test.go+15 −0internal/docs/auth_navigation.go+74 −0internal/docs/home_router_integration_test.go+4 −0internal/docs/keymail_hermetic_test.go+25 −0internal/docs/keymailtest/keymailtest.go+211 −0internal/docs/mailqueue.go+283 −0internal/docs/mailqueue_test.go+299 −0internal/docs/render.go+1 −0internal/docs/signin_timing_test.go+105 −0internal/docs/testing.go+1 −0
CI passed — run details
landed from fix/keymail-signin
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..548e0b7 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() |
| @@ -591,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 |
| @@ -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..9661838 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"), |
| @@ -515,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_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..ee9883c 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() |
| @@ -213,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 { |
| @@ -229,6 +243,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/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/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/keymail_hermetic_test.go b/internal/docs/keymail_hermetic_test.go| new file mode 100644 |
| index 0000000..28cf9d8 |
| --- /dev/null |
| +++ b/internal/docs/keymail_hermetic_test.go |
| @@ -0,0 +1,25 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestKeymailDiscoveryStaysInProcess: every unforced POST /signin |
| +// classifies its address (rastrillo/auth's Keymail discovery), so this |
| +// package's tests — TestSigninNeverWaitsForTheMailer's timing above all |
| +// — must not ask the real network whether a domain runs Keymail. With |
| +// keymailtest installed (TestMain) every query is answered NXDOMAIN |
| +// in-process, so even example.com, which public DNS resolves, must not. |
| +func TestKeymailDiscoveryStaysInProcess(t *testing.T) { |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + addrs, err := net.DefaultResolver.LookupHost(ctx, "example.com") |
| + var dnsErr *net.DNSError |
| + if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound { |
| + t.Fatalf("LookupHost(example.com) = %v, %v; want NXDOMAIN from keymailtest's in-process resolver", addrs, err) |
| + } |
| +} |
diff --git a/internal/docs/keymailtest/keymailtest.go b/internal/docs/keymailtest/keymailtest.go| new file mode 100644 |
| index 0000000..352458d |
| --- /dev/null |
| +++ b/internal/docs/keymailtest/keymailtest.go |
| @@ -0,0 +1,211 @@ |
| +// Package keymailtest keeps sign-in's Keymail classification inside the |
| +// test process. It is imported by tests only. |
| +// |
| +// rastrillo/auth (at the version this app pins) builds its classifier |
| +// with no seams: TXT lookups go through net.DefaultResolver and the |
| +// well-known probe, the federation lookup and the token exchange go |
| +// through http.DefaultTransport. So those two globals are the hooks |
| +// (auth_keymail_test.go's isolated OAuth child swaps the same two). |
| +// Install replaces both for the life of the test binary: |
| +// |
| +// - every DNS query is answered NXDOMAIN by a resolver on loopback, |
| +// so no DNS packet leaves the process, and a domain with no |
| +// `_keymail` record is probed directly — keymail.dev's own shape; |
| +// - an https request to a host registered with Serve is answered |
| +// in-process by that fixture; anything else falls through to the |
| +// real transport, where the resolver above makes a name |
| +// unreachable (IP literals, which httptest servers use, still work). |
| +// |
| +// Every address at a domain nobody registered therefore classifies as |
| +// "not Keymail", which is what every pre-existing sign-in test assumes. |
| +// |
| +// Unlike Slides' copy, http.DefaultTransport stays an *http.Transport: |
| +// home/roster clones it with a type assertion when a team runtime has |
| +// no transport of its own. Install puts a clone in its place, HTTP/1 |
| +// only, with the fixture router registered for "https" |
| +// (RegisterProtocol); a host nobody registered is skipped |
| +// (ErrSkipAltProtocol) and dialled as usual. |
| +package keymailtest |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +var ( |
| + mu sync.Mutex |
| + servers = map[string]*Server{} |
| +) |
| + |
| +// Install swaps net.DefaultResolver and http.DefaultTransport for the |
| +// stubs described in the package comment and returns a function that |
| +// puts them back. Call it once, from TestMain. |
| +func Install() (restore func(), err error) { |
| + dns, err := net.ListenPacket("udp", "127.0.0.1:0") |
| + if err != nil { |
| + return nil, err |
| + } |
| + go answerNXDOMAIN(dns) |
| + oldResolver, oldTransport := net.DefaultResolver, http.DefaultTransport |
| + base, ok := oldTransport.(*http.Transport) |
| + if !ok { |
| + _ = dns.Close() |
| + return nil, fmt.Errorf("keymailtest: http.DefaultTransport is %T, not *http.Transport", oldTransport) |
| + } |
| + tr := base.Clone() |
| + // HTTP/1 only: the bundled HTTP/2 claims the "https" slot on first |
| + // use, and the fixture router must hold it. |
| + tr.Protocols = new(http.Protocols) |
| + tr.Protocols.SetHTTP1(true) |
| + tr.RegisterProtocol("https", fixtures{}) |
| + net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "udp", dns.LocalAddr().String()) |
| + }} |
| + http.DefaultTransport = tr |
| + return func() { |
| + net.DefaultResolver, http.DefaultTransport = oldResolver, oldTransport |
| + _ = dns.Close() |
| + }, nil |
| +} |
| + |
| +// answerNXDOMAIN echoes each query back as a "no such name" answer. |
| +func answerNXDOMAIN(conn net.PacketConn) { |
| + b := make([]byte, 4096) |
| + for { |
| + n, addr, err := conn.ReadFrom(b) |
| + if err != nil { |
| + return |
| + } |
| + if n < 12 { |
| + continue |
| + } |
| + reply := append([]byte(nil), b[:n]...) |
| + reply[2], reply[3] = 0x81, 0x83 // response, recursion, NXDOMAIN |
| + for i := 6; i < 12; i++ { |
| + reply[i] = 0 // no answer, authority or additional records |
| + } |
| + _, _ = conn.WriteTo(reply, addr) |
| + } |
| +} |
| + |
| +// fixtures answers https requests to a registered host in-process and |
| +// hands every other request back to the transport. |
| +type fixtures struct{} |
| + |
| +func (fixtures) RoundTrip(r *http.Request) (*http.Response, error) { |
| + mu.Lock() |
| + s := servers[r.URL.Host] |
| + mu.Unlock() |
| + if s == nil || r.URL.Scheme != "https" { |
| + return nil, http.ErrSkipAltProtocol |
| + } |
| + rec := httptest.NewRecorder() |
| + s.ServeHTTP(rec, r) |
| + res := rec.Result() |
| + res.Request = r |
| + return res, nil |
| +} |
| + |
| +// Server is one Keymail deployment at one host: the well-known |
| +// document, the federation lookup for the accounts it holds, and the |
| +// token exchange for the codes Approve hands out. |
| +type Server struct { |
| + host string |
| + |
| + mu sync.Mutex |
| + accounts map[string]bool |
| + codes map[string]string |
| + lookups int |
| + tokens int |
| +} |
| + |
| +// Serve registers a Keymail deployment at host (which is also the |
| +// address domain it answers for, since nothing publishes a `_keymail` |
| +// record) holding the given accounts. It is unregistered when the test |
| +// ends. |
| +func Serve(t interface{ Cleanup(func()) }, host string, accounts ...string) *Server { |
| + s := &Server{host: host, accounts: map[string]bool{}, codes: map[string]string{}} |
| + for _, a := range accounts { |
| + s.accounts[strings.ToLower(a)] = true |
| + } |
| + mu.Lock() |
| + servers[host] = s |
| + mu.Unlock() |
| + t.Cleanup(func() { |
| + mu.Lock() |
| + delete(servers, host) |
| + mu.Unlock() |
| + }) |
| + return s |
| +} |
| + |
| +// Approve is Keymail's consent screen saying yes for address: it |
| +// returns the code the browser would carry back to /auth/callback. |
| +func (s *Server) Approve(address string) string { |
| + var b [12]byte |
| + _, _ = rand.Read(b[:]) |
| + code := hex.EncodeToString(b[:]) |
| + s.mu.Lock() |
| + s.codes[code] = address |
| + s.mu.Unlock() |
| + return code |
| +} |
| + |
| +// Lookups is how many federation lookups reached this deployment. |
| +func (s *Server) Lookups() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.lookups |
| +} |
| + |
| +// Tokens is how many token exchanges reached this deployment. |
| +func (s *Server) Tokens() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.tokens |
| +} |
| + |
| +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + switch r.URL.Path { |
| + case "/.well-known/keymail": |
| + _ = json.NewEncoder(w).Encode(map[string]any{"version": "1", "reauth": true}) |
| + case "/api/federation/lookup": |
| + s.mu.Lock() |
| + s.lookups++ |
| + ok := s.accounts[strings.ToLower(r.URL.Query().Get("addr"))] |
| + s.mu.Unlock() |
| + if !ok { |
| + w.WriteHeader(http.StatusNotFound) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]bool{"ok": ok}) |
| + case "/api/oauth/token": |
| + var in map[string]string |
| + _ = json.NewDecoder(r.Body).Decode(&in) |
| + s.mu.Lock() |
| + s.tokens++ |
| + address, ok := s.codes[in["code"]] |
| + delete(s.codes, in["code"]) |
| + s.mu.Unlock() |
| + if r.Method != http.MethodPost || !ok { |
| + w.WriteHeader(http.StatusBadRequest) |
| + _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"}) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "access_token": "synthetic", "token_type": "bearer", |
| + "address": address, "auth_time": time.Now().Unix(), |
| + }) |
| + default: |
| + w.WriteHeader(http.StatusNotFound) |
| + } |
| +} |
diff --git a/internal/docs/mailqueue.go b/internal/docs/mailqueue.go| new file mode 100644 |
| index 0000000..60de5a2 |
| --- /dev/null |
| +++ b/internal/docs/mailqueue.go |
| @@ -0,0 +1,283 @@ |
| +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. |
| +// |
| +// 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 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; that is counted in stuck and logged, best |
| +// effort, 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{} |
| + |
| + 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 { |
| + to, subject, body string |
| + gated bool |
| +} |
| + |
| +const ( |
| + mailQueueDepth = 64 |
| + 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() |
| + } |
| + 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{}), logs: make(chan logLine, mailLogDepth), refusedLog: refusedLog} |
| + go q.pump() |
| + 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 |
| +} |
| + |
| +// 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() |
| + if q.ctx.Err() != nil { |
| + abandoned++ |
| + } else { |
| + q.deliver(job) |
| + } |
| + q.pending.Done() |
| + } |
| + q.reportDrops() |
| + if abandoned > 0 { |
| + q.logf("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.logf("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.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.logf("docs: send sign-in link", "err", err) |
| + } |
| +} |
| + |
| +// 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). 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 { |
| + 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): |
| + // 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| new file mode 100644 |
| index 0000000..d4b9518 |
| --- /dev/null |
| +++ b/internal/docs/mailqueue_test.go |
| @@ -0,0 +1,299 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "log/slog" |
| + "os" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/docs/internal/docs/keymailtest" |
| +) |
| + |
| +// 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, through the pump, once the |
| + // sink is free. |
| + free() |
| + q.close() |
| + 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) |
| +} |
| + |
| +// 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) |
| + } |
| +} |
| + |
| +// 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 keeps Keymail classification inside the process: every |
| +// unforced POST /signin classifies its address, and without this each |
| +// one would ask the real network whether the domain runs Keymail. Every |
| +// DNS query is answered NXDOMAIN and only fixtures a test registers |
| +// answer HTTPS (keymailtest), so every address here is plain email. |
| +// |
| +// It also 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) { |
| + restore, err := keymailtest.Install() |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "keymailtest.Install:", err) |
| + os.Exit(1) |
| + } |
| + 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 |
| + } |
| + } |
| + restore() |
| + 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 |
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() |