oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "net/http/httptest"
8 "net/url"
9 "slices"
10 "strconv"
11 "strings"
12 "testing"
13 "time"
14
15 "gorm.io/gorm"
16
17 "amadan.net/oficina/suite"
18 "amadan.net/oficina/suite/server"
19)
20
21// The producer half of the suite contract (spec §6). These drive the
22// producer directly; fichastest/suite_test.go drives it through the real
23// router, and suite_conformance_test.go through the suite's own harness.
24
25const admittedAsker = "ana@example.com"
26
27// producerFor builds the producer over the real admission predicate,
28// app.Admit, with one admitted address — what LoadConfig gives a lone
29// instance whose FICHAS_OWNERS is that address.
30func producerFor(g *gorm.DB, a *app) *suiteProducer {
31 return &suiteProducer{g: g, sealer: a.sealer, admit: a.Admit}
32}
33
34// suiteWorld pins card revisions to a per-card count, 1, 2, 3, in place of
35// the random ones Fichas issues. These tests are about what S1, S2 and S3
36// answer for a revision, and readable numbers keep them so; STALE still
37// comes from the event log either way. Random revisions, and what a
38// counter would get wrong, have their own tests (suite_revision_test.go)
39// on the real source.
40func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) {
41 t.Helper()
42 pinRevisions(t, func(current int64) int64 { return current + 1 })
43 g, s := seeded(t)
44 a := &app{sealer: s, owners: ParseOwners(admittedAsker)}
45 return g, a, producerFor(g, a)
46}
47
48// pinRevisions sets how card revisions are issued for one test, and puts
49// the random source back after.
50func pinRevisions(t testing.TB, next func(current int64) int64) {
51 t.Helper()
52 old := newRevision
53 newRevision = next
54 t.Cleanup(func() { newRevision = old })
55}
56
57func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card {
58 t.Helper()
59 return mustCardBy(t, g, a, Person(1), values)
60}
61
62// mustCardBy creates a card as actor and returns it as the database holds
63// it, so its nonce — half of its item id — is the stored value.
64func mustCardBy(t *testing.T, g *gorm.DB, a *app, actor Actor, values map[string]string) Card {
65 t.Helper()
66 if _, ok := values[FieldName]; !ok {
67 named := map[string]string{FieldName: "Card"}
68 for k, v := range values {
69 named[k] = v
70 }
71 values = named
72 }
73 c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, actor, values)
74 if err != nil {
75 t.Fatalf("CreateCard: %v", err)
76 }
77 var stored Card
78 if err := g.First(&stored, c.ID).Error; err != nil {
79 t.Fatal(err)
80 }
81 return stored
82}
83
84// id is a card's item id: "<card id>.<nonce>".
85func id(c Card) string { return itemID(c.ID, c.Nonce) }
86
87// bare is the card id alone, which is not an item id.
88func bare(c Card) string { return strconv.FormatInt(c.ID, 10) }
89
90func address(v string) suite.Subject { return suite.Subject{Kind: suite.SubjectAddress, Value: v} }
91
92// testToken is the bearer serve mounts the producer behind.
93const testToken = "a-token-for-the-producer-tests"
94
95// serve mounts p exactly as the app does — server.Handler, behind a
96// consumer token — and answers one request carrying that token. Not
97// server.Routes, which revision 11 deprecates: it is the routes with no
98// bearer check, and nothing new may call it (doctrine §6.5).
99func serve(t *testing.T, p server.Producer, method, target string, body []byte) *httptest.ResponseRecorder {
100 t.Helper()
101 h := server.Handler(p, []server.Consumer{{
102 ID: "memoria",
103 Tokens: []server.Token{{Epoch: 1, SHA256: server.TokenHash(testToken)}},
104 }}, nil)
105 req := httptest.NewRequest(method, target, bytes.NewReader(body))
106 req.Header.Set("Authorization", "Bearer "+testToken)
107 rec := httptest.NewRecorder()
108 h.ServeHTTP(rec, req)
109 return rec
110}
111
112// readFeed pages from cursor to the tip, limit rows a page, and returns
113// every row and the tip's cursor.
114func readFeed(t *testing.T, p *suiteProducer, cursor string, limit int) ([]suite.FeedRow, string) {
115 t.Helper()
116 var all []suite.FeedRow
117 for pages := 0; ; pages++ {
118 if pages > 100 {
119 t.Fatal("the feed never reached its tip")
120 }
121 f, err := p.Feed(ctx(), cursor, limit)
122 if err != nil {
123 t.Fatalf("Feed(%q): %v", cursor, err)
124 }
125 if f.Cursor == "" || len(f.Rows) > limit {
126 t.Fatalf("Feed(%q) broke the contract: %+v", cursor, f)
127 }
128 if len(f.Rows) == 0 {
129 if f.Cursor != cursor && cursor != "" {
130 t.Fatalf("at the tip the cursor moved: %q → %q", cursor, f.Cursor)
131 }
132 if f.Rows == nil {
133 t.Fatal("the tip's rows are nil, not empty")
134 }
135 return all, f.Cursor
136 }
137 all = append(all, f.Rows...)
138 cursor = f.Cursor
139 }
140}
141
142type row struct {
143 item string
144 rev int64
145 gone bool
146}
147
148func rowsOf(rs []suite.FeedRow) []row {
149 out := make([]row, len(rs))
150 for i, r := range rs {
151 out[i] = row{r.ItemID, r.Revision, r.Gone}
152 }
153 return out
154}
155
156// S1 is the events table: one row per card event, in log order, carrying
157// the card's revision after that event; an entry bumps its card; a delete
158// is gone; the catalogue's type and field events and an entry's own
159// creation row are not items. Paged two at a time so every page boundary
160// is crossed, and the tip answers the same cursor and no rows.
161//
162// MUTATION-TESTED 2026-11-01, each reverted: the object_kind filter
163// dropped (seed and entry events become rows) → "rows"; Gone hard-coded
164// false → "rows"; Revision taken as 1 → "rows"; the next cursor taken from
165// the FIRST row of a page (pages repeat) → "rows"; the tip answering a
166// fresh cursor ("0") → "at the tip the cursor moved"; the tip's Rows left
167// nil → "nil, not empty"; created_at not selected (zero touched_at) →
168// "touched_at".
169func TestSuiteFeedIsTheEventLog(t *testing.T) {
170 g, a, p := suiteWorld(t)
171 c1 := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
172 c2 := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
173 if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
174 t.Fatal(err)
175 }
176 if _, err := AddEntry(ctx(), g, a.sealer, c1.ID, Person(2), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}); err != nil {
177 t.Fatal(err)
178 }
179 if err := DeleteCard(ctx(), g, a.sealer, c2.ID, Person(1)); err != nil {
180 t.Fatal(err)
181 }
182
183 rows, tip := readFeed(t, p, "", 2)
184 want := []row{
185 {id(c1), 1, false},
186 {id(c2), 1, false},
187 {id(c1), 2, false}, // an update
188 {id(c1), 3, false}, // an entry landing bumps its card
189 {id(c2), 2, true}, // a delete is gone
190 }
191 if got := rowsOf(rows); !slices.Equal(got, want) {
192 t.Fatalf("rows:\n got %+v\nwant %+v", got, want)
193 }
194 for _, r := range rows {
195 if r.TouchedAt.IsZero() {
196 t.Errorf("touched_at is zero on %+v", r)
197 }
198 }
199
200 // The tip, asked again, is the same cursor and no rows; a change after
201 // it is exactly one more row.
202 if more, again := readFeed(t, p, tip, 2); len(more) != 0 || again != tip {
203 t.Fatalf("at the tip: %d rows, cursor %q (was %q)", len(more), again, tip)
204 }
205 if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Won"}); err != nil {
206 t.Fatal(err)
207 }
208 if more, _ := readFeed(t, p, tip, 2); !slices.Equal(rowsOf(more), []row{{id(c1), 4, false}}) {
209 t.Fatalf("after the tip: %+v", rowsOf(more))
210 }
211}
212
213// A row is the four plaintext columns and nothing else: no value, label or
214// actor can reach it because the query never reads one.
215func TestSuiteFeedRowsCarryNoContent(t *testing.T) {
216 g, a, p := suiteWorld(t)
217 mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta", FieldNotes: "owes us money"})
218 f, err := p.Feed(ctx(), "", 10)
219 if err != nil {
220 t.Fatal(err)
221 }
222 for _, r := range f.Rows {
223 for _, s := range []string{r.ItemID, f.Cursor} {
224 if strings.Contains(s, "Cnoc") || strings.Contains(s, "money") {
225 t.Fatalf("content in a feed row: %+v", r)
226 }
227 }
228 }
229}
230
231// An empty log starts at "0" (the contract refuses an empty cursor) and
232// stays there.
233func TestSuiteFeedOnAnEmptyLog(t *testing.T) {
234 g := testDB(t)
235 p := &suiteProducer{g: g, sealer: testSealer(t), admit: func(string) bool { return true }}
236 f, err := p.Feed(ctx(), "", 10)
237 if err != nil || f.Cursor != "0" || f.Rows == nil || len(f.Rows) != 0 {
238 t.Fatalf("empty log: %+v, %v", f, err)
239 }
240 if f, err := p.Feed(ctx(), "0", 10); err != nil || f.Cursor != "0" || len(f.Rows) != 0 {
241 t.Fatalf("empty log again: %+v, %v", f, err)
242 }
243}
244
245// A cursor Fichas could not have issued is server.ErrCursorReset — the
246// package's 409 {"code":"CURSOR_RESET"}, which tells the consumer to start
247// over from "" (doctrine §6.6, revision 11) — never a page and never a
248// plain error (a 503, which stalls the consumer for ever): not
249// "<event id>.<stamp>" in canonical form, ahead of the log, or naming an
250// event whose stamp the log does not hold — a restore from an older
251// backup, where a page would continue silently from a position that now
252// means something else. Through the server, the reset is exactly the fixed
253// 409, and the beginning is never reset.
254//
255// MUTATION-TESTED 2026-11-01, each reverted: the canonical check removed
256// from canonicalPositive → "leading zero"/"plus"; a bare event id accepted
257// as a cursor AND the lookup skipped for it → "no stamp"; the cursor's
258// event lookup skipped → "ahead"/"wrong stamp"; the stamp comparison
259// removed → "wrong stamp"; canonicalPositive's n < 1 bound removed →
260// "zero id"/"negative id" (Astra, 2026-11-01: not equivalent — an id of 0
261// or below skips the lookup and pages from the beginning); the lookup's
262// object_kind = card restriction removed → "a catalogue event" (a correctly
263// stamped event that is not a card's would have been accepted). One mutant
264// survives and is equivalent: a bare id parsed as stamp 0, which the lookup
265// then refuses.
266//
267// MUTATION-TESTED 2026-11-02 (revision 11), each reverted: a parse failure
268// returned as a plain error (revision 10's 503) → every malformed case
269// ("letters" to "three parts", "zero id", "negative id"), and the
270// conformance harness's never-issued cursor; a missing event or a stamp
271// mismatch returned as a plain error → "ahead", "wrong stamp", "through the
272// server" (503), "a catalogue event" and both restore tests' S1; the stamp
273// comparison removed again → "wrong stamp", "through the server" (200, a
274// page) and both restore tests; "" and "0" answered with the reset → this
275// test, TestSuiteFeedOnAnEmptyLog, TestSuiteFeedIsTheEventLog and every
276// other test that reads the feed.
277func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
278 g, a, p := suiteWorld(t)
279 mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
280 _, tip := readFeed(t, p, "", 10)
281 n, stamp, ok := parseStamped(tip)
282 if !ok {
283 t.Fatalf("the tip %q is not <event id>.<stamp>", tip)
284 }
285 for name, c := range map[string]string{
286 "letters": "abc",
287 "-1": "-1",
288 "no stamp": strconv.FormatInt(n, 10),
289 "leading zero": "0" + tip,
290 "plus": "+" + tip,
291 "stamp zero": stampedID(n, 0),
292 "three parts": tip + ".1",
293 "spaces": " " + tip,
294 "ahead": stampedID(n+1000, stamp),
295 "wrong stamp": stampedID(n, stamp+1),
296 "zero id": "0.1",
297 "negative id": "-1.1",
298 } {
299 if f, err := p.Feed(ctx(), c, 10); !errors.Is(err, server.ErrCursorReset) {
300 t.Errorf("%s: cursor %q answered %+v, %v; want server.ErrCursorReset", name, c, f, err)
301 }
302 }
303 rec := serve(t, p, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(stampedID(n, stamp+1)), nil)
304 if rec.Code != suite.CursorResetStatus || strings.TrimSpace(rec.Body.String()) != suite.CursorResetBody {
305 t.Errorf("through the server: %d %q, want %d %s", rec.Code, rec.Body.String(), suite.CursorResetStatus, suite.CursorResetBody)
306 }
307
308 // A catalogue event, correctly stamped, is still not a feed position:
309 // the feed is card events only, so its ids are not positions in it.
310 other := Event{Kind: EventUpdated, ObjectKind: ObjectType, ObjectID: 1, Revision: 1, CreatedAt: time.Now().UTC(), Nonce: randomPositive()}
311 if err := g.Create(&other).Error; err != nil {
312 t.Fatalf("seeding a catalogue event: %v", err)
313 }
314 var stored Event
315 if err := g.First(&stored, other.ID).Error; err != nil {
316 t.Fatal(err)
317 }
318 c := stampedID(stored.ID, stored.Nonce)
319 if f, err := p.Feed(ctx(), c, 10); !errors.Is(err, server.ErrCursorReset) {
320 t.Errorf("a catalogue event: cursor %q answered %+v, %v; want server.ErrCursorReset", c, f, err)
321 }
322}
323
324// A failed read of the cursor's event is an error — a 503, which the
325// consumer retries — and never the reset: a database that did not answer
326// has not said the cursor is wrong, and a reset destroys the consumer's
327// whole copy of this instance (doctrine §6.6).
328//
329// MUTATION-TESTED 2026-11-02, reverted: the cursor lookup's read error
330// mapped to server.ErrCursorReset → "a failed cursor read" and "through the
331// server" (409).
332func TestSuiteFeedCursorReadFailureIsNotAReset(t *testing.T) {
333 g, a, p := suiteWorld(t)
334 mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
335 _, tip := readFeed(t, p, "", 10)
336 failing := false
337 if err := g.Callback().Query().Before("gorm:query").Register("test:fail_cursor", func(tx *gorm.DB) {
338 if failing && tx.Statement.Table == "events" {
339 tx.AddError(errors.New("the disk went away"))
340 }
341 }); err != nil {
342 t.Fatal(err)
343 }
344 failing = true
345 if f, err := p.Feed(ctx(), tip, 10); err == nil || errors.Is(err, server.ErrCursorReset) {
346 t.Errorf("a failed cursor read: %+v, %v; want an error that is not the reset", f, err)
347 }
348 if rec := serve(t, p, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(tip), nil); rec.Code != 503 {
349 t.Errorf("through the server: %d %q, want 503", rec.Code, rec.Body.String())
350 }
351}
352
353// The same for the page read that follows a recognised cursor: a failure
354// there is a 503, never the reset. Only the second events query fails, so
355// the cursor lookup succeeds and the page read is the one that breaks
356// (Fable's review of d0c7761, L1: failing every events query tripped the
357// lookup first and left this path untested).
358//
359// MUTATION-TESTED 2026-11-02, reverted: the page read's error mapped to
360// server.ErrCursorReset → "a failed page read" and "through the server".
361func TestSuiteFeedPageReadFailureIsNotAReset(t *testing.T) {
362 g, a, p := suiteWorld(t)
363 mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
364 _, tip := readFeed(t, p, "", 10)
365 mustCard(t, g, a, map[string]string{FieldName: "Sliabh Teoranta"})
366 failing, seen := false, 0
367 if err := g.Callback().Query().Before("gorm:query").Register("test:fail_page", func(tx *gorm.DB) {
368 if failing && tx.Statement.Table == "events" {
369 seen++
370 if seen == 2 {
371 tx.AddError(errors.New("the disk went away"))
372 }
373 }
374 }); err != nil {
375 t.Fatal(err)
376 }
377 failing = true
378 if f, err := p.Feed(ctx(), tip, 10); err == nil || errors.Is(err, server.ErrCursorReset) {
379 t.Errorf("a failed page read: %+v, %v; want an error that is not the reset", f, err)
380 }
381 if seen < 2 {
382 t.Fatalf("only %d events queries ran, so the page read was never reached", seen)
383 }
384 seen = 0
385 if rec := serve(t, p, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(tip), nil); rec.Code != 503 {
386 t.Errorf("through the server: %d %q, want 503", rec.Code, rec.Body.String())
387 }
388}
389
390// S2, every branch of spec §6.3's table.
391//
392// Revisions are issued 10 apart here (10, 20, 30), so the table can ask
393// about a revision below the current one that the card's log never issued
394// — the case where reading STALE off the numbers and reading it off the
395// log disagree.
396//
397// MUTATION-TESTED 2026-11-01, each reverted: the person_ref branch removed
398// (a person_ref falls to admission and answers NOT_VISIBLE) → "person_ref";
399// admission skipped → "not admitted"; the gone filter dropped from the
400// revision query → "gone"; STALE read off the numbers (1 <= asked <
401// current) instead of the log → "never issued, below current"; the history
402// query not restricted to this card → "another card's revision"; every
403// non-current revision STALE → "ahead", "revision 0", "negative revision";
404// == current answering STALE → "current"; the canonical check removed →
405// "not canonical"; the nonce comparison removed → "wrong stamp"; the query
406// restricted to owner_id = 1 → "owned by another member".
407func TestSuiteRuleEveryBranch(t *testing.T) {
408 g, a, p := suiteWorld(t)
409 pinRevisions(t, func(current int64) int64 { return current + 10 })
410 live := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
411 for _, stage := range []string{"Lead", "Won"} {
412 if err := UpdateCard(ctx(), g, a.sealer, live.ID, Person(1), map[string]string{FieldStage: stage}); err != nil {
413 t.Fatal(err)
414 }
415 }
416 // live has been at 10, 20 and is at 30.
417 gone := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
418 if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil {
419 t.Fatal(err)
420 }
421 // Owner is provenance, not authority: a card another member made is
422 // every admitted person's.
423 theirs := mustCardBy(t, g, a, Person(2), map[string]string{FieldName: "Their card"})
424 wrongStamp := itemID(live.ID, live.Nonce+1)
425
426 pairs := []suite.ItemRevision{
427 {ItemID: id(live), Revision: 30}, // current
428 {ItemID: id(live), Revision: 20}, // behind
429 {ItemID: id(live), Revision: 40}, // ahead
430 {ItemID: id(live), Revision: 0}, // revision 0
431 {ItemID: id(live), Revision: -1}, // negative revision
432 {ItemID: id(gone), Revision: 20}, // gone, at its last revision
433 {ItemID: "999999.1", Revision: 1}, // unknown
434 {ItemID: "doc-team", Revision: 1}, // not a card id
435 {ItemID: "0" + id(live), Revision: 30}, // not canonical
436 {ItemID: bare(live), Revision: 30}, // no stamp
437 {ItemID: wrongStamp, Revision: 30}, // wrong stamp
438 {ItemID: id(theirs), Revision: 10}, // owned by another member
439 {ItemID: id(live), Revision: 25}, // never issued, below current
440 {ItemID: id(live), Revision: 10}, // its first revision
441 {ItemID: id(theirs), Revision: 20}, // another card's revision
442 }
443 names := []string{"current", "behind", "ahead", "revision 0", "negative revision", "gone", "unknown",
444 "not a card id", "not canonical", "no stamp", "wrong stamp", "owned by another member",
445 "never issued, below current", "its first revision", "another card's revision"}
446
447 check := func(what string, asker suite.Subject, want []suite.Authorization) {
448 t.Helper()
449 got, err := p.Rule(ctx(), asker, pairs)
450 if err != nil {
451 t.Fatalf("%s: %v", what, err)
452 }
453 if len(got) != len(pairs) {
454 t.Fatalf("%s: %d answers for %d pairs", what, len(got), len(pairs))
455 }
456 for i := range pairs {
457 if got[i] != want[i] {
458 t.Errorf("%s, %s: got %s, want %s", what, names[i], got[i], want[i])
459 }
460 }
461 }
462 all := func(v suite.Authorization) []suite.Authorization {
463 out := make([]suite.Authorization, len(pairs))
464 for i := range out {
465 out[i] = v
466 }
467 return out
468 }
469
470 check("admitted", address(admittedAsker), []suite.Authorization{
471 suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN,
472 suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE,
473 suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.VISIBLE,
474 suite.UNKNOWN, suite.STALE, suite.UNKNOWN,
475 })
476 // A kind Fichas does not key on is UNKNOWN — loud — even when its value
477 // happens to be an admitted address.
478 check("person_ref", suite.Subject{Kind: suite.SubjectPersonRef, Value: admittedAsker}, all(suite.UNKNOWN))
479 check("not admitted", address("bo@example.com"), all(suite.NOT_VISIBLE))
480}
481
482// drawing pins card revisions to the given draws, in order, and fails the
483// test if a path asks for more than it was given.
484func drawing(t *testing.T, draws ...int64) {
485 t.Helper()
486 pinRevisions(t, func(int64) int64 {
487 if len(draws) == 0 {
488 t.Fatal("a revision was drawn that the test did not provide")
489 }
490 d := draws[0]
491 draws = draws[1:]
492 return d
493 })
494}
495
496// STALE is "this card's log once issued it", never "it is smaller": random
497// revisions go down as often as up. A card that moved 1000 → 500 is STALE
498// at 1000. A historical revision under someone else's nonce is a different
499// card's, and NOT_VISIBLE, never STALE.
500//
501// MUTATION-TESTED 2026-11-01, each reverted: STALE requiring the log AND
502// asked < current → "1000 after 1000 → 500"; the history lookup consulted
503// before the nonce check (a reused id's history read as this card's) →
504// "a wrong nonce with a historical revision".
505func TestSuiteStaleIsTheLogNotTheNumbers(t *testing.T) {
506 g, a, p := suiteWorld(t)
507 drawing(t, 1000, 500)
508 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
509 if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
510 t.Fatal(err)
511 }
512 if now := revisionOf(t, g, c.ID); now != 500 {
513 t.Fatalf("the card is at %d, want 500", now)
514 }
515 wrongNonce := itemID(c.ID, c.Nonce+1)
516 pairs := []suite.ItemRevision{
517 {ItemID: id(c), Revision: 1000},
518 {ItemID: id(c), Revision: 500},
519 {ItemID: wrongNonce, Revision: 1000},
520 }
521 got, err := p.Rule(ctx(), address(admittedAsker), pairs)
522 if err != nil {
523 t.Fatal(err)
524 }
525 for i, want := range []suite.Authorization{suite.STALE, suite.VISIBLE, suite.NOT_VISIBLE} {
526 name := []string{"1000 after 1000 → 500", "500, current", "a wrong nonce with a historical revision"}[i]
527 if got[i] != want {
528 t.Errorf("%s: %s, want %s", name, got[i], want)
529 }
530 }
531 if body, err := p.Content(ctx(), wrongNonce, 1000); !errors.Is(err, suite.ErrNotAvailable) {
532 t.Errorf("S3, a wrong nonce with a historical revision: %q, %v", body, err)
533 }
534}
535
536// A failed read of a card's history is an error — a 503, UNKNOWN for the
537// whole call on memoria's side, and logged — never a quiet UNKNOWN or STALE
538// per pair, which would read as Fichas's verdict.
539//
540// MUTATION-TESTED 2026-11-01, reverted: pastRevisions' query error
541// swallowed (an empty history returned) → "a failed history read" and
542// "through the server".
543func TestSuiteRuleHistoryFailureIsAnError(t *testing.T) {
544 g, a, p := suiteWorld(t)
545 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
546 if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
547 t.Fatal(err)
548 }
549 failing := false
550 if err := g.Callback().Query().Before("gorm:query").Register("test:fail_history", func(tx *gorm.DB) {
551 if failing && tx.Statement.Table == "events" {
552 tx.AddError(errors.New("the disk went away"))
553 }
554 }); err != nil {
555 t.Fatal(err)
556 }
557 failing = true
558 pair := []suite.ItemRevision{{ItemID: id(c), Revision: 1}} // historical: needs the log
559 if got, err := p.Rule(ctx(), address(admittedAsker), pair); err == nil {
560 t.Errorf("a failed history read: answered %v, want an error", got)
561 }
562 body, _ := json.Marshal(suite.S2Request{Asker: address(admittedAsker), Pairs: pair})
563 if rec := serve(t, p, "POST", suite.RouteS2, body); rec.Code != 503 {
564 t.Errorf("through the server: %d, want 503", rec.Code)
565 }
566}
567
568// Never cached: the same question asked twice is answered from the world as
569// it is at each call — a revision that moved, and an admission list that
570// changed.
571//
572// MUTATION-TESTED 2026-11-01, reverted: Rule memoising its first answer per
573// (asker, pair) in a map on the producer → "after an edit" and "after
574// removal".
575func TestSuiteRuleIsNeverCached(t *testing.T) {
576 g, a, p := suiteWorld(t)
577 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
578 pair := []suite.ItemRevision{{ItemID: id(c), Revision: 1}}
579 ask := func() suite.Authorization {
580 t.Helper()
581 got, err := p.Rule(ctx(), address(admittedAsker), pair)
582 if err != nil {
583 t.Fatal(err)
584 }
585 return got[0]
586 }
587 if got := ask(); got != suite.VISIBLE {
588 t.Fatalf("first: %s", got)
589 }
590 if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
591 t.Fatal(err)
592 }
593 if got := ask(); got != suite.STALE {
594 t.Errorf("after an edit: %s, want STALE", got)
595 }
596 a.owners = ParseOwners("someone-else@example.com")
597 if got := ask(); got != suite.NOT_VISIBLE {
598 t.Errorf("after removal from the owners list: %s, want NOT_VISIBLE", got)
599 }
600}
601
602// S3 serves the current revision's text, in spec §6.4's shape, and refuses
603// everything else with suite.ErrNotAvailable.
604//
605// MUTATION-TESTED 2026-11-01, each reverted: both revision checks removed
606// (any revision served) → "an older revision"/"a newer revision"; the
607// title field repeated as a "Name:" line → "text"; empty fields emitted as
608// "Label: " → "text"; entries left out → "text"; a trailing newline →
609// "text"/"title only"; the canonical check removed → "not canonical"; the
610// stamp comparison removed → "wrong stamp".
611func TestSuiteContent(t *testing.T) {
612 g, a, p := suiteWorld(t)
613 c := mustCard(t, g, a, map[string]string{
614 FieldName: "Cnoc Teoranta",
615 FieldEmail: "orders@cnoc.example",
616 FieldNotes: "met at the trade show",
617 })
618 if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "first call"}); err != nil {
619 t.Fatal(err)
620 }
621 if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "second call", FieldDuration: "15"}); err != nil {
622 t.Fatal(err)
623 }
624 // c is at revision 3.
625 got, err := p.Content(ctx(), id(c), 3)
626 if err != nil {
627 t.Fatalf("current revision: %v", err)
628 }
629 want := strings.Join([]string{
630 "Cnoc Teoranta",
631 "Email: orders@cnoc.example",
632 "Notes: met at the trade show",
633 "",
634 "Call log",
635 "What was said: second call",
636 "Duration: 15",
637 "",
638 "Call log",
639 "What was said: first call",
640 }, "\n")
641 if string(got) != want {
642 t.Errorf("text:\n got %q\nwant %q", got, want)
643 }
644
645 title := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
646 if got, err := p.Content(ctx(), id(title), 1); err != nil || string(got) != "Harbour Timber" {
647 t.Errorf("title only: %q, %v", got, err)
648 }
649
650 gone := mustCard(t, g, a, map[string]string{FieldName: "Gone Ltd"})
651 if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil {
652 t.Fatal(err)
653 }
654 for name, q := range map[string]struct {
655 item string
656 rev int64
657 }{
658 "an older revision": {id(c), 2},
659 "a newer revision": {id(c), 4},
660 "gone": {id(gone), 2},
661 "gone, its old revision": {id(gone), 1},
662 "unknown": {"999999.1", 1},
663 "not a card id": {"doc-team", 1},
664 "not canonical": {"0" + id(c), 3},
665 "no stamp": {bare(c), 3},
666 "wrong stamp": {itemID(c.ID, c.Nonce+1), 3},
667 } {
668 if body, err := p.Content(ctx(), q.item, q.rev); !errors.Is(err, suite.ErrNotAvailable) || body != nil {
669 t.Errorf("%s: %q, %v; want ErrNotAvailable and no body", name, body, err)
670 }
671 }
672}
673
674// An edit that commits while S3 is reading the card is refused, not served
675// under a revision it does not match. The edit is made to land after
676// LoadCard has read the card row and its values, before its entries; the
677// card goes from revision 1 to 2. Asked for 1, the read finished on a
678// card that is no longer at 1; asked for 2, it started on a card that was
679// not yet at 2. Both are refused.
680//
681// MUTATION-TESTED 2026-11-01, each reverted: the second revision check
682// removed → "asked for the revision it started at"; the first removed →
683// "asked for the revision the edit produced".
684func TestSuiteContentRefusesAnEditMidRead(t *testing.T) {
685 for name, asked := range map[string]int64{
686 "asked for the revision it started at": 1,
687 "asked for the revision the edit produced": 2,
688 } {
689 t.Run(name, func(t *testing.T) {
690 g, a, p := suiteWorld(t)
691 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
692 fired := false
693 if err := g.Callback().Query().After("gorm:query").Register("test:edit_mid_read", func(tx *gorm.DB) {
694 if fired || tx.Statement.Table != "card_values" {
695 return
696 }
697 fired = true
698 if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldName: "Renamed"}); err != nil {
699 t.Errorf("the mid-read edit: %v", err)
700 }
701 }); err != nil {
702 t.Fatal(err)
703 }
704 body, err := p.Content(ctx(), id(c), asked)
705 if !fired {
706 t.Fatal("the mid-read edit never ran; the test proves nothing")
707 }
708 if !errors.Is(err, suite.ErrNotAvailable) {
709 t.Errorf("served %q, %v; want ErrNotAvailable", body, err)
710 }
711 })
712 }
713}
714
715// A restore from an older backup, and a different card created after it,
716// reproduce the old card's id, revision and event position exactly (Astra,
717// 2026-11-01). memoria still holds the old card's item id, its text and its
718// feed cursor. None of the three may carry on as if nothing happened: S2
719// does not vouch for the old item, S3 does not serve the new card's text
720// under it, and S1 answers the old cursor with the reset (doctrine §6.6),
721// which sends memoria back to "" to re-read this instance.
722//
723// Modelled with two databases seeded alike: "before" is the backup, taken
724// before the original card existed; "after" is the live database that went
725// on to hold it. The test first proves the collision is real.
726//
727// MUTATION-TESTED 2026-11-01, each reverted: Rule's stamp comparison
728// removed → "S2"; Content's stamp comparison removed → "S3"; the cursor's
729// stamp comparison removed → "S1"; the cursor's event lookup skipped
730// entirely → "S1".
731func TestSuiteRestoreCannotPassOffANewCardAsAnOldOne(t *testing.T) {
732 gBefore, aBefore, pBefore := suiteWorld(t)
733 gAfter, aAfter, pAfter := suiteWorld(t)
734
735 original := mustCard(t, gAfter, aAfter, map[string]string{FieldName: "The original, which memoria holds"})
736 held := id(original)
737 _, heldCursor := readFeed(t, pAfter, "", 10)
738 if got, _ := pAfter.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}}); got[0] != suite.VISIBLE {
739 t.Fatalf("before the restore, the held item: %s", got[0])
740 }
741
742 // The restore: the live database is now "before", and a different card
743 // is made in it.
744 recreated := mustCardBy(t, gBefore, aBefore, Person(2), map[string]string{FieldName: "A different card"})
745 var origEv, newEv []Event
746 gAfter.Where("object_kind = ?", ObjectCard).Find(&origEv)
747 gBefore.Where("object_kind = ?", ObjectCard).Find(&newEv)
748 if recreated.ID != original.ID || recreated.Revision != original.Revision ||
749 len(origEv) != 1 || len(newEv) != 1 || origEv[0].ID != newEv[0].ID {
750 t.Fatalf("the collision did not happen, so this proves nothing: card %d/%d rev %d/%d, events %+v %+v",
751 original.ID, recreated.ID, original.Revision, recreated.Revision, origEv, newEv)
752 }
753 if id(recreated) == held {
754 t.Fatal("the recreated card has the held item id: the nonce repeated")
755 }
756
757 got, err := pBefore.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}})
758 if err != nil || got[0] != suite.NOT_VISIBLE {
759 t.Errorf("S2 for the held item after the restore: %v, %v; want NOT_VISIBLE", got, err)
760 }
761 if body, err := pBefore.Content(ctx(), held, 1); !errors.Is(err, suite.ErrNotAvailable) {
762 t.Errorf("S3 for the held item after the restore: served %q, %v; want ErrNotAvailable", body, err)
763 }
764 if f, err := pBefore.Feed(ctx(), heldCursor, 10); !errors.Is(err, server.ErrCursorReset) {
765 t.Errorf("S1 from the held cursor %q after the restore: %+v, %v; want server.ErrCursorReset, not a page", heldCursor, f, err)
766 }
767 // The new card is served under its own id.
768 if body, err := pBefore.Content(ctx(), id(recreated), 1); err != nil || string(body) != "A different card" {
769 t.Errorf("S3 for the new card under its own id: %q, %v", body, err)
770 }
771}
772
773// A database failure on S3's final revision re-read is an error, which the
774// server answers 503 and the consumer retries — never ErrNotAvailable, the
775// refusal that tells memoria the card is gone.
776//
777// MUTATION-TESTED 2026-11-01, reverted: the re-read's error mapped to
778// suite.ErrNotAvailable → "a refusal" and "404".
779func TestSuiteContentReReadFailureIsAnError(t *testing.T) {
780 g, a, p := suiteWorld(t)
781 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
782 cardsQueries := 0
783 if err := g.Callback().Query().Before("gorm:query").Register("test:fail_reread", func(tx *gorm.DB) {
784 if tx.Statement.Table != "cards" {
785 return
786 }
787 // LoadCard reads the card first; the re-read is the second.
788 if cardsQueries++; cardsQueries == 2 {
789 tx.AddError(errors.New("the disk went away"))
790 }
791 }); err != nil {
792 t.Fatal(err)
793 }
794 _, err := p.Content(ctx(), id(c), 1)
795 if cardsQueries < 2 {
796 t.Fatal("the re-read never ran; the test proves nothing")
797 }
798 if err == nil || errors.Is(err, suite.ErrNotAvailable) {
799 t.Errorf("a failed re-read: %v; want an error that is not a refusal", err)
800 }
801
802 cardsQueries = 0
803 if rec := serve(t, p, "GET", suite.RouteS3+"/"+id(c)+"?revision=1", nil); rec.Code != 503 {
804 t.Errorf("through the server: %d, want 503 (404 is a refusal)", rec.Code)
805 }
806}
807
808// An event naming a card with no row is a database this code did not
809// write: the cards_are_not_hard_deleted trigger (migration 0002) refuses
810// the delete, so the test drops it on its own temporary database to build
811// one. The feed fails loudly rather than skip the row, which would move
812// the consumer's cursor past a change it never saw.
813//
814// MUTATION-TESTED 2026-11-01, reverted: the missing-row check skipped →
815// "a card with no row".
816func TestSuiteFeedRefusesAnEventWithNoCard(t *testing.T) {
817 g, a, p := suiteWorld(t)
818 c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
819 if err := g.Exec("DROP TRIGGER cards_are_not_hard_deleted").Error; err != nil {
820 t.Fatal(err)
821 }
822 if err := g.Exec("DELETE FROM cards WHERE id = ?", c.ID).Error; err != nil {
823 t.Fatal(err)
824 }
825 if f, err := p.Feed(ctx(), "", 10); err == nil {
826 t.Errorf("a card with no row: %+v, want an error", f)
827 }
828}
829
830// Every suite route sits under the one prefix the app mounts and exempts.
831func TestSuiteRoutesSitUnderThePrefix(t *testing.T) {
832 for _, r := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3} {
833 if !strings.HasPrefix(r, suitePrefix) {
834 t.Errorf("%s is not under %s", r, suitePrefix)
835 }
836 }
837}
838