oficina / suite Public

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

Plain git — no account needed to clone.

Download

Download this file

1package conformance_test
2
3import (
4 "encoding/json"
5 "net/http"
6 "strconv"
7 "strings"
8 "testing"
9
10 "amadan.net/oficina/suite"
11 "amadan.net/oficina/suite/conformance"
12)
13
14// referenceServer is a correct server half, built straight from the fixture.
15// It exists so the harness can be tested against something that should pass —
16// and, with its behaviour bent, against things that should fail.
17type referenceServer struct {
18 fixture suite.CustodyFixture
19
20 // The bugs each broken variant introduces.
21 forbidInsteadOfNotFound bool // answers 403 where the contract says 404
22 intersectWithTeamRung bool // revision 9's rule: NOT_VISIBLE for anything off the team rung
23 linkCountsAsGrant bool // answers VISIBLE for a link-shared item
24 leakVisibilityInFeed bool // adds a field the feed row may not carry
25 leakBodyInRefusal bool // right status, and the item's secrets in the body
26 wrongBodyForTeamItem bool // 200, carrying a different item's bytes
27 tellExistenceApart bool // a different refusal for "never existed"
28 ignoreAskerAndRevision bool // VISIBLE for any asker, at any revision
29 serveSuperseded bool // 200 with today's bytes for an older revision
30 staleWhenAhead bool // STALE for a revision ahead of the log
31 revisionBeforePerson bool // STALE for a stranger at an old revision
32 privateAsGone bool // revision 9's feed: non-team items gone
33 leakHeaderInRefusal bool // the right 404, with a title in a header
34 serveFuture bool // 200 with today's bytes for a newer revision
35 ignoreKind bool // answers by the asker's value, whatever its kind
36 deletedLive bool // a deleted item advertised live in the feed
37 staleFeedRevision bool // feed rows one revision behind
38 neverEnds bool // a new cursor every page, for ever
39 stuckWithRows bool // the same cursor back, with rows
40 reservedCursor bool // cursors that need query escaping (correct)
41 repeatEarlierRow bool // an item's last row older than its current revision
42
43 // Revision 11 (Fable's review of c38e3ad).
44 numericRevisions bool // STALE for any revision below current, held in the log or not
45 failOpen bool // VISIBLE for an id it does not know
46 titleInS2Row bool // an S2 row carrying the item's title
47 missingRevisionIsNow bool // S3 with no ?revision serves the current bytes
48 malformedRevision400 bool // S3 answers 400 for a malformed revision
49 s3ServesPost bool // S3 serves a POST
50 foreignCursorIsTip bool // a cursor the log never issued answered as the tip
51 foreignCursorFails bool // a cursor the log never issued answered 503
52 cacheable bool // no Cache-Control: no-store
53 noVary bool // no-store, and no Vary: Authorization
54}
55
56func (s *referenceServer) find(itemID string) (suite.CustodyCase, bool) {
57 for _, c := range s.fixture.Cases {
58 if c.ItemID == itemID {
59 return c, true
60 }
61 }
62 return suite.CustodyCase{}, false
63}
64
65func (s *referenceServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
66 if !s.cacheable {
67 w.Header().Set("Cache-Control", "no-store")
68 if !s.noVary {
69 w.Header().Set("Vary", "Authorization")
70 }
71 }
72 switch {
73 case strings.HasPrefix(r.URL.Path, suite.RouteS3+"/") && (r.Method == "GET" || s.s3ServesPost):
74 s.serveS3(w, r)
75 case r.URL.Path == suite.RouteS2 && r.Method == "POST":
76 s.serveS2(w, r)
77 case r.URL.Path == suite.RouteS1 && r.Method == "GET":
78 s.serveS1(w, r)
79 default:
80 w.WriteHeader(http.StatusMethodNotAllowed)
81 }
82}
83
84func (s *referenceServer) serveS3(w http.ResponseWriter, r *http.Request) {
85 id := strings.TrimPrefix(r.URL.Path, suite.RouteS3+"/")
86 c, ok := s.find(id)
87 if !ok {
88 w.WriteHeader(404)
89 if s.tellExistenceApart {
90 // A different refusal for something that never existed lets a
91 // consumer separate "no such item" from "not yours", which is
92 // exactly what §4.2 forbids.
93 w.Write([]byte("no such item"))
94 }
95 return
96 }
97 // Revision 10: every live item is held, so every live item is served —
98 // at its current revision only.
99 raw := r.URL.Query().Get("revision")
100 rev, err := strconv.ParseInt(raw, 10, 64)
101 if raw == "" && s.missingRevisionIsNow {
102 rev = c.Revision
103 }
104 if raw != "" && err != nil && s.malformedRevision400 {
105 w.WriteHeader(400)
106 return
107 }
108 if c.Rung != suite.RungDeleted && (rev == c.Revision || (s.serveSuperseded && rev < c.Revision) || (s.serveFuture && rev > c.Revision)) {
109 w.WriteHeader(200)
110 if s.wrongBodyForTeamItem {
111 w.Write([]byte("the bytes of some other document entirely"))
112 return
113 }
114 w.Write([]byte(c.S3Body))
115 return
116 }
117 if s.forbidInsteadOfNotFound {
118 w.WriteHeader(403)
119 return
120 }
121 if s.leakHeaderInRefusal {
122 w.Header().Set("X-Item-Title", c.Name)
123 }
124 w.WriteHeader(404)
125 if s.leakBodyInRefusal {
126 // The status the contract demands, and the secret in the body anyway.
127 w.Write([]byte("refused: " + c.Name + " at revision " + strconv.FormatInt(c.Revision, 10)))
128 }
129}
130
131func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
132 var req suite.S2Request
133 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
134 w.WriteHeader(400)
135 return
136 }
137
138 type result struct {
139 ItemID string `json:"item_id"`
140 Revision int64 `json:"revision"`
141 Result suite.Authorization `json:"result"`
142 Title string `json:"title,omitempty"`
143 }
144 out := struct {
145 Results []result `json:"results"`
146 }{}
147
148 if req.Asker.Kind != s.fixture.Asker.Kind && !s.ignoreKind {
149 // An asker of a kind this server does not key on: UNKNOWN for the
150 // whole call (gate 2).
151 for _, p := range req.Pairs {
152 out.Results = append(out.Results, result{ItemID: p.ItemID, Revision: p.Revision, Result: suite.UNKNOWN})
153 }
154 w.Header().Set("Content-Type", "application/json")
155 json.NewEncoder(w).Encode(out)
156 return
157 }
158 stranger := req.Asker.Value != s.fixture.Asker.Value
159
160 // mayOpen is the app's own read check (revision 10): the team rung for
161 // any member, the item's owner, or a live individual grant. A link is
162 // not a grant, and a deleted item opens for nobody.
163 mayOpen := func(c suite.CustodyCase) bool {
164 if c.Rung == suite.RungDeleted {
165 return false
166 }
167 if stranger {
168 // The fixture's stranger owns nothing and holds no grant, so
169 // nothing opens for them. Whether a removed member keeps what
170 // they own is not ruled (doctrine §14) and not in the fixture.
171 return false
172 }
173 if s.linkCountsAsGrant && c.Link != "" {
174 return true
175 }
176 if s.intersectWithTeamRung {
177 return c.Rung == suite.RungTeam
178 }
179 return c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant
180 }
181
182 for _, p := range req.Pairs {
183 c, ok := s.find(p.ItemID)
184 answer := suite.NOT_VISIBLE
185 switch {
186 case !ok:
187 answer = suite.NOT_VISIBLE
188 if s.failOpen {
189 answer = suite.VISIBLE
190 }
191
192 case s.ignoreAskerAndRevision:
193 // Answers from the rung alone: any asker, any revision. This is
194 // the shape a server takes when nobody ever varied either.
195 if c.Rung == suite.RungTeam {
196 answer = suite.VISIBLE
197 }
198
199 case stranger && s.revisionBeforePerson && p.Revision < c.Revision:
200 answer = suite.STALE
201
202 case !mayOpen(c):
203 answer = suite.NOT_VISIBLE
204
205 case p.Revision == c.Revision:
206 answer = suite.VISIBLE
207
208 case p.Revision == c.PriorRevision:
209 // In the log, and not current (§6.6): decided from the log.
210 answer = suite.STALE
211
212 case s.numericRevisions && p.Revision < c.Revision:
213 // The counter's habit: below current reads as "older".
214 answer = suite.STALE
215
216 case s.staleWhenAhead && p.Revision > c.Revision:
217 answer = suite.STALE
218
219 default:
220 // A revision the log does not hold (§4.3, §6.6).
221 answer = suite.UNKNOWN
222 }
223 row := result{ItemID: p.ItemID, Revision: p.Revision, Result: answer}
224 if s.titleInS2Row && ok {
225 row.Title = c.Name
226 }
227 out.Results = append(out.Results, row)
228 }
229
230 w.Header().Set("Content-Type", "application/json")
231 json.NewEncoder(w).Encode(out)
232}
233
234func (s *referenceServer) serveS1(w http.ResponseWriter, r *http.Request) {
235 rows := []map[string]any{}
236 for _, c := range s.fixture.Cases {
237 rev := c.Revision
238 if s.staleFeedRevision {
239 rev--
240 }
241 row := map[string]any{
242 "item_id": c.ItemID,
243 "revision": rev,
244 "gone": (c.Rung == suite.RungDeleted && !s.deletedLive) || (s.privateAsGone && c.Rung != suite.RungTeam),
245 "touched_at": "2026-09-05T09:00:00Z",
246 }
247 if s.leakVisibilityInFeed {
248 row["visible_to_team"] = c.Rung == suite.RungTeam
249 }
250 rows = append(rows, row)
251 }
252 // Two pages of rows, and then the tip, which answers the cursor it was
253 // given. A correct feed may page; the harness must follow it.
254 cursor := r.URL.Query().Get("cursor")
255 half := len(rows) / 2
256 var page []map[string]any
257 next := cursor
258 issued := []string{"", "c-1", "c-2"}
259 if s.reservedCursor {
260 // A cursor with characters a query string must escape. A harness
261 // that sent it unescaped would read "c 1&x=y" as "c 1".
262 issued = []string{"", "c 1&x=y", "c+2#end"}
263 }
264 switch cursor {
265 case issued[0]:
266 page, next = rows[:half], issued[1]
267 case issued[1]:
268 page, next = rows[half:], issued[2]
269 case issued[2]:
270 page = []map[string]any{}
271 default:
272 // A cursor this log never issued (§6.6, revision 11).
273 switch {
274 case s.foreignCursorIsTip:
275 page = []map[string]any{}
276 case s.foreignCursorFails:
277 w.WriteHeader(503)
278 return
279 default:
280 w.Header().Set("Content-Type", "application/json")
281 w.WriteHeader(suite.CursorResetStatus)
282 w.Write([]byte(suite.CursorResetBody))
283 return
284 }
285 }
286 if s.repeatEarlierRow && cursor == issued[1] {
287 // The second page repeats an item from the first at an older
288 // revision: the item's state is its LAST row, and it is stale.
289 stale := map[string]any{}
290 for k, v := range rows[0] {
291 stale[k] = v
292 }
293 stale["revision"] = rows[0]["revision"].(int64) - 1
294 page = append(page, stale)
295 }
296 if s.neverEnds {
297 next = cursor + "x"
298 }
299 if s.stuckWithRows && cursor == issued[1] {
300 next = cursor
301 }
302 w.Header().Set("Content-Type", "application/json")
303 json.NewEncoder(w).Encode(map[string]any{"cursor": next, "rows": page})
304}
305
306func newReference(t *testing.T) *referenceServer {
307 t.Helper()
308 f, err := suite.LoadCustodyFixture()
309 if err != nil {
310 t.Fatalf("loading fixture: %v", err)
311 }
312 return &referenceServer{fixture: f}
313}
314
315// A correct server half passes. Without this the harness could fail
316// everything and still catch every bug below.
317func TestHarnessPassesACorrectServer(t *testing.T) {
318 report := conformance.Check(newReference(t))
319
320 if len(report.Failures) != 0 {
321 t.Errorf("a correct server failed conformance: %v", report.Failures)
322 }
323}
324
325// Gate 3's real target. A server answering 403 for a non-team item tells the
326// caller the item exists, which is what "404, never 403" hides.
327func TestHarnessCatches403ForANonTeamItem(t *testing.T) {
328 s := newReference(t)
329 s.forbidInsteadOfNotFound = true
330
331 report := conformance.Check(s)
332
333 if len(report.Failures) == 0 {
334 t.Error("harness passed a server answering 403 where 404 is required")
335 }
336}
337
338// Revision 10 (Paul, 2026-11-01) removed §4.3's custody intersection: the
339// consumer holds every live item, and S2 answers from the app's own read
340// check. A server still answering by revision 9's rule — NOT_VISIBLE for
341// anything off the team rung — hides a person's own private documents and
342// those granted to them from their own search.
343func TestHarnessCatchesTheOldTeamOnlyRule(t *testing.T) {
344 s := newReference(t)
345 s.intersectWithTeamRung = true
346
347 report := conformance.Check(s)
348
349 if len(report.Failures) == 0 {
350 t.Error("harness passed a server whose S2 still intersects with the team rung")
351 }
352}
353
354// A link is not a grant (§4.2), and with custody widened it is the line
355// that keeps a link-shared private document out of a teammate's search.
356func TestHarnessCatchesALinkCountedAsAGrant(t *testing.T) {
357 s := newReference(t)
358 s.linkCountsAsGrant = true
359
360 report := conformance.Check(s)
361
362 if len(report.Failures) == 0 {
363 t.Error("harness passed a server whose S2 treats a read link as a grant")
364 }
365}
366
367// Status alone is not enough. A server can return the required 404 and put
368// the item's secrets in the body, and every caller that reads the raw response
369// gets them. GPT-6 module review, finding 3.
370func TestHarnessCatchesASecretInARefusalBody(t *testing.T) {
371 s := newReference(t)
372 s.leakBodyInRefusal = true
373
374 report := conformance.Check(s)
375
376 if len(report.Failures) == 0 {
377 t.Error("harness passed a server leaking the item in its 404 body")
378 }
379}
380
381// A 200 carrying the wrong item's bytes is a leak in the other direction, and
382// checking only the status misses it.
383func TestHarnessCatchesTheWrongBodyForATeamItem(t *testing.T) {
384 s := newReference(t)
385 s.wrongBodyForTeamItem = true
386
387 report := conformance.Check(s)
388
389 if len(report.Failures) == 0 {
390 t.Error("harness passed a server returning another item's bytes")
391 }
392}
393
394// "Not team-visible" and "does not exist" must be the same answer, and no
395// fixture case can prove it — every case is an item that exists.
396func TestHarnessCatchesDistinguishableNonexistence(t *testing.T) {
397 s := newReference(t)
398 s.tellExistenceApart = true
399
400 report := conformance.Check(s)
401
402 if len(report.Failures) == 0 {
403 t.Error("harness passed a server whose refusal reveals whether the item exists")
404 }
405}
406
407// S2 carries a named asker and a revision, and a server can pass a
408// status-and-rung harness while reading neither. GPT-6 module review,
409// finding 5.
410func TestHarnessCatchesAServerIgnoringAskerAndRevision(t *testing.T) {
411 s := newReference(t)
412 s.ignoreAskerAndRevision = true
413
414 report := conformance.Check(s)
415
416 if len(report.Failures) == 0 {
417 t.Error("harness passed a server that answers from the rung alone, reading neither asker nor revision")
418 }
419}
420
421// The leak memoria's draft 1 shipped: a visibility flag on a feed row.
422func TestHarnessCatchesAFeedRowCarryingVisibility(t *testing.T) {
423 s := newReference(t)
424 s.leakVisibilityInFeed = true
425
426 report := conformance.Check(s)
427
428 if len(report.Failures) == 0 {
429 t.Error("harness passed a feed row carrying a visibility flag")
430 }
431}
432
433// Astra's surviving mutants (2026-11-01), each now a broken server the
434// harness must refuse.
435func TestHarnessCatchesWhatTheFirstRevision10HarnessMissed(t *testing.T) {
436 for name, bend := range map[string]func(*referenceServer){
437 "a superseded revision served": func(s *referenceServer) { s.serveSuperseded = true },
438 "STALE for a revision ahead": func(s *referenceServer) { s.staleWhenAhead = true },
439 "STALE for a stranger": func(s *referenceServer) { s.revisionBeforePerson = true },
440 "private items gone from the feed": func(s *referenceServer) { s.privateAsGone = true },
441 "a title in a refusal's headers": func(s *referenceServer) { s.leakHeaderInRefusal = true },
442 "a future revision served": func(s *referenceServer) { s.serveFuture = true },
443 "the asker's kind ignored": func(s *referenceServer) { s.ignoreKind = true },
444 "a deleted item advertised live": func(s *referenceServer) { s.deletedLive = true },
445 "feed rows a revision behind": func(s *referenceServer) { s.staleFeedRevision = true },
446 "a feed that never ends": func(s *referenceServer) { s.neverEnds = true },
447 "a cursor stuck with rows": func(s *referenceServer) { s.stuckWithRows = true },
448 } {
449 s := newReference(t)
450 bend(s)
451 if report := conformance.Check(s); len(report.Failures) == 0 {
452 t.Errorf("%s: the harness passed it", name)
453 }
454 }
455}
456
457// A lone-shape app keys on addresses. RunAs gives the fixture's asker and
458// stranger that kind; the reference server, keyed on addresses, passes, and
459// asks under person_ref are UNKNOWN.
460func TestHarnessRunsForAnAddressKeyedApp(t *testing.T) {
461 s := newReference(t)
462 s.fixture.Asker.Kind, s.fixture.Stranger.Kind = suite.SubjectAddress, suite.SubjectAddress
463 if report := conformance.CheckAs(s, suite.SubjectAddress); len(report.Failures) != 0 {
464 t.Errorf("an address-keyed reference server failed: %v", report.Failures)
465 }
466}
467
468// Astra's round-3 polish (2026-11-01): what its independent probes covered
469// and the repository's suite did not.
470//
471// MUTATION-TESTED 2026-11-01, each reverted: the cursor sent unescaped →
472// "reserved characters"; the FIRST row for an item taken as its state →
473// "an item's last row"; the wrong-kind check skipped in address mode → "an
474// address-keyed server ignoring the kind".
475func TestHarnessRound3(t *testing.T) {
476 s := newReference(t)
477 s.reservedCursor = true
478 if report := conformance.Check(s); len(report.Failures) != 0 {
479 t.Errorf("reserved characters: a correct server with such cursors failed: %v", report.Failures)
480 }
481 s = newReference(t)
482 s.repeatEarlierRow = true
483 if report := conformance.Check(s); len(report.Failures) == 0 {
484 t.Error("an item's last row: a feed whose last row for an item is a revision behind passed")
485 }
486 s = newReference(t)
487 s.fixture.Asker.Kind, s.fixture.Stranger.Kind = suite.SubjectAddress, suite.SubjectAddress
488 s.ignoreKind = true
489 if report := conformance.CheckAs(s, suite.SubjectAddress); len(report.Failures) == 0 {
490 t.Error("an address-keyed server ignoring the kind passed")
491 }
492}
493
494// Fable's review of c38e3ad (revision 11): each a broken server the harness
495// must refuse. The reference server above passes; each bend breaks one rule.
496//
497// MUTATION-TESTED 2026-11-01 on the harness, each reverted, by the bend that
498// then passed: the S2 questions at the fixture's unknown_revision replaced
499// by Revision+1 → "revisions compared as numbers"; the NonexistentItemID
500// questions removed → "an unknown id answered VISIBLE"; DecodeS2's
501// DisallowUnknownFields removed → "a title in an S2 row"; the
502// missing/malformed S3 loop removed → "no revision serves today's bytes"
503// and "a malformed revision answered 400"; the POST probe removed → "S3
504// served on POST"; the foreign-cursor probe removed → both foreign-cursor
505// bends; storeAudit's header check removed → "a cacheable response", and
506// its Vary half alone → "no Vary: Authorization". (The stranger questions at
507// prior and unknown revisions removed → "STALE for a stranger", in the test
508// above.)
509//
510// 2026-11-02 (Fable's review of 0a59e7d, H1): the bend "an owner without
511// standing" is withdrawn with the fixture case doc-owner-left it needed.
512// That case was revision 11's proposal, unruled by Paul and contrary to
513// gate 5's reading; with no stranger-owned case the bend breaks nothing
514// the harness asks about, so keeping it would only fail this test.
515func TestHarnessCatchesWhatRevision10Missed(t *testing.T) {
516 for name, bend := range map[string]func(*referenceServer){
517 "revisions compared as numbers": func(s *referenceServer) { s.numericRevisions = true },
518 "an unknown id answered VISIBLE": func(s *referenceServer) { s.failOpen = true },
519 "a title in an S2 row": func(s *referenceServer) { s.titleInS2Row = true },
520 "no revision serves today's bytes": func(s *referenceServer) { s.missingRevisionIsNow = true },
521 "a malformed revision answered 400": func(s *referenceServer) { s.malformedRevision400 = true },
522 "S3 served on POST": func(s *referenceServer) { s.s3ServesPost = true },
523 "a foreign cursor answered as the tip": func(s *referenceServer) { s.foreignCursorIsTip = true },
524 "a foreign cursor answered 503": func(s *referenceServer) { s.foreignCursorFails = true },
525 "a cacheable response": func(s *referenceServer) { s.cacheable = true },
526 "no Vary: Authorization": func(s *referenceServer) { s.noVary = true },
527 } {
528 s := newReference(t)
529 bend(s)
530 if report := conformance.Check(s); len(report.Failures) == 0 {
531 t.Errorf("%s: the harness passed it", name)
532 }
533 }
534}
535