| new file mode 100644 |
| index 0000000..ae40c8b |
| --- /dev/null |
| +++ b/internal/docs/suite_test.go |
| @@ -0,0 +1,870 @@ |
| +package docs |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/oficina/suite/conformance" |
| + "amadan.net/oficina/suite/server" |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// suiteVector is a case's document text as a real Yjs update |
| +// (fixtures/generate-suite.mjs). |
| +func suiteVector(t *testing.T, id string) []byte { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join("..", "..", "fixtures", "vectors", "suite", id+".update.bin")) |
| + if err != nil { |
| + t.Fatalf("suite vector %q: %v (run fixtures/generate-suite.mjs)", id, err) |
| + } |
| + return b |
| +} |
| + |
| +// bumpTo moves a document's revision up to target through bumpRevision, the |
| +// path every real change takes, so the feed carries a row per step. |
| +func bumpTo(t *testing.T, s *Store, docID, target int64) { |
| + t.Helper() |
| + for { |
| + var d Document |
| + if err := s.db.First(&d, docID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if d.Revision == target { |
| + return |
| + } |
| + if d.Revision > target { |
| + t.Fatalf("document %d is at revision %d, past %d", docID, d.Revision, target) |
| + } |
| + if err := s.db.Transaction(func(tx *gorm.DB) error { return bumpRevision(tx, docID, false) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// custodyParty is somebody in the custody fixture's world: the person id and |
| +// the address their grants key on. |
| +type custodyParty struct { |
| + id int64 |
| + address string |
| +} |
| + |
| +// seedCustody builds the custody fixture's world in a Docs store, through |
| +// Docs' own store paths: each case's rung, its owner (the asker or the other |
| +// party), a grant to the asker or to a guest, a published link, a deletion, |
| +// and the case's revision reached by real bumps. The fixture's ids are not |
| +// sqids; each document's sqid is set to the fixture id straight after it is |
| +// created (the column is a plain unique TEXT), so the producer under test is |
| +// the real one with no id-mapping in between. Documents are untitled, so S3's |
| +// body is the text alone and equals the fixture's s3_body exactly. |
| +func seedCustody(t *testing.T, s *Store, asker, other custodyParty) { |
| + t.Helper() |
| + ctx := context.Background() |
| + f, err := suite.LoadCustodyFixture() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range f.Cases { |
| + owner := other |
| + if c.Owner == "asker" { |
| + owner = asker |
| + } |
| + vis := VisibilityPrivate |
| + if c.Rung == suite.RungTeam || c.ItemID == "doc-was-team" { |
| + vis = VisibilityTeam |
| + } |
| + doc, err := s.createDocument(ctx, owner.id, "", "", vis) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.db.Model(&Document{}).Where("id = ?", doc.ID).UpdateColumn("sqid", c.ItemID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + doc.Sqid = c.ItemID |
| + // The deleted case has no text in the fixture (its S3 is a 404), so |
| + // it gets any real content; every other case gets its own s3_body. |
| + var update []byte |
| + if c.S3Body == "" { |
| + update = ReadFragmentFixture(t, "hello") |
| + } else { |
| + update = suiteVector(t, c.ItemID) |
| + } |
| + if _, err := s.ApplyUpdate(ctx, doc, localActor(owner.id, owner.address), update); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.AskerGrant { |
| + 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 { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.Rung == suite.RungGranted && !c.AskerGrant { |
| + if err := s.Grant(ctx, owner.id, c.ItemID, "guest@example.com", RoleReader); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.ItemID == "doc-was-team" { |
| + if err := s.SetVisibility(ctx, owner.id, c.ItemID, VisibilityPrivate); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.Link == "read" { |
| + if _, err := s.Publish(ctx, owner.id, c.ItemID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.Rung == suite.RungDeleted { |
| + bumpTo(t, s, doc.ID, c.Revision-1) |
| + if err := s.deleteDocument(ctx, doc.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + bumpTo(t, s, doc.ID, c.Revision) |
| + } |
| + var got Document |
| + if err := s.db.First(&got, doc.ID).Error; err != nil || got.Revision != c.Revision { |
| + t.Fatalf("%s: seeded at revision %d, want %d (%v)", c.ItemID, got.Revision, c.Revision, err) |
| + } |
| + } |
| +} |
| + |
| +// loneCustodyApp is a lone-shape Docs with the fixture's asker as a member |
| +// address and the stranger as an address that is neither a member nor holds a |
| +// grant (conformance.RunAs with SubjectAddress keeps "pers_ana"/"pers_bo" as |
| +// the values and makes them addresses). |
| +func loneCustodyApp(t *testing.T) *App { |
| + t.Helper() |
| + app, err := NewForTestWith(t, Config{AllowedAddresses: "pers_ana,owner@example.com"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + ana, err := app.store.EnsurePerson(ctx, "pers_ana") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + owner, err := app.store.EnsurePerson(ctx, "owner@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seedCustody(t, app.store, custodyParty{ana, "pers_ana"}, custodyParty{owner, "owner@example.com"}) |
| + return app |
| +} |
| + |
| +// Gate 3 in lone shape: the suite's own harness against the producer New |
| +// built, over a store holding the custody fixture's world. Askers are |
| +// addresses here, and the harness also asks under person_ref, which must be |
| +// UNKNOWN for every pair. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the link table read as a grant |
| +// in permissionScope (an EXISTS on links) → doc-link, doc-link-added-late |
| +// VISIBLE; teamReader returning true → the stranger VISIBLE on doc-team; |
| +// Rule without its "not readable is NOT_VISIBLE" branch, so the revision |
| +// decides → doc-guest, doc-link UNKNOWN; Content without both revision |
| +// checks → S3 200 at revision-1 and +1; the wrong-kind branch answering |
| +// NOT_VISIBLE → red; Feed's tip returning a fresh cursor → "no tip after |
| +// 100 pages"; deleteDocument announcing gone=false → "last row is not |
| +// gone". (A first try at the revision mutation — a STALE case inserted |
| +// ahead of the person check — stayed green, because Rule only knows a |
| +// revision for a readable document; the mutation was the wrong shape, not |
| +// the test blind, and was replaced by the one above.) |
| +func TestSuiteConformanceLoneShape(t *testing.T) { |
| + app := loneCustodyApp(t) |
| + conformance.RunAs(t, server.Routes(app.suite, nil), suite.SubjectAddress) |
| +} |
| + |
| +// renamedAskers maps the fixture's person refs onto roster-shaped subjects |
| +// (a roster person ref is "pr_" and 26 characters, and the fixture's |
| +// "pers_ana" is not one). Test-only, and the only thing between the harness |
| +// and the real producer: ids, revisions and content pass through untouched. |
| +type renamedAskers struct { |
| + server.Producer |
| + names map[string]string |
| +} |
| + |
| +func (r renamedAskers) Rule(ctx context.Context, a suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| + if v, ok := r.names[a.Value]; ok && a.Kind == suite.SubjectPersonRef { |
| + a.Value = v |
| + } |
| + return r.Producer.Rule(ctx, a, pairs) |
| +} |
| + |
| +var ( |
| + anaSubject = "pr_" + strings.Repeat("n", 26) |
| + strangerSubject = "pr_" + strings.Repeat("s", 26) |
| +) |
| + |
| +// teamCustodyStore is the same world in team mode: ana is a local person |
| +// linked to anaSubject, which is on the roster; strangerSubject is not. |
| +// connect's Resolve is stubbed to that one link (the Bridge is Home's code, |
| +// tested there); the roster, the principals and the read predicate are real. |
| +func teamCustodyStore(t *testing.T, members ...string) (*App, *suiteProducer, *teamTestClock, custodyParty, custodyParty) { |
| + t.Helper() |
| + app := newSampleDocumentsInternalTestApp(t, "0") |
| + s := app.store |
| + ctx := context.Background() |
| + anaID, err := s.EnsurePerson(ctx, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ownerID, err := s.EnsurePerson(ctx, "owner@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ana, other := custodyParty{anaID, "ana@example.com"}, custodyParty{ownerID, "owner@example.com"} |
| + seedCustody(t, s, ana, other) |
| + _, clock := testTeamRosterOf(t, s, app, append([]string{anaSubject}, members...)...) |
| + subjects := subjectsFunc(func(_ context.Context, subject string) (connect.Person, error) { |
| + if subject == anaSubject { |
| + return connect.Person{ID: anaID, Label: "ana@example.com"}, nil |
| + } |
| + return connect.Person{}, connectlinks.ErrRefused |
| + }) |
| + return app, &suiteProducer{store: s, subjects: subjects}, clock, ana, other |
| +} |
| + |
| +// Gate 3 in team mode, person_ref askers. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: teamReader ignoring standing |
| +// (true in team mode) → the stranger VISIBLE on doc-team; askerActor |
| +// accepting address in team mode → doc-deleted NOT_VISIBLE under the wrong |
| +// kind; homeActor turning a refused subject into an error → every |
| +// stranger answer UNKNOWN (a 503 for the whole call). |
| +func TestSuiteConformanceTeamMode(t *testing.T) { |
| + _, p, _, _, _ := teamCustodyStore(t) |
| + h := server.Routes(renamedAskers{Producer: p, names: map[string]string{"pers_ana": anaSubject, "pers_bo": strangerSubject}}, nil) |
| + conformance.Run(t, h) |
| +} |
| + |
| +// The two halves of Paul's 2026-11-01 ruling, "New docs Team, old private": |
| +// a document made from now on is on the team rung, and migration 0009 leaves |
| +// every existing one private. The sample library is private too. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: CreateDraft passing |
| +// VisibilityPrivate → "a new document"; 0009's DEFAULT 'team' → "an existing |
| +// document"; seed.go creating on the team rung → "sample". |
| +func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := form(t, app, "alice@example.com", "/documents", "title=Plans") |
| + if rec.Code != http.StatusSeeOther { |
| + t.Fatalf("create: %d", rec.Code) |
| + } |
| + var doc Document |
| + if err := app.store.db.Where("sqid = ?", strings.TrimPrefix(rec.Header().Get("Location"), "/d/")).First(&doc).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if doc.Visibility != VisibilityTeam || doc.Revision != 1 { |
| + t.Errorf("a new document: %q at revision %d, want team at 1", doc.Visibility, doc.Revision) |
| + } |
| + |
| + samples := newSampleDocumentsInternalTestApp(t, "1") |
| + owner := samples.TestPerson(t, "new@example.com") |
| + var teamSamples int64 |
| + samples.store.db.Model(&Document{}).Where("owner_id = ? AND visibility = ?", owner, VisibilityTeam).Count(&teamSamples) |
| + var all int64 |
| + samples.store.db.Model(&Document{}).Where("owner_id = ?", owner).Count(&all) |
| + if all == 0 || teamSamples != 0 { |
| + t.Errorf("sample library: %d of %d on the team rung, want 0 of some", teamSamples, all) |
| + } |
| + |
| + // The migration, against a database that existed before it. |
| + db, err := migrate.Memory() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + entries, err := fs.ReadDir(migrationFS, "migrations") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + for _, e := range entries { |
| + names = append(names, e.Name()) |
| + } |
| + sort.Strings(names) |
| + exec := func(name string) { |
| + t.Helper() |
| + b, err := fs.ReadFile(migrationFS, "migrations/"+name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec(string(b)); err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + for _, n := range names { |
| + if n < "0009" { |
| + exec(n) |
| + } |
| + } |
| + now := time.Now().UTC() |
| + for _, row := range []struct { |
| + id, owner int64 |
| + deleted bool |
| + }{{1, 1, false}, {2, 1, true}, {3, 0, false}, {4, 1, false}} { |
| + var del any |
| + if row.deleted { |
| + del = now |
| + } |
| + 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, ?, ?, ?, ?)`, |
| + row.id, "s"+strconv.FormatInt(row.id, 10), now, now, del, row.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + exec("0009_suite.sql") |
| + var private, atOne int |
| + db.QueryRow(`SELECT COUNT(*) FROM documents WHERE visibility = 'private'`).Scan(&private) |
| + db.QueryRow(`SELECT COUNT(*) FROM documents WHERE revision = 1`).Scan(&atOne) |
| + if private != 4 || atOne != 4 { |
| + t.Errorf("an existing document: %d of 4 private, %d of 4 at revision 1", private, atOne) |
| + } |
| + rows, err := db.Query(`SELECT document_id FROM suite_feed ORDER BY id`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var fed []int64 |
| + for rows.Next() { |
| + var id int64 |
| + rows.Scan(&id) |
| + fed = append(fed, id) |
| + } |
| + rows.Close() |
| + if len(fed) != 2 || fed[0] != 1 || fed[1] != 4 { |
| + t.Errorf("the migration announced %v, want the live documents [1 4] (not the deleted one, not the orphan)", fed) |
| + } |
| + if _, err := db.Exec(`UPDATE documents SET visibility = 'everyone' WHERE id = 1`); err == nil { |
| + t.Error("a third visibility was accepted") |
| + } |
| +} |
| + |
| +// form is a signed-in scriptless form POST. |
| +func form(t *testing.T, app *App, address, path, body string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := app.TestRequest(t, address, http.MethodPost, path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + return serve(app, r) |
| +} |
| + |
| +// The team rung in lone shape: every configured member reads a team document |
| +// and none writes it or reaches its share page; a guest (admitted only by a |
| +// grant on another document) does not read it; private takes it away. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: teamReader without the members |
| +// predicate (any address) → "the guest"; the team clause applied to |
| +// permissionWrite → "bob wrote"; the team clause dropped → "bob read" and |
| +// the list marker. |
| +func TestSuiteTeamRungLoneShape(t *testing.T) { |
| + app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com,bob@example.com"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + bob := app.TestPerson(t, "bob@example.com") |
| + team, err := app.store.Create(ctx, alice, "Team plans") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + other := app.TestCreatePrivate(t, alice, "Guest brief") |
| + if err := app.store.Grant(ctx, alice, other.Sqid, "guest@example.com", RoleReader); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.TestPerson(t, "guest@example.com") |
| + |
| + if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusOK { |
| + t.Errorf("bob read a team document: %d, want 200", rec.Code) |
| + } |
| + if app.store.CanWrite(ctx, localActor(bob, "bob@example.com"), team.ID) { |
| + t.Error("bob wrote a team document he holds no writer grant on") |
| + } |
| + if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)); rec.Code != http.StatusNotFound { |
| + t.Errorf("bob reached the share page: %d, want 404", rec.Code) |
| + } |
| + if rec := form(t, app, "bob@example.com", "/d/"+team.Sqid+"/share/team", "visibility=private"); rec.Code != http.StatusNotFound { |
| + t.Errorf("bob moved the rung: %d, want 404", rec.Code) |
| + } |
| + if rec := serve(app, app.TestRequest(t, "guest@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusNotFound { |
| + t.Errorf("the guest read a team document: %d, want 404", rec.Code) |
| + } |
| + list := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/", nil)).Body.String() |
| + if !strings.Contains(list, "docs.list.team") || strings.Contains(list, "docs.list.shared") { |
| + t.Error("bob's list does not mark the team document as the team's") |
| + } |
| + |
| + share := serve(app, app.TestRequest(t, "alice@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)).Body.String() |
| + if !strings.Contains(share, `name="visibility" value="private"`) || !strings.Contains(share, "docs.share.team.body.team") { |
| + t.Error("the share page does not offer to make a team document private") |
| + } |
| + if rec := form(t, app, "alice@example.com", "/d/"+team.Sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("make private: %d", rec.Code) |
| + } |
| + if rec := serve(app, app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+team.Sqid, nil)); rec.Code != http.StatusNotFound { |
| + t.Errorf("bob read it after it went private: %d, want 404", rec.Code) |
| + } |
| + share = serve(app, app.TestRequest(t, "alice@example.com", http.MethodGet, "/d/"+team.Sqid+"/share", nil)).Body.String() |
| + if !strings.Contains(share, `name="visibility" value="team"`) || !strings.Contains(share, "docs.share.team.body.private") { |
| + t.Error("the share page does not offer to share a private document with the team") |
| + } |
| + if rec := form(t, app, "alice@example.com", "/d/"+team.Sqid+"/share/team", "visibility=everyone"); rec.Code != http.StatusBadRequest { |
| + t.Errorf("an unknown visibility: %d, want 400", rec.Code) |
| + } |
| +} |
| + |
| +// The team rung in team mode follows roster standing: a Member who does not |
| +// own a team document reads it, a NotMember does not, and Unknown is |
| +// retryable rather than a definite no. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: teamReader returning true in |
| +// team mode → NotMember and Unknown both read the document; the team clause |
| +// dropped → "a member could not read"; the team clause on writes → "a |
| +// member may write". |
| +func TestSuiteTeamRungTeamMode(t *testing.T) { |
| + app := newSampleDocumentsInternalTestApp(t, "0") |
| + s := app.store |
| + ctx := context.Background() |
| + owner, _ := s.EnsurePerson(ctx, "owner@example.com") |
| + reader, _ := s.EnsurePerson(ctx, "reader@example.com") |
| + team, err := s.Create(ctx, owner, "Team") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + private, err := s.createDocument(ctx, owner, "Private", "", VisibilityPrivate) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + subject := "pr_" + strings.Repeat("r", 26) |
| + rt, _ := testTeamRosterOf(t, s, app, subject) |
| + actor := localActor(reader, "reader@example.com") |
| + |
| + member := context.WithValue(ctx, accessContextKey{}, rt.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject})) |
| + if _, err := s.GetFor(member, actor, team.Sqid); err != nil { |
| + t.Errorf("a member could not read a team document: %v", err) |
| + } |
| + if _, err := s.GetFor(member, actor, private.Sqid); !errors.Is(err, gorm.ErrRecordNotFound) { |
| + t.Errorf("a member read a private document: %v", err) |
| + } |
| + if s.CanWrite(member, actor, team.ID) { |
| + t.Error("a member may write a team document they hold no writer grant on") |
| + } |
| + for state, want := range map[roster.State]error{roster.NotMember: gorm.ErrRecordNotFound, roster.Unknown: errTeamUnavailable} { |
| + c := context.WithValue(ctx, accessContextKey{}, &requestAccess{runtime: rt, actor: actor, Access: standing(state)}) |
| + if _, err := s.GetFor(c, actor, team.Sqid); !errors.Is(err, want) { |
| + t.Errorf("standing %v: %v, want %v", state, err, want) |
| + } |
| + } |
| +} |
| + |
| +// S1 as Docs serves it: pages in id order, a cursor that is the last id, the |
| +// tip returning the cursor given with no rows, a malformed cursor answered |
| +// from the beginning, a row per bump (update, rename, visibility change, |
| +// deletion), nothing for a grant or an unchanged rung, gone only on deletion. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: Rename without bumpRevision, |
| +// ApplyUpdate without it, SetVisibility without it, and creation without |
| +// its announce → each a missing row in the feed comparison; SetVisibility |
| +// bumping when nothing changed → an extra row; deleteDocument announcing |
| +// gone=false → "(gone)"; Feed returning "" at an empty tip → "empty tip"; |
| +// Feed ignoring the cursor → "the cursor came back unchanged with rows". |
| +func TestSuiteFeed(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + p := app.suite |
| + empty, err := p.Feed(ctx, "", 10) |
| + if err != nil || empty.Cursor != "0" || len(empty.Rows) != 0 { |
| + t.Fatalf("empty tip: %+v %v", empty, err) |
| + } |
| + if again, _ := p.Feed(ctx, empty.Cursor, 10); again.Cursor != "0" || len(again.Rows) != 0 { |
| + t.Errorf("empty tip, asked again: %+v", again) |
| + } |
| + |
| + alice := app.TestPerson(t, "alice@example.com") |
| + actor := app.TestActorForPerson(t, alice) |
| + doc, _ := app.store.Create(ctx, alice, "One") |
| + two, _ := app.store.Create(ctx, alice, "Two") |
| + if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.Rename(ctx, actor, doc, "One, renamed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.Grant(ctx, alice, doc.Sqid, "bob@example.com", RoleReader); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.TestSoftDelete(t, two.Sqid) |
| + |
| + type step struct { |
| + sqid string |
| + rev int64 |
| + gone bool |
| + } |
| + want := []step{{doc.Sqid, 1, false}, {two.Sqid, 1, false}, {doc.Sqid, 2, false}, {doc.Sqid, 3, false}, {doc.Sqid, 4, false}, {two.Sqid, 2, true}} |
| + var got []step |
| + cursor := "" |
| + for page := 0; page < 10; page++ { |
| + f, err := p.Feed(ctx, cursor, 2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Cursor == cursor { |
| + if len(f.Rows) != 0 { |
| + t.Fatal("the cursor came back unchanged with rows") |
| + } |
| + break |
| + } |
| + if len(f.Rows) > 2 { |
| + t.Fatalf("page two: %d rows, limit 2", len(f.Rows)) |
| + } |
| + for _, r := range f.Rows { |
| + if r.TouchedAt.IsZero() { |
| + t.Error("a row without a time") |
| + } |
| + got = append(got, step{r.ItemID, r.Revision, r.Gone}) |
| + } |
| + cursor = f.Cursor |
| + } |
| + if len(got) != len(want) { |
| + t.Fatalf("feed %+v, want %+v (rename, unchanged rung, grant)", got, want) |
| + } |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Errorf("row %d: %+v, want %+v (gone)", i, got[i], want[i]) |
| + } |
| + } |
| + if tip, _ := p.Feed(ctx, cursor, 2); tip.Cursor != cursor || len(tip.Rows) != 0 { |
| + t.Errorf("tip: %+v, want cursor %q and no rows", tip, cursor) |
| + } |
| + if bad, _ := p.Feed(ctx, "not-a-cursor", 100); len(bad.Rows) != len(want) { |
| + t.Errorf("a malformed cursor: %d rows, want the whole feed again", len(bad.Rows)) |
| + } |
| + var current Document |
| + app.store.db.First(¤t, doc.ID) |
| + if current.Revision != 4 { |
| + t.Errorf("document revision %d, want 4", current.Revision) |
| + } |
| +} |
| + |
| +// Every S2 branch the brief and suite §4.3 name, in lone shape: wrong kind, |
| +// an address the front door refuses, an unknown and a deleted id, a link-only |
| +// document, ownership at, behind and ahead of the revision and below 1, a |
| +// member who has never signed in (team rung yes, private no), and a grantee |
| +// who has never signed in. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: askerActor skipping the front |
| +// door (no allows check) → "a refused address that owns a document" (the |
| +// plain refused address stayed green under it: with no ownership and no |
| +// grant nothing opens anyway, so that case alone could not see the gate, |
| +// and the owning case was added); revision 0 answered STALE → "the owner, |
| +// pair 1"; permissionScope keeping the person-row guard for reads → both |
| +// "never signed in" cases. |
| +func TestSuiteRuleLoneShape(t *testing.T) { |
| + app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com,newcomer@example.com"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + own, _ := app.store.Create(ctx, alice, "Team") |
| + private := app.TestCreatePrivate(t, alice, "Private") |
| + linked := app.TestCreatePrivate(t, alice, "Linked") |
| + granted := app.TestCreatePrivate(t, alice, "Granted") |
| + gone := app.TestCreatePrivate(t, alice, "Gone") |
| + if _, err := app.store.Publish(ctx, alice, linked.Sqid); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.Grant(ctx, alice, granted.Sqid, "invitee@example.com", RoleReader); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.TestSoftDelete(t, gone.Sqid) |
| + |
| + ask := func(kind suite.SubjectKind, who string, pairs ...suite.ItemRevision) []suite.Authorization { |
| + t.Helper() |
| + got, err := app.suite.Rule(ctx, suite.Subject{Kind: kind, Value: who}, pairs) |
| + if err != nil || len(got) != len(pairs) { |
| + t.Fatalf("Rule: %v %v", got, err) |
| + } |
| + return got |
| + } |
| + pr := func(d *Document, rev int64) suite.ItemRevision { |
| + return suite.ItemRevision{ItemID: d.Sqid, Revision: rev} |
| + } |
| + expect := func(what string, got []suite.Authorization, want ...suite.Authorization) { |
| + t.Helper() |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Errorf("%s, pair %d: %s, want %s", what, i, got[i], want[i]) |
| + } |
| + } |
| + } |
| + |
| + expect("wrong kind", ask(suite.SubjectPersonRef, "alice@example.com", pr(own, 1), pr(private, 1)), suite.UNKNOWN, suite.UNKNOWN) |
| + expect("the owner", ask(suite.SubjectAddress, "Alice@Example.com", |
| + pr(own, 1), pr(own, 0), pr(own, 2), pr(private, 1), suite.ItemRevision{ItemID: "no-such-sqid", Revision: 1}, pr(gone, 2)), |
| + suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE) |
| + if _, err := app.store.ApplyUpdate(ctx, own, app.TestActorForPerson(t, alice), ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + expect("behind", ask(suite.SubjectAddress, "alice@example.com", pr(own, 1), pr(own, 2)), suite.STALE, suite.VISIBLE) |
| + expect("a member who never signed in", ask(suite.SubjectAddress, "newcomer@example.com", pr(own, 2), pr(private, 1), pr(linked, 1)), |
| + suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE) |
| + expect("a grantee who never signed in", ask(suite.SubjectAddress, "invitee@example.com", pr(granted, 1), pr(own, 2)), |
| + suite.VISIBLE, suite.NOT_VISIBLE) |
| + expect("a refused address", ask(suite.SubjectAddress, "stranger@example.com", pr(own, 2), pr(linked, 1)), |
| + suite.NOT_VISIBLE, suite.NOT_VISIBLE) |
| + // Somebody taken off the allowlist who still owns a document: the front |
| + // door refuses them on every request (requireAdmission), so S2 must too, |
| + // although ownership alone would otherwise open it. |
| + former := app.TestPerson(t, "former@example.com") |
| + theirs := app.TestCreatePrivate(t, former, "Theirs") |
| + expect("a refused address that owns a document", ask(suite.SubjectAddress, "former@example.com", pr(theirs, 1)), suite.NOT_VISIBLE) |
| + var n int64 |
| + app.store.db.Model(&Person{}).Where("email IN ?", []string{"newcomer@example.com", "invitee@example.com", "stranger@example.com"}).Count(&n) |
| + if n != 0 { |
| + t.Errorf("S2 created %d person rows", n) |
| + } |
| +} |
| + |
| +// S2 in team mode: the person_ref kind only; a subject with no Docs principal |
| +// who is a Member reads the team rung by standing; Unknown standing withholds |
| +// loudly what only membership would open, and still answers a grant. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: homeActor returning a refused |
| +// subject as an error → Rule fails for "an unlinked member". (The Unknown |
| +// branch is held by TestSuiteRuleTeamModeUnknownStanding.) |
| +func TestSuiteRuleTeamMode(t *testing.T) { |
| + newcomer := "pr_" + strings.Repeat("w", 26) |
| + _, p, _, ana, _ := teamCustodyStore(t, newcomer) |
| + ctx := context.Background() |
| + ask := func(who suite.Subject, pairs ...suite.ItemRevision) []suite.Authorization { |
| + t.Helper() |
| + got, err := p.Rule(ctx, who, pairs) |
| + if err != nil || len(got) != len(pairs) { |
| + t.Fatalf("Rule: %v %v", got, err) |
| + } |
| + return got |
| + } |
| + team := suite.ItemRevision{ItemID: "doc-team", Revision: 7} |
| + priv := suite.ItemRevision{ItemID: "doc-private", Revision: 4} |
| + if got := ask(suite.Subject{Kind: suite.SubjectPersonRef, Value: newcomer}, team, priv); got[0] != suite.VISIBLE || got[1] != suite.NOT_VISIBLE { |
| + t.Errorf("an unlinked member: %v, want [VISIBLE NOT_VISIBLE]", got) |
| + } |
| + if got := ask(suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, team, priv); got[0] != suite.VISIBLE || got[1] != suite.VISIBLE { |
| + t.Errorf("a linked member: %v, want [VISIBLE VISIBLE]", got) |
| + } |
| + if got := ask(suite.Subject{Kind: suite.SubjectAddress, Value: ana.address}, team, priv); got[0] != suite.UNKNOWN || got[1] != suite.UNKNOWN { |
| + t.Errorf("an address in team mode: %v, want UNKNOWN", got) |
| + } |
| +} |
| + |
| +// Unknown standing, from a roster lease that has run out with the directory |
| +// unreachable: what only membership would open is UNKNOWN, a grant still |
| +// answers, and a deleted document is still NOT_VISIBLE. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: the uncertain branch removed → |
| +// doc-team and doc-private NOT_VISIBLE. |
| +func TestSuiteRuleTeamModeUnknownStanding(t *testing.T) { |
| + _, p, clock, _, _ := teamCustodyStore(t) |
| + ctx := context.Background() |
| + team := suite.ItemRevision{ItemID: "doc-team", Revision: 7} |
| + priv := suite.ItemRevision{ItemID: "doc-private", Revision: 4} |
| + grant := suite.ItemRevision{ItemID: "doc-granted", Revision: 9} |
| + gone := suite.ItemRevision{ItemID: "doc-deleted", Revision: 6} |
| + got, err := p.Rule(ctx, suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{team, priv, grant, gone}) |
| + if err != nil || got[0] != suite.VISIBLE || got[1] != suite.VISIBLE || got[2] != suite.VISIBLE { |
| + t.Fatalf("member standing: %v %v", got, err) |
| + } |
| + clock.step(61 * time.Second) |
| + got, err = p.Rule(ctx, suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{team, priv, grant, gone}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.NOT_VISIBLE} |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Errorf("unknown standing, pair %d: %s, want %s", i, got[i], want[i]) |
| + } |
| + } |
| +} |
| + |
| +// S3: the current revision only, the title on the first line, an untitled |
| +// document as its text alone, a deleted one refused. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: Content without the second |
| +// revision read → "a change during the read"; without both revision checks |
| +// → "an old revision" (the first check alone is shadowed by the second, so |
| +// it was only ever red together with it); without the title line → |
| +// "titled". |
| +func TestSuiteContent(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + actor := app.TestActorForPerson(t, alice) |
| + doc, _ := app.store.Create(ctx, alice, "Minutes") |
| + if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, err := app.suite.Content(ctx, doc.Sqid, 2) |
| + if err != nil || string(body) != "Minutes\n\nhello world" { |
| + t.Errorf("titled: %q %v", body, err) |
| + } |
| + if _, err := app.suite.Content(ctx, doc.Sqid, 1); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("an old revision: %v", err) |
| + } |
| + if _, err := app.suite.Content(ctx, doc.Sqid, 3); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("a future revision: %v", err) |
| + } |
| + untitled, _ := app.store.Create(ctx, alice, "") |
| + if _, err := app.store.ApplyUpdate(ctx, untitled, actor, ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if body, err := app.suite.Content(ctx, untitled.Sqid, 2); err != nil || string(body) != "hello world" { |
| + t.Errorf("untitled: %q %v", body, err) |
| + } |
| + // A rename that lands while the text is being replayed: the body read |
| + // is the old title's, so it must not go out labelled revision 2. |
| + app.suite.replayed = func() { |
| + app.suite.replayed = nil |
| + if err := app.store.Rename(ctx, actor, doc, "Minutes, renamed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if body, err := app.suite.Content(ctx, doc.Sqid, 2); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("a change during the read: %q %v, want not available", body, err) |
| + } |
| + if body, err := app.suite.Content(ctx, doc.Sqid, 3); err != nil || string(body) != "Minutes, renamed\n\nhello world" { |
| + t.Errorf("after the rename: %q %v", body, err) |
| + } |
| + app.TestSoftDelete(t, doc.Sqid) |
| + if _, err := app.suite.Content(ctx, doc.Sqid, 4); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("deleted: %v", err) |
| + } |
| +} |
| + |
| +const suiteTestToken = "a-test-token-for-memoria" |
| + |
| +func suiteConsumersJSON() string { |
| + return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteTestToken) + `"}]}]` |
| +} |
| + |
| +func suiteRequest(method, path, token string, body []byte) *http.Request { |
| + r := httptest.NewRequest(method, path, bytes.NewReader(body)) |
| + if token != "" { |
| + r.Header.Set("Authorization", "Bearer "+token) |
| + } |
| + return r |
| +} |
| + |
| +// The suite routes are mounted exactly, outside the session and CSRF layers: |
| +// memoria's POST /suite/s2 carries only Authorization and is served, while a |
| +// POST anywhere else with the same headers is still refused by homeCSRF — |
| +// including another method on a suite path and a path beside them. Without a |
| +// token, 401; with no consumers configured, /suite/* answers exactly as an |
| +// unknown path does. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: mounting the suite handler on |
| +// the prefix "/suite/" → POST /suite/s1, /suite/s2x and /suite/ escape |
| +// homeCSRF; mounting inside the router (after homeCSRF) → S2 with only |
| +// Authorization 403, bare and served; mountSuite without its nil check → |
| +// "http: nil handler" panic with no consumers; server.Routes mounted in |
| +// place of server.Handler → 200 with no token and routes with no |
| +// consumers. |
| +func TestSuiteRoutesAreMountedExactlyOutsideCSRF(t *testing.T) { |
| + app, err := NewForTestWith(t, Config{SuiteConsumers: suiteConsumersJSON()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := app.Handler() |
| + s2 := []byte(`{"asker":{"kind":"address","value":"a@example.com"},"pairs":[]}`) |
| + if rec := httptestServe(h, suiteRequest("POST", suite.RouteS2, suiteTestToken, s2)); rec.Code != http.StatusOK { |
| + t.Errorf("S2 with only Authorization: %d, want 200", rec.Code) |
| + } |
| + if rec := httptestServe(h, suiteRequest("GET", suite.RouteS1, suiteTestToken, nil)); rec.Code != http.StatusOK { |
| + t.Errorf("S1: %d", rec.Code) |
| + } |
| + for _, path := range []string{suite.RouteS1, "/suite/s2x", "/suite/", "/documents"} { |
| + if rec := httptestServe(h, suiteRequest("POST", path, suiteTestToken, s2)); rec.Code != http.StatusForbidden { |
| + t.Errorf("POST %s with only Authorization: %d, want homeCSRF's 403", path, rec.Code) |
| + } |
| + } |
| + // And through rastrillo's production stack (locale, security headers, |
| + // panic recovery), which cmd/docs serves: memoria meets that, not the |
| + // bare mux. |
| + served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if done != nil { |
| + defer done() |
| + } |
| + if rec := httptestServe(served, suiteRequest("POST", suite.RouteS2, suiteTestToken, s2)); rec.Code != http.StatusOK { |
| + t.Errorf("served S2 with only Authorization: %d, want 200", rec.Code) |
| + } |
| + if rec := httptestServe(served, suiteRequest("POST", "/documents", suiteTestToken, s2)); rec.Code != http.StatusForbidden { |
| + t.Errorf("served POST /documents with only Authorization: %d, want 403", rec.Code) |
| + } |
| + for name, tok := range map[string]string{"no token": "", "a wrong token": "nope"} { |
| + if rec := httptestServe(h, suiteRequest("GET", suite.RouteS1, tok, nil)); rec.Code != http.StatusUnauthorized { |
| + t.Errorf("%s: %d, want 401", name, rec.Code) |
| + } |
| + } |
| + |
| + bare, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, method := range []string{"GET", "POST"} { |
| + for _, path := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3 + "/x"} { |
| + got := httptestServe(bare.Handler(), suiteRequest(method, path, suiteTestToken, s2)) |
| + unknown := httptestServe(bare.Handler(), suiteRequest(method, "/no-such-route", suiteTestToken, s2)) |
| + if got.Code != unknown.Code || got.Code == http.StatusOK || got.Code == http.StatusUnauthorized { |
| + t.Errorf("no consumers, %s %s: %d, an unknown path answers %d", method, path, got.Code, unknown.Code) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func httptestServe(h http.Handler, r *http.Request) *httptest.ResponseRecorder { |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, r) |
| + return rec |
| +} |
| + |
| +// A malformed consumer list refuses boot; an empty one boots with no routes. |
| +// |
| +// MUTATION-TESTED 2026-11-01: New ignoring ParseConsumers' error → red. |
| +func TestSuiteConsumersMalformedRefusesBoot(t *testing.T) { |
| + for _, bad := range []string{"null", "[]", `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"plain"}]}]`, "{"} { |
| + if _, err := NewForTestWith(t, Config{SuiteConsumers: bad}); err == nil { |
| + t.Errorf("%q booted", bad) |
| + } |
| + } |
| +} |