Sheets: roster team mode (Home team-members.md Part B). With SHEETS_TEAM_ID, _DIRECTORY_ORIGIN, _PROVISIONING_BASE64, _OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN set (all or none, beside SHEETS_HOME_*), the Home roster decides standing on every request, as Docs does: Member (owner or member, the roster's role), NotMember (a guest: shares only), Unknown (a retryable 503). members.team_role is never read in team mode, fixing the never-demoted owner bug: a removed person loses access within the 60 s lease, existing sessions and live streams included. A roster Member with no account here signs in with Home alone as an addressless member; the provisioning record is pinned to configured bindings, and a marker refuses boot without the same binding. GET /api/team is Docs' readiness probe ({"team_mode":false} with team mode off, the only change to a non-team instance). SHEETS_OWNERS becomes optional in team mode. The creator's own grant counts only while Member; per Paul's ruling (2026-10-28), a roster owner holds owner on any sheet with no live owner grant. Reviewed by Claude Fable 5.1 (claude-fable-5-1) on oficina/sheets #52, APPROVED at b0264ff (O3 test added at e6490f4). Verified canary of e6490f4 on team-mode-sheets.bds.oncarlos.com (own env bundle, fresh keys, Home and team mode off; production untouched at af8deeb): /api/version served e6490f4, /api/team {"team_mode":false} no-store, local sign-in form and sent page, cross-origin POST 403, signed-out list/table/stream/cells refused; editing needed a mailbox the canary lacked and team mode ON awaits Home's production roster serve; canary removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Squashed from team-mode into main.
45 files changed,
+2,583
−33
AGENTS.md+11 −0cmd/sheets/main.go+20 −1docs/superpowers/specs/2026-08-30-sheets-design.md+20 −0go.mod+1 −0go.sum+2 −0internal/sheets/app.go+16 −5internal/sheets/auth.go+6 −1internal/sheets/begin_test.go+8 −1internal/sheets/dashboard.go+21 −1internal/sheets/errors.go+8 −0internal/sheets/errors_test.go+1 −0internal/sheets/grants.go+21 −3internal/sheets/grants_orphan_test.go+2 −2internal/sheets/handlers_history.go+7 −1internal/sheets/handlers_import.go+3 −0internal/sheets/handlers_share.go+5 −4internal/sheets/handlers_sheets.go+10 −0internal/sheets/handlers_stream.go+33 −2internal/sheets/home.go+15 −2internal/sheets/home_routes.go+1 −1internal/sheets/home_test.go+6 −0internal/sheets/lastowner.go+8 −0internal/sheets/members.go+17 −1internal/sheets/models.go+5 −0internal/sheets/native.go+4 −0internal/sheets/page.go+7 −1internal/sheets/session_guard.go+10 −1internal/sheets/sharenotice.go+8 −4internal/sheets/team_access.go+246 −0internal/sheets/team_access_test.go+249 −0internal/sheets/team_answers.go+136 −0internal/sheets/team_config.go+220 −0internal/sheets/team_config_test.go+139 −0internal/sheets/team_fixture_test.go+193 −0internal/sheets/team_home.go+174 −0internal/sheets/team_owner.go+48 −0internal/sheets/team_probe.go+77 −0internal/sheets/team_probe_test.go+74 −0internal/sheets/team_review_test.go+248 −0internal/sheets/team_stream_test.go+129 −0internal/sheets/teamstate/migrations/0001_team.sql+23 −0internal/sheets/teamstate/store.go+220 −0internal/sheets/teamstate/store_test.go+123 −0internal/sheets/templates/share.html+1 −1internal/sheets/visible_sheets.go+7 −1
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index 107a769..b1cc58f 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -141,6 +141,17 @@ relying on remembering one, make it a test instead. |
| Recheck existing admission and sheet grants on every Home request. Member IDs |
| are AUTOINCREMENT and must never be reassigned; any future deletion path must |
| remove the member's `home_identity_links` rows in the same transaction. |
| +- **Team mode is the one exception to "never create members from Home |
| + subjects"** (Home `implementation/team-members.md` Part B). With |
| + `SHEETS_TEAM_*` set, a Home subject the roster says is a Member *at that |
| + moment* gets an addressless member (`teamstate.EnsureHomeMember`, from |
| + `team_home.go` only). That row is identity, never standing: standing is the |
| + roster's answer on every request (`team_access.go`), and **`members.team_role` |
| + is never read in team mode** — reading it is how a removed owner kept access. |
| + Without `SHEETS_TEAM_*`, every rule above stands unchanged. |
| +- **A team-mode database stays in team mode.** `sheets_team_required` refuses |
| + boot without team configuration or with a different binding. Do not |
| + "fix" a refused boot by deleting it; the triggers refuse that anyway. |
| - Migrations are additive-only. New code over an old DB is always safe. |
| Never delete data to update. |
| - **Cell values are IEEE doubles end to end.** Currency is a number format, |
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go| index 7f5488d..b69ec26 100644 |
| --- a/cmd/sheets/main.go |
| +++ b/cmd/sheets/main.go |
| @@ -56,7 +56,19 @@ func main() { |
| // its schema (a structural diff migrate.Apply doesn't recognise as |
| // its own pending migrations) refuses rather than guessing, which |
| // is why this is a hard exit, same as a failed db.Open above. |
| - if _, err := migrate.Apply(context.Background(), d, sheets.BootSchema); err != nil { |
| + // |
| + // Team mode's marker is read first, before anything migrates: a |
| + // database once activated in team mode refuses to boot without |
| + // SHEETS_TEAM_*, so a dropped variable cannot hand standing back to |
| + // SHEETS_OWNERS (internal/sheets/team_config.go). Without team |
| + // configuration on a database never activated, the schema is |
| + // BootSchema exactly as before. |
| + schema, err := sheets.BootSchemaFor(context.Background(), d.Writer(), sheets.TeamConfigFromEnv() != nil) |
| + if err != nil { |
| + logger.Error("team mode", "err", err) |
| + os.Exit(1) |
| + } |
| + if _, err := migrate.Apply(context.Background(), d, schema); err != nil { |
| logger.Error("migrate", "err", err) |
| os.Exit(1) |
| } |
| @@ -105,6 +117,13 @@ func main() { |
| logger.Error("home configuration unavailable") |
| os.Exit(1) |
| } |
| + // After Home, before serving: verifies the provisioning record, |
| + // commits the team marker and starts the roster cache. A nil config |
| + // is a no-op; anything else that fails refuses boot. |
| + if err := app.ConfigureTeam(authEnv.Team); err != nil { |
| + logger.Error("team mode unavailable") |
| + os.Exit(1) |
| + } |
| if err := app.ConfigureNative(); err != nil { |
| logger.Error("native configuration unavailable") |
diff --git a/docs/superpowers/specs/2026-08-30-sheets-design.md b/docs/superpowers/specs/2026-08-30-sheets-design.md| index 709e42c..1220b06 100644 |
| --- a/docs/superpowers/specs/2026-08-30-sheets-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-sheets-design.md |
| @@ -455,6 +455,25 @@ them and learn nothing about the team beyond §9.5's disclosure. |
| **Team standing comes from the roster the home holds** (suite §5) in suite |
| shape, and from `$SHEETS_OWNERS` and the local member rows in lone shape. |
| +Suite shape is **team mode** (Home `implementation/team-members.md` Part B, |
| +ported from Docs, 2026-10-28): `SHEETS_TEAM_ID`, `_DIRECTORY_ORIGIN`, |
| +`_PROVISIONING_BASE64`, `_OPERATOR_KEYS_BASE64` and `_ROSTER_TOKEN`, all or |
| +none, beside `SHEETS_HOME_*`. Every request asks the roster: Member (owner or |
| +member, the roster's role), NotMember (a guest: shares only), or Unknown (a |
| +retryable 503 for anything a share does not reach). `$SHEETS_OWNERS` becomes |
| +optional and only admits local sign-in. A sheet's creator holds it through |
| +a grant they gave themselves; in team mode that grant is the team rung's and |
| +counts only while the roster says Member, as Docs' `owner_id` does — grants |
| +somebody else gave are shares and keep working. A database once activated in |
| +team mode refuses to boot without the same team binding. |
| +**Team owners can share orphaned sheets** (RULED by Paul, 2026-10-28, #52): |
| +a roster *owner* holds `owner` on any sheet with no live owner grant — live |
| +meaning given by somebody else, or held by a current roster Member (or one |
| +whose standing cannot be read). Nothing is written; it stops applying once |
| +the sheet has a live owner again (`team_owner.go`). A Home-only member has no |
| +address, so nothing can be shared *to* one: once removed, nothing can be |
| +re-shared to them either. Home-only members are shown as "Oficina account" |
| +and the last four characters of their person ref, as Home's Team page does. |
| **Per-sheet roles stay here.** The doctrine deliberately does not unify |
| them: a shared role vocabulary designed from three specs at once would fit |
| none of them, and it may move to the contract module when two apps have |
| @@ -1118,6 +1137,7 @@ it is a fallback rather than a scramble. |
| | Moving the provisioning queue out of the home (§9.4) | The home spec rules on it | |
| | **Destructive sort — physically reordering rows** | calc's dependency graph is keyed on POSITION (`store/handle.go`'s `cellKey` builds `CellKey{rowPos+1, colPos+1}`), so moving a row changes what every existing formula points at, silently. Plan 1's review flagged this as "valid only until rows move". Trigger: **calc's key space rebuilt on stable ids**, which is a subsystem and not a feature. Sort and filter ship non-destructively meanwhile — they reorder what is displayed and never what is stored, which is correct rather than a stopgap. | |
| | **Importing a workbook's second and later worksheets** | `xlsx.Import` reads `GetSheetList()[0]` and stops, so a three-worksheet file becomes a one-tab sheet. Stated in the import form's own hint rather than discovered afterwards (§11), because a workbook that arrives looking whole is the quiet kind of wrong PRODUCT.md's first principle forbids. Trigger: **a second tab is reachable in the UI**. Sheets already has a `Tab` table and `SheetSummary.TabID` already means "the first tab", but nothing creates, names, lists or switches tabs — so importing into tabs today would write rows no screen can open, which is worse than importing one worksheet honestly. | |
| +| ~~Sharing a sheet whose sole owner left the team~~ | **Ruled and built 2026-10-28** (Paul, oficina/sheets #52). Team mode made it routine: a removed creator's own grant stops counting, so the team could edit the sheet and nobody could share it. A roster owner now holds `owner` on any sheet with no live owner grant (§8.2, `team_owner.go`). Still not built: an explicit, auditable "Take ownership" verb that writes a grant — trigger: **a team asks who rescued a sheet**, or the rule needs to outlive a roster owner's own removal. | |
| | Pivot tables | Asked for twice | |
| | Rich presence beyond who's-here | Teams above ~5 concurrent editors | |
| | Offline editing | — | |
diff --git a/go.mod b/go.mod| index 6fd99ef..3a08496 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -7,6 +7,7 @@ require ( |
| amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
| + amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| github.com/carlosframework/rastrillo v0.23.0 |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
diff --git a/go.sum b/go.sum| index 6da4cdf..bbf5bc7 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -6,6 +6,8 @@ amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42WwR7VSn+V0eLNk20mfiY8dQmzdw13Sbo= |
| +amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
diff --git a/internal/sheets/app.go b/internal/sheets/app.go| index 533f57f..a7a907d 100644 |
| --- a/internal/sheets/app.go |
| +++ b/internal/sheets/app.go |
| @@ -59,11 +59,17 @@ type App struct { |
| home *connect.Bridge |
| homeRoutes *connect.Routes |
| homeSessions *sessions.Sessions |
| - db *gorm.DB |
| - auth *auth.Auth |
| - sealer *seal.Sealer |
| - origin string |
| - admit func(string) bool |
| + // homeCreds and homeRender are ConfigureHome's, kept for team mode. |
| + homeCreds *connect.DecodedCredentials |
| + homeRender func(http.ResponseWriter, *http.Request, string, string, int) |
| + // team is the roster runtime, nil unless SHEETS_TEAM_* configured |
| + // team mode (team_config.go). Every team-mode branch keys on it. |
| + team *teamRuntime |
| + db *gorm.DB |
| + auth *auth.Auth |
| + sealer *seal.Sealer |
| + origin string |
| + admit func(string) bool |
| // directory is the hub directory (HOME_DIRECTORY_ORIGIN), set only |
| // with Home configured: the app switcher's link. Empty, no switcher. |
| directory string |
| @@ -204,6 +210,11 @@ func (a *App) Router() http.Handler { |
| // entry (spec §8.3). The token is the entire authorization. |
| r.Get("/l/{token}", a.handleLinkView) |
| + // Alta's team-mode readiness probe (team_probe.go): unauthenticated, |
| + // no account data, {"team_mode":false} on an instance not in team |
| + // mode. |
| + r.Get(teamProbePath, a.handleTeamProbe) |
| + |
| r.Group(func(r chi.Router) { |
| r.Use(a.requireSession) |
| // After the guard, so a 500 shows the viewer's own chrome. |
diff --git a/internal/sheets/auth.go b/internal/sheets/auth.go| index 263893e..5c4d0df 100644 |
| --- a/internal/sheets/auth.go |
| +++ b/internal/sheets/auth.go |
| @@ -19,6 +19,10 @@ import ( |
| // validated. Building it is the only place these variable names appear. |
| type AuthEnv struct { |
| Home *connect.Credentials |
| + // Team is team mode's configuration (team_config.go), nil unless a |
| + // SHEETS_TEAM_* variable is set. With it the roster is the team and |
| + // SHEETS_OWNERS is optional: if set, it only admits local sign-in. |
| + Team *TeamConfig |
| // Origin is the instance's external origin, scheme included. It is |
| // the base of every emailed link and the CSRF origin check, which |
| // makes a WRONG value the dangerous case rather than a missing one: |
| @@ -80,6 +84,7 @@ func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) { |
| Origin: strings.TrimSpace(os.Getenv("SHEETS_ORIGIN")), |
| InstanceKey: strings.TrimSpace(os.Getenv("SHEETS_INSTANCE_KEY")), |
| Owners: splitOwners(os.Getenv("SHEETS_OWNERS")), |
| + Team: TeamConfigFromEnv(), |
| } |
| var missing []string |
| @@ -89,7 +94,7 @@ func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) { |
| if env.InstanceKey == "" { |
| missing = append(missing, "SHEETS_INSTANCE_KEY") |
| } |
| - if len(env.Owners) == 0 { |
| + if len(env.Owners) == 0 && env.Team == nil { |
| missing = append(missing, "SHEETS_OWNERS") |
| } |
| if len(missing) > 0 { |
diff --git a/internal/sheets/begin_test.go b/internal/sheets/begin_test.go| index 905bfb5..f482512 100644 |
| --- a/internal/sheets/begin_test.go |
| +++ b/internal/sheets/begin_test.go |
| @@ -96,13 +96,20 @@ func appWithOrigin(t *testing.T, origin string) (*App, *recorder) { |
| // appWithOwners is appWithOrigin with the SHEETS_OWNERS list spelled out. |
| func appWithOwners(t *testing.T, origin string, owners ...string) (*App, *recorder) { |
| + t.Helper() |
| + return appWithSchema(t, origin, BootSchema, owners...) |
| +} |
| + |
| +// appWithSchema is appWithOwners over a chosen boot schema: team mode's |
| +// fixture applies TeamBootSchema, as main does when SHEETS_TEAM_* is set. |
| +func appWithSchema(t *testing.T, origin string, schema *migrate.Set, owners ...string) (*App, *recorder) { |
| t.Helper() |
| d, err := rdb.Open(filepath.Join(t.TempDir(), "test.db"), quietLogger()) |
| if err != nil { |
| t.Fatalf("open db: %v", err) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, err := migrate.Apply(context.Background(), d, BootSchema); err != nil { |
| + if _, err := migrate.Apply(context.Background(), d, schema); err != nil { |
| t.Fatalf("migrate: %v", err) |
| } |
| rec := &recorder{} |
diff --git a/internal/sheets/dashboard.go b/internal/sheets/dashboard.go| index 6ea76e4..469239d 100644 |
| --- a/internal/sheets/dashboard.go |
| +++ b/internal/sheets/dashboard.go |
| @@ -10,6 +10,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/dashboard" |
| + "amadan.net/oficina/home/roster" |
| ) |
| func (a *App) configureDashboard(c *connect.DecodedCredentials) error { |
| @@ -22,6 +23,15 @@ func (a *App) configureDashboard(c *connect.DecodedCredentials) error { |
| return e |
| } |
| h, e := dashboard.NewProvider(dashboard.ProviderConfig{DB: db, Origin: a.origin, Issuer: c.Issuer, Directory: c.Directory, Keys: c.Keys, Team: team, Kind: "documents", Resolve: func(ctx context.Context, subject string) (int64, error) { |
| + if a.team != nil { |
| + // Team mode: a Home-only member too. Identity only; Read asks |
| + // the roster for standing. |
| + id, e := a.homeMemberID(ctx, subject) |
| + if errors.Is(e, errTeamUnavailable) { |
| + return 0, dashboard.ErrUnavailable |
| + } |
| + return id, e |
| + } |
| p, e := a.home.Resolve(ctx, subject) |
| if errors.Is(e, linkstore.ErrStorage) { |
| return 0, dashboard.ErrUnavailable |
| @@ -34,15 +44,25 @@ func (a *App) configureDashboard(c *connect.DecodedCredentials) error { |
| a.dashboard = h |
| return nil |
| } |
| -func (a *App) dashboardDocuments(ctx context.Context, id int64, _ string, _ time.Time) (dashboard.Response, error) { |
| +func (a *App) dashboardDocuments(ctx context.Context, id int64, subject string, _ time.Time) (dashboard.Response, error) { |
| var viewer Member |
| if e := a.db.WithContext(ctx).First(&viewer, id).Error; e != nil { |
| return dashboard.Response{}, e |
| } |
| + if a.team != nil { |
| + // The roster's standing for the subject that asked, never the |
| + // stored team_role (team_access.go). |
| + viewer = (&teamAccess{member: viewer, subject: subject, decision: a.team.check(ctx, subject)}).actor() |
| + } |
| rows, e := a.visibleSheetsLimited(ctx, viewer, dashboard.MaxItems+1) |
| if e != nil { |
| return dashboard.Response{}, e |
| } |
| + // Unknown standing is unavailable, not a short list. Asked after |
| + // listing, as the sheet list does, because a lease can lapse during it. |
| + if a.team != nil && viewer.team.state() == roster.Unknown { |
| + return dashboard.Response{}, dashboard.ErrUnavailable |
| + } |
| out := dashboard.Response{Truncated: len(rows) > dashboard.MaxItems} |
| if out.Truncated { |
| rows = rows[:dashboard.MaxItems] |
diff --git a/internal/sheets/errors.go b/internal/sheets/errors.go| index a900dd3..b53c19e 100644 |
| --- a/internal/sheets/errors.go |
| +++ b/internal/sheets/errors.go |
| @@ -80,7 +80,15 @@ func wantsHTML(r *http.Request) bool { |
| // notFound answers 404 with nothing that could name a sheet: the "sheet |
| // not available" page for a browser, and the plain "Not found." it has |
| // always been for the grid's fetches and the native apps. |
| +// |
| +// In team mode with standing Unknown it is a retryable 503 instead, for |
| +// a sheet that exists and one that does not alike: whether it is theirs |
| +// could not be decided, and a 404 would say it was not (team_access.go). |
| func (a *App) notFound(w http.ResponseWriter, r *http.Request) { |
| + if a.teamUnknown(r) { |
| + a.unavailable(w, r) |
| + return |
| + } |
| a.answer(w, r, http.StatusNotFound, kindSheet, "Not found.") |
| } |
diff --git a/internal/sheets/errors_test.go b/internal/sheets/errors_test.go| index 7574922..24dcd8c 100644 |
| --- a/internal/sheets/errors_test.go |
| +++ b/internal/sheets/errors_test.go |
| @@ -172,6 +172,7 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) { |
| "home.go:App.homeLocalComplete": {2, "Home link completion refusals (R3: moves with home/connect)"}, |
| "home.go:App.rejectDisabledHome": {1, "shared session guard for pages and fetches (R3)"}, |
| "jobpages.go:App.renderJobFragment": {2, "the job page's polled fragment, not a page"}, |
| + "team_access.go:App.teamRequire": {2, "team mode's session guard, homeRequire's twin: a page GET redirects to /signin"}, |
| } |
| got := httpErrorSites(t) |
| var problems []string |
diff --git a/internal/sheets/grants.go b/internal/sheets/grants.go| index abbb4e1..63c0ab8 100644 |
| --- a/internal/sheets/grants.go |
| +++ b/internal/sheets/grants.go |
| @@ -2,6 +2,7 @@ package sheets |
| import ( |
| "amadan.net/oficina/sheets/internal/sheets/store" |
| + "context" |
| "errors" |
| "strings" |
| @@ -33,6 +34,18 @@ var errNoAccess = errors.New("sheets: no grant") |
| // A guest gets NOTHING from step 2. That is the whole distinction in |
| // §8.2: a guest sees exactly the sheets granted to them. |
| func (a *App) roleFor(sheetID uint64, m Member) (SheetRole, bool) { |
| + role, ok := a.grantOrTeamRole(sheetID, m) |
| + if ok && role != SheetOwner && a.orphanedForRosterOwner(sheetID, m) { |
| + // Team mode: a roster owner holds every sheet nobody live owns |
| + // (team_owner.go; Paul, 2026-10-28). |
| + return SheetOwner, true |
| + } |
| + return role, ok |
| +} |
| + |
| +// grantOrTeamRole is roleFor's two sources, before team mode's |
| +// roster-owner rule. |
| +func (a *App) grantOrTeamRole(sheetID uint64, m Member) (SheetRole, bool) { |
| if a.db == nil { |
| return "", false |
| } |
| @@ -48,6 +61,11 @@ func (a *App) roleFor(sheetID uint64, m Member) (SheetRole, bool) { |
| } |
| var g Grant |
| err := a.db.Where("sheet_id = ? AND member_id = ?", sheetID, m.ID).First(&g).Error |
| + if err == nil && a.ownGrantIgnored(g, m) { |
| + // Team mode, and the creator's own grant on a sheet whose creator |
| + // the roster no longer says is on the team (team_access.go). |
| + return "", false |
| + } |
| if err == nil { |
| if role := SheetRole(g.Role); role.Valid() { |
| return role, true |
| @@ -61,7 +79,7 @@ func (a *App) roleFor(sheetID uint64, m Member) (SheetRole, bool) { |
| return "", false |
| } |
| - switch TeamRole(m.TeamRole) { |
| + switch a.teamRole(m) { |
| case TeamOwner, TeamMember: |
| // Team standing reaches every sheet, as an editor. Not as |
| // owner: sheet ownership is about who may change sharing, and |
| @@ -111,7 +129,7 @@ type sharedWith struct { |
| Role SheetRole |
| } |
| -func (a *App) grantsOn(sheetID uint64) ([]sharedWith, error) { |
| +func (a *App) grantsOn(ctx context.Context, sheetID uint64) ([]sharedWith, error) { |
| if a.db == nil { |
| return nil, errNoDB |
| } |
| @@ -125,7 +143,7 @@ func (a *App) grantsOn(sheetID uint64) ([]sharedWith, error) { |
| if err := a.db.Where("id = ?", g.MemberID).First(&m).Error; err != nil { |
| continue // a grant whose member vanished names nobody |
| } |
| - out = append(out, sharedWith{Member: m, Role: SheetRole(g.Role)}) |
| + out = append(out, sharedWith{Member: a.withStanding(ctx, m), Role: SheetRole(g.Role)}) |
| } |
| return out, nil |
| } |
diff --git a/internal/sheets/grants_orphan_test.go b/internal/sheets/grants_orphan_test.go| index 747ea6a..9f309c4 100644 |
| --- a/internal/sheets/grants_orphan_test.go |
| +++ b/internal/sheets/grants_orphan_test.go |
| @@ -40,7 +40,7 @@ func TestAnOwnerCannotDemoteThemselvesToNobody(t *testing.T) { |
| } |
| // Whatever the screen says, the sheet must still have an owner. |
| - people, err := app.grantsOn(s.ID) |
| + people, err := app.grantsOn(t.Context(), s.ID) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -81,7 +81,7 @@ func TestOneOfTwoOwnersCanBeDemoted(t *testing.T) { |
| t.Fatalf("share POST = %d, want 303", rec.Code) |
| } |
| - people, err := app.grantsOn(s.ID) |
| + people, err := app.grantsOn(t.Context(), s.ID) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/sheets/handlers_history.go b/internal/sheets/handlers_history.go| index 24d4760..7ba28df 100644 |
| --- a/internal/sheets/handlers_history.go |
| +++ b/internal/sheets/handlers_history.go |
| @@ -1,6 +1,7 @@ |
| package sheets |
| import ( |
| + "context" |
| "net/http" |
| "strconv" |
| "time" |
| @@ -115,8 +116,13 @@ func (a *App) memberNames() map[uint64]string { |
| if err := a.db.Find(&members).Error; err != nil { |
| return out |
| } |
| + refs := a.homeOnlyRefs(context.Background()) |
| for _, m := range members { |
| - out[m.ID] = m.Address |
| + if subject, ok := refs[m.ID]; ok && m.Address == "" { |
| + out[m.ID] = homeOnlyLabel(subject) |
| + continue |
| + } |
| + out[m.ID] = m.Label() |
| } |
| return out |
| } |
diff --git a/internal/sheets/handlers_import.go b/internal/sheets/handlers_import.go| index a8e973e..e7954db 100644 |
| --- a/internal/sheets/handlers_import.go |
| +++ b/internal/sheets/handlers_import.go |
| @@ -86,6 +86,9 @@ func (a *App) handleSheetImport(w http.ResponseWriter, r *http.Request) { |
| a.forbidden(w, r) |
| return |
| } |
| + if !a.teamMemberOnly(w, r) { |
| + return |
| + } |
| // jobs keys ownership on the session Subject, and jobs.Handlers |
| // reads that same value back out of sessions.Current to decide who |
| // may see a job. Starting one under any other identifier makes it |
diff --git a/internal/sheets/handlers_share.go b/internal/sheets/handlers_share.go| index f59a0fb..3bcf432 100644 |
| --- a/internal/sheets/handlers_share.go |
| +++ b/internal/sheets/handlers_share.go |
| @@ -1,6 +1,7 @@ |
| package sheets |
| import ( |
| + "context" |
| "errors" |
| "net/http" |
| "strconv" |
| @@ -67,7 +68,7 @@ func (a *App) handleShare(w http.ResponseWriter, r *http.Request) { |
| // handler that just minted it, in the same process, on the same |
| // goroutine. Nothing that crossed a URL can reach this parameter. |
| func (a *App) renderShare(w http.ResponseWriter, r *http.Request, s SheetSummary, _ Member, notice, newLink string) { |
| - people, err := a.grantsOn(s.ID) |
| + people, err := a.grantsOn(r.Context(), s.ID) |
| if err != nil { |
| a.fail(w, r, err) |
| return |
| @@ -193,7 +194,7 @@ func (a *App) handleShareRevoke(w http.ResponseWriter, r *http.Request) { |
| a.fail(w, r, err) |
| return |
| } |
| - if a.stillReaches(s.ID, memberID) { |
| + if a.stillReaches(r.Context(), s.ID, memberID) { |
| a.shareRedirectAbout(w, r, s, noticeRevokedTeam, memberID) |
| return |
| } |
| @@ -202,8 +203,8 @@ func (a *App) handleShareRevoke(w http.ResponseWriter, r *http.Request) { |
| // wouldOrphan reports whether removing this grant would leave the sheet |
| // with no owner at all. |
| -func (a *App) wouldOrphan(sheetID, memberID uint64) bool { |
| - people, err := a.grantsOn(sheetID) |
| +func (a *App) wouldOrphan(ctx context.Context, sheetID, memberID uint64) bool { |
| + people, err := a.grantsOn(ctx, sheetID) |
| if err != nil { |
| return true // cannot tell means do not risk it |
| } |
diff --git a/internal/sheets/handlers_sheets.go b/internal/sheets/handlers_sheets.go| index 75f98c1..af8ce7b 100644 |
| --- a/internal/sheets/handlers_sheets.go |
| +++ b/internal/sheets/handlers_sheets.go |
| @@ -102,6 +102,13 @@ func (a *App) renderSheetList(w http.ResponseWriter, r *http.Request, status int |
| a.fail(w, r, err) |
| return |
| } |
| + // Team mode with standing Unknown: the list above could only have |
| + // been the shares, and a short list would read as an answer. Asked |
| + // after listing because a lease can lapse during it. |
| + if a.teamUnknown(r) { |
| + a.unavailable(w, r) |
| + return |
| + } |
| if wantsNative(r) { |
| // Reuse the web preview's shape-only query; never decrypt cells or |
| // return HTML to a native renderer. |
| @@ -147,6 +154,9 @@ func (a *App) handleSheetCreate(w http.ResponseWriter, r *http.Request) { |
| a.forbidden(w, r) |
| return |
| } |
| + if !a.teamMemberOnly(w, r) { |
| + return |
| + } |
| title := r.FormValue("title") |
| if title == "" { |
| title = "Untitled sheet" |
diff --git a/internal/sheets/handlers_stream.go b/internal/sheets/handlers_stream.go| index e982db9..839cfd0 100644 |
| --- a/internal/sheets/handlers_stream.go |
| +++ b/internal/sheets/handlers_stream.go |
| @@ -62,7 +62,8 @@ func (a *App) handleStream(w http.ResponseWriter, r *http.Request) { |
| // needs the same grant a read of the grid does. Without this check |
| // the fan-out would be the one route that ignored sharing entirely |
| // — and the quietest possible leak, since nothing renders it. |
| - if !a.streamAuthorized(r, sheetID) { |
| + allowed, renew := a.streamAccess(r, sheetID) |
| + if !allowed { |
| a.notFound(w, r) |
| return |
| } |
| @@ -95,6 +96,26 @@ func (a *App) handleStream(w http.ResponseWriter, r *http.Request) { |
| defer idle.Stop() |
| life := time.NewTimer(maxStreamLife) |
| defer life.Stop() |
| + // Team mode: access that rests on roster standing lasts only as long |
| + // as its lease. At the deadline it is asked again, outside SQL, and |
| + // the stream either carries on under the new lease or says bye — a |
| + // silent stream must not outlive a removal. Never armed outside team |
| + // mode, or for access that rests on a share alone (renew 0); a nil |
| + // channel never fires. |
| + var lease *time.Timer |
| + var leaseC <-chan time.Time |
| + arm := func(d time.Duration) { |
| + if lease != nil { |
| + lease.Stop() |
| + } |
| + lease, leaseC = nil, nil |
| + if d > 0 { |
| + lease = time.NewTimer(d) |
| + leaseC = lease.C |
| + } |
| + } |
| + arm(renew) |
| + defer func() { arm(0) }() |
| for { |
| select { |
| @@ -113,6 +134,14 @@ func (a *App) handleStream(w http.ResponseWriter, r *http.Request) { |
| writeEvent(w, rc, "bye", `{"reason":"idle"}`) |
| return |
| + case <-leaseC: |
| + ok, d := a.streamAccess(r, sheetID) |
| + if !ok { |
| + writeEvent(w, rc, "bye", `{"reason":"access-changed"}`) |
| + return |
| + } |
| + arm(d) |
| + |
| case <-ping.C: |
| // A comment line: valid SSE, ignored by EventSource, and |
| // enough to keep an intermediary from calling the |
| @@ -142,10 +171,12 @@ func (a *App) handleStream(w http.ResponseWriter, r *http.Request) { |
| // One indexed read per delivered message, not per edit on |
| // the instance: a subscriber only reaches this line when a |
| // message is already addressed to its tab. |
| - if !a.streamAuthorized(r, sheetID) { |
| + ok, d := a.streamAccess(r, sheetID) |
| + if !ok { |
| writeEvent(w, rc, "bye", `{"reason":"access-changed"}`) |
| return |
| } |
| + arm(d) |
| if sub.Lost() { |
| // This subscriber overran its buffer and has missed at |
| // least one message, so everything after it would paint |
diff --git a/internal/sheets/home.go b/internal/sheets/home.go| index 8ae77e7..5a08432 100644 |
| --- a/internal/sheets/home.go |
| +++ b/internal/sheets/home.go |
| @@ -20,6 +20,11 @@ import ( |
| var errHome = errors.New("sheets: Home connection unavailable") |
| +// homeNamespace is Sheets' Home storage namespace: connect's link and |
| +// handoff sealing, and in team mode the roster evidence and the team |
| +// sign-in's handoff store, which must open connect's pending rows. |
| +const homeNamespace = "oficina/sheets" |
| + |
| // ConfigureHome runs after local auth is attached and before serving requests. |
| func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| settings, err := connect.DecodeCredentials(raw, a.origin) |
| @@ -58,7 +63,7 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| p := connect.PageFor(r, state, label, func(k string) string { return homeCopy[k] }) |
| a.render(w, r, "home_link", titled(p.Title), status, p) |
| } |
| - bridge, err := connect.New(connect.Config{DB: d, Origin: a.origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Namespace: "oficina/sheets", Keys: settings.Keys, DEK: settings.DEK, SessionCookie: sess.CookieName(), ReadSession: read, |
| + bridge, err := connect.New(connect.Config{DB: d, Origin: a.origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Namespace: homeNamespace, Keys: settings.Keys, DEK: settings.DEK, SessionCookie: sess.CookieName(), ReadSession: read, |
| MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) |
| }, |
| @@ -75,11 +80,12 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| if err != nil { |
| return errHome |
| } |
| - routes, err := connect.NewRoutes(bridge, connect.RoutesConfig{LocalLandingPath: "/sheets", Namespace: "oficina/sheets", Origin: a.origin, Issuer: settings.Issuer, SessionCookie: sess.CookieName(), DEK: settings.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.handleSignin, Protect: csrf.Protect(a.origin), Render: render, FormPolicy: connect.FormPolicy(settings.Issuer)}) |
| + routes, err := connect.NewRoutes(bridge, connect.RoutesConfig{LocalLandingPath: "/sheets", Namespace: homeNamespace, Origin: a.origin, Issuer: settings.Issuer, SessionCookie: sess.CookieName(), DEK: settings.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.handleSignin, Protect: csrf.Protect(a.origin), Render: render, FormPolicy: connect.FormPolicy(settings.Issuer)}) |
| if err != nil { |
| return errHome |
| } |
| a.home, a.homeRoutes, a.homeSessions = bridge, routes, sess |
| + a.homeCreds, a.homeRender = settings, render |
| a.directory = settings.Directory |
| return a.configureDashboard(settings) |
| } |
| @@ -96,6 +102,13 @@ func (a *App) homePerson(ctx context.Context, q linkstore.Queryer, id int64) (st |
| if address == "" { |
| return "", sql.ErrNoRows |
| } |
| + // Team mode: a link names who somebody is, not whether they may |
| + // enter. The roster and the shares decide that on every request |
| + // (team_access.go), so a linked team member needs neither a place |
| + // on SHEETS_OWNERS nor a grant to resolve. |
| + if a.team != nil { |
| + return address, nil |
| + } |
| if a.admit != nil && a.admit(address) { |
| return address, nil |
| } |
diff --git a/internal/sheets/home_routes.go b/internal/sheets/home_routes.go| index ba99562..9af1f15 100644 |
| --- a/internal/sheets/home_routes.go |
| +++ b/internal/sheets/home_routes.go |
| @@ -11,7 +11,7 @@ func (a *App) mountAuth(r chi.Router) { |
| r.Get("/signin/local", a.homeRoutes.LocalGuard(a.handleSignin)) |
| r.Get("/auth/start", a.home.Start) |
| r.Post("/auth/assertion", a.home.Callback) |
| - r.Get("/auth/finish", a.home.Finish) |
| + r.Get("/auth/finish", a.homeFinish) |
| r.Get(connect.LocalCompletePath, a.homeRoutes.LocalGuard(a.homeLocalComplete)) |
| r.Get("/account/home", a.homeRoutes.Account) |
| r.Post("/account/home", a.homeRoutes.LinkStart) |
diff --git a/internal/sheets/home_test.go b/internal/sheets/home_test.go| index 43b0be5..8f3650b 100644 |
| --- a/internal/sheets/home_test.go |
| +++ b/internal/sheets/home_test.go |
| @@ -35,6 +35,12 @@ func newHomeFixture(t *testing.T) *homeFixture { |
| func newHomeFixtureWith(t *testing.T, directory string) *homeFixture { |
| t.Helper() |
| app, _ := appWithOrigin(t, testOrigin) |
| + return homeOn(t, app, directory) |
| +} |
| + |
| +// homeOn configures Home on an app built by appWithSchema. |
| +func homeOn(t *testing.T, app *App, directory string) *homeFixture { |
| + t.Helper() |
| key, err := assertioncrypto.Generate() |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/sheets/lastowner.go b/internal/sheets/lastowner.go| index 5ee9ca1..38d4ca3 100644 |
| --- a/internal/sheets/lastowner.go |
| +++ b/internal/sheets/lastowner.go |
| @@ -31,6 +31,14 @@ var errLastOwner = errors.New("sheets: a sheet needs an owner") |
| // owners demoting each other concurrently both counted two, both passed, |
| // and both wrote. SQLite serialises the writes; it does not serialise a |
| // read against someone else's later write. |
| +// |
| +// It counts owner grant ROWS, not live owners. In team mode a departed |
| +// creator's own grant is dead (ownGrantIgnored) yet still counts here, and |
| +// a roster owner's SheetOwner over an orphaned sheet (team_owner.go) holds |
| +// no row and does not. So a roster owner rescuing an orphaned sheet gives |
| +// somebody an owner grant first; only then can the dead one be revoked. |
| +// Counting live owners instead would need the roster inside this |
| +// transaction, which the writer must never wait on. |
| func lastOwnerGoing(tx *gorm.DB, sheetID, memberID uint64, newRole SheetRole) (bool, error) { |
| if newRole == SheetOwner { |
| return false, nil // not going anywhere |
diff --git a/internal/sheets/members.go b/internal/sheets/members.go| index 8ca6376..71eb082 100644 |
| --- a/internal/sheets/members.go |
| +++ b/internal/sheets/members.go |
| @@ -43,8 +43,12 @@ func (a *App) memberFor(address string) (Member, error) { |
| // through a share and is a guest. Guest is the safe default: the |
| // wrong direction is unrecoverable in the way that matters, since a |
| // guest wrongly made a member sees every sheet on the instance. |
| + // |
| + // In team mode the roster is the team and this column is never read |
| + // (team_access.go), so SHEETS_OWNERS — if it is set at all — only |
| + // admits a local sign-in and promotes nobody. |
| role := TeamGuest |
| - if a.admit != nil && a.admit(addr) { |
| + if a.team == nil && a.admit != nil && a.admit(addr) { |
| role = TeamOwner |
| } |
| @@ -82,6 +86,18 @@ func (a *App) memberFor(address string) (Member, error) { |
| // through requireSession, so a false here in production means the |
| // session went away between the middleware and the handler. |
| func (a *App) actor(r *http.Request) (Member, bool) { |
| + if a.team != nil { |
| + // Team mode: the standing teamRequire resolved for this request, |
| + // or a fresh one off the group. Never memberFor's stored role. |
| + t, ok := teamAccessFrom(r) |
| + if !ok { |
| + var err error |
| + if t, err = a.resolveTeamAccess(r); err != nil { |
| + return Member{}, false |
| + } |
| + } |
| + return t.actor(), true |
| + } |
| if a.home != nil { |
| s, ok := a.homeSessions.From(r) |
| if ok && s.Method == "home-assertion" { |
diff --git a/internal/sheets/models.go b/internal/sheets/models.go| index aa62525..c6d2eca 100644 |
| --- a/internal/sheets/models.go |
| +++ b/internal/sheets/models.go |
| @@ -28,6 +28,11 @@ type Member struct { |
| // way that matters: a guest wrongly made a member sees every sheet. |
| TeamRole string `gorm:"size:16"` |
| CreatedAt time.Time |
| + |
| + // team is the request's roster standing in team mode (team_access.go), |
| + // attached by actor and withStanding and never stored: unexported, so |
| + // GORM does not map it. Nil outside team mode. |
| + team *teamAccess |
| } |
| // TeamRole is a person's standing on this instance as a whole. |
diff --git a/internal/sheets/native.go b/internal/sheets/native.go| index d6a271a..e6a3e81 100644 |
| --- a/internal/sheets/native.go |
| +++ b/internal/sheets/native.go |
| @@ -90,6 +90,10 @@ func (a *App) handleNativeJob(w http.ResponseWriter, r *http.Request) { |
| nativeJSON(w, 200, map[string]any{"status": job.Status, "progress": job.Progress, "error": job.Err, "location": job.Location}) |
| } |
| func (a *App) streamAuthorized(r *http.Request, sheetID uint64) bool { |
| + if a.team != nil { |
| + ok, _ := a.streamAccess(r, sheetID) |
| + return ok |
| + } |
| address, ok := a.identity(r) |
| if !ok || !a.Admits(address) { |
| return false |
diff --git a/internal/sheets/page.go b/internal/sheets/page.go| index a41f0e4..0819598 100644 |
| --- a/internal/sheets/page.go |
| +++ b/internal/sheets/page.go |
| @@ -47,7 +47,7 @@ import ( |
| // and sends a signed-out visitor to /signin?return_to=%2F. |
| func (a *App) handleIndex(w http.ResponseWriter, r *http.Request) { |
| if a.home != nil { |
| - a.homeRequire(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + a.signedInRequire(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/sheets", http.StatusSeeOther) |
| })).ServeHTTP(w, r) |
| return |
| @@ -69,6 +69,12 @@ func (a *App) identity(r *http.Request) (string, bool) { |
| } |
| if s.Method == connect.HomeMethod { |
| p, err := a.home.ResolveSession(r) |
| + if err != nil && a.team != nil { |
| + // A Home-only team member: signed in, with no address. |
| + if _, err := a.homeMemberID(r.Context(), s.Subject); err == nil { |
| + return "", true |
| + } |
| + } |
| return p.Label, err == nil |
| } |
| } |
diff --git a/internal/sheets/session_guard.go b/internal/sheets/session_guard.go| index 767f0d8..c2a77fc 100644 |
| --- a/internal/sheets/session_guard.go |
| +++ b/internal/sheets/session_guard.go |
| @@ -12,10 +12,19 @@ import "net/http" |
| // — main exits before New if sign-in is not configured. |
| func (a *App) requireSession(next http.Handler) http.Handler { |
| if a.home != nil { |
| - return a.homeRequire(next) |
| + return a.signedInRequire(next) |
| } |
| if a.auth == nil { |
| return next |
| } |
| return a.auth.RequireSession(a.rejectDisabledHome(next)) |
| } |
| + |
| +// signedInRequire is the Home-mode guard: the roster's in team mode, |
| +// the allowlist's otherwise. |
| +func (a *App) signedInRequire(next http.Handler) http.Handler { |
| + if a.team != nil { |
| + return a.teamRequire(next) |
| + } |
| + return a.homeRequire(next) |
| +} |
diff --git a/internal/sheets/sharenotice.go b/internal/sheets/sharenotice.go| index 7288c77..cefba2d 100644 |
| --- a/internal/sheets/sharenotice.go |
| +++ b/internal/sheets/sharenotice.go |
| @@ -1,6 +1,7 @@ |
| package sheets |
| import ( |
| + "context" |
| "net/http" |
| "strconv" |
| ) |
| @@ -34,14 +35,14 @@ const revokedTeamText = "The explicit permission is removed, but since they are |
| // Asked AFTER the revoke, and asked of roleFor rather than reasoned |
| // about separately, so the notice reports what the gate actually says |
| // instead of holding a second opinion that can drift from it. |
| -func (a *App) stillReaches(sheetID, memberID uint64) bool { |
| +func (a *App) stillReaches(ctx context.Context, sheetID, memberID uint64) bool { |
| m, ok := a.memberByID(memberID) |
| if !ok { |
| // The grant is gone and we cannot tell what is left. The plain |
| // sentence is the one that claims less. |
| return false |
| } |
| - _, still := a.roleFor(sheetID, m) |
| + _, still := a.roleFor(sheetID, a.withStanding(ctx, m)) |
| return still |
| } |
| @@ -65,10 +66,13 @@ func (a *App) revokedTeamNotice(r *http.Request, sheetID uint64) string { |
| return revokedTeamText |
| } |
| m, ok := a.memberByID(id) |
| - if !ok || !a.stillReaches(sheetID, m.ID) { |
| + if ok { |
| + m = a.withStanding(r.Context(), m) // for Label's Home-only ref |
| + } |
| + if !ok || !a.stillReaches(r.Context(), sheetID, m.ID) { |
| return revokedTeamText |
| } |
| - return "The explicit permission is removed, but since " + m.Address + |
| + return "The explicit permission is removed, but since " + m.Label() + |
| " is on the team, they still have access." |
| } |
diff --git a/internal/sheets/team_access.go b/internal/sheets/team_access.go| new file mode 100644 |
| index 0000000..7f61275 |
| --- /dev/null |
| +++ b/internal/sheets/team_access.go |
| @@ -0,0 +1,246 @@ |
| +package sheets |
| + |
| +// Team mode's per-request standing. With a.team nil nothing here runs: |
| +// every helper below returns today's answer unchanged. |
| +// |
| +// The shape is Docs' team_access.go. Identity is resolved from the actual |
| +// session (a local address, an account link, or a Home-only member); the |
| +// roster is asked about the Home subject, if there is one; and the answer |
| +// is one of three: |
| +// |
| +// - Member: the team rung of roleFor. The roster's role says owner or |
| +// member; the members.team_role column is never read in team mode, so |
| +// a removed owner cannot keep standing through a stale row. |
| +// - NotMember: a guest. Only sheets shared with them by somebody else. |
| +// - Unknown: the roster could not be read within its lease. Shares still |
| +// work; anything that would have needed standing answers a retryable |
| +// 503 rather than a 404 that would claim the sheet is not theirs. |
| +// |
| +// A Member decision carries a lease. teamAccess.state() checks it every |
| +// time it is asked, so the authorization each handler makes immediately |
| +// before it writes is made against a lease that is still valid then. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "sync/atomic" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +type teamAccessKey struct{} |
| + |
| +// teamAccess is one request's standing. Never stored; a stream asks for |
| +// a new one before each delivery. |
| +type teamAccess struct { |
| + member Member |
| + subject string |
| + decision roster.Decision |
| + // uncertain latches once a Member lease is found expired or |
| + // contended, so a request cannot see Member again after it has seen |
| + // Unknown. |
| + uncertain atomic.Bool |
| +} |
| + |
| +var errNoIdentity = errors.New("sheets: no team identity") |
| + |
| +func (t *teamAccess) state() roster.State { |
| + if t == nil || t.uncertain.Load() { |
| + return roster.Unknown |
| + } |
| + if t.decision.State == roster.Member && !t.decision.Lease.Valid() { |
| + t.uncertain.Store(true) |
| + return roster.Unknown |
| + } |
| + return t.decision.State |
| +} |
| + |
| +// role is the team rung the roster gives: owner or member for a Member, |
| +// guest for anybody else, Unknown included (it reaches shares only). |
| +func (t *teamAccess) role() TeamRole { |
| + if t.state() != roster.Member { |
| + return TeamGuest |
| + } |
| + if t.decision.Role == "owner" { |
| + return TeamOwner |
| + } |
| + return TeamMember |
| +} |
| + |
| +func teamAccessFrom(r *http.Request) (*teamAccess, bool) { |
| + t, ok := r.Context().Value(teamAccessKey{}).(*teamAccess) |
| + return t, ok && t != nil |
| +} |
| + |
| +// teamRole is roleFor's and visibleSheets' team rung. Outside team mode |
| +// it is the stored column, exactly as before. In team mode it is only |
| +// ever the roster's answer, and a member read without one (memberByID) |
| +// has no team standing until withStanding asks. |
| +func (a *App) teamRole(m Member) TeamRole { |
| + if a.team == nil { |
| + return TeamRole(m.TeamRole) |
| + } |
| + if m.team == nil { |
| + return TeamGuest |
| + } |
| + return m.team.role() |
| +} |
| + |
| +// ownGrantIgnored is the Docs owner_id rule in Sheets' terms. A sheet's |
| +// creator holds it through a grant they gave themselves (createSheet), so |
| +// in team mode a self-given grant is the team rung's, not a share: it |
| +// counts only while the roster says Member. Grants somebody else gave |
| +// are shares, and keep working whatever the roster says. |
| +func (a *App) ownGrantIgnored(g Grant, m Member) bool { |
| + return a.team != nil && g.GrantedBy == g.MemberID && a.teamRole(m) == TeamGuest |
| +} |
| + |
| +// homeMemberID is the member a Home subject signs in as: an account link |
| +// first, then a Home-only member. It never creates either. |
| +func (a *App) homeMemberID(ctx context.Context, subject string) (int64, error) { |
| + p, err := a.home.Resolve(ctx, subject) |
| + if err == nil { |
| + return p.ID, nil |
| + } |
| + if errors.Is(err, linkstore.ErrStorage) { |
| + return 0, errTeamUnavailable |
| + } |
| + id, err := teamstate.HomeMember(ctx, a.team.db, a.team.bindings.Issuer, subject) |
| + if errors.Is(err, teamstate.ErrUnavailable) { |
| + return 0, errTeamUnavailable |
| + } |
| + return id, err |
| +} |
| + |
| +// teamIdentify resolves the actual session to a member and the Home |
| +// subject the roster knows them by ("" when there is none: a local |
| +// account with no link, which is no team standing). |
| +func (a *App) teamIdentify(ctx context.Context, s sessions.Session) (Member, string, error) { |
| + switch s.Method { |
| + case connect.HomeMethod: |
| + id, err := a.homeMemberID(ctx, s.Subject) |
| + if err != nil { |
| + if errors.Is(err, errTeamUnavailable) { |
| + return Member{}, "", err |
| + } |
| + return Member{}, "", errNoIdentity |
| + } |
| + m, ok := a.memberByID(uint64(id)) |
| + if !ok { |
| + return Member{}, "", errTeamUnavailable |
| + } |
| + return m, s.Subject, nil |
| + case "magiclink", "keymail": |
| + // A local session was admitted at sign-in (Admits). Its member is |
| + // created on first sight exactly as actor() always has. |
| + m, err := a.memberFor(s.Subject) |
| + if err != nil { |
| + return Member{}, "", errTeamUnavailable |
| + } |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.bindings.Issuer, int64(m.ID)) |
| + if errors.Is(err, teamstate.ErrRefused) { |
| + return m, "", nil |
| + } |
| + if err != nil { |
| + return Member{}, "", errTeamUnavailable |
| + } |
| + return m, subject, nil |
| + } |
| + return Member{}, "", errNoIdentity |
| +} |
| + |
| +// resolveTeamAccess asks everything afresh: session, member, roster. |
| +// The roster call may wait for a refresh, so never call it holding the |
| +// SQLite writer. |
| +func (a *App) resolveTeamAccess(r *http.Request) (*teamAccess, error) { |
| + s, ok := a.homeSessions.From(r) |
| + if !ok { |
| + return nil, errNoIdentity |
| + } |
| + m, subject, err := a.teamIdentify(r.Context(), s) |
| + if err != nil { |
| + return nil, err |
| + } |
| + t := &teamAccess{member: m, subject: subject, decision: roster.Decision{State: roster.NotMember}} |
| + if subject != "" { |
| + t.decision = a.team.check(r.Context(), subject) |
| + } |
| + return t, nil |
| +} |
| + |
| +// actor is the member a handler acts as: the stored row with the |
| +// request's standing attached. |
| +func (t *teamAccess) actor() Member { |
| + m := t.member |
| + m.team = t |
| + m.TeamRole = string(t.role()) |
| + return m |
| +} |
| + |
| +// withStanding asks the roster about somebody other than the viewer — |
| +// the share screen's people and its revoke notice — so what it says |
| +// about them is what roleFor would decide for them. |
| +func (a *App) withStanding(ctx context.Context, m Member) Member { |
| + if a.team == nil { |
| + return m |
| + } |
| + t := &teamAccess{member: m, decision: roster.Decision{State: roster.NotMember}} |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.bindings.Issuer, int64(m.ID)) |
| + switch { |
| + case err == nil: |
| + t.subject = subject |
| + t.decision = a.team.check(ctx, subject) |
| + case !errors.Is(err, teamstate.ErrRefused): |
| + t.decision = roster.Decision{State: roster.Unknown} |
| + } |
| + return t.actor() |
| +} |
| + |
| +// teamJobOwner is the jobs registry's owner key in team mode. A |
| +// Home-only member has no address to key on, so every team-mode session |
| +// keys on its member instead; both job routes read it from the same |
| +// middleware. |
| +func teamJobOwner(id uint64) string { return "sheets-member:" + strconv.FormatUint(id, 10) } |
| + |
| +// teamRequire is homeRequire for team mode: the session must resolve to |
| +// a member, and the request carries that member's roster standing. It |
| +// does not sign anybody out for lacking standing: a removed member keeps |
| +// a session that reaches only what was shared with them. |
| +func (a *App) teamRequire(next http.Handler) http.Handler { |
| + return a.homeSessions.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + session, ok := a.homeSessions.From(r) |
| + var t *teamAccess |
| + err := errNoIdentity |
| + if ok { |
| + t, err = a.resolveTeamAccess(r) |
| + } |
| + if errors.Is(err, errTeamUnavailable) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Error(w, "Sign-in unavailable.", http.StatusServiceUnavailable) |
| + return |
| + } |
| + if err != nil { |
| + if ok { |
| + a.homeSessions.SignOut(w, r) |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| + http.Redirect(w, r, "/signin?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) |
| + } else { |
| + http.Error(w, "Sign in first.", http.StatusForbidden) |
| + } |
| + return |
| + } |
| + session.Subject = teamJobOwner(t.member.ID) |
| + r = r.WithContext(context.WithValue(r.Context(), teamAccessKey{}, t)) |
| + next.ServeHTTP(w, sessions.WithSession(r, session)) |
| + })) |
| +} |
diff --git a/internal/sheets/team_access_test.go b/internal/sheets/team_access_test.go| new file mode 100644 |
| index 0000000..17e98f7 |
| --- /dev/null |
| +++ b/internal/sheets/team_access_test.go |
| @@ -0,0 +1,249 @@ |
| +package sheets |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func sheetPath(id uint64) string { return "/sheets/" + strconv.FormatUint(id, 10) } |
| + |
| +// teamSheet makes a sheet as somebody else on the instance, so the only |
| +// way the person under test reaches it is the team rung. |
| +func teamSheet(t *testing.T, f *teamFixture, title string) SheetSummary { |
| + t.Helper() |
| + other, err := f.app.memberFor("colleague@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err := f.app.createSheet(title, other) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func memberCount(t *testing.T, f *teamFixture) int64 { |
| + t.Helper() |
| + var n int64 |
| + if err := f.app.db.Model(&Member{}).Count(&n).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// A roster member with no account here signs in with Home alone, works |
| +// as a team member, and — removed on Home — loses the team on the next |
| +// request once the roster refreshes, on the session they already hold. |
| +// Their own sheet goes with it: its creator's grant is the team rung's. |
| +func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + |
| + if fin := f.signInHome(t, a); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != "/sheets" { |
| + t.Fatalf("roster member's Home sign-in = %d %q", fin.Code, fin.Body.String()) |
| + } |
| + var addressless int64 |
| + f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless) |
| + if addressless != 1 { |
| + t.Fatalf("Home-only members = %d, want 1", addressless) |
| + } |
| + created := f.request(t, "POST", "/sheets", url.Values{"title": {"Mine"}}, false) |
| + if created.Code != http.StatusSeeOther { |
| + t.Fatalf("member create = %d", created.Code) |
| + } |
| + mine := created.Header().Get("Location") |
| + for _, p := range []string{"/sheets", sheetPath(plan.ID), mine} { |
| + if rec := f.get(t, p); rec.Code != http.StatusOK { |
| + t.Fatalf("member GET %s = %d", p, rec.Code) |
| + } |
| + } |
| + session := f.jar[f.app.homeSessions.CookieName()] |
| + |
| + f.dir.set(a, "") |
| + f.refreshed(t) |
| + if f.jar[f.app.homeSessions.CookieName()] != session { |
| + t.Fatal("the test lost the session it means to keep using") |
| + } |
| + for _, p := range []string{sheetPath(plan.ID), mine} { |
| + if rec := f.get(t, p); rec.Code != http.StatusNotFound { |
| + t.Errorf("removed member GET %s = %d, want 404", p, rec.Code) |
| + } |
| + } |
| + if list := f.get(t, "/sheets"); list.Code != http.StatusOK || strings.Contains(list.Body.String(), "Team plan") || strings.Contains(list.Body.String(), "Mine") { |
| + t.Errorf("removed member's list = %d, still showing team sheets", list.Code) |
| + } |
| + if rec := f.request(t, "POST", "/sheets", url.Values{"title": {"After"}}, false); rec.Code != http.StatusForbidden { |
| + t.Errorf("removed member create = %d, want 403", rec.Code) |
| + } |
| +} |
| + |
| +// The known Sheets bug, under team mode: an address on SHEETS_OWNERS with |
| +// a stored team_role of owner has no team standing at all unless the |
| +// roster says so, and loses it when the roster stops saying so. Roles come |
| +// from the roster. Shares from somebody else survive removal, and keep |
| +// working while the roster cannot be read. |
| +func TestTeamStandingIsTheRostersNeverTheStoredRole(t *testing.T) { |
| + f := newTeamFixture(t, signedInAddress) |
| + plan := teamSheet(t, f, "Team plan") |
| + f.local(t, signedInAddress) |
| + var stored Member |
| + if err := f.app.db.Where("address = ?", signedInAddress).First(&stored).Error; err != nil || stored.TeamRole != string(TeamGuest) { |
| + t.Fatalf("SHEETS_OWNERS promoted a member in team mode: %q %v", stored.TeamRole, err) |
| + } |
| + if err := f.app.db.Model(&Member{}).Where("address = ?", signedInAddress).Update("team_role", "owner").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := f.get(t, sheetPath(plan.ID)); rec.Code != http.StatusNotFound { |
| + t.Fatalf("stored owner without roster standing = %d, want 404", rec.Code) |
| + } |
| + |
| + p := teamSubject('p') |
| + f.dir.set(p, "owner") |
| + f.link(t, p) |
| + // Off the allowlist and holding no grant: the link still resolves, |
| + // because in team mode the roster, not admission, is the team. |
| + f.app.admit = Admits(nil) |
| + if rec := f.get(t, sheetPath(plan.ID)); rec.Code != http.StatusOK { |
| + t.Fatalf("linked roster owner = %d, want 200", rec.Code) |
| + } |
| + // And signing in with Home alone reaches the same account. |
| + if fin := f.signInHome(t, p); fin.Code != http.StatusSeeOther { |
| + t.Fatalf("linked owner's Home sign-in = %d", fin.Code) |
| + } |
| + if rec := f.get(t, sheetPath(plan.ID)); rec.Code != http.StatusOK { |
| + t.Fatalf("linked roster owner by Home session = %d, want 200", rec.Code) |
| + } |
| + paul := f.viewer(t) |
| + if !f.app.stillReaches(t.Context(), plan.ID, paul.ID) { |
| + t.Error("the share screen says a roster owner cannot reach a team sheet") |
| + } |
| + if m := f.viewer(t); m.TeamRole != string(TeamOwner) { |
| + t.Errorf("roster owner's team role = %q", m.TeamRole) |
| + } |
| + f.dir.set(p, "member") |
| + f.refreshed(t) |
| + if m := f.viewer(t); m.TeamRole != string(TeamMember) { |
| + t.Errorf("roster member's team role = %q", m.TeamRole) |
| + } |
| + |
| + colleague, _ := f.app.memberFor("colleague@example.com") |
| + shared := teamSheet(t, f, "Shared") |
| + if _, err := f.app.grant(shared.ID, signedInAddress, SheetViewer, colleague); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + f.expired(t) |
| + missing := f.get(t, "/sheets/999999") |
| + team := f.get(t, sheetPath(plan.ID)) |
| + if team.Code != http.StatusServiceUnavailable || missing.Code != team.Code || missing.Body.String() != team.Body.String() { |
| + t.Errorf("Unknown standing: team sheet %d, missing sheet %d; want identical 503s", team.Code, missing.Code) |
| + } |
| + if rec := f.get(t, sheetPath(shared.ID)); rec.Code != http.StatusOK { |
| + t.Errorf("a share under Unknown standing = %d, want 200", rec.Code) |
| + } |
| + if rec := f.get(t, "/sheets"); rec.Code != http.StatusServiceUnavailable { |
| + t.Errorf("list under Unknown standing = %d, want 503", rec.Code) |
| + } |
| + if rec := f.request(t, "POST", "/sheets", url.Values{"title": {"x"}}, false); rec.Code != http.StatusServiceUnavailable { |
| + t.Errorf("create under Unknown standing = %d, want 503", rec.Code) |
| + } |
| + |
| + f.dir.setDown(false) |
| + f.dir.set(p, "") |
| + f.refreshed(t) |
| + if rec := f.get(t, sheetPath(plan.ID)); rec.Code != http.StatusNotFound { |
| + t.Errorf("removed linked member = %d, want 404", rec.Code) |
| + } |
| + if f.app.stillReaches(t.Context(), plan.ID, paul.ID) { |
| + t.Error("the share screen says a removed member still reaches a team sheet") |
| + } |
| + if rec := f.get(t, sheetPath(shared.ID)); rec.Code != http.StatusOK { |
| + t.Errorf("removed member's share = %d, want 200", rec.Code) |
| + } |
| +} |
| + |
| +// A member's lease is sixty seconds. With the directory down, standing |
| +// holds until then and not a moment after: Unknown, retryable. |
| +func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + f.dir.setDown(true) |
| + f.clock.step(59 * time.Second) |
| + if rec := f.get(t, sheetPath(plan.ID)); rec.Code != http.StatusOK { |
| + t.Fatalf("inside the lease = %d, want 200", rec.Code) |
| + } |
| + f.clock.step(2 * time.Second) |
| + rec := f.get(t, sheetPath(plan.ID)) |
| + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") == "" { |
| + t.Fatalf("past the lease = %d (Retry-After %q), want a retryable 503", rec.Code, rec.Header().Get("Retry-After")) |
| + } |
| +} |
| + |
| +// Home sign-in allocates only for a subject the roster says is a member |
| +// right now; not for a stranger, not when the roster is unknown, and not |
| +// when somebody else is already signed in. |
| +func TestTeamSignInAllocatesOnlyForACurrentMember(t *testing.T) { |
| + f := newTeamFixture(t) |
| + if fin := f.signInHome(t, teamSubject('z')); fin.Code != http.StatusForbidden || !strings.Contains(fin.Body.String(), "/signin/local") { |
| + t.Fatalf("stranger's Home sign-in = %d", fin.Code) |
| + } |
| + if _, ok := f.jar[f.app.homeSessions.CookieName()]; ok || memberCount(t, f) != 0 { |
| + t.Fatal("a stranger got a session or a member") |
| + } |
| + |
| + f.dir.set(teamSubject('a'), "member") |
| + f.dir.set(teamSubject('b'), "member") |
| + f.refreshed(t) // the stranger's sign-in fetched the roster before they were added |
| + if fin := f.signInHome(t, teamSubject('a')); fin.Code != http.StatusSeeOther { |
| + t.Fatalf("member's Home sign-in = %d", fin.Code) |
| + } |
| + start := f.request(t, "GET", "/auth/start?return_to=%2Fsheets", nil, false) |
| + // The exchange itself refuses a different subject over a Home session |
| + // (400, as connect's does), before anything here runs. |
| + if fin := f.exchange(t, start, teamSubject('b')); fin.Code != http.StatusBadRequest { |
| + t.Errorf("a second identity over a live Home session = %d, want 400", fin.Code) |
| + } |
| + // Over a local session it reaches teamComplete, which refuses an |
| + // unknown arrival before allocating anything. |
| + f.jar = map[string]*http.Cookie{} |
| + f.local(t, "local@example.com") |
| + start = f.request(t, "GET", "/auth/start?return_to=%2Fsheets", nil, false) |
| + if fin := f.exchange(t, start, teamSubject('b')); fin.Code != http.StatusForbidden { |
| + t.Errorf("an unknown identity over a live local session = %d, want 403", fin.Code) |
| + } |
| + if n := memberCount(t, f); n != 2 { |
| + t.Errorf("members = %d after refused arrivals, want 2 (a, and the local account)", n) |
| + } |
| + |
| + f.expired(t) |
| + if fin := f.signInHome(t, teamSubject('b')); fin.Code != http.StatusServiceUnavailable { |
| + t.Errorf("unknown roster at first sign-in = %d, want 503", fin.Code) |
| + } |
| + if n := memberCount(t, f); n != 2 { |
| + t.Errorf("members = %d after an Unknown arrival, want 2", n) |
| + } |
| +} |
| + |
| +// viewer is the request's actor as a handler sees it. |
| +func (f *teamFixture) viewer(t *testing.T) Member { |
| + t.Helper() |
| + r := httptest.NewRequest("GET", testOrigin+"/sheets", nil) |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + m, ok := f.app.actor(r) |
| + if !ok { |
| + t.Fatal("no actor") |
| + } |
| + return m |
| +} |
diff --git a/internal/sheets/team_answers.go b/internal/sheets/team_answers.go| new file mode 100644 |
| index 0000000..33f5a15 |
| --- /dev/null |
| +++ b/internal/sheets/team_answers.go |
| @@ -0,0 +1,136 @@ |
| +package sheets |
| + |
| +// Team mode's answers: the retryable 503 for Unknown standing, the |
| +// member-only gate, a stream's lease-bounded re-check, and the label an |
| +// addressless member is shown by. Each is a no-op outside team mode. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// teamUnknown reports whether this request's standing could not be |
| +// decided. notFound answers it with a retryable 503: a 404 would tell a |
| +// team member their sheet is gone because Home was slow. |
| +func (a *App) teamUnknown(r *http.Request) bool { |
| + if a.team == nil { |
| + return false |
| + } |
| + t, ok := teamAccessFrom(r) |
| + return ok && t.state() == roster.Unknown |
| +} |
| + |
| +// unavailable is the retryable answer for Unknown standing. |
| +func (a *App) unavailable(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", strconv.Itoa(int(roster.RetryAfter/time.Second))) |
| + a.answer(w, r, http.StatusServiceUnavailable, kindStatus, "Try again in a moment.") |
| +} |
| + |
| +// teamMemberOnly gates what makes something new on the instance (create, |
| +// import): team members only, as Docs' create. A guest gets 403, Unknown |
| +// a retryable 503. Outside team mode it lets everybody through, as |
| +// before. |
| +func (a *App) teamMemberOnly(w http.ResponseWriter, r *http.Request) bool { |
| + if a.team == nil { |
| + return true |
| + } |
| + t, ok := teamAccessFrom(r) |
| + if !ok { |
| + a.unavailable(w, r) |
| + return false |
| + } |
| + switch t.state() { |
| + case roster.Member: |
| + return true |
| + case roster.NotMember: |
| + a.answer(w, r, http.StatusForbidden, kindStatus, "Only team members can do that.") |
| + default: |
| + a.unavailable(w, r) |
| + } |
| + return false |
| +} |
| + |
| +// streamAccess decides one stream delivery afresh and says how long a |
| +// standing-backed answer may stand before it must be asked again: the |
| +// Member lease's remaining time, or 0 when nothing expires on a timer |
| +// (outside team mode, or when the answer did not rest on a lease). |
| +func (a *App) streamAccess(r *http.Request, sheetID uint64) (bool, time.Duration) { |
| + if a.team == nil { |
| + return a.streamAuthorized(r, sheetID), 0 |
| + } |
| + t, err := a.resolveTeamAccess(r) |
| + if err != nil { |
| + return false, 0 |
| + } |
| + if !a.mayRead(sheetID, t.actor()) { |
| + return false, 0 |
| + } |
| + if t.state() != roster.Member { |
| + return true, 0 |
| + } |
| + renew := t.decision.Lease.Remaining() |
| + if renew <= 0 { |
| + renew = time.Second |
| + } |
| + return true, renew |
| +} |
| + |
| +// teamLabel is how an addressless (Home-only) member is shown where an |
| +// address would be: a share list row, a history author. |
| +const teamLabel = "Oficina account" |
| + |
| +// Label is the address, or for a member who has none — only a team-mode |
| +// Home-only member can lack one, since memberFor refuses to mint an |
| +// addressless member — teamLabel and the last four characters of their |
| +// person ref when the roster lookup supplied it ("Oficina account …k7qz", |
| +// as Home's Team page shows a ref). Outside team mode this is always |
| +// Address. |
| +func (m Member) Label() string { |
| + if strings.TrimSpace(m.Address) != "" { |
| + return m.Address |
| + } |
| + if m.team != nil { |
| + return homeOnlyLabel(m.team.subject) |
| + } |
| + return teamLabel |
| +} |
| + |
| +func homeOnlyLabel(subject string) string { |
| + if len(subject) <= 4 { |
| + return teamLabel |
| + } |
| + return teamLabel + " …" + subject[len(subject)-4:] |
| +} |
| + |
| +// homeOnlyRefs maps each Home-only member to its subject, for labels on |
| +// pages that list members without asking the roster (history). Nil |
| +// outside team mode or on a read failure, which only costs the suffix. |
| +func (a *App) homeOnlyRefs(ctx context.Context) map[uint64]string { |
| + if a.team == nil { |
| + return nil |
| + } |
| + rows, err := a.team.db.QueryContext(ctx, "SELECT member_id, subject FROM sheets_team_home_members WHERE issuer=?", a.team.bindings.Issuer) |
| + if err != nil { |
| + return nil |
| + } |
| + defer rows.Close() |
| + out := map[uint64]string{} |
| + for rows.Next() { |
| + var id uint64 |
| + var subject string |
| + if rows.Scan(&id, &subject) != nil { |
| + return nil |
| + } |
| + out[id] = subject |
| + } |
| + if rows.Err() != nil { |
| + return nil |
| + } |
| + return out |
| +} |
diff --git a/internal/sheets/team_config.go b/internal/sheets/team_config.go| new file mode 100644 |
| index 0000000..35d9261 |
| --- /dev/null |
| +++ b/internal/sheets/team_config.go |
| @@ -0,0 +1,220 @@ |
| +package sheets |
| + |
| +// Team mode: the roster decides standing (Home implementation/ |
| +// team-members.md Part B, §7). Ported from Docs' team_config.go with |
| +// Sheets' names: SHEETS_TEAM_ID, _DIRECTORY_ORIGIN, _PROVISIONING_BASE64, |
| +// _OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN, all or none, and only beside |
| +// SHEETS_HOME_*. Without them nothing in this file runs and Sheets is the |
| +// allowlist app it has always been. |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "sync/atomic" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "github.com/go-json-experiment/json" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +// TeamConfig is deployment configuration, never request input. The two |
| +// unexported fields are for tests: a directory that answers in memory |
| +// and a clock that can be stepped past the lease. |
| +type TeamConfig struct { |
| + transport http.RoundTripper |
| + clock roster.Clock |
| + TeamID string |
| + DirectoryOrigin string |
| + ProvisioningBase64 string |
| + OperatorKeysBase64 string |
| + RosterToken string |
| +} |
| + |
| +var ( |
| + errTeamConfig = errors.New("sheets: invalid team configuration") |
| + errTeamUnavailable = errors.New("sheets: team authority unavailable") |
| +) |
| + |
| +// TeamConfigFromEnv is nil only when all five variables are absent or |
| +// empty. One present and the rest missing is a configuration, and an |
| +// invalid one: ConfigureTeam refuses it rather than booting in |
| +// allowlist mode. |
| +func TeamConfigFromEnv() *TeamConfig { |
| + c := TeamConfig{ |
| + TeamID: os.Getenv("SHEETS_TEAM_ID"), |
| + DirectoryOrigin: os.Getenv("SHEETS_TEAM_DIRECTORY_ORIGIN"), |
| + ProvisioningBase64: os.Getenv("SHEETS_TEAM_PROVISIONING_BASE64"), |
| + OperatorKeysBase64: os.Getenv("SHEETS_TEAM_OPERATOR_KEYS_BASE64"), |
| + RosterToken: os.Getenv("SHEETS_TEAM_ROSTER_TOKEN"), |
| + } |
| + if c == (TeamConfig{}) { |
| + return nil |
| + } |
| + return &c |
| +} |
| + |
| +// TeamBootSchema is BootSchema plus team state, applied only when team |
| +// mode is configured. Once applied it stays: the marker in it is what |
| +// keeps the database in team mode. |
| +var TeamBootSchema = migrate.Merge(BootSchema, teamstate.Schema) |
| + |
| +// BootSchemaFor is the schema main applies, chosen before anything is |
| +// migrated. A database that has been activated in team mode refuses to |
| +// boot without team configuration: an environment variable dropped in a |
| +// redeploy must not quietly hand standing back to SHEETS_OWNERS. The |
| +// binding itself is compared in ConfigureTeam, which has the verified |
| +// record to compare it with. |
| +func BootSchemaFor(ctx context.Context, db *sql.DB, team bool) (*migrate.Set, error) { |
| + _, activated, err := teamstate.Required(ctx, db) |
| + if err != nil { |
| + return nil, errTeamConfig |
| + } |
| + if !team { |
| + if activated { |
| + return nil, errTeamConfig |
| + } |
| + return BootSchema, nil |
| + } |
| + return TeamBootSchema, nil |
| +} |
| + |
| +type teamSettings struct { |
| + record roster.VerifiedRecord |
| + token string |
| + fingerprint string |
| +} |
| + |
| +func teamBase64(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 |
| +} |
| + |
| +// validatedTeamConfig verifies the operator's provisioning record against |
| +// bindings built only from configuration: Home's issuer and consumer ID, |
| +// app "sheets", the team, the directory, and this instance's origin. |
| +func validatedTeamConfig(cfg *TeamConfig, home *connect.DecodedCredentials, origin string) (*teamSettings, error) { |
| + if cfg == nil || home == nil || !roster.ValidChallenge(cfg.RosterToken) { |
| + return nil, errTeamConfig |
| + } |
| + raw, ok := teamBase64(cfg.ProvisioningBase64, roster.BodyLimit) |
| + if !ok { |
| + return nil, errTeamConfig |
| + } |
| + encoded, ok := teamBase64(cfg.OperatorKeysBase64, 4096) |
| + if !ok { |
| + return nil, errTeamConfig |
| + } |
| + var keys []roster.Key |
| + if json.Unmarshal(encoded, &keys, json.RejectUnknownMembers(true)) != nil { |
| + return nil, errTeamConfig |
| + } |
| + expected := roster.Bindings{Issuer: home.Issuer, Directory: cfg.DirectoryOrigin, Consumer: home.ConsumerID, App: "sheets", Team: cfg.TeamID, Audience: origin} |
| + record, err := roster.VerifyProvisioning(raw, keys, expected) |
| + if err != nil { |
| + return nil, errTeamConfig |
| + } |
| + b, err := json.Marshal(record.Bindings()) |
| + if err != nil { |
| + return nil, errTeamConfig |
| + } |
| + digest := sha256.Sum256(b) |
| + return &teamSettings{record: record, token: cfg.RosterToken, fingerprint: base64.RawURLEncoding.EncodeToString(digest[:])}, nil |
| +} |
| + |
| +// teamRuntime is the process's roster cache and the pieces that act on |
| +// its answers. |
| +type teamRuntime struct { |
| + cache *roster.Cache |
| + bindings roster.Bindings |
| + db *sql.DB |
| + // finish completes a Home sign-in that connect would refuse because |
| + // the subject has no account link here: a Home-only roster member |
| + // (team_home.go). |
| + finish *handoff.Consumer |
| + // rosterHeld: some check since boot had a complete roster |
| + // (team_probe.go). |
| + rosterHeld atomic.Bool |
| +} |
| + |
| +// check is the only way the runtime asks the roster cache, so every |
| +// definite answer records that a complete roster has been held since |
| +// boot. Never call it holding the SQLite writer: a refresh publishes |
| +// through that writer. |
| +func (t *teamRuntime) 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.rosterHeld.Store(true) |
| + } |
| + return d |
| +} |
| + |
| +// ConfigureTeam runs after ConfigureHome and before serving. nil leaves |
| +// Sheets exactly as it was. Anything else either produces a verified, |
| +// activated runtime or refuses boot: there is no falling back to the |
| +// allowlist. |
| +func (a *App) ConfigureTeam(cfg *TeamConfig) error { |
| + if cfg == nil { |
| + return nil |
| + } |
| + if a.home == nil || a.homeCreds == nil || a.db == nil { |
| + return errTeamConfig |
| + } |
| + settings, err := validatedTeamConfig(cfg, a.homeCreds, a.origin) |
| + if err != nil { |
| + return err |
| + } |
| + d, err := a.db.DB() |
| + if err != nil { |
| + return errTeamUnavailable |
| + } |
| + ctx := context.Background() |
| + b := settings.record.Bindings() |
| + // Every stored link must name this issuer: the marker pins one, and |
| + // a link from another would be reinterpreted under it. |
| + var foreign int |
| + if err := d.QueryRowContext(ctx, "SELECT (SELECT COUNT(*) FROM home_identity_links WHERE issuer!=?)+(SELECT COUNT(*) FROM sheets_team_home_members WHERE issuer!=?)", b.Issuer, b.Issuer).Scan(&foreign); err != nil { |
| + return errTeamUnavailable |
| + } |
| + if foreign != 0 { |
| + return errTeamConfig |
| + } |
| + if err := teamstate.Activate(ctx, d, settings.fingerprint); err != nil { |
| + return errTeamConfig |
| + } |
| + sealer, err := seal.New(a.homeCreds.DEK, homeNamespace) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + cache, err := roster.New(ctx, roster.Config{Record: settings.record, Token: settings.token, Transport: cfg.transport, Clock: cfg.clock, Durable: teamstate.Evidence{DB: d}, Sealer: sealer}) |
| + if err != nil { |
| + return errTeamUnavailable |
| + } |
| + exchange, err := handoff.NewStore(d, sealer, a.homeCreds.Issuer, a.origin, a.homeCreds.Keys) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + t := &teamRuntime{cache: cache, bindings: b, db: d} |
| + t.finish, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: exchange, ConsumerID: a.homeCreds.ConsumerID, |
| + Complete: a.teamComplete, Fail: a.teamFail, CurrentSubject: a.teamCurrentSubject}) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + a.team = t |
| + return nil |
| +} |
diff --git a/internal/sheets/team_config_test.go b/internal/sheets/team_config_test.go| new file mode 100644 |
| index 0000000..d83afb5 |
| --- /dev/null |
| +++ b/internal/sheets/team_config_test.go |
| @@ -0,0 +1,139 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + rdb "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +// The record is verified against bindings built only from configuration; |
| +// change any one input and ConfigureTeam refuses. Team mode without Home |
| +// refuses too: there is nobody to sign in. |
| +func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| + f := newHomeFixture(t) |
| + cfg, _ := teamConfigFor(t, teamTestBindings()) |
| + if _, err := validatedTeamConfig(cfg, f.app.homeCreds, testOrigin); err != nil { |
| + t.Fatalf("valid team config refused: %v", err) |
| + } |
| + for name, change := range map[string]func(*TeamConfig){ |
| + "team": func(c *TeamConfig) { c.TeamID = "TeamB" }, |
| + "directory": func(c *TeamConfig) { c.DirectoryOrigin = "https://other.example.com" }, |
| + "token": func(c *TeamConfig) { c.RosterToken += "=" }, |
| + "record": func(c *TeamConfig) { c.ProvisioningBase64 += "\n" }, |
| + "operator": func(c *TeamConfig) { c.OperatorKeysBase64 = "e30=" }, |
| + "missing team": func(c *TeamConfig) { c.TeamID = "" }, |
| + } { |
| + bad := *cfg |
| + change(&bad) |
| + if _, err := validatedTeamConfig(&bad, f.app.homeCreds, testOrigin); !errors.Is(err, errTeamConfig) { |
| + t.Errorf("%s: changed team config accepted", name) |
| + } |
| + } |
| + if _, err := validatedTeamConfig(cfg, f.app.homeCreds, "https://elsewhere.example.com"); !errors.Is(err, errTeamConfig) { |
| + t.Error("a record for another origin was accepted") |
| + } |
| + plain, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| + if err := plain.ConfigureTeam(cfg); !errors.Is(err, errTeamConfig) { |
| + t.Errorf("team mode without Home = %v, want refusal", err) |
| + } |
| + if err := plain.ConfigureTeam(nil); err != nil || plain.team != nil { |
| + t.Error("a nil team config changed something") |
| + } |
| +} |
| + |
| +// All five or none; any one set is team mode, and SHEETS_OWNERS stops |
| +// being required. Without any, SHEETS_OWNERS is required exactly as it |
| +// always was. |
| +func TestTeamEnvIsAllOrNoneAndOwnersBecomeOptional(t *testing.T) { |
| + for _, k := range []string{"SHEETS_TEAM_ID", "SHEETS_TEAM_DIRECTORY_ORIGIN", "SHEETS_TEAM_PROVISIONING_BASE64", "SHEETS_TEAM_OPERATOR_KEYS_BASE64", "SHEETS_TEAM_ROSTER_TOKEN"} { |
| + t.Setenv(k, "") |
| + } |
| + t.Setenv("SHEETS_ORIGIN", "http://127.0.0.1:8080") |
| + t.Setenv("SHEETS_INSTANCE_KEY", "k") |
| + t.Setenv("SHEETS_OWNERS", "") |
| + if TeamConfigFromEnv() != nil { |
| + t.Fatal("no team variables made a team config") |
| + } |
| + if _, err := LoadAuthEnv(quietLogger()); err == nil || !strings.Contains(err.Error(), "SHEETS_OWNERS") { |
| + t.Fatalf("allowlist mode without SHEETS_OWNERS = %v, want the old refusal", err) |
| + } |
| + t.Setenv("SHEETS_TEAM_ROSTER_TOKEN", "x") |
| + cfg := TeamConfigFromEnv() |
| + if cfg == nil || cfg.RosterToken != "x" || cfg.TeamID != "" { |
| + t.Fatal("one team variable was not a (partial) team config") |
| + } |
| + env, err := LoadAuthEnv(quietLogger()) |
| + if err != nil || env.Team == nil || len(env.Owners) != 0 { |
| + t.Fatalf("team mode still required SHEETS_OWNERS: %v", err) |
| + } |
| + f := newHomeFixture(t) |
| + if err := f.app.ConfigureTeam(env.Team); !errors.Is(err, errTeamConfig) { |
| + t.Error("a partial team config was accepted") |
| + } |
| +} |
| + |
| +// The marker: once activated, the database refuses to boot without team |
| +// configuration, and refuses a different binding. The triggers refuse |
| +// rewriting it; a database never activated boots as before. |
| +func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| + ctx := context.Background() |
| + f := newTeamFixture(t) |
| + d, err := f.app.db.DB() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, activated, err := teamstate.Required(ctx, d) |
| + if err != nil || !activated || len(got) != 43 { |
| + t.Fatalf("ConfigureTeam committed no marker: %v", err) |
| + } |
| + if _, err := BootSchemaFor(ctx, d, false); !errors.Is(err, errTeamConfig) { |
| + t.Error("an activated database booted without team configuration") |
| + } |
| + if s, err := BootSchemaFor(ctx, d, true); err != nil || s != TeamBootSchema { |
| + t.Error("an activated database refused its team configuration") |
| + } |
| + if _, err := d.Exec("UPDATE sheets_team_required SET bindings=?", strings.Repeat("A", 43)); err == nil { |
| + t.Error("the marker was rewritten") |
| + } |
| + if _, err := d.Exec("DELETE FROM sheets_team_required"); err == nil { |
| + t.Error("the marker was deleted") |
| + } |
| + |
| + // Same database, another team's record: refused. |
| + other := teamTestBindings() |
| + other.Team = "TeamB" |
| + cfg, _ := teamConfigFor(t, other) |
| + cfg.TeamID = "TeamB" |
| + f.app.team = nil |
| + if err := f.app.ConfigureTeam(cfg); !errors.Is(err, errTeamConfig) { |
| + t.Errorf("a different binding = %v, want refusal", err) |
| + } |
| + |
| + // A database never activated: BootSchema, as before. |
| + fresh, err := rdb.Open(filepath.Join(t.TempDir(), "fresh.db"), quietLogger()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { fresh.Close() }) |
| + if s, err := BootSchemaFor(ctx, fresh.Writer(), false); err != nil || s != BootSchema { |
| + t.Error("a fresh database did not boot in allowlist mode") |
| + } |
| + // Team schema applied but never activated (a team boot refused after |
| + // migrating): still allowlist-capable, and BootSchema re-applies. |
| + if _, err := migrate.Apply(ctx, fresh, TeamBootSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s, err := BootSchemaFor(ctx, fresh.Writer(), false); err != nil || s != BootSchema { |
| + t.Fatal("an unactivated team schema locked the database") |
| + } |
| + if _, err := migrate.Apply(ctx, fresh, BootSchema); err != nil { |
| + t.Fatalf("BootSchema over an unactivated team schema: %v", err) |
| + } |
| +} |
diff --git a/internal/sheets/team_fixture_test.go b/internal/sheets/team_fixture_test.go| new file mode 100644 |
| index 0000000..46bb550 |
| --- /dev/null |
| +++ b/internal/sheets/team_fixture_test.go |
| @@ -0,0 +1,193 @@ |
| +package sheets |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| +) |
| + |
| +// Team mode's fixture: Home configured exactly as newHomeFixture does, a |
| +// directory that answers the roster in memory from a member list a test |
| +// can change or take down, and a roster clock a test can step past the |
| +// lease. Mirrors Docs' testTeamRoster. |
| + |
| +const ( |
| + teamTestDirectory = "https://home.example.com" |
| + teamTestTeam = "TeamA" |
| +) |
| + |
| +// teamSubject is a well-formed person ref: "pr_" and 26 base32 letters. |
| +func teamSubject(c byte) string { return "pr_" + strings.Repeat(string(c), 26) } |
| + |
| +type teamTestClock struct { |
| + mu sync.Mutex |
| + base time.Time |
| + elapsed time.Duration |
| +} |
| + |
| +func (c *teamTestClock) Now() (time.Time, time.Duration) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.base.Add(c.elapsed), c.elapsed |
| +} |
| + |
| +func (c *teamTestClock) step(d time.Duration) { |
| + c.mu.Lock() |
| + c.elapsed += d |
| + c.mu.Unlock() |
| +} |
| + |
| +// teamTestDirectoryServer signs roster pages for the current members. |
| +type teamTestDirectoryServer struct { |
| + mu sync.Mutex |
| + key *family.Keypair |
| + bindings roster.Bindings |
| + generation string |
| + epoch int64 |
| + members map[string]string |
| + down bool |
| + fetches int |
| +} |
| + |
| +func (d *teamTestDirectoryServer) set(subject, role string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + if role == "" { |
| + delete(d.members, subject) |
| + } else { |
| + d.members[subject] = role |
| + } |
| + d.epoch++ |
| +} |
| + |
| +func (d *teamTestDirectoryServer) setDown(down bool) { |
| + d.mu.Lock() |
| + d.down = down |
| + d.mu.Unlock() |
| +} |
| + |
| +func (d *teamTestDirectoryServer) 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 |
| +} |
| + |
| +// teamConfigFor signs a provisioning record for bindings with a fresh |
| +// operator key, and returns the TeamConfig that carries it plus the |
| +// directory that will answer for it. |
| +func teamConfigFor(t *testing.T, b roster.Bindings) (*TeamConfig, *teamTestDirectoryServer) { |
| + t.Helper() |
| + op, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fixed := func(n byte) string { return base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{n}, 32)) } |
| + 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, _ := json.Marshal([]roster.Key{{ID: "operator1", Public: base64.RawURLEncoding.EncodeToString(op.SignPub())}}) |
| + dir := &teamTestDirectoryServer{key: key, bindings: b, generation: p.Generation, epoch: 1, members: map[string]string{}} |
| + cfg := &TeamConfig{transport: dir, TeamID: b.Team, DirectoryOrigin: b.Directory, |
| + ProvisioningBase64: base64.StdEncoding.EncodeToString(raw), OperatorKeysBase64: base64.StdEncoding.EncodeToString(keys), RosterToken: fixed(7)} |
| + return cfg, dir |
| +} |
| + |
| +func teamTestBindings() roster.Bindings { |
| + return roster.Bindings{Issuer: homeTestIssuer, Directory: teamTestDirectory, Consumer: "sheets-preview", App: "sheets", Team: teamTestTeam, Audience: testOrigin} |
| +} |
| + |
| +type teamFixture struct { |
| + *homeFixture |
| + dir *teamTestDirectoryServer |
| + clock *teamTestClock |
| + cfg *TeamConfig |
| +} |
| + |
| +// newTeamFixture is a team-mode instance. owners is SHEETS_OWNERS, which |
| +// in team mode only admits local sign-in; pass none for Alta's shape. |
| +func newTeamFixture(t *testing.T, owners ...string) *teamFixture { |
| + t.Helper() |
| + return newTeamFixtureWith(t, "", owners...) |
| +} |
| + |
| +// newTeamFixtureWith sets HOME_DIRECTORY_ORIGIN too, which the dashboard |
| +// feed needs. |
| +func newTeamFixtureWith(t *testing.T, directory string, owners ...string) *teamFixture { |
| + t.Helper() |
| + app, _ := appWithSchema(t, testOrigin, TeamBootSchema, owners...) |
| + f := homeOn(t, app, directory) |
| + cfg, dir := teamConfigFor(t, teamTestBindings()) |
| + clock := &teamTestClock{base: time.Now()} |
| + cfg.clock = clock |
| + if err := app.ConfigureTeam(cfg); err != nil { |
| + t.Fatalf("ConfigureTeam: %v", err) |
| + } |
| + return &teamFixture{homeFixture: f, dir: dir, clock: clock, cfg: cfg} |
| +} |
| + |
| +// signInHome runs a full Home exchange for subject from a clean jar, and |
| +// returns the finish response. |
| +func (f *teamFixture) signInHome(t *testing.T, subject string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + f.jar = map[string]*http.Cookie{} |
| + start := f.request(t, "GET", "/auth/start?return_to=%2Fsheets", nil, false) |
| + return f.exchange(t, start, subject) |
| +} |
| + |
| +// refreshed steps the roster clock past the refresh point and waits for |
| +// the refresh, so the next request sees the directory's current list. |
| +func (f *teamFixture) refreshed(t *testing.T) { |
| + t.Helper() |
| + f.clock.step(roster.RefreshAfter + time.Second) |
| + if err := f.app.team.cache.Refresh(t.Context()); err != nil { |
| + t.Fatalf("roster refresh: %v", err) |
| + } |
| +} |
| + |
| +// expired takes the directory down and steps past the lease: Unknown. |
| +func (f *teamFixture) expired(t *testing.T) { |
| + t.Helper() |
| + f.dir.setDown(true) |
| + f.clock.step(roster.MaximumAge + time.Second) |
| +} |
| + |
| +func (f *teamFixture) get(t *testing.T, path string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return f.request(t, "GET", path, nil, false) |
| +} |
diff --git a/internal/sheets/team_home.go b/internal/sheets/team_home.go| new file mode 100644 |
| index 0000000..3f99ac9 |
| --- /dev/null |
| +++ b/internal/sheets/team_home.go |
| @@ -0,0 +1,174 @@ |
| +package sheets |
| + |
| +// Home sign-in in team mode. connect's bridge completes an assertion only |
| +// for a subject with an account link here, and refuses the rest as |
| +// "unknown" — right for an allowlist instance, where nobody may enter on a |
| +// Home identity alone. In team mode a roster member who has never had a |
| +// local account must be able to, so the ordinary (non-link) completion is |
| +// this file's: the same exchange store, the same checks connect makes, plus |
| +// one step connect does not have. An unknown subject the roster says is a |
| +// Member right now gets an addressless member (teamstate.EnsureHomeMember). |
| +// |
| +// That member is identity, never standing: every request after this one |
| +// asks the roster again (team_access.go). The link flow (the init cookie) |
| +// and every malformed-cookie refusal stay connect's. |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +// connect's cookie names (connect/bridge.go). Read here only to decide |
| +// whether a finish is the link flow, and to hand every malformed case to |
| +// connect's own refusal. |
| +const ( |
| + homeInitCookie = "__Host-oficina-home-init" |
| + homeProofCookie = "__Host-oficina-home-proof" |
| +) |
| + |
| +var errTeamRefused = errors.New("sheets: team sign-in refused") |
| + |
| +type teamFinishKey struct{} |
| + |
| +type teamFinishResult struct { |
| + state string |
| + status int |
| +} |
| + |
| +// homeCookieState is connect's homeCookie: absent, or exactly one |
| +// canonical 32-byte base64url value. Anything else is malformed. |
| +func homeCookieState(r *http.Request, name string) (present, valid bool) { |
| + count, value := 0, "" |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + count++ |
| + value = c.Value |
| + } |
| + } |
| + if count == 0 { |
| + return false, true |
| + } |
| + if count != 1 || len(value) != 43 { |
| + return true, false |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| + return true, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == value |
| +} |
| + |
| +// homeFinish is GET /auth/finish. Outside team mode it is connect's. |
| +func (a *App) homeFinish(w http.ResponseWriter, r *http.Request) { |
| + if a.team == nil { |
| + a.home.Finish(w, r) |
| + return |
| + } |
| + initPresent, initValid := homeCookieState(r, homeInitCookie) |
| + _, proofValid := homeCookieState(r, homeProofCookie) |
| + _, sessionValid := homeCookieState(r, a.homeSessions.CookieName()) |
| + if initPresent || !initValid || !proofValid || !sessionValid { |
| + a.home.Finish(w, r) |
| + return |
| + } |
| + result := &teamFinishResult{} |
| + a.team.finish.Finish(w, r.WithContext(context.WithValue(r.Context(), teamFinishKey{}, result))) |
| +} |
| + |
| +func (a *App) teamFail(w http.ResponseWriter, r *http.Request, status int) { |
| + state := "failed" |
| + if result, ok := r.Context().Value(teamFinishKey{}).(*teamFinishResult); ok && result.state != "" { |
| + state, status = result.state, result.status |
| + } |
| + a.homeRender(w, r, state, "", status) |
| +} |
| + |
| +func teamReject(r *http.Request, state string, status int) error { |
| + if result, ok := r.Context().Value(teamFinishKey{}).(*teamFinishResult); ok { |
| + result.state, result.status = state, status |
| + } |
| + return errTeamRefused |
| +} |
| + |
| +// teamCurrentSubject is connect's CurrentSubject: the Home subject of an |
| +// existing Home session, which the exchange refuses to replace with a |
| +// different one. |
| +func (a *App) teamCurrentSubject(r *http.Request) string { |
| + if s, ok := a.homeSessions.From(r); ok && s.Method == connect.HomeMethod { |
| + return s.Subject |
| + } |
| + return "" |
| +} |
| + |
| +// sessionMemberID is the member an existing session already is, read |
| +// without creating anything. |
| +func (a *App) sessionMemberID(ctx context.Context, s sessions.Session) (int64, error) { |
| + switch s.Method { |
| + case connect.HomeMethod: |
| + return a.homeMemberID(ctx, s.Subject) |
| + case "magiclink", "keymail": |
| + id, err := a.localMemberID(ctx, s.Subject) |
| + if err != nil { |
| + return 0, teamstate.ErrRefused |
| + } |
| + return id, nil |
| + } |
| + return 0, teamstate.ErrRefused |
| +} |
| + |
| +// teamComplete runs after the exchange has verified and consumed the |
| +// assertion. Like connect's ordinary completion it never matches an |
| +// address and never merges accounts; unlike it, it lets a roster member |
| +// with no account here in. |
| +func (a *App) teamComplete(w http.ResponseWriter, r *http.Request, claims assertion.Claims) error { |
| + t, ctx := a.team, r.Context() |
| + if claims.Issuer != t.bindings.Issuer { |
| + return teamReject(r, "failed", http.StatusForbidden) |
| + } |
| + id, err := a.homeMemberID(ctx, claims.Subject) |
| + known := err == nil |
| + if err != nil && !errors.Is(err, teamstate.ErrRefused) { |
| + return teamReject(r, "failed", http.StatusServiceUnavailable) |
| + } |
| + if current, ok := a.homeSessions.From(r); ok { |
| + // Somebody is already signed in here. The arrival must be that |
| + // same person; an unknown identity is refused before anything is |
| + // allocated for it. |
| + if !known { |
| + return teamReject(r, "failed", http.StatusForbidden) |
| + } |
| + existing, err := a.sessionMemberID(ctx, current) |
| + if errors.Is(err, errTeamUnavailable) { |
| + return teamReject(r, "failed", http.StatusServiceUnavailable) |
| + } |
| + if err != nil || existing != id { |
| + return teamReject(r, "failed", http.StatusForbidden) |
| + } |
| + } else if !known { |
| + d := t.check(ctx, claims.Subject) |
| + switch { |
| + case d.State == roster.Member && d.Lease.Valid(): |
| + if _, err := teamstate.EnsureHomeMember(ctx, t.db, t.bindings.Issuer, claims.Subject); err != nil { |
| + if errors.Is(err, teamstate.ErrRefused) { |
| + return teamReject(r, "failed", http.StatusForbidden) |
| + } |
| + return teamReject(r, "failed", http.StatusServiceUnavailable) |
| + } |
| + case d.State == roster.NotMember: |
| + return teamReject(r, "unknown", http.StatusForbidden) |
| + default: |
| + return teamReject(r, "failed", http.StatusServiceUnavailable) |
| + } |
| + } |
| + if err := a.homeSessions.SignIn(w, r, sessions.Session{Subject: claims.Subject, Method: connect.HomeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}); err != nil { |
| + return errTeamUnavailable |
| + } |
| + return nil |
| +} |
diff --git a/internal/sheets/team_owner.go b/internal/sheets/team_owner.go| new file mode 100644 |
| index 0000000..55143de |
| --- /dev/null |
| +++ b/internal/sheets/team_owner.go |
| @@ -0,0 +1,48 @@ |
| +package sheets |
| + |
| +// Team mode's roster-owner rule — RULED by Paul, 2026-10-28, on |
| +// oficina/sheets #52: team owners can share orphaned sheets. |
| +// |
| +// A sheet's ownership is its owner grants. In team mode the creator's own |
| +// grant counts only while the roster says Member (ownGrantIgnored), so |
| +// removing a sheet's sole owner from the team leaves a sheet the team can |
| +// still edit and nobody can share. A roster owner therefore holds |
| +// SheetOwner on any sheet with no live owner grant, where live means |
| +// given by somebody else (a share), or held by somebody the roster says |
| +// is a Member — or whose standing cannot be read right now, which is not |
| +// "gone". Nothing is written: the moment the roster owner gives somebody |
| +// an owner grant, or the departed owner is re-added, the sheet has a live |
| +// owner again and this rule stops applying. |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// orphanedForRosterOwner reports whether m is a roster owner and the sheet |
| +// has no live owner grant. Outside team mode it is always false. It asks |
| +// the roster about each owner grant holder, never under the SQLite writer: |
| +// roleFor is not called inside a transaction. |
| +func (a *App) orphanedForRosterOwner(sheetID uint64, m Member) bool { |
| + if a.team == nil || a.teamRole(m) != TeamOwner { |
| + return false |
| + } |
| + var owners []Grant |
| + if err := a.db.Where("sheet_id = ? AND role = ?", sheetID, string(SheetOwner)).Find(&owners).Error; err != nil { |
| + return false // cannot tell is not orphaned |
| + } |
| + for _, g := range owners { |
| + if g.GrantedBy != g.MemberID { |
| + return false // a share: live whatever the roster says |
| + } |
| + holder, ok := a.memberByID(g.MemberID) |
| + if !ok { |
| + return false |
| + } |
| + if a.withStanding(context.Background(), holder).team.state() != roster.NotMember { |
| + return false // a current Member, or standing unknown |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/sheets/team_probe.go b/internal/sheets/team_probe.go| new file mode 100644 |
| index 0000000..92bc4df |
| --- /dev/null |
| +++ b/internal/sheets/team_probe.go |
| @@ -0,0 +1,77 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// teamProbePath is the readiness probe Alta polls at provisioning step 11, |
| +// before it activates this instance in Home's directory (Home |
| +// implementation/team-members.md §7; Alta provision/steps.go TeamProbe). |
| +// Docs' internal/docs/team_probe.go, with the same shape and answers. |
| +// |
| +// It is unauthenticated and answers only {team_mode, consumer, roster}: |
| +// whether this instance runs in team mode, the consumer ID its verified |
| +// provisioning record names, and how its roster cache stands. No account |
| +// data — no subject, role, member count, address, team ID or issuer — and |
| +// nothing that differs with who is asking. With team mode off it answers |
| +// {"team_mode":false} and nothing else. |
| +const teamProbePath = "/api/team" |
| + |
| +type teamProbe struct { |
| + TeamMode bool `json:"team_mode"` |
| + Consumer string `json:"consumer,omitempty"` |
| + Roster string `json:"roster,omitempty"` |
| +} |
| + |
| +// rosterProbeSubject is a well-formed person ref the probe asks the cache |
| +// about. Its answer is never used, only whether there was one: Member or |
| +// NotMember both mean the cache holds a complete roster younger than |
| +// roster.MaximumAge, which is what "ok" claims. |
| +var rosterProbeSubject = "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 the cache starts a refresh when one is due and waits for it (at |
| +// most roster.FetchTimeout), exactly as a signed-in request does — which |
| +// is what lets Alta's polling pull the first roster while Home's verify |
| +// window is open. The cache's own single flight and RetryAfter backoff |
| +// bound how often an unauthenticated caller can make this instance ask |
| +// the directory. |
| +func (t *teamRuntime) rosterState(ctx context.Context) string { |
| + if t.check(ctx, rosterProbeSubject).State != roster.Unknown { |
| + return "ok" |
| + } |
| + if t.rosterHeld.Load() { |
| + return "stale" |
| + } |
| + return "unknown" |
| +} |
| + |
| +func (a *App) handleTeamProbe(w http.ResponseWriter, r *http.Request) { |
| + probe := teamProbe{} |
| + if a.team != nil { |
| + probe = teamProbe{TeamMode: true, Consumer: a.team.bindings.Consumer, Roster: a.team.rosterState(r.Context())} |
| + } |
| + body, err := json.Marshal(probe) |
| + if err != nil { |
| + a.fail(w, r, err) |
| + 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 since gone stale. |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| + _, _ = w.Write(body) |
| +} |
diff --git a/internal/sheets/team_probe_test.go b/internal/sheets/team_probe_test.go| new file mode 100644 |
| index 0000000..1bef1fa |
| --- /dev/null |
| +++ b/internal/sheets/team_probe_test.go |
| @@ -0,0 +1,74 @@ |
| +package sheets |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +func probe(t *testing.T, app *App) (*httptest.ResponseRecorder, map[string]any) { |
| + t.Helper() |
| + rec := do(t, app, httptest.NewRequest(http.MethodGet, testOrigin+teamProbePath, nil)) |
| + var body map[string]any |
| + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil { |
| + t.Fatalf("probe = %d %q", rec.Code, rec.Body.String()) |
| + } |
| + if rec.Header().Get("Cache-Control") != "no-store" || !strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") { |
| + t.Errorf("probe headers: %v", rec.Header()) |
| + } |
| + return rec, body |
| +} |
| + |
| +// With team mode off the probe says so and nothing else. |
| +func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| + app, _ := appWithOrigin(t, testOrigin) |
| + if rec, _ := probe(t, app); rec.Body.String() != `{"team_mode":false}` { |
| + t.Fatalf("team-off probe = %q", rec.Body.String()) |
| + } |
| +} |
| + |
| +// unknown before any roster, ok once one is held, stale when it ages out |
| +// with the directory down — and never a word of account data, whoever |
| +// asks, signed in or not. |
| +func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| + f := newTeamFixture(t) |
| + a := teamSubject('a') |
| + f.dir.set(a, "owner") |
| + f.dir.setDown(true) |
| + if _, body := probe(t, f.app); body["roster"] != "unknown" || body["team_mode"] != true || body["consumer"] != "sheets-preview" { |
| + t.Fatalf("probe before any roster = %v", body) |
| + } |
| + f.dir.setDown(false) |
| + f.clock.step(roster.RetryAfter + time.Second) |
| + _, body := probe(t, f.app) |
| + if body["roster"] != "ok" { |
| + t.Fatalf("probe with a roster = %v", body) |
| + } |
| + f.signInHome(t, a) |
| + signedIn := httptest.NewRequest(http.MethodGet, testOrigin+teamProbePath, nil) |
| + for _, c := range f.jar { |
| + signedIn.AddCookie(c) |
| + } |
| + rec := do(t, f.app, signedIn) |
| + if len(body) != 3 { |
| + t.Errorf("probe fields = %v, want exactly team_mode, consumer, roster", body) |
| + } |
| + for _, leak := range []string{a, teamTestTeam, homeTestIssuer, teamTestDirectory, "owner", "member", "@"} { |
| + if strings.Contains(rec.Body.String(), leak) { |
| + t.Errorf("probe for a signed-in owner carries %q: %s", leak, rec.Body.String()) |
| + } |
| + } |
| + anonymous, _ := probe(t, f.app) |
| + if rec.Body.String() != anonymous.Body.String() { |
| + t.Errorf("probe differs by who asks: %q vs %q", rec.Body.String(), anonymous.Body.String()) |
| + } |
| + f.expired(t) |
| + if _, body := probe(t, f.app); body["roster"] != "stale" { |
| + t.Fatalf("probe past the lease = %v", body) |
| + } |
| +} |
diff --git a/internal/sheets/team_review_test.go b/internal/sheets/team_review_test.go| new file mode 100644 |
| index 0000000..822ca8b |
| --- /dev/null |
| +++ b/internal/sheets/team_review_test.go |
| @@ -0,0 +1,248 @@ |
| +package sheets |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/dashboard" |
| + "github.com/go-json-experiment/json" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +// Tests added for Fable's review of #52: each kills a mutant that had |
| +// survived the first round. |
| + |
| +func (f *teamFixture) getHTML(t *testing.T, path string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest("GET", testOrigin+path, nil) |
| + r.Header.Set("Accept", "text/html") |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + f.app.Router().ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +// A Home-only member is signed in as far as the chrome is concerned: the |
| +// account menu and its Sign out render, and /signin sends them on. |
| +func TestTeamHomeOnlyMemberGetsSignedInChrome(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.dir.set(teamSubject('a'), "member") |
| + f.signInHome(t, teamSubject('a')) |
| + page := f.getHTML(t, "/sheets") |
| + if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), `action="/signout"`) { |
| + t.Fatalf("Home-only member's list = %d without the account menu's sign out", page.Code) |
| + } |
| + if strings.Contains(page.Body.String(), `href="/signin`) { |
| + t.Error("a signed-in Home-only member was offered Sign in") |
| + } |
| + if rec := f.get(t, "/signin"); rec.Code != http.StatusSeeOther { |
| + t.Errorf("/signin for a signed-in Home-only member = %d, want 303", rec.Code) |
| + } |
| +} |
| + |
| +// The dashboard feed asks the roster: team sheets while a member, shares |
| +// only once removed, unavailable — not short — under Unknown. |
| +func TestTeamDashboardFeedFollowsTheRoster(t *testing.T) { |
| + t.Setenv("OFICINA_DASHBOARD_TEAM", "blue") |
| + f := newTeamFixtureWith(t, "https://oficina.example.test") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + teamSheet(t, f, "Team plan") |
| + shared := teamSheet(t, f, "Shared") |
| + id, err := teamstate.HomeMember(t.Context(), f.app.team.db, homeTestIssuer, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + colleague, _ := f.app.memberFor("colleague@example.com") |
| + if err := f.app.db.Create(&Grant{SheetID: shared.ID, MemberID: uint64(id), Role: string(SheetViewer), GrantedBy: colleague.ID}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + feed := func() (int, []string) { |
| + jti, _ := dashboard.ID() |
| + nonce, _ := dashboard.ID() |
| + now := time.Now().Unix() |
| + token, err := dashboard.Sign(f.key, dashboard.Claims{Version: 1, Issuer: homeTestIssuer, Audience: testOrigin, Directory: "https://oficina.example.test", Subject: a, Team: "blue", Purpose: "dashboard-read", KeyID: "key", ID: jti, Nonce: nonce, Issued: now, Expires: now + 120}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest("GET", testOrigin+dashboard.Path, nil) |
| + r.Header.Set("Authorization", "Bearer "+token) |
| + w := httptest.NewRecorder() |
| + f.app.Router().ServeHTTP(w, r) |
| + var data dashboard.Response |
| + var titles []string |
| + if w.Code == http.StatusOK && json.Unmarshal(w.Body.Bytes(), &data) == nil { |
| + for _, it := range data.Items { |
| + titles = append(titles, it.Title) |
| + } |
| + } |
| + return w.Code, titles |
| + } |
| + if code, titles := feed(); code != http.StatusOK || len(titles) != 2 { |
| + t.Fatalf("member's feed = %d %v, want both sheets", code, titles) |
| + } |
| + f.dir.set(a, "") |
| + f.refreshed(t) |
| + if code, titles := feed(); code != http.StatusOK || len(titles) != 1 || titles[0] != "Shared" { |
| + t.Fatalf("removed member's feed = %d %v, want the share only", code, titles) |
| + } |
| + f.dir.set(a, "member") |
| + f.refreshed(t) |
| + f.expired(t) |
| + if code, titles := feed(); code == http.StatusOK || len(titles) != 0 { |
| + t.Fatalf("feed under Unknown = %d %v, want unavailable", code, titles) |
| + } |
| +} |
| + |
| +// A link stored under another issuer refuses activation, and leaves no |
| +// marker behind. |
| +func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| + app, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| + homeOn(t, app, "") |
| + m, err := app.memberFor("linked@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := app.db.Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)", "https://id.other.example", teamSubject('f'), m.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg, _ := teamConfigFor(t, teamTestBindings()) |
| + if err := app.ConfigureTeam(cfg); !errors.Is(err, errTeamConfig) { |
| + t.Fatalf("ConfigureTeam over a foreign issuer's link = %v, want refusal", err) |
| + } |
| + d, _ := app.db.DB() |
| + if _, activated, err := teamstate.Required(t.Context(), d); err != nil || activated { |
| + t.Fatal("a refused activation left a marker") |
| + } |
| +} |
| + |
| +// connect's same-person rule: a known Home-only member arriving over |
| +// somebody else's live local session is refused, and that session stays. |
| +func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| + f := newTeamFixture(t) |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + f.jar = map[string]*http.Cookie{} |
| + f.local(t, "x@example.com") |
| + local := f.jar[f.app.homeSessions.CookieName()] |
| + start := f.request(t, "GET", "/auth/start?return_to=%2Fsheets", nil, false) |
| + if fin := f.exchange(t, start, a); fin.Code != http.StatusForbidden { |
| + t.Fatalf("known member over another local session = %d, want 403", fin.Code) |
| + } |
| + if got := f.jar[f.app.homeSessions.CookieName()]; got == nil || got.Value != local.Value { |
| + t.Fatal("the local session did not survive the refused arrival") |
| + } |
| + if m := f.viewer(t); m.Address != "x@example.com" { |
| + t.Fatalf("the session now acts as %q", m.Label()) |
| + } |
| +} |
| + |
| +// Paul, 2026-10-28: team owners can share orphaned sheets. A roster owner |
| +// holds SheetOwner on a sheet with no live owner grant; a roster member |
| +// does not; a sheet with a live owner is untouched; and the rule stops |
| +// applying the moment the sheet has a live owner again. Home-only members |
| +// are labelled with their ref. |
| +func TestTeamRosterOwnerSharesOrphanedSheets(t *testing.T) { |
| + f := newTeamFixture(t) |
| + o, a, m := teamSubject('o'), teamSubject('a'), teamSubject('m') |
| + f.dir.set(o, "owner") |
| + f.dir.set(a, "member") |
| + f.dir.set(m, "member") |
| + create := func(subject, title string) string { |
| + f.signInHome(t, subject) |
| + rec := f.request(t, "POST", "/sheets", url.Values{"title": {title}}, false) |
| + if rec.Code != http.StatusSeeOther { |
| + t.Fatalf("%s create = %d", title, rec.Code) |
| + } |
| + return rec.Header().Get("Location") |
| + } |
| + orphan := create(a, "Orphan") |
| + live := create(m, "Live") |
| + f.dir.set(a, "") |
| + f.refreshed(t) |
| + |
| + f.signInHome(t, m) |
| + if rec := f.get(t, orphan+"/share"); rec.Code != http.StatusNotFound { |
| + t.Errorf("roster member on an orphaned sheet's sharing = %d, want 404", rec.Code) |
| + } |
| + f.signInHome(t, o) |
| + if rec := f.get(t, live+"/share"); rec.Code != http.StatusNotFound { |
| + t.Errorf("roster owner on a live-owned sheet's sharing = %d, want 404", rec.Code) |
| + } |
| + page := f.getHTML(t, orphan+"/share") |
| + if page.Code != http.StatusOK { |
| + t.Fatalf("roster owner on an orphaned sheet's sharing = %d, want 200", page.Code) |
| + } |
| + if !strings.Contains(page.Body.String(), teamLabel+" …"+a[len(a)-4:]) { |
| + t.Error("the departed Home-only owner is not labelled with their ref") |
| + } |
| + if rec := f.request(t, "POST", orphan+"/share", url.Values{"address": {"new@example.com"}, "role": {"owner"}}, false); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("roster owner sharing an orphaned sheet = %d", rec.Code) |
| + } |
| + if rec := f.get(t, orphan+"/share"); rec.Code != http.StatusNotFound { |
| + t.Errorf("after giving it a live owner, the roster owner's sharing = %d, want 404", rec.Code) |
| + } |
| +} |
| + |
| +// Revoking a current Home-only member's grant names them in the notice by |
| +// label and ref, never by an address they do not have. |
| +func TestTeamRevokeNoticeNamesAHomeOnlyMember(t *testing.T) { |
| + f := newTeamFixture(t) |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + rec := f.request(t, "POST", "/sheets", url.Values{"title": {"Mine"}}, false) |
| + sheet := rec.Header().Get("Location") |
| + if rec := f.request(t, "POST", sheet+"/share", url.Values{"address": {"new@example.com"}, "role": {"owner"}}, false); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("share = %d", rec.Code) |
| + } |
| + id, err := teamstate.HomeMember(t.Context(), f.app.team.db, homeTestIssuer, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.jar = map[string]*http.Cookie{} |
| + f.local(t, "new@example.com") |
| + revoke := f.request(t, "POST", sheet+"/share/revoke", url.Values{"member": {strconv.FormatInt(id, 10)}}, false) |
| + if revoke.Code != http.StatusSeeOther { |
| + t.Fatalf("revoke = %d", revoke.Code) |
| + } |
| + page := f.getHTML(t, revoke.Header().Get("Location")) |
| + want := "since " + teamLabel + " …" + a[len(a)-4:] + " is on the team" |
| + if !strings.Contains(page.Body.String(), want) { |
| + t.Fatalf("revoke notice does not name the Home-only member as %q", want) |
| + } |
| +} |
| + |
| +// O3: the roster-owner rule never reaches a sheet that does not exist — |
| +// deleted or still filling — so it cannot resurrect a deleted sheet's |
| +// sharing. |
| +func TestTeamRosterOwnerRuleSkipsDeletedSheets(t *testing.T) { |
| + f := newTeamFixture(t) |
| + o := teamSubject('o') |
| + f.dir.set(o, "owner") |
| + gone := teamSheet(t, f, "Gone") // its creator is not on the roster: orphaned |
| + f.signInHome(t, o) |
| + if rec := f.get(t, sheetPath(gone.ID)+"/share"); rec.Code != http.StatusOK { |
| + t.Fatalf("roster owner on an orphaned sheet's sharing = %d, want 200", rec.Code) |
| + } |
| + if err := f.app.db.Exec("UPDATE sheets SET deleted_at = ? WHERE id = ?", time.Now().UTC(), gone.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := f.get(t, sheetPath(gone.ID)+"/share"); rec.Code != http.StatusNotFound { |
| + t.Errorf("roster owner on a deleted sheet's sharing = %d, want 404", rec.Code) |
| + } |
| + if f.app.mayShare(gone.ID, f.viewer(t)) { |
| + t.Error("the roster-owner rule reached a deleted sheet") |
| + } |
| +} |
diff --git a/internal/sheets/team_stream_test.go b/internal/sheets/team_stream_test.go| new file mode 100644 |
| index 0000000..d2341b0 |
| --- /dev/null |
| +++ b/internal/sheets/team_stream_test.go |
| @@ -0,0 +1,129 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +func openTeamStream(t *testing.T, f *teamFixture, base string, s SheetSummary) *http.Response { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| + t.Cleanup(cancel) |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/api/sheets/%d/tabs/%d/stream", base, s.ID, s.TabID), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = strings.TrimPrefix(testOrigin, "https://") |
| + for _, c := range f.jar { |
| + req.AddCookie(c) |
| + } |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("stream = %d", resp.StatusCode) |
| + } |
| + return resp |
| +} |
| + |
| +// A silent stream must not outlive the lease its standing rests on. The |
| +// stream is opened a second before the lease ends with the directory |
| +// down; nothing is written to the tab, and the stream still says bye. |
| +func TestTeamStreamClosesAtLeaseExpiry(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + f.dir.setDown(true) |
| + f.clock.step(59 * time.Second) |
| + |
| + srv := liveServer(t, f.app) |
| + resp := openTeamStream(t, f, srv.URL, plan) |
| + waitForSubscriber(t, f.app, plan.TabID) |
| + f.clock.step(2 * time.Second) |
| + if got := readEventWithin(t, resp.Body, 5*time.Second); !strings.Contains(got, "access-changed") { |
| + t.Fatalf("a stream past its lease sent %q, want bye", got) |
| + } |
| +} |
| + |
| +// Renewal: at the lease deadline the stream asks again, and while the |
| +// roster still says Member it re-arms and carries on delivering. |
| +// |
| +// Set up so no refresh is in flight when the stream opens (one had just |
| +// failed, and the cache backs off), because a publish moves the cache's |
| +// version and ends every older lease: the stream opens on a lease with a |
| +// second left, the directory is back, and the deadline's re-check must |
| +// fetch a new roster to keep it open. |
| +func TestTeamStreamRenewsWhileStillAMember(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + f.clock.step(59 * time.Second) |
| + f.dir.setDown(true) |
| + if err := f.app.team.cache.Refresh(t.Context()); err == nil { |
| + t.Fatal("refresh succeeded with the directory down") |
| + } |
| + f.dir.setDown(false) |
| + |
| + srv := liveServer(t, f.app) |
| + resp := openTeamStream(t, f, srv.URL, plan) |
| + waitForSubscriber(t, f.app, plan.TabID) |
| + f.clock.step(6 * time.Second) // past the lease and the backoff |
| + time.Sleep(1500 * time.Millisecond) // past the stream's lease timer |
| + cells := fmt.Sprintf("/api/sheets/%d/tabs/%d/cells", plan.ID, plan.TabID) |
| + if post := postCellAs(t, f, cells, `{"r":0,"c":0,"raw":"still here"}`); post.Code != http.StatusOK { |
| + t.Fatalf("member write = %d %s", post.Code, post.Body.String()) |
| + } |
| + if got := readEventWithin(t, resp.Body, 5*time.Second); !strings.Contains(got, "still here") { |
| + t.Fatalf("renewed stream sent %q", got) |
| + } |
| +} |
| + |
| +func postCellAs(t *testing.T, f *teamFixture, path, body string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest(http.MethodPost, testOrigin+path, strings.NewReader(body)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Origin", testOrigin) |
| + for _, c := range f.jar { |
| + req.AddCookie(c) |
| + } |
| + return do(t, f.app, req) |
| +} |
| + |
| +// A decision held past its lease is not standing, even mid-request: the |
| +// lease is checked each time roleFor asks, not once at the door. |
| +func TestTeamLeaseEndsAHeldDecision(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.set(a, "member") |
| + f.signInHome(t, a) |
| + m := f.viewer(t) |
| + if !f.app.mayWrite(plan.ID, m) { |
| + t.Fatal("member cannot write a team sheet") |
| + } |
| + f.dir.setDown(true) |
| + f.clock.step(59 * time.Second) |
| + if !f.app.mayWrite(plan.ID, m) { |
| + t.Fatal("standing ended inside the lease") |
| + } |
| + f.clock.step(2 * time.Second) |
| + if f.app.mayWrite(plan.ID, m) || f.app.mayRead(plan.ID, m) { |
| + t.Fatal("a held decision outlived its lease") |
| + } |
| + if m.team.state() != roster.Unknown { |
| + t.Fatal("an expired lease was not Unknown") |
| + } |
| +} |
diff --git a/internal/sheets/teamstate/migrations/0001_team.sql b/internal/sheets/teamstate/migrations/0001_team.sql| new file mode 100644 |
| index 0000000..1870757 |
| --- /dev/null |
| +++ b/internal/sheets/teamstate/migrations/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; |
diff --git a/internal/sheets/teamstate/store.go b/internal/sheets/teamstate/store.go| new file mode 100644 |
| index 0000000..d9c8ce4 |
| --- /dev/null |
| +++ b/internal/sheets/teamstate/store.go |
| @@ -0,0 +1,220 @@ |
| +// Package teamstate keeps team mode's durable state: the mandatory-mode |
| +// marker, the opaque roster evidence, and the Home-only members a roster |
| +// admitted. It is Docs' teamstate (internal/docs/teamstate) with Sheets' |
| +// namespace, plus the Home-only identity table Docs keeps in its |
| +// principalstore: Sheets' local people are its members table, so a |
| +// Home-only person is a members row with no address. |
| +// |
| +// None of it is standing. A Home-only member row says who a Home subject |
| +// is on this instance, never whether they are on the team: that is the |
| +// roster's answer, asked again on every request. |
| +package teamstate |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "encoding/base64" |
| + "errors" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema follows Sheets' own and linkstore's: its triggers name members |
| +// and home_identity_links, so it is merged after both (TeamBootSchema). |
| +var Schema = migrate.MustFromFS(migrations, "sheets_team") |
| + |
| +var ( |
| + ErrRefused = errors.New("sheets team: refused") |
| + ErrUnavailable = errors.New("sheets team: unavailable") |
| +) |
| + |
| +func validBinding(s string) bool { |
| + b, e := base64.RawURLEncoding.DecodeString(s) |
| + return e == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s |
| +} |
| + |
| +// Required distinguishes a never-activated database from an unreadable |
| +// marker. It reads sqlite_master first, so it is safe on a database that |
| +// has never had the team schema applied. |
| +func Required(ctx context.Context, db *sql.DB) (string, bool, error) { |
| + var count int |
| + if e := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='sheets_team_required'").Scan(&count); e != nil { |
| + return "", false, ErrUnavailable |
| + } |
| + if count == 0 { |
| + return "", false, nil |
| + } |
| + var value string |
| + e := db.QueryRowContext(ctx, "SELECT bindings FROM sheets_team_required WHERE id=1").Scan(&value) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", false, nil |
| + } |
| + if e != nil { |
| + return "", false, ErrUnavailable |
| + } |
| + if !validBinding(value) { |
| + return "", false, ErrRefused |
| + } |
| + return value, true, nil |
| +} |
| + |
| +// Activate commits before the caller may serve requests or allocate |
| +// identities. It records an already-verified deployment binding, never |
| +// an owner or a roster. A database already bound to another binding is |
| +// refused, and the triggers refuse any rewrite. |
| +func Activate(ctx context.Context, db *sql.DB, binding string) error { |
| + if !validBinding(binding) { |
| + return ErrRefused |
| + } |
| + tx, e := db.BeginTx(ctx, nil) |
| + if e != nil { |
| + return ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + if _, e = tx.ExecContext(ctx, "INSERT INTO sheets_team_required(id,bindings) VALUES(1,?) ON CONFLICT(id) DO NOTHING", binding); e != nil { |
| + return ErrUnavailable |
| + } |
| + var got string |
| + if e = tx.QueryRowContext(ctx, "SELECT bindings FROM sheets_team_required WHERE id=1").Scan(&got); e != nil { |
| + return ErrUnavailable |
| + } |
| + if got != binding { |
| + return ErrRefused |
| + } |
| + if tx.Commit() != nil { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
| + |
| +// Evidence is roster.Durable over the replicated SQLite file: one |
| +// bounded atomic replacement and one bounded load of the cache's sealed |
| +// envelope, never decoded here. |
| +type Evidence struct{ DB *sql.DB } |
| + |
| +func (s Evidence) Load(ctx context.Context) ([]byte, error) { |
| + var b []byte |
| + e := s.DB.QueryRowContext(ctx, "SELECT payload FROM sheets_team_roster_evidence WHERE id=1").Scan(&b) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return nil, roster.ErrNoEvidence |
| + } |
| + if e != nil || len(b) > roster.EvidenceLimit+128 { |
| + return nil, ErrUnavailable |
| + } |
| + return b, nil |
| +} |
| + |
| +func (s Evidence) Save(ctx context.Context, b []byte) error { |
| + if len(b) == 0 || len(b) > roster.EvidenceLimit+128 { |
| + return ErrRefused |
| + } |
| + _, e := s.DB.ExecContext(ctx, "INSERT INTO sheets_team_roster_evidence(id,payload) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload", b) |
| + if e != nil { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
| + |
| +// HomeMember reads the member a Home-only identity was given. It never |
| +// creates one: ErrRefused means there is none. |
| +func HomeMember(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e := db.QueryRowContext(ctx, "SELECT member_id FROM sheets_team_home_members WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrRefused |
| + } |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// HomeSubject is the reverse: the Home subject a member is known by on |
| +// this instance, through a Home-only row or an explicit account link. |
| +// ErrRefused means neither, which is no standing, never an error. |
| +func HomeSubject(ctx context.Context, db *sql.DB, issuer string, member int64) (string, error) { |
| + var subject string |
| + e := db.QueryRowContext(ctx, `SELECT subject FROM sheets_team_home_members WHERE issuer=? AND member_id=? |
| + UNION ALL SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=? LIMIT 1`, issuer, member, issuer, member).Scan(&subject) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", ErrRefused |
| + } |
| + if e != nil { |
| + return "", ErrUnavailable |
| + } |
| + return subject, nil |
| +} |
| + |
| +// EnsureHomeMember gives a Home subject an addressless member, or |
| +// returns the one it already has. The caller must have just had a |
| +// current roster answer of Member for this subject: this function |
| +// records identity, not standing, and a later request asks the roster |
| +// again. A subject already linked to a local account is refused — that |
| +// person signs in as that account. |
| +func EnsureHomeMember(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) || issuer == "" { |
| + return 0, ErrRefused |
| + } |
| + tx, e := db.BeginTx(ctx, nil) |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + var linked int |
| + if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_identity_links WHERE issuer=? AND subject=?", issuer, subject).Scan(&linked); e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if linked != 0 { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e = tx.QueryRowContext(ctx, "SELECT member_id FROM sheets_team_home_members WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if e == nil { |
| + if tx.Commit() != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| + } |
| + if !errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrUnavailable |
| + } |
| + res, e := tx.ExecContext(ctx, "INSERT INTO members(address,team_role,created_at) VALUES(NULL,'guest',?)", time.Now().UTC()) |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if id, e = res.LastInsertId(); e != nil || id <= 0 { |
| + return 0, ErrUnavailable |
| + } |
| + if _, e = tx.ExecContext(ctx, "INSERT INTO sheets_team_home_members(issuer,subject,member_id) VALUES(?,?,?)", issuer, subject, id); e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if tx.Commit() != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// Opaque is a Home subject's shape: bounded, printable, and never an |
| +// address, so a subject can never be mistaken for one. |
| +func Opaque(s string) bool { |
| + if s == "" || len(s) > 512 || !utf8.ValidString(s) || strings.Contains(s, "@") { |
| + return false |
| + } |
| + for _, r := range s { |
| + if r <= 32 || r == 127 { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/sheets/teamstate/store_test.go b/internal/sheets/teamstate/store_test.go| new file mode 100644 |
| index 0000000..2572ddc |
| --- /dev/null |
| +++ b/internal/sheets/teamstate/store_test.go |
| @@ -0,0 +1,123 @@ |
| +package teamstate_test |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + rdb "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets" |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +const issuer = "https://id.example.com" |
| + |
| +func subject(c byte) string { return "pr_" + strings.Repeat(string(c), 26) } |
| + |
| +func openTeamDB(t *testing.T) *sql.DB { |
| + t.Helper() |
| + d, err := rdb.Open(filepath.Join(t.TempDir(), "team.db"), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if _, err := migrate.Apply(context.Background(), d, sheets.TeamBootSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + return d.Writer() |
| +} |
| + |
| +// A Home-only member is an addressless members row, made once per |
| +// subject, and never for a subject that is already an account link. |
| +func TestHomeOnlyMembersAreAddresslessAndUnique(t *testing.T) { |
| + ctx := context.Background() |
| + db := openTeamDB(t) |
| + id, err := teamstate.EnsureHomeMember(ctx, db, issuer, subject('a')) |
| + if err != nil || id <= 0 { |
| + t.Fatalf("EnsureHomeMember: %d %v", id, err) |
| + } |
| + again, err := teamstate.EnsureHomeMember(ctx, db, issuer, subject('a')) |
| + if err != nil || again != id { |
| + t.Fatalf("second EnsureHomeMember = %d %v, want %d", again, err, id) |
| + } |
| + var address sql.NullString |
| + if err := db.QueryRow("SELECT address FROM members WHERE id=?", id).Scan(&address); err != nil || address.Valid { |
| + t.Fatalf("Home-only member has an address: %v %v", address, err) |
| + } |
| + if got, err := teamstate.HomeMember(ctx, db, issuer, subject('a')); err != nil || got != id { |
| + t.Fatal("HomeMember did not find it") |
| + } |
| + if got, err := teamstate.HomeSubject(ctx, db, issuer, id); err != nil || got != subject('a') { |
| + t.Fatal("HomeSubject did not find it") |
| + } |
| + if _, err := teamstate.HomeMember(ctx, db, issuer, subject('b')); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatal("an unknown subject resolved") |
| + } |
| + for _, bad := range []string{"", "someone@example.com", "has space", strings.Repeat("x", 513)} { |
| + if _, err := teamstate.EnsureHomeMember(ctx, db, issuer, bad); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Errorf("subject %q accepted", bad) |
| + } |
| + } |
| + |
| + // A linked subject signs in as its account, never as a new member. |
| + if _, err := db.Exec("INSERT INTO members(address,team_role) VALUES('linked@example.com','guest')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,(SELECT id FROM members WHERE address='linked@example.com'))", issuer, subject('l')); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := teamstate.EnsureHomeMember(ctx, db, issuer, subject('l')); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatal("a linked subject got a Home-only member") |
| + } |
| + var linked int64 |
| + _ = db.QueryRow("SELECT id FROM members WHERE address='linked@example.com'").Scan(&linked) |
| + if got, err := teamstate.HomeSubject(ctx, db, issuer, linked); err != nil || got != subject('l') { |
| + t.Fatal("HomeSubject missed the account link") |
| + } |
| +} |
| + |
| +// The triggers hold the same lines against a direct write. |
| +func TestTeamTriggersRefuseDirectWrites(t *testing.T) { |
| + ctx := context.Background() |
| + db := openTeamDB(t) |
| + id, err := teamstate.EnsureHomeMember(ctx, db, issuer, subject('a')) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, stmt := range []string{ |
| + "INSERT INTO members(address,team_role) VALUES('x@example.com','guest')", |
| + "INSERT INTO members(address,team_role) VALUES(NULL,'guest')", |
| + "INSERT INTO members(address,team_role) VALUES('y@example.com','guest')", |
| + "INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('" + issuer + "','" + subject('l') + "',(SELECT id FROM members WHERE address='x@example.com'))", |
| + } { |
| + if _, err := db.Exec(stmt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for name, stmt := range map[string]string{ |
| + "map an addressed member": "INSERT INTO sheets_team_home_members(issuer,subject,member_id) VALUES('" + issuer + "','" + subject('c') + "',(SELECT id FROM members WHERE address='x@example.com'))", |
| + "link a Home-only subject": "INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('" + issuer + "','" + subject('a') + "',(SELECT id FROM members WHERE address='y@example.com'))", |
| + "link a Home-only member": "INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('" + issuer + "','" + subject('d') + "'," + itoa(id) + ")", |
| + "give a Home-only an address": "UPDATE members SET address='a@example.com' WHERE id=" + itoa(id), |
| + "delete a Home-only member": "DELETE FROM members WHERE id=" + itoa(id), |
| + "rewrite a Home-only mapping": "UPDATE sheets_team_home_members SET subject='" + subject('e') + "'", |
| + "delete a Home-only mapping": "DELETE FROM sheets_team_home_members", |
| + "store a non-blob evidence row": "INSERT INTO sheets_team_roster_evidence(id,payload) VALUES(1,'text')", |
| + "map a linked subject": "INSERT INTO sheets_team_home_members(issuer,subject,member_id) VALUES('" + issuer + "','" + subject('l') + "',(SELECT id FROM members WHERE address IS NULL AND id!=" + itoa(id) + "))", |
| + } { |
| + if _, err := db.Exec(stmt); err == nil { |
| + t.Errorf("%s: allowed", name) |
| + } |
| + } |
| + if err := teamstate.Activate(ctx, db, "short"); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Error("a malformed binding activated") |
| + } |
| +} |
| + |
| +func itoa(n int64) string { return strconv.FormatInt(n, 10) } |
diff --git a/internal/sheets/templates/share.html b/internal/sheets/templates/share.html| index 4656d23..6b7a8f5 100644 |
| --- a/internal/sheets/templates/share.html |
| +++ b/internal/sheets/templates/share.html |
| @@ -92,7 +92,7 @@ people you send it to. A link can never edit.</p> |
| {{range .Data.People}} |
| <li rst-lrow> |
| <div rst-row-main> |
| -<span>{{.Member.Address}}</span> |
| +<span>{{.Member.Label}}</span> |
| <span rst-row-sub>{{.Role}}{{if eq .Member.TeamRole "guest"}} · guest{{end}}</span> |
| </div> |
| <form method="post" action="/sheets/{{$sheet.ID}}/share/revoke"> |
diff --git a/internal/sheets/visible_sheets.go b/internal/sheets/visible_sheets.go| index 71793b9..0919d0e 100644 |
| --- a/internal/sheets/visible_sheets.go |
| +++ b/internal/sheets/visible_sheets.go |
| @@ -32,10 +32,16 @@ func (a *App) visibleSheetsLimited(ctx context.Context, m Member, limit int) ([] |
| q := a.db.WithContext(ctx).Model(&store.Sheet{}). |
| Where("sheets.deleted_at IS NULL AND sheets.filling_since IS NULL") |
| - switch TeamRole(m.TeamRole) { |
| + switch a.teamRole(m) { |
| case TeamOwner, TeamMember: |
| // The whole instance. One team, one set of sheets. |
| default: |
| + if a.team != nil { |
| + // Team mode: shares only. The creator's own grant is the |
| + // team rung's (ownGrantIgnored), and this person has none. |
| + q = q.Joins("JOIN grants ON grants.sheet_id = sheets.id AND grants.member_id = ? AND grants.granted_by != grants.member_id", m.ID) |
| + break |
| + } |
| // A guest sees exactly what they were granted. The join is an |
| // inner join precisely so a guest with no grants gets an empty |
| // list rather than everything. |