oficina / suite Public

Clone
git clone https://amadan.net/oficina/suite

Plain git — no account needed to clone.

Download

Download this file

1package server_test
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net/http"
10 "net/http/httptest"
11 "sort"
12 "strconv"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/suite"
18 "amadan.net/oficina/suite/conformance"
19 "amadan.net/oficina/suite/server"
20)
21
22// fixtureProducer is a correct Producer built from the custody fixture, the
23// same world the conformance harness checks.
24type fixtureProducer struct {
25 f suite.CustodyFixture
26 extraRows int // Feed returns this many more rows than the cases
27 contentErr error
28 feedErr error
29 ruleErr error
30 short bool // Rule answers one fewer than asked
31 cursor string // overrides the feed's cursor when set
32 content []byte // overrides S3 bytes when set
33 lastAsker suite.Subject
34 zeroTime bool // the first row carries no touched_at
35 zeroRev bool // the first row carries revision 0
36 resetStart bool // Feed resets even the beginning
37}
38
39func (p *fixtureProducer) find(id string) (suite.CustodyCase, bool) {
40 for _, c := range p.f.Cases {
41 if c.ItemID == id {
42 return c, true
43 }
44 }
45 return suite.CustodyCase{}, false
46}
47
48func (p *fixtureProducer) Feed(_ context.Context, cursor string, limit int) (suite.Feed, error) {
49 if p.feedErr != nil {
50 return suite.Feed{}, p.feedErr
51 }
52 if cursor == "end" {
53 return suite.Feed{Cursor: "end"}, nil
54 }
55 if cursor != "" || p.resetStart {
56 // The only cursors this log issues are "end" and the override, and
57 // a test's own; anything else names no position in it (§6.6).
58 if p.cursor == "" || cursor != p.cursor {
59 return suite.Feed{}, fmt.Errorf("fichas-like: cursor %q: %w", cursor, server.ErrCursorReset)
60 }
61 }
62 var rows []suite.FeedRow
63 for _, c := range p.f.Cases {
64 rows = append(rows, suite.FeedRow{ItemID: c.ItemID, Revision: c.Revision, Gone: c.Rung == suite.RungDeleted, TouchedAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)})
65 }
66 if p.zeroTime {
67 rows[0].TouchedAt = time.Time{}
68 }
69 if p.zeroRev {
70 rows[0].Revision = 0
71 }
72 for i := 0; i < p.extraRows; i++ {
73 rows = append(rows, suite.FeedRow{ItemID: "extra-" + strconv.Itoa(i), Revision: 1, TouchedAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)})
74 }
75 next := "end"
76 if p.cursor != "" {
77 next = p.cursor
78 }
79 if p.cursor == "-" {
80 next = ""
81 }
82 return suite.Feed{Cursor: next, Rows: rows}, nil
83}
84
85func (p *fixtureProducer) Rule(_ context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
86 p.lastAsker = asker
87 if p.ruleErr != nil {
88 return nil, p.ruleErr
89 }
90 out := make([]suite.Authorization, 0, len(pairs))
91 if asker.Kind != p.f.Asker.Kind {
92 for range pairs {
93 out = append(out, suite.UNKNOWN)
94 }
95 return out, nil
96 }
97 for _, pr := range pairs {
98 c, ok := p.find(pr.ItemID)
99 may := ok && asker == p.f.Asker && c.Rung != suite.RungDeleted && (c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant)
100 // STALE from the log, never by comparing numbers (§6.6): this log
101 // holds the current revision and the one before it.
102 switch {
103 case !may:
104 out = append(out, suite.NOT_VISIBLE)
105 case pr.Revision == c.Revision:
106 out = append(out, suite.VISIBLE)
107 case pr.Revision == c.PriorRevision:
108 out = append(out, suite.STALE)
109 default:
110 out = append(out, suite.UNKNOWN)
111 }
112 }
113 if p.short {
114 out = out[:len(out)-1]
115 }
116 return out, nil
117}
118
119func (p *fixtureProducer) Content(_ context.Context, id string, rev int64) ([]byte, error) {
120 if p.contentErr != nil {
121 return nil, p.contentErr
122 }
123 c, ok := p.find(id)
124 if !ok || c.Rung == suite.RungDeleted || rev != c.Revision {
125 return nil, suite.ErrNotAvailable
126 }
127 if p.content != nil {
128 return p.content, nil
129 }
130 return []byte(c.S3Body), nil
131}
132
133func producer(t *testing.T) *fixtureProducer {
134 t.Helper()
135 f, err := suite.LoadCustodyFixture()
136 if err != nil {
137 t.Fatal(err)
138 }
139 return &fixtureProducer{f: f}
140}
141
142const token = "a-test-token-for-memoria"
143
144func consumers(t *testing.T, tokens ...string) []server.Consumer {
145 t.Helper()
146 var ts []server.Token
147 for i, tok := range tokens {
148 ts = append(ts, server.Token{Epoch: i + 1, SHA256: server.TokenHash(tok)})
149 }
150 return []server.Consumer{{ID: "memoria", Tokens: ts}}
151}
152
153func do(h http.Handler, method, url, tok string, body []byte) *httptest.ResponseRecorder {
154 req := httptest.NewRequest(method, url, bytes.NewReader(body))
155 if tok != "" {
156 req.Header.Set("Authorization", "Bearer "+tok)
157 }
158 rec := httptest.NewRecorder()
159 h.ServeHTTP(rec, req)
160 return rec
161}
162
163// The routes this package serves pass the doctrine's own harness, driven
164// through a producer that only knows the fixture, mounted as an app mounts
165// it: Handler, behind a token (conformance.RunProducer, revision 11). The
166// tests below cover what the harness does not send.
167//
168// MUTATION-TESTED 2026-11-01, reverted: CheckProducer driving the deprecated
169// Routes in place of Handler → "a request with no token: got 404".
170//
171// MUTATION-TESTED 2026-11-02 (Fable's review of 0a59e7d, L6), reverted:
172// Authenticate's no-token 401 stripped of Cache-Control and Vary → "GET
173// /suite/s3 401: Cache-Control "" and Vary """ here; with CheckProducer's
174// anonymous probe sent around the header audit instead of through it (as
175// before), the same mutant passed this test.
176func TestRoutesPassConformance(t *testing.T) {
177 conformance.RunProducer(t, producer(t), suite.SubjectPersonRef)
178}
179
180// The deprecated Routes still serves what it served, for the apps whose
181// tests call it (the module is additive).
182func TestDeprecatedRoutesStillConform(t *testing.T) {
183 conformance.Run(t, server.Routes(producer(t), nil))
184}
185
186// No consumers, no routes (doctrine §3).
187func TestNoConsumersServesNothing(t *testing.T) {
188 if h := server.Handler(producer(t), nil, nil); h != nil {
189 t.Fatal("Handler with no consumers returned routes")
190 }
191}
192
193// Every failure to authenticate is the same empty 401, and both tokens of a
194// rotation are accepted.
195//
196// MUTATION-TESTED 2026-11-01, each reverted: the hash comparison skipped
197// (any bearer admitted) → "an unknown token"; only the first token of a
198// consumer compared → "the second token"; a reason written in the 401 body
199// → "alike". Revision 11: the scheme check removed (any seven bytes taken
200// as "Bearer ") → "not a bearer", which "Basic " never caught.
201func TestAuthentication(t *testing.T) {
202 h := server.Handler(producer(t), consumers(t, token, "the-next-token"), nil)
203 ok := do(h, "GET", suite.RouteS1, token, nil)
204 if ok.Code != 200 {
205 t.Fatalf("the configured token: %d", ok.Code)
206 }
207 if rec := do(h, "GET", suite.RouteS1, "the-next-token", nil); rec.Code != 200 {
208 t.Errorf("the second token of a rotation: %d", rec.Code)
209 }
210 var first string
211 for name, req := range map[string]func() *http.Request{
212 "no header": func() *http.Request { return httptest.NewRequest("GET", suite.RouteS1, nil) },
213 "an unknown token": func() *http.Request {
214 r := httptest.NewRequest("GET", suite.RouteS1, nil)
215 r.Header.Set("Authorization", "Bearer not-the-token")
216 return r
217 },
218 // Seven bytes, as "Bearer " is: with "Basic " (six) the token was
219 // cut one byte short and refused whether or not the scheme was
220 // checked (Fable, review of c38e3ad, L5).
221 "not a bearer": func() *http.Request {
222 r := httptest.NewRequest("GET", suite.RouteS1, nil)
223 r.Header.Set("Authorization", "Digest "+token)
224 return r
225 },
226 "an empty bearer": func() *http.Request {
227 r := httptest.NewRequest("GET", suite.RouteS1, nil)
228 r.Header.Set("Authorization", "Bearer ")
229 return r
230 },
231 } {
232 rec := httptest.NewRecorder()
233 h.ServeHTTP(rec, req())
234 if rec.Code != 401 {
235 t.Errorf("%s: %d, want 401", name, rec.Code)
236 }
237 got := signature(rec)
238 if first == "" {
239 first = got
240 } else if got != first {
241 t.Errorf("%s: refusals not alike: %q vs %q", name, got, first)
242 }
243 }
244}
245
246// MUTATION-TESTED 2026-11-01, reverted: the SHA-256 length check reduced to
247// "not empty" → "31 bytes of hex" and "33 bytes of hex" (Fable, review of
248// c38e3ad, L5: nothing tested it).
249func TestParseConsumers(t *testing.T) {
250 good := `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("x") + `"}]}]`
251 if cs, err := server.ParseConsumers(good); err != nil || len(cs) != 1 || cs[0].ID != "memoria" {
252 t.Fatalf("good: %+v, %v", cs, err)
253 }
254 if cs, err := server.ParseConsumers(" "); err != nil || cs != nil {
255 t.Errorf("empty is no consumers: %+v, %v", cs, err)
256 }
257 h := server.TokenHash("x")
258 for name, bad := range map[string]string{
259 "an unknown field": `[{"consumer_id":"m","origin":"x","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
260 "three tokens": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"},{"epoch":2,"sha256":"` + h + `"},{"epoch":3,"sha256":"` + h + `"}]}]`,
261 "no tokens": `[{"consumer_id":"m","tokens":[]}]`,
262 "not hex": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"plaintext-token"}]}]`,
263 // Hex, and a byte short of a SHA-256: no token can ever match it, so
264 // it is a typo that would serve nobody (Fable, review of c38e3ad, L5).
265 "31 bytes of hex": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h[:62] + `"}]}]`,
266 "33 bytes of hex": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `00"}]}]`,
267 "a repeated id": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]},{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
268 "trailing content": good + `[]`,
269 "not a list": `{"consumer_id":"m"}`,
270 } {
271 if _, err := server.ParseConsumers(bad); err == nil {
272 t.Errorf("%s: accepted", name)
273 }
274 }
275 if cs, err := server.ConsumersFromEnv(func(k string) string {
276 if k == "DOCS_SUITE_CONSUMERS" {
277 return good
278 }
279 return ""
280 }, "docs"); err != nil || len(cs) != 1 {
281 t.Errorf("ConsumersFromEnv: %+v, %v", cs, err)
282 }
283}
284
285// S1 holds the producer to what the consumer's decoder demands.
286func TestS1(t *testing.T) {
287 p := producer(t)
288 h := server.Routes(p, nil)
289 rec := do(h, "GET", suite.RouteS1+"?cursor=", "", nil)
290 feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
291 if err != nil || len(feed.Rows) != len(p.f.Cases) || feed.Cursor != "end" {
292 t.Fatalf("first page: %+v, %v", feed, err)
293 }
294 // At the tip: rows [] (never null) and the same cursor back.
295 tip := do(h, "GET", suite.RouteS1+"?cursor=end", "", nil)
296 if !strings.Contains(tip.Body.String(), `"rows":[]`) {
297 t.Errorf("rows: the tip's rows are not an empty list: %s", tip.Body.String())
298 }
299 if feed, err := suite.DecodeS1(tip.Code, tip.Body.Bytes()); err != nil || feed.Cursor != "end" || len(feed.Rows) != 0 {
300 t.Errorf("tip: %+v, %v", feed, err)
301 }
302 p.cursor = "-"
303 if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 500 {
304 t.Errorf("an empty cursor from the producer: %d, want 500", rec.Code)
305 }
306 p.cursor, p.feedErr = "", errors.New("db down")
307 if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 503 {
308 t.Errorf("a failed feed: %d, want 503 (never an empty page)", rec.Code)
309 }
310}
311
312// S2 decodes strictly, caps the batch, echoes every pair, and fails loudly.
313//
314// MUTATION-TESTED 2026-11-01, each reverted: DisallowUnknownFields removed →
315// "an unknown field"; the cap check removed → "257 pairs"; the answer-count
316// check removed → "a short answer"; a producer error answered 200 with no
317// results → "a failed rule".
318func TestS2(t *testing.T) {
319 p := producer(t)
320 h := server.Routes(p, nil)
321 ask := func(body string) *httptest.ResponseRecorder { return do(h, "POST", suite.RouteS2, "", []byte(body)) }
322 asker := `{"kind":"person_ref","value":"pers_ana"}`
323 ok := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7},{"item_id":"doc-link","revision":5}]}`)
324 got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "doc-team", Revision: 7}, {ItemID: "doc-link", Revision: 5}}, ok.Code, ok.Body.Bytes())
325 if len(got) != 2 || got[0] != suite.VISIBLE || got[1] != suite.NOT_VISIBLE {
326 t.Fatalf("answers = %v (%d %s)", got, ok.Code, ok.Body.String())
327 }
328 if p.lastAsker != (suite.Subject{Kind: suite.SubjectPersonRef, Value: "pers_ana"}) {
329 t.Errorf("the asker reached the producer as %+v", p.lastAsker)
330 }
331 var many []string
332 for i := 0; i < 257; i++ {
333 many = append(many, `{"item_id":"doc-team","revision":7}`)
334 }
335 for name, body := range map[string]string{
336 "an unknown field": `{"asker":` + asker + `,"pairs":[],"extra":1}`,
337 "257 pairs": `{"asker":` + asker + `,"pairs":[` + strings.Join(many, ",") + `]}`,
338 "a bad kind": `{"asker":{"kind":"email","value":"x"},"pairs":[]}`,
339 "an empty asker": `{"asker":{"kind":"address","value":""},"pairs":[]}`,
340 "no pairs": `{"asker":` + asker + `}`,
341 "an empty item id": `{"asker":` + asker + `,"pairs":[{"item_id":"","revision":1}]}`,
342 "not JSON": `nope`,
343 "two documents": `{"asker":` + asker + `,"pairs":[]}{}`,
344 } {
345 if rec := ask(body); rec.Code != 400 {
346 t.Errorf("%s: %d, want 400", name, rec.Code)
347 }
348 }
349 p.short = true
350 if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 500 {
351 t.Errorf("a short answer: %d, want 500", rec.Code)
352 }
353 p.short, p.ruleErr = false, errors.New("roster unreachable")
354 if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 503 {
355 t.Errorf("a failed rule: %d, want 503", rec.Code)
356 }
357}
358
359// Every S3 refusal is the same response: a deleted item, an id that never
360// existed, a superseded, missing or malformed revision, and an item too
361// large to serve.
362//
363// MUTATION-TESTED 2026-11-01, each reverted: a malformed revision answered
364// 400 → "malformed"; the size check removed → "too large"; ErrNotAvailable
365// answered 503 → "deleted".
366func TestS3RefusesAlike(t *testing.T) {
367 p := producer(t)
368 h := server.Routes(p, nil)
369 base := do(h, "GET", suite.RouteS3+"/"+suite.NonexistentItemID+"?revision=1", "", nil)
370 if base.Code != 404 {
371 t.Fatalf("baseline: %d", base.Code)
372 }
373 sig := signature
374 for name, url := range map[string]string{
375 "deleted": suite.RouteS3 + "/doc-deleted?revision=6",
376 "superseded": suite.RouteS3 + "/doc-team?revision=6",
377 "missing": suite.RouteS3 + "/doc-team",
378 "malformed": suite.RouteS3 + "/doc-team?revision=seven",
379 "zero": suite.RouteS3 + "/doc-team?revision=0",
380 } {
381 if rec := do(h, "GET", url, "", nil); sig(rec) != sig(base) {
382 t.Errorf("%s: %q, want the baseline %q", name, sig(rec), sig(base))
383 }
384 }
385 p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes+1)
386 if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); sig(rec) != sig(base) {
387 t.Errorf("too large: %d, want the baseline", rec.Code)
388 }
389 p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes)
390 if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") || !bytes.Equal(rec.Body.Bytes(), p.content) {
391 t.Errorf("at the limit: %d %s, %d bytes", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len())
392 }
393 // A producer that fails is not an item that is unavailable: 503, which
394 // the consumer retries, never the 404 it would count as gone.
395 p.content, p.contentErr = nil, errors.New("replay failed")
396 if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Code != 503 {
397 t.Errorf("a failed producer: %d, want 503", rec.Code)
398 }
399}
400
401// Astra's survivors (2026-11-01).
402//
403// MUTATION-TESTED 2026-11-01, each reverted: only the first consumer
404// compared → "a second consumer"; the consumer left out of the context →
405// "context"; the S2 body cap removed → "an oversized body"; the page limit
406// check removed → "a page over the limit"; a producer error logged with its
407// text → "the log"; Decoder.More() back as the end check → "trailing".
408func TestTheSurvivors(t *testing.T) {
409 two := append(consumers(t, token), server.Consumer{ID: "another", Tokens: []server.Token{{Epoch: 1, SHA256: server.TokenHash("another-token")}}})
410 h := server.Handler(producer(t), two, nil)
411 if rec := do(h, "GET", suite.RouteS1, "another-token", nil); rec.Code != 200 {
412 t.Errorf("a second consumer: %d", rec.Code)
413 }
414 who := server.Authenticate(two, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
415 c, _ := server.ConsumerFrom(r.Context())
416 w.Write([]byte(c.ID))
417 }))
418 if rec := do(who, "GET", "/", "another-token", nil); rec.Body.String() != "another" {
419 t.Errorf("context: the consumer is %q", rec.Body.String())
420 }
421
422 p := producer(t)
423 var logs bytes.Buffer
424 routes := server.Routes(p, slog.New(slog.NewTextHandler(&logs, nil)))
425 big := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"` + strings.Repeat("a", 300<<10) + `","revision":1}]}`
426 if rec := do(routes, "POST", suite.RouteS2, "", []byte(big)); rec.Code != 400 {
427 t.Errorf("an oversized body: %d, want 400", rec.Code)
428 }
429 p.extraRows = server.FeedPageLimit
430 if rec := do(routes, "GET", suite.RouteS1, "", nil); rec.Code != 500 {
431 t.Errorf("a page over the limit: %d, want 500", rec.Code)
432 }
433 p.extraRows = 0
434 const secret = "Q3 board pack: acquisition of Acme"
435 p.feedErr, p.ruleErr, p.contentErr = errors.New(secret), errors.New(secret), errors.New(secret)
436 do(routes, "GET", suite.RouteS1, "", nil)
437 do(routes, "POST", suite.RouteS2, "", []byte(`{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":7}]}`))
438 do(routes, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil)
439 if strings.Contains(logs.String(), "acquisition") {
440 t.Errorf("the log: a producer's error text was logged: %s", logs.String())
441 }
442 if !strings.Contains(logs.String(), "S1") || !strings.Contains(logs.String(), "S2") || !strings.Contains(logs.String(), "S3") {
443 t.Errorf("the log: failures were not logged at all: %s", logs.String())
444 }
445
446 p.feedErr, p.ruleErr, p.contentErr = nil, nil, nil
447 for _, junk := range []string{"]", "}", "[]", `{"a":1}`} {
448 body := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":7}]}` + junk
449 if rec := do(routes, "POST", suite.RouteS2, "", []byte(body)); rec.Code != 400 {
450 t.Errorf("trailing %q after an S2 request: %d, want 400", junk, rec.Code)
451 }
452 }
453 good := `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("x") + `"}]}]`
454 for _, bad := range []string{good + "]", good + "}", "null", "[]", `{"consumer_id":"m"}`} {
455 if _, err := server.ParseConsumers(bad); err == nil {
456 t.Errorf("trailing or not a list: %q accepted", bad)
457 }
458 }
459}
460
461// S1's guards at their edges (Astra, 2026-11-01).
462//
463// MUTATION-TESTED 2026-11-01, each reverted: the page limit off by one
464// (>= for >) → "exactly the limit"; the empty item id check removed → "an
465// empty item id".
466func TestS1Edges(t *testing.T) {
467 p := producer(t)
468 h := server.Routes(p, nil)
469 p.extraRows = server.FeedPageLimit - len(p.f.Cases)
470 if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 200 {
471 t.Errorf("exactly the limit: %d, want 200", rec.Code)
472 }
473 p.extraRows = 0
474 bad := &emptyIDProducer{fixtureProducer: p}
475 if rec := do(server.Routes(bad, nil), "GET", suite.RouteS1, "", nil); rec.Code != 500 {
476 t.Errorf("an empty item id: %d, want 500", rec.Code)
477 }
478}
479
480type emptyIDProducer struct{ *fixtureProducer }
481
482func (p *emptyIDProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
483 f, err := p.fixtureProducer.Feed(ctx, cursor, limit)
484 if len(f.Rows) > 0 {
485 f.Rows[0].ItemID = ""
486 }
487 return f, err
488}
489
490// signature is a response as a client could compare it: status, every
491// header, body.
492func signature(r *httptest.ResponseRecorder) string {
493 var hs []string
494 for k, v := range r.Header() {
495 hs = append(hs, k+"="+strings.Join(v, ","))
496 }
497 sort.Strings(hs)
498 return strconv.Itoa(r.Code) + "|" + strings.Join(hs, "|") + "|" + r.Body.String()
499}
500
501// A cursor the producer's log does not recognise is S1's one fixed 409, and
502// the consumer's decoder reads it as a reset (doctrine §6.6, revision 11).
503// The beginning is never reset: a producer that resets "" would send a
504// consumer back to "" for ever, so that is a 500.
505//
506// MUTATION-TESTED 2026-11-01, each reverted: the ErrCursorReset branch
507// removed (a reset answered as a failed feed) → "a foreign cursor"; the ""
508// guard removed → "the beginning reset"; the body written through
509// json.Encoder as an object with a second field → "a foreign cursor".
510func TestS1CursorReset(t *testing.T) {
511 p := producer(t)
512 h := server.Handler(p, consumers(t, token), nil)
513 rec := do(h, "GET", suite.RouteS1+"?cursor=17.4421", token, nil)
514 if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) {
515 t.Errorf("a foreign cursor: %d %q, %v; want the reset", rec.Code, rec.Body.String(), err)
516 }
517 if rec.Code != 409 || rec.Body.String() != suite.CursorResetBody || rec.Header().Get("Content-Type") != "application/json" {
518 t.Errorf("a foreign cursor: %d %q %q, want exactly 409 %s as JSON", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type"), suite.CursorResetBody)
519 }
520 // The cursors the log did issue still read.
521 if rec := do(h, "GET", suite.RouteS1+"?cursor=end", token, nil); rec.Code != 200 {
522 t.Errorf("the log's own cursor: %d", rec.Code)
523 }
524 p.resetStart = true
525 if rec := do(h, "GET", suite.RouteS1+"?cursor=", token, nil); rec.Code != 500 {
526 t.Errorf("the beginning reset: %d, want 500", rec.Code)
527 }
528}
529
530// Every response the package writes is one nobody may keep, and refusals of
531// a kind stay byte-identical with the headers on (Fable, review of c38e3ad,
532// M3). Through Handler, so the 401 is covered, and including the mux's own
533// 404 and 405, which no route of ours writes.
534//
535// MUTATION-TESTED 2026-11-01, each reverted: noStore dropped from routes →
536// "Routes" (through Handler, Authenticate's own noStore still covers it);
537// noStore dropped from Authenticate → "no token"; Vary not set → every
538// response.
539func TestEveryResponseIsNoStore(t *testing.T) {
540 p := producer(t)
541 h := server.Handler(p, consumers(t, token), nil)
542 ask := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":7}]}`
543 cases := map[string]func() *httptest.ResponseRecorder{
544 "S1 200": func() *httptest.ResponseRecorder { return do(h, "GET", suite.RouteS1, token, nil) },
545 "S1 409": func() *httptest.ResponseRecorder { return do(h, "GET", suite.RouteS1+"?cursor=x", token, nil) },
546 "S2 200": func() *httptest.ResponseRecorder { return do(h, "POST", suite.RouteS2, token, []byte(ask)) },
547 "S2 400": func() *httptest.ResponseRecorder { return do(h, "POST", suite.RouteS2, token, []byte("nope")) },
548 "S3 200": func() *httptest.ResponseRecorder {
549 return do(h, "GET", suite.RouteS3+"/doc-team?revision=7", token, nil)
550 },
551 "S3 404": func() *httptest.ResponseRecorder {
552 return do(h, "GET", suite.RouteS3+"/doc-deleted?revision=6", token, nil)
553 },
554 "S3 POST": func() *httptest.ResponseRecorder {
555 return do(h, "POST", suite.RouteS3+"/doc-team?revision=7", token, nil)
556 },
557 "no such route": func() *httptest.ResponseRecorder { return do(h, "GET", "/suite/s9", token, nil) },
558 "no token": func() *httptest.ResponseRecorder { return do(h, "GET", suite.RouteS1, "", nil) },
559 "a wrong token": func() *httptest.ResponseRecorder {
560 return do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "nope", nil)
561 },
562 }
563 for name, run := range cases {
564 rec := run()
565 if rec.Header().Get("Cache-Control") != "no-store" || rec.Header().Get("Vary") != "Authorization" {
566 t.Errorf("%s (%d): Cache-Control %q, Vary %q; want no-store and Authorization", name, rec.Code, rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"))
567 }
568 }
569 // The deprecated Routes too, which apps' own tests still call.
570 if rec := do(server.Routes(p, nil), "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Header().Get("Cache-Control") != "no-store" || rec.Header().Get("Vary") != "Authorization" {
571 t.Errorf("Routes: Cache-Control %q, Vary %q", rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"))
572 }
573 if cases["S3 POST"]().Code == 200 {
574 t.Error("S3 served a POST")
575 }
576 p.feedErr, p.ruleErr, p.contentErr = errors.New("down"), errors.New("down"), errors.New("down")
577 for name, rec := range map[string]*httptest.ResponseRecorder{
578 "S1 503": do(h, "GET", suite.RouteS1, token, nil),
579 "S2 503": do(h, "POST", suite.RouteS2, token, []byte(ask)),
580 "S3 503": do(h, "GET", suite.RouteS3+"/doc-team?revision=7", token, nil),
581 } {
582 if rec.Code != 503 || rec.Header().Get("Cache-Control") != "no-store" || rec.Header().Get("Vary") != "Authorization" {
583 t.Errorf("%s: %d, Cache-Control %q, Vary %q", name, rec.Code, rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"))
584 }
585 }
586}
587
588// Revision 11's edges (Fable, review of c38e3ad, L5): S2 refuses a revision
589// under 1 in a pair, as S3 does; a feed row with no touched_at or a revision
590// under 1 is the producer's mistake, a 500, never a page.
591//
592// MUTATION-TESTED 2026-11-01, each reverted: S2's revision check removed →
593// "revision 0" and "revision -1"; checkFeed's TouchedAt check removed → "no
594// touched_at"; checkFeed's revision check removed → "revision 0 in the feed".
595func TestRevision11Edges(t *testing.T) {
596 p := producer(t)
597 h := server.Handler(p, consumers(t, token), nil)
598 for name, rev := range map[string]string{"revision 0": "0", "revision -1": "-1"} {
599 body := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":` + rev + `}]}`
600 if rec := do(h, "POST", suite.RouteS2, token, []byte(body)); rec.Code != 400 {
601 t.Errorf("%s in an S2 pair: %d, want 400", name, rec.Code)
602 }
603 }
604 p.zeroTime = true
605 if rec := do(h, "GET", suite.RouteS1, token, nil); rec.Code != 500 {
606 t.Errorf("no touched_at: %d, want 500", rec.Code)
607 }
608 p.zeroTime, p.zeroRev = false, true
609 if rec := do(h, "GET", suite.RouteS1, token, nil); rec.Code != 500 {
610 t.Errorf("revision 0 in the feed: %d, want 500", rec.Code)
611 }
612}
613