Serve the suite contract: S1 from the events table, S2 as admission, S3 as card text
suiteProducer implements server.Producer (spec §6.2-§6.4): the feed pages card events by event id (gone = deleted, revision after the event, a cursor Fichas never issued is a 503); Rule answers UNKNOWN for a person_ref, NOT_VISIBLE for an address not admitted, then VISIBLE/STALE/ UNKNOWN by revision, never cached; Content is the card's text at its current revision, checked before and after the read. server.Handler mounts on the outer ServeMux at /suite/ only when a consumer is configured: outside the session group and outside the app's csrf.Protect, so memoria's bearer-only POST /suite/s2 is not refused. Exactly /suite/ is exempt. Tests: the suite's conformance harness over the real producer through a naming adapter, asserting the failures are exactly the twelve the fixture's ladder states produce (spec §6.7); Fichas-native tests for every S1/S2/S3 branch, the CSRF exemption, no consumers no routes, and the 401. 31 mutations, all red, recorded in the tests' comments.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,074
−0
internal/fichas/app.go+18 −0internal/fichas/suite.go+219 −0internal/fichas/suite_conformance_test.go+168 −0internal/fichas/suite_test.go+429 −0internal/fichastest/suite_test.go+240 −0
CI passed — run details
diff --git a/internal/fichas/app.go b/internal/fichas/app.go| index a8068d2..634eb1c 100644 |
| --- a/internal/fichas/app.go |
| +++ b/internal/fichas/app.go |
| @@ -14,6 +14,8 @@ import ( |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/mail" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/suite/server" |
| ) |
| // App wires the whole app: schema, router, static files. It returns a |
| @@ -138,10 +140,26 @@ func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error |
| // versioned prefix. Sessionless like the rest of static, and more |
| // specific than GET /static/, so it wins over the app's assets. |
| mux.Handle("GET "+sky.Prefix, sky.Handler()) |
| + // The suite contract (spec §6.5), only when a consumer is configured: |
| + // with none, Handler is nil and /suite/ is an unknown path like any |
| + // other. Mounted HERE, on the outer mux, and not on r: outside the |
| + // session group, because memoria is not a person and has no session, |
| + // and outside r's app-wide csrf.Protect, which would refuse its POST |
| + // /suite/s2 — it sends a bearer token and no Origin or Sec-Fetch-Site. |
| + // A bearer header is not something a cross-site form can attach, so |
| + // the CSRF check has nothing to protect here. Exactly /suite/ is |
| + // exempt; every other path still reaches r and its check. |
| + if h := server.Handler(&suiteProducer{g: d.G, sealer: cfg.Sealer, admit: a.Admit}, cfg.SuiteConsumers, logger); h != nil { |
| + mux.Handle(suitePrefix, h) |
| + } |
| mux.Handle("/", r) |
| return mux, a, nil |
| } |
| +// suitePrefix is where the suite routes live (suite.RouteS1 and its |
| +// siblings all sit under it), and the one path exempt from the CSRF check. |
| +const suitePrefix = "/suite/" |
| + |
| // AppForTest builds the app already signed in as one address. |
| // |
| // Named for what it does, and the naming is the point. memoria's earlier |
diff --git a/internal/fichas/suite.go b/internal/fichas/suite.go| new file mode 100644 |
| index 0000000..10ec570 |
| --- /dev/null |
| +++ b/internal/fichas/suite.go |
| @@ -0,0 +1,219 @@ |
| +package fichas |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strconv" |
| + "strings" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/fichas/internal/fichas/seal" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/oficina/suite/server" |
| +) |
| + |
| +// suiteProducer is Fichas' half of the suite contract (spec §6; suite |
| +// doctrine revision 10, pinned at 53b79d5, §6.5). server.Handler owns the wire — |
| +// the bearer check, the decoding, the one S3 refusal — and this owns only |
| +// what Fichas knows: its log, its admission list, and a card's text. |
| +// |
| +// Paul, 2026-11-01: "Hold private too, check per person." Fichas has no |
| +// sharing ladder — every admitted person sees every card that is not gone |
| +// (Card.OwnerID is provenance, not authority) — so the feed carries every |
| +// card, S3 serves any live card, and S2 is admission. |
| +type suiteProducer struct { |
| + g *gorm.DB |
| + sealer *seal.Sealer |
| + // admit is app.Admit: the one admission predicate sign-in and every |
| + // session already run. Passed in rather than re-derived, so S2 cannot |
| + // drift from who may open the app. |
| + admit func(address string) bool |
| +} |
| + |
| +var _ server.Producer = (*suiteProducer)(nil) |
| + |
| +// Feed pages the events table (spec §6.2): card events after the cursor, |
| +// in id order, one row each. The cursor is the last row's event id. |
| +func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| + after, err := parseCursor(cursor) |
| + if err != nil { |
| + return suite.Feed{}, err |
| + } |
| + var evs []Event |
| + // Only the four plaintext columns the row needs: nothing sealed is |
| + // read, so nothing sealed can reach a row. |
| + if err := p.g.WithContext(ctx).Model(&Event{}). |
| + Select("id", "kind", "object_id", "revision", "created_at"). |
| + Where("id > ? AND object_kind = ?", after, ObjectCard). |
| + Order("id").Limit(limit).Find(&evs).Error; err != nil { |
| + return suite.Feed{}, fmt.Errorf("fichas: reading the feed: %w", err) |
| + } |
| + if len(evs) == 0 { |
| + // At the tip, the same cursor — unless it is ahead of the log, |
| + // which means the log went backwards (a restore). An empty page |
| + // there would stall the consumer silently, so it is an error. |
| + var latest int64 |
| + if err := p.g.WithContext(ctx).Model(&Event{}). |
| + Select("COALESCE(MAX(id), 0)").Scan(&latest).Error; err != nil { |
| + return suite.Feed{}, fmt.Errorf("fichas: reading the log's tip: %w", err) |
| + } |
| + if after > latest { |
| + return suite.Feed{}, fmt.Errorf("fichas: feed cursor %d is ahead of the log (%d)", after, latest) |
| + } |
| + return suite.Feed{Cursor: strconv.FormatInt(after, 10), Rows: []suite.FeedRow{}}, nil |
| + } |
| + rows := make([]suite.FeedRow, len(evs)) |
| + for i, e := range evs { |
| + rows[i] = suite.FeedRow{ |
| + ItemID: strconv.FormatInt(e.ObjectID, 10), |
| + Revision: e.Revision, |
| + Gone: e.Kind == EventDeleted, |
| + TouchedAt: e.CreatedAt, |
| + } |
| + } |
| + return suite.Feed{Cursor: strconv.FormatInt(evs[len(evs)-1].ID, 10), Rows: rows}, nil |
| +} |
| + |
| +// parseCursor reads a cursor Fichas issued: "" is the beginning, anything |
| +// else a canonical non-negative decimal. Anything else was not issued here |
| +// and is an error, never a guess. |
| +func parseCursor(c string) (int64, error) { |
| + if c == "" { |
| + return 0, nil |
| + } |
| + n, err := strconv.ParseInt(c, 10, 64) |
| + if err != nil || n < 0 || strconv.FormatInt(n, 10) != c { |
| + return 0, fmt.Errorf("fichas: feed cursor %q was not issued by fichas", c) |
| + } |
| + return n, nil |
| +} |
| + |
| +// parseItemID reads an item id: a card id as a canonical decimal, so one |
| +// card has exactly one id on the wire ("042" and "+42" are not card 42). |
| +func parseItemID(s string) (int64, bool) { |
| + n, err := strconv.ParseInt(s, 10, 64) |
| + if err != nil || n < 1 || strconv.FormatInt(n, 10) != s { |
| + return 0, false |
| + } |
| + return n, true |
| +} |
| + |
| +// Rule is S2 (spec §6.3). Fichas is lone-shape only, so it keys on an |
| +// address; a person_ref is a kind it cannot read and answers UNKNOWN, |
| +// loudly, rather than NOT_VISIBLE, which a consumer may act on silently. |
| +// Nothing here is cached: admission and every revision are read per call. |
| +func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| + out := make([]suite.Authorization, len(pairs)) |
| + if asker.Kind != suite.SubjectAddress { |
| + for i := range out { |
| + out[i] = suite.UNKNOWN |
| + } |
| + return out, nil |
| + } |
| + if !p.admit(asker.Value) { |
| + for i := range out { |
| + out[i] = suite.NOT_VISIBLE |
| + } |
| + return out, nil |
| + } |
| + |
| + ids := make([]int64, 0, len(pairs)) |
| + for _, pr := range pairs { |
| + if id, ok := parseItemID(pr.ItemID); ok { |
| + ids = append(ids, id) |
| + } |
| + } |
| + current := map[int64]int64{} // live cards only: id → revision |
| + if len(ids) > 0 { |
| + var cards []Card |
| + if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision"). |
| + Where("id IN ? AND gone = ?", ids, false).Find(&cards).Error; err != nil { |
| + return nil, fmt.Errorf("fichas: reading revisions: %w", err) |
| + } |
| + for _, c := range cards { |
| + current[c.ID] = c.Revision |
| + } |
| + } |
| + |
| + for i, pr := range pairs { |
| + id, ok := parseItemID(pr.ItemID) |
| + rev, live := current[id] |
| + switch { |
| + case !ok || !live: |
| + out[i] = suite.NOT_VISIBLE |
| + case pr.Revision == rev: |
| + out[i] = suite.VISIBLE |
| + case pr.Revision >= 1 && pr.Revision < rev: |
| + out[i] = suite.STALE |
| + default: |
| + // Ahead of the log (a restore), or below 1, which it never |
| + // issued: a revision Fichas cannot vouch for. |
| + out[i] = suite.UNKNOWN |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// Content is S3 (spec §6.4): the card's text at its current revision, and |
| +// suite.ErrNotAvailable for anything else. |
| +func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| + id, ok := parseItemID(itemID) |
| + if !ok { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + cv, err := LoadCard(ctx, p.g, p.sealer, id) |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil, suite.ErrNotAvailable // unknown, or gone |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + // Checked twice, and each check catches what the other cannot. |
| + // LoadCard reads the card row, then its values and entries, in |
| + // separate statements, so an edit can commit between them. This first |
| + // check pins where the read STARTED: without it, an edit landing |
| + // mid-read that produces the asked revision passes the second check |
| + // with the old row's values under the new number. |
| + if cv.Card.Revision != revision { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + body := cardText(cv) |
| + // The second pins that nothing committed since. A revision moves only |
| + // in the same transaction as the values and entries — a delete too, |
| + // which is why "gone" needs no check of its own here — so if it is |
| + // unchanged now, everything above was read at that revision. |
| + var now Card |
| + if err := p.g.WithContext(ctx).Select("id", "revision").First(&now, id).Error; err != nil { |
| + return nil, err |
| + } |
| + if now.Revision != revision { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + return []byte(body), nil |
| +} |
| + |
| +// cardText is the plain text a consumer indexes: the title, each other |
| +// field with a value as "Label: value", then each entry, newest first, as |
| +// its type label and its fields. Lines are joined with "\n" and there is no |
| +// trailing newline, so a card with only a title is exactly its title. |
| +func cardText(cv CardView) string { |
| + lines := []string{cv.Title()} |
| + for _, f := range cv.Fields { |
| + if cv.IsTitle(f.Def.Key) || f.Value == "" { |
| + continue |
| + } |
| + lines = append(lines, f.Label+": "+f.Value) |
| + } |
| + for _, e := range cv.Entries { |
| + lines = append(lines, "", e.TypeLabel) |
| + for _, f := range e.Fields { |
| + if f.Value == "" { |
| + continue |
| + } |
| + lines = append(lines, f.Label+": "+f.Value) |
| + } |
| + } |
| + return strings.Join(lines, "\n") |
| +} |
diff --git a/internal/fichas/suite_conformance_test.go b/internal/fichas/suite_conformance_test.go| new file mode 100644 |
| index 0000000..3a04877 |
| --- /dev/null |
| +++ b/internal/fichas/suite_conformance_test.go |
| @@ -0,0 +1,168 @@ |
| +package fichas |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "slices" |
| + "strconv" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| + "amadan.net/oficina/suite/conformance" |
| + "amadan.net/oficina/suite/server" |
| +) |
| + |
| +// fixtureNames lets the suite's custody fixture address a real Fichas |
| +// world. It RENAMES and decides nothing: the fixture's item ids become the |
| +// card ids seeded for them (and back again in feed rows), and its person_ref askers become the addresses |
| +// a lone instance keys on (spec §6.7 — the fixture is suite-shape only). |
| +// Every answer is the real producer's, over a real database. |
| +type fixtureNames struct { |
| + inner server.Producer |
| + ids map[string]string |
| + askers map[suite.Subject]suite.Subject |
| +} |
| + |
| +// Feed renames each row's card id back to the fixture id it was seeded |
| +// for, so the harness can find its items in the feed. Rows for cards the |
| +// fixture did not seed pass through as themselves. |
| +func (n fixtureNames) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| + f, err := n.inner.Feed(ctx, cursor, limit) |
| + for i, row := range f.Rows { |
| + for fixtureID, cardID := range n.ids { |
| + if row.ItemID == cardID { |
| + f.Rows[i].ItemID = fixtureID |
| + } |
| + } |
| + } |
| + return f, err |
| +} |
| + |
| +func (n fixtureNames) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| + if a, ok := n.askers[asker]; ok { |
| + asker = a |
| + } |
| + renamed := make([]suite.ItemRevision, len(pairs)) |
| + for i, pr := range pairs { |
| + renamed[i] = suite.ItemRevision{ItemID: n.name(pr.ItemID), Revision: pr.Revision} |
| + } |
| + return n.inner.Rule(ctx, asker, renamed) |
| +} |
| + |
| +func (n fixtureNames) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| + return n.inner.Content(ctx, n.name(itemID), revision) |
| +} |
| + |
| +// name maps a fixture id to its card, and passes anything else through |
| +// untouched — so the harness's never-existed id reaches Fichas as itself. |
| +func (n fixtureNames) name(id string) string { |
| + if c, ok := n.ids[id]; ok { |
| + return c |
| + } |
| + return id |
| +} |
| + |
| +// The suite's own conformance harness, run against Fichas' real producer |
| +// over a world seeded from the custody fixture: one Customer card per case, |
| +// named with the case's s3_body (so S3's exact-body check is a real check |
| +// of the text shape: a card with only a title is exactly its title), edited |
| +// up to the case's revision, and the deleted case deleted. |
| +// |
| +// The fixture describes a sharing ladder Fichas does not have (spec §6.7): |
| +// every admitted person sees every card. So four cases — guest-only, |
| +// link-shared private, moved to private, link added late — expect |
| +// NOT_VISIBLE for the fixture's asker where Fichas, correctly for Fichas, |
| +// answers VISIBLE at the current revision, STALE one behind and UNKNOWN one |
| +// ahead (a member may open the card, so a revision the log never issued is |
| +// UNKNOWN for them, §4.3). This test asserts the failures are EXACTLY those |
| +// twelve: any other failure, or one of these passing, is red, so a change |
| +// to the fixture on the suite branch (53b79d5, after review) is noticed |
| +// here rather than absorbed. |
| +// |
| +// MUTATION-TESTED 2026-11-01 against 53b79d5, each reverted, by how many |
| +// failures the harness then reports (12 expected): both of Content's |
| +// revision checks removed → 20 (superseded S3 served); a trailing newline |
| +// on the text → 20; admission skipped → 36 (the stranger sees everything); |
| +// gone cards answered in Rule → 15; the title repeated as a "Name:" line → |
| +// 20; feed rows never gone → 13; feed rows at revision 1 → 20; a revision |
| +// ahead answered STALE → 16. |
| +func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) { |
| + f, err := suite.LoadCustodyFixture() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g, a, p := suiteWorld(t) |
| + |
| + ids := map[string]string{} |
| + for _, c := range f.Cases { |
| + gone := c.Rung == suite.RungDeleted |
| + // A deleted card's last live revision is one below the fixture's, |
| + // because the delete itself is a revision. |
| + lastLive := c.Revision |
| + if gone { |
| + lastLive-- |
| + } |
| + name := c.S3Body |
| + if gone { |
| + name = "a card about to be deleted" |
| + } |
| + first := name |
| + if lastLive > 1 { |
| + first = "draft 1" |
| + } |
| + card := mustCard(t, g, a, map[string]string{FieldName: first}) |
| + for r := int64(2); r <= lastLive; r++ { |
| + v := fmt.Sprintf("draft %d", r) |
| + if r == lastLive { |
| + v = name |
| + } |
| + if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldName: v}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if gone { |
| + if err := DeleteCard(ctx(), g, a.sealer, card.ID, Person(1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var now Card |
| + if err := g.First(&now, card.ID).Error; err != nil || now.Revision != c.Revision || now.Gone != gone { |
| + t.Fatalf("seeding %s: card is %+v (%v), want revision %d gone %v", c.ItemID, now, err, c.Revision, gone) |
| + } |
| + ids[c.ItemID] = strconv.FormatInt(card.ID, 10) |
| + } |
| + |
| + names := fixtureNames{ |
| + inner: p, |
| + ids: ids, |
| + askers: map[suite.Subject]suite.Subject{ |
| + f.Asker: address(admittedAsker), // admitted: on FICHAS_OWNERS |
| + f.Stranger: address("bo@example.com"), // not admitted |
| + }, |
| + } |
| + report := conformance.Check(server.Routes(names, nil)) |
| + if report.Checked == 0 { |
| + t.Fatal("conformance checked nothing") |
| + } |
| + |
| + var want []string |
| + for _, item := range []string{"doc-guest", "doc-link", "doc-was-team", "doc-link-added-late"} { |
| + want = append(want, |
| + fmt.Sprintf("S2 %s asked for the fixture's asker, at the current revision: got VISIBLE, want NOT_VISIBLE", item), |
| + fmt.Sprintf("S2 %s asked for the fixture's asker, one revision behind: got STALE, want NOT_VISIBLE", item), |
| + fmt.Sprintf("S2 %s asked for the fixture's asker, one revision ahead: got UNKNOWN, want NOT_VISIBLE", item)) |
| + } |
| + got := slices.Clone(report.Failures) |
| + slices.Sort(got) |
| + slices.Sort(want) |
| + if !slices.Equal(got, want) { |
| + t.Errorf("conformance failures are not exactly the inexpressible cases (spec §6.7).\n got (%d):", len(got)) |
| + for _, s := range got { |
| + t.Errorf(" %s", s) |
| + } |
| + t.Errorf("want (%d):", len(want)) |
| + for _, s := range want { |
| + t.Errorf(" %s", s) |
| + } |
| + } |
| +} |
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go| new file mode 100644 |
| index 0000000..5a8b1eb |
| --- /dev/null |
| +++ b/internal/fichas/suite_test.go |
| @@ -0,0 +1,429 @@ |
| +package fichas |
| + |
| +import ( |
| + "errors" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +// The producer half of the suite contract (spec §6). These drive the |
| +// producer directly; fichastest/suite_test.go drives it through the real |
| +// router, and suite_conformance_test.go through the suite's own harness. |
| + |
| +const admittedAsker = "ana@example.com" |
| + |
| +// producerFor builds the producer over the real admission predicate, |
| +// app.Admit, with one admitted address — what LoadConfig gives a lone |
| +// instance whose FICHAS_OWNERS is that address. |
| +func producerFor(g *gorm.DB, a *app) *suiteProducer { |
| + return &suiteProducer{g: g, sealer: a.sealer, admit: a.Admit} |
| +} |
| + |
| +func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) { |
| + t.Helper() |
| + g, s := seeded(t) |
| + a := &app{sealer: s, owners: ParseOwners(admittedAsker)} |
| + return g, a, producerFor(g, a) |
| +} |
| + |
| +func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card { |
| + t.Helper() |
| + c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, Person(1), values) |
| + if err != nil { |
| + t.Fatalf("CreateCard: %v", err) |
| + } |
| + return c |
| +} |
| + |
| +func id(c Card) string { return strconv.FormatInt(c.ID, 10) } |
| + |
| +func address(v string) suite.Subject { return suite.Subject{Kind: suite.SubjectAddress, Value: v} } |
| + |
| +// readFeed pages from cursor to the tip, limit rows a page, and returns |
| +// every row and the tip's cursor. |
| +func readFeed(t *testing.T, p *suiteProducer, cursor string, limit int) ([]suite.FeedRow, string) { |
| + t.Helper() |
| + var all []suite.FeedRow |
| + for pages := 0; ; pages++ { |
| + if pages > 100 { |
| + t.Fatal("the feed never reached its tip") |
| + } |
| + f, err := p.Feed(ctx(), cursor, limit) |
| + if err != nil { |
| + t.Fatalf("Feed(%q): %v", cursor, err) |
| + } |
| + if f.Cursor == "" || len(f.Rows) > limit { |
| + t.Fatalf("Feed(%q) broke the contract: %+v", cursor, f) |
| + } |
| + if len(f.Rows) == 0 { |
| + if f.Cursor != cursor && cursor != "" { |
| + t.Fatalf("at the tip the cursor moved: %q → %q", cursor, f.Cursor) |
| + } |
| + if f.Rows == nil { |
| + t.Fatal("the tip's rows are nil, not empty") |
| + } |
| + return all, f.Cursor |
| + } |
| + all = append(all, f.Rows...) |
| + cursor = f.Cursor |
| + } |
| +} |
| + |
| +type row struct { |
| + item string |
| + rev int64 |
| + gone bool |
| +} |
| + |
| +func rowsOf(rs []suite.FeedRow) []row { |
| + out := make([]row, len(rs)) |
| + for i, r := range rs { |
| + out[i] = row{r.ItemID, r.Revision, r.Gone} |
| + } |
| + return out |
| +} |
| + |
| +// S1 is the events table: one row per card event, in log order, carrying |
| +// the card's revision after that event; an entry bumps its card; a delete |
| +// is gone; the catalogue's type and field events and an entry's own |
| +// creation row are not items. Paged two at a time so every page boundary |
| +// is crossed, and the tip answers the same cursor and no rows. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the object_kind filter |
| +// dropped (seed and entry events become rows) → "rows"; Gone hard-coded |
| +// false → "rows"; Revision taken as 1 → "rows"; the next cursor taken from |
| +// the FIRST row of a page (pages repeat) → "rows"; the tip answering a |
| +// fresh cursor ("0") → "at the tip the cursor moved"; the tip's Rows left |
| +// nil → "nil, not empty"; created_at not selected (zero touched_at) → |
| +// "touched_at". |
| +func TestSuiteFeedIsTheEventLog(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + c1 := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + c2 := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) |
| + if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := AddEntry(ctx(), g, a.sealer, c1.ID, Person(2), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := DeleteCard(ctx(), g, a.sealer, c2.ID, Person(1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + rows, tip := readFeed(t, p, "", 2) |
| + want := []row{ |
| + {id(c1), 1, false}, |
| + {id(c2), 1, false}, |
| + {id(c1), 2, false}, // an update |
| + {id(c1), 3, false}, // an entry landing bumps its card |
| + {id(c2), 2, true}, // a delete is gone |
| + } |
| + if got := rowsOf(rows); !slices.Equal(got, want) { |
| + t.Fatalf("rows:\n got %+v\nwant %+v", got, want) |
| + } |
| + for _, r := range rows { |
| + if r.TouchedAt.IsZero() { |
| + t.Errorf("touched_at is zero on %+v", r) |
| + } |
| + } |
| + |
| + // The tip, asked again, is the same cursor and no rows; a change after |
| + // it is exactly one more row. |
| + if more, again := readFeed(t, p, tip, 2); len(more) != 0 || again != tip { |
| + t.Fatalf("at the tip: %d rows, cursor %q (was %q)", len(more), again, tip) |
| + } |
| + if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Won"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if more, _ := readFeed(t, p, tip, 2); !slices.Equal(rowsOf(more), []row{{id(c1), 4, false}}) { |
| + t.Fatalf("after the tip: %+v", rowsOf(more)) |
| + } |
| +} |
| + |
| +// A row is the four plaintext columns and nothing else: no value, label or |
| +// actor can reach it because the query never reads one. |
| +func TestSuiteFeedRowsCarryNoContent(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta", FieldNotes: "owes us money"}) |
| + f, err := p.Feed(ctx(), "", 10) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range f.Rows { |
| + for _, s := range []string{r.ItemID, f.Cursor} { |
| + if strings.Contains(s, "Cnoc") || strings.Contains(s, "money") { |
| + t.Fatalf("content in a feed row: %+v", r) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// An empty log starts at "0" (the contract refuses an empty cursor) and |
| +// stays there. |
| +func TestSuiteFeedOnAnEmptyLog(t *testing.T) { |
| + g := testDB(t) |
| + p := &suiteProducer{g: g, sealer: testSealer(t), admit: func(string) bool { return true }} |
| + f, err := p.Feed(ctx(), "", 10) |
| + if err != nil || f.Cursor != "0" || f.Rows == nil || len(f.Rows) != 0 { |
| + t.Fatalf("empty log: %+v, %v", f, err) |
| + } |
| + if f, err := p.Feed(ctx(), "0", 10); err != nil || f.Cursor != "0" || len(f.Rows) != 0 { |
| + t.Fatalf("empty log again: %+v, %v", f, err) |
| + } |
| +} |
| + |
| +// A cursor Fichas could not have issued is an error (the server makes it a |
| +// 503), never a page: not a canonical decimal, or ahead of the log — a |
| +// restore from an older backup, where an empty page would stall the |
| +// consumer silently. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the canonical-form check |
| +// removed ("007", "+5" accepted) → "007"/"+5"; the ahead-of-the-log check |
| +// removed → "ahead"; a negative accepted → "-1". |
| +func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + _, tip := readFeed(t, p, "", 10) |
| + n, _ := strconv.ParseInt(tip, 10, 64) |
| + for name, c := range map[string]string{ |
| + "letters": "abc", |
| + "-1": "-1", |
| + "007": "007", |
| + "+5": "+5", |
| + "spaces": " 5", |
| + "ahead": strconv.FormatInt(n+1000, 10), |
| + } { |
| + if f, err := p.Feed(ctx(), c, 10); err == nil { |
| + t.Errorf("%s: cursor %q answered %+v, want an error", name, c, f) |
| + } |
| + } |
| +} |
| + |
| +// S2, every branch of spec §6.3's table. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the person_ref branch removed |
| +// (a person_ref falls to admission and answers NOT_VISIBLE) → "person_ref"; |
| +// admission skipped → "not admitted"; the gone filter dropped from the |
| +// revision query → "gone"; STALE's lower bound removed (revision 0 is |
| +// STALE) → "revision 0"; the > current case answering STALE → |
| +// "ahead"; == current answering STALE → "current"; parseItemID's canonical |
| +// check removed ("03" is card 3) → "not canonical". |
| +func TestSuiteRuleEveryBranch(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + live := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + for _, stage := range []string{"Lead", "Won"} { |
| + if err := UpdateCard(ctx(), g, a.sealer, live.ID, Person(1), map[string]string{FieldStage: stage}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // live is at revision 3. |
| + gone := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) |
| + if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + padded := "0" + id(live) |
| + |
| + pairs := []suite.ItemRevision{ |
| + {ItemID: id(live), Revision: 3}, // current |
| + {ItemID: id(live), Revision: 2}, // behind |
| + {ItemID: id(live), Revision: 4}, // ahead |
| + {ItemID: id(live), Revision: 0}, // revision 0 |
| + {ItemID: id(gone), Revision: 2}, // gone, at its last revision |
| + {ItemID: "999999", Revision: 1}, // unknown |
| + {ItemID: "doc-team", Revision: 1}, // not a card id |
| + {ItemID: padded, Revision: 3}, // not canonical |
| + } |
| + names := []string{"current", "behind", "ahead", "revision 0", "gone", "unknown", "not a card id", "not canonical"} |
| + |
| + check := func(what string, asker suite.Subject, want []suite.Authorization) { |
| + t.Helper() |
| + got, err := p.Rule(ctx(), asker, pairs) |
| + if err != nil { |
| + t.Fatalf("%s: %v", what, err) |
| + } |
| + if len(got) != len(pairs) { |
| + t.Fatalf("%s: %d answers for %d pairs", what, len(got), len(pairs)) |
| + } |
| + for i := range pairs { |
| + if got[i] != want[i] { |
| + t.Errorf("%s, %s: got %s, want %s", what, names[i], got[i], want[i]) |
| + } |
| + } |
| + } |
| + all := func(v suite.Authorization) []suite.Authorization { |
| + out := make([]suite.Authorization, len(pairs)) |
| + for i := range out { |
| + out[i] = v |
| + } |
| + return out |
| + } |
| + |
| + check("admitted", address(admittedAsker), []suite.Authorization{ |
| + suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN, |
| + suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, |
| + }) |
| + // A kind Fichas does not key on is UNKNOWN — loud — even when its value |
| + // happens to be an admitted address. |
| + check("person_ref", suite.Subject{Kind: suite.SubjectPersonRef, Value: admittedAsker}, all(suite.UNKNOWN)) |
| + check("not admitted", address("bo@example.com"), all(suite.NOT_VISIBLE)) |
| +} |
| + |
| +// Never cached: the same question asked twice is answered from the world as |
| +// it is at each call — a revision that moved, and an admission list that |
| +// changed. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: Rule memoising its first answer per |
| +// (asker, pair) in a map on the producer → "after an edit" and "after |
| +// removal". |
| +func TestSuiteRuleIsNeverCached(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + pair := []suite.ItemRevision{{ItemID: id(c), Revision: 1}} |
| + ask := func() suite.Authorization { |
| + t.Helper() |
| + got, err := p.Rule(ctx(), address(admittedAsker), pair) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return got[0] |
| + } |
| + if got := ask(); got != suite.VISIBLE { |
| + t.Fatalf("first: %s", got) |
| + } |
| + if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := ask(); got != suite.STALE { |
| + t.Errorf("after an edit: %s, want STALE", got) |
| + } |
| + a.owners = ParseOwners("someone-else@example.com") |
| + if got := ask(); got != suite.NOT_VISIBLE { |
| + t.Errorf("after removal from the owners list: %s, want NOT_VISIBLE", got) |
| + } |
| +} |
| + |
| +// S3 serves the current revision's text, in spec §6.4's shape, and refuses |
| +// everything else with suite.ErrNotAvailable. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: both revision checks removed |
| +// (any revision served) → "an older revision"/"a newer revision"; the |
| +// title field repeated as a "Name:" line → "text"; empty fields emitted as |
| +// "Label: " → "text"; entries left out → "text"; a trailing newline → |
| +// "text"/"title only"; parseItemID's canonical check removed → "not |
| +// canonical". |
| +func TestSuiteContent(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + c := mustCard(t, g, a, map[string]string{ |
| + FieldName: "Cnoc Teoranta", |
| + FieldEmail: "orders@cnoc.example", |
| + FieldNotes: "met at the trade show", |
| + }) |
| + if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "first call"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "second call", FieldDuration: "15"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // c is at revision 3. |
| + got, err := p.Content(ctx(), id(c), 3) |
| + if err != nil { |
| + t.Fatalf("current revision: %v", err) |
| + } |
| + want := strings.Join([]string{ |
| + "Cnoc Teoranta", |
| + "Email: orders@cnoc.example", |
| + "Notes: met at the trade show", |
| + "", |
| + "Call log", |
| + "What was said: second call", |
| + "Duration: 15", |
| + "", |
| + "Call log", |
| + "What was said: first call", |
| + }, "\n") |
| + if string(got) != want { |
| + t.Errorf("text:\n got %q\nwant %q", got, want) |
| + } |
| + |
| + title := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) |
| + if got, err := p.Content(ctx(), id(title), 1); err != nil || string(got) != "Harbour Timber" { |
| + t.Errorf("title only: %q, %v", got, err) |
| + } |
| + |
| + gone := mustCard(t, g, a, map[string]string{FieldName: "Gone Ltd"}) |
| + if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, q := range map[string]struct { |
| + item string |
| + rev int64 |
| + }{ |
| + "an older revision": {id(c), 2}, |
| + "a newer revision": {id(c), 4}, |
| + "gone": {id(gone), 2}, |
| + "gone, its old revision": {id(gone), 1}, |
| + "unknown": {"999999", 1}, |
| + "not a card id": {"doc-team", 1}, |
| + "not canonical": {"0" + id(c), 3}, |
| + } { |
| + if body, err := p.Content(ctx(), q.item, q.rev); !errors.Is(err, suite.ErrNotAvailable) || body != nil { |
| + t.Errorf("%s: %q, %v; want ErrNotAvailable and no body", name, body, err) |
| + } |
| + } |
| +} |
| + |
| +// An edit that commits while S3 is reading the card is refused, not served |
| +// under a revision it does not match. The edit is made to land after |
| +// LoadCard has read the card row and its values, before its entries; the |
| +// card goes from revision 1 to 2. Asked for 1, the read finished on a |
| +// card that is no longer at 1; asked for 2, it started on a card that was |
| +// not yet at 2. Both are refused. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the second revision check |
| +// removed → "asked for the revision it started at"; the first removed → |
| +// "asked for the revision the edit produced". |
| +func TestSuiteContentRefusesAnEditMidRead(t *testing.T) { |
| + for name, asked := range map[string]int64{ |
| + "asked for the revision it started at": 1, |
| + "asked for the revision the edit produced": 2, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + fired := false |
| + if err := g.Callback().Query().After("gorm:query").Register("test:edit_mid_read", func(tx *gorm.DB) { |
| + if fired || tx.Statement.Table != "card_values" { |
| + return |
| + } |
| + fired = true |
| + if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldName: "Renamed"}); err != nil { |
| + t.Errorf("the mid-read edit: %v", err) |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, err := p.Content(ctx(), id(c), asked) |
| + if !fired { |
| + t.Fatal("the mid-read edit never ran; the test proves nothing") |
| + } |
| + if !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("served %q, %v; want ErrNotAvailable", body, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Every suite route sits under the one prefix the app mounts and exempts. |
| +func TestSuiteRoutesSitUnderThePrefix(t *testing.T) { |
| + for _, r := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3} { |
| + if !strings.HasPrefix(r, suitePrefix) { |
| + t.Errorf("%s is not under %s", r, suitePrefix) |
| + } |
| + } |
| +} |
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go| new file mode 100644 |
| index 0000000..0f177f2 |
| --- /dev/null |
| +++ b/internal/fichastest/suite_test.go |
| @@ -0,0 +1,240 @@ |
| +package fichastest |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/db" |
| + |
| + fichas "amadan.net/oficina/fichas/internal/fichas" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/oficina/suite/server" |
| +) |
| + |
| +// The suite routes through the real router (spec §6.5): mounted only when a |
| +// consumer is configured, behind the bearer check, and outside the app's |
| +// CSRF check at exactly /suite/. |
| + |
| +const suiteToken = "a-test-token-for-memoria" |
| + |
| +func suiteConsumers() string { |
| + return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteToken) + `"}]}]` |
| +} |
| + |
| +// suiteConfig is testConfig with FICHAS_SUITE_CONSUMERS, read through |
| +// LoadConfig as main reads it. |
| +func suiteConfig(t *testing.T, consumers string) fichas.Config { |
| + t.Helper() |
| + c, err := fichas.LoadConfig(func(k string) string { |
| + switch k { |
| + case "FICHAS_DEK": |
| + return base64.StdEncoding.EncodeToString(testKey()) |
| + case "FICHAS_ORIGIN": |
| + return testOrigin |
| + case "FICHAS_INSTANCE_KEY": |
| + return "test-instance-key" |
| + case "FICHAS_OWNERS": |
| + return TestOwner |
| + case "FICHAS_ALLOW_LOGGED_MAIL": |
| + return "1" |
| + case "FICHAS_SUITE_CONSUMERS": |
| + return consumers |
| + } |
| + return "" |
| + }) |
| + if err != nil { |
| + t.Fatalf("LoadConfig: %v", err) |
| + } |
| + return c |
| +} |
| + |
| +// suiteApp is fichas.App exactly as main builds it — not AppForTest, |
| +// so nothing here leans on the test identity. |
| +func suiteApp(t *testing.T, consumers string) http.Handler { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + mux, _, err := fichas.App(d, suiteConfig(t, consumers), logger) |
| + if err != nil { |
| + t.Fatalf("App: %v", err) |
| + } |
| + return mux |
| +} |
| + |
| +// call is a sibling's request: a bearer token when tok is set, and no |
| +// Origin, Referer or Sec-Fetch-Site — memoria sends none. |
| +func call(h http.Handler, method, target, tok string, body []byte) *httptest.ResponseRecorder { |
| + req := httptest.NewRequest(method, target, bytes.NewReader(body)) |
| + if tok != "" { |
| + req.Header.Set("Authorization", "Bearer "+tok) |
| + } |
| + if body != nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, req) |
| + return rec |
| +} |
| + |
| +func s2Body(t *testing.T, asker string, pairs ...suite.ItemRevision) []byte { |
| + t.Helper() |
| + if pairs == nil { |
| + pairs = []suite.ItemRevision{} |
| + } |
| + b, err := json.Marshal(suite.S2Request{Asker: suite.Subject{Kind: suite.SubjectAddress, Value: asker}, Pairs: pairs}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// With a consumer configured, every suite route answers the same empty 401 |
| +// to a request without its token, and serves one with it. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: server.Routes mounted in place of |
| +// server.Handler (no bearer check) → every "no token" and "a wrong token" |
| +// case. |
| +func TestSuiteRoutesNeedTheConsumerToken(t *testing.T) { |
| + h := suiteApp(t, suiteConsumers()) |
| + for _, r := range []struct{ method, target string }{ |
| + {"GET", suite.RouteS1}, |
| + {"POST", suite.RouteS2}, |
| + {"GET", suite.RouteS3 + "/1?revision=1"}, |
| + } { |
| + for name, tok := range map[string]string{"no token": "", "a wrong token": "not-the-token"} { |
| + rec := call(h, r.method, r.target, tok, s2Body(t, TestOwner)) |
| + if rec.Code != http.StatusUnauthorized || rec.Body.Len() != 0 { |
| + t.Errorf("%s %s, %s: %d %q, want an empty 401", r.method, r.target, name, rec.Code, rec.Body.String()) |
| + } |
| + } |
| + } |
| + rec := call(h, "GET", suite.RouteS1, suiteToken, nil) |
| + if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); err != nil { |
| + t.Errorf("S1 with the token: %v (%d %s)", err, rec.Code, rec.Body.String()) |
| + } |
| +} |
| + |
| +// memoria's S2 is a POST with a bearer token and no Origin, Referer or |
| +// Sec-Fetch-Site. The app-wide CSRF check would refuse it; /suite/ is |
| +// outside that check. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: the suite handler mounted on the |
| +// chi router (r.Mount("/suite", h)) instead of the outer mux → 403 here. |
| +func TestSuiteS2NeedsNoOrigin(t *testing.T) { |
| + h := suiteApp(t, suiteConsumers()) |
| + rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, suite.ItemRevision{ItemID: "1", Revision: 1})) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("POST /suite/s2 with only a bearer: %d %s", rec.Code, rec.Body.String()) |
| + } |
| + got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "1", Revision: 1}}, rec.Code, rec.Body.Bytes()) |
| + if got[0] != suite.NOT_VISIBLE { // no card 1 yet |
| + t.Errorf("S2 for a card that does not exist: %s", got[0]) |
| + } |
| +} |
| + |
| +// The exemption is exactly /suite/: every other state-changing request |
| +// without same-origin evidence is still refused, a bearer token makes no |
| +// difference to that, and a path that only looks like /suite/ is not |
| +// exempt. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: csrf.Protect replaced by a |
| +// wrapper skipping any request carrying an Authorization header → "POST |
| +// /cards with a bearer"; csrf.Protect skipped for any path starting with |
| +// the string "/suite" → "/suites/s2" and "/suite-s2". |
| +func TestOnlySuiteIsExemptFromTheCSRFCheck(t *testing.T) { |
| + h := suiteApp(t, suiteConsumers()) |
| + for name, target := range map[string]string{ |
| + "POST /cards with a bearer": "/cards", |
| + "/suites/s2": "/suites/s2", |
| + "/suite-s2": "/suite-s2", |
| + "a delete with a bearer": "/cards/1/delete", |
| + "/suite/../cards, before cleaning": "/suite/../cards", |
| + } { |
| + rec := call(h, "POST", target, suiteToken, []byte("f_name=x")) |
| + if rec.Code/100 == 2 || rec.Code == http.StatusUnauthorized { |
| + t.Errorf("%s: %d — reached a handler without same-origin evidence", name, rec.Code) |
| + } |
| + if target != "/suite/../cards" && rec.Code != http.StatusForbidden { |
| + t.Errorf("%s: %d, want the CSRF check's 403", name, rec.Code) |
| + } |
| + } |
| +} |
| + |
| +// No consumers, no routes (doctrine §3): /suite/ is an unknown path like |
| +// any other, token or not. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: the suite mounted with |
| +// server.Routes whenever Handler returned nil → "GET" serves a feed. |
| +func TestNoConsumersNoSuiteRoutes(t *testing.T) { |
| + h := suiteApp(t, "") |
| + unknown := call(h, "GET", "/no-such-path", "", nil) |
| + for _, target := range []string{suite.RouteS1, suite.RouteS3 + "/1?revision=1"} { |
| + rec := call(h, "GET", target, suiteToken, nil) |
| + if rec.Code != unknown.Code || rec.Body.String() != unknown.Body.String() { |
| + t.Errorf("GET %s: %d %q, want what an unknown path gets (%d %q)", target, rec.Code, rec.Body.String(), unknown.Code, unknown.Body.String()) |
| + } |
| + } |
| + if rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner)); rec.Code != http.StatusForbidden { |
| + t.Errorf("POST %s: %d, want the CSRF check's 403 (no exemption without consumers)", suite.RouteS2, rec.Code) |
| + } |
| +} |
| + |
| +// End to end through the whole app: a card made through the form appears |
| +// in the feed, its text is served at its revision, and its admitted owner |
| +// may see it. This is the wiring — the producer built over the app's own |
| +// database and its own admission predicate. |
| +func TestSuiteServesACardMadeThroughTheApp(t *testing.T) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + h, err := fichas.AppForTest(d, suiteConfig(t, suiteConsumers()), logger, TestOwner) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := post(t, h, "/cards", url.Values{"f_name": {"Cnoc Teoranta"}, "f_email": {"orders@cnoc.example"}}); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("creating a card: %d", rec.Code) |
| + } |
| + |
| + rec := call(h, "GET", suite.RouteS1, suiteToken, nil) |
| + feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()) |
| + if err != nil || len(feed.Rows) != 1 || feed.Rows[0].Revision != 1 || feed.Rows[0].Gone { |
| + t.Fatalf("S1: %+v, %v", feed, err) |
| + } |
| + item := feed.Rows[0].ItemID |
| + if _, err := strconv.ParseInt(item, 10, 64); err != nil { |
| + t.Errorf("item_id %q is not a card id", item) |
| + } |
| + |
| + rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision=1", suiteToken, nil) |
| + if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" || |
| + !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") { |
| + t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type")) |
| + } |
| + |
| + pairs := []suite.ItemRevision{{ItemID: item, Revision: 1}} |
| + rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...)) |
| + if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE { |
| + t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0]) |
| + } |
| + rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, "bo@example.com", pairs...)) |
| + if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.NOT_VISIBLE { |
| + t.Errorf("S2 for an address not admitted: %s", got[0]) |
| + } |
| +} |