Docs serves the suite contract's producer half for memoria, and gains a Team sharing rung
Paul, 2026-11-01: "New docs Team, old private" — a Team rung (read for every admitted member; edit stays owner + writer grants), the default for new documents, never for existing ones or samples; and suite revision 10, "Hold private too, check per person" — Docs sends memoria every live document and S2 is Docs' own per-person read check (team rung for a member, ownership, a live grant, never a link), never cached. Migration 0011_suite (visibility, revision, suite_feed); the Team clause in permissionScope (read only); share page "Your team"; producer through amadan.net/oficina/suite/server at c38e3ad: S1 pages suite_feed with random-nonce cursors, S2 person-first with STALE from the document's own log and team standing re-checked after the last read, S3 current revision only. Revisions are random positive int63s (62 bits in the migration), so a restore can never reissue one memoria holds. Exact routes on the outer mux, outside session/admission/CSRF, only when DOCS_SUITE_CONSUMERS is set. Agent-access writes (5039cf6) go through the same paths. Spec §8.2, §8.2.1, §8.2.2, §14a; AGENTS.md invariants. Reviewed: GPT-6 (Codex, Astra) four rounds, APPROVE on 65acd67; Claude Fable 5.1 whole-branch, APPROVE on 74c255a, follow-ups in ece6d6e. Discussion oficina/docs #103. Hub CI green. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/suite-producer into main.
47 files changed,
+3,104
−75
AGENTS.md+44 −0cmd/docs/main.go+5 −0docs/superpowers/specs/2026-08-30-docs-design.md+247 −9fixtures/generate-suite.mjs+32 −0fixtures/vectors/suite/doc-granted.update.binbinaryfixtures/vectors/suite/doc-guest.update.binbinaryfixtures/vectors/suite/doc-link-added-late.update.binbinaryfixtures/vectors/suite/doc-link.update.binbinaryfixtures/vectors/suite/doc-private.update.binbinaryfixtures/vectors/suite/doc-team-link.update.binbinaryfixtures/vectors/suite/doc-team.update.binbinaryfixtures/vectors/suite/doc-was-team.update.binbinarygo.mod+1 −0go.sum+2 −0internal/docs/agent_access_test.go+3 −1internal/docs/app.go+31 −1internal/docs/dashboard_test.go+3 −3internal/docs/export_test.go+1 −1internal/docs/guest_test.go+29 −7internal/docs/handlers.go+5 −0internal/docs/home_router_integration_test.go+3 −3internal/docs/identity_test.go+3 −3internal/docs/migrations/0011_suite.sql+63 −0internal/docs/models.go+46 −0internal/docs/native_test.go+5 −0internal/docs/nowebfont_test.go+1 −1internal/docs/render.go+16 −0internal/docs/search_test.go+1 −1internal/docs/seed.go+1 −1internal/docs/share.go+69 −1internal/docs/share_test.go+20 −3internal/docs/shared_list_test.go+5 −5internal/docs/store.go+46 −5internal/docs/store_test.go+1 −2internal/docs/stream_test.go+1 −1internal/docs/suite.go+450 −0internal/docs/suite_agent_test.go+213 −0internal/docs/suite_feed.go+163 −0internal/docs/suite_test.go+1,483 −0internal/docs/team_access.go+50 −13internal/docs/team_access_test.go+15 −3internal/docs/team_identity_test.go+1 −1internal/docs/team_router_test.go+3 −3internal/docs/testing.go+22 −6internal/docs/updates_test.go+1 −1internal/docs/views/share.html+17 −0internal/shipped/shipped.go+2 −0
CI passed — run details
landed from feat/suite-producer
diff --git a/AGENTS.md b/AGENTS.md| index 00d254e..165533b 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -103,6 +103,50 @@ the same fail-closed shape `Origin`/`InstanceKey`/`Mailer` already use, |
| chosen over silently admitting nobody because a silently-empty allowlist |
| would boot looking identical to a working instance. |
| +### Suite consumers (`$DOCS_SUITE_CONSUMERS`, spec §8.2.2) |
| + |
| +The siblings allowed to call Docs' suite routes (memoria, today). Strict |
| +JSON, one entry per consumer, one or two tokens each (two only while a |
| +token is being rotated): |
| + |
| + [{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}] |
| + |
| +`sha256` is the hex SHA-256 of the bearer token the operator minted for |
| +that consumer — `server.TokenHash(token)` in `amadan.net/oficina/suite/server` |
| +— never the token itself. Unset or empty: no consumers, and `/suite/*` |
| +answers 404 like any unknown path. Anything malformed (not a list, an |
| +empty list, `null`, an unknown field, a non-hex or wrong-length hash, a |
| +repeated or empty `consumer_id`, three tokens) refuses boot. |
| + |
| +## The suite producer: invariants (spec §8.2.2) |
| + |
| +Docs serves suite S1/S2/S3 to memoria and holds every live document to the |
| +suite revision 10 rules. Break one of these and memoria can show somebody a |
| +document they may no longer read; the reasoning and the review history are |
| +in spec §8.2.2. |
| + |
| +- **Every write that changes what S3 serves moves the revision in the same |
| + transaction**: call `bumpRevision` (`internal/docs/suite_feed.go`) inside |
| + the transaction that makes the change — content, title, visibility, |
| + deletion, and anything new that changes the title or the text. It draws a |
| + new random revision and writes the `suite_feed` row; if either fails the |
| + change must not commit. Creation goes through `createDocument`. |
| +- **Any delete verb goes through `Store.deleteDocument`**, which announces |
| + the document gone. A delete that only sets `deleted_at` leaves memoria |
| + holding it. |
| +- **Revisions and feed nonces come only from `randomSource`** |
| + (`crypto/rand`). A failed read is an error that stops the change; never |
| + fall back to a clock, a counter or `math/rand`, which a restore or |
| + anybody else can reproduce. Revisions have no order: S2's `STALE` is read |
| + from `suite_feed`, never from comparing numbers. |
| +- **S2 never caches** — not an answer, not a person's standing, not across |
| + pairs of one call. Team standing is asked again after the last database |
| + read (`suiteProducer.Rule`). |
| +- **Exactly three suite routes sit on the outer mux** (`mountSuite`): |
| + `GET /suite/s1`, `POST /suite/s2`, `GET /suite/s3/{item}`, outside the |
| + session, admission and `homeCSRF` layers. Never a prefix, and nothing |
| + else outside the router. |
| + |
| ## Running it locally |
| `./scripts/run-dev.sh` builds and runs the app in one command: `-env |
diff --git a/cmd/docs/main.go b/cmd/docs/main.go| index 09cd4d5..e5ae0ad 100644 |
| --- a/cmd/docs/main.go |
| +++ b/cmd/docs/main.go |
| @@ -11,6 +11,7 @@ import ( |
| "syscall" |
| "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/suite/server" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/mail" |
| @@ -287,6 +288,10 @@ func main() { |
| // The hub directory the app switcher's "All apps" goes to. The |
| // same variable Home itself reads (home origins.go). |
| Directory: os.Getenv("HOME_DIRECTORY_ORIGIN"), |
| + // The suite consumers (spec §8.2.2): $DOCS_SUITE_CONSUMERS, named by |
| + // the contract's own suffix. Unset serves no suite routes; malformed |
| + // is a refusal in docs.New. |
| + SuiteConsumers: os.Getenv("DOCS" + server.EnvSuffix), |
| } |
| home := docs.HomeConfig{Issuer: os.Getenv("DOCS_HOME_ISSUER"), ConsumerID: os.Getenv("DOCS_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("DOCS_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("DOCS_HOME_DEK_BASE64")} |
| if home.Issuer != "" || home.ConsumerID != "" || home.KeysBase64 != "" || home.DEKBase64 != "" { |
diff --git a/docs/superpowers/specs/2026-08-30-docs-design.md b/docs/superpowers/specs/2026-08-30-docs-design.md| index 28d8d7d..86a68ca 100644 |
| --- a/docs/superpowers/specs/2026-08-30-docs-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-docs-design.md |
| @@ -594,18 +594,241 @@ ruling 2). A link does not move data — whoever holds it reads the document |
| here, on this instance — so it forbids nothing here. |
| **Within a team, Docs is one of several apps sharing one trust domain** |
| -(suite ruling 1). Same-team siblings may pull team-visible documents under |
| -the suite contract, and Docs serves S1, S2, S3 and S8 wherever sibling |
| -consumer tokens are in its platform config. That switch is independent of |
| -whether a home is present (suite §3): Docs serves a lone memoria with no |
| -home in the picture. |
| +(suite ruling 1). Same-team siblings may pull documents under the suite |
| +contract, and Docs serves S1, S2 and S3 wherever sibling consumer tokens are |
| +in its platform config (§8.2.2). S8 is not served yet (§14a). That switch is |
| +independent of whether a home is present (suite §3): Docs serves a lone |
| +memoria with no home in the picture. |
| **Only the team rung is team-visible** (suite ruling 15). A document that is |
| private, granted to named people, or reachable only by link is never |
| -team-visible, so no sibling may hold a copy of it — and §8.2's existing rule |
| -that a link share is *viewer or commenter, never editor* is the rule suite |
| -ruling 15 adopts suite-wide. It stays here as the original; the doctrine |
| -cites it rather than restating it. |
| +team-visible — and §8.2's existing rule that a link share is *viewer or |
| +commenter, never editor* is the rule suite ruling 15 adopts suite-wide. It |
| +stays here as the original; the doctrine cites it rather than restating it. |
| + |
| +> **Suite revision 10 (Paul, 2026-11-01, commit `c38e3ad`) changes what a |
| +> sibling may hold, not what the rung means.** This paragraph used to end |
| +> "so no sibling may hold a copy of it". Revision 10's notes at §4.2 and |
| +> §4.3 overrule that: a consumer holds every live document, and the rung |
| +> decides who may read one only through Docs' own read check, asked per |
| +> person through S2. §8.2.2 is how Docs serves that. |
| + |
| +### 8.2.1 The team rung (Paul, 2026-11-01) |
| + |
| +Paul's ruling, 2026-11-01, asked how Docs' sharing should default once a |
| +document could be shared with the whole team: **"New docs Team, old |
| +private."** A document created from now on is on the `team` rung unless its |
| +owner makes it private; a document that already existed stays private until |
| +its owner shares it. Suite revision 10's status block records the same |
| +ruling. |
| + |
| +- **The column.** `documents.visibility` is `private` or `team` |
| + (migration `0011_suite.sql`, a CHECK holding the two values). The |
| + migration's column default is `private`, which is what every existing row |
| + gets. `Store.Create`/`CreateDraft` write `team` explicitly; nothing writes |
| + the empty string. |
| +- **One exception: the sample library is private.** The six sample documents |
| + `EnsurePerson` seeds (`Config.SampleDocuments`) are one person's welcome |
| + content, and on the team rung every member's copies would sit in every |
| + other member's list. `Seed` creates them `private`. |
| +- **Who reads a team document.** Every admitted *member*, and only for |
| + reading. Lone shape: an address on `$DOCS_ALLOWED_ADDRESSES` |
| + (`allowlist.configured`) — a guest admitted only by a grant is not a |
| + member and gets nothing from the rung. Team mode: a person whose roster |
| + standing is `Member` under a current lease. `NotMember` gets nothing; |
| + `Unknown` gets nothing from the rung, exactly as it gets nothing from |
| + ownership, and a list built under it is partial as before. |
| +- **Editing is unchanged.** The owner and writer grants edit; the team rung |
| + never writes, never shares and never publishes. Links and grants do what |
| + they did. |
| +- **One predicate.** The rung is a third clause of `Store.permissionScope` |
| + (`team_access.go`) for `permissionRead` only, so `GetFor`, `ListFor`, |
| + the export routes, the stream, the update log and S2 all read it from the |
| + same place. It never reads `links`. |
| +- **The control.** The share page carries a "Your team" section that says |
| + in words which side the switch is on, then one plain form ("Make |
| + private" / "Share with your team") with the direction in a hidden field |
| + (the shape the public link already uses), owner- and member-only like |
| + granting, `POST /d/{sqid}/share/team` and a 303 back. No script. The |
| + list marks a team document someone else owns "Shared with your team". |
| + The native apps get `visibility` in the share JSON and the same route; |
| + their UI for it is not built yet. |
| + |
| +### 8.2.2 Serving the suite contract (suite revision 10) |
| + |
| +Docs implements `server.Producer` from `amadan.net/oficina/suite/server` |
| +(suite §6.5, read at commit `c38e3ad`) and mounts `server.Handler`. The |
| +package owns the bearer check, the wire shapes, the S2 decode and cap and |
| +S3's one refusal; what follows is only the part Docs owes. Custody is every |
| +live document, per revision 10's §4.2 and §4.3 notes, which are cited and |
| +not restated. |
| + |
| +**The revision counter.** `documents.revision` moves, in the same writer |
| +transaction as the change, on creation and on every applied update |
| +(`ApplyUpdate`), rename, visibility change and deletion. `doc_updates.seq` |
| +alone misses renames, and a rename changes S3's bytes. A grant, a revoke or |
| +a link changes who may read, which S2 asks live, so none of them moves it. |
| +Each new value — on every change, on creation, and in migration 0011 for |
| +every document that existed before it — is **a fresh random positive |
| +value**, never the current one. In code it is 63 random bits from Go's |
| +`crypto/rand` (a zero, or the current value, is drawn again; a source that |
| +cannot be read is an error and the change does not commit — nothing falls |
| +back to a clock or a counter). In migration 0011 it is SQLite's `random()` |
| +masked to 63 bits and forced odd, so **62 random bits**; SQLite's PRNG is |
| +ChaCha20 (verified in modernc.org/sqlite v1.55.0), seeded from the OS |
| +(`/dev/urandom`), and falls back to the time and the process id if that |
| +cannot be opened. It is a token, not a count: it has no order. That is |
| +enough because **memoria only ever matches revisions for equality** — |
| +verified in memoria `origin/main` `f002955`, `internal/memoria/models.go` |
| +(`SiblingRevision`: "Never compared, only matched for equality"), and its |
| +uses in `store.go` and `agent_response.go` are `==`/`!=` with 0 as the |
| +"not a sibling" sentinel — and S2's `STALE` is read from Docs' own log |
| +(below), never from comparing two numbers. |
| + |
| +**The feed log.** `suite_feed (id AUTOINCREMENT, document_id, revision, |
| +gone, touched_at, stamp)` is append-only and written in the same |
| +transaction as each bump, creation included; a change whose feed row cannot |
| +be written does not commit. `stamp` is a random positive nonce, written |
| +once with the row (the backfill rows too). Migration `0011` writes one row per live |
| +document that existed before it, so a consumer's first poll sees the whole |
| +library. *Live* is `deleted_at IS NULL AND owner_id > 0`: the orphans |
| +`0002_owners.sql` made are readable by nobody and are not fed. |
| + |
| +**S1.** Pages the log by `id`, 256 rows (`server.FeedPageLimit`). The cursor |
| +is `"<id>.<stamp>"` of the last row served, in canonical decimals; `""` and |
| +`"0"` are the beginning. The stamp is checked against the row on every |
| +request, and a cursor whose row is gone or carries another stamp — or any |
| +cursor Docs did not issue — is an error, which the suite package answers |
| +503: never a page, never a guess at a position. At the tip Docs returns the |
| +cursor it was given and no rows. Every |
| +row is emitted, so a document edited ten times since the last poll appears |
| +ten times; the earlier rows name revisions that are no longer current, S3 |
| +answers them 404, and the consumer counts them missing until the last row |
| +supersedes them. `item_id` is the document's sqid; `gone` is true only on |
| +a deletion's row. |
| + |
| +**S2.** The asker is mapped to the actor Docs keys on in its current shape: |
| +`address` in lone shape (grants and admission key on it; the person row is |
| +looked up and never created), `person_ref` in team mode (the Home subject, |
| +through connect's link and then the Home-only principal, exactly as a |
| +signed-in request resolves it, and the roster standing for that subject). |
| +In team mode standing is asked again **after** the reads, from the |
| +request's latched access: if it is no longer `Member` the readable set is |
| +read again without the membership clauses, so the team rung and ownership |
| +answer `UNKNOWN` (or `NOT_VISIBLE` for a `NotMember`) and only an |
| +independent address grant stays `VISIBLE`. A lease that runs out mid-call |
| +can neither hide a document silently nor authorise one. An |
| +asker of the other kind answers `UNKNOWN` for every pair. In lone shape an |
| +address that would not pass the front door (`allowlist.allows`: a configured |
| +member, or a holder of a live grant) is refused like any other stranger. |
| +Then, for each pair: a deleted or unknown id is `NOT_VISIBLE`; a document |
| +the actor may not read through `permissionScope` is `NOT_VISIBLE`, or |
| +`UNKNOWN` when team standing is `Unknown`; a readable one is `VISIBLE` at |
| +the current revision, `STALE` at a revision **this document's `suite_feed` |
| +rows hold** (one it had and has moved on from — doctrine §4.3, "compare |
| +the asked revision against your log"), and `UNKNOWN` at any other value: |
| +one never issued, another document's, or one issued before a restore that |
| +the restored log does not hold. The person is checked before the |
| +revision. A Home subject with no Docs principal yet still reads the |
| +team rung by standing alone, since its first sign-in would. Nothing is |
| +cached: every call reads the roster lease and the database afresh. |
| + |
| +**S3.** The current revision only; anything else is |
| +`suite.ErrNotAvailable`, as is a deleted or unknown id. The body is plain |
| +UTF-8: the title, a blank line, then `Store.Text`. An untitled document is |
| +its text alone. The revision is read again after the text is replayed and a |
| +change answers `ErrNotAvailable`, so a body is never labelled with a |
| +revision it does not match. S3 carries no person, so it does not consult |
| +`permissionScope`. |
| + |
| +**Restore from a backup (Astra's review, two rounds, 2026-11-01).** What is |
| +protected: a revision or a feed position issued before a restore is never |
| +issued again after it, whatever the clock and whenever the backup was |
| +taken. Three ways of breaking that were found and are closed: |
| + |
| +- *Counted revisions* reissued the held value: a private draft backed up, |
| + renamed to confidential text and held by memoria, restored and shared |
| + with the team, answered S2 `VISIBLE` for a teammate against the |
| + confidential copy. AUTOINCREMENT reissued feed ids too, so memoria's |
| + cursor met a tip that said nothing had changed. |
| +- *Clock-floored revisions* (this branch's first fix) reissued it when the |
| + restore landed on a clock set back to the confidential edit's time, which |
| + the first fix's own allowance permitted. |
| +- *A backup taken before migration 0011*, restored and migrated again, |
| + gave its harmless, still-granted document the same revision the first |
| + migration gave the confidential one. |
| + |
| +Revisions and feed nonces are random now, here and in the migration, so the |
| +protection is **probabilistic, with no assumption about the clock**. Per |
| +draw: a new value equals one particular earlier value with probability |
| +2^-63 from code and 2^-62 from the migration (for nonces too). Cumulative: |
| +what matters is one document — S2 matches `(item, revision)` — so for a |
| +document whose history held N revisions before a restore and is given M |
| +new ones after it, the chance that any new one equals any old one is at |
| +most N·M·2^-62 (a million each side: about 2×10^-7). A cursor fails to be |
| +refused only if the row now at its id drew the same nonce, 2^-63 or 2^-62 |
| +per cursor. Barring that, a pre-restore copy is `UNKNOWN` (its revision is |
| +not in the restored log), withheld loudly, and a pre-restore cursor is a |
| +503. The migration's fallback seed (time and pid, when `/dev/urandom` |
| +cannot be opened) would weaken only migration-issued values, once. Kept as defence in depth: that persistent S1 error is the |
| +signal, not something to retry past — **after a restore memoria must drop |
| +everything it holds from Docs and its Docs cursor, and re-read from |
| +`""`.** |
| + |
| +**The delegated agent API (main `5039cf6`) and this section.** Its |
| +`docs_create` and `docs_update` write through `CreateDraft` and |
| +`ApplyUpdate` inside their own writer transaction, so an agent-created |
| +document is on the team rung, its revisions are drawn by `newRevision`, |
| +every change is announced in `suite_feed` in the same transaction, and a |
| +change whose feed row cannot be written rolls the agent's receipt and |
| +attribution back with it. Its `body_revision`, `expected_revision` and |
| +acknowledged `revision` are a different number: `doc_updates.seq`, as a |
| +decimal string, compared for equality against the current sequence for |
| +optimistic concurrency. Nothing in the agent API reads or exposes |
| +`documents.revision`, and nothing here reads the sequence, so the two never |
| +meet; the shared word is the only overlap. The suite migration is |
| +`0011_suite.sql`, after the agent API's `0009` and `0010`. |
| + |
| +**`DOCS_SUITE_CONSUMERS`.** `server.EnvSuffix`'s variable, strict JSON: |
| +`[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}]`, |
| +one or two tokens per consumer, each the SHA-256 of a token the operator |
| +mints. Unset or empty: no consumers, and `/suite/*` is the 404 every |
| +unknown path gets. Malformed: `New` refuses to start. |
| + |
| +**Where it is mounted.** On the outer `ServeMux` beside the chi router, as |
| +exactly `GET /suite/s1`, `POST /suite/s2` and `GET /suite/s3/{item}`. So it |
| +sits outside the session and admission groups and outside `homeCSRF`, which |
| +memoria's `POST /suite/s2` would fail (it sends only `Authorization`, no |
| +`Origin` and no `Sec-Fetch-Site`). Every other path, `/suite/` prefix |
| +included, still goes through the router and its CSRF check. |
| + |
| +**What is plaintext.** S3's body leaves Docs as plaintext to a |
| +bearer-authenticated consumer: the content sealing (`content_cipher.go`) |
| +protects bytes at rest, and S3 is a read of them like the editor's. |
| +`suite_feed` holds ids, revisions and times only; `visibility` and |
| +`revision` are metadata beside the `title` column that was already |
| +plaintext. Nothing here logs a title or text. |
| + |
| +**Gates.** `conformance.RunAs(…, suite.SubjectAddress)` from |
| +`amadan.net/oficina/suite/conformance` runs in `go test ./...` against the |
| +real producer over a lone-shape store seeded with `fixtures/custody.json`'s |
| +world (the fixture's asker and stranger become addresses, a member and a |
| +non-member), and `conformance.Run` (person_ref) against the same world in |
| +team mode, with the asker on the roster and the stranger off it. Docs' own tests hold the team |
| +default and the migrated private rows, the rung for a member and not a |
| +non-member, S1 paging, the tip, `gone` and every bump, every S2 branch, S3's |
| +current-only rule, the CSRF exemption being exactly the three routes, no |
| +consumers meaning no routes, and the 401; and, from Astra's review, the |
| +three restore sequences above with real SQLite backups, `STALE` read from |
| +the log (a revision from the document's history is `STALE`; a value never |
| +issued, or another document's, is `UNKNOWN`, asked of two documents in one |
| +batch), both redraws forced through a scripted random source and a broken |
| +one refused, the custody fixture seeded |
| +with each item's revision − 1 in its log, a lease running out (before, between and after S2's reads) |
| +before and after S2's reads, a change whose feed row cannot be written not |
| +committing, a lone-shape guest answered 404 by every sharing route, and |
| +the agent API's create and edit held to the same (team default, scripted |
| +random draws, a feed row each, rollback without it). |
| --- |
| @@ -1143,6 +1366,21 @@ Docs does **not** restate any of them. Where this spec previously did — the |
| five-call contract in §9.1, the instance boundary in §8.2, the egress reason |
| in §11.2 — the restatement has been replaced by a citation. |
| +**Suite revision 10, commit `c38e3ad` (2026-11-01), consumed for the producer |
| +half.** Paul's ruling that day, **"Hold private too, check per person"**, |
| +widens custody to every live item; the revision's notes at §4.2 and §4.3 and |
| +its new §6.5 (the producer package) are what §8.2.2 implements. Docs cites |
| +them by number and does not restate them. Where rulings 3 and 14 above |
| +speak of custody as team-visible items, revision 10's §4.2 note governs. |
| +`c38e3ad` is suite `main` after the revision's review (GPT-6 Astra, two |
| +rounds); §8.2.2 was built against it, conformance included. |
| + |
| +**Docs imports the contract module under its old path.** Suite §10 says Docs |
| +moves from `github.com/carlosframework/docs` to `amadan.net/oficina/docs` |
| +before it imports the contract. Importing works without the move — `go get |
| +amadan.net/oficina/suite@c38e3ad` resolves through the hub — so the move |
| +stays a follow-up of its own rather than riding this change. |
| + |
| **Not yet consumed**, because they need work this spec has not specified: |
| the hand-off (suite §7.1), which needs a receipt route, pending state and a |
| confirmation step on the create endpoint; and S8 write-as-self (suite §7.2), |
diff --git a/fixtures/generate-suite.mjs b/fixtures/generate-suite.mjs| new file mode 100644 |
| index 0000000..2167385 |
| --- /dev/null |
| +++ b/fixtures/generate-suite.mjs |
| @@ -0,0 +1,32 @@ |
| +// Generates the documents the suite conformance test seeds Docs with |
| +// (internal/docs/suite_test.go): one real Yjs update per case of the suite |
| +// contract's custody fixture, a single paragraph holding that case's |
| +// s3_body, on the "prosemirror" root Store.Text reads. Run from fixtures/ |
| +// with the fixture's path: |
| +// |
| +// node generate-suite.mjs "$(go list -m -f '{{.Dir}}' amadan.net/oficina/suite)/fixtures/custody.json" |
| +// |
| +// The client id is pinned so the bytes are reproducible, as in |
| +// generate-fragment.mjs. A fixture whose text changes needs this rerun; the |
| +// conformance test fails on the body until it is. |
| +import * as Y from 'yjs' |
| +import { writeFileSync, mkdirSync, readFileSync } from 'node:fs' |
| + |
| +const path = process.argv[2] |
| +if (!path) { |
| + console.error('usage: node generate-suite.mjs <custody.json>') |
| + process.exit(2) |
| +} |
| +const fixture = JSON.parse(readFileSync(path, 'utf8')) |
| +mkdirSync('vectors/suite', { recursive: true }) |
| +for (const c of fixture.cases) { |
| + if (!c.s3_body) continue |
| + const doc = new Y.Doc() |
| + doc.clientID = 1 |
| + const p = new Y.XmlElement('paragraph') |
| + const t = new Y.XmlText() |
| + t.insert(0, c.s3_body) |
| + p.insert(0, [t]) |
| + doc.getXmlFragment('prosemirror').insert(0, [p]) |
| + writeFileSync(`vectors/suite/${c.item_id}.update.bin`, Y.encodeStateAsUpdate(doc)) |
| +} |
diff --git a/fixtures/vectors/suite/doc-granted.update.bin b/fixtures/vectors/suite/doc-granted.update.bin| new file mode 100644 |
| index 0000000..f8d906d |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-granted.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-guest.update.bin b/fixtures/vectors/suite/doc-guest.update.bin| new file mode 100644 |
| index 0000000..a07248c |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-guest.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-link-added-late.update.bin b/fixtures/vectors/suite/doc-link-added-late.update.bin| new file mode 100644 |
| index 0000000..a2edcba |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-link-added-late.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-link.update.bin b/fixtures/vectors/suite/doc-link.update.bin| new file mode 100644 |
| index 0000000..26b3cb3 |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-link.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-private.update.bin b/fixtures/vectors/suite/doc-private.update.bin| new file mode 100644 |
| index 0000000..bce5bd5 |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-private.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-team-link.update.bin b/fixtures/vectors/suite/doc-team-link.update.bin| new file mode 100644 |
| index 0000000..2f46753 |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-team-link.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-team.update.bin b/fixtures/vectors/suite/doc-team.update.bin| new file mode 100644 |
| index 0000000..b29d002 |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-team.update.bin differ |
diff --git a/fixtures/vectors/suite/doc-was-team.update.bin b/fixtures/vectors/suite/doc-was-team.update.bin| new file mode 100644 |
| index 0000000..754e730 |
| Binary files /dev/null and b/fixtures/vectors/suite/doc-was-team.update.bin differ |
diff --git a/go.mod b/go.mod| index e946b02..85516d6 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -10,6 +10,7 @@ require ( |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af |
| + amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 |
| github.com/carlosframework/rastrillo v0.23.0 |
diff --git a/go.sum b/go.sum| index 0434a0f..e530b99 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -16,6 +16,8 @@ amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af h1:YtDEq1YUm87 |
| amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af h1:QsC+WKvYxiKipS3+J4D9YWRmKQ+cJJTevlH6kP8UVhA= |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| +amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 h1:LXUZq/L5aJ700z9A//W5G04O/lxsUSRZrBK1mrBEIP4= |
| +amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 h1:ybFov1+wRduFtkxTn44QnzCKTDhyjfFWxWsW+cKaAyk= |
diff --git a/internal/docs/agent_access_test.go b/internal/docs/agent_access_test.go| index 8140d2a..2439a0f 100644 |
| --- a/internal/docs/agent_access_test.go |
| +++ b/internal/docs/agent_access_test.go |
| @@ -192,7 +192,9 @@ func TestAgentDocumentPagesUseCurrentPermissionAndExactCursor(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - doc, e := f.a.store.Create(t.Context(), other, "Private foreign title") |
| + // Private said out loud: a new document is on the team rung (Docs spec |
| + // §8.2.1), and this test is about a document the caller may not read. |
| + doc, e := f.a.store.createDocument(t.Context(), other, "Private foreign title", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
diff --git a/internal/docs/app.go b/internal/docs/app.go| index c803d36..bbef648 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -28,6 +28,7 @@ import ( |
| "amadan.net/oficina/home/dashboard" |
| "amadan.net/oficina/home/handoff" |
| "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/suite/server" |
| nativeauth "amadan.net/rastrillo/native/server" |
| "amadan.net/rastrillo/rastrillo" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| @@ -211,6 +212,15 @@ type Config struct { |
| // safety in the first place. |
| SampleDocuments string |
| + // SuiteConsumers is $DOCS_SUITE_CONSUMERS (server.EnvSuffix), the |
| + // siblings allowed to call the suite routes (spec §8.2.2; suite §6.5): |
| + // strict JSON, [{"consumer_id":"memoria","tokens":[{"epoch":1, |
| + // "sha256":"<64 hex>"}]}], each token held only as its SHA-256. Empty |
| + // means no consumers and no /suite/ routes at all; anything malformed |
| + // is a startup refusal, so a typo never boots an instance that quietly |
| + // serves nobody — or, worse, one that looks configured and is not. |
| + SuiteConsumers string |
| + |
| // Logger defaults to slog.Default(). |
| Logger *slog.Logger |
| } |
| @@ -287,6 +297,9 @@ type App struct { |
| handlers *handlers |
| mailRecorder *recordingMailer // nil outside development; see auth.go |
| signinMail *mailQueue // sign-in links, sent after the response |
| + // suite is the producer New mounted (or would have, with consumers), so |
| + // a test drives the one New built rather than assembling its own. |
| + suite *suiteProducer |
| } |
| // Drain ends every open live-update stream and refuses new ones. Call it |
| @@ -395,6 +408,12 @@ func New(cfg Config) (*App, error) { |
| if err != nil { |
| return nil, err |
| } |
| + // Parsed before anything opens: a malformed consumer list refuses boot. |
| + // The error names no token, only that the list is not the agreed shape. |
| + consumers, err := server.ParseConsumers(cfg.SuiteConsumers) |
| + if err != nil { |
| + return nil, fmt.Errorf("docs: $DOCS_SUITE_CONSUMERS: %w", err) |
| + } |
| cipher, err := newContentCipher(cfg.ContentKey, cfg.Env) |
| if err != nil { |
| @@ -455,6 +474,8 @@ func New(cfg Config) (*App, error) { |
| // The sample library is for members. A guest admitted by a grant is |
| // visiting, not moving in. |
| store.seedOnlyMembers = list.configured |
| + // The team rung's readers in lone shape: members, never guests. |
| + store.members = list.configured |
| // Home: connect's Bridge, then the one-time move of Docs' own links |
| // into connect's table (home_links_move.go). connect.New has swept |
| // already, nothing else is running, and the team census below reads |
| @@ -759,6 +780,7 @@ func New(cfg Config) (*App, error) { |
| r.Post("/d/{sqid}/share", h.sharePost) |
| r.Post("/d/{sqid}/share/revoke", h.shareRevoke) |
| r.Post("/d/{sqid}/share/link", h.shareLink) |
| + r.Post("/d/{sqid}/share/team", h.shareTeam) |
| r.Get("/d/{sqid}/updates", h.updatesGet) |
| r.Post("/d/{sqid}/updates", h.updatesPost) |
| @@ -791,9 +813,17 @@ func New(cfg Config) (*App, error) { |
| mux.Handle("/api/v1/operations", agentHandler) |
| mux.Handle("/api/v1/operations/", agentHandler) |
| } |
| + // The suite contract's producer half (suite.go), beside the router |
| + // rather than in it. A grant admits its holder here exactly as it does |
| + // at the front door, so S2 reads the same allowlist the router does. |
| + producer := &suiteProducer{store: store, list: list} |
| + if store.team != nil { |
| + producer.subjects = home.bridge |
| + } |
| + mountSuite(mux, server.Handler(producer, consumers, logger)) |
| built = true |
| - return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder, signinMail: signinMail}, nil |
| + return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder, signinMail: signinMail, suite: producer}, nil |
| } |
| // Store returns the app's document store — models.go's Document, |
diff --git a/internal/docs/dashboard_test.go b/internal/docs/dashboard_test.go| index b462f37..b1724c1 100644 |
| --- a/internal/docs/dashboard_test.go |
| +++ b/internal/docs/dashboard_test.go |
| @@ -23,15 +23,15 @@ func TestDashboardUsesExistingAccountAndDocumentGrants(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - own, e := s.Create(ctx, alice, "Own") |
| + own, e := s.createDocument(ctx, alice, "Own", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
| - shared, e := s.Create(ctx, bob, "Shared") |
| + shared, e := s.createDocument(ctx, bob, "Shared", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
| - if _, e = s.Create(ctx, bob, "Private"); e != nil { |
| + if _, e = s.createDocument(ctx, bob, "Private", "", VisibilityPrivate); e != nil { |
| t.Fatal(e) |
| } |
| if e = s.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); e != nil { |
diff --git a/internal/docs/export_test.go b/internal/docs/export_test.go| index 7cca92f..9c41273 100644 |
| --- a/internal/docs/export_test.go |
| +++ b/internal/docs/export_test.go |
| @@ -20,7 +20,7 @@ func exportable(t *testing.T, app *App, address, title string) *Document { |
| t.Helper() |
| ctx := context.Background() |
| owner := app.TestPerson(t, address) |
| - doc, err := app.Store().Create(ctx, owner, title) |
| + doc, err := app.Store().createDocument(ctx, owner, title, "", VisibilityPrivate) |
| if err != nil { |
| t.Fatalf("Create: %v", err) |
| } |
diff --git a/internal/docs/guest_test.go b/internal/docs/guest_test.go| index 7524cb3..573050d 100644 |
| --- a/internal/docs/guest_test.go |
| +++ b/internal/docs/guest_test.go |
| @@ -59,13 +59,35 @@ func TestAGuestCannotCreateOrShare(t *testing.T) { |
| // produces for Bob on Alice's document — so deleting the member guard |
| // from sharePost left it green. The re-review caught that by mutation: |
| // three of the four guarded routes had never been exercised at all. |
| - for _, c := range []struct{ what, path, body string }{ |
| - {"share", "/d/" + sqid + "/share", "address=mallory@example.com&role=writer"}, |
| - {"revoke", "/d/" + sqid + "/share/revoke", "address=alice@example.com"}, |
| - {"publish", "/d/" + sqid + "/share/link", "on=1"}, |
| - } { |
| - if rec := post(t, app, bob, c.path, c.body); rec.Code != http.StatusForbidden { |
| - t.Errorf("guest %s: status %d, want 403 from the member guard", c.what, rec.Code) |
| + // |
| + // 404 since 2026-11-01 (Astra): a route about one document answers a |
| + // guest as one about a document they cannot reach, never 403, as team |
| + // mode always has. The owner check answers Bob 404 on Alice's document |
| + // too, so the guard is only visible on a document the guest OWNS: Carol |
| + // below owns one (made before she lost her place on the list, say) and |
| + // is admitted only by a grant. Without the guard her share would 303. |
| + // |
| + // MUTATION-TESTED 2026-11-01, each reverted: shareTeam without the |
| + // member guard → "carol on her own, team rung" 303; the lone-shape guard |
| + // answering 403 whatever item says (the old code) → every case 403. |
| + carolsID := app.TestPerson(t, "carol@example.com") |
| + carols := app.TestCreatePrivate(t, carolsID, "Carol's own").Sqid |
| + post(t, app, alice, "/d/"+sqid+"/share", "address=carol@example.com&role=reader") |
| + carol := signInCookies(t, app, "carol@example.com") |
| + for _, who := range []struct { |
| + name string |
| + cookies []*http.Cookie |
| + sqid string |
| + }{{"bob on alice's", bob, sqid}, {"carol on her own", carol, carols}, {"bob on none", bob, "zzzzzzzzzz"}} { |
| + for _, c := range []struct{ what, path, body string }{ |
| + {"share", "/share", "address=mallory@example.com&role=writer"}, |
| + {"revoke", "/share/revoke", "address=alice@example.com"}, |
| + {"publish", "/share/link", "on=1"}, |
| + {"team rung", "/share/team", "visibility=team"}, |
| + } { |
| + if rec := post(t, app, who.cookies, "/d/"+who.sqid+c.path, c.body); rec.Code != http.StatusNotFound { |
| + t.Errorf("guest %s, %s: status %d, want 404", who.name, c.what, rec.Code) |
| + } |
| } |
| } |
| } |
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go| index 57c7b11..dae406a 100644 |
| --- a/internal/docs/handlers.go |
| +++ b/internal/docs/handlers.go |
| @@ -1045,6 +1045,11 @@ func sharedNote(r *http.Request, d *Document, mine int64) string { |
| if d.OwnerID == mine { |
| return "" |
| } |
| + // A team document reads as the team's, whether or not the reader also |
| + // holds a grant on it: that is the wider of the two, and the true one. |
| + if d.Visibility == VisibilityTeam { |
| + return rastrillo.T(r, "docs.list.team") |
| + } |
| return rastrillo.T(r, "docs.list.shared") |
| } |
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go| index b737b96..278b4c1 100644 |
| --- a/internal/docs/home_router_integration_test.go |
| +++ b/internal/docs/home_router_integration_test.go |
| @@ -218,15 +218,15 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes |
| if err != nil { |
| t.Fatal(err) |
| } |
| - own, err := s.Create(ctx, alice, "Alice original") |
| + own, err := s.createDocument(ctx, alice, "Alice original", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - shared, err := s.Create(ctx, bob, "Bob shared") |
| + shared, err := s.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - hidden, err := s.Create(ctx, bob, "Bob private") |
| + hidden, err := s.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/docs/identity_test.go b/internal/docs/identity_test.go| index 19fc08a..41ffafe 100644 |
| --- a/internal/docs/identity_test.go |
| +++ b/internal/docs/identity_test.go |
| @@ -87,15 +87,15 @@ func TestLinkedHomeIdentityPreservesOwnersAndAddressGrants(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - own, err := store.Create(ctx, alice, "Alice private") |
| + own, err := store.createDocument(ctx, alice, "Alice private", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - shared, err := store.Create(ctx, bob, "Bob shared") |
| + shared, err := store.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - hidden, err := store.Create(ctx, bob, "Bob private") |
| + hidden, err := store.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/docs/migrations/0011_suite.sql b/internal/docs/migrations/0011_suite.sql| new file mode 100644 |
| index 0000000..f220cc2 |
| --- /dev/null |
| +++ b/internal/docs/migrations/0011_suite.sql |
| @@ -0,0 +1,63 @@ |
| +-- The team rung, and the revision counter and feed log the suite contract's |
| +-- producer half reads (spec §8.2.1 and §8.2.2; suite revision 10, suite |
| +-- main c38e3ad). |
| +-- |
| +-- visibility: Paul's ruling, 2026-11-01, "New docs Team, old private". The |
| +-- column DEFAULT is 'private', and that default is the half of the ruling |
| +-- this migration carries: every document that exists when it runs stays |
| +-- private until its owner shares it. New documents are written 'team' |
| +-- explicitly by Store.CreateDraft; nothing relies on this default for them. |
| +-- The CHECK keeps the vocabulary closed, so a typo is a loud write failure |
| +-- rather than a third value every reader treats as private. |
| +ALTER TABLE documents ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private' |
| + CHECK (visibility IN ('private', 'team')); |
| + |
| +-- revision: a token per document, replaced in the same writer transaction |
| +-- as every applied update, rename, visibility change and deletion. Not |
| +-- doc_updates.seq, which a rename never touches although a rename changes |
| +-- what S3 serves. Every value is a fresh random positive int63 |
| +-- (newRevision), here and in code, never a count and never a clock: after a |
| +-- restore from a backup a count or a clock issues again a value issued |
| +-- before, for different content, and a consumer's copy would be answered as |
| +-- current (Astra on oficina/docs feat/suite-producer, two rounds, |
| +-- 2026-11-01 — including a backup taken BEFORE this migration, restored and |
| +-- migrated again, which a constant here would have given the same revision |
| +-- it gave the first time). memoria only matches revisions for equality, and |
| +-- S2 decides STALE from suite_feed, so no order is needed. SQLite's random() |
| +-- is ChaCha20 seeded from the OS; masked to 63 bits and forced odd, so never |
| +-- 0 and 62 random bits (spec §8.2.2 has the probabilities). |
| +ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1 |
| + CHECK (revision >= 1); |
| +UPDATE documents SET revision = (random() & 9223372036854775807) | 1; |
| + |
| +-- suite_feed: append-only, one row per bump (creation included), written in |
| +-- the bump's own transaction, so S1 can page by id and a consumer's cursor is |
| +-- a position in this table. No title, no content, no visibility: the four |
| +-- fields suite S1 carries and a stamp, so the table holds nothing the |
| +-- plaintext gate (spec §12) would have to look at. |
| +-- |
| +-- stamp is a random positive nonce, written once with the row. The S1 |
| +-- cursor is "<id>.<stamp>" and the stamp is checked on every request: after |
| +-- a restore AUTOINCREMENT hands the same ids out again to different rows, |
| +-- and a bare id would carry on silently from a position that now means |
| +-- something else (the Fichas pattern, fichas main 7bfd4c4). Random, not a |
| +-- time, so a clock set back cannot reproduce one either. |
| +CREATE TABLE IF NOT EXISTS suite_feed ( |
| + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| + document_id INTEGER NOT NULL, |
| + revision INTEGER NOT NULL, |
| + gone INTEGER NOT NULL CHECK (gone IN (0, 1)), |
| + touched_at DATETIME NOT NULL, |
| + stamp INTEGER NOT NULL CHECK (stamp > 0) |
| +); |
| + |
| +-- Every live document that already exists is announced once, at its new |
| +-- random revision, so a consumer's first poll sees the whole library rather than only what |
| +-- changes after this deploy. Live is the producer's definition: not deleted, |
| +-- and not one of 0002_owners.sql's orphans, which nobody can read. |
| +-- Their stamps are random nonces like every other row's. |
| +INSERT INTO suite_feed (document_id, revision, gone, touched_at, stamp) |
| + SELECT id, revision, 0, updated_at, (random() & 9223372036854775807) | 1 |
| + FROM documents |
| + WHERE deleted_at IS NULL AND owner_id > 0 |
| + ORDER BY updated_at, id; |
diff --git a/internal/docs/models.go b/internal/docs/models.go| index 0522305..d3b4380 100644 |
| --- a/internal/docs/models.go |
| +++ b/internal/docs/models.go |
| @@ -55,11 +55,57 @@ type Document struct { |
| GUID string `gorm:"column:guid;not null"` |
| ClientID uint64 `gorm:"column:client_id;not null"` |
| + // Visibility is the document's rung beside grants and links: |
| + // VisibilityPrivate or VisibilityTeam (spec §8.2.1). createDocument |
| + // always writes it; the default tag only means a row built some other way |
| + // (a test inserting a Document directly) is private, as 0011 makes every |
| + // existing row, rather than an empty string the CHECK refuses. |
| + Visibility Visibility `gorm:"column:visibility;not null;default:private"` |
| + // Revision is replaced on every change a suite consumer must re-read: |
| + // every applied update, rename, visibility change and deletion, in the |
| + // same transaction (bumpRevision, suite_feed.go). Each value is a fresh |
| + // random positive int63, so a restore never reissues one; it has no |
| + // order, and S2 reads STALE from suite_feed. |
| + Revision int64 `gorm:"column:revision;not null;default:1"` |
| + |
| CreatedAt time.Time `gorm:"column:created_at;not null"` |
| UpdatedAt time.Time `gorm:"column:updated_at;not null"` |
| DeletedAt *time.Time `gorm:"column:deleted_at"` |
| } |
| +// Visibility is the team rung's switch (spec §8.2.1, Paul 2026-11-01: "New |
| +// docs Team, old private"). A link is not a rung and a grant is its own |
| +// table; this says only whether every admitted member may read it. |
| +type Visibility string |
| + |
| +const ( |
| + // VisibilityPrivate: the owner and the people it is granted to. |
| + VisibilityPrivate Visibility = "private" |
| + // VisibilityTeam: also every admitted member, for reading only. |
| + VisibilityTeam Visibility = "team" |
| +) |
| + |
| +func (v Visibility) valid() bool { return v == VisibilityPrivate || v == VisibilityTeam } |
| + |
| +// SuiteFeedRow is one row of the append-only log suite S1 pages through |
| +// (0011_suite.sql): which document, at which revision, whether that bump |
| +// deleted it, and when. Written only by bumpRevision and CreateDraft, inside |
| +// the transaction that made the change. |
| +type SuiteFeedRow struct { |
| + ID int64 `gorm:"column:id;primaryKey"` |
| + DocumentID int64 `gorm:"column:document_id;not null"` |
| + Revision int64 `gorm:"column:revision;not null"` |
| + Gone bool `gorm:"column:gone;not null"` |
| + TouchedAt time.Time `gorm:"column:touched_at;not null"` |
| + // Stamp is a random nonce written once with the row; the S1 cursor |
| + // carries it so a cursor from before a restore is refused rather than |
| + // read as a position in a log that has since been rewritten. |
| + Stamp int64 `gorm:"column:stamp;not null"` |
| +} |
| + |
| +// TableName pins the table rather than leaving it to GORM's pluralising. |
| +func (SuiteFeedRow) TableName() string { return "suite_feed" } |
| + |
| // Person is this app's own record of someone who has signed in — |
| // deliberately separate from rastrillo/auth's session Subject, which |
| // under the magic-link plugin is the verified email address itself, |
diff --git a/internal/docs/native_test.go b/internal/docs/native_test.go| index d0cbf19..9e6b271 100644 |
| --- a/internal/docs/native_test.go |
| +++ b/internal/docs/native_test.go |
| @@ -90,6 +90,11 @@ func TestNativeMetadataPreservesPermissions(t *testing.T) { |
| t.Fatalf("missing native identity: %s", created.Body.String()) |
| } |
| path := "/d/" + document.Sqid |
| + // New documents are on the team rung (spec §8.2.1); this test is about |
| + // what a grant carries, so the document goes private first. |
| + if got := nativeRequest(app, alice, "POST", path+"/share/team", "visibility=private"); got.Code != 200 { |
| + t.Fatalf("make private: %d", got.Code) |
| + } |
| if got := nativeRequest(app, bob, "GET", path, ""); got.Code != 404 { |
| t.Fatalf("foreign document: %d", got.Code) |
| } |
diff --git a/internal/docs/nowebfont_test.go b/internal/docs/nowebfont_test.go| index 44ba79d..a7cac4d 100644 |
| --- a/internal/docs/nowebfont_test.go |
| +++ b/internal/docs/nowebfont_test.go |
| @@ -69,7 +69,7 @@ func TestNoPageLinksOrPreloadsAChromeWebfont(t *testing.T) { |
| t.Fatal(err) |
| } |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| public := linkFor(t, app, alice, sqid) |
| // Someone it is not shared with meets the error page, not a 404 line. |
| bob := signInCookies(t, app, "bob@example.com") |
diff --git a/internal/docs/render.go b/internal/docs/render.go| index bf04b19..6613a0d 100644 |
| --- a/internal/docs/render.go |
| +++ b/internal/docs/render.go |
| @@ -80,6 +80,19 @@ var Catalog = rastrillo.Catalog{ |
| "docs.share.back": "Back to the document", |
| "docs.share.empty": "Only you can open this document.", |
| "docs.share.error.address": "Type the email address of the person you want to share with.", |
| + // docs.share.empty.team replaces docs.share.empty on a team document, |
| + // where "Only you can open this document" would be false. |
| + "docs.share.empty.team": "Nobody has been added by name.", |
| + // docs.share.team.* is the team rung (spec §8.2.1, Paul 2026-11-01: |
| + // "New docs Team, old private"). The body says which side the switch is |
| + // on in words, so the state never rests on a button's label alone, and |
| + // says that the team reads and does not edit. |
| + "docs.share.team.heading": "Your team", |
| + "docs.share.team.body.team": "Everyone on your team can read this document. Only you and people you give edit access can change it.", |
| + "docs.share.team.body.private": "Only you and the people you add above can open this document.", |
| + "docs.share.team.body.private_published": "Only you, the people you add above and anyone with the published link can open this document.", |
| + "docs.share.team.make_private": "Make private", |
| + "docs.share.team.make_team": "Share with your team", |
| // docs.share.public.* is the third rung — a read-only link anyone |
| // can follow, signed in or not (suite doctrine ruling 15). |
| @@ -350,6 +363,9 @@ var Catalog = rastrillo.Catalog{ |
| // day sharing landed, and a row that looks like yours and is not is |
| // how a person opens a document expecting to be able to edit it. |
| "docs.list.shared": "Shared with you", |
| + // docs.list.team marks a row somebody else owns that the reader reaches |
| + // through the team rung rather than a grant of their own. |
| + "docs.list.team": "Shared with your team", |
| "docs.signout.label": "Sign out", |
diff --git a/internal/docs/search_test.go b/internal/docs/search_test.go| index 8eca7f2..5983db2 100644 |
| --- a/internal/docs/search_test.go |
| +++ b/internal/docs/search_test.go |
| @@ -16,7 +16,7 @@ func seedTitles(t *testing.T, app *App, address string, titles ...string) int64 |
| ctx := context.Background() |
| owner := app.TestPerson(t, address) |
| for _, title := range titles { |
| - if _, err := app.Store().Create(ctx, owner, title); err != nil { |
| + if _, err := app.Store().createDocument(ctx, owner, title, "", VisibilityPrivate); err != nil { |
| t.Fatalf("Create(%q): %v", title, err) |
| } |
| } |
diff --git a/internal/docs/seed.go b/internal/docs/seed.go| index fb59e89..dde7dc0 100644 |
| --- a/internal/docs/seed.go |
| +++ b/internal/docs/seed.go |
| @@ -86,7 +86,7 @@ func Seed(ctx context.Context, store *Store, actor Actor) error { |
| base := time.Now().UTC() |
| for _, sd := range seedDocs { |
| - doc, err := store.Create(ctx, owner, sd.Title) |
| + doc, err := store.createDocument(ctx, owner, sd.Title, "", VisibilityPrivate) |
| if err != nil { |
| return fmt.Errorf("docs: seed: create %q: %w", sd.Title, err) |
| } |
diff --git a/internal/docs/share.go b/internal/docs/share.go| index 70201a2..5880766 100644 |
| --- a/internal/docs/share.go |
| +++ b/internal/docs/share.go |
| @@ -5,6 +5,7 @@ import ( |
| "net/http" |
| "amadan.net/rastrillo/rastrillo" |
| + "gorm.io/gorm" |
| ) |
| // sharePage is the share screen's view data, resolved in the handler rather |
| @@ -59,6 +60,14 @@ type sharePage struct { |
| CopyButton string |
| CopiedLabel string |
| ShareScript string |
| + |
| + // The team rung (spec §8.2.1). Team is the switch's state, and TeamBody |
| + // says it in words; the one form posts the other direction. |
| + Team bool |
| + TeamHeading string |
| + TeamBody string |
| + TeamButton string |
| + TeamDestination Visibility |
| } |
| // roleChoice is one option card: rastrillo's choice-field reads Value, |
| @@ -138,7 +147,7 @@ func (h *handlers) renderShare(w http.ResponseWriter, r *http.Request, doc *Docu |
| for _, g := range grants { |
| rows = append(rows, grant{g.Subject, g.Role}) |
| } |
| - nativeJSON(w, r, status, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "grants": rows, "published": published, "public_url": publicURL, "error": errKey}) |
| + nativeJSON(w, r, status, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "grants": rows, "published": published, "public_url": publicURL, "visibility": doc.Visibility, "error": errKey}) |
| return |
| } |
| rows := make([]shareRow, 0, len(grants)) |
| @@ -186,6 +195,22 @@ func (h *handlers) renderShare(w http.ResponseWriter, r *http.Request, doc *Docu |
| CopiedLabel: rastrillo.T(r, "docs.share.public.copied"), |
| ShareScript: shareScriptPath(), |
| } |
| + page.Team = doc.Visibility == VisibilityTeam |
| + page.TeamHeading = rastrillo.T(r, "docs.share.team.heading") |
| + if page.Team { |
| + page.EmptyBody = rastrillo.T(r, "docs.share.empty.team") |
| + page.TeamBody = rastrillo.T(r, "docs.share.team.body.team") |
| + page.TeamButton = rastrillo.T(r, "docs.share.team.make_private") |
| + page.TeamDestination = VisibilityPrivate |
| + } else if published { |
| + page.TeamBody = rastrillo.T(r, "docs.share.team.body.private_published") |
| + page.TeamButton = rastrillo.T(r, "docs.share.team.make_team") |
| + page.TeamDestination = VisibilityTeam |
| + } else { |
| + page.TeamBody = rastrillo.T(r, "docs.share.team.body.private") |
| + page.TeamButton = rastrillo.T(r, "docs.share.team.make_team") |
| + page.TeamDestination = VisibilityTeam |
| + } |
| if errKey != "" { |
| page.Error = rastrillo.T(r, errKey) |
| } |
| @@ -301,3 +326,46 @@ func (h *handlers) ownerLookupFailure(w http.ResponseWriter, r *http.Request, er |
| } |
| h.fail(w, r, http.StatusNotFound, failDocument) |
| } |
| + |
| +// shareTeam serves POST /d/{sqid}/share/team: move a document between the |
| +// private and team rungs (spec §8.2.1). Owner- and member-only, exactly as |
| +// granting is, and answering 404 to anybody else. Scriptless: the direction |
| +// rides a hidden field, so a page left open cannot flip the switch the |
| +// wrong way from a stale label, and a 303 comes back here. |
| +func (h *handlers) shareTeam(w http.ResponseWriter, r *http.Request) { |
| + if !h.requireMemberRequest(w, r, true) { |
| + return |
| + } |
| + owner, err := h.owner(r) |
| + if err != nil { |
| + h.logger.Error("docs: resolve owner for visibility", "err", err) |
| + h.fail(w, r, h.internalFailureStatus(), failStatus) |
| + return |
| + } |
| + sqid := r.PathValue("sqid") |
| + err = h.store.SetVisibility(r.Context(), owner, sqid, Visibility(r.PostFormValue("visibility"))) |
| + switch { |
| + case err == nil: |
| + if wantsNative(r) { |
| + nativeJSON(w, r, 200, map[string]bool{"ok": true}) |
| + return |
| + } |
| + http.Redirect(w, r, "/d/"+sqid+"/share", http.StatusSeeOther) |
| + case errors.Is(err, errUnknownVisibility): |
| + h.fail(w, r, http.StatusBadRequest, failStatus) |
| + default: |
| + h.ownerLookupFailureOrStatus(w, r, err) |
| + } |
| +} |
| + |
| +// ownerLookupFailureOrStatus is ownerLookupFailure for an error that may also |
| +// be a storage failure: not-found and team-unavailable answer as a lookup |
| +// does, and anything else is logged and is the internal failure status. |
| +func (h *handlers) ownerLookupFailureOrStatus(w http.ResponseWriter, r *http.Request, err error) { |
| + if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, errTeamUnavailable) { |
| + h.ownerLookupFailure(w, r, err) |
| + return |
| + } |
| + h.logger.Error("docs: set visibility", "sqid", r.PathValue("sqid"), "err", err) |
| + h.fail(w, r, h.internalFailureStatus(), failStatus) |
| +} |
diff --git a/internal/docs/share_test.go b/internal/docs/share_test.go| index b861990..2a8375f 100644 |
| --- a/internal/docs/share_test.go |
| +++ b/internal/docs/share_test.go |
| @@ -48,12 +48,29 @@ func createDoc(t *testing.T, app *docs.App, cookies []*http.Cookie, title string |
| return strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| } |
| +// createPrivateDoc makes a document and moves it off the team rung, for the |
| +// tests whose subject is who reaches a PRIVATE document — grants, revokes, |
| +// 404s for strangers. A new document is on the team rung (spec §8.2.1, Paul |
| +// 2026-11-01: "New docs Team, old private"), and in NewForTest's development |
| +// mode every signed-in address is a member, so createDoc alone would hand |
| +// every one of them the document by team standing and those tests would be |
| +// testing the rung instead of the grant. Moved through the share page's own |
| +// form, so it is the path an owner takes. |
| +func createPrivateDoc(t *testing.T, app *docs.App, cookies []*http.Cookie, title string) string { |
| + t.Helper() |
| + sqid := createDoc(t, app, cookies, title) |
| + if rec := post(t, app, cookies, "/d/"+sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("POST /d/%s/share/team: status %d, want 303", sqid, rec.Code) |
| + } |
| + return sqid |
| +} |
| + |
| // The whole point of the feature, end to end and scriptless: Alice shares a |
| // document with Bob by typing his address into a form, and Bob can read it. |
| func TestShareThenTheGranteeCanRead(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| // Bob cannot see it yet. |
| bob := signInCookies(t, app, "bob@example.com") |
| @@ -99,7 +116,7 @@ func TestSharePageListsGrantees(t *testing.T) { |
| func TestOnlyTheOwnerReachesTheSharePage(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| if rec := post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=writer"); rec.Code != http.StatusSeeOther { |
| t.Fatalf("POST share: status %d", rec.Code) |
| @@ -124,7 +141,7 @@ func TestOnlyTheOwnerReachesTheSharePage(t *testing.T) { |
| func TestRevokeRemovesAccess(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| bob := signInCookies(t, app, "bob@example.com") |
| if rec := post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader"); rec.Code != http.StatusSeeOther { |
diff --git a/internal/docs/shared_list_test.go b/internal/docs/shared_list_test.go| index 7ad59c4..532e48a 100644 |
| --- a/internal/docs/shared_list_test.go |
| +++ b/internal/docs/shared_list_test.go |
| @@ -18,7 +18,7 @@ import ( |
| func TestASharedDocumentAppearsInTheGranteesList(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| // Before the grant, Bob's list does not mention it. Without this the |
| // test would pass on a list that shows everybody everything. |
| @@ -60,9 +60,9 @@ func TestASharedDocumentAppearsInTheGranteesList(t *testing.T) { |
| func TestASharedRowSaysSo(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Alices") |
| + sqid := createPrivateDoc(t, app, alice, "Alices") |
| bob := signInCookies(t, app, "bob@example.com") |
| - createDoc(t, app, bob, "Bobs") |
| + createPrivateDoc(t, app, bob, "Bobs") |
| post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader") |
| // The catalog KEY, not the English. NewForTest's app never wires |
| @@ -96,7 +96,7 @@ func TestASharedRowSaysSo(t *testing.T) { |
| func TestRevokingRemovesItFromTheGranteesList(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Minutes") |
| + sqid := createPrivateDoc(t, app, alice, "Minutes") |
| bob := signInCookies(t, app, "bob@example.com") |
| post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader") |
| @@ -119,7 +119,7 @@ func TestRevokingRemovesItFromTheGranteesList(t *testing.T) { |
| func TestAGranteeCanSearchForASharedDocument(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| - sqid := createDoc(t, app, alice, "Quarterly plan") |
| + sqid := createPrivateDoc(t, app, alice, "Quarterly plan") |
| bob := signInCookies(t, app, "bob@example.com") |
| post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader") |
diff --git a/internal/docs/store.go b/internal/docs/store.go| index 2373ec5..eb31ce7 100644 |
| --- a/internal/docs/store.go |
| +++ b/internal/docs/store.go |
| @@ -46,6 +46,12 @@ type Store struct { |
| // an allowlist gets, and matches sampleDocuments' own default shape. |
| seedOnlyMembers func(address string) bool |
| + // members answers "is this address a member of this instance" in lone |
| + // shape — allowlist.configured, the same predicate seedOnlyMembers and |
| + // handlers.isMember hold — for the team rung (permissionScope). nil |
| + // means nobody reads the team rung in lone shape: it fails closed. |
| + members func(address string) bool |
| + |
| // logger is where a sample-seeding failure goes — see |
| // seedIfEnabled's own doc comment for why that failure is logged |
| // and swallowed here rather than ever returned to EnsurePerson's |
| @@ -285,7 +291,22 @@ func (s *Store) Create(ctx context.Context, owner int64, title string) (*Documen |
| // CreateDraft makes retries after a lost acknowledgement return the same document. |
| // The token is scoped to the authenticated owner, never a document capability. |
| +// |
| +// A new document is on the team rung (spec §8.2.1, Paul 2026-11-01: "New docs |
| +// Team, old private"); its owner makes it private from the share page. |
| func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token string) (*Document, error) { |
| + return s.createDocument(ctx, owner, title, token, VisibilityTeam) |
| +} |
| + |
| +// createDocument is CreateDraft with the rung chosen by the caller: team for |
| +// every document a person makes, private for the sample library (seed.go), |
| +// which is one person's welcome content and would otherwise sit in every |
| +// member's list. Creation writes its first revision (random, newRevision) |
| +// and its suite_feed row in the same transaction as the document. |
| +func (s *Store) createDocument(ctx context.Context, owner int64, title, token string, visibility Visibility) (*Document, error) { |
| + if !visibility.valid() { |
| + return nil, fmt.Errorf("docs: create document: unknown visibility %q", visibility) |
| + } |
| actor := s.ownerActor(ctx, owner) |
| if err := s.requireMember(ctx, actor); err != nil { |
| return nil, err |
| @@ -296,6 +317,11 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin |
| clientID := uint64(mrand.Uint32N(math.MaxUint32)) + 1 |
| now := time.Now().UTC() |
| + revision, err := newRevision(0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + |
| var lastErr error |
| for attempt := 0; attempt < maxSqidAttempts; attempt++ { |
| sqid, err := newSqid() |
| @@ -303,11 +329,15 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin |
| return nil, err |
| } |
| doc := &Document{ |
| - Sqid: sqid, |
| - Title: title, |
| - OwnerID: owner, |
| - GUID: guid, |
| - ClientID: clientID, |
| + Sqid: sqid, |
| + Title: title, |
| + OwnerID: owner, |
| + GUID: guid, |
| + ClientID: clientID, |
| + Visibility: visibility, |
| + // Random, as every later revision is (newRevision): a |
| + // restore never reissues a value. |
| + Revision: revision, |
| CreatedAt: now, |
| UpdatedAt: now, |
| } |
| @@ -333,6 +363,9 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin |
| if err := tx.Create(doc).Error; err != nil { |
| return err |
| } |
| + if err := announce(tx, doc.ID, doc.Revision, false); err != nil { |
| + return err |
| + } |
| return s.requireMember(ctx, actor) |
| }) |
| if err == nil { |
| @@ -926,6 +959,10 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd |
| if err := s.permissionScope(ctx, tx, actor, permissionWrite).Model(&Document{}).Where("documents.id = ?", doc.ID).Update("updated_at", time.Now().UTC()).Error; err != nil { |
| return s.permissionError(ctx, actor, err) |
| } |
| + // The content changed, so a suite consumer must read it again. |
| + if err := bumpRevision(tx, doc.ID, false); err != nil { |
| + return err |
| + } |
| assignedSeq = row.Seq |
| return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite) |
| }); err != nil { |
| @@ -947,6 +984,10 @@ func (s *Store) Rename(ctx context.Context, actor Actor, doc *Document, title st |
| if err := s.permissionScope(ctx, tx.Model(&Document{}), actor, permissionWrite).Where("documents.id = ? AND documents.deleted_at IS NULL", doc.ID).Updates(map[string]any{"title": title, "updated_at": time.Now().UTC()}).Error; err != nil { |
| return err |
| } |
| + // The title is the first line of what S3 serves. |
| + if err := bumpRevision(tx, doc.ID, false); err != nil { |
| + return err |
| + } |
| return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite) |
| }) |
| } |
diff --git a/internal/docs/store_test.go b/internal/docs/store_test.go| index daeeaac..723fca9 100644 |
| --- a/internal/docs/store_test.go |
| +++ b/internal/docs/store_test.go |
| @@ -180,9 +180,8 @@ func TestADocumentYouDoNotOwnIsNotThere(t *testing.T) { |
| // stranger cannot learn a sqid exists by probing it. |
| func TestUnownedDocumentOverHTTPIs404Not403(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| - ctx := context.Background() |
| alice := app.TestPerson(t, "alice@example.com") |
| - doc, _ := app.Store().Create(ctx, alice, "Alice's private notes") |
| + doc := app.TestCreatePrivate(t, alice, "Alice's private notes") |
| req := app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+doc.Sqid, nil) |
| rec := httptest.NewRecorder() |
diff --git a/internal/docs/stream_test.go b/internal/docs/stream_test.go| index 8943972..2b35469 100644 |
| --- a/internal/docs/stream_test.go |
| +++ b/internal/docs/stream_test.go |
| @@ -111,7 +111,7 @@ func TestStreamIsOwnerScoped(t *testing.T) { |
| ctx := context.Background() |
| owner := app.TestPerson(t, "owner@example.com") |
| app.TestPerson(t, "stranger@example.com") |
| - doc, err := app.Store().Create(ctx, owner, "Private") |
| + doc, err := app.Store().createDocument(ctx, owner, "Private", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatalf("Create: %v", err) |
| } |
diff --git a/internal/docs/suite.go b/internal/docs/suite.go| new file mode 100644 |
| index 0000000..d503e59 |
| --- /dev/null |
| +++ b/internal/docs/suite.go |
| @@ -0,0 +1,450 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/oficina/suite/server" |
| + "gorm.io/gorm" |
| + |
| + "github.com/carlosframework/docs/internal/docs/principalstore" |
| +) |
| + |
| +// suiteProducer is Docs' half of the suite contract (spec §8.2.2; suite |
| +// revision 10 and §6.5, commit c38e3ad): the feed of every live document, |
| +// Docs' own per-person read check, and a document's text. The suite |
| +// package owns the bearer check, the wire shapes and S3's one refusal. |
| +// |
| +// Nothing here caches. Every Rule reads the roster lease, the allowlist and |
| +// the database afresh, because an authorization answer held past its request |
| +// is a standing capability (suite §4.3). |
| +type suiteProducer struct { |
| + store *Store |
| + // list is the lone-shape front door: an address S2 names must pass it |
| + // as a request would (requireAdmission) before any document is read. |
| + list allowlist |
| + // subjects resolves a Home subject in team mode, the same connect |
| + // Bridge a signed-in request resolves through. nil outside team mode. |
| + subjects homeSubjects |
| + // step, when set, is called at named points: "asked" after the asker is |
| + // mapped, "read" after Rule's readable read, "history" after its log |
| + // read (the last before standing is checked), "replayed" between Content's replay |
| + // and its second read of the revision. Tests only: it is how a lease |
| + // running out or a change landing mid-request is made to happen on |
| + // demand, which nothing else can arrange. |
| + step func(stage string) |
| +} |
| + |
| +var _ server.Producer = (*suiteProducer)(nil) |
| + |
| +// liveDocuments is the producer's definition of live: not deleted, and not |
| +// one of 0002_owners.sql's orphans, which nobody can read. |
| +func liveDocuments(g *gorm.DB) *gorm.DB { |
| + return g.Where("documents.deleted_at IS NULL AND documents.owner_id > 0") |
| +} |
| + |
| +// Feed pages suite_feed by id. |
| +// |
| +// The cursor is "<feed id>.<that row's stamp>" (a random nonce, written |
| +// once), and the stamp is checked on every request. After a restore from an |
| +// older backup AUTOINCREMENT hands the same ids out again to different rows; |
| +// a bare id would carry on silently from a position that now means |
| +// something else, and a consumer at the restored tip would get no rows and |
| +// its own cursor back for ever (Astra, 2026-11-01). A stamp that no longer |
| +// matches, and any cursor Docs did not issue, is an error, which the suite |
| +// package answers 503: loud, never a page. "" and "0" are the beginning. At |
| +// the tip the cursor given comes back unchanged with no rows, which is what |
| +// ends a consumer's poll. |
| +func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| + after, stamp, err := parseFeedCursor(cursor) |
| + if err != nil { |
| + return suite.Feed{}, err |
| + } |
| + db := p.store.db.WithContext(ctx) |
| + if after > 0 { |
| + var at []SuiteFeedRow |
| + if err := db.Model(&SuiteFeedRow{}).Select("id", "stamp").Where("id = ?", after).Find(&at).Error; err != nil { |
| + return suite.Feed{}, err |
| + } |
| + if len(at) != 1 || at[0].Stamp != stamp { |
| + return suite.Feed{}, errors.New("docs: suite feed cursor names a row this log does not hold; the database was restored, so the consumer must drop what it holds from Docs and start again") |
| + } |
| + } |
| + var rows []struct { |
| + ID int64 |
| + Sqid string |
| + Revision int64 |
| + Gone bool |
| + TouchedAt time.Time |
| + Stamp int64 |
| + } |
| + err = db.Table("suite_feed"). |
| + Select("suite_feed.id, documents.sqid, suite_feed.revision, suite_feed.gone, suite_feed.touched_at, suite_feed.stamp"). |
| + Joins("JOIN documents ON documents.id = suite_feed.document_id"). |
| + Where("suite_feed.id > ? AND documents.owner_id > 0", after). |
| + Order("suite_feed.id"). |
| + Limit(limit). |
| + Scan(&rows).Error |
| + if err != nil { |
| + return suite.Feed{}, err |
| + } |
| + if len(rows) == 0 { |
| + // The tip: the cursor given, unchanged, so the consumer stops. "" |
| + // becomes "0", the beginning, because the contract refuses an empty |
| + // cursor. |
| + if cursor == "" { |
| + cursor = "0" |
| + } |
| + return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil |
| + } |
| + feed := suite.Feed{Rows: make([]suite.FeedRow, 0, len(rows))} |
| + for _, r := range rows { |
| + feed.Rows = append(feed.Rows, suite.FeedRow{ItemID: r.Sqid, Revision: r.Revision, Gone: r.Gone, TouchedAt: r.TouchedAt.UTC()}) |
| + } |
| + last := rows[len(rows)-1] |
| + feed.Cursor = strconv.FormatInt(last.ID, 10) + "." + strconv.FormatInt(last.Stamp, 10) |
| + return feed, nil |
| +} |
| + |
| +// parseFeedCursor reads a cursor Docs issued: "" or "0" is the beginning, |
| +// anything else "<id>.<stamp>" in canonical positive decimals, so a value has |
| +// one spelling. Anything else was not issued here, and is an error rather |
| +// than a guess at a position. |
| +func parseFeedCursor(c string) (after, stamp int64, err error) { |
| + if c == "" || c == "0" { |
| + return 0, 0, nil |
| + } |
| + head, tail, found := strings.Cut(c, ".") |
| + after, ok1 := canonicalPositive(head) |
| + stamp, ok2 := canonicalPositive(tail) |
| + if !found || !ok1 || !ok2 { |
| + return 0, 0, errors.New("docs: suite feed cursor was not issued by Docs") |
| + } |
| + return after, stamp, nil |
| +} |
| + |
| +func canonicalPositive(s string) (int64, bool) { |
| + n, err := strconv.ParseInt(s, 10, 64) |
| + if err != nil || n < 1 || strconv.FormatInt(n, 10) != s { |
| + return 0, false |
| + } |
| + return n, true |
| +} |
| + |
| +// Rule answers, per pair, whether the named asker may open the document now |
| +// in Docs: the read predicate (permissionScope — ownership, a live grant, |
| +// the team rung for a member; never a link) for the actor the asker maps to. |
| +// |
| +// In team mode standing is asked again AFTER the reads, from the request's |
| +// latched Access (Astra, 2026-11-01). A lease that ran out before the read |
| +// would otherwise answer NOT_VISIBLE for what membership opens, and one that |
| +// ran out after it would answer VISIBLE from a membership that has lapsed. |
| +// If standing is still Member the reads ran under a valid lease. If not, the |
| +// readable set is read again — now without the membership clauses, Unknown |
| +// being latched — so only what an address grant opens stays readable, and |
| +// what only membership would open is UNKNOWN (standing Unknown) or |
| +// NOT_VISIBLE (NotMember). |
| +func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| + out := make([]suite.Authorization, len(pairs)) |
| + actor, ctx, access, keyed, err := p.askerActor(ctx, asker) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !keyed { |
| + // An asker of a kind Docs does not key on in this shape. Not |
| + // NOT_VISIBLE: that is the one silent answer, and this is a |
| + // mismatch the consumer must see (suite §3). |
| + for i := range out { |
| + out[i] = suite.UNKNOWN |
| + } |
| + return out, nil |
| + } |
| + p.at("asked") |
| + ids := make([]string, 0, len(pairs)) |
| + for _, pr := range pairs { |
| + ids = append(ids, pr.ItemID) |
| + } |
| + isLive, err := p.liveRevisions(ctx, ids) |
| + if err != nil { |
| + return nil, err |
| + } |
| + canRead, err := p.readable(ctx, actor, ids) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p.at("read") |
| + issued, err := p.issued(ctx, pairs, canRead) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p.at("history") |
| + // Standing is asked here, after the LAST database read (Astra, round |
| + // 3: asked before the history read, a lease that ran out during it |
| + // answered VISIBLE from a membership that had lapsed). Still Member: |
| + // every read above ran under a valid lease. Not Member: the readable |
| + // set is read again, now without the membership clauses (Unknown is |
| + // latched), and only what an address grant opens stays readable. The |
| + // history read needs no repeat: it was asked for a superset. |
| + uncertain := false |
| + if access != nil { |
| + standing := access.state() |
| + if standing != roster.Member { |
| + if canRead, err = p.readable(ctx, actor, ids); err != nil { |
| + return nil, err |
| + } |
| + } |
| + uncertain = standing == roster.Unknown |
| + } |
| + |
| + for i, pr := range pairs { |
| + rev, can := canRead[pr.ItemID] |
| + _, live := isLive[pr.ItemID] |
| + switch { |
| + case !live: |
| + // Deleted, or never existed. |
| + out[i] = suite.NOT_VISIBLE |
| + case !can && uncertain: |
| + // The roster cannot say whether this person is a member, and |
| + // membership is what would open it: withheld loudly. |
| + out[i] = suite.UNKNOWN |
| + case !can: |
| + // The person before the revision: a document this person may |
| + // not open is NOT_VISIBLE at every revision. |
| + out[i] = suite.NOT_VISIBLE |
| + case pr.Revision == rev: |
| + out[i] = suite.VISIBLE |
| + case issued[pr]: |
| + // A revision this document had, by Docs' own log: moved on. |
| + out[i] = suite.STALE |
| + default: |
| + // A revision this log never issued for this document — one |
| + // from before a restore, or one never issued at all (suite |
| + // §4.3): withheld loudly. Revisions are random, so there is no |
| + // "ahead" or "behind" to read off the number. |
| + out[i] = suite.UNKNOWN |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// issued is which of the asked (item, revision) pairs this log holds: a |
| +// revision suite_feed recorded for that document. Asked only for pairs the |
| +// asker may read at a revision that is not current, since only those turn |
| +// on it. Revisions are random, so the log is the only thing that can say a |
| +// revision is behind (doctrine §4.3: compare against your log). |
| +func (p *suiteProducer) issued(ctx context.Context, pairs []suite.ItemRevision, canRead map[string]int64) (map[suite.ItemRevision]bool, error) { |
| + var ids []string |
| + var revs []int64 |
| + for _, pr := range pairs { |
| + if rev, can := canRead[pr.ItemID]; can && pr.Revision != rev { |
| + ids = append(ids, pr.ItemID) |
| + revs = append(revs, pr.Revision) |
| + } |
| + } |
| + out := map[suite.ItemRevision]bool{} |
| + if len(ids) == 0 { |
| + return out, nil |
| + } |
| + var rows []struct { |
| + Sqid string |
| + Revision int64 |
| + } |
| + if err := p.store.db.WithContext(ctx).Table("suite_feed"). |
| + Select("documents.sqid, suite_feed.revision"). |
| + Joins("JOIN documents ON documents.id = suite_feed.document_id"). |
| + Where("documents.sqid IN ? AND suite_feed.revision IN ?", ids, revs). |
| + Scan(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + for _, r := range rows { |
| + out[suite.ItemRevision{ItemID: r.Sqid, Revision: r.Revision}] = true |
| + } |
| + return out, nil |
| +} |
| + |
| +// liveRevisions is each live document's current revision, by sqid. |
| +func (p *suiteProducer) liveRevisions(ctx context.Context, ids []string) (map[string]int64, error) { |
| + var rows []struct { |
| + Sqid string |
| + Revision int64 |
| + } |
| + if err := liveDocuments(p.store.db.WithContext(ctx).Model(&Document{})).Where("documents.sqid IN ?", ids). |
| + Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + out := make(map[string]int64, len(rows)) |
| + for _, r := range rows { |
| + out[r.Sqid] = r.Revision |
| + } |
| + return out, nil |
| +} |
| + |
| +// readable is the documents among ids the actor may read now, with their |
| +// revisions: permissionScope, under ctx's standing. |
| +func (p *suiteProducer) readable(ctx context.Context, actor Actor, ids []string) (map[string]int64, error) { |
| + var rows []struct { |
| + Sqid string |
| + Revision int64 |
| + } |
| + if err := p.store.permissionScope(ctx, p.store.db.WithContext(ctx).Model(&Document{}), actor, permissionRead). |
| + Where("documents.sqid IN ? AND documents.deleted_at IS NULL", ids). |
| + Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + out := make(map[string]int64, len(rows)) |
| + for _, r := range rows { |
| + out[r.Sqid] = r.Revision |
| + } |
| + return out, nil |
| +} |
| + |
| +// at runs the test-only step hook, if one is set. |
| +func (p *suiteProducer) at(stage string) { |
| + if p.step != nil { |
| + p.step(stage) |
| + } |
| +} |
| + |
| +// askerActor maps the asker to the actor Docs keys on in its current shape, |
| +// and returns the context permissionScope must read it under. keyed is false |
| +// for an asker of the other kind. access is the request's latched team |
| +// standing, nil in lone shape. |
| +// |
| +// Lone shape keys on an address: the front door first (a configured member, |
| +// or a holder of a live grant, as requireAdmission asks on every request), |
| +// then the person row, looked up and never created — EnsurePerson would seed |
| +// a sample library for somebody who has never signed in. Somebody who has |
| +// not signed in yet is still the address their grants and membership name. |
| +// |
| +// Team mode keys on the Home subject (person_ref): connect's link and then |
| +// the Home-only principal, exactly as a signed-in request resolves it |
| +// (identityResolver.resolve), and the roster standing for that subject. A |
| +// subject with no Docs principal yet is an actor with no person, which reads |
| +// the team rung by standing alone and nothing else. |
| +func (p *suiteProducer) askerActor(ctx context.Context, asker suite.Subject) (actor Actor, out context.Context, access *requestAccess, keyed bool, err error) { |
| + s := p.store |
| + if s.team == nil { |
| + if asker.Kind != suite.SubjectAddress { |
| + return Actor{}, ctx, nil, false, nil |
| + } |
| + address := subjectOf(asker.Value) |
| + admitted, err := p.list.allows(address) |
| + if err != nil { |
| + return Actor{}, ctx, nil, true, err |
| + } |
| + if !admitted { |
| + return Actor{}, ctx, nil, true, nil |
| + } |
| + var person Person |
| + err = s.db.WithContext(ctx).Where("email = ?", address).First(&person).Error |
| + switch { |
| + case errors.Is(err, gorm.ErrRecordNotFound): |
| + return Actor{VerifiedAddress: &address}, ctx, nil, true, nil |
| + case err != nil: |
| + return Actor{}, ctx, nil, true, err |
| + } |
| + return localActor(person.ID, address), ctx, nil, true, nil |
| + } |
| + |
| + if asker.Kind != suite.SubjectPersonRef { |
| + return Actor{}, ctx, nil, false, nil |
| + } |
| + subject := asker.Value |
| + actor, err = p.homeActor(ctx, subject) |
| + if err != nil { |
| + return Actor{}, ctx, nil, true, err |
| + } |
| + a := s.team.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject}) |
| + return actor, withAccess(ctx, a), a, true, nil |
| +} |
| + |
| +// homeActor is a Home subject's actor in team mode, or the empty actor when |
| +// the subject has no Docs principal. Storage failures are errors: S2 answers |
| +// 503, which the consumer reads as UNKNOWN for the whole call. |
| +func (p *suiteProducer) homeActor(ctx context.Context, subject string) (Actor, error) { |
| + resolver := identityResolver{store: p.store, team: p.store.team, links: p.subjects} |
| + person, err := resolver.homePerson(ctx, subject) |
| + switch { |
| + case errors.Is(err, errIdentityRefused): |
| + return Actor{}, nil |
| + case err != nil: |
| + return Actor{}, err |
| + } |
| + principal, err := p.store.team.principals.Person(ctx, person.ID) |
| + switch { |
| + case errors.Is(err, principalstore.ErrRefused): |
| + return Actor{}, nil |
| + case err != nil: |
| + return Actor{}, err |
| + } |
| + return Actor{PersonID: principal.ID, VerifiedAddress: principal.VerifiedAddress}, nil |
| +} |
| + |
| +// Content is the document's plain text at its current revision: the title on |
| +// the first line, a blank line, then Store.Text; an untitled document is its |
| +// text alone. Any other revision, a deleted document and an unknown id are |
| +// all suite.ErrNotAvailable. S3 carries no person, so no read check runs. |
| +// |
| +// The revision is read again after the replay. Every change that could alter |
| +// the text bumps it in the same transaction, so an unchanged revision means |
| +// the text read is that revision's; a changed one answers not available, and |
| +// the consumer fetches the newer row the feed already carries. |
| +func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| + doc, err := p.liveDocument(ctx, itemID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if doc.Revision != revision { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + text, err := p.store.Text(ctx, doc) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p.at("replayed") |
| + again, err := p.liveDocument(ctx, itemID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if again.Revision != revision { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + if strings.TrimSpace(doc.Title) == "" { |
| + return []byte(text), nil |
| + } |
| + return []byte(doc.Title + "\n\n" + text), nil |
| +} |
| + |
| +func (p *suiteProducer) liveDocument(ctx context.Context, sqid string) (*Document, error) { |
| + var doc Document |
| + err := liveDocuments(p.store.db.WithContext(ctx)).Where("documents.sqid = ?", sqid).First(&doc).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil, suite.ErrNotAvailable |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &doc, nil |
| +} |
| + |
| +// mountSuite puts the three suite routes on the outer mux, beside the |
| +// router and outside it: outside the session and admission groups, and |
| +// outside homeCSRF, which memoria's POST /suite/s2 would fail (it sends only |
| +// Authorization). Exactly the three method-and-path patterns the contract |
| +// names, so nothing else under /suite/ escapes the router's CSRF check. With |
| +// no consumers server.Handler is nil and nothing is mounted: /suite/* is the |
| +// router's 404 like any unknown path. |
| +func mountSuite(mux *http.ServeMux, h http.Handler) { |
| + if h == nil { |
| + return |
| + } |
| + mux.Handle("GET "+suite.RouteS1, h) |
| + mux.Handle("POST "+suite.RouteS2, h) |
| + mux.Handle("GET "+suite.RouteS3+"/{item}", h) |
| +} |
diff --git a/internal/docs/suite_agent_test.go b/internal/docs/suite_agent_test.go| new file mode 100644 |
| index 0000000..9d3f55b |
| --- /dev/null |
| +++ b/internal/docs/suite_agent_test.go |
| @@ -0,0 +1,213 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + crand "crypto/rand" |
| + "errors" |
| + "io" |
| + "strconv" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +// feedRowsOf is a document's suite_feed rows, oldest first. |
| +func feedRowsOf(t *testing.T, s *Store, docID int64) []SuiteFeedRow { |
| + t.Helper() |
| + var rows []SuiteFeedRow |
| + if err := s.db.Where("document_id = ?", docID).Order("id").Find(&rows).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return rows |
| +} |
| + |
| +// The delegated agent API that landed on main (5039cf6) creates and edits |
| +// documents through CreateDraft and ApplyUpdate, inside its own writer |
| +// transaction. So an agent-created document is on the team rung (Paul, |
| +// 2026-11-01), its revisions are drawn by newRevision from randomSource, |
| +// each change is announced in suite_feed, and S2 reads an agent edit's |
| +// predecessor as STALE from the log. The agent's own "body_revision" / |
| +// "expected_revision" is doc_updates.seq — a different number, untouched. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each reverted: CreateDraft creating private → |
| +// "visibility"; createDocument's revision fixed at 1 instead of drawn → "the |
| +// scripted draws" (first row at 1); createDocument without its announce → |
| +// one row short; ApplyUpdate without bumpRevision → "the edit's revision" |
| +// unchanged, no third row, and S2 [VISIBLE VISIBLE]. (The fixed-revision |
| +// mutation first failed to compile — an unused variable, red for the wrong |
| +// reason — and was redone.) |
| +func TestSuiteAgentCreateAndEditAreTeamRandomAndAnnounced(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + t.Cleanup(func() { randomSource = crand.Reader }) |
| + |
| + // create: the document's revision, its nonce, the initial content's |
| + // revision, its nonce — in that order, all from randomSource. |
| + randomSource = draws(101, 102, 103, 104) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + randomSource = crand.Reader |
| + var doc Document |
| + if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if doc.Visibility != VisibilityTeam { |
| + t.Errorf("visibility: an agent-created document is %q, want team", doc.Visibility) |
| + } |
| + rows := feedRowsOf(t, f.a.store, doc.ID) |
| + if len(rows) != 2 || rows[0].Revision != 101 || rows[0].Stamp != 102 || rows[1].Revision != 103 || rows[1].Stamp != 104 || doc.Revision != 103 { |
| + t.Errorf("the scripted draws / feed rows: document at %d, rows %+v; want revisions 101 then 103 with nonces 102, 104", doc.Revision, rows) |
| + } |
| + if body.Revision != "1" { |
| + t.Errorf("the agent's body_revision is doc_updates.seq, %q; want \"1\" (the two revisions are separate)", body.Revision) |
| + } |
| + |
| + edited := f.call(t, "docs_update", editAgentInput(body)) |
| + if edited.Code != 200 { |
| + t.Fatal(edited.Code, edited.Body.String()) |
| + } |
| + before := doc.Revision |
| + if err := f.a.store.db.First(&doc, doc.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if doc.Revision == before { |
| + t.Errorf("the edit's revision: unchanged at %d", before) |
| + } |
| + rows = feedRowsOf(t, f.a.store, doc.ID) |
| + if len(rows) != 3 || rows[2].Revision != doc.Revision || rows[2].Gone { |
| + t.Errorf("the edit's feed row: %+v, want a third row at %d", rows, doc.Revision) |
| + } |
| + got, err := f.app.suite.Rule(context.Background(), suite.Subject{Kind: suite.SubjectAddress, Value: "owner@example.com"}, |
| + []suite.ItemRevision{{ItemID: doc.Sqid, Revision: before}, {ItemID: doc.Sqid, Revision: doc.Revision}}) |
| + if err != nil || got[0] != suite.STALE || got[1] != suite.VISIBLE { |
| + t.Errorf("S2 around the agent's edit: %v %v, want [STALE VISIBLE]", got, err) |
| + } |
| + if strconv.FormatInt(doc.Revision, 10) == body.Revision { |
| + t.Error("documents.revision and the agent's body_revision coincide") |
| + } |
| +} |
| + |
| +// An agent create or edit whose feed row cannot be written commits nothing: |
| +// no document, receipt or attribution for a create; no update, receipt, |
| +// attribution or new revision for an edit. |
| +// |
| +// MUTATION-TESTED 2026-11-02, reverted: bumpRevision returning nil when |
| +// announce fails → the agent edit commits. createDocument ignoring |
| +// announce's error stayed GREEN here, correctly: the agent create's initial |
| +// content goes through ApplyUpdate in the same transaction, whose own feed |
| +// row fails on the same trigger and rolls everything back. That swallow is |
| +// held where creation is alone — TestSuiteAChangeWithoutItsFeedRowDoesNotCommit |
| +// ("create"), red under it. |
| +func TestSuiteAgentWritesRollBackWithoutTheirFeedRow(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + var doc Document |
| + if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + count := func(model any) int64 { |
| + var n int64 |
| + if err := f.a.store.db.Model(model).Count(&n).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| + } |
| + docs, receipts, attributions := count(&Document{}), count(&agentReceipt{}), count(&agentAttribution{}) |
| + if w := f.call(t, "docs_create", initialAgentInput()); w.Code == 200 { |
| + t.Error("an agent create committed without its feed row") |
| + } |
| + if count(&Document{}) != docs || count(&agentReceipt{}) != receipts || count(&agentAttribution{}) != attributions { |
| + t.Error("an agent create left rows behind without its feed row") |
| + } |
| + updates, editReceipts := count(&DocUpdate{}), count(&agentUpdateReceipt{}) |
| + if w := f.call(t, "docs_update", editAgentInput(body)); w.Code == 200 { |
| + t.Error("an agent edit committed without its feed row") |
| + } |
| + var after Document |
| + if err := f.a.store.db.First(&after, doc.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if count(&DocUpdate{}) != updates || count(&agentUpdateReceipt{}) != editReceipts || after.Revision != doc.Revision { |
| + t.Error("an agent edit left rows behind without its feed row") |
| + } |
| +} |
| + |
| +// failingAfter hands out its bytes and then fails, like a source that dies |
| +// between two draws. |
| +type failingAfter struct{ r io.Reader } |
| + |
| +func (f failingAfter) Read(p []byte) (int, error) { |
| + n, err := f.r.Read(p) |
| + if err == io.EOF { |
| + return n, errors.New("entropy gone") |
| + } |
| + return n, err |
| +} |
| + |
| +// byteAtATime returns one byte per Read, as a source may. |
| +type byteAtATime struct{ r io.Reader } |
| + |
| +func (b byteAtATime) Read(p []byte) (int, error) { |
| + if len(p) == 0 { |
| + return 0, nil |
| + } |
| + return b.r.Read(p[:1]) |
| +} |
| + |
| +// Astra's two nonblocking notes on 65acd67. A source that fails after the |
| +// revision was drawn — when the feed row's nonce is drawn — still stops the |
| +// change; and a source that answers in pieces is read until eight bytes are |
| +// in hand, while one that runs out part-way is an error, never a value |
| +// built from a half-filled buffer. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each reverted: announce falling back to a |
| +// time-based nonce when randomPositive fails → "nonce failure" commits the |
| +// rename and the create; randomPositive using a single Read in place of |
| +// io.ReadFull → "one byte at a time" gets 0x0100000000000000 and "runs out |
| +// part-way" gets a value. (Falling back to a ZERO nonce stayed green: the |
| +// column's CHECK (stamp > 0) refuses it and the change rolls back anyway — a |
| +// second guard, so the mutation was redone with a guessable nonzero value.) |
| +func TestSuiteRandomnessFailsPartWayAndArrivesInPieces(t *testing.T) { |
| + t.Cleanup(func() { randomSource = crand.Reader }) |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + doc, err := app.store.Create(ctx, alice, "Kept") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var docs int64 |
| + app.store.db.Model(&Document{}).Count(&docs) |
| + rows := len(feedRowsOf(t, app.store, doc.ID)) |
| + |
| + // One draw is there (the revision), the nonce's is not. |
| + randomSource = failingAfter{draws(77)} |
| + if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil { |
| + t.Error("nonce failure: a rename committed") |
| + } |
| + randomSource = failingAfter{draws(78)} |
| + if _, err := app.store.Create(ctx, alice, "Not made"); err == nil { |
| + t.Error("nonce failure: a document was created") |
| + } |
| + randomSource = crand.Reader |
| + var after Document |
| + app.store.db.First(&after, doc.ID) |
| + var docsAfter int64 |
| + app.store.db.Model(&Document{}).Count(&docsAfter) |
| + if after.Title != "Kept" || after.Revision != doc.Revision || docsAfter != docs || len(feedRowsOf(t, app.store, doc.ID)) != rows { |
| + t.Errorf("nonce failure changed something: %+v, documents %d→%d", after, docs, docsAfter) |
| + } |
| + |
| + randomSource = byteAtATime{draws(0x0102030405060708)} |
| + if n, err := randomPositive(); err != nil || n != 0x0102030405060708 { |
| + t.Errorf("one byte at a time: %#x %v", n, err) |
| + } |
| + randomSource = failingAfter{io.LimitReader(draws(0x0102030405060708).r, 3)} |
| + if n, err := randomPositive(); !errors.Is(err, errNoRandomness) { |
| + t.Errorf("runs out part-way: %#x %v, want errNoRandomness", n, err) |
| + } |
| +} |
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go| new file mode 100644 |
| index 0000000..277cbcf |
| --- /dev/null |
| +++ b/internal/docs/suite_feed.go |
| @@ -0,0 +1,163 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + crand "crypto/rand" |
| + "encoding/binary" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +// errUnknownVisibility is a visibility form posting something other than |
| +// the two rungs this column holds. |
| +var errUnknownVisibility = errors.New("docs: unknown visibility") |
| + |
| +// suiteClock is the feed's clock, for touched_at only. Nothing the suite |
| +// contract matches on — a revision, a cursor's nonce — is read from it, so a |
| +// clock set back across a restore cannot make a value repeat. A variable so |
| +// a test can set it back and show exactly that. |
| +var suiteClock = time.Now |
| + |
| +// randomSource is where revisions and feed nonces come from: crypto/rand. |
| +// A variable so a test can force particular draws; a source that fails is |
| +// an error, and the change that wanted the value does not commit. Nothing |
| +// falls back to a clock, a counter or math/rand, which a restore or an |
| +// attacker could reproduce. |
| +var randomSource io.Reader = crand.Reader |
| + |
| +// errNoRandomness is a randomSource that could not be read. |
| +var errNoRandomness = errors.New("docs: no randomness for a revision or a feed nonce") |
| + |
| +// randomPositive is a fresh positive int63 from randomSource: eight bytes, |
| +// the sign bit cleared, and a zero drawn again (0 is memoria's "not a |
| +// sibling" value and below the column's CHECK). |
| +func randomPositive() (int64, error) { |
| + for { |
| + var b [8]byte |
| + if _, err := io.ReadFull(randomSource, b[:]); err != nil { |
| + return 0, errNoRandomness |
| + } |
| + if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 { |
| + return n, nil |
| + } |
| + } |
| +} |
| + |
| +// newRevision is the revision a change is given: a fresh random positive |
| +// int63, never the document's current one. Revisions are not counted up and |
| +// not read from a clock (Astra on oficina/docs feat/suite-producer, two |
| +// rounds, 2026-11-01): after a restore from a backup — including one taken |
| +// before migration 0011, and one restored onto a clock set back — a counter |
| +// or a clock issues again a revision it issued before, for different |
| +// content, and S2 answers VISIBLE against a copy the asker may no longer |
| +// read. A draw matches any one earlier value with probability 2^-63 |
| +// (spec §8.2.2 has the cumulative figure), whatever the clock, the |
| +// migration's timing or the backup. Order is not needed: memoria only ever |
| +// matches revisions for equality (memoria models.go, SiblingRevision), and |
| +// S2's STALE is decided from this log (Rule), not by comparing numbers. |
| +func newRevision(current int64) (int64, error) { |
| + for { |
| + r, err := randomPositive() |
| + if err != nil { |
| + return 0, err |
| + } |
| + if r != current { |
| + return r, nil |
| + } |
| + } |
| +} |
| + |
| +// announce appends one row to suite_feed, with a fresh random nonce for the |
| +// S1 cursor. Called only inside the transaction that made the change it |
| +// records, so the log and the documents table can never disagree about a |
| +// committed revision (spec §8.2.2). |
| +func announce(tx *gorm.DB, docID, revision int64, gone bool) error { |
| + nonce, err := randomPositive() |
| + if err != nil { |
| + return err |
| + } |
| + row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: suiteClock().UTC(), Stamp: nonce} |
| + if err := tx.Create(row).Error; err != nil { |
| + return fmt.Errorf("docs: announce document %d: %w", docID, err) |
| + } |
| + return nil |
| +} |
| + |
| +// bumpRevision moves a document to a new revision (newRevision) and |
| +// announces it, in the caller's transaction. Every change a suite consumer |
| +// must re-read goes through here: an applied update, a rename, a visibility |
| +// change and a deletion (gone). A row that is not there is an error rather |
| +// than a silent no-op, because a bump that touched nothing would announce a |
| +// revision no document has. |
| +func bumpRevision(tx *gorm.DB, docID int64, gone bool) error { |
| + var current int64 |
| + if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(¤t).Error; err != nil { |
| + return fmt.Errorf("docs: read revision of document %d: %w", docID, err) |
| + } |
| + revision, err := newRevision(current) |
| + if err != nil { |
| + return err |
| + } |
| + // UpdateColumn, not Update: GORM's Update also stamps updated_at, and a |
| + // bump is not an edit — the list's recency must not move on a rename of |
| + // the rung or a deletion's bookkeeping. |
| + res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", revision) |
| + if res.Error != nil { |
| + return fmt.Errorf("docs: bump revision of document %d: %w", docID, res.Error) |
| + } |
| + if res.RowsAffected != 1 { |
| + return fmt.Errorf("docs: bump revision of document %d: %d rows", docID, res.RowsAffected) |
| + } |
| + return announce(tx, docID, revision, gone) |
| +} |
| + |
| +// SetVisibility moves a document between the private and team rungs (spec |
| +// §8.2.1). The owner's alone, through the owner-scoped Get and ownerMutation, |
| +// exactly as granting is: a writer may edit a document and still may not |
| +// decide who else reads it. Setting the rung it is already on changes |
| +// nothing and announces nothing. |
| +func (s *Store) SetVisibility(ctx context.Context, owner int64, sqid string, v Visibility) error { |
| + if !v.valid() { |
| + return errUnknownVisibility |
| + } |
| + doc, err := s.Get(ctx, owner, sqid) |
| + if err != nil { |
| + return err |
| + } |
| + return s.ownerMutation(ctx, owner, doc.ID, func(tx *gorm.DB) error { |
| + res := tx.Model(&Document{}). |
| + Where("id = ? AND deleted_at IS NULL AND visibility <> ?", doc.ID, v). |
| + UpdateColumn("visibility", v) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return nil |
| + } |
| + return bumpRevision(tx, doc.ID, false) |
| + }) |
| +} |
| + |
| +// deleteDocument soft-deletes a document and announces it gone, in one |
| +// transaction. There is no delete route yet; this is the one way a |
| +// document becomes deleted (TestSoftDelete reaches it), so the delete verb |
| +// that arrives later inherits the feed row rather than forgetting it. A |
| +// document already deleted is left alone and announced nothing. |
| +func (s *Store) deleteDocument(ctx context.Context, docID int64) error { |
| + return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + res := tx.Model(&Document{}). |
| + Where("id = ? AND deleted_at IS NULL", docID). |
| + Update("deleted_at", time.Now().UTC()) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return nil |
| + } |
| + return bumpRevision(tx, docID, true) |
| + }) |
| +} |
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go| new file mode 100644 |
| index 0000000..ee09879 |
| --- /dev/null |
| +++ b/internal/docs/suite_test.go |
| @@ -0,0 +1,1483 @@ |
| +package docs |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + crand "crypto/rand" |
| + "encoding/binary" |
| + "errors" |
| + "io/fs" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "testing/fstest" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/dashboard" |
| + "amadan.net/oficina/home/handoff" |
| + "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/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "github.com/carlosframework/docs/internal/docs/linkstore" |
| + "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 |
| +} |
| + |
| +// setRevision puts a document at the fixture's revision, with the revision |
| +// before it in its history: both are announced, as two bumps would be. The |
| +// fixture numbers its revisions 2 to 11 and real bumps are random |
| +// (newRevision), so the world is seeded at the fixture's numbers directly; |
| +// the producer reads documents.revision and suite_feed and does not care how |
| +// they got there. revision - 1 being in the log is what makes the harness's |
| +// "one behind" STALE (Docs decides STALE from its log), and revision + 1 |
| +// never being announced is what makes "one ahead" UNKNOWN. |
| +func setRevision(t *testing.T, s *Store, docID, revision int64) { |
| + t.Helper() |
| + err := s.db.Transaction(func(tx *gorm.DB) error { |
| + for _, r := range []int64{revision - 1, revision} { |
| + if err := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", r).Error; err != nil { |
| + return err |
| + } |
| + if err := announce(tx, docID, r, false); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// revisionOf is a document's current revision. |
| +func revisionOf(t *testing.T, s *Store, docID int64) int64 { |
| + t.Helper() |
| + var d Document |
| + if err := s.db.First(&d, docID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return d.Revision |
| +} |
| + |
| +// 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 (setRevision). 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 { |
| + // Deleted through the real path; its last revision is a |
| + // random one, which nothing asks about: a deleted item is |
| + // NOT_VISIBLE and refused at every revision. |
| + setRevision(t, s, doc.ID, c.Revision-1) |
| + if err := s.deleteDocument(ctx, doc.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + setRevision(t, s, doc.ID, c.Revision) |
| + } |
| + } |
| +} |
| + |
| +// 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 0011 leaves |
| +// every existing one private. The sample library is private too. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: CreateDraft passing |
| +// VisibilityPrivate → "a new document"; 0011'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 a positive revision", 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 < "0011" { |
| + 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("0011_suite.sql") |
| + var private, distinct, low int |
| + db.QueryRow(`SELECT COUNT(*) FROM documents WHERE visibility = 'private'`).Scan(&private) |
| + db.QueryRow(`SELECT COUNT(DISTINCT revision) FROM documents`).Scan(&distinct) |
| + db.QueryRow(`SELECT COUNT(*) FROM documents WHERE revision < 1000000`).Scan(&low) |
| + if private != 4 || distinct != 4 || low != 0 { |
| + t.Errorf("an existing document: %d of 4 private, %d distinct revisions, %d small ones; want 4, 4 random, 0", private, distinct, low) |
| + } |
| + var unmatched int |
| + db.QueryRow(`SELECT COUNT(*) FROM suite_feed f JOIN documents d ON d.id = f.document_id WHERE f.revision != d.revision`).Scan(&unmatched) |
| + if unmatched != 0 { |
| + t.Errorf("%d backfilled rows announce a revision their document does not have", unmatched) |
| + } |
| + rows, err := db.Query(`SELECT document_id, stamp FROM suite_feed ORDER BY id`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var fed []int64 |
| + stamps := map[int64]bool{} |
| + for rows.Next() { |
| + var id, stamp int64 |
| + rows.Scan(&id, &stamp) |
| + fed = append(fed, id) |
| + if stamp < 1 || stamps[stamp] { |
| + t.Errorf("a backfilled stamp that is not a distinct positive nonce: %d", stamp) |
| + } |
| + stamps[stamp] = true |
| + } |
| + 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 "<id>.<stamp>", the tip |
| +// returning the cursor given with no rows, any cursor Docs did not issue an |
| +// error, a row per bump (update, rename, visibility change, deletion) at a |
| +// fresh positive revision, 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"; |
| +// Feed not checking the stamp → cursor "2.1" answered a page. |
| +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") |
| + revs := []int64{revisionOf(t, app.store, doc.ID)} |
| + if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + revs = append(revs, revisionOf(t, app.store, doc.ID)) |
| + if err := app.store.Rename(ctx, actor, doc, "One, renamed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + revs = append(revs, revisionOf(t, app.store, doc.ID)) |
| + if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil { |
| + t.Fatal(err) |
| + } |
| + revs = append(revs, revisionOf(t, app.store, doc.ID)) |
| + 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) |
| + } |
| + twoBefore := revisionOf(t, app.store, two.ID) |
| + app.TestSoftDelete(t, two.Sqid) |
| + twoGone := revisionOf(t, app.store, two.ID) |
| + |
| + // Every revision is new: no two the same, none below 1 (newRevision). |
| + seen := map[int64]bool{} |
| + for _, r := range append(revs, twoBefore, twoGone) { |
| + if r < 1 || seen[r] { |
| + t.Errorf("revisions not fresh and positive: %v, %d, %d", revs, twoBefore, twoGone) |
| + } |
| + seen[r] = true |
| + } |
| + |
| + type step struct { |
| + sqid string |
| + rev int64 |
| + gone bool |
| + } |
| + 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}} |
| + var got []step |
| + var cursors []string |
| + 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 |
| + cursors = append(cursors, cursor) |
| + } |
| + if len(got) != len(want) { |
| + t.Fatalf("feed %+v, want %+v (rename, unchanged rung, grant)", got, want) |
| + } |
| + for k := range want { |
| + if got[k] != want[k] { |
| + t.Errorf("row %d: %+v, want %+v (gone)", k, got[k], want[k]) |
| + } |
| + } |
| + 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) |
| + } |
| + // A cursor Docs did not issue is an error (the suite package's 503), |
| + // never a page: not a bare id, not a stamp that does not match the row, |
| + // not another spelling of a real one. |
| + id, stamp, _ := strings.Cut(cursors[0], ".") |
| + for _, bad := range []string{"not-a-cursor", id, id + ".1", "0" + cursors[0], id + "." + stamp + "0", "-1", "+" + cursors[0]} { |
| + if f, err := p.Feed(ctx, bad, 100); err == nil { |
| + t.Errorf("cursor %q: a page of %d rows, want an error", bad, len(f.Rows)) |
| + } |
| + } |
| + if f, err := p.Feed(ctx, cursors[0], 100); err != nil || len(f.Rows) != len(want)-2 { |
| + t.Errorf("a cursor Docs issued: %d rows, %v", len(f.Rows), err) |
| + } |
| +} |
| + |
| +// 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]) |
| + } |
| + } |
| + } |
| + |
| + rev := func(d *Document) int64 { return revisionOf(t, app.store, d.ID) } |
| + first := rev(own) |
| + expect("wrong kind", ask(suite.SubjectPersonRef, "alice@example.com", pr(own, first), pr(private, rev(private))), suite.UNKNOWN, suite.UNKNOWN) |
| + expect("the owner", ask(suite.SubjectAddress, "Alice@Example.com", |
| + 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))), |
| + 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) |
| + } |
| + now := rev(own) |
| + expect("behind", ask(suite.SubjectAddress, "alice@example.com", pr(own, first), pr(own, now)), suite.STALE, suite.VISIBLE) |
| + expect("a member who never signed in", ask(suite.SubjectAddress, "newcomer@example.com", pr(own, now), pr(private, rev(private)), pr(linked, rev(linked))), |
| + suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE) |
| + expect("a grantee who never signed in", ask(suite.SubjectAddress, "invitee@example.com", pr(granted, rev(granted)), pr(own, now)), |
| + suite.VISIBLE, suite.NOT_VISIBLE) |
| + expect("a refused address", ask(suite.SubjectAddress, "stranger@example.com", pr(own, now), pr(linked, rev(linked))), |
| + 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, rev(theirs))), 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") |
| + created := revisionOf(t, app.store, doc.ID) |
| + if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil { |
| + t.Fatal(err) |
| + } |
| + current := revisionOf(t, app.store, doc.ID) |
| + body, err := app.suite.Content(ctx, doc.Sqid, current) |
| + if err != nil || string(body) != "Minutes\n\nhello world" { |
| + t.Errorf("titled: %q %v", body, err) |
| + } |
| + if _, err := app.suite.Content(ctx, doc.Sqid, created); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("an old revision: %v", err) |
| + } |
| + if _, err := app.suite.Content(ctx, doc.Sqid, current+1); !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, revisionOf(t, app.store, untitled.ID)); 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 with the revision |
| + // it was asked at. |
| + app.suite.step = func(stage string) { |
| + if stage != "replayed" { |
| + return |
| + } |
| + app.suite.step = 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, current); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("a change during the read: %q %v, want not available", body, err) |
| + } |
| + renamed := revisionOf(t, app.store, doc.ID) |
| + if body, err := app.suite.Content(ctx, doc.Sqid, renamed); 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, revisionOf(t, app.store, doc.ID)); !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) |
| + } |
| + } |
| +} |
| + |
| +// Astra's restore sequences (oficina/docs feat/suite-producer, two rounds, |
| +// 2026-11-01), with a real SQLite backup: a private draft is backed up; it |
| +// is renamed to confidential text, and memoria holds that revision and the |
| +// feed cursor after it; the backup is restored and the harmless draft is |
| +// shared with the team. With revisions counted up from the restored value |
| +// the share reissued the held revision, so S2 answered VISIBLE for a |
| +// teammate against the confidential copy, and S1 answered the held cursor |
| +// with no rows and the same cursor for ever. With revisions and nonces read |
| +// from a clock, the same happened when the restore landed on a clock set |
| +// back to the confidential edit's time ("clock set back"). Revisions and |
| +// nonces are random now, so neither repeats. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: sequential revisions |
| +// (newRevision returning current + 1, creation at 1) → both subtests |
| +// VISIBLE against the confidential copy; time-based revisions and nonces |
| +// (newRevision and randomPositive reading suiteClock) → "clock set back" |
| +// VISIBLE and its old cursor answered a page, while "real clock" stayed |
| +// green, which is why both subtests exist; Feed without the nonce check → |
| +// both subtests' old cursor answered a page. |
| +func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + // clock is suiteClock at each step, or nil for the real clock. |
| + clock map[string]time.Time |
| + }{ |
| + {"real clock", nil}, |
| + {"clock set back", map[string]time.Time{ |
| + "backup": time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC), |
| + "confidential": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC), |
| + // The restore happens at 10:20 on a clock that reads 10:10. |
| + "restored": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC), |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + at := func(step string) { |
| + if when, ok := tc.clock[step]; ok { |
| + suiteClock = func() time.Time { return when } |
| + } |
| + } |
| + t.Cleanup(func() { suiteClock = time.Now }) |
| + at("backup") |
| + dir := t.TempDir() |
| + path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db") |
| + cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"} |
| + app, err := New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + app.TestPerson(t, "bob@example.com") |
| + doc := app.TestCreatePrivate(t, alice, "Draft") |
| + if _, err := app.db.Writer().Exec("VACUUM INTO ?", backup); err != nil { |
| + t.Fatal(err) |
| + } |
| + at("confidential") |
| + if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Confidential: the acquisition"); err != nil { |
| + t.Fatal(err) |
| + } |
| + held := revisionOf(t, app.store, doc.ID) |
| + if body, err := app.suite.Content(ctx, doc.Sqid, held); err != nil || !strings.Contains(string(body), "Confidential") { |
| + t.Fatalf("memoria's copy: %q %v", body, err) |
| + } |
| + cursor := feedTip(t, app.suite) |
| + if err := app.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + restoreFile(t, backup, path) |
| + at("restored") |
| + restored, err := NewForTestWith(t, cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := restored.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityTeam); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: doc.Sqid, Revision: held}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got[0] != suite.UNKNOWN { |
| + 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]) |
| + } |
| + if current := revisionOf(t, restored.store, doc.ID); current == held { |
| + t.Errorf("the restore reissued revision %d", held) |
| + } |
| + if f, err := restored.suite.Feed(ctx, cursor, 100); err == nil { |
| + t.Errorf("the cursor from before the restore (%q) answered a page: cursor %q, %d rows; want an error", cursor, f.Cursor, len(f.Rows)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Astra's second-round sequence: a backup taken BEFORE migration 0011. A |
| +// harmless document is granted to Bob and backed up; Bob is revoked and the |
| +// document renamed to confidential text; the suite is deployed (0011 runs) |
| +// and memoria holds the confidential revision; the pre-0011 backup is |
| +// restored and the new build boots, running 0011 again over the harmless, |
| +// Bob-granted document. A constant there gave it the same revision as the |
| +// confidential copy, and S2 answered VISIBLE for Bob. No clock involved. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: 0011 without its random UPDATE (every |
| +// existing document at revision 1, as before) → Bob VISIBLE. |
| +func TestSuiteRestoreOfAPreSuiteBackupIssuesNewRevisions(t *testing.T) { |
| + dir := t.TempDir() |
| + path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db") |
| + |
| + // A database at 0010: the boot schema with Docs' own set cut before 0011. |
| + old := fstest.MapFS{} |
| + entries, err := fs.ReadDir(migrationFS, "migrations") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range entries { |
| + if e.Name() < "0011" { |
| + b, _ := fs.ReadFile(migrationFS, "migrations/"+e.Name()) |
| + old["migrations/"+e.Name()] = &fstest.MapFile{Data: b} |
| + } |
| + } |
| + 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)) |
| + d, err := db.Open(path, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := migrate.Apply(context.Background(), d, pre); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now().UTC() |
| + for _, q := range []struct { |
| + sql string |
| + args []any |
| + }{ |
| + {`INSERT INTO people (id, email, created_at) VALUES (1, 'alice@example.com', ?), (2, 'bob@example.com', ?)`, []any{now, now}}, |
| + {`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}}, |
| + {`INSERT INTO grants (doc_id, subject, role, created_by, created_at) VALUES (1, 'bob@example.com', 'reader', 1, ?)`, []any{now}}, |
| + } { |
| + if _, err := d.Writer().Exec(q.sql, q.args...); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := d.Writer().Exec("VACUUM INTO ?", backup); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec(`DELETE FROM grants`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec(`UPDATE documents SET title = 'Confidential: the acquisition' WHERE id = 1`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := d.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"} |
| + deployed, err := New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + held := revisionOf(t, deployed.store, 1) |
| + if body, err := deployed.suite.Content(ctx, "harmless01", held); err != nil || !strings.Contains(string(body), "Confidential") { |
| + t.Fatalf("memoria's copy: %q %v", body, err) |
| + } |
| + if err := deployed.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + restoreFile(t, backup, path) |
| + restored, err := NewForTestWith(t, cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: "harmless01", Revision: held}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got[0] != suite.UNKNOWN { |
| + t.Errorf("S2 for Bob at the confidential copy's revision after restoring a pre-0011 backup: %s, want UNKNOWN", got[0]) |
| + } |
| +} |
| + |
| +// feedTip follows the feed to its tip and returns the cursor there. |
| +func feedTip(t *testing.T, p *suiteProducer) string { |
| + t.Helper() |
| + cursor := "" |
| + for { |
| + f, err := p.Feed(context.Background(), cursor, 100) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Cursor == cursor { |
| + return cursor |
| + } |
| + cursor = f.Cursor |
| + } |
| +} |
| + |
| +// restoreFile puts a backup over a closed database file, its journal gone, |
| +// as an operator restoring from a snapshot does. |
| +func restoreFile(t *testing.T, backup, path string) { |
| + t.Helper() |
| + for _, f := range []string{path + "-wal", path + "-shm"} { |
| + os.Remove(f) |
| + } |
| + b, err := os.ReadFile(backup) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, b, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// A roster lease that runs out during an S2 call (Astra, 2026-11-01, and |
| +// round 3 for the history read): before the reads, after the readable read, |
| +// and after the log read. Each way what only membership opens — the team |
| +// rung, and ownership in team mode — is UNKNOWN, and an independent address |
| +// grant still answers, VISIBLE at its current revision and STALE at one |
| +// from its log. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: standing taken once in |
| +// askerActor, before the reads (the old code) → "asked": doc-team and |
| +// doc-private NOT_VISIBLE, and "read": both VISIBLE; the second read |
| +// skipped when standing has lapsed → "read": both VISIBLE; the standing |
| +// check moved back before the history read (round 2's order) → "history": |
| +// both VISIBLE, Astra's probe exactly. |
| +func TestSuiteRuleLeaseRunsOutMidCall(t *testing.T) { |
| + for _, stage := range []string{"asked", "read", "history"} { |
| + t.Run(stage, func(t *testing.T) { |
| + _, p, clock, _, _ := teamCustodyStore(t) |
| + p.step = func(at string) { |
| + if at == stage { |
| + clock.step(61 * time.Second) |
| + } |
| + } |
| + got, err := p.Rule(context.Background(), suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{ |
| + {ItemID: "doc-team", Revision: 7}, {ItemID: "doc-private", Revision: 4}, {ItemID: "doc-granted", Revision: 9}, {ItemID: "doc-granted", Revision: 8}, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.STALE} |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Errorf("pair %d: %s, want %s", i, got[i], want[i]) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Every change and its feed row are one transaction: when the feed row |
| +// cannot be written, the change does not commit either. A rename committed |
| +// without its row would leave a consumer holding a title the feed never |
| +// told it had changed (Astra, 2026-11-01: swallowing the insert's error |
| +// survived the suite). |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: bumpRevision returning nil |
| +// when announce fails → rename, update, visibility and deletion all commit; |
| +// createDocument ignoring announce's error → "create". |
| +func TestSuiteAChangeWithoutItsFeedRowDoesNotCommit(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, err := app.store.Create(ctx, alice, "Before") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + var updates, docs int64 |
| + app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updates) |
| + app.store.db.Model(&Document{}).Count(&docs) |
| + rev := revisionOf(t, app.store, doc.ID) |
| + |
| + if err := app.store.Rename(ctx, actor, doc, "After"); err == nil { |
| + t.Error("rename: succeeded without its feed row") |
| + } |
| + if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err == nil { |
| + t.Error("update: succeeded without its feed row") |
| + } |
| + if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err == nil { |
| + t.Error("visibility: succeeded without its feed row") |
| + } |
| + if err := app.store.deleteDocument(ctx, doc.ID); err == nil { |
| + t.Error("deletion: succeeded without its feed row") |
| + } |
| + if _, err := app.store.Create(ctx, alice, "New"); err == nil { |
| + t.Error("create: succeeded without its feed row") |
| + } |
| + |
| + var after Document |
| + if err := app.store.db.First(&after, doc.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if after.Title != "Before" || after.Visibility != VisibilityTeam || after.DeletedAt != nil || after.Revision != rev { |
| + t.Errorf("a change committed without its feed row: %+v", after) |
| + } |
| + var updatesAfter, docsAfter int64 |
| + app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updatesAfter) |
| + app.store.db.Model(&Document{}).Count(&docsAfter) |
| + if updatesAfter != updates || docsAfter != docs { |
| + t.Errorf("rows committed without their feed rows: updates %d→%d, documents %d→%d", updates, updatesAfter, docs, docsAfter) |
| + } |
| +} |
| + |
| +// STALE is decided by Docs' own log, not by comparing numbers (doctrine |
| +// §4.3): revisions are random, so a revision from this document's history |
| +// is STALE, one it never had — never issued, or another document's — is |
| +// UNKNOWN, whatever its size. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: Rule answering STALE for any |
| +// non-current revision without consulting the log → both "never issued" |
| +// cases and the cross-document ones STALE (and conformance's "one revision |
| +// ahead" STALE in both shapes); the log lookup not keyed on the document |
| +// (any history row with the asked revision counts) → the three |
| +// cross-document cases STALE. (A first try at the second dropped the |
| +// document from the SQL in a way SQLite refused — red for a syntax error, |
| +// not the rule — and was redone as a valid query.) |
| +func TestSuiteStaleIsDecidedByTheLog(t *testing.T) { |
| + app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com"}) |
| + 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, "One") |
| + other, _ := app.store.Create(ctx, alice, "Two") |
| + historyOf := func(d *Document, titles ...string) []int64 { |
| + h := []int64{revisionOf(t, app.store, d.ID)} |
| + for _, title := range titles { |
| + if err := app.store.Rename(ctx, actor, d, title); err != nil { |
| + t.Fatal(err) |
| + } |
| + h = append(h, revisionOf(t, app.store, d.ID)) |
| + } |
| + return h |
| + } |
| + history := historyOf(doc, "One, again", "One, once more") |
| + otherHistory := historyOf(other, "Two, again") |
| + current := history[len(history)-1] |
| + // One batch, both documents, each asked at the other's old revisions: |
| + // a log read that mixes the two documents' histories answers those |
| + // STALE here, not only in conformance. |
| + ask := []suite.ItemRevision{ |
| + {ItemID: doc.Sqid, Revision: history[0]}, |
| + {ItemID: doc.Sqid, Revision: history[1]}, |
| + {ItemID: doc.Sqid, Revision: current}, |
| + {ItemID: doc.Sqid, Revision: current - 1}, |
| + {ItemID: doc.Sqid, Revision: 1}, |
| + {ItemID: doc.Sqid, Revision: otherHistory[1]}, |
| + {ItemID: doc.Sqid, Revision: otherHistory[0]}, |
| + {ItemID: other.Sqid, Revision: history[0]}, |
| + {ItemID: other.Sqid, Revision: otherHistory[0]}, |
| + } |
| + got, err := app.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "alice@example.com"}, ask) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []suite.Authorization{suite.STALE, suite.STALE, suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.STALE} |
| + 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"} |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Errorf("%s: %s, want %s", names[i], got[i], want[i]) |
| + } |
| + } |
| +} |
| + |
| +// scriptedRandom is a randomSource that hands out the bytes it was given, and |
| +// then fails. |
| +type scriptedRandom struct{ r *bytes.Reader } |
| + |
| +func (s scriptedRandom) Read(p []byte) (int, error) { return s.r.Read(p) } |
| + |
| +func draws(values ...uint64) scriptedRandom { |
| + var b []byte |
| + for _, v := range values { |
| + b = binary.BigEndian.AppendUint64(b, v) |
| + } |
| + return scriptedRandom{bytes.NewReader(b)} |
| +} |
| + |
| +type brokenRandom struct{} |
| + |
| +func (brokenRandom) Read([]byte) (int, error) { return 0, errors.New("no entropy") } |
| + |
| +// The two redraws, forced (Astra, round 3: both survived the suite): a draw |
| +// of zero — directly, or a value that is zero once its sign bit is cleared — |
| +// is drawn again, and a draw equal to the document's current revision is |
| +// drawn again. And a source that fails is an error that stops the change: |
| +// nothing falls back to a value a restore or anybody else could reproduce. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: randomPositive returning its |
| +// first draw whatever it is → "zero, then 7" gets 0 and "the sign bit" gets |
| +// 0; newRevision returning its first draw → "current, then the next" gets |
| +// 5; randomPositive answering a failed read with a time-based value instead |
| +// of an error → "a broken source" commits a document. |
| +func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) { |
| + t.Cleanup(func() { randomSource = crand.Reader }) |
| + |
| + randomSource = draws(0, 7) |
| + if n, err := randomPositive(); err != nil || n != 7 { |
| + t.Errorf("zero, then 7: %d %v", n, err) |
| + } |
| + randomSource = draws(1<<63, 11) |
| + if n, err := randomPositive(); err != nil || n != 11 { |
| + t.Errorf("the sign bit alone (zero once cleared), then 11: %d %v", n, err) |
| + } |
| + randomSource = draws(5, 9) |
| + if n, err := newRevision(5); err != nil || n != 9 { |
| + t.Errorf("current, then the next: %d %v", n, err) |
| + } |
| + randomSource = draws(5) |
| + if n, err := newRevision(4); err != nil || n != 5 { |
| + t.Errorf("a draw that is not current is kept: %d %v", n, err) |
| + } |
| + |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + randomSource = crand.Reader |
| + alice := app.TestPerson(t, "alice@example.com") |
| + doc, err := app.store.Create(ctx, alice, "Kept") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + randomSource = brokenRandom{} |
| + if _, err := randomPositive(); !errors.Is(err, errNoRandomness) { |
| + t.Errorf("a broken source: %v, want errNoRandomness", err) |
| + } |
| + var before int64 |
| + app.store.db.Model(&Document{}).Count(&before) |
| + if _, err := app.store.Create(ctx, alice, "Not made"); err == nil { |
| + t.Error("a broken source: a document was created") |
| + } |
| + if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil { |
| + t.Error("a broken source: a rename committed") |
| + } |
| + var after int64 |
| + app.store.db.Model(&Document{}).Count(&after) |
| + if after != before || revisionOf(t, app.store, doc.ID) != doc.Revision { |
| + t.Errorf("a broken source changed something: documents %d→%d, revision %d→%d", before, after, doc.Revision, revisionOf(t, app.store, doc.ID)) |
| + } |
| +} |
| + |
| +// An orphan — a document 0002_owners.sql left at owner_id 0, readable by |
| +// nobody — is not live, even if a feed row names it. Nothing in Docs writes |
| +// one (announce runs only for documents with an owner), so the row is made |
| +// by hand: S1 skips it, S3 refuses it and S2 answers NOT_VISIBLE. Kept as a |
| +// clause in Feed rather than left to S2 and S3 because a feed row is itself |
| +// a disclosure that an item exists, and an orphan is not Docs' to announce. |
| +// |
| +// MUTATION-TESTED 2026-11-02, reverted: Feed without "documents.owner_id > |
| +// 0" → the orphan's sqid in the feed (Fable's review found this clause |
| +// survived every other test). |
| +func TestSuiteAnOrphanIsNeverAnnounced(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + now := time.Now().UTC() |
| + orphan := &Document{Sqid: "orphan0011", Title: "Nobody's", GUID: "orphan-guid", ClientID: 1, OwnerID: 0, Visibility: VisibilityTeam, Revision: 42, CreatedAt: now, UpdatedAt: now} |
| + if err := app.store.db.Create(orphan).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.store.db.Transaction(func(tx *gorm.DB) error { return announce(tx, orphan.ID, 42, false) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := app.suite.Feed(ctx, "", 100) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, row := range f.Rows { |
| + if row.ItemID == orphan.Sqid { |
| + t.Errorf("the feed announced an orphan: %+v", row) |
| + } |
| + } |
| + if _, err := app.suite.Content(ctx, orphan.Sqid, 42); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("S3 served an orphan: %v", err) |
| + } |
| + app.TestPerson(t, "alice@example.com") |
| + got, err := app.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "alice@example.com"}, []suite.ItemRevision{{ItemID: orphan.Sqid, Revision: 42}}) |
| + if err != nil || got[0] != suite.NOT_VISIBLE { |
| + t.Errorf("S2 for an orphan on the team rung: %v %v, want NOT_VISIBLE", got, err) |
| + } |
| +} |
| + |
| +// The rung's words on the share page are true (Fable on #103): a private |
| +// document with a published link says the link opens it too, and a team |
| +// document says edit access, not "the people above", decides who changes it. |
| +// |
| +// MUTATION-TESTED 2026-11-02, reverted: renderShare without the published |
| +// branch → the plain private words on a published document. |
| +func TestSuiteShareWordsMentionThePublishedLink(t *testing.T) { |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req := app.TestRequest(t, "alice@example.com", http.MethodGet, "/", nil) |
| + cookies := req.Cookies() |
| + do := func(method, path, body string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest(method, path, strings.NewReader(body)) |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + if method == http.MethodPost { |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Sec-Fetch-Site", "same-origin") |
| + } |
| + return serve(app, r) |
| + } |
| + rec := do(http.MethodPost, "/documents", "title=Notes") |
| + sqid := strings.TrimPrefix(rec.Header().Get("Location"), "/d/") |
| + if !strings.Contains(do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String(), "docs.share.team.body.team") { |
| + t.Error("a team document's share page") |
| + } |
| + if rec := do(http.MethodPost, "/d/"+sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("make private: %d", rec.Code) |
| + } |
| + if rec := do(http.MethodPost, "/d/"+sqid+"/share/link", "on=1"); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("publish: %d", rec.Code) |
| + } |
| + share := do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String() |
| + if !strings.Contains(share, "docs.share.team.body.private_published") { |
| + t.Error("a published private document's share page does not mention the link") |
| + } |
| + if rec := do(http.MethodPost, "/d/"+sqid+"/share/link", "on=0"); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("unpublish: %d", rec.Code) |
| + } |
| + share = do(http.MethodGet, "/d/"+sqid+"/share", "").Body.String() |
| + if strings.Contains(share, "docs.share.team.body.private_published") || !strings.Contains(share, "docs.share.team.body.private") { |
| + t.Error("an unpublished private document's share page still mentions a link") |
| + } |
| +} |
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go| index 8839575..81a12c7 100644 |
| --- a/internal/docs/team_access.go |
| +++ b/internal/docs/team_access.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "errors" |
| "net/http" |
| + "strings" |
| "amadan.net/oficina/home/roster" |
| "amadan.net/oficina/home/teammode" |
| @@ -83,18 +84,32 @@ func (t *teamRuntime) admission(next http.Handler) http.Handler { |
| // permissionScope is also usable under the SQLite writer. It never refreshes |
| // the roster, and checks a lease without waiting for a cache publisher. |
| +// |
| +// It is the one read predicate (spec §8.2.1, §8.2.2): ownership, an |
| +// individual grant, and for reading only the team rung. A link is never one |
| +// of its clauses — links are a separate table this never reads — so a |
| +// link-shared document reaches nobody here by being link-shared. |
| +// |
| +// The team rung is read by an admitted member: in team mode a roster Member |
| +// under the request's own lease (the same standing ownership needs), and in |
| +// lone shape an address on the configured allowlist (Store.members). A guest |
| +// admitted only by a grant is not a member. The rung needs no person row: |
| +// S2 asks for members who have never opened Docs, and their first sign-in |
| +// would show them the team's documents, so the answer is the same now. |
| +// Ownership and every write still need a person. |
| func (s *Store) permissionScope(ctx context.Context, g *gorm.DB, actor Actor, p permission) *gorm.DB { |
| - owner := s.team == nil |
| + member := s.team == nil |
| if s.team != nil { |
| a, ok := s.access(ctx, actor) |
| if !ok { |
| return g.Where("1 = 0") |
| } |
| - owner = a.state() == roster.Member |
| + member = a.state() == roster.Member |
| } |
| - if actor.PersonID <= 0 { |
| + if actor.PersonID <= 0 && p != permissionRead { |
| return g.Where("1 = 0") |
| } |
| + owner := member && actor.PersonID > 0 |
| if p == permissionOwner { |
| if !owner { |
| return g.Where("1 = 0") |
| @@ -102,28 +117,42 @@ func (s *Store) permissionScope(ctx context.Context, g *gorm.DB, actor Actor, p |
| return owned(g, actor.PersonID) |
| } |
| grant := actor.VerifiedAddress != nil && *actor.VerifiedAddress != "" |
| - if !owner && !grant { |
| + team := p == permissionRead && s.teamReader(actor, member) |
| + if !owner && !grant && !team { |
| return g.Where("1 = 0") |
| } |
| - clause := "documents.owner_id > 0 AND (" |
| + var clauses []string |
| args := []any{} |
| if owner { |
| - clause += "documents.owner_id = ?" |
| + clauses = append(clauses, "documents.owner_id = ?") |
| args = append(args, actor.PersonID) |
| } |
| if grant { |
| - if owner { |
| - clause += " OR " |
| - } |
| - clause += "EXISTS (SELECT 1 FROM grants WHERE grants.doc_id = documents.id AND grants.subject = ?" |
| + clause := "EXISTS (SELECT 1 FROM grants WHERE grants.doc_id = documents.id AND grants.subject = ?" |
| args = append(args, subjectOf(*actor.VerifiedAddress)) |
| if p == permissionWrite { |
| clause += " AND grants.role = ?" |
| args = append(args, RoleWriter) |
| } |
| - clause += ")" |
| + clauses = append(clauses, clause+")") |
| + } |
| + if team { |
| + clauses = append(clauses, "documents.visibility = ?") |
| + args = append(args, VisibilityTeam) |
| + } |
| + return g.Where("documents.owner_id > 0 AND ("+strings.Join(clauses, " OR ")+")", args...) |
| +} |
| + |
| +// teamReader is whether actor reads the team rung: member is the team-mode |
| +// standing permissionScope already read (a Member under a current lease); |
| +// in lone shape it is an address on the configured allowlist. A Store with |
| +// no members predicate (one built without an allowlist) has no team readers |
| +// in lone shape: the rung fails closed. |
| +func (s *Store) teamReader(actor Actor, member bool) bool { |
| + if s.team != nil { |
| + return member |
| } |
| - return g.Where(clause+")", args...) |
| + return actor.VerifiedAddress != nil && *actor.VerifiedAddress != "" && s.members != nil && s.members(*actor.VerifiedAddress) |
| } |
| func (s *Store) permissionError(ctx context.Context, actor Actor, err error) error { |
| if s.team == nil || err == nil { |
| @@ -210,7 +239,15 @@ func (h *handlers) requireMemberRequest(w http.ResponseWriter, r *http.Request, |
| if h.member(r) { |
| return true |
| } |
| - h.fail(w, r, http.StatusForbidden, failStatus) |
| + // A route about one document answers a guest as one about a |
| + // document they cannot reach: 404, never 403, as team mode below |
| + // always has (Astra, 2026-11-01). Create, which names no document, |
| + // stays 403. |
| + if item { |
| + h.fail(w, r, http.StatusNotFound, failDocument) |
| + } else { |
| + h.fail(w, r, http.StatusForbidden, failStatus) |
| + } |
| return false |
| } |
| actor, e := h.actor(r) |
diff --git a/internal/docs/team_access_test.go b/internal/docs/team_access_test.go| index 72729c5..e3d0079 100644 |
| --- a/internal/docs/team_access_test.go |
| +++ b/internal/docs/team_access_test.go |
| @@ -170,6 +170,16 @@ func (refuseAdopt) Adopt(context.Context, *sql.Tx, string, string, int64) error |
| } |
| func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestClock, string) { |
| + t.Helper() |
| + subject := "pr_" + strings.Repeat("a", 26) |
| + rt, clock := testTeamRosterOf(t, s, app, subject) |
| + return rt, clock, subject |
| +} |
| + |
| +// testTeamRosterOf is testTeamRoster with the roster's members named: each |
| +// subject is a Member, and every other subject is NotMember under the same |
| +// signed, complete roster. |
| +func testTeamRosterOf(t *testing.T, s *Store, app *App, subjects ...string) (*teamRuntime, *teamTestClock) { |
| t.Helper() |
| op, e := family.Generate() |
| if e != nil { |
| @@ -192,14 +202,16 @@ func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestCl |
| } |
| migrateTeam(t, app) |
| clock := &teamTestClock{} |
| - subject := "pr_" + strings.Repeat("a", 26) |
| transport := teamTestTransport(func(r *http.Request) (*http.Response, error) { |
| _, elapsed := clock.Now() |
| if elapsed >= 30*time.Second { |
| return nil, errors.New("directory unavailable") |
| } |
| i, complete := 0, true |
| - members := []roster.MemberEntry{{Subject: subject, Role: "member"}} |
| + members := make([]roster.MemberEntry, 0, len(subjects)) |
| + for _, subject := range subjects { |
| + members = append(members, roster.MemberEntry{Subject: subject, Role: "member"}) |
| + } |
| page := roster.Page{Version: 1, Type: "page", Directory: b.Directory, Consumer: b.Consumer, Team: b.Team, Audience: b.Audience, Fetch: r.URL.Query().Get("fetch"), RequestCursorHash: roster.CursorHash(r.URL.Query().Get("cursor")), Generation: p.Generation, Epoch: 1, Index: &i, Members: &members, Complete: &complete} |
| raw, e := roster.SignPage(key, "roster1", page) |
| if e != nil { |
| @@ -225,7 +237,7 @@ func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestCl |
| } |
| rt := &teamRuntime{cache: cache, bindings: b, db: app.db.Writer(), principals: ps} |
| s.team = rt |
| - return rt, clock, subject |
| + return rt, clock |
| } |
| func TestTeamPermissionMemberLeaseEndsAtSixtySeconds(t *testing.T) { |
diff --git a/internal/docs/team_identity_test.go b/internal/docs/team_identity_test.go| index 89b6321..32e5647 100644 |
| --- a/internal/docs/team_identity_test.go |
| +++ b/internal/docs/team_identity_test.go |
| @@ -79,7 +79,7 @@ func TestTeamIdentityAddressAbsenceNeverRedeemsEmptyGrant(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - doc, e := s.Create(ctx, local, "private") |
| + doc, e := s.createDocument(ctx, local, "private", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go| index d87278f..4157677 100644 |
| --- a/internal/docs/team_router_test.go |
| +++ b/internal/docs/team_router_test.go |
| @@ -100,15 +100,15 @@ func newTeamRouterFixtureWithDashboard(t *testing.T, dashboard bool) *teamRouter |
| if e != nil { |
| t.Fatal(e) |
| } |
| - f.own, e = app.store.Create(ctx, f.alice, "Alice original") |
| + f.own, e = app.store.createDocument(ctx, f.alice, "Alice original", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
| - f.shared, e = app.store.Create(ctx, f.bob, "Bob shared") |
| + f.shared, e = app.store.createDocument(ctx, f.bob, "Bob shared", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
| - f.hidden, e = app.store.Create(ctx, f.bob, "Bob private") |
| + f.hidden, e = app.store.createDocument(ctx, f.bob, "Bob private", "", VisibilityPrivate) |
| if e != nil { |
| t.Fatal(e) |
| } |
diff --git a/internal/docs/testing.go b/internal/docs/testing.go| index 29a22a7..2437157 100644 |
| --- a/internal/docs/testing.go |
| +++ b/internal/docs/testing.go |
| @@ -13,7 +13,6 @@ import ( |
| "path/filepath" |
| "strings" |
| "testing" |
| - "time" |
| ) |
| // NewForTest builds an App against a temporary SQLite database. It is |
| @@ -325,17 +324,34 @@ func TestEditorScriptPath() string { return editorScriptPath() } |
| // TestSoftDelete marks a document deleted the way a delete verb would, for |
| // tests that need a live link pointing at a document that is no longer |
| // there. There is no delete route yet; this is the state the schema |
| -// already models (documents.deleted_at) and that ByToken filters on. |
| +// already models (documents.deleted_at) and that ByToken filters on. It |
| +// goes through Store.deleteDocument, so the suite feed announces it gone |
| +// exactly as a real deletion will. |
| func (a *App) TestSoftDelete(t *testing.T, sqid string) { |
| t.Helper() |
| - err := a.store.db.Model(&Document{}). |
| - Where("sqid = ?", sqid). |
| - Update("deleted_at", time.Now().UTC()).Error |
| - if err != nil { |
| + var doc Document |
| + if err := a.store.db.Where("sqid = ?", sqid).First(&doc).Error; err != nil { |
| + t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err) |
| + } |
| + if err := a.store.deleteDocument(context.Background(), doc.ID); err != nil { |
| t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err) |
| } |
| } |
| +// TestCreatePrivate makes a document on the private rung, for a test outside |
| +// the package whose subject is who reaches a private document. Store.Create |
| +// puts a new document on the team rung (spec §8.2.1), and in development every |
| +// signed-in address is a member, so a test of grants or of a stranger's 404 |
| +// needs the private rung said out loud. |
| +func (a *App) TestCreatePrivate(t *testing.T, owner int64, title string) *Document { |
| + t.Helper() |
| + doc, err := a.store.createDocument(context.Background(), owner, title, "", VisibilityPrivate) |
| + if err != nil { |
| + t.Fatalf("docs: TestCreatePrivate(%q): %v", title, err) |
| + } |
| + return doc |
| +} |
| + |
| // TestWrite applies one update to a document as the signed-in owner, |
| // through the same store path a real edit takes, so a test can publish a |
| // document that actually has text in it. |
diff --git a/internal/docs/updates_test.go b/internal/docs/updates_test.go| index 13b3b38..cd3024b 100644 |
| --- a/internal/docs/updates_test.go |
| +++ b/internal/docs/updates_test.go |
| @@ -58,7 +58,7 @@ func TestUpdatesEndpointsAreOwnerScoped(t *testing.T) { |
| ctx := context.Background() |
| owner := app.TestPerson(t, "owner@example.com") |
| app.TestPerson(t, "stranger@example.com") |
| - doc, err := app.Store().Create(ctx, owner, "Private") |
| + doc, err := app.Store().createDocument(ctx, owner, "Private", "", VisibilityPrivate) |
| if err != nil { |
| t.Fatalf("Create: %v", err) |
| } |
diff --git a/internal/docs/views/share.html b/internal/docs/views/share.html| index 5dee3c4..153cf23 100644 |
| --- a/internal/docs/views/share.html |
| +++ b/internal/docs/views/share.html |
| @@ -140,6 +140,23 @@ |
| <div rst-form-foot><button rst-btn="primary" type="submit">{{.ShareButton}}</button></div> |
| </form> |
| + {{/* The team rung (spec §8.2.1; Paul, 2026-11-01: "New docs Team, old |
| + private"). The body names the state in words, so it never rests on |
| + the button's label alone, and says the team reads and does not edit. |
| + One <form> whichever way the switch points, the direction in a hidden |
| + field, like the public link below: a page left open in a tab cannot |
| + flip it the wrong way from a stale label. Scriptless; a 303 back. */}} |
| + <section docs-share-public docs-share-team> |
| + <h2>{{.TeamHeading}}</h2> |
| + <p rst-muted docs-share-team-state>{{.TeamBody}}</p> |
| + <div docs-share-actions> |
| + <form method="post" action="/d/{{.Sqid}}/share/team"> |
| + <input type="hidden" name="visibility" value="{{.TeamDestination}}"> |
| + {{if .Team}}<button rst-btn type="submit">{{.TeamButton}}</button>{{else}}<button rst-btn="primary" type="submit">{{.TeamButton}}</button>{{end}} |
| + </form> |
| + </div> |
| + </section> |
| + |
| {{/* The third rung: a read-only link anyone can follow, signed in or |
| not. One <form> whichever way the switch currently points, with the |
| direction in a hidden field — so a page left open in a tab cannot |
diff --git a/internal/shipped/shipped.go b/internal/shipped/shipped.go| index ea35492..e42e846 100644 |
| --- a/internal/shipped/shipped.go |
| +++ b/internal/shipped/shipped.go |
| @@ -63,6 +63,8 @@ var FirstParty = map[string]bool{ |
| "amadan.net/oficina/home/handoff": true, |
| "amadan.net/oficina/home/roster": true, |
| "amadan.net/oficina/home/teammode": true, |
| + // The suite contract (spec §8.2.2): Oficina's own, like Home's modules. |
| + "amadan.net/oficina/suite": true, |
| } |
| // toolchain is a toolchain the build or the checks run, found by its |