home/teammode: shared roster team mode for every app, and its design note
A new module, extracted from Docs (e58a22f) and Sheets (ca78cc1) per Fable's sequencing on oficina/sheets #52: the five <PREFIX>_TEAM_* variables, all or none, beside Home credentials; the provisioning record verified against bindings built only from configuration, and the bindings fingerprint; the activation marker and roster evidence under a namespace parameter (with "docs" byte-identical to Docs' applied migration, with "sheets" the marker half of Sheets'), read by BootSchema before any migration, refusing boot without configuration or with another binding; Open's issuer census and activation; Runtime.Check as the one path to the cache; Access, the tri-state standing whose State re-checks the lease without waiting and latches Unknown; Guard, which threads that check into the app's writer transaction; AdmitUnlinked for connect's Unlinked hook; Partial for list pages under Unknown; and the GET /api/team probe. teammodetest exports the in-memory directory, provisioning and clock fixture. Tests mirror Docs' and Sheets' team suites at package level, plus a Sheets-shaped end-to-end exchange over connect's hooks and a Docs-shaped store; hand mutations are recorded in implementation/teammode-package.md, which also carries the API, invariants, the Unknown-list ruling, what stays per app, and the Docs/Sheets migration plan and port order. The module is in make test (vet, build, test, race).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 files changed,
+2,718
−2
Makefile+5 −1implementation/team-members.md+2 −1implementation/teammode-package.md+329 −0teammode/access.go+145 −0teammode/config.go+165 −0teammode/config_test.go+168 −0teammode/fit_docs_test.go+139 −0teammode/fit_sheets_test.go+285 −0teammode/fixture_test.go+149 −0teammode/go.mod+30 −0teammode/go.sum+83 −0teammode/probe.go+44 −0teammode/probe_test.go+79 −0teammode/runtime.go+160 −0teammode/runtime_test.go+373 −0teammode/schema/0001_team.sql.tmpl+10 −0teammode/state.go+192 −0teammode/state_test.go+162 −0teammode/teammodetest/teammodetest.go+165 −0teammode/testdata/docs_0001_team.sql+10 −0teammode/testdata/sheets_0001_team.sql+23 −0
CI passed — run details
diff --git a/Makefile b/Makefile| index bb60285..a035680 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -72,7 +72,7 @@ test: test-vet test-fmt test-build test-go test-race |
| # with HTTP 429 however long the runner waited between runs. What one |
| # attempt fetched stays cached, so each retry asks for less. |
| deps: |
| - @for dir in . handoff roster connect dashboard; do \ |
| + @for dir in . handoff roster connect dashboard teammode; do \ |
| n=0; until (cd $$dir && go mod download); do \ |
| n=$$((n+1)); [ $$n -lt 6 ] || exit 1; \ |
| echo "go mod download in $$dir failed (the hub's git rate limit?); retrying in $$((n*5))s"; \ |
| @@ -87,6 +87,7 @@ test-vet: deps |
| cd roster && CGO_ENABLED=0 go vet ./... |
| cd dashboard && CGO_ENABLED=0 go vet ./... |
| cd connect && CGO_ENABLED=0 go vet ./... |
| + cd teammode && CGO_ENABLED=0 go vet ./... |
| # Fails on unformatted files rather than rewriting them. CI must never |
| # silently "fix" a diff out from under a branch — a red test-fmt tells |
| @@ -105,6 +106,7 @@ test-build: |
| cd roster && CGO_ENABLED=0 go build ./... |
| cd dashboard && CGO_ENABLED=0 go build ./... |
| cd connect && CGO_ENABLED=0 go build ./... |
| + cd teammode && CGO_ENABLED=0 go build ./... |
| test-go: |
| CGO_ENABLED=0 go test -count=1 ./... |
| @@ -112,6 +114,7 @@ test-go: |
| cd roster && CGO_ENABLED=0 go test -count=1 ./... |
| cd dashboard && CGO_ENABLED=0 go test ./... |
| cd connect && CGO_ENABLED=0 go test -count=1 ./... |
| + cd teammode && CGO_ENABLED=0 go test -count=1 ./... |
| # The one concurrency-bearing package. internal/home's link store is |
| # taken by a single DELETE ... RETURNING precisely so that two clicks on |
| @@ -129,6 +132,7 @@ test-race: |
| cd roster && CGO_ENABLED=1 go test -race -count=1 ./... |
| cd dashboard && CGO_ENABLED=1 go test -race -count=1 ./... |
| cd connect && CGO_ENABLED=1 go test -race -count=1 ./... |
| + cd teammode && CGO_ENABLED=1 go test -race -count=1 ./... |
| # The browser checks, in a real Chromium (RASTRILLO_CHROME, on PATH, or |
| # the newest in a Playwright cache: Linux's ~/.cache or macOS's |
diff --git a/implementation/team-members.md b/implementation/team-members.md| index f4e503d..ba3e6ff 100644 |
| --- a/implementation/team-members.md |
| +++ b/implementation/team-members.md |
| @@ -292,7 +292,8 @@ allowlist mode. Each port copies that shape with `<APP>_TEAM_*` names and |
| the same five variables. Shared code to extract first: a small |
| `home/teammode` helper (config parse, record verification, admission |
| middleware, fingerprint marker) so five apps do not re-implement Docs' |
| -`team_config.go`. Then per app: |
| +`team_config.go`. (Built after the Sheets port, per Fable's sequencing on |
| +oficina/sheets #52: `teammode-package.md`.) Then per app: |
| | App | Admission today | Port work beyond the shared helper | Hard part | |
| |---|---|---|---| |
diff --git a/implementation/teammode-package.md b/implementation/teammode-package.md| new file mode 100644 |
| index 0000000..63b3362 |
| --- /dev/null |
| +++ b/implementation/teammode-package.md |
| @@ -0,0 +1,329 @@ |
| +# home/teammode, connect's Unlinked hook, and the roster lease fix |
| + |
| +**Status:** built on branch `teammode` (Claude Opus 5.5, 2026-10-28); whole-code |
| +review requested from Claude Fable 5.1. Not merged, not deployed. Implements |
| +Fable's sequencing ruling and roster note on oficina/sheets #52 (round 1) and |
| +oficina/home #97. Design context: `team-members.md` Part B §7. |
| + |
| +Two apps carry roster team mode today, each by hand: Docs (`e58a22f`, on a |
| +private `homeBridge` fork of connect) and Sheets (`ca78cc1`, on connect plus a |
| +private completion in `team_home.go`). This branch extracts what is the same, |
| +so Slides, Memoria, Calendar and Calls do not write a third and fourth copy. |
| +It re-points neither app: those are follow-up branches in their repos. |
| + |
| +## 1. What is in the branch |
| + |
| +| Piece | Where | One line | |
| +|---|---|---| |
| +| Roster lease fix (#97) | `roster/cache.go` | A publication keeps a lease whose subject and role it still lists. | |
| +| `roster.ValidSubject` | `roster/protocol.go` | The person-ref shape `Check` answers about. | |
| +| Unlinked / HomeOnly hooks | `connect/api.go`, `bridge.go` | Optional; a Home-only person in team mode, nothing changes otherwise. | |
| +| `home/teammode` | `teammode/` (own module) | Config, verification, marker, runtime, access, guard, probe. | |
| +| `home/teammode/teammodetest` | `teammode/teammodetest/` | Directory, provisioning and clock fixture for app tests. | |
| + |
| +## 2. The teammode API |
| + |
| +```go |
| +// Configuration (all or none, Home required) |
| +func EnvNames(prefix string) [5]string |
| +func ConfigFromEnv(prefix string) *Config // nil only when all five are empty |
| +func ConfigFromLookup(prefix string, getenv func(string) string) *Config |
| +type Home struct{ Issuer, ConsumerID string } |
| +func Verify(cfg *Config, home *Home, app, origin string) (*Settings, error) // nil cfg: off |
| +func (*Settings) Bindings() roster.Bindings |
| +func (*Settings) Fingerprint() string |
| +func Fingerprint(roster.Bindings) string |
| + |
| +// Marker and evidence, per app namespace |
| +func NewState(namespace string) (State, error); func MustState(string) State |
| +func (State) Schema() *migrate.Set // set "<ns>_team", migration 0001_team |
| +func (State) SQL() string |
| +func (State) BootSchema(ctx, db, settings, base, team *migrate.Set) (*migrate.Set, error) |
| +func (State) Required(ctx, db) (fingerprint string, activated bool, err error) |
| +func (State) Activate(ctx, db, fingerprint string) error |
| +func (State) Evidence(db) roster.Durable |
| + |
| +// Runtime |
| +func Open(ctx, RuntimeConfig{Settings, State, DB, Sealer, IssuerTables, Transport, Clock}) (*Runtime, error) |
| +func (*Runtime) Check(ctx, subject) roster.Decision // the only way to ask the cache |
| +func (*Runtime) Access(ctx, subject) *Access // "" is NotMember, unasked |
| +func (*Runtime) AdmitUnlinked(ctx, issuer, subject) error // nil | ErrNotMember | ErrUnavailable |
| +func (*Runtime) RosterState(ctx) string // "ok" | "stale" | "unknown" |
| +func (*Runtime) Refresh(ctx) error |
| +func (*Runtime) Bindings() roster.Bindings |
| + |
| +// One request's standing |
| +func (*Access) State() roster.State // lease re-checked, TryLock, latches Unknown |
| +func (*Access) Role() string // roster role while Member, else "" |
| +func (*Access) Remaining() time.Duration // stream timer; latches like State |
| +func (*Access) Partial() bool // Unknown: render the list as partial |
| +func (*Access) Subject() string |
| +func WithAccess(ctx, *Access) context.Context; func FromContext(ctx) (*Access, bool) |
| +func Standing(ctx) roster.State |
| +func Guard(ctx, authorize func(roster.State) error, write func() error) error |
| +func RequireMember(roster.State) error |
| + |
| +// Probe |
| +const ProbePath = "/api/team" |
| +func Probe(*Runtime) http.Handler // nil Runtime: {"team_mode":false} |
| + |
| +var ErrConfig, ErrUnavailable, ErrNotMember |
| +``` |
| + |
| +Connect gains two optional `Config` fields and a sentinel: |
| + |
| +```go |
| +Unlinked func(ctx context.Context, issuer, subject string) (Person, error) |
| +HomeOnly func(ctx context.Context, issuer, subject string) (Person, error) |
| +var ErrNoPerson |
| +``` |
| + |
| +## 3. Invariants |
| + |
| +**Configuration.** |
| +1. Team mode is the five `<PREFIX>_TEAM_*` variables, all or none. One |
| + present is a configuration and an invalid one; `Verify` refuses it. There |
| + is no fall back to the allowlist. |
| +2. Team mode requires Home: `Verify` refuses a nil or empty `Home`. |
| +3. The provisioning record is verified against bindings built only from |
| + configuration: Home's issuer and consumer ID, the app, the team, the |
| + directory and the instance's origin. Values arrive as canonical standard |
| + base64 only (no padding games, no embedded newlines); operator keys are |
| + strict JSON. Errors carry no supplied value. |
| +4. The fingerprint is base64url SHA-256 of the bindings' JSON, the bindings |
| + alone, pinned by a test vector so an encoding change cannot strand every |
| + activated database. It is Docs' and Sheets' digest exactly. |
| + |
| +**Marker.** |
| +5. `BootSchema` reads the marker before any migration (via `sqlite_master` |
| + first, so a never-migrated database is safe). An activated database |
| + refuses to boot without team configuration, or with a different binding. |
| + This is Docs' rule; Sheets compared the binding only at `Activate`, so |
| + adopting this refuses the same deployments one step earlier. |
| +6. `Open` activates before the runtime exists: it refuses a census that finds |
| + any Home identity from another issuer (the app names its issuer-bearing |
| + tables), writes the marker or refuses a different one, and only then |
| + builds the roster cache. A refused `Open` writes no marker. |
| +7. The marker's triggers refuse UPDATE and DELETE. With namespace `docs`, the |
| + schema is Docs' applied migration byte for byte; with `sheets`, it is the |
| + marker half of Sheets' (testdata), so neither app's ledger checksum moves. |
| + |
| +**Standing.** |
| +8. `Runtime.Check` is the only path to the cache, so every definite answer |
| + (a request's, an allocation's, the probe's) records that a roster has |
| + been held; the probe's "stale" depends on it. |
| +9. An app's stored roles are never consulted for standing. `Access.Role` is |
| + the roster's role, and only while `State` is Member. |
| +10. `Access.State` re-checks the Member lease every time it is asked, with |
| + `roster.Lease.Valid`'s TryLock: it never waits on the cache, so it is safe |
| + inside the SQLite writer transaction, where a refresh's publication may be |
| + queued behind the caller. Contention reads as Unknown. |
| +11. The first Unknown latches for the life of the `Access`. One request never |
| + sees Member after Unknown, even when the lease would read valid again |
| + (contention ending, or #97's surviving lease). |
| +12. A held decision ends within `roster.MaximumAge` (60 s) under a failing |
| + refresh, and at the next publication that removes the subject or changes |
| + their role. |
| + |
| +**Writes.** |
| +13. `Guard` runs the app's authorize against the carried standing, the write, |
| + and the authorize again, all inside the caller's transaction. It never |
| + asks the roster. A lease that lapses mid-write fails the commit. It |
| + decides nothing itself: the app's rule says what Unknown may still reach |
| + (a share). |
| + |
| +**Home-only people.** |
| +14. A person is created from a Home subject alone only in connect's ordinary |
| + completion, after the assertion is verified and consumed, only when no |
| + app session is present, only for a subject with no link and no Home-only |
| + person, and only when `AdmitUnlinked` returns nil: the roster says Member |
| + now and the decision's lease is still valid when checked again. |
| +15. Connect's same-person rules hold for Home-only people: `HomeOnly` is |
| + consulted wherever connect resolves a Home subject, so a known Home-only |
| + member arriving over somebody else's live session is 403, and that |
| + session survives. An unknown arrival over any live session allocates |
| + nothing ("unknown", 403). |
| +16. A Home-only person has no address. Connect refuses one whose `Label` is |
| + not empty. Every cookie shape check stays connect's (Sheets' copy goes). |
| +17. With both hooks nil, connect behaves exactly as before for every existing |
| + consumer (Slides, Calendar, Calls, Memoria, Sheets today): the full |
| + pre-existing connect suite passes unchanged. |
| + |
| +**Probe.** |
| +18. `GET /api/team` is unauthenticated and `no-store`, answers only |
| + `{team_mode, consumer, roster}`, the same body whoever asks, and |
| + `{"team_mode":false}` with team mode off. |
| + |
| +**Roster (#97).** |
| +19. A `Lease` names its subject and role. `Valid` and `Remaining` accept a |
| + newer cache version when the cache is usable, the subject still holds |
| + that role, and every publication since the lease has listed them so (a |
| + per-member "since" version). A removal or role change ends the lease for |
| + good; re-adding the subject does not revive it. The deadline is the |
| + original one, so the 60 s contract is untouched. A fence (record update, |
| + generation block, clock discrepancy) ends every earlier lease even after |
| + a later publication, because the deadline was measured on a clock the |
| + fence distrusts. Apps still do not re-ask on an invalid lease: under the |
| + writer that would wait on the publisher. |
| + |
| +## 4. Unknown on list pages: ruling |
| + |
| +**Partial, not 503.** Under Unknown a list page shows what the person reaches |
| +without standing (their shares), with a "partial" notice; it does not answer |
| +503 for the whole page. This is Docs' behaviour; Fable leaned to it on #52 |
| +(deviation 3): the list is where every sign-in lands, and a 503 there during a |
| +Home blip over 60 s reads as "the app is down", where a partial list reads as |
| +"Home is slow". Item pages that need standing still answer a retryable 503 |
| +(never a 404), and create/import stay member-only (403 guest, 503 Unknown). |
| + |
| +The primitive is `Access.Partial()`. Ask it after building the list, from the |
| +same `Access`: `State` latches, so a lease that lapsed while listing marks the |
| +page partial. NotMember is not partial: a guest's shares are their complete |
| +list. Sheets moves from 503 to partial when it re-points. This is recorded as |
| +a proposal in this branch for the review to confirm; Paul has not ruled. |
| + |
| +## 5. What stays per app |
| + |
| +- **The mapping onto the app's access queries:** which rows the team rung |
| + reaches (Docs: own documents; Sheets: every sheet, self-grants counting |
| + only while Member, roster owners on orphaned sheets), and the `authorize` |
| + passed to `Guard`. |
| +- **Home-only allocation:** the app's people table and its Home-only identity |
| + table with its triggers (addressless, undeletable, disjoint from links), |
| + and the two connect hooks that read and fill it. |
| +- **The reverse lookup** (person to Home subject) for asking the roster about |
| + someone other than the viewer (a share list's "still on the team"). |
| +- **The stream hook:** re-decide before each delivery, re-arm at |
| + `Access.Remaining()`, close on anything but a renewed answer. |
| +- **Copy:** the partial notice, the Unknown message, the Home-only label. |
| +- **The `IssuerTables` list** and the evidence `Sealer` namespace. |
| + |
| +## 6. Migration plan |
| + |
| +Each is its own branch in its own repo, after this lands on Home main, each |
| +with its own review and canary. Each bumps `home/teammode`, `home/roster` and |
| +`home/connect` to the main squash commit. (This branch's `teammode/go.mod` |
| +pins roster and connect at the branch commit `6b23c73`, the precedent being |
| +the root module's roster pin on `feat-roster-lease`; consumers pinning main |
| +take the later pseudo-version by MVS. A follow-up bump in Home is optional.) |
| + |
| +### Sheets (first: it is on connect already) |
| + |
| +| Sheets at ca78cc1 | Becomes | |
| +|---|---| |
| +| `TeamConfigFromEnv` | `teammode.ConfigFromEnv("SHEETS")` | |
| +| `validatedTeamConfig` | `teammode.Verify(cfg, &teammode.Home{creds.Issuer, creds.ConsumerID}, "sheets", origin)` | |
| +| `BootSchemaFor` | `teammode.MustState("sheets").BootSchema(ctx, w, settings, BootSchema, TeamBootSchema)` | |
| +| `teamstate.Required/Activate/Evidence` | `State` methods over the same tables. Sheets keeps its own `sheets_team` set (its `0001_team.sql` also holds the Home-only tables, and the ledger checksums the whole file); it does not apply `State.Schema()`. | |
| +| `ConfigureTeam`'s census, `Activate`, `roster.New` | `teammode.Open(ctx, RuntimeConfig{…, IssuerTables: {"home_identity_links", "sheets_team_home_members"}})` | |
| +| `teamRuntime.check`, `rosterHeld` | `Runtime.Check` | |
| +| `team_home.go` (whole file: `homeFinish`, `teamComplete`, cookie copies, `t.finish`) | deleted. `connect.Config.HomeOnly` = `teamstate.HomeMember`; `Unlinked` = `AdmitUnlinked` then `teamstate.EnsureHomeMember`. `/auth/finish` is connect's `Finish`. | |
| +| `homeMemberID` | `bridge.Resolve`, which now finds Home-only members | |
| +| `teamAccess{member, subject, decision, uncertain}` | `teamAccess{member, *teammode.Access}`; `state()` is `Access.State`, `role()` maps `Access.Role` | |
| +| `resolveTeamAccess`, `withStanding` | `rt.Access(ctx, subject)` | |
| +| `streamAccess`'s timer | `Access.Remaining()` | |
| +| list under Unknown: 503 | `Access.Partial()` and the notice (§4) | |
| +| `mayWrite` in the handler | `teammode.Guard` inside the store's write transactions (Fable's deviation 7) | |
| +| `team_probe.go` | `teammode.Probe(rt)` at `teammode.ProbePath` | |
| +| `team_fixture_test.go`'s directory and clock | `teammodetest.Provision`, `Directory`, `Clock` | |
| + |
| +Stays: `team_owner.go`, `ownGrantIgnored`, `teamstate.HomeSubject`, |
| +`homeOnlyRefs`, labels, `teamMemberOnly`'s copy. `TestFitsSheets` in this |
| +branch runs this shape end to end through a real exchange. |
| + |
| +### Docs |
| + |
| +| Docs at e58a22f | Becomes | |
| +|---|---| |
| +| `validatedTeamConfig` | `teammode.Verify(cfg.Team, &teammode.Home{home.issuer, home.consumerID}, "docs", origin)`; `ConfigFromEnv("DOCS")` in `cmd/docs` | |
| +| `TeamConfig.transport/clock` | `RuntimeConfig.Transport/Clock` | |
| +| `app.go`'s `teamstate.Required` check before `migrate.Apply` | `MustState("docs").BootSchema(...)` | |
| +| `TeamBootSchema = Merge(BootSchema, principalstore.Schema, teamstate.Schema)` | `teamstate.Schema` becomes `MustState("docs").Schema()`: same set name, same migration ID, byte-identical SQL, so the applied ledger row matches (tested). | |
| +| `newTeamRuntime`'s census, `Activate`, `roster.New` | `teammode.Open(…, IssuerTables: {"docs_identity_links", "docs_home_identities"})` | |
| +| `principalstore`'s `RequireMembership` | `AdmitUnlinked`, mapping `ErrNotMember` to `principalstore.ErrRefused`, else `ErrUnavailable` | |
| +| `requestAccess.state()`, `resolveAccess` | embedded `*teammode.Access`, `rt.Access(ctx, id.HomeSubject)` | |
| +| `permissionScope`, `ownerMutation` | unchanged in shape: they already authorize inside the writer transaction before and after; `ownerMutation` can be `teammode.Guard` | |
| +| `partialCatalog` | `Access.Partial()` | |
| +| `team_probe.go`, `check`, `rosterHeld` | `teammode.Probe`, `Runtime.Check` | |
| + |
| +**Docs' `homeBridge` stays in the first Docs branch.** Moving Docs onto |
| +`home/connect` (its `completeTeamPrincipal` mapping onto `HomeOnly` = |
| +`principals.Resolve` for Home principals and `Unlinked` = `EnsureHome`) also |
| +moves its link table (`docs_identity_links` to connect's |
| +`home_identity_links`) and its local reauthentication, which is a data |
| +migration with its own review. It is a second Docs branch, after the first |
| +has a canary. `TestFitsDocs` in this branch runs Docs' store-side shape |
| +(allocation gate, in-transaction authorize, partial catalog). |
| + |
| +## 7. The other four, in Paul's order |
| + |
| +Each port: `ConfigFromEnv("<APP>")`, `MustState("<app>")` with |
| +`State.Schema()` merged after the app's schema, a Home-only people table with |
| +Sheets' triggers, the two connect hooks, `Access` mapped onto the app's |
| +access query, `Guard` in its write transactions, `Partial` on its lists, |
| +`Probe` mounted, `teammodetest` in its tests; Alta's recipe gets |
| +`Roster: true` and the five keys. Then §7's acceptance list, full app CI, |
| +top-model review, verified canary. |
| + |
| +1. **Slides.** As Sheets. Team instances ship without uploads; when storage |
| + arrives, presigned GETs are capped at `Access.Remaining()` (never beyond |
| + 60 s). The edit channel uses the stream hook. |
| +2. **Memoria.** `Partial` applies to search results and to the AI answer's |
| + sources (sources drawn only from what the person reaches; a partial |
| + answer says so). AI stays off for teams unless the owner asks and Paul |
| + agrees. Sibling calls already bind to `MEMORIA_TEAM` hosts. |
| +3. **Calendar.** Published `.ics` feed tokens stay capability links with an |
| + owner revoke. Home-only members have no address, so reminders need an |
| + in-app "email for reminders" the instance stores (ruling 5) before a |
| + Home-only member can get one. |
| +4. **Calls.** Standing checked at room join and on every signaling reconnect, |
| + and the signaling socket closed at `Access.Remaining()` unless renewed. |
| + Native clients need a team-host picker and Home sign-in first, which is |
| + why Calls is last. |
| + |
| +## 8. Tests and hand mutations |
| + |
| +`make test` runs the new module in vet, build, test and race. Package tests |
| +mirror the strongest of Docs' and Sheets' team tests: all-or-none |
| +configuration per variable; every binding pinned; malformed values; the |
| +pinned fingerprint; marker lock-in, rebinding and triggers; boot before |
| +migrations (fresh, applied-not-activated, activated with none, other and same |
| +binding); census per table with no marker written; roles; the 59 s / 61 s |
| +lease under failing refresh with the latch; #97 across a refresh (unchanged |
| +kept on the old deadline, removal and role change ended); `AdmitUnlinked` for |
| +Member, stranger, Unknown, impossible subjects (no fetch) and a lease that |
| +lapses between decision and check; `Guard` before and after the write, a |
| +lapse mid-write, and inside a real one-connection SQLite writer with a |
| +publication queued behind it (no wait, contention latched, an uncontended |
| +request's lease surviving the publication); the probe's three states, team |
| +off, no account data, same body whoever asks, and "stale" from a request's |
| +check alone. Connect: the hooks as a pair, Home-only sign-in and re-sign-in, |
| +refusal as connect's unknown with the marker, undecided 503, an address |
| +refused, never asked over a live session, the known arrival over another |
| +session refused with that session intact, links and the link flow untouched, |
| +malformed cookies never reaching the hook. Roster: unchanged publication |
| +kept on its own deadline, role change both ways, removal then re-add, another |
| +member's change, fence then publication. |
| + |
| +Hand mutations, killed: in teammode, every binding unpinned (six), operator |
| +keys' unknown members, non-canonical base64, all-or-none, boot ignoring the |
| +marker, boot ignoring the binding, `Activate` accepting a rebind or a |
| +malformed fingerprint, `sqlite_master` skipped, census dropped, table |
| +validation dropped, census list optional, `Activate` skipped in `Open`, the |
| +held flag, `AdmitUnlinked` without the lease re-check / issuer / subject |
| +shape, the empty subject asking the roster, "stale" dropped, the probe |
| +bypassing `Check`, the probe leaking the team, `no-store` dropped, `State` |
| +without the lease check, `State` without the latch, `Guard` without the |
| +before or after check, `Partial` always false, `Role` ignoring standing, |
| +`RequireMember` admitting a guest. In connect: the hook pair, Unlinked over a |
| +live session, the same-person check, the label check, the Resolve fallback, |
| +storage read as refusal, the resume marker. In roster: the since check, the |
| +fence check, the role and since checks together, any member accepted, since |
| +always reset, the deadline. |
| + |
| +Equivalent, recorded: `Verify`'s explicit empty-field and Home-field checks |
| +(roster's binding validation refuses the same values; kept as the stated |
| +rule); `Remaining`'s own latch (`State`, called first, latches on contention, |
| +so it is reachable only if contention begins between the two calls); in |
| +roster, the role check and the since check each alone (a role change also |
| +resets since; the pair together is killed). |
diff --git a/teammode/access.go b/teammode/access.go| new file mode 100644 |
| index 0000000..f93a3dc |
| --- /dev/null |
| +++ b/teammode/access.go |
| @@ -0,0 +1,145 @@ |
| +package teammode |
| + |
| +import ( |
| + "context" |
| + "sync/atomic" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// Access is one request's team standing: |
| +// |
| +// - roster.Member: on the team, with the roster's role ("owner" or |
| +// "member"). The app's team rung. |
| +// - roster.NotMember: a guest. Only what was shared with them. |
| +// - roster.Unknown: the roster could not be read within its lease. Shares |
| +// still work; anything that would have needed standing answers a |
| +// retryable 503, never a 404 that would claim the item is not theirs. |
| +// |
| +// A Member answer carries a lease. State checks it every time it is asked, |
| +// without waiting (roster.Lease.Valid refuses on contention instead of |
| +// queueing behind a publication), and latches Unknown the first time it |
| +// finds the lease expired or contended, so one request can never see Member |
| +// again after it has seen Unknown. A held decision therefore ends within |
| +// roster.MaximumAge, existing sessions included. |
| +// |
| +// Never store an Access beyond its request; a stream asks for a new one |
| +// before each delivery and at Remaining. |
| +type Access struct { |
| + subject string |
| + decision roster.Decision |
| + uncertain atomic.Bool |
| +} |
| + |
| +// State is the standing now. Safe under the SQLite writer: it never asks |
| +// the roster and never blocks. A nil Access is Unknown. |
| +func (a *Access) State() roster.State { |
| + if a == nil || a.uncertain.Load() { |
| + return roster.Unknown |
| + } |
| + if a.decision.State == roster.Member && !a.decision.Lease.Valid() { |
| + a.uncertain.Store(true) |
| + return roster.Unknown |
| + } |
| + return a.decision.State |
| +} |
| + |
| +// Role is the roster's role while State is Member ("owner" or "member"), |
| +// and "" otherwise. An app's stored role is never consulted for standing. |
| +func (a *Access) Role() string { |
| + if a.State() != roster.Member { |
| + return "" |
| + } |
| + return a.decision.Role |
| +} |
| + |
| +// Subject is the Home subject the roster was asked about, "" for none. |
| +func (a *Access) Subject() string { |
| + if a == nil { |
| + return "" |
| + } |
| + return a.subject |
| +} |
| + |
| +// Remaining is how long a Member answer may stand before it must be asked |
| +// again: the time a stream may run before re-deciding, or closing. 0 when |
| +// the answer does not rest on a lease (NotMember: nothing expires on a |
| +// timer) or when it has lapsed, which latches Unknown as State does. |
| +func (a *Access) Remaining() time.Duration { |
| + if a.State() != roster.Member { |
| + return 0 |
| + } |
| + left := a.decision.Lease.Remaining() |
| + if left <= 0 { |
| + a.uncertain.Store(true) |
| + return 0 |
| + } |
| + return left |
| +} |
| + |
| +// Partial reports whether a list built for this request is incomplete |
| +// because standing is Unknown. The ruling for list pages (implementation/ |
| +// teammode-package.md, "Unknown on list pages"): under Unknown, list what |
| +// the person reaches without standing — their shares — and render a |
| +// "partial" notice, rather than a 503 for the whole page. Ask it after |
| +// building the list, from the same Access: State latches, so a lease that |
| +// lapsed while listing marks the page partial. |
| +func (a *Access) Partial() bool { return a.State() == roster.Unknown } |
| + |
| +type accessKey struct{} |
| + |
| +// WithAccess carries a request's Access to the store, so a check inside the |
| +// writer transaction reads the same latched standing. |
| +func WithAccess(ctx context.Context, a *Access) context.Context { |
| + return context.WithValue(ctx, accessKey{}, a) |
| +} |
| + |
| +// FromContext is the Access WithAccess carried. |
| +func FromContext(ctx context.Context) (*Access, bool) { |
| + a, ok := ctx.Value(accessKey{}).(*Access) |
| + return a, ok && a != nil |
| +} |
| + |
| +// Standing is the carried Access's State, Unknown when none was carried. |
| +func Standing(ctx context.Context) roster.State { |
| + a, _ := FromContext(ctx) |
| + return a.State() |
| +} |
| + |
| +// Guard threads the lease check into the app's store transaction: it runs |
| +// authorize against the request's standing, then write, then authorize |
| +// again, so the transaction commits only if the standing that admitted the |
| +// write still holds after it. Call it inside the writer transaction: |
| +// |
| +// return db.Transaction(func(tx *gorm.DB) error { |
| +// return teammode.Guard(ctx, mayEdit(tx, doc), func() error { return save(tx) }) |
| +// }) |
| +// |
| +// authorize is the app's own rule over the standing — Unknown may still |
| +// reach a share — so Guard decides nothing itself. It never asks the roster |
| +// and never waits on it: a contended or lapsed lease reads as Unknown, so a |
| +// refresh publication queued behind this transaction's writer cannot |
| +// deadlock it, and a decision that lapses mid-write fails the commit. |
| +func Guard(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + if err := authorize(Standing(ctx)); err != nil { |
| + return err |
| + } |
| + if err := write(); err != nil { |
| + return err |
| + } |
| + return authorize(Standing(ctx)) |
| +} |
| + |
| +// RequireMember is the common authorize for Guard and for member-only |
| +// actions (create, import): nil for Member, ErrNotMember for NotMember, |
| +// ErrUnavailable for Unknown. |
| +func RequireMember(s roster.State) error { |
| + switch s { |
| + case roster.Member: |
| + return nil |
| + case roster.NotMember: |
| + return ErrNotMember |
| + } |
| + return ErrUnavailable |
| +} |
diff --git a/teammode/config.go b/teammode/config.go| new file mode 100644 |
| index 0000000..18bed4f |
| --- /dev/null |
| +++ b/teammode/config.go |
| @@ -0,0 +1,165 @@ |
| +// Package teammode is roster team mode for an Oficina app: the shared half |
| +// of what Docs and Sheets each built by hand (Home implementation/ |
| +// team-members.md Part B §7; implementation/teammode-package.md). |
| +// |
| +// With team mode configured, Home's roster decides a person's team standing |
| +// on every request, and the app's own stored roles are never read for it. |
| +// This package holds the parts that are the same in every app: |
| +// |
| +// - the five <PREFIX>_TEAM_* variables, all or none, beside Home |
| +// credentials (ConfigFromEnv, Verify); |
| +// - the operator's provisioning record, verified against bindings built |
| +// only from configuration, and the bindings fingerprint (Settings); |
| +// - the activation marker and the roster evidence store, under the app's |
| +// namespace, read before any migration (State, State.BootSchema); |
| +// - the runtime around the roster cache, whose Check is the only way the |
| +// app asks it (Runtime, Runtime.Check); |
| +// - one request's tri-state standing, Member / NotMember / Unknown, with a |
| +// lease re-checked every time it is asked and never waited on (Access, |
| +// Guard); |
| +// - the GET /api/team readiness probe (Probe). |
| +// |
| +// What stays in each app: how standing maps onto its access queries, how a |
| +// Home-only person is allocated in its people table (through connect's |
| +// Unlinked hook, gated by Runtime.AdmitUnlinked), and its stream hook. |
| +package teammode |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "errors" |
| + "os" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "github.com/go-json-experiment/json" |
| +) |
| + |
| +var ( |
| + // ErrConfig refuses boot: configuration that is incomplete, malformed, |
| + // or does not match the verified provisioning record or the marker. |
| + // There is no falling back to the allowlist. |
| + ErrConfig = errors.New("teammode: invalid team configuration") |
| + // ErrUnavailable is "cannot decide now": storage, or the roster. |
| + ErrUnavailable = errors.New("teammode: team authority unavailable") |
| + // ErrNotMember is a definite answer: the roster does not list the |
| + // subject on this team. |
| + ErrNotMember = errors.New("teammode: not a team member") |
| +) |
| + |
| +// Config is the five deployment variables, never request input. |
| +type Config struct { |
| + TeamID string |
| + DirectoryOrigin string |
| + ProvisioningBase64 string |
| + OperatorKeysBase64 string |
| + RosterToken string |
| +} |
| + |
| +// EnvNames are the five variables for an app's prefix, in Config's order: |
| +// <PREFIX>_TEAM_ID, _TEAM_DIRECTORY_ORIGIN, _TEAM_PROVISIONING_BASE64, |
| +// _TEAM_OPERATOR_KEYS_BASE64 and _TEAM_ROSTER_TOKEN. |
| +func EnvNames(prefix string) [5]string { |
| + return [5]string{prefix + "_TEAM_ID", prefix + "_TEAM_DIRECTORY_ORIGIN", prefix + "_TEAM_PROVISIONING_BASE64", prefix + "_TEAM_OPERATOR_KEYS_BASE64", prefix + "_TEAM_ROSTER_TOKEN"} |
| +} |
| + |
| +// ConfigFromEnv reads the five variables for prefix ("DOCS", "SHEETS"). |
| +// It is nil only when all five are absent or empty. One present and the rest |
| +// missing is a configuration, and an invalid one: Verify refuses it rather |
| +// than letting the app boot in allowlist mode. |
| +func ConfigFromEnv(prefix string) *Config { return ConfigFromLookup(prefix, os.Getenv) } |
| + |
| +// ConfigFromLookup is ConfigFromEnv over any lookup. |
| +func ConfigFromLookup(prefix string, getenv func(string) string) *Config { |
| + n := EnvNames(prefix) |
| + c := Config{TeamID: getenv(n[0]), DirectoryOrigin: getenv(n[1]), ProvisioningBase64: getenv(n[2]), OperatorKeysBase64: getenv(n[3]), RosterToken: getenv(n[4])} |
| + if c == (Config{}) { |
| + return nil |
| + } |
| + return &c |
| +} |
| + |
| +// Home is the app's validated Home credentials, as far as team mode needs |
| +// them: team mode exists only beside Home sign-in. Sheets builds it from |
| +// connect.DecodedCredentials, Docs from its own Home settings. |
| +type Home struct { |
| + Issuer string |
| + ConsumerID string |
| +} |
| + |
| +// Settings is a verified team configuration: the operator's provisioning |
| +// record checked against bindings built only from configuration. |
| +type Settings struct { |
| + record roster.VerifiedRecord |
| + token string |
| + fingerprint string |
| +} |
| + |
| +// Bindings are the verified record's bindings. |
| +func (s *Settings) Bindings() roster.Bindings { return s.record.Bindings() } |
| + |
| +// Fingerprint is what the activation marker records. |
| +func (s *Settings) Fingerprint() string { return s.fingerprint } |
| + |
| +// Fingerprint is the marker's digest of a deployment's bindings: base64url |
| +// SHA-256 of their JSON. Only the bindings, so a re-issued record for the |
| +// same bindings (a new sequence, a rotated roster key) still matches. |
| +func Fingerprint(b roster.Bindings) string { |
| + raw, err := json.Marshal(b) |
| + if err != nil { |
| + return "" |
| + } |
| + digest := sha256.Sum256(raw) |
| + return base64.RawURLEncoding.EncodeToString(digest[:]) |
| +} |
| + |
| +// Verify checks cfg for app at origin. A nil cfg is team mode off (nil, nil). |
| +// Anything else is a verified Settings or ErrConfig: every variable present, |
| +// Home configured, the roster token well formed, and the provisioning record |
| +// signed by one of the operator keys for exactly these bindings — Home's |
| +// issuer and consumer ID, the app, the team, the directory and this |
| +// instance's origin. Errors never carry a supplied value. |
| +func Verify(cfg *Config, home *Home, app, origin string) (*Settings, error) { |
| + if cfg == nil { |
| + return nil, nil |
| + } |
| + if home == nil || home.Issuer == "" || home.ConsumerID == "" { |
| + return nil, ErrConfig |
| + } |
| + if cfg.TeamID == "" || cfg.DirectoryOrigin == "" || cfg.ProvisioningBase64 == "" || cfg.OperatorKeysBase64 == "" || !roster.ValidChallenge(cfg.RosterToken) { |
| + return nil, ErrConfig |
| + } |
| + raw, ok := strictBase64(cfg.ProvisioningBase64, roster.BodyLimit) |
| + if !ok { |
| + return nil, ErrConfig |
| + } |
| + encoded, ok := strictBase64(cfg.OperatorKeysBase64, 4096) |
| + if !ok { |
| + return nil, ErrConfig |
| + } |
| + var keys []roster.Key |
| + if json.Unmarshal(encoded, &keys, json.RejectUnknownMembers(true)) != nil { |
| + return nil, ErrConfig |
| + } |
| + expected := roster.Bindings{Issuer: home.Issuer, Directory: cfg.DirectoryOrigin, Consumer: home.ConsumerID, App: app, Team: cfg.TeamID, Audience: origin} |
| + record, err := roster.VerifyProvisioning(raw, keys, expected) |
| + if err != nil { |
| + return nil, ErrConfig |
| + } |
| + fingerprint := Fingerprint(record.Bindings()) |
| + if fingerprint == "" { |
| + return nil, ErrConfig |
| + } |
| + return &Settings{record: record, token: cfg.RosterToken, fingerprint: fingerprint}, nil |
| +} |
| + |
| +// strictBase64 accepts only canonical standard base64 of at most limit bytes. |
| +func strictBase64(encoded string, limit int) ([]byte, bool) { |
| + if encoded == "" || len(encoded) > base64.StdEncoding.EncodedLen(limit) { |
| + return nil, false |
| + } |
| + decoded, err := base64.StdEncoding.Strict().DecodeString(encoded) |
| + if err != nil || len(decoded) > limit || base64.StdEncoding.EncodeToString(decoded) != encoded { |
| + return nil, false |
| + } |
| + return decoded, true |
| +} |
diff --git a/teammode/config_test.go b/teammode/config_test.go| new file mode 100644 |
| index 0000000..7685777 |
| --- /dev/null |
| +++ b/teammode/config_test.go |
| @@ -0,0 +1,168 @@ |
| +package teammode_test |
| + |
| +import ( |
| + "encoding/base64" |
| + "errors" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + "github.com/go-json-experiment/json" |
| +) |
| + |
| +func TestConfigFromLookupIsAllOrNone(t *testing.T) { |
| + names := teammode.EnvNames("SLIDES") |
| + want := [5]string{"SLIDES_TEAM_ID", "SLIDES_TEAM_DIRECTORY_ORIGIN", "SLIDES_TEAM_PROVISIONING_BASE64", "SLIDES_TEAM_OPERATOR_KEYS_BASE64", "SLIDES_TEAM_ROSTER_TOKEN"} |
| + if names != want { |
| + t.Fatalf("names %v", names) |
| + } |
| + env := map[string]string{} |
| + lookup := func(k string) string { return env[k] } |
| + if teammode.ConfigFromLookup("SLIDES", lookup) != nil { |
| + t.Fatal("no variables is not team mode off") |
| + } |
| + b := teammodetest.Bindings("slides", "slides-preview", "https://slides.example.com") |
| + full, _ := teammodetest.Provision(t, b) |
| + values := [5]string{full.TeamID, full.DirectoryOrigin, full.ProvisioningBase64, full.OperatorKeysBase64, full.RosterToken} |
| + for i := range names { |
| + env = map[string]string{names[i]: values[i]} |
| + c := teammode.ConfigFromLookup("SLIDES", lookup) |
| + if c == nil { |
| + t.Fatalf("%s alone read as team mode off", names[i]) |
| + } |
| + if _, err := teammode.Verify(c, teammodetest.Home(b), "slides", "https://slides.example.com"); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("%s alone: %v", names[i], err) |
| + } |
| + // Every variable but this one: still refused. |
| + env = map[string]string{} |
| + for j := range names { |
| + if j != i { |
| + env[names[j]] = values[j] |
| + } |
| + } |
| + if _, err := teammode.Verify(teammode.ConfigFromLookup("SLIDES", lookup), teammodetest.Home(b), "slides", "https://slides.example.com"); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("without %s: %v", names[i], err) |
| + } |
| + // Another prefix's variables are not this app's. |
| + env = map[string]string{strings.Replace(names[i], "SLIDES", "SHEETS", 1): values[i]} |
| + if teammode.ConfigFromLookup("SLIDES", lookup) != nil { |
| + t.Fatal("read another prefix") |
| + } |
| + } |
| + for i := range names { |
| + env[names[i]] = values[i] |
| + } |
| + if _, err := teammode.Verify(teammode.ConfigFromLookup("SLIDES", lookup), teammodetest.Home(b), "slides", "https://slides.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestVerifyOffAndHomeRequired(t *testing.T) { |
| + if s, err := teammode.Verify(nil, nil, testApp, testOrigin); s != nil || err != nil { |
| + t.Fatal("nil configuration is not team mode off") |
| + } |
| + b := teammodetest.Bindings(testApp, testConsumer, testOrigin) |
| + cfg, _ := teammodetest.Provision(t, b) |
| + for _, home := range []*teammode.Home{nil, {}, {Issuer: b.Issuer}, {ConsumerID: b.Consumer}} { |
| + if _, err := teammode.Verify(cfg, home, testApp, testOrigin); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("team mode without Home %+v: %v", home, err) |
| + } |
| + } |
| +} |
| + |
| +// Every binding is pinned from configuration: a record for any other value |
| +// of any one of them is refused. |
| +func TestVerifyPinsEveryBinding(t *testing.T) { |
| + b := teammodetest.Bindings(testApp, testConsumer, testOrigin) |
| + cfg, _ := teammodetest.Provision(t, b) |
| + s, err := teammode.Verify(cfg, teammodetest.Home(b), testApp, testOrigin) |
| + if err != nil || s.Bindings() != b || s.Fingerprint() != teammode.Fingerprint(b) { |
| + t.Fatalf("verify: %v", err) |
| + } |
| + type tweak struct { |
| + name string |
| + home teammode.Home |
| + cfg teammode.Config |
| + app, origin string |
| + recordBindings func(*roster.Bindings) |
| + } |
| + other := "https://other.example.com" |
| + for _, tc := range []tweak{ |
| + {name: "issuer", home: teammode.Home{Issuer: other, ConsumerID: b.Consumer}}, |
| + {name: "consumer", home: teammode.Home{Issuer: b.Issuer, ConsumerID: "docs-preview"}}, |
| + {name: "app", app: "docs"}, |
| + {name: "origin", origin: other}, |
| + {name: "team", cfg: teammode.Config{TeamID: "TeamB"}}, |
| + {name: "directory", cfg: teammode.Config{DirectoryOrigin: other}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + home, c, app, origin := *teammodetest.Home(b), *cfg, testApp, testOrigin |
| + if tc.home != (teammode.Home{}) { |
| + home = tc.home |
| + } |
| + if tc.cfg.TeamID != "" { |
| + c.TeamID = tc.cfg.TeamID |
| + } |
| + if tc.cfg.DirectoryOrigin != "" { |
| + c.DirectoryOrigin = tc.cfg.DirectoryOrigin |
| + } |
| + if tc.app != "" { |
| + app = tc.app |
| + } |
| + if tc.origin != "" { |
| + origin = tc.origin |
| + } |
| + if _, err := teammode.Verify(&c, &home, app, origin); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a different %s was accepted: %v", tc.name, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestVerifyRefusesMalformedValues(t *testing.T) { |
| + b := teammodetest.Bindings(testApp, testConsumer, testOrigin) |
| + cfg, _ := teammodetest.Provision(t, b) |
| + otherCfg, _ := teammodetest.Provision(t, b) // a different operator key |
| + raw, _ := base64.StdEncoding.DecodeString(cfg.OperatorKeysBase64) |
| + var keys []map[string]any |
| + if err := json.Unmarshal(raw, &keys); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys[0]["extra"] = "x" |
| + extra, _ := json.Marshal(keys) |
| + for name, mutate := range map[string]func(*teammode.Config){ |
| + "short token": func(c *teammode.Config) { c.RosterToken = "abc" }, |
| + "padded provisioning": func(c *teammode.Config) { c.ProvisioningBase64 += "=" }, |
| + "url-encoded provisioning": func(c *teammode.Config) { |
| + c.ProvisioningBase64 = strings.NewReplacer("+", "-", "/", "_").Replace(c.ProvisioningBase64) + "-" |
| + }, |
| + "provisioning with a newline": func(c *teammode.Config) { |
| + c.ProvisioningBase64 = c.ProvisioningBase64[:8] + "\n" + c.ProvisioningBase64[8:] |
| + }, |
| + "operator keys with a newline": func(c *teammode.Config) { |
| + c.OperatorKeysBase64 = c.OperatorKeysBase64[:8] + "\n" + c.OperatorKeysBase64[8:] |
| + }, |
| + "provisioning not a record": func(c *teammode.Config) { c.ProvisioningBase64 = base64.StdEncoding.EncodeToString([]byte("{}")) }, |
| + "operator keys not JSON": func(c *teammode.Config) { c.OperatorKeysBase64 = base64.StdEncoding.EncodeToString([]byte("nope")) }, |
| + "operator key with extra field": func(c *teammode.Config) { c.OperatorKeysBase64 = base64.StdEncoding.EncodeToString(extra) }, |
| + "another operator's key": func(c *teammode.Config) { c.OperatorKeysBase64 = otherCfg.OperatorKeysBase64 }, |
| + } { |
| + c := *cfg |
| + mutate(&c) |
| + if _, err := teammode.Verify(&c, teammodetest.Home(b), testApp, testOrigin); !errors.Is(err, teammode.ErrConfig) { |
| + t.Errorf("%s accepted: %v", name, err) |
| + } |
| + } |
| +} |
| + |
| +// The fingerprint is Docs' and Sheets' exactly: base64url SHA-256 of the |
| +// bindings' JSON. Pinned, so an encoding change cannot silently strand every |
| +// activated database. |
| +func TestFingerprintIsPinned(t *testing.T) { |
| + b := roster.Bindings{Issuer: "https://id.oficina.works", Directory: "https://oficina.works", Consumer: "lagged-docs", App: "docs", Team: "Lagged", Audience: "https://lagged.docs.oficina.works"} |
| + if got, want := teammode.Fingerprint(b), "8htR78xHdA8DcPCA0-nUbwv0h2kleKEKIPlFOt-FOtE"; got != want { |
| + t.Fatalf("fingerprint %s, want %s", got, want) |
| + } |
| +} |
diff --git a/teammode/fit_docs_test.go b/teammode/fit_docs_test.go| new file mode 100644 |
| index 0000000..b84974e |
| --- /dev/null |
| +++ b/teammode/fit_docs_test.go |
| @@ -0,0 +1,139 @@ |
| +package teammode_test |
| + |
| +// The API fits Docs: Docs' store-side team mode (internal/docs |
| +// team_access.go, team_config.go at e58a22f) on teammode. Docs authorizes |
| +// inside its writer transaction — permissionScope and ownerMutation check |
| +// the request's standing before and after the mutation — and lists a |
| +// grant-only "partial" catalog under Unknown. Its principal store allocates |
| +// a Home principal only through RequireMembership. Each maps onto one |
| +// teammode call; implementation/teammode-package.md writes the mapping out. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +var errNotFound = errors.New("not found") |
| + |
| +// docsLike is Docs' Store in miniature: documents owned by a person, grants |
| +// to a person (Docs keys grants on the verified address; a person ID here). |
| +type docsLike struct{ db *sql.DB } |
| + |
| +// permission is Docs' permissionScope over one document, as a Guard |
| +// authorize: owner standing only while Member, a grant whatever the roster |
| +// says, and Unknown never turned into "not found". |
| +func (d docsLike) permission(ctx context.Context, tx *sql.Tx, person, doc int64) func(roster.State) error { |
| + return func(s roster.State) error { |
| + var owner int64 |
| + var granted bool |
| + if err := tx.QueryRowContext(ctx, "SELECT owner, EXISTS(SELECT 1 FROM shares WHERE item=items.id AND person=?) FROM items WHERE id=?", person, doc).Scan(&owner, &granted); err != nil { |
| + return errNotFound |
| + } |
| + switch { |
| + case granted, s == roster.Member && owner == person: |
| + return nil |
| + case s == roster.Unknown: |
| + return teammode.ErrUnavailable // Docs' permissionError: 503, not 404 |
| + } |
| + return errNotFound |
| + } |
| +} |
| + |
| +// edit is Docs' ownerMutation: the check, the mutation and the re-check, |
| +// all inside the writer transaction. |
| +func (d docsLike) edit(ctx context.Context, person, doc int64, title string) error { |
| + tx, err := d.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if err := teammode.Guard(ctx, d.permission(ctx, tx, person, doc), func() error { |
| + _, err := tx.ExecContext(ctx, "UPDATE items SET title=? WHERE id=?", title, doc) |
| + return err |
| + }); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// catalog is Docs' list with partialCatalog: own documents only while |
| +// Member, grants always, and the partial notice under Unknown. |
| +func (d docsLike) catalog(ctx context.Context, person int64) ([]string, bool) { |
| + a, _ := teammode.FromContext(ctx) |
| + member := a.State() == roster.Member |
| + rows, err := d.db.QueryContext(ctx, "SELECT title FROM items WHERE (? AND owner=?) OR id IN (SELECT item FROM shares WHERE person=?) ORDER BY id", member, person, person) |
| + if err != nil { |
| + return nil, true |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var title string |
| + _ = rows.Scan(&title) |
| + out = append(out, title) |
| + } |
| + return out, a.Partial() |
| +} |
| + |
| +func TestFitsDocs(t *testing.T) { |
| + f := newFixture(t) |
| + ctx := context.Background() |
| + w := f.db.Writer() |
| + d := docsLike{db: w} |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + |
| + // principalstore.EnsureHome's RequireMembership is AdmitUnlinked. |
| + requireMembership := func(subject string) error { return f.rt.AdmitUnlinked(ctx, f.bindings.Issuer, subject) } |
| + if requireMembership(alice) != nil || !errors.Is(requireMembership(bob), teammode.ErrNotMember) { |
| + t.Fatal("principal allocation does not follow the roster") |
| + } |
| + |
| + const me, other = 1, 2 |
| + if _, err := w.Exec("INSERT INTO items(id,owner,title) VALUES(1,?,'mine'),(2,?,'shared with me'),(3,?,'not mine')", me, other, other); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.Exec("INSERT INTO shares(item,person) VALUES(2,?)", me); err != nil { |
| + t.Fatal(err) |
| + } |
| + req := teammode.WithAccess(ctx, f.rt.Access(ctx, alice)) |
| + if err := d.edit(req, me, 1, "mine, edited"); err != nil { |
| + t.Fatalf("member edits own: %v", err) |
| + } |
| + if err := d.edit(req, me, 3, "x"); !errors.Is(err, errNotFound) { |
| + t.Fatalf("member edits another's unshared document: %v", err) |
| + } |
| + if titles, partial := d.catalog(req, me); len(titles) != 2 || partial { |
| + t.Fatalf("member catalog %v partial=%v", titles, partial) |
| + } |
| + |
| + // The lease lapses inside the same request: own documents answer 503, |
| + // shares still work, and the catalog is shares only, marked partial. |
| + f.expired() |
| + if err := d.edit(req, me, 1, "x"); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("own document under Unknown: %v", err) |
| + } |
| + if err := d.edit(req, me, 2, "shared, edited"); err != nil { |
| + t.Fatalf("share under Unknown: %v", err) |
| + } |
| + if titles, partial := d.catalog(req, me); len(titles) != 1 || titles[0] != "shared, edited" || !partial { |
| + t.Fatalf("Unknown catalog %v partial=%v", titles, partial) |
| + } |
| + |
| + // Removed: a guest, with the complete (not partial) list of shares. |
| + f.dir.SetDown(false) |
| + f.dir.Set(alice, "") |
| + f.refreshed() |
| + guest := teammode.WithAccess(ctx, f.rt.Access(ctx, alice)) |
| + if err := d.edit(guest, me, 1, "x"); !errors.Is(err, errNotFound) { |
| + t.Fatalf("removed owner edits: %v", err) |
| + } |
| + if titles, partial := d.catalog(guest, me); len(titles) != 1 || partial { |
| + t.Fatalf("guest catalog %v partial=%v", titles, partial) |
| + } |
| +} |
diff --git a/teammode/fit_sheets_test.go b/teammode/fit_sheets_test.go| new file mode 100644 |
| index 0000000..076bdb0 |
| --- /dev/null |
| +++ b/teammode/fit_sheets_test.go |
| @@ -0,0 +1,285 @@ |
| +package teammode_test |
| + |
| +// The API fits Sheets: this is Sheets' team mode (internal/sheets |
| +// team_config.go, team_access.go, team_home.go at ca78cc1) rebuilt on |
| +// teammode and connect's Unlinked hook, end to end through a real Home |
| +// exchange, with Sheets' private completion (team_home.go) gone. The |
| +// mapping is written out in implementation/teammode-package.md. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/base64" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "testing/fstest" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +const sheetsCookie = "__Host-sheets-session" |
| + |
| +// sheetsLike is the app: its members table (address NULL for a Home-only |
| +// member), the Home-only identity table, and an in-memory session store. |
| +type sheetsLike struct { |
| + t *testing.T |
| + f *fixture |
| + bridge *connect.Bridge |
| + key *family.Keypair |
| + mu sync.Mutex |
| + sessions map[string]connect.Session |
| +} |
| + |
| +var sheetsBase = migrate.MustFromFS(fstest.MapFS{"migrations/0001_app.sql": {Data: []byte(` |
| +CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE); |
| +CREATE TABLE app_home_only (issuer TEXT NOT NULL, subject TEXT NOT NULL, person_id INTEGER NOT NULL UNIQUE REFERENCES people(id), PRIMARY KEY(issuer,subject)); |
| +`)}}, "app") |
| + |
| +func newSheetsLike(t *testing.T) *sheetsLike { |
| + t.Helper() |
| + ctx := context.Background() |
| + b := teammodetest.Bindings(testApp, testConsumer, testOrigin) |
| + cfg, dir := teammodetest.Provision(t, b) |
| + settings, err := teammode.Verify(cfg, teammodetest.Home(b), testApp, testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &fixture{t: t, db: openDB(t, filepath.Join(t.TempDir(), "sheets.db")), cfg: cfg, bindings: b, dir: dir, clock: teammodetest.NewClock(), settings: settings} |
| + base := migrate.Merge(sheetsBase, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| + schema, err := testState.BootSchema(ctx, f.db.Writer(), settings, base, migrate.Merge(base, testState.Schema())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := migrate.Apply(ctx, f.db, schema); err != nil { |
| + t.Fatal(err) |
| + } |
| + rc := f.runtimeConfig() |
| + if f.rt, err = teammode.Open(ctx, rc); err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := &sheetsLike{t: t, f: f, key: key, sessions: map[string]connect.Session{}} |
| + w := f.db.Writer() |
| + rt := f.rt |
| + a.bridge, err = connect.New(connect.Config{DB: w, Origin: testOrigin, Issuer: b.Issuer, ConsumerID: b.Consumer, Namespace: "oficina/sheets", |
| + Keys: map[string][]byte{"key": key.SignPub()}, DEK: bytes.Repeat([]byte{9}, 32), SessionCookie: sheetsCookie, |
| + ReadSession: func(r *http.Request) (*connect.Session, error) { |
| + s, ok := a.session(r) |
| + if !ok { |
| + return nil, nil |
| + } |
| + return &s, nil |
| + }, |
| + MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| + http.SetCookie(w, &http.Cookie{Name: sheetsCookie, Value: a.mint(s), Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| + return nil |
| + }, |
| + LookupLocalSession: func(ctx context.Context, s connect.Session) (connect.Person, error) { |
| + var p connect.Person |
| + err := w.QueryRowContext(ctx, "SELECT id,address FROM people WHERE address=?", s.Subject).Scan(&p.ID, &p.Label) |
| + return p, err |
| + }, |
| + LookupPerson: func(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| + var label string |
| + err := q.QueryRowContext(ctx, "SELECT address FROM people WHERE id=? AND address IS NOT NULL", id).Scan(&label) |
| + return label, err |
| + }, |
| + Render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| + w.WriteHeader(status) |
| + _, _ = w.Write([]byte(state)) |
| + }, |
| + // Sheets' teamstate.HomeMember. |
| + HomeOnly: func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + var p connect.Person |
| + err := w.QueryRowContext(ctx, "SELECT person_id FROM app_home_only WHERE issuer=? AND subject=?", issuer, subject).Scan(&p.ID) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return p, err |
| + }, |
| + // Sheets' teamComplete, minus everything connect now does: the |
| + // roster decision, then teamstate.EnsureHomeMember. |
| + Unlinked: func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + if err := rt.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, err |
| + } |
| + tx, err := w.BeginTx(ctx, nil) |
| + if err != nil { |
| + return connect.Person{}, err |
| + } |
| + defer tx.Rollback() |
| + res, err := tx.ExecContext(ctx, "INSERT INTO people(address) VALUES(NULL)") |
| + if err != nil { |
| + return connect.Person{}, err |
| + } |
| + id, _ := res.LastInsertId() |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO app_home_only(issuer,subject,person_id) VALUES(?,?,?)", issuer, subject, id); err != nil { |
| + return connect.Person{}, err |
| + } |
| + return connect.Person{ID: id}, tx.Commit() |
| + }, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return a |
| +} |
| + |
| +func (a *sheetsLike) mint(s connect.Session) string { |
| + raw := make([]byte, 32) |
| + _, _ = rand.Read(raw) |
| + token := base64.RawURLEncoding.EncodeToString(raw) |
| + s.At = time.Now() |
| + a.mu.Lock() |
| + a.sessions[token] = s |
| + a.mu.Unlock() |
| + return token |
| +} |
| + |
| +func (a *sheetsLike) session(r *http.Request) (connect.Session, bool) { |
| + c, err := r.Cookie(sheetsCookie) |
| + if err != nil { |
| + return connect.Session{}, false |
| + } |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + s, ok := a.sessions[c.Value] |
| + return s, ok |
| +} |
| + |
| +func cookieFrom(w *httptest.ResponseRecorder, name string) *http.Cookie { |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == name && c.MaxAge >= 0 && c.Value != "" { |
| + return c |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// signIn runs Start, the issuer's callback and Finish for subject, with |
| +// cookies already in the jar. |
| +func (a *sheetsLike) signIn(subject string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + a.t.Helper() |
| + req := func(method, path string, jar []*http.Cookie) *http.Request { |
| + r := httptest.NewRequest(method, testOrigin+path, nil) |
| + for _, c := range jar { |
| + r.AddCookie(c) |
| + } |
| + return r |
| + } |
| + start := httptest.NewRecorder() |
| + a.bridge.Start(start, req(http.MethodGet, "/auth/start?return_to=%2Fsheets", cookies)) |
| + if start.Code != 303 { |
| + a.t.Fatalf("start %d", start.Code) |
| + } |
| + target, _ := url.Parse(start.Header().Get("Location")) |
| + pending := cookieFrom(start, "__Host-oficina-assertion-pending") |
| + id, _ := assertion.RandomID() |
| + now := time.Now().Unix() |
| + token, err := assertion.Sign(a.key, assertion.Claims{Version: 1, Issuer: a.f.bindings.Issuer, Audience: testOrigin, Subject: subject, KeyID: "key", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now}) |
| + if err != nil { |
| + a.t.Fatal(err) |
| + } |
| + cb := httptest.NewRequest(http.MethodPost, testOrigin+"/auth/assertion", strings.NewReader(url.Values{"assertion": {token}}.Encode())) |
| + cb.Header.Set("Origin", a.f.bindings.Issuer) |
| + cb.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + callback := httptest.NewRecorder() |
| + a.bridge.Callback(callback, cb) |
| + if callback.Code != 303 { |
| + a.t.Fatalf("callback %d", callback.Code) |
| + } |
| + finish := httptest.NewRecorder() |
| + a.bridge.Finish(finish, req(http.MethodGet, "/auth/finish", append(append([]*http.Cookie{}, cookies...), pending, cookieFrom(callback, "__Host-oficina-assertion-inbox")))) |
| + return finish |
| +} |
| + |
| +// standing is Sheets' resolveTeamAccess: session, person, then the roster |
| +// about the session's Home subject. |
| +func (a *sheetsLike) standing(cookie *http.Cookie) (connect.Person, *teammode.Access, error) { |
| + r := httptest.NewRequest(http.MethodGet, testOrigin+"/sheets", nil) |
| + r.AddCookie(cookie) |
| + p, err := a.bridge.ResolveSession(r) |
| + if err != nil { |
| + return p, nil, err |
| + } |
| + s, _ := a.session(r) |
| + return p, a.f.rt.Access(r.Context(), s.Subject), nil |
| +} |
| + |
| +func (a *sheetsLike) people() int { |
| + var n int |
| + if err := a.f.db.Writer().QueryRow("SELECT COUNT(*) FROM people").Scan(&n); err != nil { |
| + a.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func TestFitsSheets(t *testing.T) { |
| + a := newSheetsLike(t) |
| + a.f.dir.Set(alice, "owner") |
| + a.f.refreshed() |
| + |
| + // A roster member with no account here signs in on Home alone, as an |
| + // addressless person, and has the roster's role. |
| + w := a.signIn(alice) |
| + if w.Code != 303 || w.Header().Get("Location") != "/sheets" { |
| + t.Fatalf("member sign-in %d %s", w.Code, w.Body.String()) |
| + } |
| + session := cookieFrom(w, sheetsCookie) |
| + p, access, err := a.standing(session) |
| + if err != nil || p.ID <= 0 || p.Label != "" || access.Role() != "owner" { |
| + t.Fatalf("member standing %+v %v", p, err) |
| + } |
| + |
| + // A stranger allocates nothing and sees connect's unknown page. |
| + if w := a.signIn(bob); w.Code != 403 || w.Body.String() != "unknown" || a.people() != 1 { |
| + t.Fatalf("stranger %d %q, %d people", w.Code, w.Body.String(), a.people()) |
| + } |
| + |
| + // A known Home-only member arriving over somebody else's session: 403. |
| + if _, err := a.f.db.Writer().Exec("INSERT INTO people(address) VALUES('x@example.com')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + local := &http.Cookie{Name: sheetsCookie, Value: a.mint(connect.Session{Subject: "x@example.com", Method: "magiclink", AuthTime: time.Now()})} |
| + if w := a.signIn(alice, local); w.Code != 403 { |
| + t.Fatalf("known arrival over another session %d", w.Code) |
| + } |
| + |
| + // Removal reaches the existing session at the next refresh: identity |
| + // stays (shares still open), standing goes. |
| + a.f.dir.Set(alice, "") |
| + a.f.refreshed() |
| + if p2, access, err := a.standing(session); err != nil || p2.ID != p.ID || access.State() != roster.NotMember { |
| + t.Fatal("removal did not reach the held session") |
| + } |
| + |
| + // Unknown: a member who has never signed in cannot be allocated now. |
| + a.f.dir.Set(carol, "member") |
| + a.f.expired() |
| + if w := a.signIn(carol); w.Code != 503 || a.people() != 2 { |
| + t.Fatalf("Unknown arrival %d, %d people", w.Code, a.people()) |
| + } |
| +} |
diff --git a/teammode/fixture_test.go b/teammode/fixture_test.go| new file mode 100644 |
| index 0000000..cadbb98 |
| --- /dev/null |
| +++ b/teammode/fixture_test.go |
| @@ -0,0 +1,149 @@ |
| +package teammode_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| + "testing/fstest" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +const ( |
| + testApp = "sheets" |
| + testOrigin = "https://sheets.example.com" |
| + testConsumer = "sheets-preview" |
| +) |
| + |
| +var testState = teammode.MustState("sheets") |
| + |
| +// baseSchema stands in for an app's own schema: its people, connect's links |
| +// and a Home-only identity table, the two tables a census reads. |
| +var baseSchema = migrate.MustFromFS(fstest.MapFS{"migrations/0001_app.sql": {Data: []byte(` |
| +CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE); |
| +CREATE TABLE home_identity_links (issuer TEXT NOT NULL, subject TEXT NOT NULL, person_id INTEGER NOT NULL, PRIMARY KEY(issuer,subject)); |
| +CREATE TABLE app_home_only (issuer TEXT NOT NULL, subject TEXT NOT NULL, person_id INTEGER NOT NULL UNIQUE, PRIMARY KEY(issuer,subject)); |
| +CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, owner INTEGER NOT NULL, title TEXT NOT NULL); |
| +CREATE TABLE shares (item INTEGER NOT NULL, person INTEGER NOT NULL); |
| +`)}}, "app") |
| + |
| +var teamSchema = migrate.Merge(baseSchema, testState.Schema()) |
| + |
| +var issuerTables = []string{"home_identity_links", "app_home_only"} |
| + |
| +type fixture struct { |
| + t *testing.T |
| + db *db.DB |
| + cfg *teammode.Config |
| + bindings roster.Bindings |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| + settings *teammode.Settings |
| + rt *teammode.Runtime |
| +} |
| + |
| +func openDB(t *testing.T, path string) *db.DB { |
| + t.Helper() |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + return d |
| +} |
| + |
| +// newFixture is a team-mode instance at boot: schema chosen by BootSchema, |
| +// applied, and the runtime opened, with an empty roster. |
| +func newFixture(t *testing.T) *fixture { |
| + t.Helper() |
| + f := provisioned(t) |
| + f.boot() |
| + return f |
| +} |
| + |
| +// provisioned is the configuration and a fresh database, nothing applied. |
| +func provisioned(t *testing.T) *fixture { |
| + t.Helper() |
| + b := teammodetest.Bindings(testApp, testConsumer, testOrigin) |
| + cfg, dir := teammodetest.Provision(t, b) |
| + settings, err := teammode.Verify(cfg, teammodetest.Home(b), testApp, testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return &fixture{t: t, db: openDB(t, filepath.Join(t.TempDir(), "app.db")), cfg: cfg, bindings: b, dir: dir, clock: teammodetest.NewClock(), settings: settings} |
| +} |
| + |
| +func (f *fixture) boot() { |
| + f.t.Helper() |
| + ctx := context.Background() |
| + schema, err := testState.BootSchema(ctx, f.db.Writer(), f.settings, baseSchema, teamSchema) |
| + if err != nil { |
| + f.t.Fatalf("BootSchema: %v", err) |
| + } |
| + if _, err := migrate.Apply(ctx, f.db, schema); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.rt, err = f.open() |
| + if err != nil { |
| + f.t.Fatalf("Open: %v", err) |
| + } |
| +} |
| + |
| +func testSealer(t testing.TB) *seal.Sealer { |
| + t.Helper() |
| + s, err := seal.New(bytes.Repeat([]byte{9}, 32), "oficina/sheets") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func (f *fixture) runtimeConfig() teammode.RuntimeConfig { |
| + return teammode.RuntimeConfig{Settings: f.settings, State: testState, DB: f.db.Writer(), Sealer: testSealer(f.t), IssuerTables: issuerTables, Transport: f.dir, Clock: f.clock} |
| +} |
| + |
| +func (f *fixture) open() (*teammode.Runtime, error) { |
| + return teammode.Open(context.Background(), f.runtimeConfig()) |
| +} |
| + |
| +// refreshed steps past the refresh point and waits for the refresh, so the |
| +// next decision sees the directory's current list. |
| +func (f *fixture) refreshed() { |
| + f.t.Helper() |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + if err := f.rt.Refresh(context.Background()); err != nil { |
| + f.t.Fatalf("refresh: %v", err) |
| + } |
| +} |
| + |
| +// expired takes the directory down and steps past the lease: Unknown. |
| +func (f *fixture) expired() { |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| +} |
| + |
| +var ( |
| + alice = teammodetest.Subject('a') |
| + bob = teammodetest.Subject('b') |
| + carol = teammodetest.Subject('c') |
| +) |
| + |
| +func wantState(t *testing.T, a *teammode.Access, want roster.State) { |
| + t.Helper() |
| + if got := a.State(); got != want { |
| + t.Fatalf("state %d, want %d", got, want) |
| + } |
| +} |
| + |
| +func migrateApply(f *fixture, schema *migrate.Set) (migrate.Result, error) { |
| + return migrate.Apply(context.Background(), f.db, schema) |
| +} |
diff --git a/teammode/go.mod b/teammode/go.mod| new file mode 100644 |
| index 0000000..cce2a24 |
| --- /dev/null |
| +++ b/teammode/go.mod |
| @@ -0,0 +1,30 @@ |
| +module amadan.net/oficina/home/teammode |
| + |
| +go 1.25.0 |
| + |
| +require ( |
| + amadan.net/oficina/home/connect v0.0.0-20261028160933-6b23c73a22c6 |
| + amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| + amadan.net/oficina/home/roster v0.0.0-20261028160933-6b23c73a22c6 |
| + amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd |
| + github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| +) |
| + |
| +require ( |
| + amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef // indirect |
| + github.com/dustin/go-humanize v1.0.1 // indirect |
| + github.com/google/uuid v1.6.0 // indirect |
| + github.com/jinzhu/inflection v1.0.0 // indirect |
| + github.com/jinzhu/now v1.1.5 // indirect |
| + github.com/mattn/go-isatty v0.0.20 // indirect |
| + github.com/ncruces/go-strftime v1.0.0 // indirect |
| + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| + golang.org/x/sys v0.46.0 // indirect |
| + golang.org/x/text v0.20.0 // indirect |
| + gorm.io/gorm v1.31.2 // indirect |
| + gorm.io/plugin/dbresolver v1.6.2 // indirect |
| + modernc.org/libc v1.74.1 // indirect |
| + modernc.org/mathutil v1.7.1 // indirect |
| + modernc.org/memory v1.11.0 // indirect |
| + modernc.org/sqlite v1.55.0 // indirect |
| +) |
diff --git a/teammode/go.sum b/teammode/go.sum| new file mode 100644 |
| index 0000000..b8adccb |
| --- /dev/null |
| +++ b/teammode/go.sum |
| @@ -0,0 +1,83 @@ |
| +amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef h1:c+0jDD33fLLQ0L4lOF7mYjEC6dbcIq1d3RGAAxGtXWo= |
| +amadan.net/oficina/estilo.git v0.0.0-20261024225503-1817c1c6c7ef/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| +amadan.net/oficina/home/connect v0.0.0-20261028160933-6b23c73a22c6 h1:AQRbXYwYSUC4+lXslbIhGkskCke5Hsj6Ap+MRfPSnBs= |
| +amadan.net/oficina/home/connect v0.0.0-20261028160933-6b23c73a22c6/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM= |
| +amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/roster v0.0.0-20261028160933-6b23c73a22c6 h1:DxQaZcJoSkbs/ZNqcEqHPodkWiKUvE5CUnZlDcaXJBg= |
| +amadan.net/oficina/home/roster v0.0.0-20261028160933-6b23c73a22c6/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| +amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc= |
| +amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE= |
| +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= |
| +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= |
| +github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs= |
| +github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M= |
| +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= |
| +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= |
| +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= |
| +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= |
| +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= |
| +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= |
| +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= |
| +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= |
| +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= |
| +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= |
| +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= |
| +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= |
| +github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q= |
| +github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls= |
| +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= |
| +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= |
| +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= |
| +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= |
| +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= |
| +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= |
| +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
| +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= |
| +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= |
| +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= |
| +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= |
| +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
| +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= |
| +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= |
| +golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= |
| +golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= |
| +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= |
| +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= |
| +gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= |
| +gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= |
| +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= |
| +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= |
| +gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= |
| +gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= |
| +gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc= |
| +gorm.io/plugin/dbresolver v1.6.2/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM= |
| +modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc= |
| +modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= |
| +modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= |
| +modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk= |
| +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= |
| +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= |
| +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= |
| +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= |
| +modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI= |
| +modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= |
| +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= |
| +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= |
| +modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ= |
| +modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os= |
| +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= |
| +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= |
| +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= |
| +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= |
| +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= |
| +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= |
| +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= |
| +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= |
| +modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM= |
| +modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= |
| +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= |
| +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= |
| +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= |
| +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= |
diff --git a/teammode/probe.go b/teammode/probe.go| new file mode 100644 |
| index 0000000..143c247 |
| --- /dev/null |
| +++ b/teammode/probe.go |
| @@ -0,0 +1,44 @@ |
| +package teammode |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| +) |
| + |
| +// ProbePath is the readiness probe Alta polls at provisioning step 11 |
| +// before it activates an instance in Home's directory (team-members.md §7; |
| +// Alta provision/steps.go TeamProbe). Mount Probe there for GET. |
| +const ProbePath = "/api/team" |
| + |
| +type probeBody struct { |
| + TeamMode bool `json:"team_mode"` |
| + Consumer string `json:"consumer,omitempty"` |
| + Roster string `json:"roster,omitempty"` |
| +} |
| + |
| +// Probe answers GET /api/team, unauthenticated, with only {team_mode, |
| +// consumer, roster}: whether this instance runs in team mode, the consumer |
| +// ID its verified provisioning record names, and RosterState. No account |
| +// data — no subject, role, member count, address, team ID or issuer — and |
| +// nothing that differs with who is asking. A nil Runtime (team mode off) |
| +// answers {"team_mode":false} and nothing else. Docs' and Sheets' probe, |
| +// byte for byte. |
| +func Probe(t *Runtime) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body := probeBody{} |
| + if t != nil { |
| + body = probeBody{TeamMode: true, Consumer: t.bindings.Consumer, Roster: t.RosterState(r.Context())} |
| + } |
| + raw, err := json.Marshal(body) |
| + if err != nil { |
| + http.Error(w, "Unavailable.", http.StatusInternalServerError) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| + // Readiness changes from one second to the next; a cached "ok" |
| + // would let Alta activate an instance whose roster has gone stale. |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| + _, _ = w.Write(raw) |
| + }) |
| +} |
diff --git a/teammode/probe_test.go b/teammode/probe_test.go| new file mode 100644 |
| index 0000000..1a614ef |
| --- /dev/null |
| +++ b/teammode/probe_test.go |
| @@ -0,0 +1,79 @@ |
| +package teammode_test |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +func probe(t *testing.T, rt *teammode.Runtime, cookies ...*http.Cookie) string { |
| + t.Helper() |
| + r := httptest.NewRequest(http.MethodGet, testOrigin+teammode.ProbePath, nil) |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + teammode.Probe(rt).ServeHTTP(w, r) |
| + if w.Code != 200 || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/json; charset=utf-8" || w.Header().Get("X-Content-Type-Options") != "nosniff" { |
| + t.Fatalf("probe %d %v", w.Code, w.Header()) |
| + } |
| + return w.Body.String() |
| +} |
| + |
| +func TestProbeTeamModeOff(t *testing.T) { |
| + if body := probe(t, nil); body != `{"team_mode":false}` { |
| + t.Fatalf("team off body %s", body) |
| + } |
| +} |
| + |
| +// unknown before any roster, ok while one decides, stale once it has aged |
| +// out — and nothing about anybody, whoever asks. |
| +func TestProbeRosterStates(t *testing.T) { |
| + f := provisioned(t) |
| + f.dir.SetDown(true) |
| + f.boot() |
| + f.dir.Set(alice, "owner") |
| + unknown := `{"team_mode":true,"consumer":"` + testConsumer + `","roster":"unknown"}` |
| + if body := probe(t, f.rt); body != unknown { |
| + t.Fatalf("before any roster %s", body) |
| + } |
| + f.dir.SetDown(false) |
| + f.clock.Step(roster.RetryAfter) |
| + ok := strings.Replace(unknown, "unknown", "ok", 1) |
| + signedIn := &http.Cookie{Name: "__Host-session", Value: "x"} |
| + if body := probe(t, f.rt); body != ok { |
| + t.Fatalf("with a roster %s", body) |
| + } |
| + if body := probe(t, f.rt, signedIn); body != ok { |
| + t.Fatal("the answer differs with who asks") |
| + } |
| + for _, secret := range []string{alice, "owner", f.bindings.Team, f.bindings.Issuer, f.bindings.Directory} { |
| + if strings.Contains(ok, secret) { |
| + t.Fatalf("probe leaks %q", secret) |
| + } |
| + } |
| + f.expired() |
| + if body := probe(t, f.rt); body != strings.Replace(unknown, "unknown", "stale", 1) { |
| + t.Fatalf("aged out %s", body) |
| + } |
| +} |
| + |
| +// rosterHeld is set by the one Check every path shares: a request's |
| +// decision alone makes a later outage "stale", though the probe never saw |
| +// "ok". |
| +func TestProbeStaleAfterARequestHeldTheRoster(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + if f.rt.Access(context.Background(), alice).State() != roster.Member { |
| + t.Fatal("no roster") |
| + } |
| + f.expired() |
| + if body := probe(t, f.rt); !strings.Contains(body, `"roster":"stale"`) { |
| + t.Fatalf("held roster not recorded: %s", body) |
| + } |
| +} |
diff --git a/teammode/runtime.go b/teammode/runtime.go| new file mode 100644 |
| index 0000000..808f45d |
| --- /dev/null |
| +++ b/teammode/runtime.go |
| @@ -0,0 +1,160 @@ |
| +package teammode |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "sync/atomic" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// RuntimeConfig opens a Runtime. Settings, State, DB, Sealer and |
| +// IssuerTables are required. |
| +type RuntimeConfig struct { |
| + Settings *Settings |
| + State State |
| + // DB is the app's writer. Activation and evidence go through it. |
| + DB *sql.DB |
| + // Sealer seals the roster evidence: the app's Home DEK under its own |
| + // namespace, as Docs ("oficina/docs") and Sheets do. |
| + Sealer handoff.Sealer |
| + // IssuerTables are the app's tables holding Home identities in an |
| + // issuer column: connect's home_identity_links, the app's Home-only |
| + // people. Open refuses activation while any row names another issuer: |
| + // the marker pins one, and a row from another would be reinterpreted |
| + // under it. Lower-case SQL identifiers only. |
| + IssuerTables []string |
| + // Transport and Clock are for tests (teammodetest); nil in production. |
| + Transport http.RoundTripper |
| + Clock roster.Clock |
| +} |
| + |
| +var tablePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,62}$`) |
| + |
| +// Runtime is the process's roster cache and what acts on its answers. |
| +type Runtime struct { |
| + cache *roster.Cache |
| + bindings roster.Bindings |
| + // held: some Check since boot had a complete roster (the probe's |
| + // "stale" versus "unknown"). |
| + held atomic.Bool |
| +} |
| + |
| +// Open activates team mode and builds the roster cache, after the app has |
| +// applied its team schema and before it serves. It either returns a |
| +// verified, activated runtime or refuses: ErrConfig for configuration (a |
| +// foreign issuer, a different binding), ErrUnavailable for storage or |
| +// evidence the cache cannot use. |
| +func Open(ctx context.Context, c RuntimeConfig) (*Runtime, error) { |
| + if c.Settings == nil || !c.State.valid() || c.DB == nil || c.Sealer == nil || len(c.IssuerTables) == 0 { |
| + return nil, ErrConfig |
| + } |
| + b := c.Settings.Bindings() |
| + parts := make([]string, 0, len(c.IssuerTables)) |
| + args := make([]any, 0, len(c.IssuerTables)) |
| + for _, t := range c.IssuerTables { |
| + if !tablePattern.MatchString(t) { |
| + return nil, ErrConfig |
| + } |
| + parts = append(parts, "(SELECT COUNT(*) FROM "+t+" WHERE issuer!=?)") |
| + args = append(args, b.Issuer) |
| + } |
| + var foreign int |
| + if err := c.DB.QueryRowContext(ctx, "SELECT "+strings.Join(parts, "+"), args...).Scan(&foreign); err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + if foreign != 0 { |
| + return nil, ErrConfig |
| + } |
| + if err := c.State.Activate(ctx, c.DB, c.Settings.fingerprint); err != nil { |
| + return nil, err |
| + } |
| + cache, err := roster.New(ctx, roster.Config{Record: c.Settings.record, Token: c.Settings.token, Transport: c.Transport, Clock: c.Clock, Durable: c.State.Evidence(c.DB), Sealer: c.Sealer}) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return &Runtime{cache: cache, bindings: b}, nil |
| +} |
| + |
| +// Bindings are the verified bindings this runtime serves. |
| +func (t *Runtime) Bindings() roster.Bindings { return t.bindings } |
| + |
| +// Check is the only way an app asks the roster cache, so every definite |
| +// answer — a request's, an allocation's or the probe's — records that a |
| +// complete roster has been held since boot. It may wait for a refresh (at |
| +// most roster.FetchTimeout), and a refresh publishes through the SQLite |
| +// writer: never call it holding the writer. Inside a transaction, use |
| +// Access.State or Guard, which never ask. |
| +func (t *Runtime) Check(ctx context.Context, subject string) roster.Decision { |
| + d := t.cache.Check(ctx, t.bindings.Issuer, t.bindings.Team, subject) |
| + if d.State != roster.Unknown { |
| + t.held.Store(true) |
| + } |
| + return d |
| +} |
| + |
| +// Access decides one request's standing for the Home subject its session |
| +// resolved to. subject "" (a local account with no Home identity) is |
| +// NotMember without asking: no Home identity, no team standing. Call it per |
| +// request, before any transaction; never store the result. |
| +func (t *Runtime) Access(ctx context.Context, subject string) *Access { |
| + if subject == "" { |
| + return &Access{decision: roster.Decision{State: roster.NotMember}} |
| + } |
| + return &Access{subject: subject, decision: t.Check(ctx, subject)} |
| +} |
| + |
| +// AdmitUnlinked is the decision behind connect's Unlinked hook: nil only |
| +// when the roster says the subject is a Member now and the lease on that |
| +// answer is still valid, which is the one condition on which an app may |
| +// create a Home-only person. ErrNotMember for a subject the roster does not |
| +// list, or one that cannot be on this team (another issuer, not a person |
| +// ref); ErrUnavailable when it cannot be decided. It records identity's |
| +// precondition, not standing: every later request asks the roster again. |
| +func (t *Runtime) AdmitUnlinked(ctx context.Context, issuer, subject string) error { |
| + if issuer != t.bindings.Issuer || !roster.ValidSubject(subject) { |
| + return ErrNotMember |
| + } |
| + d := t.Check(ctx, subject) |
| + switch { |
| + case d.State == roster.Member && d.Lease.Valid(): |
| + return nil |
| + case d.State == roster.NotMember: |
| + return ErrNotMember |
| + } |
| + return ErrUnavailable |
| +} |
| + |
| +// Refresh joins (or starts) the cache's refresh flight and waits for it. |
| +// Ordinary requests never need it; Check refreshes when due. |
| +func (t *Runtime) Refresh(ctx context.Context) error { return t.cache.Refresh(ctx) } |
| + |
| +// probeSubject is a well-formed person ref the probe asks about. Its answer |
| +// is never used, only whether there was one. |
| +var probeSubject = "pr_" + strings.Repeat("2", 26) |
| + |
| +// RosterState is the probe's roster field: |
| +// |
| +// - "ok": a complete roster, fetched within roster.MaximumAge, decides |
| +// standing now; |
| +// - "stale": one was held since this process started, but it has aged out |
| +// and could not be refreshed, so standing is Unknown; |
| +// - "unknown": no complete roster has been held since boot. |
| +// |
| +// Asking starts a refresh when one is due and waits for it, exactly as a |
| +// signed-in request does, which is what lets Alta's polling pull the first |
| +// roster. The cache's single flight and RetryAfter backoff bound how often |
| +// an unauthenticated caller can make this instance ask the directory. |
| +func (t *Runtime) RosterState(ctx context.Context) string { |
| + if t.Check(ctx, probeSubject).State != roster.Unknown { |
| + return "ok" |
| + } |
| + if t.held.Load() { |
| + return "stale" |
| + } |
| + return "unknown" |
| +} |
diff --git a/teammode/runtime_test.go b/teammode/runtime_test.go| new file mode 100644 |
| index 0000000..6ce66e0 |
| --- /dev/null |
| +++ b/teammode/runtime_test.go |
| @@ -0,0 +1,373 @@ |
| +package teammode_test |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| +) |
| + |
| +func TestOpenRefusesAForeignIssuerAndWritesNoMarker(t *testing.T) { |
| + ctx := context.Background() |
| + for _, table := range issuerTables { |
| + t.Run(table, func(t *testing.T) { |
| + f := provisioned(t) |
| + if _, err := migrateTeam(f); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.db.Writer().Exec("INSERT INTO " + table + "(issuer,subject,person_id) VALUES('https://other.example.com','pr_x',1)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.open(); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("foreign issuer in %s: %v", table, err) |
| + } |
| + if _, ok, _ := testState.Required(ctx, f.db.Writer()); ok { |
| + t.Fatal("refused activation wrote the marker") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestOpenRefusesIncompleteConfigurationAndBadTables(t *testing.T) { |
| + f := provisioned(t) |
| + if _, err := migrateTeam(f); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, mutate := range map[string]func(*teammode.RuntimeConfig){ |
| + "no settings": func(c *teammode.RuntimeConfig) { c.Settings = nil }, |
| + "zero state": func(c *teammode.RuntimeConfig) { c.State = teammode.State{} }, |
| + "no db": func(c *teammode.RuntimeConfig) { c.DB = nil }, |
| + "no sealer": func(c *teammode.RuntimeConfig) { c.Sealer = nil }, |
| + "no census": func(c *teammode.RuntimeConfig) { c.IssuerTables = nil }, |
| + "injected table": func(c *teammode.RuntimeConfig) { c.IssuerTables = []string{"people; DROP TABLE people"} }, |
| + } { |
| + c := f.runtimeConfig() |
| + mutate(&c) |
| + if _, err := teammode.Open(context.Background(), c); !errors.Is(err, teammode.ErrConfig) { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| + if _, ok, _ := testState.Required(context.Background(), f.db.Writer()); ok { |
| + t.Fatal("a refused Open wrote the marker") |
| + } |
| +} |
| + |
| +// Open activates: the marker is written before the runtime exists, and from |
| +// then on the database will not boot without this binding. |
| +func TestOpenActivates(t *testing.T) { |
| + f := newFixture(t) |
| + ctx := context.Background() |
| + if fp, ok, err := testState.Required(ctx, f.db.Writer()); err != nil || !ok || fp != f.settings.Fingerprint() { |
| + t.Fatal("Open did not write the marker") |
| + } |
| + if _, err := testState.BootSchema(ctx, f.db.Writer(), nil, baseSchema, teamSchema); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatal("activated database boots without team configuration") |
| + } |
| + if _, err := f.open(); err != nil { |
| + t.Fatalf("reopen with the same binding: %v", err) |
| + } |
| +} |
| + |
| +// A second deployment with another binding cannot take over an activated |
| +// database, even past BootSchema. |
| +func TestOpenRefusesADifferentBinding(t *testing.T) { |
| + f := newFixture(t) |
| + b := f.bindings |
| + b.Team = "TeamB" |
| + cfg, _ := teammodetest.Provision(t, b) |
| + s, err := teammode.Verify(cfg, teammodetest.Home(b), testApp, testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := f.runtimeConfig() |
| + c.Settings = s |
| + if _, err := teammode.Open(context.Background(), c); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("rebinding Open: %v", err) |
| + } |
| +} |
| + |
| +func TestAccessFollowsTheRostersRole(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "owner") |
| + f.dir.Set(bob, "member") |
| + f.refreshed() |
| + ctx := context.Background() |
| + a := f.rt.Access(ctx, alice) |
| + if a.State() != roster.Member || a.Role() != "owner" || a.Subject() != alice || a.Partial() { |
| + t.Fatalf("owner: %d %q", a.State(), a.Role()) |
| + } |
| + b := f.rt.Access(ctx, bob) |
| + if b.State() != roster.Member || b.Role() != "member" { |
| + t.Fatalf("member: %d %q", b.State(), b.Role()) |
| + } |
| + c := f.rt.Access(ctx, carol) |
| + if c.State() != roster.NotMember || c.Role() != "" || c.Remaining() != 0 || c.Partial() { |
| + t.Fatal("stranger has standing") |
| + } |
| + fetches := f.dir.Fetches() |
| + none := f.rt.Access(ctx, "") |
| + if none.State() != roster.NotMember || none.Role() != "" || f.dir.Fetches() != fetches { |
| + t.Fatal("no Home identity asked the roster or had standing") |
| + } |
| + var nilAccess *teammode.Access |
| + if nilAccess.State() != roster.Unknown || nilAccess.Role() != "" || !nilAccess.Partial() || nilAccess.Remaining() != 0 { |
| + t.Fatal("a nil Access has standing") |
| + } |
| +} |
| + |
| +// Removal reaches a held decision within the 60 s lease, under a failing |
| +// refresh, and the request never sees Member again once it has seen Unknown. |
| +func TestHeldDecisionEndsAtTheLeaseAndLatches(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + a := f.rt.Access(context.Background(), alice) |
| + if a.Remaining() != roster.MaximumAge { |
| + t.Fatalf("remaining %v", a.Remaining()) |
| + } |
| + f.dir.SetDown(true) |
| + f.clock.Step(59 * time.Second) |
| + if a.State() != roster.Member || a.Role() != "member" || a.Remaining() != time.Second { |
| + t.Fatal("early expiry") |
| + } |
| + f.clock.Step(2 * time.Second) |
| + if a.State() != roster.Unknown || a.Role() != "" || !a.Partial() || a.Remaining() != 0 { |
| + t.Fatal("standing survived the lease") |
| + } |
| + // The directory is back and a refresh lands: this request's Access |
| + // stays Unknown; the next request's is Member. |
| + f.dir.SetDown(false) |
| + f.clock.Step(roster.RetryAfter) |
| + if err := f.rt.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a.State() != roster.Unknown { |
| + t.Fatal("Unknown did not latch") |
| + } |
| + if f.rt.Access(context.Background(), alice).State() != roster.Member { |
| + t.Fatal("next request not decided afresh") |
| + } |
| +} |
| + |
| +// Remaining latches too: a stream that finds its lease gone must not then |
| +// read Member from State. |
| +func TestRemainingLatches(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + a := f.rt.Access(context.Background(), alice) |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge) |
| + if a.Remaining() != 0 { |
| + t.Fatal("lapsed lease has time left") |
| + } |
| + if a.State() != roster.Unknown { |
| + t.Fatal("Remaining did not latch") |
| + } |
| +} |
| + |
| +// #97 at the package level: a refresh that still lists the person with the |
| +// same role keeps a held decision; a removal or a role change ends it at |
| +// the refresh, not at the lease's end. |
| +func TestHeldDecisionAcrossARefresh(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.dir.Set(bob, "member") |
| + f.dir.Set(carol, "member") |
| + f.refreshed() |
| + ctx := context.Background() |
| + a, b, c := f.rt.Access(ctx, alice), f.rt.Access(ctx, bob), f.rt.Access(ctx, carol) |
| + f.dir.Set(bob, "") |
| + f.dir.Set(carol, "owner") |
| + f.refreshed() |
| + if a.State() != roster.Member { |
| + t.Fatal("an unchanged member's held decision ended at a refresh") |
| + } |
| + if left := a.Remaining(); left != roster.MaximumAge-roster.RefreshAfter-time.Second { |
| + t.Fatalf("the refresh moved the deadline: %v left", left) |
| + } |
| + if b.State() != roster.Unknown { |
| + t.Fatal("removal did not end the held decision") |
| + } |
| + if c.State() != roster.Unknown { |
| + t.Fatal("a role change did not end the held decision") |
| + } |
| + if f.rt.Access(ctx, bob).State() != roster.NotMember || f.rt.Access(ctx, carol).Role() != "owner" { |
| + t.Fatal("the refresh was not decided") |
| + } |
| +} |
| + |
| +func TestUnknownWhenNoRosterCanBeHeld(t *testing.T) { |
| + f := provisioned(t) |
| + f.dir.SetDown(true) |
| + f.boot() |
| + a := f.rt.Access(context.Background(), alice) |
| + if a.State() != roster.Unknown || !a.Partial() || a.Role() != "" { |
| + t.Fatal("no roster, but standing") |
| + } |
| +} |
| + |
| +func TestAdmitUnlinkedOnlyACurrentMember(t *testing.T) { |
| + f := newFixture(t) |
| + ctx := context.Background() |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + iss := f.bindings.Issuer |
| + if err := f.rt.AdmitUnlinked(ctx, iss, alice); err != nil { |
| + t.Fatalf("member refused: %v", err) |
| + } |
| + if err := f.rt.AdmitUnlinked(ctx, iss, bob); !errors.Is(err, teammode.ErrNotMember) { |
| + t.Fatalf("stranger: %v", err) |
| + } |
| + fetches := f.dir.Fetches() |
| + for _, tc := range []struct{ issuer, subject string }{{"https://other.example.com", alice}, {iss, "someone@example.com"}, {iss, "pr_short"}} { |
| + if err := f.rt.AdmitUnlinked(ctx, tc.issuer, tc.subject); !errors.Is(err, teammode.ErrNotMember) { |
| + t.Fatalf("%+v: %v", tc, err) |
| + } |
| + } |
| + if f.dir.Fetches() != fetches { |
| + t.Fatal("an impossible subject asked the directory") |
| + } |
| + f.expired() |
| + if err := f.rt.AdmitUnlinked(ctx, iss, alice); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("Unknown: %v", err) |
| + } |
| +} |
| + |
| +// The lease is checked again after the decision: a Member answer whose lease |
| +// lapses before allocation allocates nothing. |
| +func TestAdmitUnlinkedRechecksTheLease(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + // The cache's answer is still usable at this reading (59.5 s into a 60 |
| + // s lease) but every reading moves the clock on 0.6 s, so the lease the |
| + // decision carries has lapsed by the time it is checked. |
| + f.clock.Step(roster.MaximumAge - 500*time.Millisecond) |
| + f.clock.SetTick(600 * time.Millisecond) |
| + err := f.rt.AdmitUnlinked(context.Background(), f.bindings.Issuer, alice) |
| + if !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("an expired lease admitted: %v", err) |
| + } |
| +} |
| + |
| +// Guard reads the carried standing on both sides of the write, and the app's |
| +// rule decides: here a member-only write. |
| +func TestGuardChecksBeforeAndAfterTheWrite(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + ctx := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), alice)) |
| + wrote := 0 |
| + if err := teammode.Guard(ctx, teammode.RequireMember, func() error { wrote++; return nil }); err != nil || wrote != 1 { |
| + t.Fatalf("member write: %v", err) |
| + } |
| + // The lease lapses during the write: the commit is refused. |
| + f.dir.SetDown(true) |
| + err := teammode.Guard(ctx, teammode.RequireMember, func() error { f.clock.Step(roster.MaximumAge); return nil }) |
| + if !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("lapse mid-write committed: %v", err) |
| + } |
| + wrote = 0 |
| + if err := teammode.Guard(ctx, teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrUnavailable) || wrote != 0 { |
| + t.Fatal("wrote under Unknown") |
| + } |
| + stranger := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), "")) |
| + if err := teammode.Guard(stranger, teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrNotMember) || wrote != 0 { |
| + t.Fatal("a guest wrote a member-only write") |
| + } |
| + if err := teammode.Guard(context.Background(), teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrUnavailable) || wrote != 0 { |
| + t.Fatal("no carried standing wrote") |
| + } |
| + writeErr := errors.New("write failed") |
| + ok := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), "")) |
| + if err := teammode.Guard(ok, func(roster.State) error { return nil }, func() error { return writeErr }); err != writeErr { |
| + t.Fatal("write error not returned") |
| + } |
| +} |
| + |
| +// The lease check is safe inside the writer transaction: with a refresh's |
| +// publication waiting on the one SQLite writer this transaction holds, Guard |
| +// answers at once (contention reads as Unknown) instead of deadlocking. |
| +func TestGuardUnderTheWriterNeverWaitsOnAPublication(t *testing.T) { |
| + f := newFixture(t) |
| + f.dir.Set(alice, "member") |
| + f.refreshed() |
| + w := f.db.Writer() |
| + w.SetMaxOpenConns(1) |
| + ctx := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), alice)) |
| + tx, err := w.BeginTx(context.Background(), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.Exec("INSERT INTO items(owner,title) VALUES(1,'x')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Two more of this person's requests: one asks for a stream's time |
| + // left during the contention, one is not asked at all. |
| + streamed := f.rt.Access(context.Background(), alice) |
| + untouched := f.rt.Access(context.Background(), alice) |
| + f.dir.Set(bob, "member") // a new epoch, so the refresh must publish |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + refreshed := make(chan error, 1) |
| + go func() { refreshed <- f.rt.Refresh(context.Background()) }() |
| + // Wait until the publication is queued on the writer. |
| + deadline := time.Now().Add(2 * time.Second) |
| + for w.Stats().WaitCount == 0 && time.Now().Before(deadline) { |
| + time.Sleep(time.Millisecond) |
| + } |
| + if w.Stats().WaitCount == 0 { |
| + t.Fatal("publication never waited for the writer") |
| + } |
| + done := make(chan error, 1) |
| + go func() { |
| + done <- teammode.Guard(ctx, teammode.RequireMember, func() error { |
| + _, err := tx.Exec("UPDATE items SET title='y'") |
| + return err |
| + }) |
| + }() |
| + select { |
| + case err = <-done: |
| + case <-time.After(time.Second): |
| + _ = tx.Rollback() |
| + t.Fatal("Guard waited on the publication") |
| + } |
| + if left := streamed.Remaining(); left != 0 { |
| + t.Fatalf("contended lease has %v left", left) |
| + } |
| + _ = tx.Rollback() |
| + if !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("contended lease granted standing: %v", err) |
| + } |
| + if e := <-refreshed; e != nil { |
| + t.Fatal(e) |
| + } |
| + // The publication listed alice unchanged, so her lease survived it |
| + // (#97): a request that was never contended is still Member. The two |
| + // that saw the contention latched Unknown and stay there. |
| + if untouched.State() != roster.Member { |
| + t.Fatal("an unchanged publication ended an uncontended request's lease") |
| + } |
| + if a, _ := teammode.FromContext(ctx); a.State() != roster.Unknown { |
| + t.Fatal("State did not latch the contention") |
| + } |
| + if streamed.State() != roster.Unknown { |
| + t.Fatal("Remaining did not latch the contention") |
| + } |
| +} |
| + |
| +func migrateTeam(f *fixture) (*sql.DB, error) { |
| + schema, err := testState.BootSchema(context.Background(), f.db.Writer(), f.settings, baseSchema, teamSchema) |
| + if err != nil { |
| + return nil, err |
| + } |
| + _, err = migrateApply(f, schema) |
| + return f.db.Writer(), err |
| +} |
diff --git a/teammode/schema/0001_team.sql.tmpl b/teammode/schema/0001_team.sql.tmpl| new file mode 100644 |
| index 0000000..4fd5035 |
| --- /dev/null |
| +++ b/teammode/schema/0001_team.sql.tmpl |
| @@ -0,0 +1,10 @@ |
| +CREATE TABLE {{ns}}_team_required ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + bindings TEXT NOT NULL CHECK(typeof(bindings)='text' AND length(bindings)=43) |
| +); |
| +CREATE TRIGGER {{ns}}_team_required_keep_update BEFORE UPDATE ON {{ns}}_team_required BEGIN SELECT RAISE(ABORT,'{{ns}} team: refused'); END; |
| +CREATE TRIGGER {{ns}}_team_required_keep_delete BEFORE DELETE ON {{ns}}_team_required BEGIN SELECT RAISE(ABORT,'{{ns}} team: refused'); END; |
| +CREATE TABLE {{ns}}_team_roster_evidence ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + payload BLOB NOT NULL CHECK(typeof(payload)='blob' AND length(payload)<=1048704) |
| +); |
diff --git a/teammode/state.go b/teammode/state.go| new file mode 100644 |
| index 0000000..dd80291 |
| --- /dev/null |
| +++ b/teammode/state.go |
| @@ -0,0 +1,192 @@ |
| +package teammode |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "encoding/base64" |
| + "errors" |
| + "regexp" |
| + "strings" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +// The marker and evidence tables, with the namespace a parameter. With |
| +// "docs" this is byte-for-byte Docs' teamstate/migrations/0001_team.sql, |
| +// and with "sheets" the first ten lines of Sheets' — so either app keeps its |
| +// applied migration (rastrillo checksums it) and its tables when it |
| +// re-points here (testdata, TestSchemaIsDocsAndSheetsMarker). |
| +// |
| +//go:embed schema/0001_team.sql.tmpl |
| +var schemaTemplate string |
| + |
| +var namespacePattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,30}$`) |
| + |
| +// State is team mode's durable state for one app: the activation marker and |
| +// the roster evidence, in tables named <namespace>_team_required and |
| +// <namespace>_team_roster_evidence. The zero State refuses everything. |
| +type State struct{ ns string } |
| + |
| +// NewState names an app's team state: lower-case letters and digits, |
| +// conventionally the app ("docs", "sheets", "slides"). |
| +func NewState(namespace string) (State, error) { |
| + if !namespacePattern.MatchString(namespace) { |
| + return State{}, ErrConfig |
| + } |
| + return State{ns: namespace}, nil |
| +} |
| + |
| +// MustState is NewState for a package-level constant. |
| +func MustState(namespace string) State { |
| + s, err := NewState(namespace) |
| + if err != nil { |
| + panic("teammode: invalid state namespace") |
| + } |
| + return s |
| +} |
| + |
| +func (s State) Namespace() string { return s.ns } |
| +func (s State) valid() bool { return namespacePattern.MatchString(s.ns) } |
| +func (s State) required() string { return s.ns + "_team_required" } |
| +func (s State) evidence() string { return s.ns + "_team_roster_evidence" } |
| + |
| +// SQL is the marker and evidence migration for this namespace. |
| +func (s State) SQL() string { return strings.ReplaceAll(schemaTemplate, "{{ns}}", s.ns) } |
| + |
| +// Schema is the migration set "<namespace>_team" holding SQL as |
| +// 0001_team. An app merges it after its own schema (and after any table its |
| +// own team migrations' triggers name) and applies it only in team mode; |
| +// once applied it stays, because the marker in it is what keeps the |
| +// database in team mode. An app whose existing team set already carries |
| +// these tables (Sheets) keeps its own set and uses State over it. |
| +func (s State) Schema() *migrate.Set { |
| + if !s.valid() { |
| + panic("teammode: invalid state namespace") |
| + } |
| + return migrate.MustFromFS(noFiles, s.ns+"_team").Add(migrate.Migration{ID: "0001_team", SQL: s.SQL()}) |
| +} |
| + |
| +// noFiles names a set with no files, so the one migration is SQL built here. |
| +var noFiles embed.FS |
| + |
| +func validFingerprint(v string) bool { |
| + b, err := base64.RawURLEncoding.DecodeString(v) |
| + return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == v |
| +} |
| + |
| +// Required reads the marker. It reads sqlite_master first, so it is safe on |
| +// a database that has never had the team schema applied — which is what |
| +// lets BootSchema run before any migration. activated is false for a |
| +// never-activated database; ErrUnavailable is a read failure; ErrConfig a |
| +// marker that is not a fingerprint. |
| +func (s State) Required(ctx context.Context, db *sql.DB) (fingerprint string, activated bool, err error) { |
| + if !s.valid() || db == nil { |
| + return "", false, ErrConfig |
| + } |
| + var count int |
| + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", s.required()).Scan(&count); err != nil { |
| + return "", false, ErrUnavailable |
| + } |
| + if count == 0 { |
| + return "", false, nil |
| + } |
| + var value string |
| + err = db.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&value) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", false, nil |
| + } |
| + if err != nil { |
| + return "", false, ErrUnavailable |
| + } |
| + if !validFingerprint(value) { |
| + return "", false, ErrConfig |
| + } |
| + return value, true, nil |
| +} |
| + |
| +// BootSchema is the schema an app applies, chosen before anything is |
| +// migrated, from the marker and the verified settings (nil: team mode off). |
| +// A database activated in team mode refuses to boot without team |
| +// configuration — an environment variable dropped in a redeploy must not |
| +// quietly hand standing back to an allowlist — and refuses a configuration |
| +// with a different binding. base is the app's schema; team is base plus its |
| +// team sets (State.Schema among them), applied only when settings is set. |
| +func (s State) BootSchema(ctx context.Context, db *sql.DB, settings *Settings, base, team *migrate.Set) (*migrate.Set, error) { |
| + fingerprint, activated, err := s.Required(ctx, db) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if activated && (settings == nil || fingerprint != settings.fingerprint) { |
| + return nil, ErrConfig |
| + } |
| + if settings == nil { |
| + return base, nil |
| + } |
| + return team, nil |
| +} |
| + |
| +// Activate records the verified fingerprint, and commits, before the app |
| +// serves a request or allocates an identity. It records a deployment |
| +// binding, never an owner or a roster. A database already bound to another |
| +// binding is refused, and the marker's triggers refuse any rewrite. |
| +func (s State) Activate(ctx context.Context, db *sql.DB, fingerprint string) error { |
| + if !s.valid() || db == nil || !validFingerprint(fingerprint) { |
| + return ErrConfig |
| + } |
| + tx, err := db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO "+s.required()+"(id,bindings) VALUES(1,?) ON CONFLICT(id) DO NOTHING", fingerprint); err != nil { |
| + return ErrUnavailable |
| + } |
| + var got string |
| + if err = tx.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&got); err != nil { |
| + return ErrUnavailable |
| + } |
| + if got != fingerprint { |
| + return ErrConfig |
| + } |
| + if tx.Commit() != nil { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
| + |
| +// Evidence is roster.Durable over the app's replicated SQLite file: one |
| +// bounded atomic replacement and one bounded load of the cache's sealed |
| +// envelope, never decoded here. |
| +func (s State) Evidence(db *sql.DB) roster.Durable { return evidence{s, db} } |
| + |
| +type evidence struct { |
| + s State |
| + db *sql.DB |
| +} |
| + |
| +func (e evidence) Load(ctx context.Context) ([]byte, error) { |
| + if !e.s.valid() || e.db == nil { |
| + return nil, ErrUnavailable |
| + } |
| + var b []byte |
| + err := e.db.QueryRowContext(ctx, "SELECT payload FROM "+e.s.evidence()+" WHERE id=1").Scan(&b) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, roster.ErrNoEvidence |
| + } |
| + if err != nil || len(b) > roster.EvidenceLimit+128 { |
| + return nil, ErrUnavailable |
| + } |
| + return b, nil |
| +} |
| + |
| +func (e evidence) Save(ctx context.Context, b []byte) error { |
| + if !e.s.valid() || e.db == nil || len(b) == 0 || len(b) > roster.EvidenceLimit+128 { |
| + return ErrUnavailable |
| + } |
| + if _, err := e.db.ExecContext(ctx, "INSERT INTO "+e.s.evidence()+"(id,payload) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload", b); err != nil { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
diff --git a/teammode/state_test.go b/teammode/state_test.go| new file mode 100644 |
| index 0000000..ff3e92b |
| --- /dev/null |
| +++ b/teammode/state_test.go |
| @@ -0,0 +1,162 @@ |
| +package teammode_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +// With "docs" the schema is Docs' applied migration byte for byte, and with |
| +// "sheets" the marker half of Sheets' (testdata: e58a22f and ca78cc1). A |
| +// re-pointed app keeps its ledger row: rastrillo refuses a migration whose |
| +// checksum changed. |
| +func TestSchemaIsDocsAndSheetsMarker(t *testing.T) { |
| + docs, err := os.ReadFile("testdata/docs_0001_team.sql") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := teammode.MustState("docs").SQL(); got != string(docs) { |
| + t.Fatalf("docs schema differs from Docs' migration:\n%s", got) |
| + } |
| + all := teammode.MustState("docs").Schema().All() |
| + if len(all) != 1 || all[0].ID != "docs_team/0001_team" || migrate.Checksum(all[0].SQL) != migrate.Checksum(string(docs)) { |
| + t.Fatalf("docs set %+v", all) |
| + } |
| + sheets, err := os.ReadFile("testdata/sheets_0001_team.sql") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.HasPrefix(sheets, []byte(teammode.MustState("sheets").SQL())) { |
| + t.Fatal("sheets marker tables differ from Sheets' migration") |
| + } |
| +} |
| + |
| +func TestStateNamespaceIsValidated(t *testing.T) { |
| + for _, ns := range []string{"", "Docs", "docs_x", "docs;drop", "1docs", strings.Repeat("a", 32)} { |
| + if _, err := teammode.NewState(ns); !errors.Is(err, teammode.ErrConfig) { |
| + t.Errorf("namespace %q accepted", ns) |
| + } |
| + } |
| + var zero teammode.State |
| + d := openDB(t, filepath.Join(t.TempDir(), "z.db")) |
| + if _, _, err := zero.Required(context.Background(), d.Writer()); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatal("zero State read a marker") |
| + } |
| + if err := zero.Activate(context.Background(), d.Writer(), teammode.Fingerprint(roster.Bindings{})); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatal("zero State activated") |
| + } |
| + if _, err := zero.Evidence(d.Writer()).Load(context.Background()); err == nil { |
| + t.Fatal("zero State loaded evidence") |
| + } |
| +} |
| + |
| +// The marker is read before any migration, and once activated it holds the |
| +// database in team mode, with the same binding. |
| +func TestBootSchemaLocksInTeamMode(t *testing.T) { |
| + ctx := context.Background() |
| + f := provisioned(t) |
| + w := f.db.Writer() |
| + // A database that has never seen the team schema: no table to read. |
| + if s, err := testState.BootSchema(ctx, w, nil, baseSchema, teamSchema); err != nil || s != baseSchema { |
| + t.Fatalf("fresh, team off: %v", err) |
| + } |
| + if s, err := testState.BootSchema(ctx, w, f.settings, baseSchema, teamSchema); err != nil || s != teamSchema { |
| + t.Fatalf("fresh, team on: %v", err) |
| + } |
| + if _, err := migrate.Apply(ctx, f.db, teamSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Applied but never activated (boot refused after migrating): still |
| + // boots either way. |
| + if s, err := testState.BootSchema(ctx, w, nil, baseSchema, teamSchema); err != nil || s != baseSchema { |
| + t.Fatalf("applied, never activated, team off: %v", err) |
| + } |
| + if err := testState.Activate(ctx, w, f.settings.Fingerprint()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := testState.BootSchema(ctx, w, nil, baseSchema, teamSchema); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database booted without team configuration: %v", err) |
| + } |
| + otherBindings := f.bindings |
| + otherBindings.Team = "TeamB" |
| + cfg, _ := teammodetest.Provision(t, otherBindings) |
| + differ, err := teammode.Verify(cfg, &teammode.Home{Issuer: otherBindings.Issuer, ConsumerID: otherBindings.Consumer}, testApp, testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := testState.BootSchema(ctx, w, differ, baseSchema, teamSchema); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database booted with another binding: %v", err) |
| + } |
| + if s, err := testState.BootSchema(ctx, w, f.settings, baseSchema, teamSchema); err != nil || s != teamSchema { |
| + t.Fatalf("activated, same binding: %v", err) |
| + } |
| + // Another app's namespace on the same file reads its own marker. |
| + if s, err := teammode.MustState("docs").BootSchema(ctx, w, nil, baseSchema, teamSchema); err != nil || s != baseSchema { |
| + t.Fatal("namespace leaked") |
| + } |
| +} |
| + |
| +func TestActivateRefusesRebindingAndTriggersHold(t *testing.T) { |
| + ctx := context.Background() |
| + f := provisioned(t) |
| + w := f.db.Writer() |
| + if _, err := migrate.Apply(ctx, f.db, teamSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := testState.Activate(ctx, w, "not-a-fingerprint"); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatal("malformed fingerprint activated") |
| + } |
| + fp := f.settings.Fingerprint() |
| + if err := testState.Activate(ctx, w, fp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := testState.Activate(ctx, w, fp); err != nil { |
| + t.Fatal("re-activation with the same binding refused") |
| + } |
| + other := teammode.Fingerprint(roster.Bindings{Team: "TeamB"}) |
| + if err := testState.Activate(ctx, w, other); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("rebinding accepted: %v", err) |
| + } |
| + if _, err := w.Exec("UPDATE sheets_team_required SET bindings=? WHERE id=1", other); err == nil { |
| + t.Fatal("marker update allowed") |
| + } |
| + if _, err := w.Exec("DELETE FROM sheets_team_required"); err == nil { |
| + t.Fatal("marker delete allowed") |
| + } |
| + if got, ok, err := testState.Required(ctx, w); err != nil || !ok || got != fp { |
| + t.Fatal("marker changed") |
| + } |
| +} |
| + |
| +func TestEvidenceRoundTrip(t *testing.T) { |
| + ctx := context.Background() |
| + f := provisioned(t) |
| + if _, err := migrate.Apply(ctx, f.db, teamSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + ev := testState.Evidence(f.db.Writer()) |
| + if _, err := ev.Load(ctx); !errors.Is(err, roster.ErrNoEvidence) { |
| + t.Fatalf("empty load %v", err) |
| + } |
| + if ev.Save(ctx, nil) == nil || ev.Save(ctx, make([]byte, roster.EvidenceLimit+129)) == nil { |
| + t.Fatal("unbounded save") |
| + } |
| + for _, v := range [][]byte{{1, 2, 3}, {4}} { |
| + if err := ev.Save(ctx, v); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := ev.Load(ctx) |
| + if err != nil || !bytes.Equal(got, v) { |
| + t.Fatal("evidence did not round-trip") |
| + } |
| + } |
| +} |
diff --git a/teammode/teammodetest/teammodetest.go b/teammode/teammodetest/teammodetest.go| new file mode 100644 |
| index 0000000..6862289 |
| --- /dev/null |
| +++ b/teammode/teammodetest/teammodetest.go |
| @@ -0,0 +1,165 @@ |
| +// Package teammodetest is team mode's test fixture, shared by every app's |
| +// team tests: a directory that signs roster pages in memory from a member |
| +// list a test can change or take down, a provisioning record signed for it, |
| +// and a roster clock a test can step past the lease. It is Docs' |
| +// testTeamRoster and Sheets' team_fixture_test.go, extracted. Never import |
| +// it outside tests. |
| +package teammodetest |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| + "github.com/go-json-experiment/json" |
| +) |
| + |
| +// Test deployment values. Any https origins would do; these are the ones |
| +// Docs' and Sheets' fixtures use. |
| +const ( |
| + Issuer = "https://id.example.com" |
| + DirectoryOrigin = "https://home.example.com" |
| + Team = "TeamA" |
| +) |
| + |
| +// Subject is a well-formed person ref: "pr_" and 26 copies of c, which must |
| +// be a lower-case letter or a digit 2-7. |
| +func Subject(c byte) string { return "pr_" + strings.Repeat(string(c), 26) } |
| + |
| +// Bindings for app, its Home consumer ID and its origin, on the test |
| +// issuer, directory and team. |
| +func Bindings(app, consumer, origin string) roster.Bindings { |
| + return roster.Bindings{Issuer: Issuer, Directory: DirectoryOrigin, Consumer: consumer, App: app, Team: Team, Audience: origin} |
| +} |
| + |
| +// Home is the teammode.Home the bindings name. |
| +func Home(b roster.Bindings) *teammode.Home { |
| + return &teammode.Home{Issuer: b.Issuer, ConsumerID: b.Consumer} |
| +} |
| + |
| +// Clock is a steppable roster.Clock. Tick, when set, advances it by that |
| +// much after every reading, so time passes between two observations in one |
| +// request (a lease checked twice). |
| +type Clock struct { |
| + mu sync.Mutex |
| + base time.Time |
| + elapsed time.Duration |
| + wall time.Duration |
| + tick time.Duration |
| +} |
| + |
| +func NewClock() *Clock { return &Clock{base: time.Unix(1800000000, 0)} } |
| + |
| +func (c *Clock) Now() (time.Time, time.Duration) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + w, m := c.base.Add(c.elapsed+c.wall), c.elapsed |
| + c.elapsed += c.tick |
| + return w, m |
| +} |
| + |
| +// Step advances wall and monotonic time together. |
| +func (c *Clock) Step(d time.Duration) { c.mu.Lock(); c.elapsed += d; c.mu.Unlock() } |
| + |
| +// WallStep moves wall time alone, as a clock adjustment would. |
| +func (c *Clock) WallStep(d time.Duration) { c.mu.Lock(); c.wall += d; c.mu.Unlock() } |
| + |
| +// SetTick makes every reading advance the clock by d. |
| +func (c *Clock) SetTick(d time.Duration) { c.mu.Lock(); c.tick = d; c.mu.Unlock() } |
| + |
| +// Directory is an in-memory Home directory serving one team's roster. It is |
| +// an http.RoundTripper for teammode.RuntimeConfig.Transport. |
| +type Directory struct { |
| + mu sync.Mutex |
| + key *family.Keypair |
| + bindings roster.Bindings |
| + generation string |
| + epoch int64 |
| + members map[string]string |
| + down bool |
| + fetches int |
| +} |
| + |
| +// Set changes subject's role ("owner" or "member"), or removes them with |
| +// "". Every change is a new epoch, as Home's triggers make it. |
| +func (d *Directory) Set(subject, role string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + if role == "" { |
| + delete(d.members, subject) |
| + } else { |
| + d.members[subject] = role |
| + } |
| + d.epoch++ |
| +} |
| + |
| +// SetDown makes every fetch fail (true) or succeed again (false). |
| +func (d *Directory) SetDown(down bool) { d.mu.Lock(); d.down = down; d.mu.Unlock() } |
| + |
| +// Fetches counts roster requests, failed ones included. |
| +func (d *Directory) Fetches() int { d.mu.Lock(); defer d.mu.Unlock(); return d.fetches } |
| + |
| +func (d *Directory) RoundTrip(r *http.Request) (*http.Response, error) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.fetches++ |
| + if d.down || r.URL.Scheme+"://"+r.URL.Host != d.bindings.Directory || r.URL.Path != "/roster" { |
| + return nil, errors.New("directory unavailable") |
| + } |
| + members := []roster.MemberEntry{} |
| + for s, role := range d.members { |
| + members = append(members, roster.MemberEntry{Subject: s, Role: role}) |
| + } |
| + sort.Slice(members, func(i, j int) bool { return members[i].Subject < members[j].Subject }) |
| + i, complete := 0, true |
| + q := r.URL.Query() |
| + page := roster.Page{Version: 1, Type: "page", Directory: d.bindings.Directory, Consumer: d.bindings.Consumer, Team: d.bindings.Team, Audience: d.bindings.Audience, |
| + Fetch: q.Get("fetch"), RequestCursorHash: roster.CursorHash(q.Get("cursor")), Generation: d.generation, Epoch: d.epoch, Index: &i, Members: &members, Complete: &complete} |
| + raw, err := roster.SignPage(d.key, "roster1", page) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(bytes.NewReader(raw))}, nil |
| +} |
| + |
| +// Provision signs a provisioning record for b with a fresh operator key and |
| +// returns the teammode.Config that carries it, plus the directory that |
| +// answers for it (empty roster, epoch 1). |
| +func Provision(t testing.TB, b roster.Bindings) (*teammode.Config, *Directory) { |
| + t.Helper() |
| + op, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := roster.Provisioning{Version: 1, Operation: "provision1", Sequence: 1, Bindings: b, Generation: Fixed(1), MinEpoch: 1, |
| + Keys: []roster.Key{{ID: "roster1", Public: base64.RawURLEncoding.EncodeToString(key.SignPub())}}} |
| + raw, err := roster.SignProvisioning(op, "operator1", p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + keys, err := json.Marshal([]roster.Key{{ID: "operator1", Public: base64.RawURLEncoding.EncodeToString(op.SignPub())}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := &Directory{key: key, bindings: b, generation: p.Generation, epoch: 1, members: map[string]string{}} |
| + cfg := &teammode.Config{TeamID: b.Team, DirectoryOrigin: b.Directory, |
| + ProvisioningBase64: base64.StdEncoding.EncodeToString(raw), OperatorKeysBase64: base64.StdEncoding.EncodeToString(keys), RosterToken: Fixed(7)} |
| + return cfg, dir |
| +} |
| + |
| +// Fixed is 32 bytes of n, base64url: a well-formed token or generation. |
| +func Fixed(n byte) string { return base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{n}, 32)) } |
diff --git a/teammode/testdata/docs_0001_team.sql b/teammode/testdata/docs_0001_team.sql| new file mode 100644 |
| index 0000000..637b599 |
| --- /dev/null |
| +++ b/teammode/testdata/docs_0001_team.sql |
| @@ -0,0 +1,10 @@ |
| +CREATE TABLE docs_team_required ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + bindings TEXT NOT NULL CHECK(typeof(bindings)='text' AND length(bindings)=43) |
| +); |
| +CREATE TRIGGER docs_team_required_keep_update BEFORE UPDATE ON docs_team_required BEGIN SELECT RAISE(ABORT,'docs team: refused'); END; |
| +CREATE TRIGGER docs_team_required_keep_delete BEFORE DELETE ON docs_team_required BEGIN SELECT RAISE(ABORT,'docs team: refused'); END; |
| +CREATE TABLE docs_team_roster_evidence ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + payload BLOB NOT NULL CHECK(typeof(payload)='blob' AND length(payload)<=1048704) |
| +); |
diff --git a/teammode/testdata/sheets_0001_team.sql b/teammode/testdata/sheets_0001_team.sql| new file mode 100644 |
| index 0000000..1870757 |
| --- /dev/null |
| +++ b/teammode/testdata/sheets_0001_team.sql |
| @@ -0,0 +1,23 @@ |
| +CREATE TABLE sheets_team_required ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + bindings TEXT NOT NULL CHECK(typeof(bindings)='text' AND length(bindings)=43) |
| +); |
| +CREATE TRIGGER sheets_team_required_keep_update BEFORE UPDATE ON sheets_team_required BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_required_keep_delete BEFORE DELETE ON sheets_team_required BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TABLE sheets_team_roster_evidence ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + payload BLOB NOT NULL CHECK(typeof(payload)='blob' AND length(payload)<=1048704) |
| +); |
| +CREATE TABLE sheets_team_home_members ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + member_id INTEGER NOT NULL UNIQUE REFERENCES members(id), |
| + PRIMARY KEY(issuer,subject) |
| +); |
| +CREATE TRIGGER sheets_team_home_member_addressless BEFORE INSERT ON sheets_team_home_members WHEN NOT EXISTS(SELECT 1 FROM members WHERE id=NEW.member_id AND address IS NULL) BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_home_member_unlinked BEFORE INSERT ON sheets_team_home_members WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_home_members_keep_update BEFORE UPDATE ON sheets_team_home_members BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_home_members_keep_delete BEFORE DELETE ON sheets_team_home_members BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_link_not_home_only BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM sheets_team_home_members WHERE (issuer=NEW.issuer AND subject=NEW.subject) OR member_id=NEW.person_id) BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_home_member_keeps_no_address BEFORE UPDATE OF address ON members WHEN EXISTS(SELECT 1 FROM sheets_team_home_members WHERE member_id=OLD.id) BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |
| +CREATE TRIGGER sheets_team_home_member_keep_row BEFORE DELETE ON members WHEN EXISTS(SELECT 1 FROM sheets_team_home_members WHERE member_id=OLD.id) BEGIN SELECT RAISE(ABORT,'sheets team: refused'); END; |