| 1 | package fichastest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "net/url" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | |
| 19 | "amadan.net/rastrillo/rastrillo" |
| 20 | "amadan.net/rastrillo/rastrillo/db" |
| 21 | |
| 22 | fichas "amadan.net/oficina/fichas/internal/fichas" |
| 23 | "amadan.net/oficina/suite" |
| 24 | "amadan.net/oficina/suite/server" |
| 25 | ) |
| 26 | |
| 27 | // The suite routes through the real router (spec §6.5): mounted only when a |
| 28 | // consumer is configured, behind the bearer check, and outside the app's |
| 29 | // CSRF check at exactly /suite/. |
| 30 | |
| 31 | const suiteToken = "a-test-token-for-memoria" |
| 32 | |
| 33 | func suiteConsumers() string { |
| 34 | return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteToken) + `"}]}]` |
| 35 | } |
| 36 | |
| 37 | // suiteConfig is testConfig with FICHAS_SUITE_CONSUMERS, read through |
| 38 | // LoadConfig as main reads it. |
| 39 | func suiteConfig(t *testing.T, consumers string) fichas.Config { |
| 40 | t.Helper() |
| 41 | c, err := fichas.LoadConfig(func(k string) string { |
| 42 | switch k { |
| 43 | case "FICHAS_DEK": |
| 44 | return base64.StdEncoding.EncodeToString(testKey()) |
| 45 | case "FICHAS_ORIGIN": |
| 46 | return testOrigin |
| 47 | case "FICHAS_INSTANCE_KEY": |
| 48 | return "test-instance-key" |
| 49 | case "FICHAS_OWNERS": |
| 50 | return TestOwner |
| 51 | case "FICHAS_ALLOW_LOGGED_MAIL": |
| 52 | return "1" |
| 53 | case "FICHAS_SUITE_CONSUMERS": |
| 54 | return consumers |
| 55 | } |
| 56 | return "" |
| 57 | }) |
| 58 | if err != nil { |
| 59 | t.Fatalf("LoadConfig: %v", err) |
| 60 | } |
| 61 | return c |
| 62 | } |
| 63 | |
| 64 | // suiteApp is fichas.App exactly as main builds it — not AppForTest, |
| 65 | // so nothing here leans on the test identity. |
| 66 | func suiteApp(t *testing.T, consumers string) http.Handler { |
| 67 | t.Helper() |
| 68 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 69 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 70 | if err != nil { |
| 71 | t.Fatalf("db.Open: %v", err) |
| 72 | } |
| 73 | t.Cleanup(func() { d.Close() }) |
| 74 | mux, _, err := fichas.App(d, suiteConfig(t, consumers), logger) |
| 75 | if err != nil { |
| 76 | t.Fatalf("App: %v", err) |
| 77 | } |
| 78 | return mux |
| 79 | } |
| 80 | |
| 81 | // call is a sibling's request: a bearer token when tok is set, and no |
| 82 | // Origin, Referer or Sec-Fetch-Site — memoria sends none. |
| 83 | func call(h http.Handler, method, target, tok string, body []byte) *httptest.ResponseRecorder { |
| 84 | req := httptest.NewRequest(method, target, bytes.NewReader(body)) |
| 85 | if tok != "" { |
| 86 | req.Header.Set("Authorization", "Bearer "+tok) |
| 87 | } |
| 88 | if body != nil { |
| 89 | req.Header.Set("Content-Type", "application/json") |
| 90 | } |
| 91 | rec := httptest.NewRecorder() |
| 92 | h.ServeHTTP(rec, req) |
| 93 | return rec |
| 94 | } |
| 95 | |
| 96 | func s2Body(t *testing.T, asker string, pairs ...suite.ItemRevision) []byte { |
| 97 | t.Helper() |
| 98 | if pairs == nil { |
| 99 | pairs = []suite.ItemRevision{} |
| 100 | } |
| 101 | b, err := json.Marshal(suite.S2Request{Asker: suite.Subject{Kind: suite.SubjectAddress, Value: asker}, Pairs: pairs}) |
| 102 | if err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | return b |
| 106 | } |
| 107 | |
| 108 | // With a consumer configured, every suite route answers the same empty 401 |
| 109 | // to a request without its token, and serves one with it. |
| 110 | // |
| 111 | // MUTATION-TESTED 2026-11-01, reverted: server.Routes mounted in place of |
| 112 | // server.Handler (no bearer check) → every "no token" and "a wrong token" |
| 113 | // case. |
| 114 | func TestSuiteRoutesNeedTheConsumerToken(t *testing.T) { |
| 115 | h := suiteApp(t, suiteConsumers()) |
| 116 | for _, r := range []struct{ method, target string }{ |
| 117 | {"GET", suite.RouteS1}, |
| 118 | {"POST", suite.RouteS2}, |
| 119 | {"GET", suite.RouteS3 + "/1?revision=1"}, |
| 120 | } { |
| 121 | for name, tok := range map[string]string{"no token": "", "a wrong token": "not-the-token"} { |
| 122 | rec := call(h, r.method, r.target, tok, s2Body(t, TestOwner)) |
| 123 | if rec.Code != http.StatusUnauthorized || rec.Body.Len() != 0 { |
| 124 | t.Errorf("%s %s, %s: %d %q, want an empty 401", r.method, r.target, name, rec.Code, rec.Body.String()) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | rec := call(h, "GET", suite.RouteS1, suiteToken, nil) |
| 129 | if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); err != nil { |
| 130 | t.Errorf("S1 with the token: %v (%d %s)", err, rec.Code, rec.Body.String()) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // memoria's S2 is a POST with a bearer token and no Origin, Referer or |
| 135 | // Sec-Fetch-Site. The app-wide CSRF check would refuse it; /suite/ is |
| 136 | // outside that check. |
| 137 | // |
| 138 | // MUTATION-TESTED 2026-11-01, reverted: the suite handler mounted on the |
| 139 | // chi router (r.Mount("/suite", h)) instead of the outer mux → 403 here. |
| 140 | func TestSuiteS2NeedsNoOrigin(t *testing.T) { |
| 141 | h := suiteApp(t, suiteConsumers()) |
| 142 | rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, suite.ItemRevision{ItemID: "1", Revision: 1})) |
| 143 | if rec.Code != http.StatusOK { |
| 144 | t.Fatalf("POST /suite/s2 with only a bearer: %d %s", rec.Code, rec.Body.String()) |
| 145 | } |
| 146 | got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "1", Revision: 1}}, rec.Code, rec.Body.Bytes()) |
| 147 | if got[0] != suite.NOT_VISIBLE { // no card 1 yet |
| 148 | t.Errorf("S2 for a card that does not exist: %s", got[0]) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // The exemption is exactly /suite/: every other state-changing request |
| 153 | // without same-origin evidence is still refused, a bearer token makes no |
| 154 | // difference to that, and a path that only looks like /suite/ is not |
| 155 | // exempt. |
| 156 | // |
| 157 | // MUTATION-TESTED 2026-11-01, each reverted: csrf.Protect replaced by a |
| 158 | // wrapper skipping any request carrying an Authorization header → "POST |
| 159 | // /cards with a bearer"; csrf.Protect skipped for any path starting with |
| 160 | // the string "/suite" → "/suites/s2" and "/suite-s2". |
| 161 | func TestOnlySuiteIsExemptFromTheCSRFCheck(t *testing.T) { |
| 162 | h := suiteApp(t, suiteConsumers()) |
| 163 | for name, target := range map[string]string{ |
| 164 | "POST /cards with a bearer": "/cards", |
| 165 | "/suites/s2": "/suites/s2", |
| 166 | "/suite-s2": "/suite-s2", |
| 167 | "a delete with a bearer": "/cards/1/delete", |
| 168 | "/suite/../cards, before cleaning": "/suite/../cards", |
| 169 | } { |
| 170 | rec := call(h, "POST", target, suiteToken, []byte("f_name=x")) |
| 171 | if rec.Code/100 == 2 || rec.Code == http.StatusUnauthorized { |
| 172 | t.Errorf("%s: %d — reached a handler without same-origin evidence", name, rec.Code) |
| 173 | } |
| 174 | if target != "/suite/../cards" && rec.Code != http.StatusForbidden { |
| 175 | t.Errorf("%s: %d, want the CSRF check's 403", name, rec.Code) |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // No consumers, no routes (doctrine §3): /suite/ is an unknown path like |
| 181 | // any other, token or not. |
| 182 | // |
| 183 | // MUTATION-TESTED 2026-11-01, reverted: the suite mounted with |
| 184 | // server.Routes whenever Handler returned nil → "GET" serves a feed. |
| 185 | func TestNoConsumersNoSuiteRoutes(t *testing.T) { |
| 186 | h := suiteApp(t, "") |
| 187 | unknown := call(h, "GET", "/no-such-path", "", nil) |
| 188 | for _, target := range []string{suite.RouteS1, suite.RouteS3 + "/1?revision=1"} { |
| 189 | rec := call(h, "GET", target, suiteToken, nil) |
| 190 | if rec.Code != unknown.Code || rec.Body.String() != unknown.Body.String() { |
| 191 | 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()) |
| 192 | } |
| 193 | } |
| 194 | if rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner)); rec.Code != http.StatusForbidden { |
| 195 | t.Errorf("POST %s: %d, want the CSRF check's 403 (no exemption without consumers)", suite.RouteS2, rec.Code) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // End to end through the whole app: a card made through the form appears |
| 200 | // in the feed, its text is served at its revision, and its admitted owner |
| 201 | // may see it. This is the wiring — the producer built over the app's own |
| 202 | // database and its own admission predicate. |
| 203 | func TestSuiteServesACardMadeThroughTheApp(t *testing.T) { |
| 204 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 205 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 206 | if err != nil { |
| 207 | t.Fatal(err) |
| 208 | } |
| 209 | t.Cleanup(func() { d.Close() }) |
| 210 | h, err := fichas.AppForTest(d, suiteConfig(t, suiteConsumers()), logger, TestOwner) |
| 211 | if err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | if rec := post(t, h, "/cards", url.Values{"f_name": {"Cnoc Teoranta"}, "f_email": {"orders@cnoc.example"}}); rec.Code != http.StatusSeeOther { |
| 215 | t.Fatalf("creating a card: %d", rec.Code) |
| 216 | } |
| 217 | |
| 218 | if rec := post(t, h, "/cards", url.Values{"f_name": {"Second card"}}); rec.Code != http.StatusSeeOther { |
| 219 | t.Fatalf("creating a second card: %d", rec.Code) |
| 220 | } |
| 221 | rec := call(h, "GET", suite.RouteS1, suiteToken, nil) |
| 222 | feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()) |
| 223 | if err != nil || len(feed.Rows) != 2 || feed.Rows[0].Gone { |
| 224 | t.Fatalf("S1: %+v, %v", feed, err) |
| 225 | } |
| 226 | // Revisions are random through the whole app (spec §6.2): two new |
| 227 | // cards, which a count would both put at 1, do not share one. |
| 228 | if feed.Rows[0].Revision < 1 || feed.Rows[1].Revision < 1 || feed.Rows[0].Revision == feed.Rows[1].Revision { |
| 229 | t.Errorf("S1 revisions %d and %d: not two distinct random revisions", feed.Rows[0].Revision, feed.Rows[1].Revision) |
| 230 | } |
| 231 | item, rev := feed.Rows[0].ItemID, feed.Rows[0].Revision |
| 232 | revision := strconv.FormatInt(rev, 10) |
| 233 | // "<card id>.<created_at unix nanos>" (spec §6.2). |
| 234 | if !regexp.MustCompile(`^[1-9][0-9]*\.[1-9][0-9]*$`).MatchString(item) { |
| 235 | t.Errorf("item_id %q is not <card id>.<stamp>", item) |
| 236 | } |
| 237 | |
| 238 | rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision="+revision, suiteToken, nil) |
| 239 | if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" || |
| 240 | !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") { |
| 241 | t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type")) |
| 242 | } |
| 243 | |
| 244 | pairs := []suite.ItemRevision{{ItemID: item, Revision: rev}} |
| 245 | rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...)) |
| 246 | if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE { |
| 247 | t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0]) |
| 248 | } |
| 249 | rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, "bo@example.com", pairs...)) |
| 250 | if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.NOT_VISIBLE { |
| 251 | t.Errorf("S2 for an address not admitted: %s", got[0]) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // Every suite response the app serves carries Cache-Control: no-store and |
| 256 | // Vary: Authorization (doctrine §6.5, revision 11) — a 200, each refusal, |
| 257 | // the cursor reset, the 401 and the mux's own 404 and 405 — as it leaves |
| 258 | // the process: through rastrillo.Handler, the assembly Serve uses, around |
| 259 | // fichas.App exactly as main builds it. server.Handler sets both, and |
| 260 | // conformance.CheckProducer checks Handler alone; this checks that nothing |
| 261 | // in front of it — rastrillo's panic recovery and security headers, and |
| 262 | // app.go's outer mux — drops or rewrites them. Today nothing does: |
| 263 | // rastrillo's securityHeaders sets only the CSP, nosniff, X-Frame-Options |
| 264 | // and Referrer-Policy, before the handler runs. |
| 265 | // |
| 266 | // The cursor reset is also checked end to end here: a cursor no Fichas log |
| 267 | // issued is exactly 409 {"code":"CURSOR_RESET"} at the app's edge, which |
| 268 | // suite.DecodeS1 reads as suite.ErrCursorReset. |
| 269 | // |
| 270 | // MUTATION-TESTED 2026-11-02, each reverted: a middleware wrapped round the |
| 271 | // suite mount in app.go that sets Cache-Control: private, max-age=60 as the |
| 272 | // status is written → every case; the same middleware deleting Vary → |
| 273 | // every case; the producer answering an unparseable cursor with a plain |
| 274 | // error (revision 10's 503) → "the cursor reset", twice. |
| 275 | func TestEverySuiteResponseIsNoStore(t *testing.T) { |
| 276 | served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: suiteApp(t, suiteConsumers()).(*http.ServeMux), ErrorPage: fichas.ErrorPage}) |
| 277 | if err != nil { |
| 278 | t.Fatalf("rastrillo.Handler: %v", err) |
| 279 | } |
| 280 | t.Cleanup(func() { closeDB() }) |
| 281 | |
| 282 | reset := call(served, "GET", suite.RouteS1+"?cursor=never-issued-by-fichas", suiteToken, nil) |
| 283 | if _, err := suite.DecodeS1(reset.Code, reset.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) { |
| 284 | t.Errorf("the cursor reset: %d %q, want %d %s", reset.Code, reset.Body.String(), suite.CursorResetStatus, suite.CursorResetBody) |
| 285 | } |
| 286 | |
| 287 | pair := suite.ItemRevision{ItemID: "1.1", Revision: 1} |
| 288 | for _, c := range []struct { |
| 289 | name, method, target, tok string |
| 290 | body []byte |
| 291 | want int |
| 292 | }{ |
| 293 | {"S1", "GET", suite.RouteS1, suiteToken, nil, http.StatusOK}, |
| 294 | {"the cursor reset", "GET", suite.RouteS1 + "?cursor=never-issued-by-fichas", suiteToken, nil, suite.CursorResetStatus}, |
| 295 | {"S2", "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, pair), http.StatusOK}, |
| 296 | {"S2, malformed", "POST", suite.RouteS2, suiteToken, []byte("{"), http.StatusBadRequest}, |
| 297 | {"S3, refused", "GET", suite.RouteS3 + "/1.1?revision=1", suiteToken, nil, http.StatusNotFound}, |
| 298 | {"no token", "GET", suite.RouteS1, "", nil, http.StatusUnauthorized}, |
| 299 | {"the mux's 404", "GET", "/suite/s9", suiteToken, nil, http.StatusNotFound}, |
| 300 | {"the mux's 405", "DELETE", suite.RouteS1, suiteToken, nil, http.StatusMethodNotAllowed}, |
| 301 | } { |
| 302 | rec := call(served, c.method, c.target, c.tok, c.body) |
| 303 | if rec.Code != c.want { |
| 304 | t.Errorf("%s: %d, want %d", c.name, rec.Code, c.want) |
| 305 | } |
| 306 | // The harness's own reading of the rule (conformance.storeAudit). |
| 307 | if cc, vary := rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"); cc != "no-store" || vary != "Authorization" { |
| 308 | t.Errorf("%s: Cache-Control %q, Vary %q; want no-store and Authorization", c.name, cc, vary) |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |