oficina / docs Public

Docs: serve the suite contract's producer half (suite revision 10)

suiteProducer implements amadan.net/oficina/suite/server.Producer, pinned at
suite main c38e3ad (spec §8.2.2):

- Feed pages suite_feed by id; the cursor is the last id in decimal, the
  tip returns the cursor given with no rows, and a cursor that does not
  parse is answered from the beginning ("0" at an empty tip).
- Rule maps the asker to Docs' actor: address in lone shape, through the
  same front door a request passes (configured member or live grant) and a
  person lookup that never creates; person_ref in team mode, through
  connect's link then the Home-only principal and the roster standing for
  that subject. The other kind is UNKNOWN for every pair. Per pair: deleted
  or unknown is NOT_VISIBLE; not readable through permissionScope is
  NOT_VISIBLE, or UNKNOWN under Unknown standing; readable is VISIBLE at
  the current revision, STALE below it, UNKNOWN above it or below 1. The
  person is checked before the revision. Nothing is cached.
- Content serves the current revision only, as the title, a blank line and
  Store.Text (an untitled document is its text alone), and re-reads the
  revision after the replay so a body is never labelled with a revision it
  does not match.

DOCS_SUITE_CONSUMERS (Config.SuiteConsumers) is parsed with
server.ParseConsumers before the database opens; malformed refuses boot,
empty mounts nothing. The three routes go on the outer ServeMux beside the
router as exactly GET /suite/s1, POST /suite/s2 and GET /suite/s3/{item},
so they sit outside the session, admission and homeCSRF layers and nothing
else under /suite/ does. The suite module is first-party for the Colophon.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ec1b8bb45f485048cd8ca99f982ecf475c5ef67f parent b516a6c
6 files changed, +332 −0
  • cmd/docs/main.go +5 −0
  • go.mod +1 −0
  • go.sum +2 −0
  • internal/docs/app.go +24 −0
  • internal/docs/suite.go +298 −0
  • internal/shipped/shipped.go +2 −0
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index f984078..39debaa 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"
@@ -285,6 +286,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/go.mod b/go.mod
index 31ed322..955a72b 100644
--- a/go.mod
+++ b/go.mod
@@ -8,6 +8,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 4f51c46..3a959b9 100644
--- a/go.sum
+++ b/go.sum
@@ -16,6 +16,8 @@ amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+
amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA=
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/app.go b/internal/docs/app.go
index afc0799..06d9773 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"
@@ -209,6 +210,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
}
@@ -389,6 +399,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 {
@@ -778,6 +794,14 @@ func New(cfg Config) (*App, error) {
mux := http.NewServeMux()
mux.Handle("/", r)
+ // 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
diff --git a/internal/docs/suite.go b/internal/docs/suite.go
new file mode 100644
index 0000000..4ee4930
--- /dev/null
+++ b/internal/docs/suite.go
@@ -0,0 +1,298 @@
+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
+}
+
+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 the last id served, in decimal;
+// "" is the beginning, and a cursor that does not parse is answered from the
+// beginning too (a re-announce is always safe; a refusal would stall the
+// consumer on its own stored cursor). 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, err := strconv.ParseInt(cursor, 10, 64)
+ valid := err == nil && after >= 0
+ if !valid {
+ after = 0
+ }
+ var rows []struct {
+ ID int64
+ Sqid string
+ Revision int64
+ Gone bool
+ TouchedAt time.Time
+ }
+ err = p.store.db.WithContext(ctx).Table("suite_feed").
+ Select("suite_feed.id, documents.sqid, suite_feed.revision, suite_feed.gone, suite_feed.touched_at").
+ 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. A
+ // cursor that did not parse ("" included) gets a real position to
+ // come back with instead, never "" (outside the contract).
+ if !valid {
+ 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()})
+ }
+ feed.Cursor = strconv.FormatInt(rows[len(rows)-1].ID, 10)
+ return feed, nil
+}
+
+// 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.
+func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
+ out := make([]suite.Authorization, len(pairs))
+ actor, ctx, uncertain, 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
+ }
+ ids := make([]string, 0, len(pairs))
+ for _, pr := range pairs {
+ ids = append(ids, pr.ItemID)
+ }
+ db := p.store.db.WithContext(ctx)
+
+ type current struct {
+ Sqid string
+ Revision int64
+ }
+ var live, readable []current
+ if err := liveDocuments(db.Model(&Document{})).Where("documents.sqid IN ?", ids).
+ Select("documents.sqid, documents.revision").Scan(&live).Error; err != nil {
+ return nil, err
+ }
+ if err := p.store.permissionScope(ctx, db.Model(&Document{}), actor, permissionRead).
+ Where("documents.sqid IN ? AND documents.deleted_at IS NULL", ids).
+ Select("documents.sqid, documents.revision").Scan(&readable).Error; err != nil {
+ return nil, err
+ }
+ isLive := make(map[string]bool, len(live))
+ for _, d := range live {
+ isLive[d.Sqid] = true
+ }
+ canRead := make(map[string]int64, len(readable))
+ for _, d := range readable {
+ canRead[d.Sqid] = d.Revision
+ }
+
+ for i, pr := range pairs {
+ rev, can := canRead[pr.ItemID]
+ switch {
+ case !isLive[pr.ItemID]:
+ // 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 pr.Revision >= 1 && pr.Revision < rev:
+ out[i] = suite.STALE
+ default:
+ // Ahead of Docs' own revision (a restore from backup, suite
+ // §4.3), or below 1: a revision this log does not recognise.
+ out[i] = suite.UNKNOWN
+ }
+ }
+ return out, nil
+}
+
+// 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. uncertain is team standing Unknown.
+//
+// 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, uncertain, keyed bool, err error) {
+ s := p.store
+ if s.team == nil {
+ if asker.Kind != suite.SubjectAddress {
+ return Actor{}, ctx, false, false, nil
+ }
+ address := subjectOf(asker.Value)
+ admitted, err := p.list.allows(address)
+ if err != nil {
+ return Actor{}, ctx, false, true, err
+ }
+ if !admitted {
+ return Actor{}, ctx, false, 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, false, true, nil
+ case err != nil:
+ return Actor{}, ctx, false, true, err
+ }
+ return localActor(person.ID, address), ctx, false, true, nil
+ }
+
+ if asker.Kind != suite.SubjectPersonRef {
+ return Actor{}, ctx, false, false, nil
+ }
+ subject := asker.Value
+ actor, err = p.homeActor(ctx, subject)
+ if err != nil {
+ return Actor{}, ctx, false, true, err
+ }
+ a := s.team.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject})
+ return actor, withAccess(ctx, a), a.state() == roster.Unknown, 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
+ }
+ 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/shipped/shipped.go b/internal/shipped/shipped.go
index 58585a2..92cca85 100644
--- a/internal/shipped/shipped.go
+++ b/internal/shipped/shipped.go
@@ -62,6 +62,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