oficina / docs Public

Cancel queued team session lookups in the database, not just the wait

Review #77 (Astra, P2): running From in a goroutine only abandoned a
cancelled lookup, so with the writer held every cancelled stream check
stayed queued for the connection (64 of 64). Docs now pins rastrillo
feat/session-from-context (9866809), which ports Sessions.FromContext onto
main, and the team reader is back to calling it: the context reaches
connection acquisition and the query itself.

TestTeamSessionReaderCancelledLookupsLeaveNoWorkQueued holds the writer,
cancels 64 queued lookups and requires none left inside rastrillo's
session lookup; it fails on a871701's reader.

Also from the review: the CSP test now compares Docs' policy with
rastrillo's real default and allows a difference only in style-src.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1345bb93d08fac676e52fd7d4d7be818a5e236cb parent a871701
5 files changed, +126 −31
  • go.mod +1 −1
  • go.sum +2 −2
  • internal/docs/home_security_test.go +26 −0
  • internal/docs/team_session_reader.go +4 −28
  • internal/docs/team_session_reader_test.go +93 −0

CI passed — run details

diff --git a/go.mod b/go.mod
index 8abdd1f..deaed17 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,7 @@ require (
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3
- amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060
+ amadan.net/rastrillo/rastrillo v0.27.1-0.20261006214031-98668096a56b
github.com/carlosframework/rastrillo v0.23.0
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
diff --git a/go.sum b/go.sum
index 18f936f..90f9bfe 100644
--- a/go.sum
+++ b/go.sum
@@ -6,8 +6,8 @@ amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8=
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY=
-amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE=
-amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608=
+amadan.net/rastrillo/rastrillo v0.27.1-0.20261006214031-98668096a56b h1:8ephOfyM355H2hXJ5ZDSo+WsNpogjWGteHu5HHCAoiI=
+amadan.net/rastrillo/rastrillo v0.27.1-0.20261006214031-98668096a56b/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608=
amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
diff --git a/internal/docs/home_security_test.go b/internal/docs/home_security_test.go
index 5b154a1..d56691e 100644
--- a/internal/docs/home_security_test.go
+++ b/internal/docs/home_security_test.go
@@ -27,6 +27,21 @@ func TestHomeFormPolicyPreservesFrameworkAndStandalone(t *testing.T) {
if baseline != ContentSecurityPolicy {
t.Fatalf("rastrillo did not serve Options.CSP as given: %q", baseline)
}
+ // Docs' policy departs from the framework's only in style-src. Any
+ // other directive rastrillo tightens later must reach Docs too, so
+ // compare against the real default, not Docs' own constant.
+ plain, plainDone, err := rastrillo.Handler(rastrillo.Options{Mux: mux})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plainDone != nil {
+ defer plainDone()
+ }
+ rec = httptest.NewRecorder()
+ plain.ServeHTTP(rec, httptest.NewRequest("GET", bridgeOrigin+"/", nil))
+ if a, b := withoutStyleSrc(rec.Header().Get("Content-Security-Policy")), withoutStyleSrc(ContentSecurityPolicy); a != b {
+ t.Fatalf("ContentSecurityPolicy differs from rastrillo's default outside style-src:\n framework %q\n docs %q", a, b)
+ }
want := strings.Replace(baseline, "form-action 'self'", "form-action 'self' "+bridgeIssuer, 1)
if want == baseline {
t.Fatal("form-action changed; review policy")
@@ -63,3 +78,14 @@ func TestHomeFormPolicyPreservesFrameworkAndStandalone(t *testing.T) {
t.Fatal("standalone policy changed")
}
}
+
+// withoutStyleSrc is policy with its style-src directive removed.
+func withoutStyleSrc(policy string) string {
+ var kept []string
+ for _, d := range strings.Split(policy, ";") {
+ if d = strings.TrimSpace(d); d != "" && !strings.HasPrefix(d, "style-src") {
+ kept = append(kept, d)
+ }
+ }
+ return strings.Join(kept, "; ")
+}
diff --git a/internal/docs/team_session_reader.go b/internal/docs/team_session_reader.go
index 352795c..c69e117 100644
--- a/internal/docs/team_session_reader.go
+++ b/internal/docs/team_session_reader.go
@@ -9,42 +9,18 @@ import (
"amadan.net/rastrillo/rastrillo/sessions"
)
-// The caller's context bounds the wait for the session lookup. Docs used
-// to pin rastrillo's feat-session-context branch for Sessions.FromContext,
-// which bounded the query itself; that branch never reached rastrillo's
-// main, so here From runs aside and a canceled or expired context answers
-// "no session" without waiting for it. The query is not interrupted (From
-// takes no context), but From only reads: it never deletes, refreshes or
-// rotates the row, so abandoning its answer changes nothing.
+// Keep validation in the shared reader: FromContext bounds the session
+// lookup by the caller's context. (Before Docs moved off rastrillo's
+// pre-move path, this converted between the two packages' Session types.)
func newTeamSessionReader(db *sql.DB, origin, cookieName string, logger *slog.Logger) (func(context.Context, *http.Request) (sessions.Session, bool), error) {
reader, e := sessions.New(sessions.Config{DB: db, Origin: origin, Logger: logger})
if e != nil || reader.CookieName() != cookieName {
return nil, errTeamConfig
}
- type answer struct {
- session sessions.Session
- ok bool
- }
return func(ctx context.Context, r *http.Request) (sessions.Session, bool) {
if _, present, ok := homeCookie(r, cookieName); !ok || !present {
return sessions.Session{}, false
}
- if ctx.Err() != nil {
- return sessions.Session{}, false
- }
- done := make(chan answer, 1)
- go func() {
- s, ok := reader.From(r)
- done <- answer{s, ok}
- }()
- select {
- case a := <-done:
- if ctx.Err() != nil {
- return sessions.Session{}, false
- }
- return a.session, a.ok
- case <-ctx.Done():
- return sessions.Session{}, false
- }
+ return reader.FromContext(ctx, r)
}, nil
}
diff --git a/internal/docs/team_session_reader_test.go b/internal/docs/team_session_reader_test.go
index 1088568..b22f7a2 100644
--- a/internal/docs/team_session_reader_test.go
+++ b/internal/docs/team_session_reader_test.go
@@ -4,6 +4,8 @@ import (
"context"
"net/http"
"net/http/httptest"
+ "runtime"
+ "strings"
"testing"
"time"
@@ -102,3 +104,94 @@ func TestTeamSessionReaderRevocationAndDatabaseErrorParity(t *testing.T) {
t.Fatal("legacy database failure differs")
}
}
+
+// A lookup cancelled while it waits for the writer must end its database
+// work, not merely stop waiting for it. A reader that only abandons the
+// answer (a871701 ran From in a goroutine and returned on ctx.Done) leaves
+// one goroutine per cancelled lookup queued for the connection, and they
+// all run when the writer comes back. Review #77, Astra: 64 left behind.
+func TestTeamSessionReaderCancelledLookupsLeaveNoWorkQueued(t *testing.T) {
+ f := newBridgeFixture(t)
+ reader, e := newTeamSessionReader(f.app.db.Writer(), f.b.origin, f.b.sessionCookie, f.app.logger)
+ if e != nil {
+ t.Fatal(e)
+ }
+ r := bridgeRequest("GET", "/", nil)
+ w := httptest.NewRecorder()
+ if e = f.b.sessions.SignIn(w, r, sessions.Session{Subject: "alice@example.com", Method: "magiclink", AuthTime: time.Now()}); e != nil {
+ t.Fatal(e)
+ }
+ r.AddCookie(bridgeCookie(t, w, f.b.sessionCookie))
+
+ db := f.app.db.Writer()
+ tx, e := db.BeginTx(t.Context(), nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer tx.Rollback()
+
+ const lookups = 64
+ for i := 0; i < lookups; i++ {
+ ctx, cancel := context.WithCancel(t.Context())
+ before := db.Stats().WaitCount
+ done := make(chan bool, 1)
+ go func() { _, ok := reader(ctx, r); done <- ok }()
+ for deadline := time.Now().Add(2 * time.Second); db.Stats().WaitCount == before; {
+ if time.Now().After(deadline) {
+ cancel()
+ t.Fatal("the lookup never queued for the held writer")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ cancel()
+ select {
+ case ok := <-done:
+ if ok {
+ t.Fatal("a cancelled lookup admitted the session")
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("cancelling a queued lookup did not return")
+ }
+ }
+
+ // Every caller has returned and the writer is still held: nothing may
+ // still be waiting inside rastrillo's session lookup.
+ var queued int
+ for deadline := time.Now().Add(time.Second); ; {
+ queued = goroutinesIn("rastrillo/sessions.")
+ if queued == 0 || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if queued != 0 {
+ t.Fatalf("%d of %d cancelled session lookups are still queued for the writer", queued, lookups)
+ }
+ if e = tx.Rollback(); e != nil {
+ t.Fatal(e)
+ }
+ if _, ok := reader(t.Context(), r); !ok {
+ t.Fatal("cancelled lookups disturbed the live session")
+ }
+}
+
+// goroutinesIn counts goroutines with a frame in a function whose name
+// contains marker.
+func goroutinesIn(marker string) int {
+ buf := make([]byte, 1<<20)
+ for {
+ n := runtime.Stack(buf, true)
+ if n < len(buf) {
+ buf = buf[:n]
+ break
+ }
+ buf = make([]byte, 2*len(buf))
+ }
+ count := 0
+ for _, g := range strings.Split(string(buf), "\n\n") {
+ if strings.Contains(g, marker) {
+ count++
+ }
+ }
+ return count
+}