oficina / slides Public

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

Astra on #20 (P1): a permitted address waited for SMTP before its
?sent=1 and a denied one did not — 252 ms against 0.35 ms — so the
allowlist was readable off a stopwatch, and force=1 exposed Keymail
addresses the same way.

rauth's Mailer is now mailQueue: Send queues the link and returns at
once, and one background worker asks the allowlist and only then talks
to SMTP. POST /signin does the same synchronous work for every address
(rauth's budgets, its link row, the enqueue); the send, and any failure
of it, happens where nobody can time it and is logged, never answered.
The queue is bounded (a full queue drops with a log line) and app.Close
drains it.

TestSigninNeverWaitsForTheMailer holds the mailer blocked and requires
every POST — permitted, denied, and both with force=1 — to answer while
it is, then the permitted links to go out. It fails on a61f0d2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 833936502b927aab44fb77a831ca064ceca990cc parent a61f0d2
12 files changed, +264 −35
  • AGENTS.md +1 −1
  • internal/slides/app.go +11 −1
  • internal/slides/auth.go +15 −32
  • internal/slides/config.go +1 −1
  • internal/slides/handlers.go +15 −0
  • internal/slides/home_test.go +1 −0
  • internal/slides/keymail_home_test.go +1 −0
  • internal/slides/mailqueue.go +124 −0
  • internal/slidestest/browser_test.go +1 −0
  • internal/slidestest/capabilities_test.go +1 −0
  • internal/slidestest/harness_test.go +10 −0
  • internal/slidestest/signin_timing_test.go +83 −0

CI passed — run details

diff --git a/AGENTS.md b/AGENTS.md
index 05b7831..ce5858b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,7 +51,7 @@ seeded on first sign-in — and comes back out as a PDF.
oracle. A Keymail address, permitted or not, gets the continuation
page to Keymail (never a 303 out of the form POST: Safari applies
`form-action` to it); any other gets `303 ?sent=1`, and only a
- permitted one is mailed (`admissionMailer`). Admission is
+ permitted one is mailed, by a worker after the response (`mailQueue`), so not even the response time differs. Admission is
rastrillo/auth's `Authorize`, after verification, and its refusal is
the door with `?err=refused` (`doorOnRefusal`), not rastrillo's bare
text. `?force=1&err=keymail` (a failed Keymail exchange) makes the
diff --git a/internal/slides/app.go b/internal/slides/app.go
index c820921..55f269c 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -302,12 +302,17 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
logger.Info("migrate", "applied", migrated.Applied,
"skipped", migrated.Skipped, "adopted", migrated.Adopted)
- authPlugin, err := newAuthPlugin(cfg, d.Writer(), list)
+ // The sign-in mailer: links are queued and sent after the response,
+ // to permitted addresses only (mailqueue.go). Closed by app.Close.
+ mailer := newMailQueue(cfg.Mailer, list.allows, logger)
+ authPlugin, err := newAuthPlugin(cfg, d.Writer(), list, mailer)
if err != nil {
+ mailer.close()
return nil, nil, err
}
returnSeal, err := newReturnSealer(cfg.InstanceKey)
if err != nil {
+ mailer.close()
return nil, nil, err
}
@@ -320,6 +325,7 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
// request happens to open the first deck.
rt, err := core.New(context.Background())
if err != nil {
+ mailer.close()
return nil, nil, err
}
@@ -332,6 +338,7 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
returnNow: time.Now,
core: rt,
auth: authPlugin,
+ mail: mailer,
hub: present.New(),
live: live.New(),
jobs: jobs.New(logger),
@@ -345,12 +352,14 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, Logger: logger})
if err != nil {
rt.Close(context.Background())
+ mailer.close()
return nil, nil, err
}
a.sessions = sess
if err := a.initHome(homeConfig); err != nil {
rt.Close(context.Background())
+ mailer.close()
return nil, nil, err
}
@@ -365,6 +374,7 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
})
if err != nil {
rt.Close(context.Background())
+ mailer.close()
return nil, nil, err
}
a.jobPages = pages
diff --git a/internal/slides/auth.go b/internal/slides/auth.go
index d8abe2e..551f5f8 100644
--- a/internal/slides/auth.go
+++ b/internal/slides/auth.go
@@ -15,8 +15,8 @@
// credential at Keymail's own origin, and a magic link enrols nothing.
//
// Admission is a separate question from the ceremony, asked at two
-// places that cannot be observed from the form: the mailer
-// (admissionMailer — a non-permitted address is never mailed) and
+// places that cannot be observed from the form: the mail worker
+// (mailQueue — a non-permitted address is never mailed) and
// rauth's Authorize, after Keymail or the link has verified the
// address. Neither changes what POST /signin answers (gateBegin).
//
@@ -168,7 +168,8 @@ func resolveAllowlist(cfg Config) (allowlist, error) {
// door saying so (doorOnRefusal) — told only to somebody who has
// just proved they hold the address.
// - Any other address is answered `303 /signin?sent=1`, and a link is
-// mailed only if it is permitted: admissionMailer drops the rest.
+// mailed only if it is permitted: mailQueue drops the rest, after
+// the response, so not even its timing differs (mailqueue.go).
// So this instance's sending identity is no open relay for whatever
// a stranger types, which is why a gate exists at all
// (rauth.Config.Authorize alone runs only after a link was mailed
@@ -181,37 +182,19 @@ func resolveAllowlist(cfg Config) (allowlist, error) {
// stuck. A stranger posting force for any address gets exactly the
// plain-email answer above.
//
-// What sameAnswer still has to hide is the one outcome only a
-// permitted address can reach: `?err=1`, a send that failed, since a
-// non-permitted address never gets as far as a real send. `?err=rate`
-// and `?err=address` no longer depend on admission — both kinds of
-// address spend the same budgets and parse the same way — but
-// sameAnswer still answers them as sent, as it always has. Giving those
-// two back their own sentences is a separate, safe change, not made
-// here.
+// No outcome of Begin depends on admission any more: both kinds of
+// address spend the same budgets and parse the same way, and the send
+// that only a permitted address reaches happens in mailQueue's worker,
+// after the response, where its failures are logged rather than
+// answered. sameAnswer still rewrites `?err=rate|address|1` to sent, as
+// it always has; giving rate and address back their own sentences is a
+// separate, safe change, not made here.
func gateBegin(next http.HandlerFunc, logger *slog.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
next(&sameAnswer{ResponseWriter: w, logger: logger}, r)
}
}
-// admissionMailer is the mail half of the allowlist: Begin runs for
-// every address (gateBegin), and this is where a non-permitted one is
-// quietly not mailed. rauth has already stored an expiring link token
-// by the time it calls Send; one that is never delivered is never
-// redeemed, and Authorize would refuse it if it were.
-type admissionMailer struct {
- next mail.Sender
- list allowlist
-}
-
-func (m admissionMailer) Send(ctx context.Context, to, subject, body string) error {
- if !m.list.allows(to) {
- return nil
- }
- return m.next.Send(ctx, to, subject, body)
-}
-
// newBegin is the POST /signin handler both modes mount: gateBegin
// under connect.OAuthContinuation, which ends the POST with a page
// (renderKeymailContinuation) when Begin's answer is Keymail's
@@ -345,8 +328,8 @@ func (s *sameAnswer) WriteHeader(status int) {
// both the emailed link's base and the cookie decision, InstanceKey and
// Mailer already resolved and fail-closed above.
//
-// Authorize is list.allows as well as admissionMailer — two checks
-// defending two different things: admissionMailer stops the mail,
+// Authorize is list.allows as well as mailQueue — two checks
+// defending two different things: mailQueue stops the mail,
// Authorize stops a session being minted for a non-permitted address,
// whether Keymail verified it or a link was somehow issued for it
// (mailed before the allowlist changed, say). SecondFactor stays nil,
@@ -361,7 +344,7 @@ func (s *sameAnswer) WriteHeader(status int) {
// copy of that literal and app.go mounts the page at ours; saying it
// once, out loud, is what keeps the two from drifting silently if
// either default ever changes.
-func newAuthPlugin(cfg Config, writer *sql.DB, list allowlist) (*rauth.Auth, error) {
+func newAuthPlugin(cfg Config, writer *sql.DB, list allowlist, mailer *mailQueue) (*rauth.Auth, error) {
signedInPath := landedPath
if cfg.Home != nil {
signedInPath = connect.LocalCompletePath
@@ -371,7 +354,7 @@ func newAuthPlugin(cfg Config, writer *sql.DB, list allowlist) (*rauth.Auth, err
DB: writer,
Origin: cfg.Origin,
InstanceKey: cfg.InstanceKey,
- Mailer: admissionMailer{next: cfg.Mailer, list: list},
+ Mailer: mailer,
Subject: chrome.EmailSubject("Slides"),
Authorize: list.allows,
SigninPath: signinPath,
diff --git a/internal/slides/config.go b/internal/slides/config.go
index 3374f11..89bcff4 100644
--- a/internal/slides/config.go
+++ b/internal/slides/config.go
@@ -92,7 +92,7 @@ type Config struct {
//
// It is wired to two places on purpose: rauth.Config.Authorize
// gates admission, after Keymail or a link has verified the
- // address, and admissionMailer (auth.go) drops the mail for an
+ // address, and mailQueue (mailqueue.go) drops the mail for an
// address not on it. The second is what keeps this instance's
// sending identity from being an open relay for any address a
// stranger types into the form, since Authorize fires only after
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go
index 83fa42d..2de7561 100644
--- a/internal/slides/handlers.go
+++ b/internal/slides/handlers.go
@@ -42,6 +42,8 @@ type app struct {
logger *slog.Logger
cfg Config
allowed allowlist
+ // mail is the sign-in mail queue rauth sends through (mailqueue.go).
+ mail *mailQueue
// returnSeal authenticates the short-lived return_to cookie. It is
// derived from this instance's sign-in key, never from a browser
// value, and the clock is a seam for expiry tests.
@@ -113,6 +115,10 @@ func (a *app) Close() error {
if a.live != nil {
a.live.Close()
}
+ // Queued sign-in links are sent before the process lets go.
+ if a.mail != nil {
+ a.mail.close()
+ }
// The PDF module, if any export ever built one. Same argument as
// the deck core's below: a test binary builds an app per test, and
// a compiled wasm module nobody releases is a leak per app.
@@ -124,3 +130,12 @@ func (a *app) Close() error {
}
return a.core.Close(context.Background())
}
+
+// FlushMail waits until every sign-in link queued so far has been sent
+// or dropped. The links go out after the response (mailqueue.go), so a
+// test reads the mailer only after this.
+func (a *app) FlushMail() {
+ if a.mail != nil {
+ a.mail.wait()
+ }
+}
diff --git a/internal/slides/home_test.go b/internal/slides/home_test.go
index 6400586..700de7b 100644
--- a/internal/slides/home_test.go
+++ b/internal/slides/home_test.go
@@ -469,6 +469,7 @@ func TestHomeLocalPluginRecoveryRotatesThenReturnsToLink(t *testing.T) {
if sent.Code != 303 {
t.Fatal(sent.Code)
}
+ a.FlushMail()
body := a.cfg.Mailer.(*homeTestMail).body
link := regexp.MustCompile(`https://[^\s<>]+/auth/verify\?token=[A-Za-z0-9_-]+`).FindString(body)
if link == "" {
diff --git a/internal/slides/keymail_home_test.go b/internal/slides/keymail_home_test.go
index 66841cf..b0a8d0f 100644
--- a/internal/slides/keymail_home_test.go
+++ b/internal/slides/keymail_home_test.go
@@ -92,6 +92,7 @@ func TestHomeLocalKeymailIsAContinuationAndRefusesAtTheDoor(t *testing.T) {
_, _ = begin(member)
rec, u := begin(stranger)
+ a.FlushMail()
if mail.body != "" {
t.Fatal("a Keymail address was mailed a link")
}
diff --git a/internal/slides/mailqueue.go b/internal/slides/mailqueue.go
new file mode 100644
index 0000000..a0f9d55
--- /dev/null
+++ b/internal/slides/mailqueue.go
@@ -0,0 +1,124 @@
+package slides
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/mail"
+)
+
+// mailQueue is the sign-in mailer rauth is given: Send queues the link
+// and returns at once, and one background worker asks the allowlist and
+// only then talks to SMTP.
+//
+// Both halves are the no-oracle guarantee (gateBegin), 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 #20). A response
+// time is an answer like any other. So POST /signin does the same
+// synchronous work for every address — rauth'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 admission check
+// moved into the worker for the same reason: a check before responding
+// would be a branch an attacker could time, however cheap it is today.
+//
+// Delivery failures are logged, never surfaced. A failure only a
+// permitted address can reach is the oracle again, and the person is
+// told what every address is told: check your email, or ask again.
+//
+// Bounded: a queue of mailQueueDepth links. A full queue drops the link
+// with a log line instead of blocking a request — the per-IP and
+// per-address budgets inside Begin keep that from being an ordinary
+// event. Close drains what is queued, within mailDrainTimeout.
+type mailQueue struct {
+ next mail.Sender
+ admits func(string) bool
+ logger *slog.Logger
+
+ mu sync.Mutex
+ closed bool
+ jobs chan mailJob
+ pending sync.WaitGroup
+ done chan struct{}
+}
+
+type mailJob struct{ to, subject, body string }
+
+const (
+ mailQueueDepth = 64
+ mailSendTimeout = time.Minute
+ mailDrainTimeout = 30 * time.Second
+)
+
+func newMailQueue(next mail.Sender, admits func(string) bool, logger *slog.Logger) *mailQueue {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ q := &mailQueue{next: next, admits: admits, logger: logger,
+ jobs: make(chan mailJob, mailQueueDepth), done: make(chan struct{})}
+ go q.run()
+ return q
+}
+
+// Send queues one link. It never blocks and never fails: the request
+// that called it answers the same way whatever happens next.
+func (q *mailQueue) Send(_ context.Context, to, subject, body string) error {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ if q.closed {
+ q.logger.Error("slides: sign-in mail after shutdown; dropped")
+ return nil
+ }
+ q.pending.Add(1)
+ select {
+ case q.jobs <- mailJob{to: to, subject: subject, body: body}:
+ default:
+ q.pending.Done()
+ q.logger.Error("slides: sign-in mail queue full; link dropped")
+ }
+ return nil
+}
+
+func (q *mailQueue) run() {
+ defer close(q.done)
+ for job := range q.jobs {
+ q.deliver(job)
+ q.pending.Done()
+ }
+}
+
+func (q *mailQueue) deliver(job mailJob) {
+ if !q.admits(job.to) {
+ // Not on the allowlist: the link rauth stored is never
+ // delivered, so it is never redeemed. No address in the log.
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), mailSendTimeout)
+ defer cancel()
+ if err := q.next.Send(ctx, job.to, job.subject, job.body); err != nil {
+ q.logger.Error("slides: send sign-in link", "err", err)
+ }
+}
+
+// wait blocks until every link queued so far has been delivered or
+// dropped. Tests use it (App.FlushMail) to read the mailer afterwards.
+func (q *mailQueue) wait() { q.pending.Wait() }
+
+// close stops taking links and drains what is queued.
+func (q *mailQueue) close() {
+ q.mu.Lock()
+ if q.closed {
+ q.mu.Unlock()
+ return
+ }
+ q.closed = true
+ close(q.jobs)
+ q.mu.Unlock()
+ select {
+ case <-q.done:
+ case <-time.After(mailDrainTimeout):
+ q.logger.Error("slides: sign-in mail still sending at shutdown; abandoned")
+ }
+}
diff --git a/internal/slidestest/browser_test.go b/internal/slidestest/browser_test.go
index cec28e9..f5dad94 100644
--- a/internal/slidestest/browser_test.go
+++ b/internal/slidestest/browser_test.go
@@ -82,6 +82,7 @@ func newRigWith(t *testing.T, store blobs.Store) (*harness.Rig, *fakeMailer) {
t.Fatalf("slides.New: %v", err)
}
t.Cleanup(func() { a.Close() })
+ mailer.flush = a.FlushMail
return localised(t, mux)
})
return rig, mailer
diff --git a/internal/slidestest/capabilities_test.go b/internal/slidestest/capabilities_test.go
index 76dd319..840b817 100644
--- a/internal/slidestest/capabilities_test.go
+++ b/internal/slidestest/capabilities_test.go
@@ -395,5 +395,6 @@ func newAppOver(t *testing.T, d *db.DB, cfg slides.Config, mailer *fakeMailer) *
t.Fatalf("slides.New: %v", err)
}
t.Cleanup(func() { a.Close() })
+ mailer.flush = a.FlushMail
return &testApp{Handler: localised(t, mux), mailer: mailer, db: d, app: a}
}
diff --git a/internal/slidestest/harness_test.go b/internal/slidestest/harness_test.go
index 01841e4..dde46af 100644
--- a/internal/slidestest/harness_test.go
+++ b/internal/slidestest/harness_test.go
@@ -55,6 +55,9 @@ type sentMail struct{ To, Subject, Body string }
type fakeMailer struct {
mu sync.Mutex
sent []sentMail
+ // flush waits for the app's mail queue: links are sent after the
+ // response (mailqueue.go), so messages reads only after it.
+ flush func()
}
func (m *fakeMailer) Send(_ context.Context, to, subject, body string) error {
@@ -66,6 +69,9 @@ func (m *fakeMailer) Send(_ context.Context, to, subject, body string) error {
// messages returns a copy of everything sent so far.
func (m *fakeMailer) messages() []sentMail {
+ if m.flush != nil {
+ m.flush()
+ }
m.mu.Lock()
defer m.mu.Unlock()
return append([]sentMail(nil), m.sent...)
@@ -94,6 +100,7 @@ type testApp struct {
Close() error
SetExportCaps(perDeck, perInstance int64)
ForgetExportJobs() error
+ FlushMail()
}
}
@@ -133,6 +140,9 @@ func newAppWith(t *testing.T, cfg slides.Config, mailer *fakeMailer) *testApp {
// Releases the compiled deck core's wazero runtime; every test app
// built over slides.New leaks one without this (task 3 fix round 1).
t.Cleanup(func() { a.Close() })
+ if mailer != nil {
+ mailer.flush = a.FlushMail
+ }
return &testApp{Handler: localised(t, mux), mailer: mailer, db: d, app: a}
}
diff --git a/internal/slidestest/signin_timing_test.go b/internal/slidestest/signin_timing_test.go
new file mode 100644
index 0000000..9fd99b0
--- /dev/null
+++ b/internal/slidestest/signin_timing_test.go
@@ -0,0 +1,83 @@
+package slidestest
+
+import (
+ "context"
+ "net/http/httptest"
+ "net/url"
+ "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 is the timing half of the no-oracle
+// guarantee (Astra on #20, P1). When the send ran inside the request, a
+// permitted address waited for SMTP before its ?sent=1 and a denied one
+// did not — 252 ms against 0.35 ms, the allowlist readable off a
+// stopwatch, and force=1 made Keymail addresses readable the same way.
+//
+// Here the mailer never answers until the test says so. Every POST —
+// permitted, denied, and both again with force=1 — must come back while
+// it is still blocked, and the permitted links must then go out.
+func TestSigninNeverWaitsForTheMailer(t *testing.T) {
+ bm := &blockingMailer{release: make(chan struct{})}
+ cfg, _ := newConfig(t)
+ cfg.Mailer = bm
+ app := newAppWith(t, cfg, nil)
+ var once sync.Once
+ free := func() { once.Do(func() { close(bm.release) }) }
+ t.Cleanup(free) // before the app's own Close, which drains the queue
+
+ posts := []url.Values{
+ {"address": {allowedAddress}},
+ {"address": {deniedAddress}},
+ {"address": {allowedAddress}, "force": {"1"}},
+ {"address": {deniedAddress}, "force": {"1"}},
+ }
+ for _, form := range posts {
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() { done <- post(t, app, "/signin", form) }()
+ select {
+ case rec := <-done:
+ if rec.Code != 303 || rec.Header().Get("Location") != "/signin?sent=1" {
+ t.Errorf("POST %v: %d %q, want 303 /signin?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) // and nothing more arrives
+ got := bm.sent()
+ if len(got) != 2 || got[0] != allowedAddress || got[1] != allowedAddress {
+ t.Fatalf("mail sent = %v, want two links, both to %s", got, allowedAddress)
+ }
+}