oficina / suite Public

Revision 10: custody widened to every live item (Paul, 2026-11-01); the producer half

Paul: "Hold private too, check per person" — a consumer holds every live
item and S2 is the app's own per-person read check, with no custody
intersection; and Docs: "New docs Team, old private". custody.json is
rewritten to that rule (owner, asker_grant per case), the harness's
reference server follows it, and its broken variants now include revision
9's team-only S2 and a link counted as a grant.

server/ is the producer half: Producer (Feed, Rule, Content), the bearer
check over <APP>_SUITE_CONSUMERS hashes, strict S2 decoding, and S3's one
identical refusal. Standard library only. Thirteen mutations, all red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 12848f8736db32260417a6302b9699bc1887cb5e parent 1d8e22e
9 files changed, +918 −65
  • README.md +3 −0
  • conformance/conformance.go +9 −7
  • conformance/conformance_test.go +44 −16
  • docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md +97 −1
  • fixtures.go +13 −5
  • fixtures/custody.json +63 −36
  • server/consumers.go +113 −0
  • server/server.go +244 −0
  • server/server_test.go +332 −0

CI passed — run details

CI log
=== gate ===
ok  	amadan.net/oficina/suite	0.022s
ok  	amadan.net/oficina/suite/conformance	0.008s
ok  	amadan.net/oficina/suite/server	0.010s
diff --git a/README.md b/README.md
index 1141e05..c80cff8 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,9 @@ owns the rule that binds the others.
client must refuse. Both are shared so every app runs the same gate
rather than inventing its own.
- `conformance/`: the harness an app points at its own server half.
+- `server/`: the producer half — the bearer check, the three routes and
+ their wire shapes — that an app mounts by implementing `Producer`
+ (doctrine §6.5, revision 10).
## How an app uses it
diff --git a/conformance/conformance.go b/conformance/conformance.go
index 3fcc01e..5988096 100644
--- a/conformance/conformance.go
+++ b/conformance/conformance.go
@@ -62,9 +62,10 @@ func Check(h http.Handler) Report {
return r
}
-// Gate 3, the content half. Every rung but `team` answers 404, and it answers
-// the same 404 as a deleted item — a consumer that could tell "not
-// team-visible" from "does not exist" would learn that a private item exists.
+// Gate 3, the content half. Since revision 10 (Paul, 2026-11-01) every live
+// item is served — the consumer holds private and granted items too, and S2
+// decides who sees them — and a deleted item answers the same 404 as one
+// that never existed, so a consumer cannot tell a deletion from a made-up id.
func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
// The refusal every non-team item must be indistinguishable from. Taken
// from an id that is not in the fixture at all, so it is the server's
@@ -109,10 +110,11 @@ func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
}
}
-// Gate 3, the authorization half. The fixture's asker deliberately holds a
-// live grant on the private and granted items and a former grant on the
-// deleted one: the custody intersection (§4.3) has to beat the grant, or a
-// consumer holding an ingested id learns the item is still there.
+// Gate 3, the authorization half. Since revision 10, S2 is the app's own read
+// check for the named asker: the team rung, ownership, or a live individual
+// grant, and never a link. The fixture's asker owns one private item, holds a
+// grant on another and a former grant on a deleted one, and does not own the
+// link-shared and moved-to-private items, so each part of the check shows.
func checkS2(h http.Handler, f suite.CustodyFixture, r *Report) {
// Three questions, not one. A single question at the current revision for
// a single person lets a server answer from the rung alone and read
diff --git a/conformance/conformance_test.go b/conformance/conformance_test.go
index acc53b7..4c17546 100644
--- a/conformance/conformance_test.go
+++ b/conformance/conformance_test.go
@@ -19,7 +19,8 @@ type referenceServer struct {
// The bugs each broken variant introduces.
forbidInsteadOfNotFound bool // answers 403 where the contract says 404
- honourGrantOverCustody bool // answers VISIBLE for a granted item
+ intersectWithTeamRung bool // revision 9's rule: NOT_VISIBLE for anything off the team rung
+ linkCountsAsGrant bool // answers VISIBLE for a link-shared item
leakVisibilityInFeed bool // adds a field the feed row may not carry
leakBodyInRefusal bool // right status, and the item's secrets in the body
wrongBodyForTeamItem bool // 200, carrying a different item's bytes
@@ -62,7 +63,8 @@ func (s *referenceServer) serveS3(w http.ResponseWriter, r *http.Request) {
}
return
}
- if c.Rung == suite.RungTeam {
+ // Revision 10: every live item is held, so every live item is served.
+ if c.Rung != suite.RungDeleted {
w.WriteHeader(200)
if s.wrongBodyForTeamItem {
w.Write([]byte("the bytes of some other document entirely"))
@@ -100,6 +102,22 @@ func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
stranger := req.Asker.Value != s.fixture.Asker.Value
+ // mayOpen is the app's own read check (revision 10): the team rung for
+ // any member, the item's owner, or a live individual grant. A link is
+ // not a grant, and a deleted item opens for nobody.
+ mayOpen := func(c suite.CustodyCase) bool {
+ if c.Rung == suite.RungDeleted {
+ return false
+ }
+ if s.linkCountsAsGrant && c.Link != "" {
+ return true
+ }
+ if s.intersectWithTeamRung {
+ return c.Rung == suite.RungTeam
+ }
+ return c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant
+ }
+
for _, p := range req.Pairs {
c, ok := s.find(p.ItemID)
answer := suite.NOT_VISIBLE
@@ -118,15 +136,10 @@ func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
// No team standing reaches nothing, the team rung included.
answer = suite.NOT_VISIBLE
- case c.Rung == suite.RungTeam && p.Revision != c.Revision:
+ case mayOpen(c) && p.Revision != c.Revision:
answer = suite.STALE
- case c.Rung == suite.RungTeam:
- answer = suite.VISIBLE
-
- case s.honourGrantOverCustody && c.Rung == suite.RungGranted:
- // The bug the intersection exists to prevent: answering from the
- // grants join alone, so a grantee learns a non-team item exists.
+ case mayOpen(c):
answer = suite.VISIBLE
}
out.Results = append(out.Results, result{ItemID: p.ItemID, Revision: p.Revision, Result: answer})
@@ -142,7 +155,7 @@ func (s *referenceServer) serveS1(w http.ResponseWriter, r *http.Request) {
row := map[string]any{
"item_id": c.ItemID,
"revision": c.Revision,
- "gone": c.Rung != suite.RungTeam,
+ "gone": c.Rung == suite.RungDeleted,
"touched_at": "2026-09-05T09:00:00Z",
}
if s.leakVisibilityInFeed {
@@ -186,17 +199,32 @@ func TestHarnessCatches403ForANonTeamItem(t *testing.T) {
}
}
-// §4.3's custody intersection. A server answering from its grants join alone
-// says VISIBLE for an individually granted item, and a consumer holding that
-// item's id learns it still exists.
-func TestHarnessCatchesGrantBeatingCustody(t *testing.T) {
+// Revision 10 (Paul, 2026-11-01) removed §4.3's custody intersection: the
+// consumer holds every live item, and S2 answers from the app's own read
+// check. A server still answering by revision 9's rule — NOT_VISIBLE for
+// anything off the team rung — hides a person's own private documents and
+// those granted to them from their own search.
+func TestHarnessCatchesTheOldTeamOnlyRule(t *testing.T) {
+ s := newReference(t)
+ s.intersectWithTeamRung = true
+
+ report := conformance.Check(s)
+
+ if len(report.Failures) == 0 {
+ t.Error("harness passed a server whose S2 still intersects with the team rung")
+ }
+}
+
+// A link is not a grant (§4.2), and with custody widened it is the line
+// that keeps a link-shared private document out of a teammate's search.
+func TestHarnessCatchesALinkCountedAsAGrant(t *testing.T) {
s := newReference(t)
- s.honourGrantOverCustody = true
+ s.linkCountsAsGrant = true
report := conformance.Check(s)
if len(report.Failures) == 0 {
- t.Error("harness passed a server whose S2 ignored the custody intersection")
+ t.Error("harness passed a server whose S2 treats a read link as a grant")
}
}
diff --git a/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md b/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
index f5ac5c6..0db6aaa 100644
--- a/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
+++ b/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
@@ -3,7 +3,53 @@
How the apps of the suite share identity, membership and content with
each other, and where the line is that nothing crosses.
-**Status:** design, **revision 9**, 2026-10-26.
+**Status:** design, **revision 10**, 2026-11-01. Revision 10 awaits its
+review pass (AGENTS.md); until then it is a proposal carrying Paul's ruling.
+
+**Revision 10 widens custody to every live item, by Paul's ruling, and
+builds the producer half.** Asked *"Is it possible for everyone's Memoria to
+respect / search across the things that only they have access to?"* and
+offered three answers — keep custody to the team rung; let a consumer hold
+private and granted items too and rule each one per person on every
+request; or search each app live and copy nothing — Paul chose the second:
+**"Hold private too, check per person"** (2026-11-01). The same day he ruled
+Docs' sharing default: *"New docs Team, old private"* — a new document is on
+the `team` rung unless its owner makes it private, and an existing document
+stays where it is. What changes, each where it lives:
+
+- **§4.2 custody** is every live item. The ladder still exists and still
+ decides who may open what inside the app; it no longer bounds what a
+ consumer may hold. `gone` means deleted, and only that.
+- **§4.3**: S2 is the app's own read check for the named asker — the team
+ rung for a member, ownership, a live grant, never a link — with **no
+ intersection with custody**. The cost the intersection paid is gone with
+ it; the risk it carried moves into S2 itself (below).
+- **S3** serves every live item, and refuses with one byte-identical 404
+ only what is deleted, unknown, at a revision that is not current, or too
+ large to serve.
+- **The fixture** (`custody.json`) is rewritten to that rule, with an
+ `owner` and `asker_grant` per case so an app can seed it; the harness's
+ reference server is the new rule, and its broken variants now include
+ revision 9's team-only S2 and a link counted as a grant.
+- **§6.5** is new: the producer half, `amadan.net/oficina/suite/server`.
+
+**What Paul accepted, said plainly.** Under revision 9 a consumer held only
+what every teammate could read, so a bug in its per-person gate could at
+worst show a teammate something they could already open in the app. Under
+revision 10 a consumer holds everyone's private and individually shared
+items, sealed at rest like everything else it holds, and the same bug shows
+a teammate somebody else's private document. S2 — asked per person, per
+request, never cached, with every non-`VISIBLE` answer withholding — is now
+the only thing between those documents and a teammate's search, and every
+surface of a consumer that names an item must pass through it, not search
+alone. A consumer also learns that private items exist, which §4.2's
+indistinguishability used to hide from it; it was never a person, and the
+person-facing guarantee is S2's.
+
+**What is not ruled by this revision:** guests. A guest is never on a
+roster, so a consumer never names one as an asker; an item granted only to a
+guest is held, and only its owner (and any member it is also granted to)
+sees it in a consumer.
**Revision 8 records that the contract module cannot be imported**, which
makes §12 step 2 built rather than done. `amadan.net/oficina/suite` does not
@@ -275,6 +321,15 @@ they are claimed as (memoria §6.3).
### 4.2 Custody
+> **Revision 10 (Paul, 2026-11-01): custody is every live item.** The
+> predicate below — team-visible — and the ladder now decide only who may
+> open an item inside its app, through S2 (§4.3); they no longer bound what
+> a consumer holds. A consumer holds every live item, `gone` means deleted
+> and nothing else, and S3 serves every live item. The text that follows is
+> revision 9's and is kept because its reasoning — a link is not a grant,
+> the rung and not the link decides — still governs S2. Where it says a
+> private item must not reach a consumer, revision 10 overrules it.
+
What a sibling may *hold* a copy of. The predicate is **team-visible**:
readable by every roster member by virtue of team standing alone. Each app
defines it in one function, and the conformance suite (§11) proves that a
@@ -385,6 +440,13 @@ in.** A copy never becomes an authority, and a derived artefact carries the
provenance of every source it was built from, transitively, so two hops
cannot launder what one cannot (memoria §13, now a suite rule).
+> **Revision 10 (Paul, 2026-11-01) removes the intersection below.** With
+> custody widened to every live item there is nothing to intersect with: S2
+> is the app's own read check for the named asker — the team rung for a
+> member, ownership, a live individual grant, never a link. A person's own
+> private documents and those granted to them reach their own search, and
+> nobody else's. The two paragraphs that follow are revision 9's.
+
**S2's answer is intersected with custody.** The app of record runs its
grants join for the named asker, and then answers `NOT_VISIBLE` for any
item that is not team-visible, whatever the asker's individual grants say.
@@ -720,6 +782,40 @@ Both are settled; they are recorded here because a table that runs S1, S2,
S3, S6, S8 leaves two holes, and a hole in a numbered contract is somewhere
a later call falls. *(Review pass, 2026-09-05.)*
+### 6.5 The producer half (revision 10)
+
+`amadan.net/oficina/suite/server` is the server half §6 names, built with
+the first two apps that serve it (Docs and Fichas). An app implements one
+interface, `Producer` — `Feed(cursor, limit)`, `Rule(asker, pairs)`,
+`Content(item, revision)` — and mounts `server.Handler` beside its router.
+The package owns everything an app could get subtly wrong and must not get
+differently from its neighbour:
+
+- **The bearer check.** `<APP>_SUITE_CONSUMERS` is strict JSON,
+ `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<hex>"}]}]`,
+ one or two tokens per consumer (§6.2's rotation), each held only as its
+ SHA-256. Every configured hash is compared in constant time, and every
+ failure is the same empty 401. Unset means no consumers and no routes;
+ malformed refuses boot.
+- **S1.** `rows` is never null; a producer's empty cursor is a 500, and a
+ failed read a 503, never an empty page. At the tip the producer returns
+ the cursor it was given and no rows, which is what stops memoria's poll.
+ 256 rows a page.
+- **S2.** The request is decoded strictly (no unknown fields, no trailing
+ document), the asker through `NewSubject`, the batch through
+ `CheckS2Batch`; anything else is a 400. A producer error is a 503, which
+ the consumer reads as `UNKNOWN` for the whole call; an answer count that
+ differs from the pair count is a 500. Every pair is echoed.
+- **S3.** One refusal — an empty 404 — for a deleted item, an id that
+ never existed, a revision that is not current, missing or malformed, and
+ a body over 2 MiB (memoria refuses more than 2 MiB + 64 KiB and would
+ otherwise retry the same feed page for ever). Never 403. A 200 is
+ `text/plain`.
+
+`server.Routes` is the same routes without the bearer check, for the
+conformance harness, which drives a handler with no token. An app never
+mounts it. The package keeps the module's rule: standard library only.
+
### 6.1 Why two credentials
**Only the home can mint an assertion**, and putting the home in the loop
diff --git a/fixtures.go b/fixtures.go
index 1e63ad5..a1bea5d 100644
--- a/fixtures.go
+++ b/fixtures.go
@@ -39,14 +39,22 @@ const (
)
// CustodyCase is one row of the custody fixture: an item, where it sits, and
-// what both calls must answer for the fixture's asker.
+// what both calls must answer for the fixture's asker. Since revision 10
+// (Paul, 2026-11-01) a consumer holds every live item and S2 answers from
+// the app's own read check, so the rung matters only through that check.
type CustodyCase struct {
Name string `json:"name"`
ItemID string `json:"item_id"`
Revision int64 `json:"revision"`
Rung Rung `json:"rung"`
Link string `json:"link"`
- S3Status int `json:"s3_status"`
+ // Owner is "asker" when the fixture's asker owns the item and "other"
+ // when somebody else does; AskerGrant is whether the asker holds a live
+ // individual grant on it. Together with Rung they are what an app seeds
+ // so its own read check produces the S2 answers below (revision 10).
+ Owner string `json:"owner"`
+ AskerGrant bool `json:"asker_grant"`
+ S3Status int `json:"s3_status"`
// S3Body is the exact body a content fetch must return: the item's bytes
// for a 200, and empty for every refusal. Checking the status alone let a
// server return the required 404 while including the item's secrets in the
@@ -62,9 +70,9 @@ type CustodyCase struct {
}
// NonexistentItemID is never in the fixture. A refusal for an item that does
-// not exist has to be byte-for-byte the refusal for one that exists and is not
-// team-visible — that indistinguishability is the whole of §4.2, and no case
-// in the fixture can test it, because every case is an item that exists.
+// not exist has to be byte-for-byte the refusal for one that was deleted, so
+// a consumer cannot tell a deletion from an id it made up. (Before revision
+// 10 the same held for every item that was not team-visible.)
const NonexistentItemID = "doc-no-such-item-ever"
// CustodyFixture is gate 3's world: one case per rung, plus team-plus-link and
diff --git a/fixtures/custody.json b/fixtures/custody.json
index fb10c04..92589fc 100644
--- a/fixtures/custody.json
+++ b/fixtures/custody.json
@@ -1,33 +1,44 @@
{
"comment": [
- "Gate 3. One fixture per rung of the sharing ladder (doctrine §4.2,",
- "ruling 15), plus the two cases the reviews asked for: an item on the",
- "team rung that also carries a link, and an item whose link changed",
- "after it was ingested.",
+ "Gate 3. One fixture per rung of the sharing ladder (doctrine §4.2), plus",
+ "the cases the reviews asked for: an item on the team rung that also",
+ "carries a link, and an item whose link or rung changed after it was",
+ "ingested.",
+ "",
+ "REVISION 10 (Paul, 2026-11-01): custody is every live item, not only",
+ "team-visible ones. A consumer holds private and granted items too, and",
+ "S2 decides per person, from the app's own read check, with no",
+ "intersection with custody. So every live item answers S3 200 with its",
+ "own bytes; only a deleted item, and one that never existed, answer the",
+ "identical 404.",
"",
"The asker is the same person for every case, and the item id is quoted",
"in every case, so a server cannot pass by answering differently for",
- "different ids. What must differ is the rung; what must not differ is",
- "the answer for everything that is not `team`.",
- "",
- "s3_status is what a content fetch answers. s2_result is what an",
- "authorization call answers for `asker`, who deliberately holds a live",
- "grant on doc-private and doc-granted and a former grant on doc-deleted:",
- "the intersection with custody (§4.3) must beat the grant every time."
+ "different ids. `owner` says who owns the item (the asker or someone",
+ "else) and `asker_grant` whether the asker holds a live individual grant",
+ "on it, so an app can seed the world. What must differ is whether the",
+ "asker may open the item today; the rung decides that only through the",
+ "app's own read check."
],
-
"team": "acme",
- "asker": { "kind": "person_ref", "value": "pers_ana" },
- "stranger": { "kind": "person_ref", "value": "pers_bo" },
-
+ "asker": {
+ "kind": "person_ref",
+ "value": "pers_ana"
+ },
+ "stranger": {
+ "kind": "person_ref",
+ "value": "pers_bo"
+ },
"cases": [
{
- "name": "team rung is the only thing custody admits",
+ "name": "team rung: every member may open it",
"item_id": "doc-team",
"s3_body": "the Q3 plan, shared with the whole team",
"revision": 7,
"rung": "team",
"link": null,
+ "owner": "other",
+ "asker_grant": false,
"s3_status": 200,
"s2_result": "VISIBLE",
"s2_result_superseded": "STALE",
@@ -36,47 +47,55 @@
{
"name": "private, and the asker owns it",
"item_id": "doc-private",
- "s3_body": "",
+ "s3_body": "my own notes, private to me",
"revision": 4,
"rung": "private",
"link": null,
- "s3_status": 404,
- "s2_result": "NOT_VISIBLE",
- "s2_result_superseded": "NOT_VISIBLE",
+ "owner": "asker",
+ "asker_grant": false,
+ "s3_status": 200,
+ "s2_result": "VISIBLE",
+ "s2_result_superseded": "STALE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "granted to the asker individually",
+ "name": "private to someone else, granted to the asker by name",
"item_id": "doc-granted",
- "s3_body": "",
+ "s3_body": "the board pack, shared with me by name",
"revision": 9,
"rung": "granted",
"link": null,
- "s3_status": 404,
- "s2_result": "NOT_VISIBLE",
- "s2_result_superseded": "NOT_VISIBLE",
+ "owner": "other",
+ "asker_grant": true,
+ "s3_status": 200,
+ "s2_result": "VISIBLE",
+ "s2_result_superseded": "STALE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "granted to a guest only",
+ "name": "granted to a guest only: held, and the asker may not open it",
"item_id": "doc-guest",
- "s3_body": "",
+ "s3_body": "the contractor brief, shared with a guest only",
"revision": 2,
"rung": "granted",
"link": null,
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "link-shared but not team-shared: a link is not a rung",
+ "name": "private to someone else and link-shared: a link is not a grant",
"item_id": "doc-link",
- "s3_body": "",
+ "s3_body": "the press draft, private with a read link",
"revision": 5,
"rung": "private",
"link": "read",
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
@@ -88,6 +107,8 @@
"revision": 3,
"rung": "team",
"link": "read",
+ "owner": "other",
+ "asker_grant": false,
"s3_status": 200,
"s2_result": "VISIBLE",
"s2_result_superseded": "STALE",
@@ -100,19 +121,23 @@
"revision": 6,
"rung": "deleted",
"link": null,
+ "owner": "other",
+ "asker_grant": true,
"s3_status": 404,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "ingested on the team rung, since moved to private",
+ "name": "ingested on the team rung, since moved to private by its owner",
"item_id": "doc-was-team",
- "s3_body": "",
+ "s3_body": "the old roadmap, moved back to private",
"revision": 8,
"rung": "private",
"link": null,
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
@@ -120,11 +145,13 @@
{
"name": "a link added after ingest changes nothing either way",
"item_id": "doc-link-added-late",
- "s3_body": "",
+ "s3_body": "the hiring plan, private, link added later",
"revision": 11,
"rung": "private",
"link": "read",
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
diff --git a/server/consumers.go b/server/consumers.go
new file mode 100644
index 0000000..13e6be9
--- /dev/null
+++ b/server/consumers.go
@@ -0,0 +1,113 @@
+package server
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+// Consumer is one sibling allowed to call this app's suite routes: memoria,
+// today. Doctrine §6.2: one bearer token per consumer, minted by the
+// operator, delivered as platform config, and held here only as its SHA-256.
+// Up to two tokens at once, each with an epoch, so a token can be rotated in
+// three steps (accept both, switch the sender, drop the old) without a gap.
+type Consumer struct {
+ ID string `json:"consumer_id"`
+ Tokens []Token `json:"tokens"`
+}
+
+// Token is one accepted token, as the hex SHA-256 of its bytes.
+type Token struct {
+ Epoch int `json:"epoch"`
+ SHA256 string `json:"sha256"`
+}
+
+// MaxTokensPerConsumer is two: the old token and the new one, for the length
+// of a rotation, and never more.
+const MaxTokensPerConsumer = 2
+
+// EnvSuffix names the variable an app reads its consumers from:
+// <APP>_SUITE_CONSUMERS, e.g. DOCS_SUITE_CONSUMERS.
+const EnvSuffix = "_SUITE_CONSUMERS"
+
+// ConsumersFromEnv reads <app>_SUITE_CONSUMERS. Unset or empty is no
+// consumers — the routes are not served — and anything malformed is an
+// error, so a typo refuses boot rather than silently serving nobody.
+func ConsumersFromEnv(getenv func(string) string, app string) ([]Consumer, error) {
+ return ParseConsumers(getenv(strings.ToUpper(app) + EnvSuffix))
+}
+
+// ParseConsumers reads the strict JSON list:
+//
+// [{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}]
+func ParseConsumers(raw string) ([]Consumer, error) {
+ if strings.TrimSpace(raw) == "" {
+ return nil, nil
+ }
+ dec := json.NewDecoder(bytes.NewReader([]byte(raw)))
+ dec.DisallowUnknownFields()
+ var cs []Consumer
+ if err := dec.Decode(&cs); err != nil || dec.More() {
+ return nil, errors.New("suite consumers: not the agreed JSON list")
+ }
+ seen := map[string]bool{}
+ for _, c := range cs {
+ if c.ID == "" || seen[c.ID] {
+ return nil, errors.New("suite consumers: a consumer_id is empty or repeated")
+ }
+ seen[c.ID] = true
+ if len(c.Tokens) == 0 || len(c.Tokens) > MaxTokensPerConsumer {
+ return nil, fmt.Errorf("suite consumers: %s must have one or two tokens", c.ID)
+ }
+ for _, t := range c.Tokens {
+ b, err := hex.DecodeString(t.SHA256)
+ if err != nil || len(b) != sha256.Size {
+ return nil, fmt.Errorf("suite consumers: %s has a token that is not a hex SHA-256", c.ID)
+ }
+ }
+ }
+ return cs, nil
+}
+
+// TokenHash is what an operator puts in the consumers list for a token.
+func TokenHash(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+// Authenticate admits a request carrying a configured consumer's token and
+// answers every other one with the same empty 401: no token, a malformed
+// header, an unknown token and a retired one are indistinguishable. Every
+// configured hash is compared, in constant time, whatever matched first.
+func Authenticate(consumers []Consumer, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ tok, ok := bearer(r)
+ if !ok || tok == "" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ sum := sha256.Sum256([]byte(tok))
+ var match Consumer
+ found := 0
+ for _, c := range consumers {
+ for _, t := range c.Tokens {
+ want, _ := hex.DecodeString(t.SHA256)
+ if subtle.ConstantTimeCompare(sum[:], want) == 1 {
+ match = c
+ found = 1
+ }
+ }
+ }
+ if found == 0 {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ next.ServeHTTP(w, r.WithContext(contextWithConsumer(r.Context(), match)))
+ })
+}
diff --git a/server/server.go b/server/server.go
new file mode 100644
index 0000000..4f7e791
--- /dev/null
+++ b/server/server.go
@@ -0,0 +1,244 @@
+// Package server is the producer half of the suite contract: the three
+// routes an app of record serves so a same-team consumer (memoria) can hold
+// and rule on its items. Doctrine §6; revision 10 (Paul, 2026-11-01) for what
+// is held.
+//
+// An app implements Producer — its feed, its own per-person read check, and
+// an item's text — and mounts Handler beside its router. Everything the
+// contract fixes and an app could get subtly wrong lives here instead: the
+// bearer check, the strict S2 decode and cap, the wire shapes, and the one
+// byte-identical refusal S3 gives for anything it will not serve.
+//
+// Like the rest of the module it has no dependencies beyond the standard
+// library, so an app's pin chain stays one deep (AGENTS.md).
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/suite"
+)
+
+// Producer is an app's half of the contract.
+type Producer interface {
+ // Feed returns the rows after cursor — "" is the beginning — at most
+ // limit of them, in the app's own log order, and the cursor to ask from
+ // next. At the tip it returns rows: [] and the SAME cursor it was given
+ // (a consumer stops polling only when the cursor comes back unchanged
+ // with no rows; a fresh cursor at the tip makes it page forever). The
+ // cursor is opaque and never empty.
+ //
+ // Since revision 10 the feed carries every live item, private and
+ // granted ones included; gone means deleted, and nothing else.
+ Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error)
+
+ // Rule answers, for each pair in order, whether asker may open that item
+ // now: the app's own read check (team rung, ownership, a live grant;
+ // never a link). VISIBLE at the current revision; STALE when the asker
+ // may open it and the asked revision is older than current; NOT_VISIBLE
+ // when the asker may not, or the item is deleted or unknown; UNKNOWN when
+ // the app cannot say (an asker of a kind it does not key on, a revision
+ // its log does not recognise, a roster it cannot reach). Never cached.
+ // It returns exactly len(pairs) answers.
+ Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error)
+
+ // Content returns the item's text at revision, as the plain text a
+ // consumer indexes. suite.ErrNotAvailable for a deleted item, an unknown
+ // id, or a revision that is not the current one; this package turns it
+ // into the one refusal every such case shares.
+ Content(ctx context.Context, itemID string, revision int64) ([]byte, error)
+}
+
+// FeedPageLimit is how many rows one S1 page carries. memoria caps an S1
+// response at 4 MiB; a row is under 200 bytes on the wire, so 256 rows sit
+// two orders of magnitude inside it, and memoria pages up to 50 times a poll.
+const FeedPageLimit = 256
+
+// MaxContentBytes is the largest body S3 serves. memoria refuses a body over
+// 2 MiB + 64 KiB as an error and retries the same feed page for ever, so an
+// item over this is answered as not available instead — counted by the
+// consumer as missing, and the feed moves on. The slack keeps a body at
+// exactly this size well inside the consumer's cap.
+const MaxContentBytes = 2 << 20
+
+// maxS2Body bounds an S2 request: 256 pairs of a long id and a revision,
+// and an asker, are far under it.
+const maxS2Body = 256 << 10
+
+// Handler returns the authenticated routes, or nil when no consumer is
+// configured: an app with no consumers serves no suite routes at all
+// (doctrine §3, A.2 — the routes exist wherever consumer tokens do).
+func Handler(p Producer, consumers []Consumer, logger *slog.Logger) http.Handler {
+ if len(consumers) == 0 {
+ return nil
+ }
+ return Authenticate(consumers, Routes(p, logger))
+}
+
+// Routes is the three routes with no authentication. An app never mounts it
+// directly; it exists for Handler and for the conformance harness, which
+// drives a handler without a bearer token.
+func Routes(p Producer, logger *slog.Logger) http.Handler {
+ if logger == nil {
+ logger = slog.New(slog.NewTextHandler(io.Discard, nil))
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET "+suite.RouteS1, func(w http.ResponseWriter, r *http.Request) { serveS1(p, logger, w, r) })
+ mux.HandleFunc("POST "+suite.RouteS2, func(w http.ResponseWriter, r *http.Request) { serveS2(p, logger, w, r) })
+ mux.HandleFunc("GET "+suite.RouteS3+"/{item}", func(w http.ResponseWriter, r *http.Request) { serveS3(p, logger, w, r) })
+ return mux
+}
+
+func serveS1(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ cursor := r.URL.Query().Get("cursor")
+ feed, err := p.Feed(r.Context(), cursor, FeedPageLimit)
+ if err != nil {
+ // Never an empty feed: an empty page for a failed read would move a
+ // consumer's cursor past changes it never saw.
+ logger.Error("suite S1: feed failed", "err", err)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if err := checkFeed(feed); err != nil {
+ logger.Error("suite S1: producer broke the contract", "err", err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ if feed.Rows == nil {
+ feed.Rows = []suite.FeedRow{}
+ }
+ writeJSON(w, feed)
+}
+
+// checkFeed holds the producer to what DecodeS1 will demand, so a mistake
+// is a 500 here rather than a consumer stalling on a page it refuses.
+func checkFeed(f suite.Feed) error {
+ if f.Cursor == "" {
+ return errors.New("empty cursor")
+ }
+ if len(f.Rows) > FeedPageLimit {
+ return errors.New("page over the limit")
+ }
+ for _, row := range f.Rows {
+ if row.ItemID == "" || row.TouchedAt.IsZero() {
+ return errors.New("row without an item id or a time")
+ }
+ }
+ return nil
+}
+
+type s2Result struct {
+ ItemID string `json:"item_id"`
+ Revision int64 `json:"revision"`
+ Result suite.Authorization `json:"result"`
+}
+
+func serveS2(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxS2Body))
+ dec.DisallowUnknownFields()
+ var req suite.S2Request
+ if err := dec.Decode(&req); err != nil || dec.More() {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ asker, err := suite.NewSubject(req.Asker.Kind, req.Asker.Value)
+ if err != nil || req.Pairs == nil || suite.CheckS2Batch(req.Pairs) != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ for _, pr := range req.Pairs {
+ if pr.ItemID == "" {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ }
+ answers, err := p.Rule(r.Context(), asker, req.Pairs)
+ if err != nil {
+ // A non-2xx is UNKNOWN for the whole call on the consumer's side:
+ // withheld loudly, never silently.
+ logger.Error("suite S2: rule failed", "err", err)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if len(answers) != len(req.Pairs) {
+ logger.Error("suite S2: producer broke the contract", "err", "answer count differs from pair count")
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ out := struct {
+ Results []s2Result `json:"results"`
+ }{Results: make([]s2Result, len(answers))}
+ for i, a := range answers {
+ out.Results[i] = s2Result{ItemID: req.Pairs[i].ItemID, Revision: req.Pairs[i].Revision, Result: a}
+ }
+ writeJSON(w, out)
+}
+
+func serveS3(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ item := r.PathValue("item")
+ rev, err := strconv.ParseInt(r.URL.Query().Get("revision"), 10, 64)
+ if item == "" || err != nil || rev < 1 {
+ notAvailable(w)
+ return
+ }
+ body, err := p.Content(r.Context(), item, rev)
+ switch {
+ case errors.Is(err, suite.ErrNotAvailable):
+ notAvailable(w)
+ return
+ case err != nil:
+ logger.Error("suite S3: content failed", "err", err)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ case len(body) > MaxContentBytes:
+ notAvailable(w)
+ return
+ }
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(http.StatusOK)
+ w.Write(body)
+}
+
+// notAvailable is the one refusal S3 gives: the same status, headers and
+// (empty) body for a deleted item, an id that never existed, a superseded or
+// malformed revision and an item too large to serve, so none of them can be
+// told apart. Never 403.
+func notAvailable(w http.ResponseWriter) {
+ w.WriteHeader(http.StatusNotFound)
+}
+
+func writeJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ json.NewEncoder(w).Encode(v)
+}
+
+// contextKey carries the authenticated consumer.
+type contextKey struct{}
+
+// ConsumerFrom returns the consumer a request authenticated as, for an app
+// that keeps per-consumer state.
+func ConsumerFrom(ctx context.Context) (Consumer, bool) {
+ c, ok := ctx.Value(contextKey{}).(Consumer)
+ return c, ok
+}
+
+func bearer(r *http.Request) (string, bool) {
+ h := r.Header.Get("Authorization")
+ const prefix = "Bearer "
+ if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
+ return "", false
+ }
+ return strings.TrimSpace(h[len(prefix):]), true
+}
+
+func contextWithConsumer(ctx context.Context, c Consumer) context.Context {
+ return context.WithValue(ctx, contextKey{}, c)
+}
diff --git a/server/server_test.go b/server/server_test.go
new file mode 100644
index 0000000..b2c2f48
--- /dev/null
+++ b/server/server_test.go
@@ -0,0 +1,332 @@
+package server_test
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/conformance"
+ "amadan.net/oficina/suite/server"
+)
+
+// fixtureProducer is a correct Producer built from the custody fixture, the
+// same world the conformance harness checks.
+type fixtureProducer struct {
+ f suite.CustodyFixture
+ feedErr error
+ ruleErr error
+ short bool // Rule answers one fewer than asked
+ cursor string // overrides the feed's cursor when set
+ content []byte // overrides S3 bytes when set
+ lastAsker suite.Subject
+}
+
+func (p *fixtureProducer) find(id string) (suite.CustodyCase, bool) {
+ for _, c := range p.f.Cases {
+ if c.ItemID == id {
+ return c, true
+ }
+ }
+ return suite.CustodyCase{}, false
+}
+
+func (p *fixtureProducer) Feed(_ context.Context, cursor string, limit int) (suite.Feed, error) {
+ if p.feedErr != nil {
+ return suite.Feed{}, p.feedErr
+ }
+ if cursor == "end" {
+ return suite.Feed{Cursor: "end"}, nil
+ }
+ var rows []suite.FeedRow
+ for _, c := range p.f.Cases {
+ rows = append(rows, suite.FeedRow{ItemID: c.ItemID, Revision: c.Revision, Gone: c.Rung == suite.RungDeleted, TouchedAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)})
+ }
+ next := "end"
+ if p.cursor != "" {
+ next = p.cursor
+ }
+ if p.cursor == "-" {
+ next = ""
+ }
+ return suite.Feed{Cursor: next, Rows: rows}, nil
+}
+
+func (p *fixtureProducer) Rule(_ context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
+ p.lastAsker = asker
+ if p.ruleErr != nil {
+ return nil, p.ruleErr
+ }
+ out := make([]suite.Authorization, 0, len(pairs))
+ for _, pr := range pairs {
+ c, ok := p.find(pr.ItemID)
+ may := ok && asker == p.f.Asker && c.Rung != suite.RungDeleted && (c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant)
+ switch {
+ case !may:
+ out = append(out, suite.NOT_VISIBLE)
+ case pr.Revision != c.Revision:
+ out = append(out, suite.STALE)
+ default:
+ out = append(out, suite.VISIBLE)
+ }
+ }
+ if p.short {
+ out = out[:len(out)-1]
+ }
+ return out, nil
+}
+
+func (p *fixtureProducer) Content(_ context.Context, id string, rev int64) ([]byte, error) {
+ c, ok := p.find(id)
+ if !ok || c.Rung == suite.RungDeleted || rev != c.Revision {
+ return nil, suite.ErrNotAvailable
+ }
+ if p.content != nil {
+ return p.content, nil
+ }
+ return []byte(c.S3Body), nil
+}
+
+func producer(t *testing.T) *fixtureProducer {
+ t.Helper()
+ f, err := suite.LoadCustodyFixture()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &fixtureProducer{f: f}
+}
+
+const token = "a-test-token-for-memoria"
+
+func consumers(t *testing.T, tokens ...string) []server.Consumer {
+ t.Helper()
+ var ts []server.Token
+ for i, tok := range tokens {
+ ts = append(ts, server.Token{Epoch: i + 1, SHA256: server.TokenHash(tok)})
+ }
+ return []server.Consumer{{ID: "memoria", Tokens: ts}}
+}
+
+func do(h http.Handler, method, url, tok string, body []byte) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, url, bytes.NewReader(body))
+ if tok != "" {
+ req.Header.Set("Authorization", "Bearer "+tok)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
+// The routes this package serves pass the doctrine's own harness, driven
+// through a producer that only knows the fixture. The harness never sends a
+// malformed revision or an unauthenticated request, which is why the tests
+// below exist beside it.
+func TestRoutesPassConformance(t *testing.T) {
+ conformance.Run(t, server.Routes(producer(t), nil))
+}
+
+// No consumers, no routes (doctrine §3).
+func TestNoConsumersServesNothing(t *testing.T) {
+ if h := server.Handler(producer(t), nil, nil); h != nil {
+ t.Fatal("Handler with no consumers returned routes")
+ }
+}
+
+// Every failure to authenticate is the same empty 401, and both tokens of a
+// rotation are accepted.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the hash comparison skipped
+// (any bearer admitted) → "an unknown token"; only the first token of a
+// consumer compared → "the second token"; a reason written in the 401 body
+// → "alike".
+func TestAuthentication(t *testing.T) {
+ h := server.Handler(producer(t), consumers(t, token, "the-next-token"), nil)
+ ok := do(h, "GET", suite.RouteS1, token, nil)
+ if ok.Code != 200 {
+ t.Fatalf("the configured token: %d", ok.Code)
+ }
+ if rec := do(h, "GET", suite.RouteS1, "the-next-token", nil); rec.Code != 200 {
+ t.Errorf("the second token of a rotation: %d", rec.Code)
+ }
+ var first string
+ for name, req := range map[string]func() *http.Request{
+ "no header": func() *http.Request { return httptest.NewRequest("GET", suite.RouteS1, nil) },
+ "an unknown token": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Bearer not-the-token")
+ return r
+ },
+ "not a bearer": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Basic "+token)
+ return r
+ },
+ "an empty bearer": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Bearer ")
+ return r
+ },
+ } {
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req())
+ if rec.Code != 401 {
+ t.Errorf("%s: %d, want 401", name, rec.Code)
+ }
+ got := strconv.Itoa(rec.Code) + "|" + rec.Body.String()
+ if first == "" {
+ first = got
+ } else if got != first {
+ t.Errorf("%s: refusals not alike: %q vs %q", name, got, first)
+ }
+ }
+}
+
+func TestParseConsumers(t *testing.T) {
+ good := `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("x") + `"}]}]`
+ if cs, err := server.ParseConsumers(good); err != nil || len(cs) != 1 || cs[0].ID != "memoria" {
+ t.Fatalf("good: %+v, %v", cs, err)
+ }
+ if cs, err := server.ParseConsumers(" "); err != nil || cs != nil {
+ t.Errorf("empty is no consumers: %+v, %v", cs, err)
+ }
+ h := server.TokenHash("x")
+ for name, bad := range map[string]string{
+ "an unknown field": `[{"consumer_id":"m","origin":"x","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
+ "three tokens": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"},{"epoch":2,"sha256":"` + h + `"},{"epoch":3,"sha256":"` + h + `"}]}]`,
+ "no tokens": `[{"consumer_id":"m","tokens":[]}]`,
+ "not hex": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"plaintext-token"}]}]`,
+ "a repeated id": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]},{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
+ "trailing content": good + `[]`,
+ "not a list": `{"consumer_id":"m"}`,
+ } {
+ if _, err := server.ParseConsumers(bad); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ if cs, err := server.ConsumersFromEnv(func(k string) string {
+ if k == "DOCS_SUITE_CONSUMERS" {
+ return good
+ }
+ return ""
+ }, "docs"); err != nil || len(cs) != 1 {
+ t.Errorf("ConsumersFromEnv: %+v, %v", cs, err)
+ }
+}
+
+// S1 holds the producer to what the consumer's decoder demands.
+func TestS1(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ rec := do(h, "GET", suite.RouteS1+"?cursor=", "", nil)
+ feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
+ if err != nil || len(feed.Rows) != len(p.f.Cases) || feed.Cursor != "end" {
+ t.Fatalf("first page: %+v, %v", feed, err)
+ }
+ // At the tip: rows [] (never null) and the same cursor back.
+ tip := do(h, "GET", suite.RouteS1+"?cursor=end", "", nil)
+ if !strings.Contains(tip.Body.String(), `"rows":[]`) {
+ t.Errorf("rows: the tip's rows are not an empty list: %s", tip.Body.String())
+ }
+ if feed, err := suite.DecodeS1(tip.Code, tip.Body.Bytes()); err != nil || feed.Cursor != "end" || len(feed.Rows) != 0 {
+ t.Errorf("tip: %+v, %v", feed, err)
+ }
+ p.cursor = "-"
+ if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 500 {
+ t.Errorf("an empty cursor from the producer: %d, want 500", rec.Code)
+ }
+ p.cursor, p.feedErr = "", errors.New("db down")
+ if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 503 {
+ t.Errorf("a failed feed: %d, want 503 (never an empty page)", rec.Code)
+ }
+}
+
+// S2 decodes strictly, caps the batch, echoes every pair, and fails loudly.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: DisallowUnknownFields removed →
+// "an unknown field"; the cap check removed → "257 pairs"; the answer-count
+// check removed → "a short answer"; a producer error answered 200 with no
+// results → "a failed rule".
+func TestS2(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ ask := func(body string) *httptest.ResponseRecorder { return do(h, "POST", suite.RouteS2, "", []byte(body)) }
+ asker := `{"kind":"person_ref","value":"pers_ana"}`
+ ok := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7},{"item_id":"doc-link","revision":5}]}`)
+ got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "doc-team", Revision: 7}, {ItemID: "doc-link", Revision: 5}}, ok.Code, ok.Body.Bytes())
+ if len(got) != 2 || got[0] != suite.VISIBLE || got[1] != suite.NOT_VISIBLE {
+ t.Fatalf("answers = %v (%d %s)", got, ok.Code, ok.Body.String())
+ }
+ if p.lastAsker != (suite.Subject{Kind: suite.SubjectPersonRef, Value: "pers_ana"}) {
+ t.Errorf("the asker reached the producer as %+v", p.lastAsker)
+ }
+ var many []string
+ for i := 0; i < 257; i++ {
+ many = append(many, `{"item_id":"doc-team","revision":7}`)
+ }
+ for name, body := range map[string]string{
+ "an unknown field": `{"asker":` + asker + `,"pairs":[],"extra":1}`,
+ "257 pairs": `{"asker":` + asker + `,"pairs":[` + strings.Join(many, ",") + `]}`,
+ "a bad kind": `{"asker":{"kind":"email","value":"x"},"pairs":[]}`,
+ "an empty asker": `{"asker":{"kind":"address","value":""},"pairs":[]}`,
+ "no pairs": `{"asker":` + asker + `}`,
+ "an empty item id": `{"asker":` + asker + `,"pairs":[{"item_id":"","revision":1}]}`,
+ "not JSON": `nope`,
+ "two documents": `{"asker":` + asker + `,"pairs":[]}{}`,
+ } {
+ if rec := ask(body); rec.Code != 400 {
+ t.Errorf("%s: %d, want 400", name, rec.Code)
+ }
+ }
+ p.short = true
+ if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 500 {
+ t.Errorf("a short answer: %d, want 500", rec.Code)
+ }
+ p.short, p.ruleErr = false, errors.New("roster unreachable")
+ if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 503 {
+ t.Errorf("a failed rule: %d, want 503", rec.Code)
+ }
+}
+
+// Every S3 refusal is the same response: a deleted item, an id that never
+// existed, a superseded, missing or malformed revision, and an item too
+// large to serve.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: a malformed revision answered
+// 400 → "malformed"; the size check removed → "too large"; ErrNotAvailable
+// answered 503 → "deleted".
+func TestS3RefusesAlike(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ base := do(h, "GET", suite.RouteS3+"/"+suite.NonexistentItemID+"?revision=1", "", nil)
+ if base.Code != 404 {
+ t.Fatalf("baseline: %d", base.Code)
+ }
+ sig := func(r *httptest.ResponseRecorder) string {
+ return strconv.Itoa(r.Code) + "|" + r.Header().Get("Content-Type") + "|" + r.Body.String()
+ }
+ for name, url := range map[string]string{
+ "deleted": suite.RouteS3 + "/doc-deleted?revision=6",
+ "superseded": suite.RouteS3 + "/doc-team?revision=6",
+ "missing": suite.RouteS3 + "/doc-team",
+ "malformed": suite.RouteS3 + "/doc-team?revision=seven",
+ "zero": suite.RouteS3 + "/doc-team?revision=0",
+ } {
+ if rec := do(h, "GET", url, "", nil); sig(rec) != sig(base) {
+ t.Errorf("%s: %q, want the baseline %q", name, sig(rec), sig(base))
+ }
+ }
+ p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes+1)
+ if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); sig(rec) != sig(base) {
+ t.Errorf("too large: %d, want the baseline", rec.Code)
+ }
+ p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes)
+ if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
+ t.Errorf("at the limit: %d %s", rec.Code, rec.Header().Get("Content-Type"))
+ }
+}