oficina / suite Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package conformance drives an app's server half against the doctrine's
2// golden fixtures.
3//
4// An app built on suite/server hands its Producer to RunProducer, which
5// mounts it exactly as the app does — server.Handler, behind a bearer token
6// the harness mints for itself — so what is tested is what is served, and
7// no unauthenticated handler ever needs to exist. An app with its own server
8// half hands that handler to Run or RunAs. The harness fires the fixture's
9// requests and reports what the contract says should have happened and did
10// not. Doctrine §10: two specs are guesses, two implementations are facts —
11// this is where the second implementation corrects the first.
12package conformance
13
14import (
15 "bytes"
16 "crypto/rand"
17 "encoding/hex"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "net/http"
22 "net/http/httptest"
23 "net/url"
24 "sort"
25 "strconv"
26 "strings"
27 "testing"
28
29 "amadan.net/oficina/suite"
30 "amadan.net/oficina/suite/server"
31)
32
33// Report is what a run found. An empty Failures is a pass.
34type Report struct {
35 Checked int
36 Failures []string
37}
38
39func (r *Report) fail(format string, args ...any) {
40 r.Failures = append(r.Failures, fmt.Sprintf(format, args...))
41}
42
43// Run drives the handler and fails the test with anything the contract
44// forbids. This is what an app calls from its own CI.
45func Run(t *testing.T, h http.Handler) {
46 t.Helper()
47 report := Check(h)
48 for _, f := range report.Failures {
49 t.Error(f)
50 }
51 if report.Checked == 0 {
52 t.Error("conformance ran no checks; a gate that asserts nothing passes everything")
53 }
54}
55
56// RunAs is Run for an app that keys its askers on kind — a lone-shape app
57// keys on addresses, a suite-shape one on person refs (§3). The fixture's
58// asker and stranger keep their values and take that kind, and the harness
59// also asks with the other kind, which must be UNKNOWN for the whole call
60// (gate 2).
61func RunAs(t *testing.T, h http.Handler, kind suite.SubjectKind) {
62 t.Helper()
63 report := CheckAs(h, kind)
64 for _, f := range report.Failures {
65 t.Error(f)
66 }
67 if report.Checked == 0 {
68 t.Error("conformance ran no checks; a gate that asserts nothing passes everything")
69 }
70}
71
72// RunProducer is how an app built on suite/server runs gate 3: the
73// producer mounted through server.Handler, exactly as the app mounts it, and
74// driven with a token the harness mints (revision 11). kind is the asker
75// kind the app keys on.
76//
77// It tests Handler and the Producer behind it, nothing else: middleware an
78// app puts in front of Handler — its own router, a proxy, a cache, a CSRF
79// or session layer — is not in the request path here and is not covered.
80// Nor can it see how the app seeded its world from the fixture's owner,
81// asker_grant and rung; a case seeded wrongly can pass.
82func RunProducer(t *testing.T, p server.Producer, kind suite.SubjectKind) {
83 t.Helper()
84 report := CheckProducer(p, kind)
85 for _, f := range report.Failures {
86 t.Error(f)
87 }
88 if report.Checked == 0 {
89 t.Error("conformance ran no checks; a gate that asserts nothing passes everything")
90 }
91}
92
93// CheckProducer is RunProducer without a *testing.T. Beyond CheckAs it
94// asks once with no token, which must be the 401 — Handler, not routes
95// served to anybody — and that 401 is held to the same Cache-Control and
96// Vary as every other response (Fable's review of 0a59e7d, L6).
97func CheckProducer(p server.Producer, kind suite.SubjectKind) Report {
98 var r Report
99 raw := make([]byte, 32)
100 if _, err := rand.Read(raw); err != nil {
101 r.fail("minting the harness's token: %v", err)
102 return r
103 }
104 token := hex.EncodeToString(raw)
105 h := server.Handler(p, []server.Consumer{{
106 ID: "suite-conformance",
107 Tokens: []server.Token{{Epoch: 1, SHA256: server.TokenHash(token)}},
108 }}, nil)
109
110 // Through the header audit, as every request in CheckAs is: the 401 is
111 // a response like any other, and a cache keeping it keyed without
112 // Authorization would serve it to the next caller.
113 audit := &storeAudit{next: h, r: &r, seen: map[string]bool{}}
114 anon := do(audit, "GET", suite.RouteS3+"/"+suite.NonexistentItemID+"?revision=1", nil)
115 r.Checked++
116 if anon.Code != http.StatusUnauthorized {
117 r.fail("a request with no token: got %d, want 401", anon.Code)
118 }
119
120 report := CheckAs(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
121 req = req.Clone(req.Context())
122 req.Header.Set("Authorization", "Bearer "+token)
123 h.ServeHTTP(w, req)
124 }), kind)
125 r.Checked += report.Checked
126 r.Failures = append(r.Failures, report.Failures...)
127 return r
128}
129
130// Check drives the handler and returns what it found, without touching a
131// *testing.T. It exists so the harness itself can be tested: a harness that
132// passes every server is worse than no harness, and the only way to know is to
133// point it at servers that should fail. It asks as the fixture's own kind,
134// person_ref.
135func Check(h http.Handler) Report {
136 return CheckAs(h, suite.SubjectPersonRef)
137}
138
139// CheckAs is Check for an app that keys on kind (see RunAs).
140func CheckAs(h http.Handler, kind suite.SubjectKind) Report {
141 var r Report
142
143 fixture, err := suite.LoadCustodyFixture()
144 if err != nil {
145 r.fail("loading the custody fixture: %v", err)
146 return r
147 }
148 if kind != suite.SubjectPersonRef && kind != suite.SubjectAddress {
149 r.fail("unknown asker kind %q", kind)
150 return r
151 }
152 fixture.Asker.Kind, fixture.Stranger.Kind = kind, kind
153
154 audit := &storeAudit{next: h, r: &r, seen: map[string]bool{}}
155 checkS3(audit, fixture, &r)
156 checkS2(audit, fixture, &r)
157 checkWrongKind(audit, fixture, kind, &r)
158 checkS1(audit, fixture, &r)
159 return r
160}
161
162// storeAudit holds every response the harness receives to the headers the
163// doctrine requires on all of them (§6.5, revision 11): Cache-Control:
164// no-store, so no cache between two apps keeps one person's S2 answer or a
165// private item's S3 body for the next request, and Vary: Authorization. One
166// failure per route, method and status, not one per request.
167type storeAudit struct {
168 next http.Handler
169 r *Report
170 seen map[string]bool
171}
172
173func (a *storeAudit) ServeHTTP(w http.ResponseWriter, req *http.Request) {
174 rec := httptest.NewRecorder()
175 a.next.ServeHTTP(rec, req)
176 res := rec.Result()
177 route := req.URL.Path
178 if strings.HasPrefix(route, suite.RouteS3+"/") {
179 route = suite.RouteS3
180 }
181 key := fmt.Sprintf("%s %s %d", req.Method, route, res.StatusCode)
182 if !a.seen[key] {
183 a.seen[key] = true
184 a.r.Checked++
185 if res.Header.Get("Cache-Control") != "no-store" || res.Header.Get("Vary") != "Authorization" {
186 a.r.fail("%s: Cache-Control %q and Vary %q, want no-store and Authorization on every response",
187 key, res.Header.Get("Cache-Control"), res.Header.Get("Vary"))
188 }
189 }
190 for k, v := range res.Header {
191 w.Header()[k] = v
192 }
193 w.WriteHeader(res.StatusCode)
194 w.Write(rec.Body.Bytes())
195}
196
197// Gate 2's kind rule: an asker of a kind the app does not key on is UNKNOWN
198// for the whole call, never NOT_VISIBLE and never an answer read off the
199// value alone (Astra, 2026-11-01: the reference server compared values only
200// and answered VISIBLE to the right string under the wrong kind).
201func checkWrongKind(h http.Handler, f suite.CustodyFixture, kind suite.SubjectKind, r *Report) {
202 other := suite.SubjectAddress
203 if kind == suite.SubjectAddress {
204 other = suite.SubjectPersonRef
205 }
206 wrong := suite.Subject{Kind: other, Value: f.Asker.Value}
207 pairs := make([]suite.ItemRevision, 0, len(f.Cases))
208 want := make([]suite.Authorization, 0, len(f.Cases))
209 for _, c := range f.Cases {
210 pairs = append(pairs, suite.ItemRevision{ItemID: c.ItemID, Revision: c.Revision})
211 want = append(want, suite.UNKNOWN)
212 }
213 ask(h, r, "the asker's value under the kind this app does not key on", wrong, pairs, want)
214}
215
216// Gate 3, the content half. Since revision 10 (Paul, 2026-11-01) every live
217// item is served — the consumer holds private and granted items too, and S2
218// decides who sees them — and a deleted item answers the same 404 as one
219// that never existed, so a consumer cannot tell a deletion from a made-up id.
220func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
221 // The refusal every non-team item must be indistinguishable from. Taken
222 // from an id that is not in the fixture at all, so it is the server's
223 // answer for "no such item" rather than anything the fixture arranged.
224 baseline := do(h, "GET", suite.RouteS3+"/"+suite.NonexistentItemID+"?revision=1", nil)
225 r.Checked++
226 if baseline.Code != 404 {
227 r.fail("S3 for an item that does not exist: got %d, want 404", baseline.Code)
228 }
229
230 // Only the current revision is ever served: a consumer asking for a
231 // revision the log holds but has moved past, or one it never issued,
232 // gets the refusal, not today's bytes under another name (Astra,
233 // 2026-11-01: the reference server served the older one; a mutant
234 // serving the newer one passed). Since revision 11 the fixture names
235 // both revisions; the harness computes neither.
236 for _, c := range f.Cases {
237 for _, rev := range []int64{c.PriorRevision, c.UnknownRevision} {
238 rec := do(h, "GET", suite.RouteS3+"/"+c.ItemID+"?revision="+strconv.FormatInt(rev, 10), nil)
239 r.Checked++
240 if refusal(rec) != refusal(baseline) {
241 r.fail("S3 %s at revision %d (current %d): %s, want the refusal for an item that does not exist (%s)",
242 c.ItemID, rev, c.Revision, refusal(rec), refusal(baseline))
243 }
244 }
245 // No revision, a malformed one and one under 1 are the same refusal
246 // (Fable, review of c38e3ad, M5): a server that read a missing
247 // revision as "the current one" serves bytes nobody named, and one
248 // that answered 400 tells the caller the item exists.
249 for what, query := range map[string]string{"no revision": "", "a malformed revision": "?revision=seven", "revision 0": "?revision=0"} {
250 rec := do(h, "GET", suite.RouteS3+"/"+c.ItemID+query, nil)
251 r.Checked++
252 if refusal(rec) != refusal(baseline) {
253 r.fail("S3 %s with %s: %s, want the refusal for an item that does not exist (%s)",
254 c.ItemID, what, refusal(rec), refusal(baseline))
255 }
256 }
257 // S3 is a GET. A POST is not served, whatever it is answered with.
258 if c.S3Status == 200 {
259 rec := do(h, "POST", suite.RouteS3+"/"+c.ItemID+"?revision="+strconv.FormatInt(c.Revision, 10), nil)
260 r.Checked++
261 if rec.Code >= 200 && rec.Code <= 299 || strings.Contains(rec.Body.String(), c.S3Body) {
262 r.fail("S3 %s on POST: %d, and S3 serves a GET only", c.ItemID, rec.Code)
263 }
264 }
265 }
266
267 for _, c := range f.Cases {
268 url := suite.RouteS3 + "/" + c.ItemID + "?revision=" + strconv.FormatInt(c.Revision, 10)
269 rec := do(h, "GET", url, nil)
270 r.Checked++
271
272 if rec.Code != c.S3Status {
273 r.fail("S3 %s (%s, rung %s): got %d, want %d", c.ItemID, c.Name, c.Rung, rec.Code, c.S3Status)
274 continue
275 }
276 if rec.Code == 403 {
277 r.fail("S3 %s: answered 403, and the contract is 404 never 403 — a 403 says the item exists, which is the fact custody hides", c.ItemID)
278 continue
279 }
280
281 body := rec.Body.String()
282 if c.S3Status == 200 {
283 // The item's own bytes, not merely some bytes. A 200 carrying a
284 // different item is a leak that a status check cannot see.
285 if body != c.S3Body {
286 r.fail("S3 %s: body %q, want %q", c.ItemID, body, c.S3Body)
287 }
288 continue
289 }
290
291 // A refusal must be identical to the refusal for an item that never
292 // existed — body AND headers. Anything a server adds here, a reason
293 // in the body or a title in a header, tells the caller the item is
294 // real (headers: Astra, 2026-11-01).
295 if refusal(rec) != refusal(baseline) {
296 r.fail("S3 %s: refusal %s differs from the refusal for an item that does not exist (%s), so the answer reveals that this item exists",
297 c.ItemID, refusal(rec), refusal(baseline))
298 }
299 }
300}
301
302// Gate 3, the authorization half. Since revision 10, S2 is the app's own read
303// check for the named asker: the team rung, ownership, or a live individual
304// grant, and never a link. The fixture's asker owns one private item, holds a
305// grant on another and a former grant on a deleted one, and does not own the
306// link-shared and moved-to-private items, so each part of the check shows.
307//
308// Since revision 11 the revisions asked about are the fixture's own: its
309// prior_revision (one the log holds, not current) and its unknown_revision
310// (one the log never issued). The harness computes no "one behind": a
311// revision is a name, and a producer comparing numbers is the one a restore
312// turns into a leak (doctrine §6.6).
313func checkS2(h http.Handler, f suite.CustodyFixture, r *Report) {
314 // Several questions, not one. A single question at the current revision
315 // for a single person lets a server answer from the rung alone and read
316 // neither the asker nor the revision it was sent.
317 at := func(rev func(suite.CustodyCase) int64, want func(suite.CustodyCase) suite.Authorization) ([]suite.ItemRevision, []suite.Authorization) {
318 pairs := make([]suite.ItemRevision, 0, len(f.Cases))
319 wants := make([]suite.Authorization, 0, len(f.Cases))
320 for _, c := range f.Cases {
321 pairs = append(pairs, suite.ItemRevision{ItemID: c.ItemID, Revision: rev(c)})
322 wants = append(wants, want(c))
323 }
324 return pairs, wants
325 }
326 current := func(c suite.CustodyCase) int64 { return c.Revision }
327 prior := func(c suite.CustodyCase) int64 { return c.PriorRevision }
328 unknown := func(c suite.CustodyCase) int64 { return c.UnknownRevision }
329 stranger := func(c suite.CustodyCase) suite.Authorization { return c.S2ResultStranger }
330
331 pairs, want := at(current, func(c suite.CustodyCase) suite.Authorization { return c.S2Result })
332 ask(h, r, "the fixture's asker, at the current revision", f.Asker, pairs, want)
333 pairs, want = at(prior, func(c suite.CustodyCase) suite.Authorization { return c.S2ResultSuperseded })
334 ask(h, r, "the fixture's asker, at a prior revision the log holds", f.Asker, pairs, want)
335 pairs, want = at(unknown, func(c suite.CustodyCase) suite.Authorization { return c.S2ResultAhead })
336 ask(h, r, "the fixture's asker, at a revision the log never issued", f.Asker, pairs, want)
337
338 // The stranger at every revision: a server that checks the revision
339 // before the person tells a stranger STALE or UNKNOWN where it owes
340 // them NOT_VISIBLE (Astra, 2026-11-01).
341 pairs, want = at(current, stranger)
342 ask(h, r, "a person with no team standing", f.Stranger, pairs, want)
343 pairs, want = at(prior, stranger)
344 ask(h, r, "a person with no team standing, at a prior revision", f.Stranger, pairs, want)
345 pairs, want = at(unknown, stranger)
346 ask(h, r, "a person with no team standing, at a revision never issued", f.Stranger, pairs, want)
347
348 // An id the producer does not know is NOT_VISIBLE for everybody. A
349 // server that fails open — VISIBLE for whatever it cannot find — passes
350 // every fixture case, because every fixture case exists (Fable, review
351 // of c38e3ad, H2).
352 none := []suite.ItemRevision{{ItemID: suite.NonexistentItemID, Revision: 1}}
353 ask(h, r, "the fixture's asker, about an id the app does not know", f.Asker, none, []suite.Authorization{suite.NOT_VISIBLE})
354 ask(h, r, "a person with no team standing, about an id the app does not know", f.Stranger, none, []suite.Authorization{suite.NOT_VISIBLE})
355}
356
357// ask puts one S2 question and holds each answer to want, pair by pair.
358func ask(h http.Handler, r *Report, what string, asker suite.Subject, pairs []suite.ItemRevision, want []suite.Authorization) {
359 if err := suite.CheckS2Batch(pairs); err != nil {
360 r.fail("custody fixture is over the S2 cap: %v", err)
361 return
362 }
363
364 body, err := json.Marshal(suite.S2Request{Asker: asker, Pairs: pairs})
365 if err != nil {
366 r.fail("encoding the S2 question: %v", err)
367 return
368 }
369
370 rec := do(h, "POST", suite.RouteS2, body)
371 // DecodeS2 is strict: a row carrying anything beyond item_id, revision
372 // and result makes the whole call UNKNOWN, and fails here.
373 got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes())
374
375 for i, p := range pairs {
376 r.Checked++
377 if got[i] != want[i] {
378 r.fail("S2 %s asked for %s: got %s, want %s", p.ItemID, what, got[i], want[i])
379 }
380 }
381}
382
383// Gate 1 for the feed, and the leak memoria's draft 1 shipped. The decoder
384// refuses unknown fields, so a row carrying a title, a body or a visibility
385// flag fails here rather than in a store somebody greps a year later.
386//
387// And what the rows say (Astra, 2026-11-01). Under revision 10 the feed
388// carries every live item at its current revision, not gone, and `gone`
389// means deleted and nothing else: a server still marking private items gone
390// would keep a person's own documents out of their search. The last row for
391// an item is its state; a deleted item may be absent or gone, never live.
392func checkS1(h http.Handler, f suite.CustodyFixture, r *Report) {
393 // Every page, as a consumer reads them: follow the cursor until it
394 // comes back unchanged with no rows (Astra, 2026-11-01: the first
395 // version read one page and failed a correct server that paged). A
396 // cursor that comes back unchanged WITH rows, or a feed that will not
397 // end, is a server a consumer cannot finish reading.
398 const maxPages = 100
399 last := map[string]suite.FeedRow{}
400 cursor := ""
401 for page := 0; ; page++ {
402 if page == maxPages {
403 r.fail("S1: no tip after %d pages — a consumer polls a feed like this for ever", maxPages)
404 return
405 }
406 rec := do(h, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(cursor), nil)
407 r.Checked++
408 feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
409 if err != nil {
410 r.fail("S1: %v", err)
411 return
412 }
413 for _, row := range feed.Rows {
414 last[row.ItemID] = row
415 }
416 if feed.Cursor == cursor {
417 if len(feed.Rows) > 0 {
418 r.fail("S1: the cursor came back unchanged with %d rows; a consumer cannot make progress", len(feed.Rows))
419 }
420 break
421 }
422 cursor = feed.Cursor
423 }
424
425 // A cursor the log does not recognise — restored from a backup, or
426 // issued by another log — is the fixed 409, which tells the consumer to
427 // drop what it holds and read from the beginning. Answered as the tip,
428 // it leaves a consumer holding a dead log's items for ever; answered as
429 // a failure, it stalls the consumer for ever (Fable, review of c38e3ad,
430 // H1; doctrine §6.6).
431 rec := do(h, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(suite.NeverIssuedCursor), nil)
432 r.Checked++
433 if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) {
434 r.fail("S1 with a cursor the log never issued: %d %q, want %d %s", rec.Code, rec.Body.String(), suite.CursorResetStatus, suite.CursorResetBody)
435 }
436
437 for _, c := range f.Cases {
438 r.Checked++
439 row, ok := last[c.ItemID]
440 if c.Rung == suite.RungDeleted {
441 if ok && !row.Gone {
442 r.fail("S1 %s: a deleted item's last row is not gone", c.ItemID)
443 }
444 continue
445 }
446 switch {
447 case !ok:
448 r.fail("S1 %s (%s): a live item is missing from the feed", c.ItemID, c.Name)
449 case row.Gone:
450 r.fail("S1 %s (%s): a live item's last row is gone; gone means deleted", c.ItemID, c.Name)
451 case row.Revision != c.Revision:
452 r.fail("S1 %s: last row at revision %d, want %d", c.ItemID, row.Revision, c.Revision)
453 }
454 }
455}
456
457// refusal is a response as a consumer could compare it: status, body and
458// every header but Date.
459func refusal(rec *httptest.ResponseRecorder) string {
460 var keys []string
461 for k := range rec.Header() {
462 if k != "Date" {
463 keys = append(keys, k)
464 }
465 }
466 sort.Strings(keys)
467 var b strings.Builder
468 b.WriteString(strconv.Itoa(rec.Code))
469 for _, k := range keys {
470 b.WriteString("|" + k + "=" + strings.Join(rec.Header()[k], ","))
471 }
472 b.WriteString("|" + rec.Body.String())
473 return b.String()
474}
475
476func do(h http.Handler, method, url string, body []byte) *httptest.ResponseRecorder {
477 var rdr *bytes.Reader
478 if body == nil {
479 rdr = bytes.NewReader(nil)
480 } else {
481 rdr = bytes.NewReader(body)
482 }
483 req := httptest.NewRequest(method, url, rdr)
484 rec := httptest.NewRecorder()
485 h.ServeHTTP(rec, req)
486 return rec
487}
488