| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/home/roster" |
| 12 | "amadan.net/oficina/suite" |
| 13 | "amadan.net/oficina/suite/server" |
| 14 | "gorm.io/gorm" |
| 15 | |
| 16 | "github.com/carlosframework/docs/internal/docs/principalstore" |
| 17 | ) |
| 18 | |
| 19 | // suiteProducer is Docs' half of the suite contract (spec §8.2.2; suite |
| 20 | // revision 11, §6.5 and §6.6, commit 91affa1): the feed of every live |
| 21 | // document, Docs' own per-person read check, and a document's text. The |
| 22 | // suite package owns the bearer check, the wire shapes, the cache headers, |
| 23 | // the cursor reset's 409 and S3's one refusal. |
| 24 | // |
| 25 | // Nothing here caches. Every Rule reads the roster lease, the allowlist and |
| 26 | // the database afresh, because an authorization answer held past its request |
| 27 | // is a standing capability (suite §4.3). |
| 28 | type suiteProducer struct { |
| 29 | store *Store |
| 30 | // list is the lone-shape front door: an address S2 names must pass it |
| 31 | // as a request would (requireAdmission) before any document is read. |
| 32 | list allowlist |
| 33 | // subjects resolves a Home subject in team mode, the same connect |
| 34 | // Bridge a signed-in request resolves through. nil outside team mode. |
| 35 | subjects homeSubjects |
| 36 | // step, when set, is called at named points: "asked" after the asker is |
| 37 | // mapped, "read" after Rule's readable read, "history" after its log |
| 38 | // read (the last before standing is checked), "replayed" between Content's replay |
| 39 | // and its second read of the revision. Tests only: it is how a lease |
| 40 | // running out or a change landing mid-request is made to happen on |
| 41 | // demand, which nothing else can arrange. |
| 42 | step func(stage string) |
| 43 | } |
| 44 | |
| 45 | var _ server.Producer = (*suiteProducer)(nil) |
| 46 | |
| 47 | // liveDocuments is the producer's definition of live: not deleted, and not |
| 48 | // one of 0002_owners.sql's orphans, which nobody can read. |
| 49 | func liveDocuments(g *gorm.DB) *gorm.DB { |
| 50 | return g.Where("documents.deleted_at IS NULL AND documents.owner_id > 0") |
| 51 | } |
| 52 | |
| 53 | // Feed pages suite_feed by id. |
| 54 | // |
| 55 | // The cursor is "<feed id>.<that row's stamp>", and the stamp is checked on |
| 56 | // every request. The stamp is a random nonce drawn per event and written |
| 57 | // once with that event's row (announce), which is the first of the two |
| 58 | // shapes suite revision 11 §6.6 makes normative: a restored log holds only |
| 59 | // the stamps of the rows it actually has. (A generation id kept in this same |
| 60 | // database would not do: a restore brings the old one back with the old |
| 61 | // rows.) After a restore from an older backup AUTOINCREMENT hands the same |
| 62 | // ids out again to different rows; a bare id would carry on silently from a |
| 63 | // position that now means something else, and a consumer at the restored |
| 64 | // tip would get no rows and its own cursor back for ever (Astra, |
| 65 | // 2026-11-01). |
| 66 | // |
| 67 | // A cursor this log does not recognise — one that does not parse, names a |
| 68 | // row the log does not hold, or carries another stamp than that row's — is |
| 69 | // server.ErrCursorReset, which the suite package answers with §6.6's one |
| 70 | // fixed 409 {"code":"CURSOR_RESET"}: the consumer sets aside what it holds |
| 71 | // from Docs and reads again from "". Suite revision 10 had Docs answer it |
| 72 | // 503 and leave the reset to a person; revision 11 (suite main 91affa1) |
| 73 | // makes the reset the contract. Docs never expires or compacts suite_feed, |
| 74 | // so no cursor it issued goes stale any other way. A failed read is NOT a |
| 75 | // reset: it is the error it is, which the package answers 503, because a |
| 76 | // reset destroys a consumer's whole copy and a database that is briefly |
| 77 | // unreadable has lost nothing. "" and "0" are the beginning and are never |
| 78 | // reset. At the tip the cursor given comes back unchanged with no rows, |
| 79 | // which is what ends a consumer's poll. |
| 80 | func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| 81 | after, stamp, ok := parseFeedCursor(cursor) |
| 82 | if !ok { |
| 83 | return suite.Feed{}, server.ErrCursorReset |
| 84 | } |
| 85 | db := p.store.db.WithContext(ctx) |
| 86 | if after > 0 { |
| 87 | var at []SuiteFeedRow |
| 88 | if err := db.Model(&SuiteFeedRow{}).Select("id", "stamp").Where("id = ?", after).Find(&at).Error; err != nil { |
| 89 | return suite.Feed{}, err |
| 90 | } |
| 91 | if len(at) != 1 || at[0].Stamp != stamp { |
| 92 | // A row this log does not hold, or another row at that id: |
| 93 | // the database was restored, or another log issued it. |
| 94 | return suite.Feed{}, server.ErrCursorReset |
| 95 | } |
| 96 | } |
| 97 | var rows []struct { |
| 98 | ID int64 |
| 99 | Sqid string |
| 100 | Revision int64 |
| 101 | Gone bool |
| 102 | TouchedAt time.Time |
| 103 | Stamp int64 |
| 104 | } |
| 105 | err := db.Table("suite_feed"). |
| 106 | Select("suite_feed.id, documents.sqid, suite_feed.revision, suite_feed.gone, suite_feed.touched_at, suite_feed.stamp"). |
| 107 | Joins("JOIN documents ON documents.id = suite_feed.document_id"). |
| 108 | Where("suite_feed.id > ? AND documents.owner_id > 0", after). |
| 109 | Order("suite_feed.id"). |
| 110 | Limit(limit). |
| 111 | Scan(&rows).Error |
| 112 | if err != nil { |
| 113 | return suite.Feed{}, err |
| 114 | } |
| 115 | if len(rows) == 0 { |
| 116 | // The tip: the cursor given, unchanged, so the consumer stops. "" |
| 117 | // becomes "0", the beginning, because the contract refuses an empty |
| 118 | // cursor. |
| 119 | if cursor == "" { |
| 120 | cursor = "0" |
| 121 | } |
| 122 | return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil |
| 123 | } |
| 124 | feed := suite.Feed{Rows: make([]suite.FeedRow, 0, len(rows))} |
| 125 | for _, r := range rows { |
| 126 | feed.Rows = append(feed.Rows, suite.FeedRow{ItemID: r.Sqid, Revision: r.Revision, Gone: r.Gone, TouchedAt: r.TouchedAt.UTC()}) |
| 127 | } |
| 128 | last := rows[len(rows)-1] |
| 129 | feed.Cursor = strconv.FormatInt(last.ID, 10) + "." + strconv.FormatInt(last.Stamp, 10) |
| 130 | return feed, nil |
| 131 | } |
| 132 | |
| 133 | // parseFeedCursor reads a cursor Docs issued: "" or "0" is the beginning, |
| 134 | // anything else "<id>.<stamp>" in canonical positive decimals, so a value has |
| 135 | // one spelling. Anything else was not issued here: ok is false, and Feed |
| 136 | // answers it with the cursor reset rather than a guess at a position. |
| 137 | func parseFeedCursor(c string) (after, stamp int64, ok bool) { |
| 138 | if c == "" || c == "0" { |
| 139 | return 0, 0, true |
| 140 | } |
| 141 | head, tail, found := strings.Cut(c, ".") |
| 142 | after, ok1 := canonicalPositive(head) |
| 143 | stamp, ok2 := canonicalPositive(tail) |
| 144 | if !found || !ok1 || !ok2 { |
| 145 | return 0, 0, false |
| 146 | } |
| 147 | return after, stamp, true |
| 148 | } |
| 149 | |
| 150 | func canonicalPositive(s string) (int64, bool) { |
| 151 | n, err := strconv.ParseInt(s, 10, 64) |
| 152 | if err != nil || n < 1 || strconv.FormatInt(n, 10) != s { |
| 153 | return 0, false |
| 154 | } |
| 155 | return n, true |
| 156 | } |
| 157 | |
| 158 | // Rule answers, per pair, whether the named asker may open the document now |
| 159 | // in Docs: the read predicate (permissionScope — ownership, a live grant, |
| 160 | // the team rung for a member; never a link) for the actor the asker maps to. |
| 161 | // |
| 162 | // In team mode standing is asked again AFTER the reads, from the request's |
| 163 | // latched Access (Astra, 2026-11-01). A lease that ran out before the read |
| 164 | // would otherwise answer NOT_VISIBLE for what membership opens, and one that |
| 165 | // ran out after it would answer VISIBLE from a membership that has lapsed. |
| 166 | // If standing is still Member the reads ran under a valid lease. If not, the |
| 167 | // readable set is read again — now without the membership clauses, Unknown |
| 168 | // being latched — so only what an address grant opens stays readable, and |
| 169 | // what only membership would open is UNKNOWN (standing Unknown) or |
| 170 | // NOT_VISIBLE (NotMember). |
| 171 | func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| 172 | out := make([]suite.Authorization, len(pairs)) |
| 173 | actor, ctx, access, keyed, err := p.askerActor(ctx, asker) |
| 174 | if err != nil { |
| 175 | return nil, err |
| 176 | } |
| 177 | if !keyed { |
| 178 | // An asker of a kind Docs does not key on in this shape. Not |
| 179 | // NOT_VISIBLE: that is the one silent answer, and this is a |
| 180 | // mismatch the consumer must see (suite §3). |
| 181 | for i := range out { |
| 182 | out[i] = suite.UNKNOWN |
| 183 | } |
| 184 | return out, nil |
| 185 | } |
| 186 | p.at("asked") |
| 187 | ids := make([]string, 0, len(pairs)) |
| 188 | for _, pr := range pairs { |
| 189 | ids = append(ids, pr.ItemID) |
| 190 | } |
| 191 | isLive, err := p.liveRevisions(ctx, ids) |
| 192 | if err != nil { |
| 193 | return nil, err |
| 194 | } |
| 195 | canRead, err := p.readable(ctx, actor, ids) |
| 196 | if err != nil { |
| 197 | return nil, err |
| 198 | } |
| 199 | p.at("read") |
| 200 | issued, err := p.issued(ctx, pairs, canRead) |
| 201 | if err != nil { |
| 202 | return nil, err |
| 203 | } |
| 204 | p.at("history") |
| 205 | // Standing is asked here, after the LAST database read (Astra, round |
| 206 | // 3: asked before the history read, a lease that ran out during it |
| 207 | // answered VISIBLE from a membership that had lapsed). Still Member: |
| 208 | // every read above ran under a valid lease. Not Member: the readable |
| 209 | // set is read again, now without the membership clauses (Unknown is |
| 210 | // latched), and only what an address grant opens stays readable. The |
| 211 | // history read needs no repeat: it was asked for a superset. |
| 212 | uncertain := false |
| 213 | if access != nil { |
| 214 | standing := access.state() |
| 215 | if standing != roster.Member { |
| 216 | if canRead, err = p.readable(ctx, actor, ids); err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | } |
| 220 | uncertain = standing == roster.Unknown |
| 221 | } |
| 222 | |
| 223 | for i, pr := range pairs { |
| 224 | rev, can := canRead[pr.ItemID] |
| 225 | _, live := isLive[pr.ItemID] |
| 226 | switch { |
| 227 | case !live: |
| 228 | // Deleted, or never existed. |
| 229 | out[i] = suite.NOT_VISIBLE |
| 230 | case !can && uncertain: |
| 231 | // The roster cannot say whether this person is a member, and |
| 232 | // membership is what would open it: withheld loudly. |
| 233 | out[i] = suite.UNKNOWN |
| 234 | case !can: |
| 235 | // The person before the revision: a document this person may |
| 236 | // not open is NOT_VISIBLE at every revision. |
| 237 | out[i] = suite.NOT_VISIBLE |
| 238 | case pr.Revision == rev: |
| 239 | out[i] = suite.VISIBLE |
| 240 | case issued[pr]: |
| 241 | // A revision this document had, by Docs' own log: moved on. |
| 242 | out[i] = suite.STALE |
| 243 | default: |
| 244 | // A revision this log never issued for this document — one |
| 245 | // from before a restore, or one never issued at all (suite |
| 246 | // §4.3): withheld loudly. Revisions are random, so there is no |
| 247 | // "ahead" or "behind" to read off the number. |
| 248 | out[i] = suite.UNKNOWN |
| 249 | } |
| 250 | } |
| 251 | return out, nil |
| 252 | } |
| 253 | |
| 254 | // issued is which of the asked (item, revision) pairs this log holds: a |
| 255 | // revision suite_feed recorded for that document. Asked only for pairs the |
| 256 | // asker may read at a revision that is not current, since only those turn |
| 257 | // on it. Revisions are random, so the log is the only thing that can say a |
| 258 | // revision is behind (doctrine §4.3: compare against your log). |
| 259 | func (p *suiteProducer) issued(ctx context.Context, pairs []suite.ItemRevision, canRead map[string]int64) (map[suite.ItemRevision]bool, error) { |
| 260 | var ids []string |
| 261 | var revs []int64 |
| 262 | for _, pr := range pairs { |
| 263 | if rev, can := canRead[pr.ItemID]; can && pr.Revision != rev { |
| 264 | ids = append(ids, pr.ItemID) |
| 265 | revs = append(revs, pr.Revision) |
| 266 | } |
| 267 | } |
| 268 | out := map[suite.ItemRevision]bool{} |
| 269 | if len(ids) == 0 { |
| 270 | return out, nil |
| 271 | } |
| 272 | var rows []struct { |
| 273 | Sqid string |
| 274 | Revision int64 |
| 275 | } |
| 276 | if err := p.store.db.WithContext(ctx).Table("suite_feed"). |
| 277 | Select("documents.sqid, suite_feed.revision"). |
| 278 | Joins("JOIN documents ON documents.id = suite_feed.document_id"). |
| 279 | Where("documents.sqid IN ? AND suite_feed.revision IN ?", ids, revs). |
| 280 | Scan(&rows).Error; err != nil { |
| 281 | return nil, err |
| 282 | } |
| 283 | for _, r := range rows { |
| 284 | out[suite.ItemRevision{ItemID: r.Sqid, Revision: r.Revision}] = true |
| 285 | } |
| 286 | return out, nil |
| 287 | } |
| 288 | |
| 289 | // liveRevisions is each live document's current revision, by sqid. |
| 290 | func (p *suiteProducer) liveRevisions(ctx context.Context, ids []string) (map[string]int64, error) { |
| 291 | var rows []struct { |
| 292 | Sqid string |
| 293 | Revision int64 |
| 294 | } |
| 295 | if err := liveDocuments(p.store.db.WithContext(ctx).Model(&Document{})).Where("documents.sqid IN ?", ids). |
| 296 | Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil { |
| 297 | return nil, err |
| 298 | } |
| 299 | out := make(map[string]int64, len(rows)) |
| 300 | for _, r := range rows { |
| 301 | out[r.Sqid] = r.Revision |
| 302 | } |
| 303 | return out, nil |
| 304 | } |
| 305 | |
| 306 | // readable is the documents among ids the actor may read now, with their |
| 307 | // revisions: permissionScope, under ctx's standing. |
| 308 | func (p *suiteProducer) readable(ctx context.Context, actor Actor, ids []string) (map[string]int64, error) { |
| 309 | var rows []struct { |
| 310 | Sqid string |
| 311 | Revision int64 |
| 312 | } |
| 313 | if err := p.store.permissionScope(ctx, p.store.db.WithContext(ctx).Model(&Document{}), actor, permissionRead). |
| 314 | Where("documents.sqid IN ? AND documents.deleted_at IS NULL", ids). |
| 315 | Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil { |
| 316 | return nil, err |
| 317 | } |
| 318 | out := make(map[string]int64, len(rows)) |
| 319 | for _, r := range rows { |
| 320 | out[r.Sqid] = r.Revision |
| 321 | } |
| 322 | return out, nil |
| 323 | } |
| 324 | |
| 325 | // at runs the test-only step hook, if one is set. |
| 326 | func (p *suiteProducer) at(stage string) { |
| 327 | if p.step != nil { |
| 328 | p.step(stage) |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | // askerActor maps the asker to the actor Docs keys on in its current shape, |
| 333 | // and returns the context permissionScope must read it under. keyed is false |
| 334 | // for an asker of the other kind. access is the request's latched team |
| 335 | // standing, nil in lone shape. |
| 336 | // |
| 337 | // Lone shape keys on an address: the front door first (a configured member, |
| 338 | // or a holder of a live grant, as requireAdmission asks on every request), |
| 339 | // then the person row, looked up and never created — EnsurePerson would seed |
| 340 | // a sample library for somebody who has never signed in. Somebody who has |
| 341 | // not signed in yet is still the address their grants and membership name. |
| 342 | // |
| 343 | // Team mode keys on the Home subject (person_ref): connect's link and then |
| 344 | // the Home-only principal, exactly as a signed-in request resolves it |
| 345 | // (identityResolver.resolve), and the roster standing for that subject. A |
| 346 | // subject with no Docs principal yet is an actor with no person, which reads |
| 347 | // the team rung by standing alone and nothing else. |
| 348 | func (p *suiteProducer) askerActor(ctx context.Context, asker suite.Subject) (actor Actor, out context.Context, access *requestAccess, keyed bool, err error) { |
| 349 | s := p.store |
| 350 | if s.team == nil { |
| 351 | if asker.Kind != suite.SubjectAddress { |
| 352 | return Actor{}, ctx, nil, false, nil |
| 353 | } |
| 354 | address := subjectOf(asker.Value) |
| 355 | admitted, err := p.list.allows(address) |
| 356 | if err != nil { |
| 357 | return Actor{}, ctx, nil, true, err |
| 358 | } |
| 359 | if !admitted { |
| 360 | return Actor{}, ctx, nil, true, nil |
| 361 | } |
| 362 | var person Person |
| 363 | err = s.db.WithContext(ctx).Where("email = ?", address).First(&person).Error |
| 364 | switch { |
| 365 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 366 | return Actor{VerifiedAddress: &address}, ctx, nil, true, nil |
| 367 | case err != nil: |
| 368 | return Actor{}, ctx, nil, true, err |
| 369 | } |
| 370 | return localActor(person.ID, address), ctx, nil, true, nil |
| 371 | } |
| 372 | |
| 373 | if asker.Kind != suite.SubjectPersonRef { |
| 374 | return Actor{}, ctx, nil, false, nil |
| 375 | } |
| 376 | subject := asker.Value |
| 377 | actor, err = p.homeActor(ctx, subject) |
| 378 | if err != nil { |
| 379 | return Actor{}, ctx, nil, true, err |
| 380 | } |
| 381 | a := s.team.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject}) |
| 382 | return actor, withAccess(ctx, a), a, true, nil |
| 383 | } |
| 384 | |
| 385 | // homeActor is a Home subject's actor in team mode, or the empty actor when |
| 386 | // the subject has no Docs principal. Storage failures are errors: S2 answers |
| 387 | // 503, which the consumer reads as UNKNOWN for the whole call. |
| 388 | func (p *suiteProducer) homeActor(ctx context.Context, subject string) (Actor, error) { |
| 389 | resolver := identityResolver{store: p.store, team: p.store.team, links: p.subjects} |
| 390 | person, err := resolver.homePerson(ctx, subject) |
| 391 | switch { |
| 392 | case errors.Is(err, errIdentityRefused): |
| 393 | return Actor{}, nil |
| 394 | case err != nil: |
| 395 | return Actor{}, err |
| 396 | } |
| 397 | principal, err := p.store.team.principals.Person(ctx, person.ID) |
| 398 | switch { |
| 399 | case errors.Is(err, principalstore.ErrRefused): |
| 400 | return Actor{}, nil |
| 401 | case err != nil: |
| 402 | return Actor{}, err |
| 403 | } |
| 404 | return Actor{PersonID: principal.ID, VerifiedAddress: principal.VerifiedAddress}, nil |
| 405 | } |
| 406 | |
| 407 | // Content is the document's plain text at its current revision: the title on |
| 408 | // the first line, a blank line, then Store.Text; an untitled document is its |
| 409 | // text alone. Any other revision, a deleted document and an unknown id are |
| 410 | // all suite.ErrNotAvailable. S3 carries no person, so no read check runs. |
| 411 | // |
| 412 | // The revision is read again after the replay. Every change that could alter |
| 413 | // the text bumps it in the same transaction, so an unchanged revision means |
| 414 | // the text read is that revision's; a changed one answers not available, and |
| 415 | // the consumer fetches the newer row the feed already carries. |
| 416 | func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| 417 | doc, err := p.liveDocument(ctx, itemID) |
| 418 | if err != nil { |
| 419 | return nil, err |
| 420 | } |
| 421 | if doc.Revision != revision { |
| 422 | return nil, suite.ErrNotAvailable |
| 423 | } |
| 424 | text, err := p.store.Text(ctx, doc) |
| 425 | if err != nil { |
| 426 | return nil, err |
| 427 | } |
| 428 | p.at("replayed") |
| 429 | again, err := p.liveDocument(ctx, itemID) |
| 430 | if err != nil { |
| 431 | return nil, err |
| 432 | } |
| 433 | if again.Revision != revision { |
| 434 | return nil, suite.ErrNotAvailable |
| 435 | } |
| 436 | if strings.TrimSpace(doc.Title) == "" { |
| 437 | return []byte(text), nil |
| 438 | } |
| 439 | return []byte(doc.Title + "\n\n" + text), nil |
| 440 | } |
| 441 | |
| 442 | func (p *suiteProducer) liveDocument(ctx context.Context, sqid string) (*Document, error) { |
| 443 | var doc Document |
| 444 | err := liveDocuments(p.store.db.WithContext(ctx)).Where("documents.sqid = ?", sqid).First(&doc).Error |
| 445 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 446 | return nil, suite.ErrNotAvailable |
| 447 | } |
| 448 | if err != nil { |
| 449 | return nil, err |
| 450 | } |
| 451 | return &doc, nil |
| 452 | } |
| 453 | |
| 454 | // mountSuite puts the three suite routes on the outer mux, beside the |
| 455 | // router and outside it: outside the session and admission groups, and |
| 456 | // outside homeCSRF, which memoria's POST /suite/s2 would fail (it sends only |
| 457 | // Authorization). Exactly the three method-and-path patterns the contract |
| 458 | // names, so nothing else under /suite/ escapes the router's CSRF check. With |
| 459 | // no consumers server.Handler is nil and nothing is mounted: /suite/* is the |
| 460 | // router's 404 like any unknown path. |
| 461 | func mountSuite(mux *http.ServeMux, h http.Handler) { |
| 462 | if h == nil { |
| 463 | return |
| 464 | } |
| 465 | mux.Handle("GET "+suite.RouteS1, h) |
| 466 | mux.Handle("POST "+suite.RouteS2, h) |
| 467 | mux.Handle("GET "+suite.RouteS3+"/{item}", h) |
| 468 | } |
| 469 | |