oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "bytes"
5 "context"
6 crand "crypto/rand"
7 "encoding/binary"
8 "errors"
9 "io/fs"
10 "net/http"
11 "net/http/httptest"
12 "net/url"
13 "os"
14 "path/filepath"
15 "sort"
16 "strconv"
17 "strings"
18 "testing"
19 "testing/fstest"
20 "time"
21
22 "amadan.net/oficina/home/connect"
23 connectlinks "amadan.net/oficina/home/connect/linkstore"
24 "amadan.net/oficina/home/dashboard"
25 "amadan.net/oficina/home/handoff"
26 "amadan.net/oficina/home/roster"
27 "amadan.net/oficina/suite"
28 "amadan.net/oficina/suite/conformance"
29 "amadan.net/oficina/suite/server"
30 "amadan.net/rastrillo/rastrillo"
31 "amadan.net/rastrillo/rastrillo/db"
32 "amadan.net/rastrillo/rastrillo/migrate"
33 "amadan.net/rastrillo/rastrillo/sessions"
34 "github.com/carlosframework/docs/internal/docs/linkstore"
35 "gorm.io/gorm"
36)
37
38// suiteVector is a case's document text as a real Yjs update
39// (fixtures/generate-suite.mjs).
40func suiteVector(t *testing.T, id string) []byte {
41 t.Helper()
42 b, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "vectors", "suite", id+".update.bin"))
43 if err != nil {
44 t.Fatalf("suite vector %q: %v (run fixtures/generate-suite.mjs)", id, err)
45 }
46 return b
47}
48
49// setRevision puts a document at the fixture's revision, with the case's
50// prior revision before it in its history: both are announced, as two bumps
51// would be. The fixture names its revisions and real bumps are random
52// (newRevision), so the world is seeded at the fixture's numbers directly;
53// the producer reads documents.revision and suite_feed and does not care how
54// they got there. prior being in the log is what makes the harness's
55// prior_revision STALE (Docs decides STALE from its log), and the case's
56// unknown_revision never being announced is what makes it UNKNOWN. Suite
57// revision 11 (91affa1) names prior_revision in the fixture rather than
58// letting the harness compute "one behind"; it is revision - 1 in every case
59// today, and is read from the fixture here all the same.
60func setRevision(t *testing.T, s *Store, docID, prior, revision int64) {
61 t.Helper()
62 err := s.db.Transaction(func(tx *gorm.DB) error {
63 for _, r := range []int64{prior, revision} {
64 if err := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", r).Error; err != nil {
65 return err
66 }
67 if err := announce(tx, docID, r, false); err != nil {
68 return err
69 }
70 }
71 return nil
72 })
73 if err != nil {
74 t.Fatal(err)
75 }
76}
77
78// revisionOf is a document's current revision.
79func revisionOf(t *testing.T, s *Store, docID int64) int64 {
80 t.Helper()
81 var d Document
82 if err := s.db.First(&d, docID).Error; err != nil {
83 t.Fatal(err)
84 }
85 return d.Revision
86}
87
88// custodyParty is somebody in the custody fixture's world: the person id and
89// the address their grants key on.
90type custodyParty struct {
91 id int64
92 address string
93}
94
95// seedCustody builds the custody fixture's world in a Docs store, through
96// Docs' own store paths: each case's rung, its owner (the asker or the other
97// party), a grant to the asker or to a guest, a published link, a deletion,
98// and the case's revisions (setRevision). The fixture's ids are not
99// sqids; each document's sqid is set to the fixture id straight after it is
100// created (the column is a plain unique TEXT), so the producer under test is
101// the real one with no id-mapping in between. Documents are untitled, so S3's
102// body is the text alone and equals the fixture's s3_body exactly.
103//
104// MUTATION-TESTED 2026-11-02, each reverted: the "other" owner arm renamed
105// so the switch no longer knows it → both conformance tests fatal on
106// "custody case doc-team: owner "other" is not one this seeding knows";
107// setRevision seeding revision + 1000 in place of the fixture's
108// prior_revision → both conformance tests "at a prior revision the log
109// holds: got UNKNOWN, want STALE" for the four cases the asker may open.
110// (A first try seeded revision - 2 and went red on the column's CHECK, not
111// on the rule, so it proved nothing and was redone.)
112func seedCustody(t *testing.T, s *Store, asker, other custodyParty) {
113 t.Helper()
114 ctx := context.Background()
115 f, err := suite.LoadCustodyFixture()
116 if err != nil {
117 t.Fatal(err)
118 }
119 for _, c := range f.Cases {
120 // "asker" and "other" are the only owners a binding case names.
121 // Revision 11 briefly added "stranger" (doc-owner-left: an owner
122 // who has lost team standing), withdrawn at 91affa1 until Paul rules
123 // (suite §14); Docs' Rule keeps gate 5's reading meanwhile. A case
124 // naming any other owner is refused here rather than seeded as
125 // owned by "other", which would pass it for the wrong reason.
126 var owner custodyParty
127 switch c.Owner {
128 case "asker":
129 owner = asker
130 case "other":
131 owner = other
132 default:
133 t.Fatalf("custody case %s: owner %q is not one this seeding knows (asker, other)", c.ItemID, c.Owner)
134 }
135 vis := VisibilityPrivate
136 if c.Rung == suite.RungTeam || c.ItemID == "doc-was-team" {
137 vis = VisibilityTeam
138 }
139 doc, err := s.createDocument(ctx, owner.id, "", "", vis)
140 if err != nil {
141 t.Fatal(err)
142 }
143 if err := s.db.Model(&Document{}).Where("id = ?", doc.ID).UpdateColumn("sqid", c.ItemID).Error; err != nil {
144 t.Fatal(err)
145 }
146 doc.Sqid = c.ItemID
147 // The deleted case has no text in the fixture (its S3 is a 404), so
148 // it gets any real content; every other case gets its own s3_body.
149 var update []byte
150 if c.S3Body == "" {
151 update = ReadFragmentFixture(t, "hello")
152 } else {
153 update = suiteVector(t, c.ItemID)
154 }
155 if _, err := s.ApplyUpdate(ctx, doc, localActor(owner.id, owner.address), update); err != nil {
156 t.Fatal(err)
157 }
158 if c.AskerGrant {
159 if err := s.db.Create(&Grant{DocID: doc.ID, Subject: subjectOf(asker.address), Role: RoleReader, CreatedBy: owner.id, CreatedAt: time.Now().UTC()}).Error; err != nil {
160 t.Fatal(err)
161 }
162 }
163 if c.Rung == suite.RungGranted && !c.AskerGrant {
164 if err := s.Grant(ctx, owner.id, c.ItemID, "guest@example.com", RoleReader); err != nil {
165 t.Fatal(err)
166 }
167 }
168 if c.ItemID == "doc-was-team" {
169 if err := s.SetVisibility(ctx, owner.id, c.ItemID, VisibilityPrivate); err != nil {
170 t.Fatal(err)
171 }
172 }
173 if c.Link == "read" {
174 if _, err := s.Publish(ctx, owner.id, c.ItemID); err != nil {
175 t.Fatal(err)
176 }
177 }
178 if c.Rung == suite.RungDeleted {
179 // Deleted through the real path; its last revision is a
180 // random one, which nothing asks about: a deleted item is
181 // NOT_VISIBLE and refused at every revision.
182 setRevision(t, s, doc.ID, c.PriorRevision, c.Revision)
183 if err := s.deleteDocument(ctx, doc.ID); err != nil {
184 t.Fatal(err)
185 }
186 } else {
187 setRevision(t, s, doc.ID, c.PriorRevision, c.Revision)
188 }
189 }
190}
191
192// loneCustodyApp is a lone-shape Docs with the fixture's asker as a member
193// address and the stranger as an address that is neither a member nor holds a
194// grant (conformance.RunAs with SubjectAddress keeps "pers_ana"/"pers_bo" as
195// the values and makes them addresses).
196func loneCustodyApp(t *testing.T) *App {
197 t.Helper()
198 app, err := NewForTestWith(t, Config{AllowedAddresses: "pers_ana,owner@example.com"})
199 if err != nil {
200 t.Fatal(err)
201 }
202 ctx := context.Background()
203 ana, err := app.store.EnsurePerson(ctx, "pers_ana")
204 if err != nil {
205 t.Fatal(err)
206 }
207 owner, err := app.store.EnsurePerson(ctx, "owner@example.com")
208 if err != nil {
209 t.Fatal(err)
210 }
211 seedCustody(t, app.store, custodyParty{ana, "pers_ana"}, custodyParty{owner, "owner@example.com"})
212 return app
213}
214
215// Gate 3 in lone shape: the suite's own harness against the producer New
216// built, over a store holding the custody fixture's world. Askers are
217// addresses here, and the harness also asks under person_ref, which must be
218// UNKNOWN for every pair.
219//
220// Run through conformance.RunProducer (suite revision 11, 91affa1): the
221// harness mounts the producer behind server.Handler with a token it mints,
222// requires the 401 without it, and audits Cache-Control: no-store and Vary:
223// Authorization on every response. It replaces conformance.RunAs over
224// server.Routes, the unauthenticated routes the module has deprecated. It
225// covers Handler and the producer only; what Docs mounts in front of
226// Handler is TestSuiteS1ResetIsNotAFailure's and
227// TestSuiteRoutesAreMountedExactlyOutsideCSRF's.
228//
229// MUTATION-TESTED 2026-11-02, reverted: Feed answering an unparseable
230// cursor with a plain error (revision 10's 503) → "S1 with a cursor the log
231// never issued: 503, want 409 {"code":"CURSOR_RESET"}" here and in team
232// mode.
233//
234// MUTATION-TESTED 2026-11-01, each reverted: the link table read as a grant
235// in permissionScope (an EXISTS on links) → doc-link, doc-link-added-late
236// VISIBLE; teamReader returning true → the stranger VISIBLE on doc-team;
237// Rule without its "not readable is NOT_VISIBLE" branch, so the revision
238// decides → doc-guest, doc-link UNKNOWN; Content without both revision
239// checks → S3 200 at revision-1 and +1; the wrong-kind branch answering
240// NOT_VISIBLE → red; Feed's tip returning a fresh cursor → "no tip after
241// 100 pages"; deleteDocument announcing gone=false → "last row is not
242// gone". (A first try at the revision mutation — a STALE case inserted
243// ahead of the person check — stayed green, because Rule only knows a
244// revision for a readable document; the mutation was the wrong shape, not
245// the test blind, and was replaced by the one above.)
246func TestSuiteConformanceLoneShape(t *testing.T) {
247 app := loneCustodyApp(t)
248 conformance.RunProducer(t, app.suite, suite.SubjectAddress)
249}
250
251// renamedAskers maps the fixture's person refs onto roster-shaped subjects
252// (a roster person ref is "pr_" and 26 characters, and the fixture's
253// "pers_ana" is not one). Test-only, and the only thing between the harness
254// and the real producer: ids, revisions and content pass through untouched.
255type renamedAskers struct {
256 server.Producer
257 names map[string]string
258}
259
260func (r renamedAskers) Rule(ctx context.Context, a suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
261 if v, ok := r.names[a.Value]; ok && a.Kind == suite.SubjectPersonRef {
262 a.Value = v
263 }
264 return r.Producer.Rule(ctx, a, pairs)
265}
266
267var (
268 anaSubject = "pr_" + strings.Repeat("n", 26)
269 strangerSubject = "pr_" + strings.Repeat("s", 26)
270)
271
272// teamCustodyStore is the same world in team mode: ana is a local person
273// linked to anaSubject, which is on the roster; strangerSubject is not.
274// connect's Resolve is stubbed to that one link (the Bridge is Home's code,
275// tested there); the roster, the principals and the read predicate are real.
276func teamCustodyStore(t *testing.T, members ...string) (*App, *suiteProducer, *teamTestClock, custodyParty, custodyParty) {
277 t.Helper()
278 app := newSampleDocumentsInternalTestApp(t, "0")
279 s := app.store
280 ctx := context.Background()
281 anaID, err := s.EnsurePerson(ctx, "ana@example.com")
282 if err != nil {
283 t.Fatal(err)
284 }
285 ownerID, err := s.EnsurePerson(ctx, "owner@example.com")
286 if err != nil {
287 t.Fatal(err)
288 }
289 ana, other := custodyParty{anaID, "ana@example.com"}, custodyParty{ownerID, "owner@example.com"}
290 seedCustody(t, s, ana, other)
291 _, clock := testTeamRosterOf(t, s, app, append([]string{anaSubject}, members...)...)
292 subjects := subjectsFunc(func(_ context.Context, subject string) (connect.Person, error) {
293 if subject == anaSubject {
294 return connect.Person{ID: anaID, Label: "ana@example.com"}, nil
295 }
296 return connect.Person{}, connectlinks.ErrRefused
297 })
298 return app, &suiteProducer{store: s, subjects: subjects}, clock, ana, other
299}
300
301// Gate 3 in team mode, person_ref askers.
302//
303// MUTATION-TESTED 2026-11-01, each reverted: teamReader ignoring standing
304// (true in team mode) → the stranger VISIBLE on doc-team; askerActor
305// accepting address in team mode → doc-deleted NOT_VISIBLE under the wrong
306// kind; homeActor turning a refused subject into an error → every
307// stranger answer UNKNOWN (a 503 for the whole call).
308func TestSuiteConformanceTeamMode(t *testing.T) {
309 _, p, _, _, _ := teamCustodyStore(t)
310 conformance.RunProducer(t, renamedAskers{Producer: p, names: map[string]string{"pers_ana": anaSubject, "pers_bo": strangerSubject}}, suite.SubjectPersonRef)
311}
312
313// The two halves of Paul's 2026-11-01 ruling, "New docs Team, old private":
314// a document made from now on is on the team rung, and migration 0011 leaves
315// every existing one private. The sample library is private too.
316//
317// MUTATION-TESTED 2026-11-01, each reverted: CreateDraft passing
318// VisibilityPrivate → "a new document"; 0011's DEFAULT 'team' → "an existing
319// document"; seed.go creating on the team rung → "sample".
320func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
321 app, err := NewForTest(t)
322 if err != nil {
323 t.Fatal(err)
324 }
325 rec := form(t, app, "alice@example.com", "/documents", "title=Plans")
326 if rec.Code != http.StatusSeeOther {
327 t.Fatalf("create: %d", rec.Code)
328 }
329 var doc Document
330 if err := app.store.db.Where("sqid = ?", strings.TrimPrefix(rec.Header().Get("Location"), "/d/")).First(&doc).Error; err != nil {
331 t.Fatal(err)
332 }
333 if doc.Visibility != VisibilityTeam || doc.Revision < 1 {
334 t.Errorf("a new document: %q at revision %d, want team at a positive revision", doc.Visibility, doc.Revision)
335 }
336
337 samples := newSampleDocumentsInternalTestApp(t, "1")
338 owner := samples.TestPerson(t, "new@example.com")
339 var teamSamples int64
340 samples.store.db.Model(&Document{}).Where("owner_id = ? AND visibility = ?", owner, VisibilityTeam).Count(&teamSamples)
341 var all int64
342 samples.store.db.Model(&Document{}).Where("owner_id = ?", owner).Count(&all)
343 if all == 0 || teamSamples != 0 {
344 t.Errorf("sample library: %d of %d on the team rung, want 0 of some", teamSamples, all)
345 }
346
347 // The migration, against a database that existed before it.
348 db, err := migrate.Memory()
349 if err != nil {
350 t.Fatal(err)
351 }
352 defer db.Close()
353 entries, err := fs.ReadDir(migrationFS, "migrations")
354 if err != nil {
355 t.Fatal(err)
356 }
357 var names []string
358 for _, e := range entries {
359 names = append(names, e.Name())
360 }
361 sort.Strings(names)
362 exec := func(name string) {
363 t.Helper()
364 b, err := fs.ReadFile(migrationFS, "migrations/"+name)
365 if err != nil {
366 t.Fatal(err)
367 }
368 if _, err := db.Exec(string(b)); err != nil {
369 t.Fatalf("%s: %v", name, err)
370 }
371 }
372 for _, n := range names {
373 if n < "0011" {
374 exec(n)
375 }
376 }
377 now := time.Now().UTC()
378 for _, row := range []struct {
379 id, owner int64
380 deleted bool
381 }{{1, 1, false}, {2, 1, true}, {3, 0, false}, {4, 1, false}} {
382 var del any
383 if row.deleted {
384 del = now
385 }
386 if _, err := db.Exec(`INSERT INTO documents (id, sqid, title, guid, client_id, created_at, updated_at, deleted_at, owner_id) VALUES (?, ?, 't', 'g', 1, ?, ?, ?, ?)`,
387 row.id, "s"+strconv.FormatInt(row.id, 10), now, now, del, row.owner); err != nil {
388 t.Fatal(err)
389 }
390 }
391 exec("0011_suite.sql")
392 var private, distinct, low int
393 db.QueryRow(`SELECT COUNT(*) FROM documents WHERE visibility = 'private'`).Scan(&private)
394 db.QueryRow(`SELECT COUNT(DISTINCT revision) FROM documents`).Scan(&distinct)
395 db.QueryRow(`SELECT COUNT(*) FROM documents WHERE revision < 1000000`).Scan(&low)
396 if private != 4 || distinct != 4 || low != 0 {
397 t.Errorf("an existing document: %d of 4 private, %d distinct revisions, %d small ones; want 4, 4 random, 0", private, distinct, low)
398 }
399 var unmatched int
400 db.QueryRow(`SELECT COUNT(*) FROM suite_feed f JOIN documents d ON d.id = f.document_id WHERE f.revision != d.revision`).Scan(&unmatched)
401 if unmatched != 0 {
402 t.Errorf("%d backfilled rows announce a revision their document does not have", unmatched)
403 }
404 rows, err := db.Query(`SELECT document_id, stamp FROM suite_feed ORDER BY id`)
405 if err != nil {
406 t.Fatal(err)
407 }
408 var fed []int64
409 stamps := map[int64]bool{}
410 for rows.Next() {
411 var id, stamp int64
412 rows.Scan(&id, &stamp)
413 fed = append(fed, id)
414 if stamp < 1 || stamps[stamp] {
415 t.Errorf("a backfilled stamp that is not a distinct positive nonce: %d", stamp)
416 }
417 stamps[stamp] = true
418 }
419 rows.Close()
420 if len(fed) != 2 || fed[0] != 1 || fed[1] != 4 {
421 t.Errorf("the migration announced %v, want the live documents [1 4] (not the deleted one, not the orphan)", fed)
422 }
423 if _, err := db.Exec(`UPDATE documents SET visibility = 'everyone' WHERE id = 1`); err == nil {
424 t.Error("a third visibility was accepted")
425 }
426}
427
428// form is a signed-in scriptless form POST.
429func form(t *testing.T, app *App, address, path, body string) *httptest.ResponseRecorder {
430 t.Helper()
431 r := app.TestRequest(t, address, http.MethodPost, path, strings.NewReader(body))
432 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
433 return serve(app, r)
434}
435
436// The team rung in lone shape: every configured member reads a team document
437// and none writes it or reaches its share page; a guest (admitted only by a
438// grant on another document) does not read it; private takes it away.
439//
440// MUTATION-TESTED 2026-11-01, each reverted: teamReader without the members
441// predicate (any address) → "the guest"; the team clause applied to
442// permissionWrite → "bob wrote"; the team clause dropped → "bob read" and
443// the list marker.
444func TestSuiteTeamRungLoneShape(t *testing.T) {
445 app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com,bob@example.com"})
446 if err != nil {
447 t.Fatal(err)
448 }
449 ctx := context.Background()
450 alice := app.TestPerson(t, "alice@example.com")
451 bob := app.TestPerson(t, "bob@example.com")
452 team, err := app.store.Create(ctx, alice, "Team plans")
453 if err != nil {
454 t.Fatal(err)
455 }
456 other := app.TestCreatePrivate(t, alice, "Guest brief")
457 if err := app.store.Grant(ctx, alice, other.Sqid, "guest@example.com", RoleReader); err != nil {
458 t.Fatal(err)
459 }
460 app.TestPerson(t, "guest@example.com")
461
462 if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusOK {
463 t.Errorf("bob read a team document: %d, want 200", rec.Code)
464 }
465 if app.store.CanWrite(ctx, localActor(bob, "bob@example.com"), team.ID) {
466 t.Error("bob wrote a team document he holds no writer grant on")
467 }
468 if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)); rec.Code != http.StatusNotFound {
469 t.Errorf("bob reached the share page: %d, want 404", rec.Code)
470 }
471 if rec := form(t, app, "bob@example.com", "/d/"+team.Sqid+"/share/team", "visibility=private"); rec.Code != http.StatusNotFound {
472 t.Errorf("bob moved the rung: %d, want 404", rec.Code)
473 }
474 if rec := serve(app, app.TestRequest(t, "guest@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusNotFound {
475 t.Errorf("the guest read a team document: %d, want 404", rec.Code)
476 }
477 list := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/", nil)).Body.String()
478 if !strings.Contains(list, "docs.list.team") || strings.Contains(list, "docs.list.shared") {
479 t.Error("bob's list does not mark the team document as the team's")
480 }
481
482 share := serve(app, app.TestRequest(t, "alice@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)).Body.String()
483 if !strings.Contains(share, `name="visibility" value="private"`) || !strings.Contains(share, "docs.share.team.body.team") {
484 t.Error("the share page does not offer to make a team document private")
485 }
486 if rec := form(t, app, "alice@example.com", "/d/"+team.Sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther {
487 t.Fatalf("make private: %d", rec.Code)
488 }
489 if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusNotFound {
490 t.Errorf("bob read it after it went private: %d, want 404", rec.Code)
491 }
492 share = serve(app, app.TestRequest(t, "alice@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)).Body.String()
493 if !strings.Contains(share, `name="visibility" value="team"`) || !strings.Contains(share, "docs.share.team.body.private") {
494 t.Error("the share page does not offer to share a private document with the team")
495 }
496 if rec := form(t, app, "alice@example.com", "/d/"+team.Sqid+"/share/team", "visibility=everyone"); rec.Code != http.StatusBadRequest {
497 t.Errorf("an unknown visibility: %d, want 400", rec.Code)
498 }
499
500}
501
502// The team rung in team mode follows roster standing: a Member who does not
503// own a team document reads it, a NotMember does not, and Unknown is
504// retryable rather than a definite no.
505//
506// MUTATION-TESTED 2026-11-01, each reverted: teamReader returning true in
507// team mode → NotMember and Unknown both read the document; the team clause
508// dropped → "a member could not read"; the team clause on writes → "a
509// member may write".
510func TestSuiteTeamRungTeamMode(t *testing.T) {
511 app := newSampleDocumentsInternalTestApp(t, "0")
512 s := app.store
513 ctx := context.Background()
514 owner, _ := s.EnsurePerson(ctx, "owner@example.com")
515 reader, _ := s.EnsurePerson(ctx, "reader@example.com")
516 team, err := s.Create(ctx, owner, "Team")
517 if err != nil {
518 t.Fatal(err)
519 }
520 private, err := s.createDocument(ctx, owner, "Private", "", VisibilityPrivate)
521 if err != nil {
522 t.Fatal(err)
523 }
524 subject := "pr_" + strings.Repeat("r", 26)
525 rt, _ := testTeamRosterOf(t, s, app, subject)
526 actor := localActor(reader, "reader@example.com")
527
528 member := context.WithValue(ctx, accessContextKey{}, rt.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject}))
529 if _, err := s.GetFor(member, actor, team.Sqid); err != nil {
530 t.Errorf("a member could not read a team document: %v", err)
531 }
532 if _, err := s.GetFor(member, actor, private.Sqid); !errors.Is(err, gorm.ErrRecordNotFound) {
533 t.Errorf("a member read a private document: %v", err)
534 }
535 if s.CanWrite(member, actor, team.ID) {
536 t.Error("a member may write a team document they hold no writer grant on")
537 }
538 for state, want := range map[roster.State]error{roster.NotMember: gorm.ErrRecordNotFound, roster.Unknown: errTeamUnavailable} {
539 c := context.WithValue(ctx, accessContextKey{}, &requestAccess{runtime: rt, actor: actor, Access: standing(state)})
540 if _, err := s.GetFor(c, actor, team.Sqid); !errors.Is(err, want) {
541 t.Errorf("standing %v: %v, want %v", state, err, want)
542 }
543 }
544}
545
546// S1 as Docs serves it: pages in id order, a cursor "<id>.<stamp>", the tip
547// returning the cursor given with no rows, any cursor Docs did not issue an
548// error, a row per bump (update, rename, visibility change, deletion) at a
549// fresh positive revision, nothing for a grant or an unchanged rung, gone
550// only on deletion.
551//
552// MUTATION-TESTED 2026-11-01, each reverted: Rename without bumpRevision,
553// ApplyUpdate without it, SetVisibility without it, and creation without
554// its announce → each a missing row in the feed comparison; SetVisibility
555// bumping when nothing changed → an extra row; deleteDocument announcing
556// gone=false → "(gone)"; Feed returning "" at an empty tip → "empty tip";
557// Feed ignoring the cursor → "the cursor came back unchanged with rows";
558// Feed not checking the stamp → cursor "2.1" answered a page.
559//
560// MUTATION-TESTED 2026-11-02 (suite revision 11, the cursor reset), each
561// reverted: Feed answering a stamp mismatch or a missing row with a plain
562// error (revision 10's 503) → "2.1", "999.<stamp>" and the conformance
563// fixture's never-issued cursor "want server.ErrCursorReset"; Feed
564// answering an unparseable cursor with a plain error → "not-a-cursor", "-1"
565// and the four respellings, same message.
566func TestSuiteFeed(t *testing.T) {
567 app, err := NewForTest(t)
568 if err != nil {
569 t.Fatal(err)
570 }
571 ctx := context.Background()
572 p := app.suite
573 empty, err := p.Feed(ctx, "", 10)
574 if err != nil || empty.Cursor != "0" || len(empty.Rows) != 0 {
575 t.Fatalf("empty tip: %+v %v", empty, err)
576 }
577 if again, _ := p.Feed(ctx, empty.Cursor, 10); again.Cursor != "0" || len(again.Rows) != 0 {
578 t.Errorf("empty tip, asked again: %+v", again)
579 }
580
581 alice := app.TestPerson(t, "alice@example.com")
582 actor := app.TestActorForPerson(t, alice)
583 doc, _ := app.store.Create(ctx, alice, "One")
584 two, _ := app.store.Create(ctx, alice, "Two")
585 revs := []int64{revisionOf(t, app.store, doc.ID)}
586 if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil {
587 t.Fatal(err)
588 }
589 revs = append(revs, revisionOf(t, app.store, doc.ID))
590 if err := app.store.Rename(ctx, actor, doc, "One, renamed"); err != nil {
591 t.Fatal(err)
592 }
593 revs = append(revs, revisionOf(t, app.store, doc.ID))
594 if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil {
595 t.Fatal(err)
596 }
597 revs = append(revs, revisionOf(t, app.store, doc.ID))
598 if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil {
599 t.Fatal(err)
600 }
601 if err := app.store.Grant(ctx, alice, doc.Sqid, "bob@example.com", RoleReader); err != nil {
602 t.Fatal(err)
603 }
604 twoBefore := revisionOf(t, app.store, two.ID)
605 app.TestSoftDelete(t, two.Sqid)
606 twoGone := revisionOf(t, app.store, two.ID)
607
608 // Every revision is new: no two the same, none below 1 (newRevision).
609 seen := map[int64]bool{}
610 for _, r := range append(revs, twoBefore, twoGone) {
611 if r < 1 || seen[r] {
612 t.Errorf("revisions not fresh and positive: %v, %d, %d", revs, twoBefore, twoGone)
613 }
614 seen[r] = true
615 }
616
617 type step struct {
618 sqid string
619 rev int64
620 gone bool
621 }
622 want := []step{{doc.Sqid, revs[0], false}, {two.Sqid, twoBefore, false}, {doc.Sqid, revs[1], false}, {doc.Sqid, revs[2], false}, {doc.Sqid, revs[3], false}, {two.Sqid, twoGone, true}}
623 var got []step
624 var cursors []string
625 cursor := ""
626 for page := 0; page < 10; page++ {
627 f, err := p.Feed(ctx, cursor, 2)
628 if err != nil {
629 t.Fatal(err)
630 }
631 if f.Cursor == cursor {
632 if len(f.Rows) != 0 {
633 t.Fatal("the cursor came back unchanged with rows")
634 }
635 break
636 }
637 if len(f.Rows) > 2 {
638 t.Fatalf("page two: %d rows, limit 2", len(f.Rows))
639 }
640 for _, r := range f.Rows {
641 if r.TouchedAt.IsZero() {
642 t.Error("a row without a time")
643 }
644 got = append(got, step{r.ItemID, r.Revision, r.Gone})
645 }
646 cursor = f.Cursor
647 cursors = append(cursors, cursor)
648 }
649 if len(got) != len(want) {
650 t.Fatalf("feed %+v, want %+v (rename, unchanged rung, grant)", got, want)
651 }
652 for k := range want {
653 if got[k] != want[k] {
654 t.Errorf("row %d: %+v, want %+v (gone)", k, got[k], want[k])
655 }
656 }
657 if tip, _ := p.Feed(ctx, cursor, 2); tip.Cursor != cursor || len(tip.Rows) != 0 {
658 t.Errorf("tip: %+v, want cursor %q and no rows", tip, cursor)
659 }
660 // A cursor Docs did not issue is the cursor reset (suite revision 11
661 // §6.6; the suite package's 409 CURSOR_RESET), never a page and never
662 // another error: not a bare id, not a stamp that does not match the
663 // row, not another spelling of a real one, not a row past the log's end.
664 id, stamp, _ := strings.Cut(cursors[0], ".")
665 for _, bad := range []string{"not-a-cursor", id, id + ".1", "0" + cursors[0], id + "." + stamp + "0", "-1", "+" + cursors[0], "999." + stamp, suite.NeverIssuedCursor} {
666 if f, err := p.Feed(ctx, bad, 100); !errors.Is(err, server.ErrCursorReset) {
667 t.Errorf("cursor %q: %d rows, error %v; want server.ErrCursorReset", bad, len(f.Rows), err)
668 }
669 }
670 if f, err := p.Feed(ctx, cursors[0], 100); err != nil || len(f.Rows) != len(want)-2 {
671 t.Errorf("a cursor Docs issued: %d rows, %v", len(f.Rows), err)
672 }
673}
674
675// Every S2 branch the brief and suite §4.3 name, in lone shape: wrong kind,
676// an address the front door refuses, an unknown and a deleted id, a link-only
677// document, ownership at, behind and ahead of the revision and below 1, a
678// member who has never signed in (team rung yes, private no), and a grantee
679// who has never signed in.
680//
681// MUTATION-TESTED 2026-11-01, each reverted: askerActor skipping the front
682// door (no allows check) → "a refused address that owns a document" (the
683// plain refused address stayed green under it: with no ownership and no
684// grant nothing opens anyway, so that case alone could not see the gate,
685// and the owning case was added); revision 0 answered STALE → "the owner,
686// pair 1"; permissionScope keeping the person-row guard for reads → both
687// "never signed in" cases.
688func TestSuiteRuleLoneShape(t *testing.T) {
689 app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com,newcomer@example.com"})
690 if err != nil {
691 t.Fatal(err)
692 }
693 ctx := context.Background()
694 alice := app.TestPerson(t, "alice@example.com")
695 own, _ := app.store.Create(ctx, alice, "Team")
696 private := app.TestCreatePrivate(t, alice, "Private")
697 linked := app.TestCreatePrivate(t, alice, "Linked")
698 granted := app.TestCreatePrivate(t, alice, "Granted")
699 gone := app.TestCreatePrivate(t, alice, "Gone")
700 if _, err := app.store.Publish(ctx, alice, linked.Sqid); err != nil {
701 t.Fatal(err)
702 }
703 if err := app.store.Grant(ctx, alice, granted.Sqid, "invitee@example.com", RoleReader); err != nil {
704 t.Fatal(err)
705 }
706 app.TestSoftDelete(t, gone.Sqid)
707
708 ask := func(kind suite.SubjectKind, who string, pairs ...suite.ItemRevision) []suite.Authorization {
709 t.Helper()
710 got, err := app.suite.Rule(ctx, suite.Subject{Kind: kind, Value: who}, pairs)
711 if err != nil || len(got) != len(pairs) {
712 t.Fatalf("Rule: %v %v", got, err)
713 }
714 return got
715 }
716 pr := func(d *Document, rev int64) suite.ItemRevision {
717 return suite.ItemRevision{ItemID: d.Sqid, Revision: rev}
718 }
719 expect := func(what string, got []suite.Authorization, want ...suite.Authorization) {
720 t.Helper()
721 for i := range want {
722 if got[i] != want[i] {
723 t.Errorf("%s, pair %d: %s, want %s", what, i, got[i], want[i])
724 }
725 }
726 }
727
728 rev := func(d *Document) int64 { return revisionOf(t, app.store, d.ID) }
729 first := rev(own)
730 expect("wrong kind", ask(suite.SubjectPersonRef, "alice@example.com", pr(own, first), pr(private, rev(private))), suite.UNKNOWN, suite.UNKNOWN)
731 expect("the owner", ask(suite.SubjectAddress, "Alice@Example.com",
732 pr(own, first), pr(own, 0), pr(own, first+1), pr(private, rev(private)), suite.ItemRevision{ItemID: "no-such-sqid", Revision: 1}, pr(gone, rev(gone))),
733 suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE)
734 if _, err := app.store.ApplyUpdate(ctx, own, app.TestActorForPerson(t, alice), ReadFragmentFixture(t, "hello")); err != nil {
735 t.Fatal(err)
736 }
737 now := rev(own)
738 expect("behind", ask(suite.SubjectAddress, "alice@example.com", pr(own, first), pr(own, now)), suite.STALE, suite.VISIBLE)
739 expect("a member who never signed in", ask(suite.SubjectAddress, "newcomer@example.com", pr(own, now), pr(private, rev(private)), pr(linked, rev(linked))),
740 suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE)
741 expect("a grantee who never signed in", ask(suite.SubjectAddress, "invitee@example.com", pr(granted, rev(granted)), pr(own, now)),
742 suite.VISIBLE, suite.NOT_VISIBLE)
743 expect("a refused address", ask(suite.SubjectAddress, "stranger@example.com", pr(own, now), pr(linked, rev(linked))),
744 suite.NOT_VISIBLE, suite.NOT_VISIBLE)
745 // Somebody taken off the allowlist who still owns a document: the front
746 // door refuses them on every request (requireAdmission), so S2 must too,
747 // although ownership alone would otherwise open it.
748 former := app.TestPerson(t, "former@example.com")
749 theirs := app.TestCreatePrivate(t, former, "Theirs")
750 expect("a refused address that owns a document", ask(suite.SubjectAddress, "former@example.com", pr(theirs, rev(theirs))), suite.NOT_VISIBLE)
751 var n int64
752 app.store.db.Model(&Person{}).Where("email IN ?", []string{"newcomer@example.com", "invitee@example.com", "stranger@example.com"}).Count(&n)
753 if n != 0 {
754 t.Errorf("S2 created %d person rows", n)
755 }
756}
757
758// S2 in team mode: the person_ref kind only; a subject with no Docs principal
759// who is a Member reads the team rung by standing; Unknown standing withholds
760// loudly what only membership would open, and still answers a grant.
761//
762// MUTATION-TESTED 2026-11-01, reverted: homeActor returning a refused
763// subject as an error → Rule fails for "an unlinked member". (The Unknown
764// branch is held by TestSuiteRuleTeamModeUnknownStanding.)
765func TestSuiteRuleTeamMode(t *testing.T) {
766 newcomer := "pr_" + strings.Repeat("w", 26)
767 _, p, _, ana, _ := teamCustodyStore(t, newcomer)
768 ctx := context.Background()
769 ask := func(who suite.Subject, pairs ...suite.ItemRevision) []suite.Authorization {
770 t.Helper()
771 got, err := p.Rule(ctx, who, pairs)
772 if err != nil || len(got) != len(pairs) {
773 t.Fatalf("Rule: %v %v", got, err)
774 }
775 return got
776 }
777 team := suite.ItemRevision{ItemID: "doc-team", Revision: 7}
778 priv := suite.ItemRevision{ItemID: "doc-private", Revision: 4}
779 if got := ask(suite.Subject{Kind: suite.SubjectPersonRef, Value: newcomer}, team, priv); got[0] != suite.VISIBLE || got[1] != suite.NOT_VISIBLE {
780 t.Errorf("an unlinked member: %v, want [VISIBLE NOT_VISIBLE]", got)
781 }
782 if got := ask(suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, team, priv); got[0] != suite.VISIBLE || got[1] != suite.VISIBLE {
783 t.Errorf("a linked member: %v, want [VISIBLE VISIBLE]", got)
784 }
785 if got := ask(suite.Subject{Kind: suite.SubjectAddress, Value: ana.address}, team, priv); got[0] != suite.UNKNOWN || got[1] != suite.UNKNOWN {
786 t.Errorf("an address in team mode: %v, want UNKNOWN", got)
787 }
788}
789
790// Unknown standing, from a roster lease that has run out with the directory
791// unreachable: what only membership would open is UNKNOWN, a grant still
792// answers, and a deleted document is still NOT_VISIBLE.
793//
794// MUTATION-TESTED 2026-11-01, reverted: the uncertain branch removed →
795// doc-team and doc-private NOT_VISIBLE.
796func TestSuiteRuleTeamModeUnknownStanding(t *testing.T) {
797 _, p, clock, _, _ := teamCustodyStore(t)
798 ctx := context.Background()
799 team := suite.ItemRevision{ItemID: "doc-team", Revision: 7}
800 priv := suite.ItemRevision{ItemID: "doc-private", Revision: 4}
801 grant := suite.ItemRevision{ItemID: "doc-granted", Revision: 9}
802 gone := suite.ItemRevision{ItemID: "doc-deleted", Revision: 6}
803 got, err := p.Rule(ctx, suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{team, priv, grant, gone})
804 if err != nil || got[0] != suite.VISIBLE || got[1] != suite.VISIBLE || got[2] != suite.VISIBLE {
805 t.Fatalf("member standing: %v %v", got, err)
806 }
807 clock.step(61 * time.Second)
808 got, err = p.Rule(ctx, suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{team, priv, grant, gone})
809 if err != nil {
810 t.Fatal(err)
811 }
812 want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.NOT_VISIBLE}
813 for i := range want {
814 if got[i] != want[i] {
815 t.Errorf("unknown standing, pair %d: %s, want %s", i, got[i], want[i])
816 }
817 }
818}
819
820// S3: the current revision only, the title on the first line, an untitled
821// document as its text alone, a deleted one refused.
822//
823// MUTATION-TESTED 2026-11-01, each reverted: Content without the second
824// revision read → "a change during the read"; without both revision checks
825// → "an old revision" (the first check alone is shadowed by the second, so
826// it was only ever red together with it); without the title line →
827// "titled".
828func TestSuiteContent(t *testing.T) {
829 app, err := NewForTest(t)
830 if err != nil {
831 t.Fatal(err)
832 }
833 ctx := context.Background()
834 alice := app.TestPerson(t, "alice@example.com")
835 actor := app.TestActorForPerson(t, alice)
836 doc, _ := app.store.Create(ctx, alice, "Minutes")
837 created := revisionOf(t, app.store, doc.ID)
838 if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil {
839 t.Fatal(err)
840 }
841 current := revisionOf(t, app.store, doc.ID)
842 body, err := app.suite.Content(ctx, doc.Sqid, current)
843 if err != nil || string(body) != "Minutes\n\nhello world" {
844 t.Errorf("titled: %q %v", body, err)
845 }
846 if _, err := app.suite.Content(ctx, doc.Sqid, created); !errors.Is(err, suite.ErrNotAvailable) {
847 t.Errorf("an old revision: %v", err)
848 }
849 if _, err := app.suite.Content(ctx, doc.Sqid, current+1); !errors.Is(err, suite.ErrNotAvailable) {
850 t.Errorf("a future revision: %v", err)
851 }
852 untitled, _ := app.store.Create(ctx, alice, "")
853 if _, err := app.store.ApplyUpdate(ctx, untitled, actor, ReadFragmentFixture(t, "hello")); err != nil {
854 t.Fatal(err)
855 }
856 if body, err := app.suite.Content(ctx, untitled.Sqid, revisionOf(t, app.store, untitled.ID)); err != nil || string(body) != "hello world" {
857 t.Errorf("untitled: %q %v", body, err)
858 }
859 // A rename that lands while the text is being replayed: the body read
860 // is the old title's, so it must not go out labelled with the revision
861 // it was asked at.
862 app.suite.step = func(stage string) {
863 if stage != "replayed" {
864 return
865 }
866 app.suite.step = nil
867 if err := app.store.Rename(ctx, actor, doc, "Minutes, renamed"); err != nil {
868 t.Fatal(err)
869 }
870 }
871 if body, err := app.suite.Content(ctx, doc.Sqid, current); !errors.Is(err, suite.ErrNotAvailable) {
872 t.Errorf("a change during the read: %q %v, want not available", body, err)
873 }
874 renamed := revisionOf(t, app.store, doc.ID)
875 if body, err := app.suite.Content(ctx, doc.Sqid, renamed); err != nil || string(body) != "Minutes, renamed\n\nhello world" {
876 t.Errorf("after the rename: %q %v", body, err)
877 }
878 app.TestSoftDelete(t, doc.Sqid)
879 if _, err := app.suite.Content(ctx, doc.Sqid, revisionOf(t, app.store, doc.ID)); !errors.Is(err, suite.ErrNotAvailable) {
880 t.Errorf("deleted: %v", err)
881 }
882}
883
884const suiteTestToken = "a-test-token-for-memoria"
885
886func suiteConsumersJSON() string {
887 return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteTestToken) + `"}]}]`
888}
889
890func suiteRequest(method, path, token string, body []byte) *http.Request {
891 r := httptest.NewRequest(method, path, bytes.NewReader(body))
892 if token != "" {
893 r.Header.Set("Authorization", "Bearer "+token)
894 }
895 return r
896}
897
898// The suite routes are mounted exactly, outside the session and CSRF layers:
899// memoria's POST /suite/s2 carries only Authorization and is served, while a
900// POST anywhere else with the same headers is still refused by homeCSRF —
901// including another method on a suite path and a path beside them. Without a
902// token, 401; with no consumers configured, /suite/* answers exactly as an
903// unknown path does.
904//
905// MUTATION-TESTED 2026-11-01, each reverted: mounting the suite handler on
906// the prefix "/suite/" → POST /suite/s1, /suite/s2x and /suite/ escape
907// homeCSRF; mounting inside the router (after homeCSRF) → S2 with only
908// Authorization 403, bare and served; mountSuite without its nil check →
909// "http: nil handler" panic with no consumers; server.Routes mounted in
910// place of server.Handler → 200 with no token and routes with no
911// consumers.
912func TestSuiteRoutesAreMountedExactlyOutsideCSRF(t *testing.T) {
913 app, err := NewForTestWith(t, Config{SuiteConsumers: suiteConsumersJSON()})
914 if err != nil {
915 t.Fatal(err)
916 }
917 h := app.Handler()
918 s2 := []byte(`{"asker":{"kind":"address","value":"a@example.com"},"pairs":[]}`)
919 if rec := httptestServe(h, suiteRequest("POST", suite.RouteS2, suiteTestToken, s2)); rec.Code != http.StatusOK {
920 t.Errorf("S2 with only Authorization: %d, want 200", rec.Code)
921 }
922 if rec := httptestServe(h, suiteRequest("GET", suite.RouteS1, suiteTestToken, nil)); rec.Code != http.StatusOK {
923 t.Errorf("S1: %d", rec.Code)
924 }
925 for _, path := range []string{suite.RouteS1, "/suite/s2x", "/suite/", "/documents"} {
926 if rec := httptestServe(h, suiteRequest("POST", path, suiteTestToken, s2)); rec.Code != http.StatusForbidden {
927 t.Errorf("POST %s with only Authorization: %d, want homeCSRF's 403", path, rec.Code)
928 }
929 }
930 // And through rastrillo's production stack (locale, security headers,
931 // panic recovery), which cmd/docs serves: memoria meets that, not the
932 // bare mux.
933 served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app))
934 if err != nil {
935 t.Fatal(err)
936 }
937 if done != nil {
938 defer done()
939 }
940 if rec := httptestServe(served, suiteRequest("POST", suite.RouteS2, suiteTestToken, s2)); rec.Code != http.StatusOK {
941 t.Errorf("served S2 with only Authorization: %d, want 200", rec.Code)
942 }
943 if rec := httptestServe(served, suiteRequest("POST", "/documents", suiteTestToken, s2)); rec.Code != http.StatusForbidden {
944 t.Errorf("served POST /documents with only Authorization: %d, want 403", rec.Code)
945 }
946 for name, tok := range map[string]string{"no token": "", "a wrong token": "nope"} {
947 if rec := httptestServe(h, suiteRequest("GET", suite.RouteS1, tok, nil)); rec.Code != http.StatusUnauthorized {
948 t.Errorf("%s: %d, want 401", name, rec.Code)
949 }
950 }
951
952 bare, err := NewForTest(t)
953 if err != nil {
954 t.Fatal(err)
955 }
956 for _, method := range []string{"GET", "POST"} {
957 for _, path := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3 + "/x"} {
958 got := httptestServe(bare.Handler(), suiteRequest(method, path, suiteTestToken, s2))
959 unknown := httptestServe(bare.Handler(), suiteRequest(method, "/no-such-route", suiteTestToken, s2))
960 if got.Code != unknown.Code || got.Code == http.StatusOK || got.Code == http.StatusUnauthorized {
961 t.Errorf("no consumers, %s %s: %d, an unknown path answers %d", method, path, got.Code, unknown.Code)
962 }
963 }
964 }
965}
966
967// S1 over the wire as memoria meets it — the app's own mux and rastrillo's
968// production stack in front of it, as cmd/docs serves — for the two answers
969// suite revision 11 (§6.6, 91affa1) keeps apart. A cursor this log does not
970// recognise is the fixed 409 {"code":"CURSOR_RESET"}, the one way a
971// consumer is told to set aside what it holds from Docs and read from "".
972// A log that cannot be read is a 503, because it has lost nothing and a
973// reset would destroy the consumer's whole copy. Both carry Cache-Control:
974// no-store and Vary: Authorization through every layer Docs puts in front
975// of server.Handler (conformance.RunProducer drives Handler alone and cannot
976// see those layers, doctrine §6.5).
977//
978// MUTATION-TESTED 2026-11-02, each reverted: Feed answering a failed stamp
979// read with server.ErrCursorReset (a database failure read as a reset) →
980// "a log that cannot be read, from a cursor it issued: 409, want 503";
981// Feed answering a stamp mismatch with a plain error (revision 10) → "a
982// stamp this log never wrote: 503"; Feed answering an unparseable cursor
983// with a plain error → "a cursor that does not parse: 503"; mountSuite
984// wrapping Handler in a layer whose ResponseWriter sets Cache-Control:
985// private at WriteHeader → every "Cache-Control" line, on both layers. (A
986// first try set the header before calling Handler and stayed green:
987// Handler sets no-store over it, so that layer was harmless, not the test
988// blind.)
989func TestSuiteS1ResetIsNotAFailure(t *testing.T) {
990 app, err := NewForTestWith(t, Config{SuiteConsumers: suiteConsumersJSON()})
991 if err != nil {
992 t.Fatal(err)
993 }
994 ctx := context.Background()
995 alice := app.TestPerson(t, "alice@example.com")
996 if _, err := app.store.Create(ctx, alice, "One"); err != nil {
997 t.Fatal(err)
998 }
999 served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app))
1000 if err != nil {
1001 t.Fatal(err)
1002 }
1003 if done != nil {
1004 defer done()
1005 }
1006 layers := map[string]http.Handler{"the app's mux": app.Handler(), "rastrillo's production stack": served}
1007 s1 := func(h http.Handler, cursor string) *httptest.ResponseRecorder {
1008 return httptestServe(h, suiteRequest("GET", suite.RouteS1+"?cursor="+url.QueryEscape(cursor), suiteTestToken, nil))
1009 }
1010 headers := func(t *testing.T, what string, rec *httptest.ResponseRecorder) {
1011 t.Helper()
1012 if got := rec.Header().Get("Cache-Control"); got != "no-store" {
1013 t.Errorf("%s: Cache-Control %q, want no-store", what, got)
1014 }
1015 if got := rec.Header().Values("Vary"); len(got) != 1 || got[0] != "Authorization" {
1016 t.Errorf("%s: Vary %q, want Authorization", what, got)
1017 }
1018 }
1019 first := s1(app.Handler(), "")
1020 feed, err := suite.DecodeS1(first.Code, first.Body.Bytes())
1021 if err != nil || len(feed.Rows) == 0 {
1022 t.Fatalf("S1 from the beginning: %d %v", first.Code, err)
1023 }
1024 issued := feed.Cursor
1025 id, stamp, _ := strings.Cut(issued, ".")
1026 wrongStamp := "1"
1027 if stamp == wrongStamp {
1028 wrongStamp = "2"
1029 }
1030
1031 for name, h := range layers {
1032 t.Run(name, func(t *testing.T) {
1033 for what, cursor := range map[string]string{
1034 "a stamp this log never wrote": id + "." + wrongStamp,
1035 "a row this log does not hold": "999999." + stamp,
1036 "a cursor that does not parse": "not-a-cursor",
1037 "the fixture's never-issued one": suite.NeverIssuedCursor,
1038 } {
1039 rec := s1(h, cursor)
1040 if rec.Code != suite.CursorResetStatus || rec.Body.String() != suite.CursorResetBody {
1041 t.Errorf("%s: %d %q, want %d %s", what, rec.Code, rec.Body.String(), suite.CursorResetStatus, suite.CursorResetBody)
1042 }
1043 if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) {
1044 t.Errorf("%s: memoria's decoder reads %v, want suite.ErrCursorReset", what, err)
1045 }
1046 headers(t, what, rec)
1047 }
1048 if rec := s1(h, issued); rec.Code != http.StatusOK {
1049 t.Errorf("a cursor Docs issued: %d, want 200", rec.Code)
1050 } else {
1051 headers(t, "a cursor Docs issued", rec)
1052 }
1053 })
1054 }
1055
1056 // The log cannot be read. The table is moved aside, not dropped, so
1057 // nothing about the log's content changes: only whether it can be read.
1058 if err := app.store.db.Exec("ALTER TABLE suite_feed RENAME TO suite_feed_away").Error; err != nil {
1059 t.Fatal(err)
1060 }
1061 for name, h := range layers {
1062 t.Run(name+", log unreadable", func(t *testing.T) {
1063 for what, cursor := range map[string]string{
1064 "a log that cannot be read, from a cursor it issued": issued,
1065 "a log that cannot be read, from the beginning": "",
1066 } {
1067 rec := s1(h, cursor)
1068 if rec.Code != http.StatusServiceUnavailable {
1069 t.Errorf("%s: %d %q, want 503", what, rec.Code, rec.Body.String())
1070 }
1071 headers(t, what, rec)
1072 }
1073 })
1074 }
1075}
1076
1077func httptestServe(h http.Handler, r *http.Request) *httptest.ResponseRecorder {
1078 rec := httptest.NewRecorder()
1079 h.ServeHTTP(rec, r)
1080 return rec
1081}
1082
1083// A malformed consumer list refuses boot; an empty one boots with no routes.
1084//
1085// MUTATION-TESTED 2026-11-01: New ignoring ParseConsumers' error → red.
1086func TestSuiteConsumersMalformedRefusesBoot(t *testing.T) {
1087 for _, bad := range []string{"null", "[]", `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"plain"}]}]`, "{"} {
1088 if _, err := NewForTestWith(t, Config{SuiteConsumers: bad}); err == nil {
1089 t.Errorf("%q booted", bad)
1090 }
1091 }
1092}
1093
1094// Astra's restore sequences (oficina/docs feat/suite-producer, two rounds,
1095// 2026-11-01), with a real SQLite backup: a private draft is backed up; it
1096// is renamed to confidential text, and memoria holds that revision and the
1097// feed cursor after it; the backup is restored and the harmless draft is
1098// shared with the team. With revisions counted up from the restored value
1099// the share reissued the held revision, so S2 answered VISIBLE for a
1100// teammate against the confidential copy, and S1 answered the held cursor
1101// with no rows and the same cursor for ever. With revisions and nonces read
1102// from a clock, the same happened when the restore landed on a clock set
1103// back to the confidential edit's time ("clock set back"). Revisions and
1104// nonces are random now, so neither repeats.
1105//
1106// MUTATION-TESTED 2026-11-01, each reverted: sequential revisions
1107// (newRevision returning current + 1, creation at 1) → both subtests
1108// VISIBLE against the confidential copy; time-based revisions and nonces
1109// (newRevision and randomPositive reading suiteClock) → "clock set back"
1110// VISIBLE and its old cursor answered a page, while "real clock" stayed
1111// green, which is why both subtests exist; Feed without the nonce check →
1112// both subtests' old cursor answered a page. MUTATION-TESTED 2026-11-02
1113// (suite revision 11 §6.6), reverted: Feed answering the stamp mismatch with
1114// a plain error, revision 10's 503 → both subtests "want
1115// server.ErrCursorReset".
1116func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) {
1117 for _, tc := range []struct {
1118 name string
1119 // clock is suiteClock at each step, or nil for the real clock.
1120 clock map[string]time.Time
1121 }{
1122 {"real clock", nil},
1123 {"clock set back", map[string]time.Time{
1124 "backup": time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC),
1125 "confidential": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC),
1126 // The restore happens at 10:20 on a clock that reads 10:10.
1127 "restored": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC),
1128 }},
1129 } {
1130 t.Run(tc.name, func(t *testing.T) {
1131 at := func(step string) {
1132 if when, ok := tc.clock[step]; ok {
1133 suiteClock = func() time.Time { return when }
1134 }
1135 }
1136 t.Cleanup(func() { suiteClock = time.Now })
1137 at("backup")
1138 dir := t.TempDir()
1139 path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db")
1140 cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"}
1141 app, err := New(cfg)
1142 if err != nil {
1143 t.Fatal(err)
1144 }
1145 ctx := context.Background()
1146 alice := app.TestPerson(t, "alice@example.com")
1147 app.TestPerson(t, "bob@example.com")
1148 doc := app.TestCreatePrivate(t, alice, "Draft")
1149 if _, err := app.db.Writer().Exec("VACUUM INTO ?", backup); err != nil {
1150 t.Fatal(err)
1151 }
1152 at("confidential")
1153 if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Confidential: the acquisition"); err != nil {
1154 t.Fatal(err)
1155 }
1156 held := revisionOf(t, app.store, doc.ID)
1157 if body, err := app.suite.Content(ctx, doc.Sqid, held); err != nil || !strings.Contains(string(body), "Confidential") {
1158 t.Fatalf("memoria's copy: %q %v", body, err)
1159 }
1160 cursor := feedTip(t, app.suite)
1161 if err := app.Close(); err != nil {
1162 t.Fatal(err)
1163 }
1164
1165 restoreFile(t, backup, path)
1166 at("restored")
1167 restored, err := NewForTestWith(t, cfg)
1168 if err != nil {
1169 t.Fatal(err)
1170 }
1171 if err := restored.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityTeam); err != nil {
1172 t.Fatal(err)
1173 }
1174 got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: doc.Sqid, Revision: held}})
1175 if err != nil {
1176 t.Fatal(err)
1177 }
1178 if got[0] != suite.UNKNOWN {
1179 t.Errorf("S2 for a teammate at the confidential copy's revision after the restore: %s, want UNKNOWN (not in the restored log)", got[0])
1180 }
1181 if current := revisionOf(t, restored.store, doc.ID); current == held {
1182 t.Errorf("the restore reissued revision %d", held)
1183 }
1184 if f, err := restored.suite.Feed(ctx, cursor, 100); !errors.Is(err, server.ErrCursorReset) {
1185 t.Errorf("the cursor from before the restore (%q): cursor %q, %d rows, error %v; want server.ErrCursorReset (suite revision 11 §6.6)", cursor, f.Cursor, len(f.Rows), err)
1186 }
1187 })
1188 }
1189}
1190
1191// Astra's second-round sequence: a backup taken BEFORE migration 0011. A
1192// harmless document is granted to Bob and backed up; Bob is revoked and the
1193// document renamed to confidential text; the suite is deployed (0011 runs)
1194// and memoria holds the confidential revision; the pre-0011 backup is
1195// restored and the new build boots, running 0011 again over the harmless,
1196// Bob-granted document. A constant there gave it the same revision as the
1197// confidential copy, and S2 answered VISIBLE for Bob. No clock involved.
1198//
1199// MUTATION-TESTED 2026-11-01, reverted: 0011 without its random UPDATE (every
1200// existing document at revision 1, as before) → Bob VISIBLE.
1201func TestSuiteRestoreOfAPreSuiteBackupIssuesNewRevisions(t *testing.T) {
1202 dir := t.TempDir()
1203 path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db")
1204
1205 // A database at 0010: the boot schema with Docs' own set cut before 0011.
1206 old := fstest.MapFS{}
1207 entries, err := fs.ReadDir(migrationFS, "migrations")
1208 if err != nil {
1209 t.Fatal(err)
1210 }
1211 for _, e := range entries {
1212 if e.Name() < "0011" {
1213 b, _ := fs.ReadFile(migrationFS, "migrations/"+e.Name())
1214 old["migrations/"+e.Name()] = &fstest.MapFile{Data: b}
1215 }
1216 }
1217 pre := migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, migrate.MustFromFS(old, "docs"), linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(connectlinks.Migrations, connectlinks.SchemaNamespace))
1218 d, err := db.Open(path, nil)
1219 if err != nil {
1220 t.Fatal(err)
1221 }
1222 if _, err := migrate.Apply(context.Background(), d, pre); err != nil {
1223 t.Fatal(err)
1224 }
1225 now := time.Now().UTC()
1226 for _, q := range []struct {
1227 sql string
1228 args []any
1229 }{
1230 {`INSERT INTO people (id, email, created_at) VALUES (1, 'alice@example.com', ?), (2, 'bob@example.com', ?)`, []any{now, now}},
1231 {`INSERT INTO documents (id, sqid, title, guid, client_id, created_at, updated_at, owner_id) VALUES (1, 'harmless01', 'Harmless', 'g', 1, ?, ?, 1)`, []any{now, now}},
1232 {`INSERT INTO grants (doc_id, subject, role, created_by, created_at) VALUES (1, 'bob@example.com', 'reader', 1, ?)`, []any{now}},
1233 } {
1234 if _, err := d.Writer().Exec(q.sql, q.args...); err != nil {
1235 t.Fatal(err)
1236 }
1237 }
1238 if _, err := d.Writer().Exec("VACUUM INTO ?", backup); err != nil {
1239 t.Fatal(err)
1240 }
1241 if _, err := d.Writer().Exec(`DELETE FROM grants`); err != nil {
1242 t.Fatal(err)
1243 }
1244 if _, err := d.Writer().Exec(`UPDATE documents SET title = 'Confidential: the acquisition' WHERE id = 1`); err != nil {
1245 t.Fatal(err)
1246 }
1247 if err := d.Close(); err != nil {
1248 t.Fatal(err)
1249 }
1250
1251 cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"}
1252 deployed, err := New(cfg)
1253 if err != nil {
1254 t.Fatal(err)
1255 }
1256 ctx := context.Background()
1257 held := revisionOf(t, deployed.store, 1)
1258 if body, err := deployed.suite.Content(ctx, "harmless01", held); err != nil || !strings.Contains(string(body), "Confidential") {
1259 t.Fatalf("memoria's copy: %q %v", body, err)
1260 }
1261 if err := deployed.Close(); err != nil {
1262 t.Fatal(err)
1263 }
1264
1265 restoreFile(t, backup, path)
1266 restored, err := NewForTestWith(t, cfg)
1267 if err != nil {
1268 t.Fatal(err)
1269 }
1270 got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: "harmless01", Revision: held}})
1271 if err != nil {
1272 t.Fatal(err)
1273 }
1274 if got[0] != suite.UNKNOWN {
1275 t.Errorf("S2 for Bob at the confidential copy's revision after restoring a pre-0011 backup: %s, want UNKNOWN", got[0])
1276 }
1277}
1278
1279// feedTip follows the feed to its tip and returns the cursor there.
1280func feedTip(t *testing.T, p *suiteProducer) string {
1281 t.Helper()
1282 cursor := ""
1283 for {
1284 f, err := p.Feed(context.Background(), cursor, 100)
1285 if err != nil {
1286 t.Fatal(err)
1287 }
1288 if f.Cursor == cursor {
1289 return cursor
1290 }
1291 cursor = f.Cursor
1292 }
1293}
1294
1295// restoreFile puts a backup over a closed database file, its journal gone,
1296// as an operator restoring from a snapshot does.
1297func restoreFile(t *testing.T, backup, path string) {
1298 t.Helper()
1299 for _, f := range []string{path + "-wal", path + "-shm"} {
1300 os.Remove(f)
1301 }
1302 b, err := os.ReadFile(backup)
1303 if err != nil {
1304 t.Fatal(err)
1305 }
1306 if err := os.WriteFile(path, b, 0o600); err != nil {
1307 t.Fatal(err)
1308 }
1309}
1310
1311// A roster lease that runs out during an S2 call (Astra, 2026-11-01, and
1312// round 3 for the history read): before the reads, after the readable read,
1313// and after the log read. Each way what only membership opens — the team
1314// rung, and ownership in team mode — is UNKNOWN, and an independent address
1315// grant still answers, VISIBLE at its current revision and STALE at one
1316// from its log.
1317//
1318// MUTATION-TESTED 2026-11-01, each reverted: standing taken once in
1319// askerActor, before the reads (the old code) → "asked": doc-team and
1320// doc-private NOT_VISIBLE, and "read": both VISIBLE; the second read
1321// skipped when standing has lapsed → "read": both VISIBLE; the standing
1322// check moved back before the history read (round 2's order) → "history":
1323// both VISIBLE, Astra's probe exactly.
1324func TestSuiteRuleLeaseRunsOutMidCall(t *testing.T) {
1325 for _, stage := range []string{"asked", "read", "history"} {
1326 t.Run(stage, func(t *testing.T) {
1327 _, p, clock, _, _ := teamCustodyStore(t)
1328 p.step = func(at string) {
1329 if at == stage {
1330 clock.step(61 * time.Second)
1331 }
1332 }
1333 got, err := p.Rule(context.Background(), suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{
1334 {ItemID: "doc-team", Revision: 7}, {ItemID: "doc-private", Revision: 4}, {ItemID: "doc-granted", Revision: 9}, {ItemID: "doc-granted", Revision: 8},
1335 })
1336 if err != nil {
1337 t.Fatal(err)
1338 }
1339 want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.STALE}
1340 for i := range want {
1341 if got[i] != want[i] {
1342 t.Errorf("pair %d: %s, want %s", i, got[i], want[i])
1343 }
1344 }
1345 })
1346 }
1347}
1348
1349// Every change and its feed row are one transaction: when the feed row
1350// cannot be written, the change does not commit either. A rename committed
1351// without its row would leave a consumer holding a title the feed never
1352// told it had changed (Astra, 2026-11-01: swallowing the insert's error
1353// survived the suite).
1354//
1355// MUTATION-TESTED 2026-11-01, each reverted: bumpRevision returning nil
1356// when announce fails → rename, update, visibility and deletion all commit;
1357// createDocument ignoring announce's error → "create".
1358func TestSuiteAChangeWithoutItsFeedRowDoesNotCommit(t *testing.T) {
1359 app, err := NewForTest(t)
1360 if err != nil {
1361 t.Fatal(err)
1362 }
1363 ctx := context.Background()
1364 alice := app.TestPerson(t, "alice@example.com")
1365 actor := app.TestActorForPerson(t, alice)
1366 doc, err := app.store.Create(ctx, alice, "Before")
1367 if err != nil {
1368 t.Fatal(err)
1369 }
1370 if _, err := app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
1371 t.Fatal(err)
1372 }
1373 var updates, docs int64
1374 app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updates)
1375 app.store.db.Model(&Document{}).Count(&docs)
1376 rev := revisionOf(t, app.store, doc.ID)
1377
1378 if err := app.store.Rename(ctx, actor, doc, "After"); err == nil {
1379 t.Error("rename: succeeded without its feed row")
1380 }
1381 if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err == nil {
1382 t.Error("update: succeeded without its feed row")
1383 }
1384 if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err == nil {
1385 t.Error("visibility: succeeded without its feed row")
1386 }
1387 if err := app.store.deleteDocument(ctx, doc.ID); err == nil {
1388 t.Error("deletion: succeeded without its feed row")
1389 }
1390 if _, err := app.store.Create(ctx, alice, "New"); err == nil {
1391 t.Error("create: succeeded without its feed row")
1392 }
1393
1394 var after Document
1395 if err := app.store.db.First(&after, doc.ID).Error; err != nil {
1396 t.Fatal(err)
1397 }
1398 if after.Title != "Before" || after.Visibility != VisibilityTeam || after.DeletedAt != nil || after.Revision != rev {
1399 t.Errorf("a change committed without its feed row: %+v", after)
1400 }
1401 var updatesAfter, docsAfter int64
1402 app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updatesAfter)
1403 app.store.db.Model(&Document{}).Count(&docsAfter)
1404 if updatesAfter != updates || docsAfter != docs {
1405 t.Errorf("rows committed without their feed rows: updates %d→%d, documents %d→%d", updates, updatesAfter, docs, docsAfter)
1406 }
1407}
1408
1409// STALE is decided by Docs' own log, not by comparing numbers (doctrine
1410// §4.3): revisions are random, so a revision from this document's history
1411// is STALE, one it never had — never issued, or another document's — is
1412// UNKNOWN, whatever its size.
1413//
1414// MUTATION-TESTED 2026-11-01, each reverted: Rule answering STALE for any
1415// non-current revision without consulting the log → both "never issued"
1416// cases and the cross-document ones STALE (and conformance's "one revision
1417// ahead" STALE in both shapes); the log lookup not keyed on the document
1418// (any history row with the asked revision counts) → the three
1419// cross-document cases STALE. (A first try at the second dropped the
1420// document from the SQL in a way SQLite refused — red for a syntax error,
1421// not the rule — and was redone as a valid query.)
1422func TestSuiteStaleIsDecidedByTheLog(t *testing.T) {
1423 app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com"})
1424 if err != nil {
1425 t.Fatal(err)
1426 }
1427 ctx := context.Background()
1428 alice := app.TestPerson(t, "alice@example.com")
1429 actor := app.TestActorForPerson(t, alice)
1430 doc, _ := app.store.Create(ctx, alice, "One")
1431 other, _ := app.store.Create(ctx, alice, "Two")
1432 historyOf := func(d *Document, titles ...string) []int64 {
1433 h := []int64{revisionOf(t, app.store, d.ID)}
1434 for _, title := range titles {
1435 if err := app.store.Rename(ctx, actor, d, title); err != nil {
1436 t.Fatal(err)
1437 }
1438 h = append(h, revisionOf(t, app.store, d.ID))
1439 }
1440 return h
1441 }
1442 history := historyOf(doc, "One, again", "One, once more")
1443 otherHistory := historyOf(other, "Two, again")
1444 current := history[len(history)-1]
1445 // One batch, both documents, each asked at the other's old revisions:
1446 // a log read that mixes the two documents' histories answers those
1447 // STALE here, not only in conformance.
1448 ask := []suite.ItemRevision{
1449 {ItemID: doc.Sqid, Revision: history[0]},
1450 {ItemID: doc.Sqid, Revision: history[1]},
1451 {ItemID: doc.Sqid, Revision: current},
1452 {ItemID: doc.Sqid, Revision: current - 1},
1453 {ItemID: doc.Sqid, Revision: 1},
1454 {ItemID: doc.Sqid, Revision: otherHistory[1]},
1455 {ItemID: doc.Sqid, Revision: otherHistory[0]},
1456 {ItemID: other.Sqid, Revision: history[0]},
1457 {ItemID: other.Sqid, Revision: otherHistory[0]},
1458 }
1459 got, err := app.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "alice@example.com"}, ask)
1460 if err != nil {
1461 t.Fatal(err)
1462 }
1463 want := []suite.Authorization{suite.STALE, suite.STALE, suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.STALE}
1464 names := []string{"first", "second", "current", "never issued (current - 1)", "never issued (1)", "another document's current", "another document's old", "this one's old, asked of the other", "the other's own old"}
1465 for i := range want {
1466 if got[i] != want[i] {
1467 t.Errorf("%s: %s, want %s", names[i], got[i], want[i])
1468 }
1469 }
1470}
1471
1472// scriptedRandom is a randomSource that hands out the bytes it was given, and
1473// then fails.
1474type scriptedRandom struct{ r *bytes.Reader }
1475
1476func (s scriptedRandom) Read(p []byte) (int, error) { return s.r.Read(p) }
1477
1478func draws(values ...uint64) scriptedRandom {
1479 var b []byte
1480 for _, v := range values {
1481 b = binary.BigEndian.AppendUint64(b, v)
1482 }
1483 return scriptedRandom{bytes.NewReader(b)}
1484}
1485
1486type brokenRandom struct{}
1487
1488func (brokenRandom) Read([]byte) (int, error) { return 0, errors.New("no entropy") }
1489
1490// The two redraws, forced (Astra, round 3: both survived the suite): a draw
1491// of zero — directly, or a value that is zero once its sign bit is cleared —
1492// is drawn again, and a draw equal to the document's current revision is
1493// drawn again. And a source that fails is an error that stops the change:
1494// nothing falls back to a value a restore or anybody else could reproduce.
1495//
1496// MUTATION-TESTED 2026-11-01, each reverted: randomPositive returning its
1497// first draw whatever it is → "zero, then 7" gets 0 and "the sign bit" gets
1498// 0; newRevision returning its first draw → "current, then the next" gets
1499// 5; randomPositive answering a failed read with a time-based value instead
1500// of an error → "a broken source" commits a document.
1501//
1502// newRevision now takes what is taken rather than the current revision
1503// (suite revision 11 §6.6, 91affa1: unique against the whole log; the log
1504// half is TestSuiteARevisionIsNeverOneTheLogHolds). MUTATION-TESTED
1505// 2026-11-02, reverted: newRevision ignoring taken's error → "a log that
1506// cannot be read: a revision was drawn anyway".
1507func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) {
1508 t.Cleanup(func() { randomSource = crand.Reader })
1509
1510 randomSource = draws(0, 7)
1511 if n, err := randomPositive(); err != nil || n != 7 {
1512 t.Errorf("zero, then 7: %d %v", n, err)
1513 }
1514 randomSource = draws(1<<63, 11)
1515 if n, err := randomPositive(); err != nil || n != 11 {
1516 t.Errorf("the sign bit alone (zero once cleared), then 11: %d %v", n, err)
1517 }
1518 only := func(held ...int64) func(int64) (bool, error) {
1519 return func(r int64) (bool, error) {
1520 for _, h := range held {
1521 if r == h {
1522 return true, nil
1523 }
1524 }
1525 return false, nil
1526 }
1527 }
1528 randomSource = draws(5, 9)
1529 if n, err := newRevision(only(5)); err != nil || n != 9 {
1530 t.Errorf("current, then the next: %d %v", n, err)
1531 }
1532 randomSource = draws(5)
1533 if n, err := newRevision(only(4)); err != nil || n != 5 {
1534 t.Errorf("a draw that is not taken is kept: %d %v", n, err)
1535 }
1536 randomSource = draws(5)
1537 if _, err := newRevision(func(int64) (bool, error) { return false, errors.New("log unreadable") }); err == nil {
1538 t.Error("a log that cannot be read: a revision was drawn anyway")
1539 }
1540
1541 app, err := NewForTest(t)
1542 if err != nil {
1543 t.Fatal(err)
1544 }
1545 ctx := context.Background()
1546 randomSource = crand.Reader
1547 alice := app.TestPerson(t, "alice@example.com")
1548 doc, err := app.store.Create(ctx, alice, "Kept")
1549 if err != nil {
1550 t.Fatal(err)
1551 }
1552 randomSource = brokenRandom{}
1553 if _, err := randomPositive(); !errors.Is(err, errNoRandomness) {
1554 t.Errorf("a broken source: %v, want errNoRandomness", err)
1555 }
1556 var before int64
1557 app.store.db.Model(&Document{}).Count(&before)
1558 if _, err := app.store.Create(ctx, alice, "Not made"); err == nil {
1559 t.Error("a broken source: a document was created")
1560 }
1561 if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil {
1562 t.Error("a broken source: a rename committed")
1563 }
1564 var after int64
1565 app.store.db.Model(&Document{}).Count(&after)
1566 if after != before || revisionOf(t, app.store, doc.ID) != doc.Revision {
1567 t.Errorf("a broken source changed something: documents %d→%d, revision %d→%d", before, after, doc.Revision, revisionOf(t, app.store, doc.ID))
1568 }
1569}
1570
1571// A revision is never one the document's log holds (suite revision 11 §6.6,
1572// 91affa1, answering Fable's review of 0a59e7d, L4): a draw equal to ANY
1573// earlier revision of the document is drawn again, not only a draw equal to
1574// the current one. A draw equal to a prior revision would give an old name
1575// to new bytes, and a consumer still holding the old copy would be answered
1576// VISIBLE over text the document no longer has. The draws are forced: the
1577// document's first revision, its second, its current one, then a fresh
1578// value, which is the one the rename must take.
1579//
1580// MUTATION-TESTED 2026-11-02, each reverted: logRevisionTaken checking only
1581// the current revision (the revision-10 rule) → "the rename took revision
1582// <first>, one the log already held"; 0012 deleted → "the log probe's plan
1583// is [{Detail:SCAN suite_feed}]"; 0012's UNIQUE dropped → "suite_feed
1584// took a second row"; logRevisionTaken returning false,
1585// nil on a failed read → "a log that cannot be read: taken false and no
1586// error".
1587func TestSuiteARevisionIsNeverOneTheLogHolds(t *testing.T) {
1588 t.Cleanup(func() { randomSource = crand.Reader })
1589 app, err := NewForTest(t)
1590 if err != nil {
1591 t.Fatal(err)
1592 }
1593 ctx := context.Background()
1594 alice := app.TestPerson(t, "alice@example.com")
1595 actor := app.TestActorForPerson(t, alice)
1596 doc, err := app.store.Create(ctx, alice, "One")
1597 if err != nil {
1598 t.Fatal(err)
1599 }
1600 history := []int64{revisionOf(t, app.store, doc.ID)}
1601 for _, title := range []string{"One, again", "One, once more"} {
1602 if err := app.store.Rename(ctx, actor, doc, title); err != nil {
1603 t.Fatal(err)
1604 }
1605 history = append(history, revisionOf(t, app.store, doc.ID))
1606 }
1607 const fresh, nonce = 42, 4242
1608 for _, h := range history {
1609 if h == fresh {
1610 t.Skip("a random revision happened to be the fresh value")
1611 }
1612 }
1613 // Bump: history[0], history[1], history[2] (current), then fresh; then
1614 // announce's nonce.
1615 randomSource = draws(uint64(history[0]), uint64(history[1]), uint64(history[2]), fresh, nonce)
1616 if err := app.store.Rename(ctx, actor, doc, "Different text"); err != nil {
1617 t.Fatal(err)
1618 }
1619 if got := revisionOf(t, app.store, doc.ID); got != fresh {
1620 t.Errorf("the rename took revision %d, one the log already held (history %v); want the fresh draw %d", got, history, fresh)
1621 }
1622
1623 // The probe is one index lookup (0012), not a scan of a log that grows
1624 // with every applied update.
1625 var plan []struct{ Detail string }
1626 if err := app.store.db.Raw("EXPLAIN QUERY PLAN SELECT revision FROM suite_feed WHERE document_id = ? AND revision = ? LIMIT 1", doc.ID, fresh).Scan(&plan).Error; err != nil {
1627 t.Fatal(err)
1628 }
1629 if len(plan) != 1 || !strings.Contains(plan[0].Detail, "suite_feed_document_revision") {
1630 t.Errorf("the log probe's plan is %+v, want a search on suite_feed_document_revision", plan)
1631 }
1632
1633 // The schema holds the rule too: a second row for a revision the log
1634 // already holds is refused, whatever path writes it. The forced draws
1635 // are spent, so the real source goes back first — announce draws a
1636 // nonce, and a failed draw would pass this for the wrong reason (it
1637 // did, the first time). The presence half: a revision the log does not
1638 // hold is taken.
1639 randomSource = crand.Reader
1640 if err := announce(app.store.db, doc.ID, fresh+1, false); err != nil {
1641 t.Fatalf("suite_feed refused a revision it did not hold: %v", err)
1642 }
1643 if err := announce(app.store.db, doc.ID, fresh, false); err == nil {
1644 t.Errorf("suite_feed took a second row at revision %d for one document", fresh)
1645 }
1646
1647 // A log that cannot be read is an error, never "not taken". Asked of
1648 // the probe directly: through a bump, announce's insert into the same
1649 // missing table would fail anyway and hide whether the probe did.
1650 if err := app.store.db.Exec("ALTER TABLE suite_feed RENAME TO suite_feed_away").Error; err != nil {
1651 t.Fatal(err)
1652 }
1653 if taken, err := logRevisionTaken(app.store.db, doc.ID, fresh)(7); err == nil {
1654 t.Errorf("a log that cannot be read: taken %v and no error", taken)
1655 }
1656}
1657
1658// An orphan — a document 0002_owners.sql left at owner_id 0, readable by
1659// nobody — is not live, even if a feed row names it. Nothing in Docs writes
1660// one (announce runs only for documents with an owner), so the row is made
1661// by hand: S1 skips it, S3 refuses it and S2 answers NOT_VISIBLE. Kept as a
1662// clause in Feed rather than left to S2 and S3 because a feed row is itself
1663// a disclosure that an item exists, and an orphan is not Docs' to announce.
1664//
1665// MUTATION-TESTED 2026-11-02, reverted: Feed without "documents.owner_id >
1666// 0" → the orphan's sqid in the feed (Fable's review found this clause
1667// survived every other test).
1668func TestSuiteAnOrphanIsNeverAnnounced(t *testing.T) {
1669 app, err := NewForTest(t)
1670 if err != nil {
1671 t.Fatal(err)
1672 }
1673 ctx := context.Background()
1674 now := time.Now().UTC()
1675 orphan := &Document{Sqid: "orphan0011", Title: "Nobody's", GUID: "orphan-guid", ClientID: 1, OwnerID: 0, Visibility: VisibilityTeam, Revision: 42, CreatedAt: now, UpdatedAt: now}
1676 if err := app.store.db.Create(orphan).Error; err != nil {
1677 t.Fatal(err)
1678 }
1679 if err := app.store.db.Transaction(func(tx *gorm.DB) error { return announce(tx, orphan.ID, 42, false) }); err != nil {
1680 t.Fatal(err)
1681 }
1682 f, err := app.suite.Feed(ctx, "", 100)
1683 if err != nil {
1684 t.Fatal(err)
1685 }
1686 for _, row := range f.Rows {
1687 if row.ItemID == orphan.Sqid {
1688 t.Errorf("the feed announced an orphan: %+v", row)
1689 }
1690 }
1691 if _, err := app.suite.Content(ctx, orphan.Sqid, 42); !errors.Is(err, suite.ErrNotAvailable) {
1692 t.Errorf("S3 served an orphan: %v", err)
1693 }
1694 app.TestPerson(t, "alice@example.com")
1695 got, err := app.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "alice@example.com"}, []suite.ItemRevision{{ItemID: orphan.Sqid, Revision: 42}})
1696 if err != nil || got[0] != suite.NOT_VISIBLE {
1697 t.Errorf("S2 for an orphan on the team rung: %v %v, want NOT_VISIBLE", got, err)
1698 }
1699}
1700
1701// The rung's words on the share page are true (Fable on #103): a private
1702// document with a published link says the link opens it too, and a team
1703// document says edit access, not "the people above", decides who changes it.
1704//
1705// MUTATION-TESTED 2026-11-02, reverted: renderShare without the published
1706// branch → the plain private words on a published document.
1707func TestSuiteShareWordsMentionThePublishedLink(t *testing.T) {
1708 app, err := NewForTest(t)
1709 if err != nil {
1710 t.Fatal(err)
1711 }
1712 req := app.TestRequest(t, "alice@example.com", http.MethodGet, "/", nil)
1713 cookies := req.Cookies()
1714 do := func(method, path, body string) *httptest.ResponseRecorder {
1715 t.Helper()
1716 r := httptest.NewRequest(method, path, strings.NewReader(body))
1717 for _, c := range cookies {
1718 r.AddCookie(c)
1719 }
1720 if method == http.MethodPost {
1721 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
1722 r.Header.Set("Sec-Fetch-Site", "same-origin")
1723 }
1724 return serve(app, r)
1725 }
1726 rec := do(http.MethodPost, "/documents", "title=Notes")
1727 sqid := strings.TrimPrefix(rec.Header().Get("Location"), "/d/")
1728 if !strings.Contains(do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String(), "docs.share.team.body.team") {
1729 t.Error("a team document's share page")
1730 }
1731 if rec := do(http.MethodPost, "/d/"+sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther {
1732 t.Fatalf("make private: %d", rec.Code)
1733 }
1734 if rec := do(http.MethodPost, "/d/"+sqid+"/share/link", "on=1"); rec.Code != http.StatusSeeOther {
1735 t.Fatalf("publish: %d", rec.Code)
1736 }
1737 share := do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String()
1738 if !strings.Contains(share, "docs.share.team.body.private_published") {
1739 t.Error("a published private document's share page does not mention the link")
1740 }
1741 if rec := do(http.MethodPost, "/d/"+sqid+"/share/link", "on=0"); rec.Code != http.StatusSeeOther {
1742 t.Fatalf("unpublish: %d", rec.Code)
1743 }
1744 share = do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String()
1745 if strings.Contains(share, "docs.share.team.body.private_published") || !strings.Contains(share, "docs.share.team.body.private") {
1746 t.Error("an unpublished private document's share page still mentions a link")
1747 }
1748}
1749