| 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) |
| +} |