package fichastest import ( "bytes" "encoding/base64" "encoding/json" "errors" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strconv" "strings" "testing" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/oficina/suite" "amadan.net/oficina/suite/server" ) // The suite routes through the real router (spec §6.5): mounted only when a // consumer is configured, behind the bearer check, and outside the app's // CSRF check at exactly /suite/. const suiteToken = "a-test-token-for-memoria" func suiteConsumers() string { return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteToken) + `"}]}]` } // suiteConfig is testConfig with FICHAS_SUITE_CONSUMERS, read through // LoadConfig as main reads it. func suiteConfig(t *testing.T, consumers string) fichas.Config { t.Helper() c, err := fichas.LoadConfig(func(k string) string { switch k { case "FICHAS_DEK": return base64.StdEncoding.EncodeToString(testKey()) case "FICHAS_ORIGIN": return testOrigin case "FICHAS_INSTANCE_KEY": return "test-instance-key" case "FICHAS_OWNERS": return TestOwner case "FICHAS_ALLOW_LOGGED_MAIL": return "1" case "FICHAS_SUITE_CONSUMERS": return consumers } return "" }) if err != nil { t.Fatalf("LoadConfig: %v", err) } return c } // suiteApp is fichas.App exactly as main builds it — not AppForTest, // so nothing here leans on the test identity. func suiteApp(t *testing.T, consumers string) http.Handler { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) mux, _, err := fichas.App(d, suiteConfig(t, consumers), logger) if err != nil { t.Fatalf("App: %v", err) } return mux } // call is a sibling's request: a bearer token when tok is set, and no // Origin, Referer or Sec-Fetch-Site — memoria sends none. func call(h http.Handler, method, target, tok string, body []byte) *httptest.ResponseRecorder { req := httptest.NewRequest(method, target, bytes.NewReader(body)) if tok != "" { req.Header.Set("Authorization", "Bearer "+tok) } if body != nil { req.Header.Set("Content-Type", "application/json") } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func s2Body(t *testing.T, asker string, pairs ...suite.ItemRevision) []byte { t.Helper() if pairs == nil { pairs = []suite.ItemRevision{} } b, err := json.Marshal(suite.S2Request{Asker: suite.Subject{Kind: suite.SubjectAddress, Value: asker}, Pairs: pairs}) if err != nil { t.Fatal(err) } return b } // With a consumer configured, every suite route answers the same empty 401 // to a request without its token, and serves one with it. // // MUTATION-TESTED 2026-11-01, reverted: server.Routes mounted in place of // server.Handler (no bearer check) → every "no token" and "a wrong token" // case. func TestSuiteRoutesNeedTheConsumerToken(t *testing.T) { h := suiteApp(t, suiteConsumers()) for _, r := range []struct{ method, target string }{ {"GET", suite.RouteS1}, {"POST", suite.RouteS2}, {"GET", suite.RouteS3 + "/1?revision=1"}, } { for name, tok := range map[string]string{"no token": "", "a wrong token": "not-the-token"} { rec := call(h, r.method, r.target, tok, s2Body(t, TestOwner)) if rec.Code != http.StatusUnauthorized || rec.Body.Len() != 0 { t.Errorf("%s %s, %s: %d %q, want an empty 401", r.method, r.target, name, rec.Code, rec.Body.String()) } } } rec := call(h, "GET", suite.RouteS1, suiteToken, nil) if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); err != nil { t.Errorf("S1 with the token: %v (%d %s)", err, rec.Code, rec.Body.String()) } } // memoria's S2 is a POST with a bearer token and no Origin, Referer or // Sec-Fetch-Site. The app-wide CSRF check would refuse it; /suite/ is // outside that check. // // MUTATION-TESTED 2026-11-01, reverted: the suite handler mounted on the // chi router (r.Mount("/suite", h)) instead of the outer mux → 403 here. func TestSuiteS2NeedsNoOrigin(t *testing.T) { h := suiteApp(t, suiteConsumers()) rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, suite.ItemRevision{ItemID: "1", Revision: 1})) if rec.Code != http.StatusOK { t.Fatalf("POST /suite/s2 with only a bearer: %d %s", rec.Code, rec.Body.String()) } got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "1", Revision: 1}}, rec.Code, rec.Body.Bytes()) if got[0] != suite.NOT_VISIBLE { // no card 1 yet t.Errorf("S2 for a card that does not exist: %s", got[0]) } } // The exemption is exactly /suite/: every other state-changing request // without same-origin evidence is still refused, a bearer token makes no // difference to that, and a path that only looks like /suite/ is not // exempt. // // MUTATION-TESTED 2026-11-01, each reverted: csrf.Protect replaced by a // wrapper skipping any request carrying an Authorization header → "POST // /cards with a bearer"; csrf.Protect skipped for any path starting with // the string "/suite" → "/suites/s2" and "/suite-s2". func TestOnlySuiteIsExemptFromTheCSRFCheck(t *testing.T) { h := suiteApp(t, suiteConsumers()) for name, target := range map[string]string{ "POST /cards with a bearer": "/cards", "/suites/s2": "/suites/s2", "/suite-s2": "/suite-s2", "a delete with a bearer": "/cards/1/delete", "/suite/../cards, before cleaning": "/suite/../cards", } { rec := call(h, "POST", target, suiteToken, []byte("f_name=x")) if rec.Code/100 == 2 || rec.Code == http.StatusUnauthorized { t.Errorf("%s: %d — reached a handler without same-origin evidence", name, rec.Code) } if target != "/suite/../cards" && rec.Code != http.StatusForbidden { t.Errorf("%s: %d, want the CSRF check's 403", name, rec.Code) } } } // No consumers, no routes (doctrine §3): /suite/ is an unknown path like // any other, token or not. // // MUTATION-TESTED 2026-11-01, reverted: the suite mounted with // server.Routes whenever Handler returned nil → "GET" serves a feed. func TestNoConsumersNoSuiteRoutes(t *testing.T) { h := suiteApp(t, "") unknown := call(h, "GET", "/no-such-path", "", nil) for _, target := range []string{suite.RouteS1, suite.RouteS3 + "/1?revision=1"} { rec := call(h, "GET", target, suiteToken, nil) if rec.Code != unknown.Code || rec.Body.String() != unknown.Body.String() { t.Errorf("GET %s: %d %q, want what an unknown path gets (%d %q)", target, rec.Code, rec.Body.String(), unknown.Code, unknown.Body.String()) } } if rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner)); rec.Code != http.StatusForbidden { t.Errorf("POST %s: %d, want the CSRF check's 403 (no exemption without consumers)", suite.RouteS2, rec.Code) } } // End to end through the whole app: a card made through the form appears // in the feed, its text is served at its revision, and its admitted owner // may see it. This is the wiring — the producer built over the app's own // database and its own admission predicate. func TestSuiteServesACardMadeThroughTheApp(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) h, err := fichas.AppForTest(d, suiteConfig(t, suiteConsumers()), logger, TestOwner) if err != nil { t.Fatal(err) } if rec := post(t, h, "/cards", url.Values{"f_name": {"Cnoc Teoranta"}, "f_email": {"orders@cnoc.example"}}); rec.Code != http.StatusSeeOther { t.Fatalf("creating a card: %d", rec.Code) } if rec := post(t, h, "/cards", url.Values{"f_name": {"Second card"}}); rec.Code != http.StatusSeeOther { t.Fatalf("creating a second card: %d", rec.Code) } rec := call(h, "GET", suite.RouteS1, suiteToken, nil) feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()) if err != nil || len(feed.Rows) != 2 || feed.Rows[0].Gone { t.Fatalf("S1: %+v, %v", feed, err) } // Revisions are random through the whole app (spec §6.2): two new // cards, which a count would both put at 1, do not share one. if feed.Rows[0].Revision < 1 || feed.Rows[1].Revision < 1 || feed.Rows[0].Revision == feed.Rows[1].Revision { t.Errorf("S1 revisions %d and %d: not two distinct random revisions", feed.Rows[0].Revision, feed.Rows[1].Revision) } item, rev := feed.Rows[0].ItemID, feed.Rows[0].Revision revision := strconv.FormatInt(rev, 10) // "." (spec §6.2). if !regexp.MustCompile(`^[1-9][0-9]*\.[1-9][0-9]*$`).MatchString(item) { t.Errorf("item_id %q is not .", item) } rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision="+revision, suiteToken, nil) if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") { t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type")) } pairs := []suite.ItemRevision{{ItemID: item, Revision: rev}} rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...)) if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE { t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0]) } rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, "bo@example.com", pairs...)) if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.NOT_VISIBLE { t.Errorf("S2 for an address not admitted: %s", got[0]) } } // Every suite response the app serves carries Cache-Control: no-store and // Vary: Authorization (doctrine §6.5, revision 11) — a 200, each refusal, // the cursor reset, the 401 and the mux's own 404 and 405 — as it leaves // the process: through rastrillo.Handler, the assembly Serve uses, around // fichas.App exactly as main builds it. server.Handler sets both, and // conformance.CheckProducer checks Handler alone; this checks that nothing // in front of it — rastrillo's panic recovery and security headers, and // app.go's outer mux — drops or rewrites them. Today nothing does: // rastrillo's securityHeaders sets only the CSP, nosniff, X-Frame-Options // and Referrer-Policy, before the handler runs. // // The cursor reset is also checked end to end here: a cursor no Fichas log // issued is exactly 409 {"code":"CURSOR_RESET"} at the app's edge, which // suite.DecodeS1 reads as suite.ErrCursorReset. // // MUTATION-TESTED 2026-11-02, each reverted: a middleware wrapped round the // suite mount in app.go that sets Cache-Control: private, max-age=60 as the // status is written → every case; the same middleware deleting Vary → // every case; the producer answering an unparseable cursor with a plain // error (revision 10's 503) → "the cursor reset", twice. func TestEverySuiteResponseIsNoStore(t *testing.T) { served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: suiteApp(t, suiteConsumers()).(*http.ServeMux), ErrorPage: fichas.ErrorPage}) if err != nil { t.Fatalf("rastrillo.Handler: %v", err) } t.Cleanup(func() { closeDB() }) reset := call(served, "GET", suite.RouteS1+"?cursor=never-issued-by-fichas", suiteToken, nil) if _, err := suite.DecodeS1(reset.Code, reset.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) { t.Errorf("the cursor reset: %d %q, want %d %s", reset.Code, reset.Body.String(), suite.CursorResetStatus, suite.CursorResetBody) } pair := suite.ItemRevision{ItemID: "1.1", Revision: 1} for _, c := range []struct { name, method, target, tok string body []byte want int }{ {"S1", "GET", suite.RouteS1, suiteToken, nil, http.StatusOK}, {"the cursor reset", "GET", suite.RouteS1 + "?cursor=never-issued-by-fichas", suiteToken, nil, suite.CursorResetStatus}, {"S2", "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, pair), http.StatusOK}, {"S2, malformed", "POST", suite.RouteS2, suiteToken, []byte("{"), http.StatusBadRequest}, {"S3, refused", "GET", suite.RouteS3 + "/1.1?revision=1", suiteToken, nil, http.StatusNotFound}, {"no token", "GET", suite.RouteS1, "", nil, http.StatusUnauthorized}, {"the mux's 404", "GET", "/suite/s9", suiteToken, nil, http.StatusNotFound}, {"the mux's 405", "DELETE", suite.RouteS1, suiteToken, nil, http.StatusMethodNotAllowed}, } { rec := call(served, c.method, c.target, c.tok, c.body) if rec.Code != c.want { t.Errorf("%s: %d, want %d", c.name, rec.Code, c.want) } // The harness's own reading of the rule (conformance.storeAudit). if cc, vary := rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"); cc != "no-store" || vary != "Authorization" { t.Errorf("%s: Cache-Control %q, Vary %q; want no-store and Authorization", c.name, cc, vary) } } }