Sheets: re-point team mode onto home/teammode
Team configuration, the marker, the roster runtime, per-request standing and the /api/team probe are now Home's shared home/teammode package (Home main 67c12e3; implementation/teammode-package.md §6), and a Home-only member signs in through connect's own completion with its Unlinked/HomeOnly hooks (team_home_only.go). team_home.go and Sheets' private config, marker, evidence, access and probe code are gone. Sheets keeps its sheets_team migration set (the ledger checksums the whole file), roleFor/visibleSheets mapping, the members-table allocation, the stream timer and the orphan rule. teamstate keeps only the Home-only table. Pins: teammode, roster and connect at 67c12e3. Paul's ruling (2026-10-28): under Unknown standing the sheet list shows the person's shares with a "partial" notice instead of a 503, asked of the same Access after listing. NotMember is never partial; the dashboard feed stays unavailable; item pages stay a retryable 503. Fable's #52 deviation 7 closed: every write (cells, batch, table, undo and restore, format, size, rename, comments, view, share and revoke, links, create, import) runs teammode.Guard inside its own transaction via store.Guard, so a lease that lapses mid-write fails the commit. The marker's binding is now compared at boot, before migrating (teammode's BootSchema), so main verifies team settings before it migrates. Team-mode-off output is byte-identical (the list, sheet, share, table, comments, history and probe pages, HTML and JSON, diffed against ca78cc1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
65 files changed,
+1,377
−1,086
AGENTS.md+16 −4cmd/sheets/main.go+33 −21docs/superpowers/specs/2026-08-30-sheets-design.md+9 −1go.mod+3 −2go.sum+6 −4internal/sheets/app.go+15 −10internal/sheets/auth.go+7 −5internal/sheets/chrome_menu_test.go+1 −1internal/sheets/chrome_test.go+1 −1internal/sheets/comments.go+18 −10internal/sheets/dashboard.go+6 −11internal/sheets/dashboard_test.go+1 −1internal/sheets/grants.go+30 −23internal/sheets/grants_sheetstate_test.go+2 −2internal/sheets/grants_test.go+5 −5internal/sheets/handlers_cell_batch.go+4 −1internal/sheets/handlers_comments.go+8 −2internal/sheets/handlers_format.go+11 −4internal/sheets/handlers_grid.go+4 −1internal/sheets/handlers_history.go+10 −6internal/sheets/handlers_import.go+4 −1internal/sheets/handlers_import_hidden_test.go+4 −4internal/sheets/handlers_link.go+9 −3internal/sheets/handlers_rename.go+12 −5internal/sheets/handlers_share.go+9 −3internal/sheets/handlers_sheets.go+18 −10internal/sheets/handlers_size.go+8 −3internal/sheets/handlers_table.go+4 −1internal/sheets/handlers_view.go+4 −1internal/sheets/home.go+9 −3internal/sheets/home_routes.go+1 −1internal/sheets/home_test.go+5 −2internal/sheets/importlifecycle_test.go+6 −6internal/sheets/page.go+2 −6internal/sheets/sharelink.go+14 −8internal/sheets/sharelink_test.go+8 −8internal/sheets/sharelink_url_test.go+1 −1internal/sheets/sheetsvc.go+25 −20internal/sheets/sheetsvc_test.go+10 −10internal/sheets/signin_confirm_test.go+2 −2internal/sheets/store/guard.go+77 −0internal/sheets/store/handle_grid.go+21 −13internal/sheets/store/handle_report.go+7 −2internal/sheets/store/handle_set.go+52 −48internal/sheets/store/handle_sizes.go+19 −7internal/sheets/store/handle_write_batch.go+46 −39internal/sheets/stream_revoke_test.go+1 −1internal/sheets/team_access.go+49 −48internal/sheets/team_access_test.go+31 −17internal/sheets/team_answers.go+20 −4internal/sheets/team_config.go+67 −163internal/sheets/team_config_test.go+76 −34internal/sheets/team_fixture_test.go+46 −121internal/sheets/team_guard.go+88 −0internal/sheets/team_guard_test.go+293 −0internal/sheets/team_home.go+0 −174internal/sheets/team_home_only.go+68 −0internal/sheets/team_probe.go+9 −65internal/sheets/team_probe_test.go+4 −4internal/sheets/team_review_test.go+15 −16internal/sheets/team_stream_test.go+14 −14internal/sheets/teamstate/store.go+7 −95internal/sheets/teamstate/store_test.go+3 −1internal/sheets/templates/sheets.html+11 −2internal/sheets/viewspec.go+8 −5
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index b1cc58f..50b8e60 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -145,10 +145,22 @@ relying on remembering one, make it a test instead. |
| 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. |
| + connect's `Unlinked` hook in `team_home_only.go` only, behind |
| + `teammode.Runtime.AdmitUnlinked`). That row is identity, never standing: |
| + standing is the roster's answer on every request (`home/teammode`'s |
| + `Access`, `team_access.go`), and **`members.team_role` is never read in team |
| + mode** — reading it is how a removed owner kept access. Team configuration, |
| + the marker, the roster runtime and the probe are `home/teammode`'s; do not |
| + grow a private copy back. Without `SHEETS_TEAM_*`, every rule above stands |
| + unchanged. |
| +- **In team mode every write is guarded inside its own transaction** |
| + (`team_guard.go`, `store.Guard`): the handler's `roleFor` decides whether a |
| + write may start, `teammode.Guard` re-checks standing before and after the |
| + write, in the writer transaction, so a lease that lapses mid-write fails the |
| + commit. A new write path takes `a.writeGuard` (or `a.memberGuard` for |
| + create and import) and answers a refusal with `a.guardRefused`. |
| + `TestTeamEveryWriteRouteRefusesALapseBeforeCommit` lists every write route; |
| + add yours to it. |
| - **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. |
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go| index b69ec26..4a89a0a 100644 |
| --- a/cmd/sheets/main.go |
| +++ b/cmd/sheets/main.go |
| @@ -50,6 +50,28 @@ func main() { |
| } |
| defer d.Close() |
| + // Sign-in configuration is validated before anything serves. Every |
| + // failure here is one where continuing would produce an instance |
| + // that looks like it works: no mailer means magic links get written |
| + // to platform-held logs instead of emailed, and an empty allowlist |
| + // means anyone who can receive mail can hold a session. Both answer |
| + // /healthz perfectly well, which is why this is a hard exit and not |
| + // a warning. It reads the environment only, so it runs before the |
| + // schema is chosen: team mode's configuration decides that. |
| + authEnv, err := sheets.LoadAuthEnv(logger) |
| + if err != nil { |
| + logger.Error("sign-in", "err", err) |
| + os.Exit(1) |
| + } |
| + // Team mode's provisioning record is verified against configuration |
| + // alone (home/teammode), before anything migrates. nil with team |
| + // mode off. |
| + team, err := sheets.TeamSettings(authEnv.Team, authEnv.Home, authEnv.Origin) |
| + if err != nil { |
| + logger.Error("team mode unavailable") |
| + os.Exit(1) |
| + } |
| + |
| // Ledgered, once-at-boot, never re-run or reversed — see |
| // internal/sheets/migrations.go's Schema/BootSchema/Models and |
| // AGENTS.md's additive-only constraint. A boot that can't reconcile |
| @@ -59,11 +81,12 @@ func main() { |
| // |
| // 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) |
| + // SHEETS_TEAM_*, or with a different binding, 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(), team) |
| if err != nil { |
| logger.Error("team mode", "err", err) |
| os.Exit(1) |
| @@ -73,18 +96,6 @@ func main() { |
| os.Exit(1) |
| } |
| - // Sign-in configuration is validated before anything serves. Every |
| - // failure here is one where continuing would produce an instance |
| - // that looks like it works: no mailer means magic links get written |
| - // to platform-held logs instead of emailed, and an empty allowlist |
| - // means anyone who can receive mail can hold a session. Both answer |
| - // /healthz perfectly well, which is why this is a hard exit and not |
| - // a warning. |
| - authEnv, err := sheets.LoadAuthEnv(logger) |
| - if err != nil { |
| - logger.Error("sign-in", "err", err) |
| - os.Exit(1) |
| - } |
| // Same shape as the sign-in refusals above, and for the same |
| // reason: an instance with no DEK answers /healthz perfectly well |
| // and then fails on the first cell anybody types. The key arrives |
| @@ -105,6 +116,7 @@ func main() { |
| Sealer: sealer, |
| Origin: authEnv.Origin, |
| Admit: sheets.Admits(authEnv.Owners), |
| + Team: team, |
| }) |
| signin, err := sheets.NewAuth(d.Writer(), authEnv, logger, app) |
| @@ -117,10 +129,10 @@ 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 { |
| + // After Home, before serving: commits the team marker and starts the |
| + // roster cache. Without team settings it is a no-op; anything else |
| + // that fails refuses boot. |
| + if err := app.ConfigureTeam(); err != nil { |
| logger.Error("team mode unavailable") |
| os.Exit(1) |
| } |
diff --git a/docs/superpowers/specs/2026-08-30-sheets-design.md b/docs/superpowers/specs/2026-08-30-sheets-design.md| index 1220b06..b974d6f 100644 |
| --- a/docs/superpowers/specs/2026-08-30-sheets-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-sheets-design.md |
| @@ -460,7 +460,15 @@ 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 |
| +retryable 503 for anything a share does not reach). **Under Unknown the sheet |
| +list shows the person's shares with a "partial" notice, not a 503** (RULED |
| +by Paul, 2026-10-28, Home `implementation/teammode-package.md` §4): asked of |
| +the same standing the list was built with, never for NotMember (a guest's |
| +shares are their whole list); the cross-origin dashboard feed stays |
| +unavailable, and a sheet that needs standing stays a retryable 503. Standing |
| +is re-checked inside each write's own transaction, before and after it, so a |
| +lease that lapses mid-write fails the commit. The machinery is Home's |
| +`home/teammode` package and connect's Home-only hooks. `$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 |
diff --git a/go.mod b/go.mod| index 3a08496..33648a6 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -4,10 +4,11 @@ go 1.25.0 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| - amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d |
| + amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 |
| 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/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 |
| + amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| 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 bbf5bc7..8d2415a 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,13 +1,15 @@ |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw= |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| -amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d h1:9sVZBph2xUuejZt73DYaoCfoyvrvZCnuPHcyMsg562E= |
| -amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I= |
| 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/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk= |
| +amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| +amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+9cbTHE67Y4/SmW1sPH1NNWNwTceNFyMjTY= |
| +amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| 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 a7a907d..4595114 100644 |
| --- a/internal/sheets/app.go |
| +++ b/internal/sheets/app.go |
| @@ -8,6 +8,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/rastrillo/rastrillo/auth" |
| @@ -50,6 +51,9 @@ type Config struct { |
| // consulted before a link is SENT (admissionMailer) and at |
| // redemption (auth.Config.Authorize). See handleBegin. |
| Admit func(string) bool |
| + // Team is team mode's verified configuration (TeamSettings), nil |
| + // unless SHEETS_TEAM_* is set (team_config.go). |
| + Team *teammode.Settings |
| } |
| // App holds the wiring. One per process. |
| @@ -59,12 +63,12 @@ type App struct { |
| home *connect.Bridge |
| homeRoutes *connect.Routes |
| homeSessions *sessions.Sessions |
| - // homeCreds and homeRender are ConfigureHome's, kept for team mode. |
| - homeCreds *connect.DecodedCredentials |
| - homeRender func(http.ResponseWriter, *http.Request, string, string, int) |
| + homeCreds *connect.DecodedCredentials // ConfigureHome's, kept for team mode |
| // team is the roster runtime, nil unless SHEETS_TEAM_* configured |
| // team mode (team_config.go). Every team-mode branch keys on it. |
| - team *teamRuntime |
| + team *teamRuntime |
| + teamSettings *teammode.Settings |
| + teamTest |
| db *gorm.DB |
| auth *auth.Auth |
| sealer *seal.Sealer |
| @@ -103,12 +107,13 @@ type App struct { |
| // New builds an App. |
| func New(cfg Config) *App { |
| a := &App{ |
| - db: cfg.DB, |
| - auth: cfg.Auth, |
| - sealer: cfg.Sealer, |
| - origin: cfg.Origin, |
| - admit: cfg.Admit, |
| - hub: live.NewHub(), |
| + db: cfg.DB, |
| + auth: cfg.Auth, |
| + sealer: cfg.Sealer, |
| + origin: cfg.Origin, |
| + admit: cfg.Admit, |
| + hub: live.NewHub(), |
| + teamSettings: cfg.Team, |
| // nil logger means slog.Default(), which is exactly what main |
| // passes rastrillo everywhere else. |
| jobs: jobs.New(nil), |
diff --git a/internal/sheets/auth.go b/internal/sheets/auth.go| index 5c4d0df..b50f604 100644 |
| --- a/internal/sheets/auth.go |
| +++ b/internal/sheets/auth.go |
| @@ -3,6 +3,7 @@ package sheets |
| import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| "database/sql" |
| "errors" |
| "fmt" |
| @@ -19,10 +20,11 @@ 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 |
| + // Team is team mode's configuration (teammode.ConfigFromEnv), 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. TeamSettings verifies it. |
| + Team *teammode.Config |
| // 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: |
| @@ -84,7 +86,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(), |
| + Team: teammode.ConfigFromEnv("SHEETS"), |
| } |
| var missing []string |
diff --git a/internal/sheets/chrome_menu_test.go b/internal/sheets/chrome_menu_test.go| index 5e260ec..4c8cc1c 100644 |
| --- a/internal/sheets/chrome_menu_test.go |
| +++ b/internal/sheets/chrome_menu_test.go |
| @@ -32,7 +32,7 @@ func TestTheBarRenamesTheSheet(t *testing.T) { |
| t.Error("the old in-bar rename form is still rendered") |
| } |
| // A reader: a viewer grant only, signed in through the real link. |
| - if _, err := app.grant(s.ID, "reader@example.com", SheetViewer, signedInMember(t, app)); err != nil { |
| + if _, err := app.grant(nil, s.ID, "reader@example.com", SheetViewer, signedInMember(t, app)); err != nil { |
| t.Fatal(err) |
| } |
| postSignin(t, app, "reader@example.com") |
diff --git a/internal/sheets/chrome_test.go b/internal/sheets/chrome_test.go| index 0d43943..d53f8b5 100644 |
| --- a/internal/sheets/chrome_test.go |
| +++ b/internal/sheets/chrome_test.go |
| @@ -128,7 +128,7 @@ func TestEverySignedInPageHasOneSignOutInTheSameCorner(t *testing.T) { |
| func TestTheSignedOutCorner(t *testing.T) { |
| app, cookies := signIn(t) |
| s, _ := newSheet(t, app, cookies, "Budget") |
| - token, err := app.createLink(s.ID, SheetViewer, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/sheets/comments.go b/internal/sheets/comments.go| index 0a8fa6e..b9201ae 100644 |
| --- a/internal/sheets/comments.go |
| +++ b/internal/sheets/comments.go |
| @@ -4,6 +4,10 @@ import ( |
| "errors" |
| "strings" |
| "time" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| ) |
| // maxCommentRunes caps one comment. |
| @@ -52,7 +56,7 @@ func (a *App) mayComment(sheetID uint64, m Member) bool { |
| } |
| // addComment writes a comment on a cell. |
| -func (a *App) addComment(tabID, rowID, colID uint64, body string, by Member) error { |
| +func (a *App) addComment(g store.Guard, tabID, rowID, colID uint64, body string, by Member) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| @@ -70,25 +74,29 @@ func (a *App) addComment(tabID, rowID, colID uint64, body string, by Member) err |
| if err != nil { |
| return err |
| } |
| - return a.db.Create(&Comment{ |
| - TabID: tabID, RowID: rowID, ColID: colID, |
| - AuthorID: by.ID, BodySealed: sealed, |
| - }).Error |
| + return a.guarded(g, func(db *gorm.DB) error { |
| + return db.Create(&Comment{ |
| + TabID: tabID, RowID: rowID, ColID: colID, |
| + AuthorID: by.ID, BodySealed: sealed, |
| + }).Error |
| + }) |
| } |
| // resolveThread marks every comment on a cell as settled. |
| // |
| // The whole cell, not one comment: a thread is the unit people think |
| // in, and resolving one message of a conversation says nothing useful. |
| -func (a *App) resolveThread(tabID, rowID, colID uint64, by Member) error { |
| +func (a *App) resolveThread(g store.Guard, tabID, rowID, colID uint64, by Member) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| now := time.Now().UTC() |
| - return a.db.Model(&Comment{}). |
| - Where("tab_id = ? AND row_id = ? AND col_id = ? AND resolved_at IS NULL", |
| - tabID, rowID, colID). |
| - Updates(map[string]any{"resolved_at": now, "resolved_by": by.ID}).Error |
| + return a.guarded(g, func(db *gorm.DB) error { |
| + return db.Model(&Comment{}). |
| + Where("tab_id = ? AND row_id = ? AND col_id = ? AND resolved_at IS NULL", |
| + tabID, rowID, colID). |
| + Updates(map[string]any{"resolved_at": now, "resolved_by": by.ID}).Error |
| + }) |
| } |
| // commentThreads reads every thread on a tab, unsealed. |
diff --git a/internal/sheets/dashboard.go b/internal/sheets/dashboard.go| index 469239d..29baf2e 100644 |
| --- a/internal/sheets/dashboard.go |
| +++ b/internal/sheets/dashboard.go |
| @@ -23,15 +23,8 @@ 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 |
| - } |
| + // In team mode this finds a Home-only member too (connect's |
| + // HomeOnly hook). Identity only; Read asks the roster for standing. |
| p, e := a.home.Resolve(ctx, subject) |
| if errors.Is(e, linkstore.ErrStorage) { |
| return 0, dashboard.ErrUnavailable |
| @@ -52,13 +45,15 @@ func (a *App) dashboardDocuments(ctx context.Context, id int64, subject string, |
| 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() |
| + viewer = (&teamAccess{member: viewer, Access: a.team.Access(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 |
| + // Unknown standing is unavailable, not a short list: the feed is read |
| + // on another origin, by a reader who never sees the sheet list's |
| + // partial notice (teammode-package.md §4, condition 3). 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 |
diff --git a/internal/sheets/dashboard_test.go b/internal/sheets/dashboard_test.go| index bfecace..b6b7342 100644 |
| --- a/internal/sheets/dashboard_test.go |
| +++ b/internal/sheets/dashboard_test.go |
| @@ -14,7 +14,7 @@ func TestDashboardExistingLinkAndCurrentAdmission(t *testing.T) { |
| t.Setenv("OFICINA_DASHBOARD_TEAM", "blue") |
| f := newHomeFixtureWith(t, "https://oficina.example.test") |
| member := f.local(t, signedInAddress) |
| - sheet, e := f.app.createSheet("Linked workbook", member) |
| + sheet, e := f.app.createSheet(nil, "Linked workbook", member) |
| if e != nil { |
| t.Fatal(e) |
| } |
diff --git a/internal/sheets/grants.go b/internal/sheets/grants.go| index 63c0ab8..9ae2b2f 100644 |
| --- a/internal/sheets/grants.go |
| +++ b/internal/sheets/grants.go |
| @@ -155,7 +155,10 @@ func (a *App) grantsOn(ctx context.Context, sheetID uint64) ([]sharedWith, error |
| // a guest wrongly made a member sees every sheet on the instance, while |
| // a member wrongly left a guest sees one sheet too few and says so. |
| // Only SHEETS_OWNERS promotes beyond guest, at sign-in. |
| -func (a *App) grant(sheetID uint64, address string, role SheetRole, by Member) (Member, error) { |
| +// |
| +// g is the request's write guard (team_guard.go), run inside the |
| +// transaction; nil outside team mode. |
| +func (a *App) grant(g store.Guard, sheetID uint64, address string, role SheetRole, by Member) (Member, error) { |
| if a.db == nil { |
| return Member{}, errNoDB |
| } |
| @@ -176,22 +179,24 @@ func (a *App) grant(sheetID uint64, address string, role SheetRole, by Member) ( |
| // Upsert: re-sharing with somebody who already has access changes |
| // their role rather than failing on the unique index, which is what |
| // a person doing it expects. |
| - g := Grant{SheetID: sheetID, MemberID: m.ID, Role: string(role), GrantedBy: by.ID} |
| + row := Grant{SheetID: sheetID, MemberID: m.ID, Role: string(role), GrantedBy: by.ID} |
| // One transaction, because the check and the write are the same |
| // decision. Scoped to tx throughout, never the outer handle |
| // (AGENTS.md) — the one-connection writer pool deadlocks otherwise. |
| if err := a.db.Transaction(func(tx *gorm.DB) error { |
| - going, err := lastOwnerGoing(tx, sheetID, m.ID, role) |
| - if err != nil { |
| - return err |
| - } |
| - if going { |
| - return errLastOwner |
| - } |
| - return tx.Clauses(clause.OnConflict{ |
| - Columns: []clause.Column{{Name: "sheet_id"}, {Name: "member_id"}}, |
| - DoUpdates: clause.AssignmentColumns([]string{"role", "granted_by", "updated_at"}), |
| - }).Create(&g).Error |
| + return g.Run(func() error { |
| + going, err := lastOwnerGoing(tx, sheetID, m.ID, role) |
| + if err != nil { |
| + return err |
| + } |
| + if going { |
| + return errLastOwner |
| + } |
| + return tx.Clauses(clause.OnConflict{ |
| + Columns: []clause.Column{{Name: "sheet_id"}, {Name: "member_id"}}, |
| + DoUpdates: clause.AssignmentColumns([]string{"role", "granted_by", "updated_at"}), |
| + }).Create(&row).Error |
| + }) |
| }); err != nil { |
| return Member{}, err |
| } |
| @@ -201,7 +206,7 @@ func (a *App) grant(sheetID uint64, address string, role SheetRole, by Member) ( |
| // revoke removes a grant. Removing one that is not there is not an |
| // error: the caller wanted that person not to have access, and they do |
| // not. |
| -func (a *App) revoke(sheetID, memberID uint64) error { |
| +func (a *App) revoke(g store.Guard, sheetID, memberID uint64) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| @@ -211,15 +216,17 @@ func (a *App) revoke(sheetID, memberID uint64) error { |
| // time: two owners revoking each other at once both saw two owners |
| // and both deleted. |
| return a.db.Transaction(func(tx *gorm.DB) error { |
| - going, err := lastOwnerGoing(tx, sheetID, memberID, SheetViewer) |
| - if err != nil { |
| - return err |
| - } |
| - if going { |
| - return errLastOwner |
| - } |
| - return tx.Where("sheet_id = ? AND member_id = ?", sheetID, memberID). |
| - Delete(&Grant{}).Error |
| + return g.Run(func() error { |
| + going, err := lastOwnerGoing(tx, sheetID, memberID, SheetViewer) |
| + if err != nil { |
| + return err |
| + } |
| + if going { |
| + return errLastOwner |
| + } |
| + return tx.Where("sheet_id = ? AND member_id = ?", sheetID, memberID). |
| + Delete(&Grant{}).Error |
| + }) |
| }) |
| } |
diff --git a/internal/sheets/grants_sheetstate_test.go b/internal/sheets/grants_sheetstate_test.go| index b4fbb6b..3b5f6a2 100644 |
| --- a/internal/sheets/grants_sheetstate_test.go |
| +++ b/internal/sheets/grants_sheetstate_test.go |
| @@ -26,7 +26,7 @@ func TestAFillingSheetIsClosedToItsOwnImporter(t *testing.T) { |
| app, cookies := signIn(t) |
| importer := signedInMember(t, app) |
| - s, err := app.createFillingSheet("half a workbook", importer) |
| + s, err := app.createFillingSheet(nil, "half a workbook", importer) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -74,7 +74,7 @@ func TestADeletedSheetIsClosedToAGrantHolder(t *testing.T) { |
| app := newTestApp(t) |
| owner := testMember(t, app) |
| - s, err := app.createSheet("a sheet about to go", owner) |
| + s, err := app.createSheet(nil, "a sheet about to go", owner) |
| if err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
diff --git a/internal/sheets/grants_test.go b/internal/sheets/grants_test.go| index 693dc73..8503500 100644 |
| --- a/internal/sheets/grants_test.go |
| +++ b/internal/sheets/grants_test.go |
| @@ -15,7 +15,7 @@ import "testing" |
| // the only way they reach anything is the grant itself. |
| func guestOn(t *testing.T, app *App, sheetID uint64, address string, role SheetRole) Member { |
| t.Helper() |
| - m, err := app.grant(sheetID, address, role, signedInMember(t, app)) |
| + m, err := app.grant(nil, sheetID, address, role, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("grant %s as %s: %v", address, role, err) |
| } |
| @@ -132,7 +132,7 @@ func TestRevokeRemovesAccess(t *testing.T) { |
| if !app.mayRead(s.ID, ada) { |
| t.Fatal("the grant did not take") |
| } |
| - if err := app.revoke(s.ID, ada.ID); err != nil { |
| + if err := app.revoke(nil, s.ID, ada.ID); err != nil { |
| t.Fatalf("revoke: %v", err) |
| } |
| if app.mayRead(s.ID, ada) { |
| @@ -140,7 +140,7 @@ func TestRevokeRemovesAccess(t *testing.T) { |
| } |
| // Revoking again is not an error: the caller wanted them not to |
| // have access, and they do not. |
| - if err := app.revoke(s.ID, ada.ID); err != nil { |
| + if err := app.revoke(nil, s.ID, ada.ID); err != nil { |
| t.Fatalf("revoking twice: %v", err) |
| } |
| } |
| @@ -152,7 +152,7 @@ func TestRegrantingChangesTheRole(t *testing.T) { |
| s, _ := newSheet(t, app, cookies, "Promote me") |
| ada := guestOn(t, app, s.ID, "ada@elsewhere.example", SheetViewer) |
| - if _, err := app.grant(s.ID, "ada@elsewhere.example", SheetEditor, signedInMember(t, app)); err != nil { |
| + if _, err := app.grant(nil, s.ID, "ada@elsewhere.example", SheetEditor, signedInMember(t, app)); err != nil { |
| t.Fatalf("re-grant: %v", err) |
| } |
| role, ok := app.roleFor(s.ID, ada) |
| @@ -176,7 +176,7 @@ func TestGrantRefusesRubbish(t *testing.T) { |
| {"ada@elsewhere.example", SheetRole("admin")}, |
| {"ada@elsewhere.example", SheetRole("")}, |
| } { |
| - if _, err := app.grant(s.ID, tc.address, tc.role, by); err == nil { |
| + if _, err := app.grant(nil, s.ID, tc.address, tc.role, by); err == nil { |
| t.Errorf("grant(%q, %q) was accepted", tc.address, tc.role) |
| } |
| } |
diff --git a/internal/sheets/handlers_cell_batch.go b/internal/sheets/handlers_cell_batch.go| index e794bf6..522c717 100644 |
| --- a/internal/sheets/handlers_cell_batch.go |
| +++ b/internal/sheets/handlers_cell_batch.go |
| @@ -52,7 +52,10 @@ func (a *App) handleCellBatchPost(w http.ResponseWriter, r *http.Request) { |
| } |
| writes[i] = store.CellWrite{Row: cell.R, Col: cell.C, Raw: raw} |
| } |
| - rep, err := h.SetBatch(writes, actor.ID) |
| + rep, err := h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), actor, SheetEditor)).SetBatch(writes, actor.ID) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| http.Error(w, "That cell could not be written.", http.StatusBadRequest) |
| return |
diff --git a/internal/sheets/handlers_comments.go b/internal/sheets/handlers_comments.go| index 2ce457c..5fc64d0 100644 |
| --- a/internal/sheets/handlers_comments.go |
| +++ b/internal/sheets/handlers_comments.go |
| @@ -78,7 +78,10 @@ func (a *App) handleCommentAdd(w http.ResponseWriter, r *http.Request) { |
| a.commentRedirect(w, r, s, "no-cell") |
| return |
| } |
| - if err := a.addComment(s.TabID, rowID, colID, r.FormValue("body"), viewer); err != nil { |
| + if err := a.addComment(a.writeGuard(r.Context(), s.ID, viewer, SheetCommenter), s.TabID, rowID, colID, r.FormValue("body"), viewer); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| // The body is not echoed. It is user content, and an error |
| // string is a log line waiting to happen (AGENTS.md). |
| a.commentRedirect(w, r, s, "empty") |
| @@ -100,7 +103,10 @@ func (a *App) handleCommentResolve(w http.ResponseWriter, r *http.Request) { |
| a.commentRedirect(w, r, s, "no-cell") |
| return |
| } |
| - if err := a.resolveThread(s.TabID, rowID, colID, viewer); err != nil { |
| + if err := a.resolveThread(a.writeGuard(r.Context(), s.ID, viewer, SheetCommenter), s.TabID, rowID, colID, viewer); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, err) |
| return |
| } |
diff --git a/internal/sheets/handlers_format.go b/internal/sheets/handlers_format.go| index bb9f93d..e2c33cd 100644 |
| --- a/internal/sheets/handlers_format.go |
| +++ b/internal/sheets/handlers_format.go |
| @@ -38,7 +38,8 @@ const maxFormatCells = 4000 |
| func (a *App) handleFormatPost(w http.ResponseWriter, r *http.Request) { |
| // The viewer is checked but not recorded: formatting appends no |
| // event, so there is no actor column to write one to. |
| - if _, ok := a.actor(r); !ok { |
| + viewer, ok := a.actor(r) |
| + if !ok { |
| http.Error(w, "Sign in first.", http.StatusForbidden) |
| return |
| } |
| @@ -86,7 +87,10 @@ func (a *App) handleFormatPost(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - coords, err := a.applyFormat(h, p, r1, c1, r2, c2) |
| + coords, err := a.applyFormat(h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), viewer, SheetEditor)), h, p, r1, c1, r2, c2) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, err) |
| return |
| @@ -151,7 +155,10 @@ func tableReturn(sheetID uint64, page string) string { |
| // Every cell in the range is visited, including blank ones: a coloured |
| // header nobody has typed into yet is a real thing to want, and |
| // store.Handle.SetFormat creates the Cell row to carry it. |
| -func (a *App) applyFormat(h *store.Handle, p formatPatch, r1, c1, r2, c2 int) ([]store.CellCoord, error) { |
| +// |
| +// Each cell's format is written through wr, the handle under the |
| +// request's write guard (team_guard.go). |
| +func (a *App) applyFormat(wr store.Writer, h *store.Handle, p formatPatch, r1, c1, r2, c2 int) ([]store.CellCoord, error) { |
| existing, err := h.Formats() |
| if err != nil { |
| return nil, err |
| @@ -178,7 +185,7 @@ func (a *App) applyFormat(h *store.Handle, p formatPatch, r1, c1, r2, c2 int) ([ |
| if f, ok := existing[coord]; ok && f != nil { |
| base = *f |
| } |
| - if err := h.SetFormat(rowID, colID, p.applyTo(base)); err != nil { |
| + if err := wr.SetFormat(rowID, colID, p.applyTo(base)); err != nil { |
| return nil, err |
| } |
| out = append(out, coord) |
diff --git a/internal/sheets/handlers_grid.go b/internal/sheets/handlers_grid.go| index ad1f098..b3c71d9 100644 |
| --- a/internal/sheets/handlers_grid.go |
| +++ b/internal/sheets/handlers_grid.go |
| @@ -162,7 +162,10 @@ func (a *App) handleCellPost(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - rep, err := h.SetReport(rowID, colID, in.Raw, actor.ID) |
| + rep, err := h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), actor, SheetEditor)).SetReport(rowID, colID, in.Raw, actor.ID) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| // A parse failure is the caller's fault and a storage failure is |
| // ours, but neither may quote the input, so both answer the same |
diff --git a/internal/sheets/handlers_history.go b/internal/sheets/handlers_history.go| index 7ba28df..1ff4e40 100644 |
| --- a/internal/sheets/handlers_history.go |
| +++ b/internal/sheets/handlers_history.go |
| @@ -158,8 +158,10 @@ func (a *App) handleRestore(w http.ResponseWriter, r *http.Request) { |
| a.historyRedirect(w, r, s, "gone") |
| return |
| } |
| - if err := a.applyRaw(s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil { |
| - a.fail(w, r, err) |
| + if err := a.applyRaw(r.Context(), s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil { |
| + if !a.guardRefused(w, r, err) { |
| + a.fail(w, r, err) |
| + } |
| return |
| } |
| a.historyRedirect(w, r, s, "restored") |
| @@ -215,8 +217,10 @@ func (a *App) handleUndo(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| rec := records[0] |
| - if err := a.applyRaw(s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil { |
| - a.fail(w, r, err) |
| + if err := a.applyRaw(r.Context(), s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil { |
| + if !a.guardRefused(w, r, err) { |
| + a.fail(w, r, err) |
| + } |
| return |
| } |
| a.historyRedirect(w, r, s, "undone") |
| @@ -227,14 +231,14 @@ func (a *App) handleUndo(w http.ResponseWriter, r *http.Request) { |
| // |
| // Shared by restore and undo so neither can drift from the write path |
| // the grid uses: same store call, same hub publish, same version. |
| -func (a *App) applyRaw(s SheetSummary, rowID, colID uint64, raw string, by Member) error { |
| +func (a *App) applyRaw(ctx context.Context, s SheetSummary, rowID, colID uint64, raw string, by Member) error { |
| h, err := a.openTabFor(s) |
| if err != nil { |
| return err |
| } |
| defer h.Release() |
| - rep, err := h.SetReport(rowID, colID, raw, by.ID) |
| + rep, err := h.Guarded(a.writeGuard(ctx, s.ID, by, SheetEditor)).SetReport(rowID, colID, raw, by.ID) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/sheets/handlers_import.go b/internal/sheets/handlers_import.go| index e7954db..78661db 100644 |
| --- a/internal/sheets/handlers_import.go |
| +++ b/internal/sheets/handlers_import.go |
| @@ -118,7 +118,10 @@ func (a *App) handleSheetImport(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - s, err := a.createFillingSheet(titleFromFilename(filename), actor) |
| + s, err := a.createFillingSheet(a.memberGuard(r.Context()), titleFromFilename(filename), actor) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, err) |
| return |
diff --git a/internal/sheets/handlers_import_hidden_test.go b/internal/sheets/handlers_import_hidden_test.go| index 429aba2..7aecda1 100644 |
| --- a/internal/sheets/handlers_import_hidden_test.go |
| +++ b/internal/sheets/handlers_import_hidden_test.go |
| @@ -23,7 +23,7 @@ func TestAnUnfinishedImportIsInvisible(t *testing.T) { |
| app := newTestApp(t) |
| member := testMember(t, app) |
| - s, err := app.createFillingSheet("half a workbook", member) |
| + s, err := app.createFillingSheet(nil, "half a workbook", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -62,7 +62,7 @@ func TestAnOrdinaryNewSheetIsVisibleImmediately(t *testing.T) { |
| app := newTestApp(t) |
| member := testMember(t, app) |
| - if _, err := app.createSheet("an ordinary sheet", member); err != nil { |
| + if _, err := app.createSheet(nil, "an ordinary sheet", member); err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
| list, err := app.listSheets(member) |
| @@ -86,7 +86,7 @@ func TestDiscardingAnImportRemovesItsGrants(t *testing.T) { |
| app.admit = func(string) bool { return false } |
| guest := testMember(t, app) |
| - s, err := app.createFillingSheet("a workbook that will fail", guest) |
| + s, err := app.createFillingSheet(nil, "a workbook that will fail", guest) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -126,7 +126,7 @@ func TestAdmitsIgnoresGrantsToSheetsYouCannotOpen(t *testing.T) { |
| app.admit = func(string) bool { return false } |
| guest := testMember(t, app) |
| - s, err := app.createSheet("shared with a guest", guest) |
| + s, err := app.createSheet(nil, "shared with a guest", guest) |
| if err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
diff --git a/internal/sheets/handlers_link.go b/internal/sheets/handlers_link.go| index e7a35bf..2366f00 100644 |
| --- a/internal/sheets/handlers_link.go |
| +++ b/internal/sheets/handlers_link.go |
| @@ -152,13 +152,16 @@ func (a *App) handleLinkCreate(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| role := SheetRole(r.FormValue("role")) |
| - token, err := a.createLink(s.ID, role, viewer) |
| + token, err := a.createLink(a.writeGuard(r.Context(), s.ID, viewer, SheetOwner), s.ID, role, viewer) |
| if errors.Is(err, errBadLinkRole) { |
| // The only failure the person can act on, and the only one they |
| // are told about in these terms. |
| a.shareRedirect(w, r, s, "bad-link-role") |
| return |
| } |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| // Ours, not theirs: the same 500 every other broken write on |
| // this screen gives, rather than a sentence blaming a role |
| @@ -171,7 +174,7 @@ func (a *App) handleLinkCreate(w http.ResponseWriter, r *http.Request) { |
| // handleLinkRevoke turns a link off. |
| func (a *App) handleLinkRevoke(w http.ResponseWriter, r *http.Request) { |
| - s, _, ok := a.sheetForSharing(w, r) |
| + s, viewer, ok := a.sheetForSharing(w, r) |
| if !ok { |
| return |
| } |
| @@ -180,7 +183,10 @@ func (a *App) handleLinkRevoke(w http.ResponseWriter, r *http.Request) { |
| a.notFound(w, r) |
| return |
| } |
| - if err := a.revokeLink(s.ID, linkID); err != nil { |
| + if err := a.revokeLink(a.writeGuard(r.Context(), s.ID, viewer, SheetOwner), s.ID, linkID); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, err) |
| return |
| } |
diff --git a/internal/sheets/handlers_rename.go b/internal/sheets/handlers_rename.go| index 435bbbd..ab48ee0 100644 |
| --- a/internal/sheets/handlers_rename.go |
| +++ b/internal/sheets/handlers_rename.go |
| @@ -6,6 +6,8 @@ import ( |
| "strconv" |
| "strings" |
| + "gorm.io/gorm" |
| + |
| "amadan.net/oficina/sheets/internal/sheets/store" |
| ) |
| @@ -98,7 +100,10 @@ func (a *App) handleSheetRename(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - if err := a.renameSheet(s.ID, title); err != nil { |
| + if err := a.renameSheet(a.writeGuard(r.Context(), s.ID, viewer, SheetEditor), s.ID, title); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if errors.Is(err, errBlankTitle) { |
| if wantsNative(r) { |
| http.Error(w, "A sheet needs a title.", 400) |
| @@ -137,7 +142,7 @@ func (a *App) sheetRedirect(w http.ResponseWriter, r *http.Request, id uint64) { |
| // this statement cannot touch a field nobody asked it to. GORM bumps |
| // UpdatedAt as part of it, which is what makes a renamed sheet rise to |
| // the top of the list — correct, since renaming it is changing it. |
| -func (a *App) renameSheet(sheetID uint64, title string) error { |
| +func (a *App) renameSheet(g store.Guard, sheetID uint64, title string) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| @@ -157,7 +162,9 @@ func (a *App) renameSheet(sheetID uint64, title string) error { |
| if err != nil { |
| return err |
| } |
| - return a.db.Model(&store.Sheet{}). |
| - Where("id = ?", sheetID). |
| - Update("title_sealed", sealed).Error |
| + return a.guarded(g, func(db *gorm.DB) error { |
| + return db.Model(&store.Sheet{}). |
| + Where("id = ?", sheetID). |
| + Update("title_sealed", sealed).Error |
| + }) |
| } |
diff --git a/internal/sheets/handlers_share.go b/internal/sheets/handlers_share.go| index 3bcf432..3c4b8f3 100644 |
| --- a/internal/sheets/handlers_share.go |
| +++ b/internal/sheets/handlers_share.go |
| @@ -150,7 +150,10 @@ func (a *App) handleShareGrant(w http.ResponseWriter, r *http.Request) { |
| a.shareRedirect(w, r, s, "bad-role") |
| return |
| } |
| - if _, err := a.grant(s.ID, r.FormValue("address"), role, viewer); err != nil { |
| + if _, err := a.grant(a.writeGuard(r.Context(), s.ID, viewer, SheetOwner), s.ID, r.FormValue("address"), role, viewer); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| // Demoting the last owner is refused, and says so. Told |
| // "that does not look like an email address" instead, a person |
| // would retype their own address and try again — the one |
| @@ -169,7 +172,7 @@ func (a *App) handleShareGrant(w http.ResponseWriter, r *http.Request) { |
| // handleShareRevoke removes somebody's access. |
| func (a *App) handleShareRevoke(w http.ResponseWriter, r *http.Request) { |
| - s, _, ok := a.sheetForSharing(w, r) |
| + s, viewer, ok := a.sheetForSharing(w, r) |
| if !ok { |
| return |
| } |
| @@ -186,7 +189,10 @@ func (a *App) handleShareRevoke(w http.ResponseWriter, r *http.Request) { |
| // Here it was a read separated from its delete by the rest of this |
| // handler, so two owners revoking each other at the same moment both |
| // saw two owners and both deleted. |
| - if err := a.revoke(s.ID, memberID); err != nil { |
| + if err := a.revoke(a.writeGuard(r.Context(), s.ID, viewer, SheetOwner), s.ID, memberID); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if errors.Is(err, errLastOwner) { |
| a.shareRedirect(w, r, s, "last-owner") |
| return |
diff --git a/internal/sheets/handlers_sheets.go b/internal/sheets/handlers_sheets.go| index af8ce7b..fea4cae 100644 |
| --- a/internal/sheets/handlers_sheets.go |
| +++ b/internal/sheets/handlers_sheets.go |
| @@ -29,6 +29,9 @@ type sheetRow struct { |
| // rather than being dropped: it is importPageView.Error now. |
| type sheetListView struct { |
| Sheets []sheetRow |
| + // Partial is team mode with standing Unknown: Sheets holds the |
| + // viewer's shares only, and the page says so (teamPartial). |
| + Partial bool |
| } |
| // sheetPageView is the grid page's payload. |
| @@ -102,13 +105,11 @@ 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 |
| - } |
| + // Team mode with standing Unknown: the list above holds the shares |
| + // only, and is shown as partial, with a notice, rather than as a 503 |
| + // (Paul, 2026-10-28). Asked after listing, of the same Access the list |
| + // was built with, because a lease can lapse during it. |
| + partial := a.teamPartial(viewer) |
| if wantsNative(r) { |
| // Reuse the web preview's shape-only query; never decrypt cells or |
| // return HTML to a native renderer. |
| @@ -120,7 +121,11 @@ func (a *App) renderSheetList(w http.ResponseWriter, r *http.Request, status int |
| for _, sheet := range list { |
| rows = append(rows, nativeSheetRow{SheetSummary: sheet, Preview: a.buildPreview(sheet.TabID)}) |
| } |
| - nativeJSON(w, status, map[string]any{"Sheets": rows}) |
| + body := map[string]any{"Sheets": rows} |
| + if partial { |
| + body["Partial"] = true |
| + } |
| + nativeJSON(w, status, body) |
| return |
| } |
| rows := make([]sheetRow, 0, len(list)) |
| @@ -135,7 +140,7 @@ func (a *App) renderSheetList(w http.ResponseWriter, r *http.Request, status int |
| {Item: estilomenu.Item{Href: "/sheets/import", Label: "Import"}}, |
| {Item: estilomenu.Item{Action: "/sheets", Label: "Create"}, Primary: true}, |
| }} |
| - a.render(w, r, "sheets", f, status, sheetListView{Sheets: rows}) |
| + a.render(w, r, "sheets", f, status, sheetListView{Sheets: rows, Partial: partial}) |
| } |
| // handleSheetCreate makes a sheet and sends you to it. |
| @@ -161,7 +166,10 @@ func (a *App) handleSheetCreate(w http.ResponseWriter, r *http.Request) { |
| if title == "" { |
| title = "Untitled sheet" |
| } |
| - s, err := a.createSheet(title, actor) |
| + s, err := a.createSheet(a.memberGuard(r.Context()), title, actor) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, err) |
| return |
diff --git a/internal/sheets/handlers_size.go b/internal/sheets/handlers_size.go| index 02f39a3..19985c5 100644 |
| --- a/internal/sheets/handlers_size.go |
| +++ b/internal/sheets/handlers_size.go |
| @@ -33,7 +33,8 @@ type sizeWrite struct { |
| // Like formatting, a resize writes no event and is therefore not |
| // undoable. Same reason, same named limitation. |
| func (a *App) handleSizePost(w http.ResponseWriter, r *http.Request) { |
| - if _, ok := a.actor(r); !ok { |
| + viewer, ok := a.actor(r) |
| + if !ok { |
| http.Error(w, "Sign in first.", http.StatusForbidden) |
| return |
| } |
| @@ -42,6 +43,7 @@ func (a *App) handleSizePost(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| defer h.Release() |
| + wr := h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), viewer, SheetEditor)) |
| // One route, two decoders, converging on one sizeWrite before |
| // anything is checked — the same shape handleFormatPost took, and |
| @@ -75,7 +77,7 @@ func (a *App) handleSizePost(w http.ResponseWriter, r *http.Request) { |
| } |
| var colID uint64 |
| if colID, err = h.EnsureCol(*in.Col); err == nil { |
| - err = h.SetColWidth(colID, in.Size) |
| + err = wr.SetColWidth(colID, in.Size) |
| } |
| default: |
| if *in.Row < 0 || *in.Row >= maxWindowRows*10 { |
| @@ -84,9 +86,12 @@ func (a *App) handleSizePost(w http.ResponseWriter, r *http.Request) { |
| } |
| var rowID uint64 |
| if rowID, err = h.EnsureRow(*in.Row); err == nil { |
| - err = h.SetRowHeight(rowID, in.Size) |
| + err = wr.SetRowHeight(rowID, in.Size) |
| } |
| } |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| // A size outside the bounds is the caller's fault and a storage |
| // failure is ours. Both answer the same fixed string: the error |
diff --git a/internal/sheets/handlers_table.go b/internal/sheets/handlers_table.go| index 9e25c47..3d1efee 100644 |
| --- a/internal/sheets/handlers_table.go |
| +++ b/internal/sheets/handlers_table.go |
| @@ -205,7 +205,10 @@ func (a *App) handleTableWrite(w http.ResponseWriter, r *http.Request) { |
| a.fail(w, r, err) |
| return |
| } |
| - rep, err := h.SetReport(rowID, colID, raw, actor.ID) |
| + rep, err := h.Guarded(a.writeGuard(r.Context(), s.ID, actor, SheetEditor)).SetReport(rowID, colID, raw, actor.ID) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.badRequest(w, r, http.StatusBadRequest, "That cell could not be written.") |
| return |
diff --git a/internal/sheets/handlers_view.go b/internal/sheets/handlers_view.go| index 8cd45bd..096c716 100644 |
| --- a/internal/sheets/handlers_view.go |
| +++ b/internal/sheets/handlers_view.go |
| @@ -56,7 +56,10 @@ func (a *App) handleViewSave(w http.ResponseWriter, r *http.Request) { |
| a.tableRedirect(w, r, s) |
| return |
| } |
| - if err := a.saveView(s.TabID, spec, viewer); err != nil { |
| + if err := a.saveView(a.writeGuard(r.Context(), s.ID, viewer, SheetEditor), s.TabID, spec, viewer); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, err) |
| return |
| } |
diff --git a/internal/sheets/home.go b/internal/sheets/home.go| index 5a08432..ef2d605 100644 |
| --- a/internal/sheets/home.go |
| +++ b/internal/sheets/home.go |
| @@ -63,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: homeNamespace, Keys: settings.Keys, DEK: settings.DEK, SessionCookie: sess.CookieName(), ReadSession: read, |
| + cfg := 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}) |
| }, |
| @@ -76,7 +76,13 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| } |
| label, err := a.homePerson(ctx, d, id) |
| return connect.Person{ID: id, Label: label}, err |
| - }, Render: render}) |
| + }, Render: render} |
| + if a.teamSettings != nil { |
| + // Team mode only: with both hooks nil connect is exactly what it |
| + // was (team_home_only.go). |
| + cfg.HomeOnly, cfg.Unlinked = a.teamHomeOnly(d), a.teamUnlinked(d) |
| + } |
| + bridge, err := connect.New(cfg) |
| if err != nil { |
| return errHome |
| } |
| @@ -85,7 +91,7 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| return errHome |
| } |
| a.home, a.homeRoutes, a.homeSessions = bridge, routes, sess |
| - a.homeCreds, a.homeRender = settings, render |
| + a.homeCreds = settings |
| a.directory = settings.Directory |
| return a.configureDashboard(settings) |
| } |
diff --git a/internal/sheets/home_routes.go b/internal/sheets/home_routes.go| index 9af1f15..ba99562 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.homeFinish) |
| + r.Get("/auth/finish", a.home.Finish) |
| 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 8f3650b..a60eff0 100644 |
| --- a/internal/sheets/home_test.go |
| +++ b/internal/sheets/home_test.go |
| @@ -23,6 +23,9 @@ type homeFixture struct { |
| app *App |
| key *assertioncrypto.Keypair |
| jar map[string]*http.Cookie |
| + // creds are the Home credentials ConfigureHome was given, as main |
| + // reads them: team mode's settings are verified against them. |
| + creds connect.Credentials |
| } |
| func newHomeFixture(t *testing.T) *homeFixture { |
| @@ -60,7 +63,7 @@ func homeOn(t *testing.T, app *App, directory string) *homeFixture { |
| if err := app.ConfigureHome(&cfg); err != nil { |
| t.Fatal(err) |
| } |
| - return &homeFixture{app: app, key: key, jar: map[string]*http.Cookie{}} |
| + return &homeFixture{app: app, key: key, jar: map[string]*http.Cookie{}, creds: cfg} |
| } |
| func (f *homeFixture) request(t *testing.T, method, path string, form url.Values, issuer bool) *httptest.ResponseRecorder { |
| t.Helper() |
| @@ -157,7 +160,7 @@ func (f *homeFixture) link(t *testing.T, subject string) { |
| func TestHomeConnectionPreservesSheetsAndCurrentAdmission(t *testing.T) { |
| f := newHomeFixture(t) |
| member := f.local(t, signedInAddress) |
| - sheet, err := f.app.createSheet("Existing linked workbook", member) |
| + sheet, err := f.app.createSheet(nil, "Existing linked workbook", member) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/sheets/importlifecycle_test.go b/internal/sheets/importlifecycle_test.go| index 9fa9689..825c44c 100644 |
| --- a/internal/sheets/importlifecycle_test.go |
| +++ b/internal/sheets/importlifecycle_test.go |
| @@ -25,7 +25,7 @@ func TestStaleImportsAreSweptAtBoot(t *testing.T) { |
| app := newTestApp(t) |
| member := testMember(t, app) |
| - old, err := app.createFillingSheet("interrupted by a deploy", member) |
| + old, err := app.createFillingSheet(nil, "interrupted by a deploy", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -37,7 +37,7 @@ func TestStaleImportsAreSweptAtBoot(t *testing.T) { |
| // This one started moments ago, so a live job may well still be |
| // filling it in another instance. |
| - fresh, err := app.createFillingSheet("still going", member) |
| + fresh, err := app.createFillingSheet(nil, "still going", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -73,7 +73,7 @@ func TestARevealRefusesADiscardedSheet(t *testing.T) { |
| app := newTestApp(t) |
| member := testMember(t, app) |
| - s, err := app.createFillingSheet("swept mid-import", member) |
| + s, err := app.createFillingSheet(nil, "swept mid-import", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -95,7 +95,7 @@ func TestImportingReclaimsStaleImports(t *testing.T) { |
| app, cookies := signIn(t) |
| member := signedInMember(t, app) |
| - abandoned, err := app.createFillingSheet("nobody is coming back", member) |
| + abandoned, err := app.createFillingSheet(nil, "nobody is coming back", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| @@ -181,11 +181,11 @@ func TestImportedSheetIsNotReachableByLinkWhileFilling(t *testing.T) { |
| app := newTestApp(t) |
| member := testMember(t, app) |
| - s, err := app.createFillingSheet("half a workbook", member) |
| + s, err := app.createFillingSheet(nil, "half a workbook", member) |
| if err != nil { |
| t.Fatalf("createFillingSheet: %v", err) |
| } |
| - token, err := app.createLink(s.ID, SheetViewer, member) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, member) |
| if err != nil { |
| // Minting a link for a filling sheet may itself be refused, |
| // which is a perfectly good answer to this question. |
diff --git a/internal/sheets/page.go b/internal/sheets/page.go| index 0819598..5ba79a2 100644 |
| --- a/internal/sheets/page.go |
| +++ b/internal/sheets/page.go |
| @@ -68,13 +68,9 @@ func (a *App) identity(r *http.Request) (string, bool) { |
| return "", false |
| } |
| if s.Method == connect.HomeMethod { |
| + // In team mode this resolves a Home-only member too (connect's |
| + // HomeOnly hook): signed in, with no address. |
| 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/sharelink.go b/internal/sheets/sharelink.go| index 0cbe327..2891a84 100644 |
| --- a/internal/sheets/sharelink.go |
| +++ b/internal/sheets/sharelink.go |
| @@ -10,6 +10,8 @@ import ( |
| "time" |
| "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| ) |
| // linkTokenBytes is the token's entropy: 32 bytes from crypto/rand. |
| @@ -66,7 +68,7 @@ var errBadLinkRole = errors.New("sheets: a link can only view or comment, never |
| // createLink mints a link for a sheet and returns the token, which the |
| // caller must show once and then forget. |
| -func (a *App) createLink(sheetID uint64, role SheetRole, by Member) (string, error) { |
| +func (a *App) createLink(g store.Guard, sheetID uint64, role SheetRole, by Member) (string, error) { |
| if a.db == nil { |
| return "", errNoDB |
| } |
| @@ -80,9 +82,11 @@ func (a *App) createLink(sheetID uint64, role SheetRole, by Member) (string, err |
| if err != nil { |
| return "", err |
| } |
| - if err := a.db.Create(&ShareLink{ |
| - SheetID: sheetID, TokenHash: hash, Role: string(role), CreatedBy: by.ID, |
| - }).Error; err != nil { |
| + if err := a.guarded(g, func(db *gorm.DB) error { |
| + return db.Create(&ShareLink{ |
| + SheetID: sheetID, TokenHash: hash, Role: string(role), CreatedBy: by.ID, |
| + }).Error |
| + }); err != nil { |
| return "", err |
| } |
| return token, nil |
| @@ -103,14 +107,16 @@ func (a *App) linksOn(sheetID uint64) ([]ShareLink, error) { |
| // revokeLink turns a link off. The row survives so that somebody |
| // holding a stale URL can be told the link was turned off rather than |
| // that it never existed. |
| -func (a *App) revokeLink(sheetID, linkID uint64) error { |
| +func (a *App) revokeLink(g store.Guard, sheetID, linkID uint64) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| now := time.Now().UTC() |
| - return a.db.Model(&ShareLink{}). |
| - Where("id = ? AND sheet_id = ? AND revoked_at IS NULL", linkID, sheetID). |
| - Update("revoked_at", now).Error |
| + return a.guarded(g, func(db *gorm.DB) error { |
| + return db.Model(&ShareLink{}). |
| + Where("id = ? AND sheet_id = ? AND revoked_at IS NULL", linkID, sheetID). |
| + Update("revoked_at", now).Error |
| + }) |
| } |
| // linkFor resolves a token to its live link. |
diff --git a/internal/sheets/sharelink_test.go b/internal/sheets/sharelink_test.go| index efb9d8b..86ce413 100644 |
| --- a/internal/sheets/sharelink_test.go |
| +++ b/internal/sheets/sharelink_test.go |
| @@ -16,7 +16,7 @@ func TestALinkTokenIsNeverStored(t *testing.T) { |
| app, cookies := signIn(t) |
| s, _ := newSheet(t, app, cookies, "Budget") |
| - token, err := app.createLink(s.ID, SheetViewer, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
| @@ -46,7 +46,7 @@ func TestTwoLinksNeverCollide(t *testing.T) { |
| seen := map[string]bool{} |
| for i := 0; i < 20; i++ { |
| - token, err := app.createLink(s.ID, SheetViewer, me) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, me) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
| @@ -65,12 +65,12 @@ func TestALinkCanNeverEdit(t *testing.T) { |
| me := signedInMember(t, app) |
| for _, role := range []SheetRole{SheetEditor, SheetOwner, SheetRole("admin"), SheetRole("")} { |
| - if _, err := app.createLink(s.ID, role, me); err == nil { |
| + if _, err := app.createLink(nil, s.ID, role, me); err == nil { |
| t.Errorf("a %q link was created", role) |
| } |
| } |
| for _, role := range []SheetRole{SheetViewer, SheetCommenter} { |
| - if _, err := app.createLink(s.ID, role, me); err != nil { |
| + if _, err := app.createLink(nil, s.ID, role, me); err != nil { |
| t.Errorf("a %q link was refused: %v", role, err) |
| } |
| } |
| @@ -82,7 +82,7 @@ func TestALinkOpensTheSheetWithNoAccount(t *testing.T) { |
| s, cells := newSheet(t, app, cookies, "Budget") |
| postCell(t, app, cookies, cells, `{"r":0,"c":0,"raw":"=6*7"}`) |
| - token, err := app.createLink(s.ID, SheetViewer, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
| @@ -113,7 +113,7 @@ func TestALinkOpensTheSheetWithNoAccount(t *testing.T) { |
| func TestALinkHolderCannotWrite(t *testing.T) { |
| app, cookies := signIn(t) |
| s, cells := newSheet(t, app, cookies, "Budget") |
| - token, err := app.createLink(s.ID, SheetCommenter, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetCommenter, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
| @@ -139,7 +139,7 @@ func TestALinkHolderCannotWrite(t *testing.T) { |
| func TestARevokedLinkGivesNothing(t *testing.T) { |
| app, cookies := signIn(t) |
| s, _ := newSheet(t, app, cookies, "Budget") |
| - token, err := app.createLink(s.ID, SheetViewer, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
| @@ -151,7 +151,7 @@ func TestARevokedLinkGivesNothing(t *testing.T) { |
| if err != nil || len(links) != 1 { |
| t.Fatalf("linksOn: %v (%d links)", err, len(links)) |
| } |
| - if err := app.revokeLink(s.ID, links[0].ID); err != nil { |
| + if err := app.revokeLink(nil, s.ID, links[0].ID); err != nil { |
| t.Fatalf("revokeLink: %v", err) |
| } |
| if rec := do(t, app, httptest.NewRequest(http.MethodGet, "/l/"+token, nil)); rec.Code != http.StatusNotFound { |
diff --git a/internal/sheets/sharelink_url_test.go b/internal/sheets/sharelink_url_test.go| index bbab8f9..8116742 100644 |
| --- a/internal/sheets/sharelink_url_test.go |
| +++ b/internal/sheets/sharelink_url_test.go |
| @@ -57,7 +57,7 @@ func TestTheShareScreenIgnoresATokenInItsQuery(t *testing.T) { |
| app, cookies := signIn(t) |
| s, _ := newSheet(t, app, cookies, "Budget") |
| - token, err := app.createLink(s.ID, SheetViewer, signedInMember(t, app)) |
| + token, err := app.createLink(nil, s.ID, SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatalf("createLink: %v", err) |
| } |
diff --git a/internal/sheets/sheetsvc.go b/internal/sheets/sheetsvc.go| index 1a66551..19a8aec 100644 |
| --- a/internal/sheets/sheetsvc.go |
| +++ b/internal/sheets/sheetsvc.go |
| @@ -76,8 +76,11 @@ type SheetSummary struct { |
| // has at least one tab" a real invariant rather than a convention |
| // everyone remembers. |
| // createSheet makes an ordinary, immediately visible sheet. |
| -func (a *App) createSheet(title string, by Member) (SheetSummary, error) { |
| - return a.newSheet(title, by, false) |
| +// |
| +// g is the request's write guard (team_guard.go: member-only in team |
| +// mode), run inside the transaction; nil outside team mode. |
| +func (a *App) createSheet(g store.Guard, title string, by Member) (SheetSummary, error) { |
| + return a.newSheet(g, title, by, false) |
| } |
| // createFillingSheet makes a sheet that is HIDDEN until something |
| @@ -86,11 +89,11 @@ func (a *App) createSheet(title string, by Member) (SheetSummary, error) { |
| // The caller owns the other half: markFilled on success, discardSheet |
| // on failure. A caller that does neither leaves an invisible row, which |
| // is the failure this is designed to have. |
| -func (a *App) createFillingSheet(title string, by Member) (SheetSummary, error) { |
| - return a.newSheet(title, by, true) |
| +func (a *App) createFillingSheet(g store.Guard, title string, by Member) (SheetSummary, error) { |
| + return a.newSheet(g, title, by, true) |
| } |
| -func (a *App) newSheet(title string, by Member, filling bool) (SheetSummary, error) { |
| +func (a *App) newSheet(g store.Guard, title string, by Member, filling bool) (SheetSummary, error) { |
| if a.db == nil { |
| return SheetSummary{}, errNoDB |
| } |
| @@ -120,21 +123,23 @@ func (a *App) newSheet(title string, by Member, filling bool) (SheetSummary, err |
| } |
| tab := store.Tab{NameSealed: sealedName, Position: 0} |
| if err := a.db.Transaction(func(tx *gorm.DB) error { |
| - if err := tx.Create(&sheet).Error; err != nil { |
| - return err |
| - } |
| - tab.SheetID = sheet.ID |
| - if err := tx.Create(&tab).Error; err != nil { |
| - return err |
| - } |
| - // The creator owns it, written here rather than inferred from |
| - // Sheet.CreatedBy. Inferring would mean two sources of truth |
| - // for one question, and the share screen could not then take |
| - // ownership away or hand it on. |
| - return tx.Create(&Grant{ |
| - SheetID: sheet.ID, MemberID: by.ID, |
| - Role: string(SheetOwner), GrantedBy: by.ID, |
| - }).Error |
| + return g.Run(func() error { |
| + if err := tx.Create(&sheet).Error; err != nil { |
| + return err |
| + } |
| + tab.SheetID = sheet.ID |
| + if err := tx.Create(&tab).Error; err != nil { |
| + return err |
| + } |
| + // The creator owns it, written here rather than inferred from |
| + // Sheet.CreatedBy. Inferring would mean two sources of truth |
| + // for one question, and the share screen could not then take |
| + // ownership away or hand it on. |
| + return tx.Create(&Grant{ |
| + SheetID: sheet.ID, MemberID: by.ID, |
| + Role: string(SheetOwner), GrantedBy: by.ID, |
| + }).Error |
| + }) |
| }); err != nil { |
| return SheetSummary{}, err |
| } |
diff --git a/internal/sheets/sheetsvc_test.go b/internal/sheets/sheetsvc_test.go| index 90229f0..84e246e 100644 |
| --- a/internal/sheets/sheetsvc_test.go |
| +++ b/internal/sheets/sheetsvc_test.go |
| @@ -11,7 +11,7 @@ import ( |
| func TestCreateSheetMakesAFirstTab(t *testing.T) { |
| app := newTestApp(t) |
| - s, err := app.createSheet("Budget", testMember(t, app)) |
| + s, err := app.createSheet(nil, "Budget", testMember(t, app)) |
| if err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
| @@ -33,7 +33,7 @@ func TestCreateSheetMakesAFirstTab(t *testing.T) { |
| func TestSheetTitleIsSealedAtRest(t *testing.T) { |
| app := newTestApp(t) |
| const secret = "Salaries 2027" |
| - if _, err := app.createSheet(secret, testMember(t, app)); err != nil { |
| + if _, err := app.createSheet(nil, secret, testMember(t, app)); err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
| var raw []byte |
| @@ -52,7 +52,7 @@ func TestSheetTitleIsSealedAtRest(t *testing.T) { |
| func TestTabNameIsSealedAtRest(t *testing.T) { |
| app := newTestApp(t) |
| - if _, err := app.createSheet("Budget", testMember(t, app)); err != nil { |
| + if _, err := app.createSheet(nil, "Budget", testMember(t, app)); err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
| var raw []byte |
| @@ -81,10 +81,10 @@ func TestListSheetsIsTeamWideNotPerCreator(t *testing.T) { |
| if err != nil { |
| t.Fatalf("memberFor bob: %v", err) |
| } |
| - if _, err := app.createSheet("Ada's", ada); err != nil { |
| + if _, err := app.createSheet(nil, "Ada's", ada); err != nil { |
| t.Fatalf("createSheet ada: %v", err) |
| } |
| - if _, err := app.createSheet("Bob's", bob); err != nil { |
| + if _, err := app.createSheet(nil, "Bob's", bob); err != nil { |
| t.Fatalf("createSheet bob: %v", err) |
| } |
| got, err := app.listSheets(ada) |
| @@ -106,10 +106,10 @@ func TestListSheetsIsTeamWideNotPerCreator(t *testing.T) { |
| func TestCreateSheetRefusesAnEmptyTitle(t *testing.T) { |
| app := newTestApp(t) |
| m := testMember(t, app) |
| - if _, err := app.createSheet(" ", m); err == nil { |
| + if _, err := app.createSheet(nil, " ", m); err == nil { |
| t.Fatal("createSheet with a blank title = nil error, want a refusal") |
| } |
| - if _, err := app.createSheet("", m); err == nil { |
| + if _, err := app.createSheet(nil, "", m); err == nil { |
| t.Fatal(`createSheet("") = nil error, want a refusal`) |
| } |
| } |
| @@ -117,7 +117,7 @@ func TestCreateSheetRefusesAnEmptyTitle(t *testing.T) { |
| func TestCreateSheetTruncatesAnOverlongTitle(t *testing.T) { |
| app := newTestApp(t) |
| long := strings.Repeat("é", maxTitleRunes+50) |
| - s, err := app.createSheet(long, testMember(t, app)) |
| + s, err := app.createSheet(nil, long, testMember(t, app)) |
| if err != nil { |
| t.Fatalf("createSheet: %v", err) |
| } |
| @@ -142,11 +142,11 @@ func TestSheetSummaryForAMissingSheetIsNotFound(t *testing.T) { |
| func TestTabBelongsToRefusesACrossSheetPairing(t *testing.T) { |
| app := newTestApp(t) |
| m := testMember(t, app) |
| - one, err := app.createSheet("One", m) |
| + one, err := app.createSheet(nil, "One", m) |
| if err != nil { |
| t.Fatalf("createSheet one: %v", err) |
| } |
| - two, err := app.createSheet("Two", m) |
| + two, err := app.createSheet(nil, "Two", m) |
| if err != nil { |
| t.Fatalf("createSheet two: %v", err) |
| } |
diff --git a/internal/sheets/signin_confirm_test.go b/internal/sheets/signin_confirm_test.go| index 6c07523..cc7466f 100644 |
| --- a/internal/sheets/signin_confirm_test.go |
| +++ b/internal/sheets/signin_confirm_test.go |
| @@ -102,14 +102,14 @@ func TestEmailedLinkOpensTheConfirmDoor(t *testing.T) { |
| func TestALinkRefusedAtRedemptionIsTheDoor(t *testing.T) { |
| app, cookies := signIn(t) |
| s, _ := newSheet(t, app, cookies, "Budget") |
| - guest, err := app.grant(s.ID, "ada@elsewhere.example", SheetViewer, signedInMember(t, app)) |
| + guest, err := app.grant(nil, s.ID, "ada@elsewhere.example", SheetViewer, signedInMember(t, app)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| mail := app.testMailer(t) |
| postSignin(t, app, "ada@elsewhere.example") |
| link := mail.lastLink(t) |
| - if err := app.revoke(s.ID, guest.ID); err != nil { |
| + if err := app.revoke(nil, s.ID, guest.ID); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/sheets/store/guard.go b/internal/sheets/store/guard.go| new file mode 100644 |
| index 0000000..b2f1ea9 |
| --- /dev/null |
| +++ b/internal/sheets/store/guard.go |
| @@ -0,0 +1,77 @@ |
| +package store |
| + |
| +import "gorm.io/gorm" |
| + |
| +// Guard runs one write inside that write's own transaction, and may |
| +// refuse it: before the write, after it, or both. A refusal rolls the |
| +// transaction back. The app's team mode passes teammode.Guard here, so a |
| +// person's roster standing is checked inside the SQLite writer |
| +// transaction that commits their edit, not only in the handler before it |
| +// (Home implementation/teammode-package.md §3, invariant 13). A Guard |
| +// must not wait on anything that needs the writer: teammode's never asks |
| +// the roster, it reads the lease the request already holds. |
| +// |
| +// A nil Guard is no guard, and every write takes exactly the path it |
| +// took before guards existed. |
| +type Guard func(write func() error) error |
| + |
| +// Run is write under g, or write alone when there is no guard. |
| +func (g Guard) Run(write func() error) error { |
| + if g == nil { |
| + return write() |
| + } |
| + return g(write) |
| +} |
| + |
| +// Writer is a Handle whose writes run under a Guard. Reads, and the |
| +// row and column allocation (EnsureRow, EnsureCol), stay the Handle's: |
| +// an empty grid coordinate is no edit, and the write that uses it is |
| +// guarded. |
| +type Writer struct { |
| + h *Handle |
| + g Guard |
| +} |
| + |
| +// Guarded is h with every write below run under g. |
| +func (h *Handle) Guarded(g Guard) Writer { return Writer{h: h, g: g} } |
| + |
| +// SetReport is Handle.SetReport under the guard. Only the transaction |
| +// that commits the input is guarded; the recalculation that follows |
| +// persists derived values, which are nobody's edit, and Open recovers |
| +// them if they are missing. |
| +func (w Writer) SetReport(rowID, colID uint64, raw string, actor uint64) (Report, error) { |
| + return w.h.setReport(w.g, rowID, colID, raw, actor) |
| +} |
| + |
| +// SetBatch is Handle.SetBatch under the guard: the batch's one |
| +// transaction. |
| +func (w Writer) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| + return w.h.setBatch(w.g, writes, actor) |
| +} |
| + |
| +// SetFormat is Handle.SetFormat under the guard, in one transaction. |
| +func (w Writer) SetFormat(rowID, colID uint64, f Format) error { |
| + return w.h.setFormat(w.g, rowID, colID, f) |
| +} |
| + |
| +// SetColWidth is Handle.SetColWidth under the guard, in one transaction. |
| +func (w Writer) SetColWidth(colID uint64, width int) error { |
| + return w.h.setColWidth(w.g, colID, width) |
| +} |
| + |
| +// SetRowHeight is Handle.SetRowHeight under the guard, in one transaction. |
| +func (w Writer) SetRowHeight(rowID uint64, height int) error { |
| + return w.h.setRowHeight(w.g, rowID, height) |
| +} |
| + |
| +// guardedDB runs op against h.db exactly as it always has when g is nil, |
| +// and otherwise against one transaction, inside g. For writes that had no |
| +// transaction of their own. |
| +func (h *Handle) guardedDB(g Guard, op func(db *gorm.DB) error) error { |
| + if g == nil { |
| + return op(h.db) |
| + } |
| + return h.db.Transaction(func(tx *gorm.DB) error { |
| + return g(func() error { return op(tx) }) |
| + }) |
| +} |
diff --git a/internal/sheets/store/handle_grid.go b/internal/sheets/store/handle_grid.go| index d087dfe..c0f101c 100644 |
| --- a/internal/sheets/store/handle_grid.go |
| +++ b/internal/sheets/store/handle_grid.go |
| @@ -162,27 +162,35 @@ func (h *Handle) RawInput(rowID, colID uint64) (string, bool) { |
| // Cell, so a formatted-but-empty cell (a coloured header nothing has been |
| // typed into yet) still needs a row to carry it. |
| func (h *Handle) SetFormat(rowID, colID uint64, f Format) error { |
| + return h.setFormat(nil, rowID, colID, f) |
| +} |
| + |
| +// setFormat is SetFormat under g (guard.go): with a guard, the intern and |
| +// the assignment are one transaction. |
| +func (h *Handle) setFormat(g Guard, rowID, colID uint64, f Format) error { |
| h.mu.Lock() |
| defer h.mu.Unlock() |
| if _, ok := h.cellKey(rowID, colID); !ok { |
| return fmt.Errorf("store: row %d col %d is not part of tab %d", rowID, colID, h.tabID) |
| } |
| - formatID, err := h.internFormat(f) |
| - if err != nil { |
| - return err |
| - } |
| - return h.assignFormat(rowID, colID, formatID) |
| + return h.guardedDB(g, func(db *gorm.DB) error { |
| + formatID, err := h.internFormat(db, f) |
| + if err != nil { |
| + return err |
| + } |
| + return h.assignFormat(db, rowID, colID, formatID) |
| + }) |
| } |
| // internFormat finds the existing Format row matching f's content |
| // (by digest) or creates one. A duplicate-key race against a concurrent |
| // interner of the identical format is resolved by re-reading rather than |
| // failing: the digest's uniqueIndex is what makes that safe. |
| -func (h *Handle) internFormat(f Format) (uint64, error) { |
| +func (h *Handle) internFormat(db *gorm.DB, f Format) (uint64, error) { |
| digest := formatDigest(f) |
| var existing Format |
| - err := h.db.Where("digest = ?", digest).First(&existing).Error |
| + err := db.Where("digest = ?", digest).First(&existing).Error |
| if err == nil { |
| return existing.ID, nil |
| } |
| @@ -191,12 +199,12 @@ func (h *Handle) internFormat(f Format) (uint64, error) { |
| } |
| f.Digest = digest |
| - if err := h.db.Create(&f).Error; err != nil { |
| + if err := db.Create(&f).Error; err != nil { |
| // Another writer interned the same content between the lookup |
| // above and this Create — re-read rather than propagating what |
| // is, from the caller's point of view, not really a failure. |
| var again Format |
| - if err2 := h.db.Where("digest = ?", digest).First(&again).Error; err2 == nil { |
| + if err2 := db.Where("digest = ?", digest).First(&again).Error; err2 == nil { |
| return again.ID, nil |
| } |
| return 0, fmt.Errorf("store: create format: %w", err) |
| @@ -246,9 +254,9 @@ func formatDigest(f Format) string { |
| // assignFormat points the cell at (rowID, colID)'s FormatID at formatID, |
| // creating the Cell row (with empty sealed input) if none exists yet. |
| -func (h *Handle) assignFormat(rowID, colID, formatID uint64) error { |
| +func (h *Handle) assignFormat(db *gorm.DB, rowID, colID, formatID uint64) error { |
| var cell Cell |
| - err := h.db.Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| + err := db.Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| First(&cell).Error |
| if errors.Is(err, gorm.ErrRecordNotFound) { |
| sealedEmpty, serr := h.sealer.Seal("cell.input", []byte("")) |
| @@ -256,7 +264,7 @@ func (h *Handle) assignFormat(rowID, colID, formatID uint64) error { |
| return fmt.Errorf("store: seal empty input for format-only cell: %w", serr) |
| } |
| id := formatID |
| - return h.db.Create(&Cell{ |
| + return db.Create(&Cell{ |
| TabID: h.tabID, RowID: rowID, ColID: colID, |
| InputSealed: sealedEmpty, FormatID: &id, |
| }).Error |
| @@ -265,7 +273,7 @@ func (h *Handle) assignFormat(rowID, colID, formatID uint64) error { |
| return fmt.Errorf("store: look up cell for format assignment: %w", err) |
| } |
| id := formatID |
| - return h.db.Model(&Cell{}). |
| + return db.Model(&Cell{}). |
| Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| Update("format_id", &id).Error |
| } |
diff --git a/internal/sheets/store/handle_report.go b/internal/sheets/store/handle_report.go| index ff7a414..0ba0671 100644 |
| --- a/internal/sheets/store/handle_report.go |
| +++ b/internal/sheets/store/handle_report.go |
| @@ -95,6 +95,11 @@ func (h *Handle) Version() uint64 { |
| // edit that a failed transaction then rolled back, and the client has no |
| // way to un-paint it. |
| func (h *Handle) SetReport(rowID, colID uint64, raw string, actor uint64) (Report, error) { |
| + return h.setReport(nil, rowID, colID, raw, actor) |
| +} |
| + |
| +// setReport is SetReport with its input transaction run under g (guard.go). |
| +func (h *Handle) setReport(g Guard, rowID, colID uint64, raw string, actor uint64) (Report, error) { |
| h.mu.Lock() |
| defer h.mu.Unlock() |
| @@ -120,9 +125,9 @@ func (h *Handle) SetReport(rowID, colID uint64, raw string, actor uint64) (Repor |
| capped bool |
| ) |
| if blank { |
| - touched, capped, err = h.setBlank(rowID, colID, key, v, actor, prevRaw) |
| + touched, capped, err = h.setBlank(g, rowID, colID, key, v, actor, prevRaw) |
| } else { |
| - touched, capped, err = h.setContent(rowID, colID, key, node, raw, v, actor, prevRaw) |
| + touched, capped, err = h.setContent(g, rowID, colID, key, node, raw, v, actor, prevRaw) |
| } |
| if err != nil { |
| return Report{}, err |
diff --git a/internal/sheets/store/handle_set.go b/internal/sheets/store/handle_set.go| index c64abbc..a337a01 100644 |
| --- a/internal/sheets/store/handle_set.go |
| +++ b/internal/sheets/store/handle_set.go |
| @@ -43,7 +43,7 @@ func (h *Handle) Set(rowID, colID uint64, raw string, actor uint64) error { |
| // It returns the dependents it actually recomputed, and whether the |
| // dependent set was too wide to recompute at all — SetReport turns both |
| // into a report a live client can either paint or resync from. |
| -func (h *Handle) setBlank(rowID, colID uint64, key calc.CellKey, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) { |
| +func (h *Handle) setBlank(guard Guard, rowID, colID uint64, key calc.CellKey, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) { |
| // TransitiveDependents reads g.dependents[key], which Clear (called |
| // below, after this transaction commits) never touches — only key's |
| // own precedent edges are rewired by Clear — so this is safe to |
| @@ -52,31 +52,33 @@ func (h *Handle) setBlank(rowID, colID uint64, key calc.CellKey, v uint64, actor |
| withinCap := len(touched) > 0 && len(touched) <= calc.MaxDirtyPerPass |
| if err := h.db.Transaction(func(tx *gorm.DB) error { |
| - if err := h.advanceContentVersion(tx, v); err != nil { |
| - return err |
| - } |
| - if err := tx.Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| - Delete(&Cell{}).Error; err != nil { |
| - return err |
| - } |
| - // Marking is unconditional on len(touched) > 0 — NOT gated by |
| - // withinCap. MaxDirtyPerPass bounds the RECOMPUTE below (a full |
| - // Eval of every touched cell), not this marker (one version-bump |
| - // UPDATE per touched cell). Past the cap this cell's own row is |
| - // gone, so a durable marker on every dependent is the only |
| - // recovery signal that will ever exist for them; skipping it |
| - // here — as this code once did — left them looking permanently |
| - // consistent (CacheVersion == InputVersion, both untouched) while |
| - // silently reading a cell that no longer exists. See |
| - // TestBlankFeederOverCapDependentsAreRecoverable. |
| - if len(touched) > 0 { |
| - if err := h.markDirty(tx, touched, v); err != nil { |
| + return guard.Run(func() error { |
| + if err := h.advanceContentVersion(tx, v); err != nil { |
| return err |
| } |
| - } |
| - return AppendInput(tx, h.sealer, InputEvent{ |
| - TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor, |
| - OldRaw: prevRaw, NewRaw: "", |
| + if err := tx.Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| + Delete(&Cell{}).Error; err != nil { |
| + return err |
| + } |
| + // Marking is unconditional on len(touched) > 0 — NOT gated by |
| + // withinCap. MaxDirtyPerPass bounds the RECOMPUTE below (a full |
| + // Eval of every touched cell), not this marker (one version-bump |
| + // UPDATE per touched cell). Past the cap this cell's own row is |
| + // gone, so a durable marker on every dependent is the only |
| + // recovery signal that will ever exist for them; skipping it |
| + // here — as this code once did — left them looking permanently |
| + // consistent (CacheVersion == InputVersion, both untouched) while |
| + // silently reading a cell that no longer exists. See |
| + // TestBlankFeederOverCapDependentsAreRecoverable. |
| + if len(touched) > 0 { |
| + if err := h.markDirty(tx, touched, v); err != nil { |
| + return err |
| + } |
| + } |
| + return AppendInput(tx, h.sealer, InputEvent{ |
| + TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor, |
| + OldRaw: prevRaw, NewRaw: "", |
| + }) |
| }) |
| }); err != nil { |
| return nil, false, err |
| @@ -121,37 +123,39 @@ func (h *Handle) setBlank(rowID, colID uint64, key calc.CellKey, v uint64, actor |
| // recalculates forward from it. |
| // It returns everything the recalculation touched — the edited cell |
| // included — and whether the pass was too wide to run. |
| -func (h *Handle) setContent(rowID, colID uint64, key calc.CellKey, node calc.Node, raw string, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) { |
| +func (h *Handle) setContent(guard Guard, rowID, colID uint64, key calc.CellKey, node calc.Node, raw string, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) { |
| sealedInput, err := h.sealer.Seal("cell.input", []byte(raw)) |
| if err != nil { |
| return nil, false, err |
| } |
| if err := h.db.Transaction(func(tx *gorm.DB) error { |
| - if err := h.advanceContentVersion(tx, v); err != nil { |
| - return err |
| - } |
| - res := tx.Model(&Cell{}). |
| - Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| - Updates(map[string]any{ |
| - "input_sealed": sealedInput, |
| - "input_version": v, |
| - "updated_by": actor, |
| - }) |
| - if res.Error != nil { |
| - return res.Error |
| - } |
| - if res.RowsAffected == 0 { |
| - if err := tx.Create(&Cell{ |
| - TabID: h.tabID, RowID: rowID, ColID: colID, |
| - InputSealed: sealedInput, InputVersion: v, |
| - UpdatedBy: actor, |
| - }).Error; err != nil { |
| + return guard.Run(func() error { |
| + if err := h.advanceContentVersion(tx, v); err != nil { |
| return err |
| } |
| - } |
| - return AppendInput(tx, h.sealer, InputEvent{ |
| - TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor, |
| - OldRaw: prevRaw, NewRaw: raw, |
| + res := tx.Model(&Cell{}). |
| + Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID). |
| + Updates(map[string]any{ |
| + "input_sealed": sealedInput, |
| + "input_version": v, |
| + "updated_by": actor, |
| + }) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + if err := tx.Create(&Cell{ |
| + TabID: h.tabID, RowID: rowID, ColID: colID, |
| + InputSealed: sealedInput, InputVersion: v, |
| + UpdatedBy: actor, |
| + }).Error; err != nil { |
| + return err |
| + } |
| + } |
| + return AppendInput(tx, h.sealer, InputEvent{ |
| + TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor, |
| + OldRaw: prevRaw, NewRaw: raw, |
| + }) |
| }) |
| }); err != nil { |
| return nil, false, err |
diff --git a/internal/sheets/store/handle_sizes.go b/internal/sheets/store/handle_sizes.go| index 2aff9d3..9da5216 100644 |
| --- a/internal/sheets/store/handle_sizes.go |
| +++ b/internal/sheets/store/handle_sizes.go |
| @@ -1,6 +1,10 @@ |
| package store |
| -import "fmt" |
| +import ( |
| + "fmt" |
| + |
| + "gorm.io/gorm" |
| +) |
| // Column widths and row heights. |
| // |
| @@ -70,18 +74,26 @@ func (h *Handle) Sizes() (cols map[int]int, rows map[int]int, err error) { |
| // it here instead would put grid positions back into a method that |
| // otherwise speaks only in stable ids. |
| func (h *Handle) SetColWidth(colID uint64, width int) error { |
| + return h.setColWidth(nil, colID, width) |
| +} |
| + |
| +// SetRowHeight is SetColWidth's twin. |
| +func (h *Handle) SetRowHeight(rowID uint64, height int) error { |
| + return h.setRowHeight(nil, rowID, height) |
| +} |
| + |
| +func (h *Handle) setColWidth(g Guard, colID uint64, width int) error { |
| if err := checkSize(width); err != nil { |
| return err |
| } |
| - return h.updateSize(&Col{}, "width", colID, width, "column") |
| + return h.guardedDB(g, func(db *gorm.DB) error { return h.updateSize(db, &Col{}, "width", colID, width, "column") }) |
| } |
| -// SetRowHeight is SetColWidth's twin. |
| -func (h *Handle) SetRowHeight(rowID uint64, height int) error { |
| +func (h *Handle) setRowHeight(g Guard, rowID uint64, height int) error { |
| if err := checkSize(height); err != nil { |
| return err |
| } |
| - return h.updateSize(&Row{}, "height", rowID, height, "row") |
| + return h.guardedDB(g, func(db *gorm.DB) error { return h.updateSize(db, &Row{}, "height", rowID, height, "row") }) |
| } |
| func checkSize(v int) error { |
| @@ -97,8 +109,8 @@ func checkSize(v int) error { |
| // ambiguous — it is a primary key — but because it makes the query |
| // refuse to write to another tab's row if a caller ever passes an id |
| // from the wrong handle. The id alone would happily do it. |
| -func (h *Handle) updateSize(model any, column string, id uint64, v int, what string) error { |
| - res := h.db.Model(model). |
| +func (h *Handle) updateSize(db *gorm.DB, model any, column string, id uint64, v int, what string) error { |
| + res := db.Model(model). |
| Where("id = ? AND tab_id = ?", id, h.tabID). |
| Update(column, v) |
| if res.Error != nil { |
diff --git a/internal/sheets/store/handle_write_batch.go b/internal/sheets/store/handle_write_batch.go| index 74f4340..489ba3a 100644 |
| --- a/internal/sheets/store/handle_write_batch.go |
| +++ b/internal/sheets/store/handle_write_batch.go |
| @@ -17,6 +17,11 @@ type CellWrite struct { |
| var errCellBatch = errors.New("store: invalid cell batch") |
| func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| + return h.setBatch(nil, writes, actor) |
| +} |
| + |
| +// setBatch is SetBatch with its one transaction run under g (guard.go). |
| +func (h *Handle) setBatch(g Guard, writes []CellWrite, actor uint64) (Report, error) { |
| if len(writes) == 0 || len(writes) > MaxCellBatch { |
| return Report{}, errCellBatch |
| } |
| @@ -37,53 +42,55 @@ func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| var staged *Handle |
| var result Report |
| err := h.db.Transaction(func(tx *gorm.DB) error { |
| - var err error |
| - staged, err = buildHandle(tx, h.sealer, h.tabID) |
| - if err != nil { |
| - return err |
| - } |
| - if staged.nextVersion < h.nextVersion { |
| - staged.nextVersion = h.nextVersion |
| - } |
| - changed := make(map[CellCoord]ChangedCell) |
| - direct := make(map[CellCoord]bool) |
| - for _, w := range writes { |
| - r, err := staged.EnsureRow(w.Row) |
| + return g.Run(func() error { |
| + var err error |
| + staged, err = buildHandle(tx, h.sealer, h.tabID) |
| if err != nil { |
| return err |
| } |
| - c, err := staged.EnsureCol(w.Col) |
| - if err != nil { |
| - return err |
| + if staged.nextVersion < h.nextVersion { |
| + staged.nextVersion = h.nextVersion |
| } |
| - rep, err := staged.SetReport(r, c, w.Raw, actor) |
| - if err != nil { |
| - return err |
| + changed := make(map[CellCoord]ChangedCell) |
| + direct := make(map[CellCoord]bool) |
| + for _, w := range writes { |
| + r, err := staged.EnsureRow(w.Row) |
| + if err != nil { |
| + return err |
| + } |
| + c, err := staged.EnsureCol(w.Col) |
| + if err != nil { |
| + return err |
| + } |
| + rep, err := staged.SetReport(r, c, w.Raw, actor) |
| + if err != nil { |
| + return err |
| + } |
| + if rep.Capped { |
| + return errCellBatch |
| + } |
| + direct[CellCoord{r, c}] = true |
| + result.Version = rep.Version |
| + for _, cell := range rep.Cells { |
| + changed[CellCoord{cell.RowID, cell.ColID}] = cell |
| + } |
| + if len(changed) > calc.MaxDirtyPerPass { |
| + return errCellBatch |
| + } |
| } |
| - if rep.Capped { |
| - return errCellBatch |
| + var count int64 |
| + if err := tx.Model(&Cell{}).Where("tab_id = ?", h.tabID).Count(&count).Error; err != nil { |
| + return err |
| } |
| - direct[CellCoord{r, c}] = true |
| - result.Version = rep.Version |
| - for _, cell := range rep.Cells { |
| - changed[CellCoord{cell.RowID, cell.ColID}] = cell |
| + if count > MaxCellsPerTab { |
| + return ErrTabTooLarge |
| } |
| - if len(changed) > calc.MaxDirtyPerPass { |
| - return errCellBatch |
| + for coord, cell := range changed { |
| + cell.Derived = !direct[coord] |
| + result.Cells = append(result.Cells, cell) |
| } |
| - } |
| - var count int64 |
| - if err := tx.Model(&Cell{}).Where("tab_id = ?", h.tabID).Count(&count).Error; err != nil { |
| - return err |
| - } |
| - if count > MaxCellsPerTab { |
| - return ErrTabTooLarge |
| - } |
| - for coord, cell := range changed { |
| - cell.Derived = !direct[coord] |
| - result.Cells = append(result.Cells, cell) |
| - } |
| - return nil |
| + return nil |
| + }) |
| }) |
| if err != nil { |
| return Report{}, err |
diff --git a/internal/sheets/stream_revoke_test.go b/internal/sheets/stream_revoke_test.go| index af6d639..a0f4c74 100644 |
| --- a/internal/sheets/stream_revoke_test.go |
| +++ b/internal/sheets/stream_revoke_test.go |
| @@ -33,7 +33,7 @@ func TestARevokedGuestStopsReceivingCells(t *testing.T) { |
| t.Fatalf("the guest did not receive the first edit: %q", line) |
| } |
| - if err := app.revoke(s.ID, ada.ID); err != nil { |
| + if err := app.revoke(nil, s.ID, ada.ID); err != nil { |
| t.Fatalf("revoke: %v", err) |
| } |
| postCell(t, app, cookies, cells, `{"r":0,"c":1,"raw":"CONFIDENTIAL"}`) |
diff --git a/internal/sheets/team_access.go b/internal/sheets/team_access.go| index 7f61275..9307061 100644 |
| --- a/internal/sheets/team_access.go |
| +++ b/internal/sheets/team_access.go |
| @@ -3,22 +3,24 @@ 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: |
| +// Standing itself is home/teammode's Access. 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. |
| +// work, and the sheet list shows them with a "partial" notice (Paul, |
| +// 2026-10-28); anything else 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. |
| +// time it is asked, and a write checks it again inside its own |
| +// transaction, before and after the write (team_guard.go). |
| import ( |
| "context" |
| @@ -26,11 +28,11 @@ import ( |
| "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/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| @@ -38,38 +40,35 @@ import ( |
| type teamAccessKey struct{} |
| -// teamAccess is one request's standing. Never stored; a stream asks for |
| -// a new one before each delivery. |
| +// teamAccess is one request's standing: the member the session resolved |
| +// to and teammode's Access for their Home subject (Member, NotMember or |
| +// Unknown, with the lease re-checked and Unknown latched every time it |
| +// is asked). Never stored; a stream asks for a new one before each |
| +// delivery. A nil Access is Unknown. |
| 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 |
| + member Member |
| + *teammode.Access |
| } |
| var errNoIdentity = errors.New("sheets: no team identity") |
| func (t *teamAccess) state() roster.State { |
| - if t == nil || t.uncertain.Load() { |
| + if t == nil { |
| return roster.Unknown |
| } |
| - if t.decision.State == roster.Member && !t.decision.Lease.Valid() { |
| - t.uncertain.Store(true) |
| - return roster.Unknown |
| - } |
| - return t.decision.State |
| + return t.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 { |
| + if t == nil { |
| return TeamGuest |
| } |
| - if t.decision.Role == "owner" { |
| + switch t.Role() { |
| + case "": |
| + return TeamGuest |
| + case "owner": |
| return TeamOwner |
| } |
| return TeamMember |
| @@ -104,20 +103,14 @@ func (a *App) ownGrantIgnored(g Grant, m Member) bool { |
| } |
| // homeMemberID is the member a Home subject signs in as: an account link |
| -// first, then a Home-only member. It never creates either. |
| +// first, then a Home-only member (connect's Resolve, with the HomeOnly |
| +// hook ConfigureHome gives it in team mode). 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 |
| + return p.ID, err |
| } |
| // teamIdentify resolves the actual session to a member and the Home |
| @@ -145,7 +138,7 @@ func (a *App) teamIdentify(ctx context.Context, s sessions.Session) (Member, str |
| if err != nil { |
| return Member{}, "", errTeamUnavailable |
| } |
| - subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.bindings.Issuer, int64(m.ID)) |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.issuer(), int64(m.ID)) |
| if errors.Is(err, teamstate.ErrRefused) { |
| return m, "", nil |
| } |
| @@ -169,11 +162,7 @@ func (a *App) resolveTeamAccess(r *http.Request) (*teamAccess, error) { |
| 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 |
| + return &teamAccess{member: m, Access: a.team.Access(r.Context(), subject)}, nil |
| } |
| // actor is the member a handler acts as: the stored row with the |
| @@ -192,18 +181,26 @@ 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)) |
| + t := &teamAccess{member: m} |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.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} |
| + t.Access = a.team.Access(ctx, subject) |
| + case errors.Is(err, teamstate.ErrRefused): |
| + t.Access = a.team.Access(ctx, "") // no Home identity: NotMember, unasked |
| } |
| + // Anything else leaves Access nil, which is Unknown. |
| return t.actor() |
| } |
| +// asGuest is m as the share rung alone sees them: no team standing, so |
| +// roleFor reaches only what somebody else shared with them. It never asks |
| +// the roster. writeGuard uses it to tell a write a share allows from one |
| +// that rests on standing. |
| +func (a *App) asGuest(ctx context.Context, m Member) Member { |
| + return (&teamAccess{member: m, Access: a.team.Access(ctx, "")}).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 |
| @@ -240,7 +237,11 @@ func (a *App) teamRequire(next http.Handler) http.Handler { |
| return |
| } |
| session.Subject = teamJobOwner(t.member.ID) |
| - r = r.WithContext(context.WithValue(r.Context(), teamAccessKey{}, t)) |
| + // Twice: Sheets' own handlers read the member with it, and |
| + // teammode.Guard reads the same Access inside a write's |
| + // transaction (team_guard.go), so both see one latched standing. |
| + ctx := teammode.WithAccess(context.WithValue(r.Context(), teamAccessKey{}, t), t.Access) |
| + r = r.WithContext(ctx) |
| next.ServeHTTP(w, sessions.WithSession(r, session)) |
| })) |
| } |
diff --git a/internal/sheets/team_access_test.go b/internal/sheets/team_access_test.go| index 17e98f7..eaf49ad 100644 |
| --- a/internal/sheets/team_access_test.go |
| +++ b/internal/sheets/team_access_test.go |
| @@ -20,7 +20,7 @@ func teamSheet(t *testing.T, f *teamFixture, title string) SheetSummary { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - s, err := f.app.createSheet(title, other) |
| + s, err := f.app.createSheet(nil, title, other) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -44,7 +44,7 @@ func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) { |
| f := newTeamFixture(t) |
| plan := teamSheet(t, f, "Team plan") |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + 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()) |
| @@ -66,7 +66,7 @@ func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) { |
| } |
| session := f.jar[f.app.homeSessions.CookieName()] |
| - f.dir.set(a, "") |
| + 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") |
| @@ -78,6 +78,8 @@ func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) { |
| } |
| 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) |
| + } else if strings.Contains(list.Body.String(), "data-partial") { |
| + t.Error("a NotMember's list is marked partial: a guest's shares are their whole list") |
| } |
| 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) |
| @@ -105,7 +107,7 @@ func TestTeamStandingIsTheRostersNeverTheStoredRole(t *testing.T) { |
| } |
| p := teamSubject('p') |
| - f.dir.set(p, "owner") |
| + 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. |
| @@ -127,7 +129,7 @@ func TestTeamStandingIsTheRostersNeverTheStoredRole(t *testing.T) { |
| 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.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) |
| @@ -135,7 +137,7 @@ func TestTeamStandingIsTheRostersNeverTheStoredRole(t *testing.T) { |
| colleague, _ := f.app.memberFor("colleague@example.com") |
| shared := teamSheet(t, f, "Shared") |
| - if _, err := f.app.grant(shared.ID, signedInAddress, SheetViewer, colleague); err != nil { |
| + if _, err := f.app.grant(nil, shared.ID, signedInAddress, SheetViewer, colleague); err != nil { |
| t.Fatal(err) |
| } |
| @@ -148,15 +150,27 @@ func TestTeamStandingIsTheRostersNeverTheStoredRole(t *testing.T) { |
| 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) |
| + // Paul's ruling (2026-10-28): the list under Unknown is the shares, |
| + // marked partial, never a 503 for the whole page and never the team's. |
| + if rec := f.get(t, "/sheets"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Shared") || |
| + strings.Contains(rec.Body.String(), "Team plan") || !strings.Contains(rec.Body.String(), "data-partial") || |
| + !strings.Contains(rec.Body.String(), "Only sheets shared with you are shown.") { |
| + t.Errorf("list under Unknown standing = %d, want the shares marked partial", rec.Code) |
| + } |
| + native := httptest.NewRequest("GET", testOrigin+"/sheets", nil) |
| + native.Header.Set("Accept", "application/json") |
| + for _, c := range f.jar { |
| + native.AddCookie(c) |
| + } |
| + if rec := do(t, f.app, native); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Partial":true`) || strings.Contains(rec.Body.String(), "Team plan") { |
| + t.Errorf("native list under Unknown standing = %d %s, want the shares marked partial", rec.Code, rec.Body.String()) |
| } |
| 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.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) |
| @@ -175,14 +189,14 @@ func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| f := newTeamFixture(t) |
| plan := teamSheet(t, f, "Team plan") |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + f.dir.Set(a, "member") |
| f.signInHome(t, a) |
| - f.dir.setDown(true) |
| - f.clock.step(59 * time.Second) |
| + 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) |
| + 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")) |
| @@ -201,8 +215,8 @@ func TestTeamSignInAllocatesOnlyForACurrentMember(t *testing.T) { |
| t.Fatal("a stranger got a session or a member") |
| } |
| - f.dir.set(teamSubject('a'), "member") |
| - f.dir.set(teamSubject('b'), "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) |
| @@ -213,7 +227,7 @@ func TestTeamSignInAllocatesOnlyForACurrentMember(t *testing.T) { |
| 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 |
| + // Over a local session it reaches connect's completion, which refuses an |
| // unknown arrival before allocating anything. |
| f.jar = map[string]*http.Cookie{} |
| f.local(t, "local@example.com") |
diff --git a/internal/sheets/team_answers.go b/internal/sheets/team_answers.go| index 33f5a15..e0eb94d 100644 |
| --- a/internal/sheets/team_answers.go |
| +++ b/internal/sheets/team_answers.go |
| @@ -1,7 +1,7 @@ |
| 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 |
| +// partial list, 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 ( |
| @@ -32,6 +32,22 @@ func (a *App) unavailable(w http.ResponseWriter, r *http.Request) { |
| a.answer(w, r, http.StatusServiceUnavailable, kindStatus, "Try again in a moment.") |
| } |
| +// teamPartial reports whether a list built for viewer is incomplete |
| +// because their standing is Unknown: Paul's ruling (2026-10-28, Home |
| +// implementation/teammode-package.md §4) is a partial list with a |
| +// notice, not a 503. visibleSheets has already withheld the team rung, so |
| +// the list holds the person's shares and nothing more. Ask it after |
| +// building the list, of the same Access the list was built with: State |
| +// latches, so a lease that lapsed while listing marks the page partial. |
| +// NotMember is never partial: a guest's shares are their whole list. |
| +// Always false outside team mode. |
| +func (a *App) teamPartial(viewer Member) bool { |
| + if a.team == nil { |
| + return false |
| + } |
| + return viewer.team == nil || viewer.team.Partial() |
| +} |
| + |
| // 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 |
| @@ -74,7 +90,7 @@ func (a *App) streamAccess(r *http.Request, sheetID uint64) (bool, time.Duration |
| if t.state() != roster.Member { |
| return true, 0 |
| } |
| - renew := t.decision.Lease.Remaining() |
| + renew := t.Remaining() |
| if renew <= 0 { |
| renew = time.Second |
| } |
| @@ -96,7 +112,7 @@ func (m Member) Label() string { |
| return m.Address |
| } |
| if m.team != nil { |
| - return homeOnlyLabel(m.team.subject) |
| + return homeOnlyLabel(m.team.Subject()) |
| } |
| return teamLabel |
| } |
| @@ -115,7 +131,7 @@ 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) |
| + rows, err := a.team.db.QueryContext(ctx, "SELECT member_id, subject FROM sheets_team_home_members WHERE issuer=?", a.team.issuer()) |
| if err != nil { |
| return nil |
| } |
diff --git a/internal/sheets/team_config.go b/internal/sheets/team_config.go| index 35d9261..dcb4159 100644 |
| --- a/internal/sheets/team_config.go |
| +++ b/internal/sheets/team_config.go |
| @@ -1,220 +1,124 @@ |
| 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, |
| +// team-members.md Part B, §7). Configuration, the marker, the roster |
| +// runtime and the probe are home/teammode's (Home implementation/ |
| +// teammode-package.md §6 maps each piece of Sheets' own copy onto it): |
| +// 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/oficina/home/teammode" |
| "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") |
| + errTeamConfig = teammode.ErrConfig |
| + errTeamUnavailable = teammode.ErrUnavailable |
| ) |
| -// 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 |
| -} |
| +// teamState is the marker and the roster evidence, in Sheets' own |
| +// tables (sheets_team_required, sheets_team_roster_evidence). Their |
| +// schema stays teamstate.Schema, never teamState.Schema(): Sheets' |
| +// 0001_team.sql also holds the Home-only member table, and the |
| +// migration ledger checksums the whole file. |
| +var teamState = teammode.MustState("sheets") |
| + |
| +// teamIssuerTables are the tables holding Home identities in an issuer |
| +// column: connect's links and Sheets' Home-only members. teammode.Open |
| +// refuses activation while any row names another issuer. |
| +var teamIssuerTables = []string{"home_identity_links", "sheets_team_home_members"} |
| // 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 |
| +// TeamSettings verifies team configuration for this instance: nil, nil |
| +// with team mode off; otherwise a verified record or errTeamConfig. Team |
| +// mode exists only beside Home, so the Home credentials are decoded here |
| +// for their issuer and consumer ID. It touches no database, which is |
| +// what lets main decide the schema before anything migrates. |
| +func TeamSettings(cfg *teammode.Config, home *connect.Credentials, origin string) (*teammode.Settings, error) { |
| + if cfg == nil { |
| + return nil, nil |
| } |
| - decoded, err := base64.StdEncoding.Strict().DecodeString(encoded) |
| - if err != nil || len(decoded) > limit || base64.StdEncoding.EncodeToString(decoded) != encoded { |
| - return nil, false |
| + creds, err := connect.DecodeCredentials(home, origin) |
| + if err != nil || creds == nil { |
| + return nil, errTeamConfig |
| } |
| - return decoded, true |
| + return teammode.Verify(cfg, &teammode.Home{Issuer: creds.Issuer, ConsumerID: creds.ConsumerID}, "sheets", origin) |
| } |
| -// 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 |
| +// BootSchemaFor is the schema main applies, chosen before anything is |
| +// migrated. A database activated in team mode refuses to boot without |
| +// team configuration, or with a different binding: an environment |
| +// variable dropped in a redeploy must not quietly hand standing back to |
| +// SHEETS_OWNERS. |
| +func BootSchemaFor(ctx context.Context, db *sql.DB, settings *teammode.Settings) (*migrate.Set, error) { |
| + return teamState.BootSchema(ctx, db, settings, BootSchema, TeamBootSchema) |
| } |
| -// teamRuntime is the process's roster cache and the pieces that act on |
| -// its answers. |
| +// teamRuntime is the process's roster runtime and the database the |
| +// Home-only member table lives in. |
| 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 |
| + *teammode.Runtime |
| + db *sql.DB |
| } |
| -// 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 |
| -} |
| +func (t *teamRuntime) issuer() string { return t.Bindings().Issuer } |
| -// 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 { |
| +// ConfigureTeam runs after ConfigureHome and before serving. Without |
| +// team settings (Config.Team) it does nothing. Anything else either |
| +// produces a verified, activated runtime or refuses boot: there is no |
| +// falling back to the allowlist. |
| +func (a *App) ConfigureTeam() error { |
| + settings := a.teamSettings |
| + if settings == 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 |
| + // The settings were verified against the Home credentials main |
| + // decoded; these are the ones the bridge was built with. They must |
| + // be the same deployment. |
| + b := settings.Bindings() |
| + if b.Issuer != a.homeCreds.Issuer || b.Consumer != a.homeCreds.ConsumerID || b.Audience != a.origin { |
| + return errTeamConfig |
| } |
| 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}) |
| + rt, err := teammode.Open(context.Background(), teammode.RuntimeConfig{Settings: settings, State: teamState, DB: d, Sealer: sealer, |
| + IssuerTables: teamIssuerTables, Transport: a.teamTransport, Clock: a.teamClock}) |
| 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 |
| + return err |
| } |
| - a.team = t |
| + a.team = &teamRuntime{Runtime: rt, db: d} |
| return nil |
| } |
| + |
| +// teamTest is what a test sets on an App before ConfigureTeam: a |
| +// directory that answers in memory and a clock it can step. Production |
| +// leaves both nil. |
| +type teamTest struct { |
| + teamTransport http.RoundTripper |
| + teamClock roster.Clock |
| +} |
diff --git a/internal/sheets/team_config_test.go b/internal/sheets/team_config_test.go| index d83afb5..1d38dd1 100644 |
| --- a/internal/sheets/team_config_test.go |
| +++ b/internal/sheets/team_config_test.go |
| @@ -10,41 +10,82 @@ import ( |
| rdb "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| - "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| ) |
| // The record is verified against bindings built only from configuration; |
| -// change any one input and ConfigureTeam refuses. Team mode without Home |
| +// change any one input and TeamSettings 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 { |
| + if _, err := TeamSettings(cfg, &f.creds, 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 = "" }, |
| + for name, change := range map[string]func(*teammode.Config){ |
| + "team": func(c *teammode.Config) { c.TeamID = "TeamB" }, |
| + "directory": func(c *teammode.Config) { c.DirectoryOrigin = "https://other.example.com" }, |
| + "token": func(c *teammode.Config) { c.RosterToken += "=" }, |
| + "record": func(c *teammode.Config) { c.ProvisioningBase64 += "\n" }, |
| + "operator": func(c *teammode.Config) { c.OperatorKeysBase64 = "e30=" }, |
| + "missing team": func(c *teammode.Config) { c.TeamID = "" }, |
| } { |
| bad := *cfg |
| change(&bad) |
| - if _, err := validatedTeamConfig(&bad, f.app.homeCreds, testOrigin); !errors.Is(err, errTeamConfig) { |
| + if _, err := TeamSettings(&bad, &f.creds, 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) { |
| + if _, err := TeamSettings(cfg, &f.creds, "https://elsewhere.example.com"); !errors.Is(err, errTeamConfig) { |
| t.Error("a record for another origin was accepted") |
| } |
| + other := f.creds |
| + other.ConsumerID = "someone-else" |
| + if _, err := TeamSettings(cfg, &other, testOrigin); !errors.Is(err, errTeamConfig) { |
| + t.Error("a record for another Home consumer was accepted") |
| + } |
| + if _, err := TeamSettings(cfg, nil, testOrigin); !errors.Is(err, errTeamConfig) { |
| + t.Error("team mode without Home credentials was accepted") |
| + } |
| plain, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| - if err := plain.ConfigureTeam(cfg); !errors.Is(err, errTeamConfig) { |
| + plain.teamSettings = teamSettingsFor(t, cfg) |
| + if err := plain.ConfigureTeam(); !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") |
| + // Settings verified for another deployment (here, another origin) |
| + // than the Home credentials the bridge was built with: refused. |
| + elsewhere := teammodetest.Bindings("sheets", "sheets-preview", "https://elsewhere.example.com") |
| + otherCfg, _ := teamConfigFor(t, elsewhere) |
| + otherSettings, err := teammode.Verify(otherCfg, teammodetest.Home(elsewhere), "sheets", elsewhere.Audience) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mismatched, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| + mismatched.teamSettings = otherSettings |
| + homeOn(t, mismatched, "") |
| + if err := mismatched.ConfigureTeam(); !errors.Is(err, errTeamConfig) || mismatched.team != nil { |
| + t.Errorf("settings for another deployment = %v, want refusal", err) |
| + } |
| + // And for another Home consumer at this origin. |
| + consumer := teammodetest.Bindings("sheets", "another-consumer", testOrigin) |
| + consumerCfg, _ := teamConfigFor(t, consumer) |
| + consumerSettings, err := teammode.Verify(consumerCfg, teammodetest.Home(consumer), "sheets", testOrigin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wrongConsumer, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| + wrongConsumer.teamSettings = consumerSettings |
| + homeOn(t, wrongConsumer, "") |
| + if err := wrongConsumer.ConfigureTeam(); !errors.Is(err, errTeamConfig) { |
| + t.Errorf("settings for another consumer = %v, want refusal", err) |
| + } |
| + none, _ := appWithSchema(t, testOrigin, TeamBootSchema, signedInAddress) |
| + if err := none.ConfigureTeam(); err != nil || none.team != nil { |
| + t.Error("no team settings changed something") |
| + } |
| + if s, err := TeamSettings(nil, &f.creds, testOrigin); s != nil || err != nil { |
| + t.Error("no team config made team settings") |
| } |
| } |
| @@ -58,30 +99,27 @@ func TestTeamEnvIsAllOrNoneAndOwnersBecomeOptional(t *testing.T) { |
| t.Setenv("SHEETS_ORIGIN", "http://127.0.0.1:8080") |
| t.Setenv("SHEETS_INSTANCE_KEY", "k") |
| t.Setenv("SHEETS_OWNERS", "") |
| - if TeamConfigFromEnv() != nil { |
| + if teammode.ConfigFromEnv("SHEETS") != 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) |
| + if err != nil || env.Team == nil || env.Team.RosterToken != "x" || env.Team.TeamID != "" || len(env.Owners) != 0 { |
| + t.Fatalf("one team variable was not a (partial) team config, or team mode still required SHEETS_OWNERS: %v", err) |
| } |
| f := newHomeFixture(t) |
| - if err := f.app.ConfigureTeam(env.Team); !errors.Is(err, errTeamConfig) { |
| + if _, err := TeamSettings(env.Team, &f.creds, testOrigin); !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. |
| +// configuration, or with a different binding, before anything migrates. |
| +// The triggers refuse rewriting it; a database never activated boots as |
| +// before. |
| func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| ctx := context.Background() |
| f := newTeamFixture(t) |
| @@ -89,14 +127,14 @@ func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - got, activated, err := teamstate.Required(ctx, d) |
| + 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) { |
| + if _, err := BootSchemaFor(ctx, d, nil); !errors.Is(err, errTeamConfig) { |
| t.Error("an activated database booted without team configuration") |
| } |
| - if s, err := BootSchemaFor(ctx, d, true); err != nil || s != TeamBootSchema { |
| + if s, err := BootSchemaFor(ctx, d, f.app.teamSettings); 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 { |
| @@ -106,13 +144,17 @@ func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| t.Error("the marker was deleted") |
| } |
| - // Same database, another team's record: refused. |
| + // Same database, another team's record: refused at boot, and at |
| + // activation. |
| 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) { |
| + otherSettings := teamSettingsFor(t, cfg) |
| + if _, err := BootSchemaFor(ctx, d, otherSettings); !errors.Is(err, errTeamConfig) { |
| + t.Error("an activated database booted with a different binding") |
| + } |
| + f.app.team, f.app.teamSettings = nil, otherSettings |
| + if err := f.app.ConfigureTeam(); !errors.Is(err, errTeamConfig) { |
| t.Errorf("a different binding = %v, want refusal", err) |
| } |
| @@ -122,7 +164,7 @@ func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { fresh.Close() }) |
| - if s, err := BootSchemaFor(ctx, fresh.Writer(), false); err != nil || s != BootSchema { |
| + if s, err := BootSchemaFor(ctx, fresh.Writer(), nil); 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 |
| @@ -130,7 +172,7 @@ func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| if _, err := migrate.Apply(ctx, fresh, TeamBootSchema); err != nil { |
| t.Fatal(err) |
| } |
| - if s, err := BootSchemaFor(ctx, fresh.Writer(), false); err != nil || s != BootSchema { |
| + if s, err := BootSchemaFor(ctx, fresh.Writer(), nil); err != nil || s != BootSchema { |
| t.Fatal("an unactivated team schema locked the database") |
| } |
| if _, err := migrate.Apply(ctx, fresh, BootSchema); err != nil { |
diff --git a/internal/sheets/team_fixture_test.go b/internal/sheets/team_fixture_test.go| index 46bb550..8149848 100644 |
| --- a/internal/sheets/team_fixture_test.go |
| +++ b/internal/sheets/team_fixture_test.go |
| @@ -1,142 +1,57 @@ |
| 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" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| ) |
| -// 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. |
| +// Team mode's fixture: Home configured exactly as newHomeFixture does, and |
| +// home/teammode's test directory (teammodetest) answering the roster in |
| +// memory from a member list a test can change or take down, with a roster |
| +// clock a test can step past the lease. |
| const ( |
| - teamTestDirectory = "https://home.example.com" |
| - teamTestTeam = "TeamA" |
| + teamTestDirectory = teammodetest.DirectoryOrigin |
| + teamTestTeam = teammodetest.Team |
| ) |
| // teamSubject is a well-formed person ref: "pr_" and 26 base32 letters. |
| -func teamSubject(c byte) string { return "pr_" + strings.Repeat(string(c), 26) } |
| +func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| -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 |
| +func teamTestBindings() roster.Bindings { |
| + return teammodetest.Bindings("sheets", "sheets-preview", testOrigin) |
| } |
| // teamConfigFor signs a provisioning record for bindings with a fresh |
| -// operator key, and returns the TeamConfig that carries it plus the |
| +// operator key, and returns the configuration that carries it plus the |
| // directory that will answer for it. |
| -func teamConfigFor(t *testing.T, b roster.Bindings) (*TeamConfig, *teamTestDirectoryServer) { |
| +func teamConfigFor(t *testing.T, b roster.Bindings) (*teammode.Config, *teammodetest.Directory) { |
| 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 |
| + return teammodetest.Provision(t, b) |
| } |
| -func teamTestBindings() roster.Bindings { |
| - return roster.Bindings{Issuer: homeTestIssuer, Directory: teamTestDirectory, Consumer: "sheets-preview", App: "sheets", Team: teamTestTeam, Audience: testOrigin} |
| +// teamSettingsFor verifies cfg for the test instance, as main does |
| +// before it migrates. |
| +func teamSettingsFor(t *testing.T, cfg *teammode.Config) *teammode.Settings { |
| + t.Helper() |
| + s, err := teammode.Verify(cfg, teammodetest.Home(teamTestBindings()), "sheets", testOrigin) |
| + if err != nil { |
| + t.Fatalf("team settings: %v", err) |
| + } |
| + return s |
| } |
| type teamFixture struct { |
| *homeFixture |
| - dir *teamTestDirectoryServer |
| - clock *teamTestClock |
| - cfg *TeamConfig |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| + cfg *teammode.Config |
| } |
| // newTeamFixture is a team-mode instance. owners is SHEETS_OWNERS, which |
| @@ -150,14 +65,24 @@ func newTeamFixture(t *testing.T, owners ...string) *teamFixture { |
| // 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 { |
| + f := newTeamApp(t, directory, owners...) |
| + if err := f.app.ConfigureTeam(); err != nil { |
| t.Fatalf("ConfigureTeam: %v", err) |
| } |
| + return f |
| +} |
| + |
| +// newTeamApp is newTeamFixtureWith before ConfigureTeam: the app built |
| +// as main builds a team-mode one (TeamBootSchema, verified settings in |
| +// Config.Team, Home configured with them), with the test directory and |
| +// clock in place of the real ones. |
| +func newTeamApp(t *testing.T, directory string, owners ...string) *teamFixture { |
| + t.Helper() |
| + cfg, dir := teamConfigFor(t, teamTestBindings()) |
| + app, _ := appWithSchema(t, testOrigin, TeamBootSchema, owners...) |
| + clock := teammodetest.NewClock() |
| + app.teamSettings, app.teamTransport, app.teamClock = teamSettingsFor(t, cfg), dir, clock |
| + f := homeOn(t, app, directory) |
| return &teamFixture{homeFixture: f, dir: dir, clock: clock, cfg: cfg} |
| } |
| @@ -174,8 +99,8 @@ func (f *teamFixture) signInHome(t *testing.T, subject string) *httptest.Respons |
| // 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 { |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + if err := f.app.team.Refresh(t.Context()); err != nil { |
| t.Fatalf("roster refresh: %v", err) |
| } |
| } |
| @@ -183,8 +108,8 @@ func (f *teamFixture) refreshed(t *testing.T) { |
| // 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) |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| } |
| func (f *teamFixture) get(t *testing.T, path string) *httptest.ResponseRecorder { |
diff --git a/internal/sheets/team_guard.go b/internal/sheets/team_guard.go| new file mode 100644 |
| index 0000000..ecfb382 |
| --- /dev/null |
| +++ b/internal/sheets/team_guard.go |
| @@ -0,0 +1,88 @@ |
| +package sheets |
| + |
| +// Team mode's write guard: the request's standing checked again inside |
| +// the transaction that commits a write, before and after it |
| +// (teammode.Guard; Fable's deviation 7 on oficina/sheets #52). The |
| +// handler's roleFor decides whether the write may start; this decides |
| +// whether it may commit, so a lease that lapses between the two fails the |
| +// write instead of landing it. It never asks the roster: it reads the |
| +// Access teamRequire put on the request, whose lease check never waits, |
| +// so it is safe under the one-connection SQLite writer. |
| +// |
| +// Outside team mode every guard here is nil, and a nil store.Guard is the |
| +// write path exactly as it was. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +// writeGuard is the guard for m writing to a sheet with a role of at |
| +// least need, which roleFor has already granted. When a share somebody |
| +// else gave reaches need on its own, the write does not rest on |
| +// standing, and Unknown may still make it (the rule teammode leaves to |
| +// the app). Otherwise the role came from the team rung — standing, the |
| +// creator's own grant, or a roster owner's orphaned sheet — and every one |
| +// of those holds only while the roster says Member. |
| +func (a *App) writeGuard(ctx context.Context, sheetID uint64, m Member, need SheetRole) store.Guard { |
| + if a.team == nil { |
| + return nil |
| + } |
| + authorize := teammode.RequireMember |
| + if role, ok := a.roleFor(sheetID, a.asGuest(ctx, m)); ok && role.Allows(need) { |
| + authorize = func(roster.State) error { return nil } |
| + } |
| + return func(write func() error) error { return teamGuard(ctx, authorize, write) } |
| +} |
| + |
| +// memberGuard is the guard for a write only team members may make at |
| +// all (create, import). |
| +func (a *App) memberGuard(ctx context.Context) store.Guard { |
| + if a.team == nil { |
| + return nil |
| + } |
| + return func(write func() error) error { return teamGuard(ctx, teammode.RequireMember, write) } |
| +} |
| + |
| +// teamGuard is teammode.Guard. A variable only so a test can let the lease |
| +// run out between the write and its commit on every write route. |
| +var teamGuard = teammode.Guard |
| + |
| +// guarded runs write against the app's database exactly as it always |
| +// has when g is nil, and otherwise in one transaction, inside g, against |
| +// that transaction (never the outer handle: the writer pool has one |
| +// connection). |
| +func (a *App) guarded(g store.Guard, write func(db *gorm.DB) error) error { |
| + if g == nil { |
| + return write(a.db) |
| + } |
| + return a.db.Transaction(func(tx *gorm.DB) error { |
| + return g(func() error { return write(tx) }) |
| + }) |
| +} |
| + |
| +// guardRefused answers a write the guard refused, and reports whether it |
| +// did. Standing lapsed between the handler's check and the commit: the |
| +// same retryable 503 as Unknown anywhere else, and a 404 for a definite |
| +// NotMember (which one request's Access cannot reach once it has said |
| +// Member, but costs nothing to answer correctly). Outside team mode no |
| +// error is ever one of these. |
| +func (a *App) guardRefused(w http.ResponseWriter, r *http.Request, err error) bool { |
| + switch { |
| + case errors.Is(err, teammode.ErrUnavailable): |
| + a.unavailable(w, r) |
| + case errors.Is(err, teammode.ErrNotMember): |
| + a.answer(w, r, http.StatusNotFound, kindSheet, "Not found.") |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
diff --git a/internal/sheets/team_guard_test.go b/internal/sheets/team_guard_test.go| new file mode 100644 |
| index 0000000..dce7b96 |
| --- /dev/null |
| +++ b/internal/sheets/team_guard_test.go |
| @@ -0,0 +1,293 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + rdb "amadan.net/rastrillo/rastrillo/db" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +// teamWriter is the signed-in viewer as a write handler sees them: the |
| +// member, and a request context carrying the same Access the guard reads. |
| +func (f *teamFixture) teamWriter(t *testing.T) (*http.Request, Member) { |
| + t.Helper() |
| + r := httptest.NewRequest("POST", testOrigin+"/sheets", nil) |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + access, err := f.app.resolveTeamAccess(r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r.WithContext(teammode.WithAccess(r.Context(), access.Access)), access.actor() |
| +} |
| + |
| +// Fable's deviation 7 on #52, closed: standing is checked inside the |
| +// transaction that commits a write, after the write as well as before it. |
| +// A lease that lapses mid-write fails the commit and leaves nothing behind, |
| +// in the store's cell transaction and in the app's own writes alike. |
| +func TestTeamWriteFailsWhenTheLeaseLapsesMidWrite(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + a := teamSubject('a') |
| + f.dir.Set(a, "member") |
| + f.signInHome(t, a) |
| + r, viewer := f.teamWriter(t) |
| + guard := f.app.writeGuard(r.Context(), plan.ID, viewer, SheetEditor) |
| + if guard == nil { |
| + t.Fatal("team mode gave a write no guard") |
| + } |
| + // The write runs, then the lease runs out before the commit. |
| + lapsing := store.Guard(func(write func() error) error { |
| + return guard(func() error { |
| + if err := write(); err != nil { |
| + return err |
| + } |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return nil |
| + }) |
| + }) |
| + |
| + h, err := store.Open(f.app.db, f.app.sealer, plan.TabID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rowID, _ := h.EnsureRow(0) |
| + colID, _ := h.EnsureCol(0) |
| + if _, err := h.Guarded(lapsing).SetReport(rowID, colID, "42", viewer.ID); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("cell write across a lapsed lease = %v, want ErrUnavailable", err) |
| + } |
| + h.Release() |
| + h, err = store.Open(f.app.db, f.app.sealer, plan.TabID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if raw, ok := h.RawInput(rowID, colID); ok || raw != "" { |
| + t.Errorf("a refused cell write committed %q", raw) |
| + } |
| + h.Release() |
| + |
| + // The request's Access has latched Unknown: a guarded write does not |
| + // even start now. |
| + started := false |
| + if err := guard(func() error { started = true; return nil }); !errors.Is(err, teammode.ErrUnavailable) || started { |
| + t.Errorf("write after the lapse = %v (started %v), want refused before it runs", err, started) |
| + } |
| + if err := f.app.addComment(guard, plan.TabID, rowID, colID, "hello", viewer); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Errorf("comment after the lapse = %v, want ErrUnavailable", err) |
| + } |
| + var comments int64 |
| + f.app.db.Model(&Comment{}).Count(&comments) |
| + if comments != 0 { |
| + t.Errorf("a refused comment was stored") |
| + } |
| +} |
| + |
| +// What a share reaches does not rest on standing, so Unknown may still |
| +// write through it (the app's rule; teammode decides nothing itself). The |
| +// team rung under Unknown is the handler's retryable 503. |
| +func TestTeamShareStillWritesUnderUnknownStanding(t *testing.T) { |
| + f := newTeamFixture(t) |
| + plan := teamSheet(t, f, "Team plan") |
| + shared := teamSheet(t, f, "Shared") |
| + a := teamSubject('a') |
| + f.dir.Set(a, "member") |
| + f.signInHome(t, a) |
| + _, me := f.teamWriter(t) |
| + var row teamHomeMember |
| + if err := f.app.db.Raw("SELECT member_id FROM sheets_team_home_members").Scan(&row).Error; err != nil || row.MemberID != me.ID { |
| + t.Fatalf("no Home-only member: %v", err) |
| + } |
| + colleague, _ := f.app.memberFor("colleague@example.com") |
| + // A share needs an address; a Home-only member has none, so the grant |
| + // is written as the share screen's upsert would write it. |
| + if err := f.app.db.Create(&Grant{SheetID: shared.ID, MemberID: me.ID, Role: string(SheetEditor), GrantedBy: colleague.ID}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + f.expired(t) |
| + cells := func(s SheetSummary) string { return fmt.Sprintf("/api/sheets/%d/tabs/%d/cells", s.ID, s.TabID) } |
| + if post := postCellAs(t, f, cells(shared), `{"r":0,"c":0,"raw":"via the share"}`); post.Code != http.StatusOK { |
| + t.Errorf("a share's write under Unknown = %d %s, want 200", post.Code, post.Body.String()) |
| + } |
| + if post := postCellAs(t, f, cells(plan), `{"r":0,"c":0,"raw":"via the team"}`); post.Code != http.StatusServiceUnavailable { |
| + t.Errorf("a team sheet's write under Unknown = %d, want 503", post.Code) |
| + } |
| +} |
| + |
| +type teamHomeMember struct{ MemberID uint64 } |
| + |
| +// Outside team mode there is no guard, and every write takes the path it |
| +// always took. |
| +func TestNoGuardOutsideTeamMode(t *testing.T) { |
| + app, _ := appWithOrigin(t, testOrigin) |
| + m := signedInMember(t, app) |
| + s, err := app.createSheet(nil, "Plain", m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest("POST", testOrigin+"/sheets", nil) |
| + if app.writeGuard(r.Context(), s.ID, m, SheetEditor) != nil || app.memberGuard(r.Context()) != nil { |
| + t.Fatal("a guard outside team mode") |
| + } |
| +} |
| + |
| +// Every write route threads the guard into its transaction and answers a |
| +// lapse inside it with the retryable 503: the lease runs out after each |
| +// write and before its commit, and the route must refuse. |
| +func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| + f := newTeamFixture(t) |
| + a := teamSubject('a') |
| + f.dir.Set(a, "owner") |
| + f.signInHome(t, a) |
| + created := f.request(t, "POST", "/sheets", url.Values{"title": {"Mine"}}, false) |
| + if created.Code != http.StatusSeeOther { |
| + t.Fatalf("create = %d", created.Code) |
| + } |
| + var s SheetSummary |
| + for _, sheet := range mustList(t, f) { |
| + s = sheet |
| + } |
| + sheet := fmt.Sprintf("/sheets/%d", s.ID) |
| + api := fmt.Sprintf("/api/sheets/%d/tabs/%d", s.ID, s.TabID) |
| + // Something to undo, revoke and turn off, written without a lapse. |
| + if post := postCellAs(t, f, api+"/cells", `{"r":0,"c":0,"raw":"kept"}`); post.Code != http.StatusOK { |
| + t.Fatalf("setup write = %d", post.Code) |
| + } |
| + _, me := f.teamWriter(t) |
| + guest, err := f.app.grant(nil, s.ID, "guest@example.com", SheetViewer, me) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.app.createLink(nil, s.ID, SheetViewer, me); err != nil { |
| + t.Fatal(err) |
| + } |
| + links, _ := f.app.linksOn(s.ID) |
| + |
| + lapse := func() { |
| + teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + return teammode.Guard(ctx, authorize, func() error { |
| + if err := write(); err != nil { |
| + return err |
| + } |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return nil |
| + }) |
| + } |
| + } |
| + t.Cleanup(func() { teamGuard = teammode.Guard }) |
| + form := func(path string, v url.Values) func() *httptest.ResponseRecorder { |
| + return func() *httptest.ResponseRecorder { return f.request(t, "POST", path, v, false) } |
| + } |
| + js := func(path, body string) func() *httptest.ResponseRecorder { |
| + return func() *httptest.ResponseRecorder { return postCellAs(t, f, path, body) } |
| + } |
| + for _, c := range []struct { |
| + name string |
| + do func() *httptest.ResponseRecorder |
| + }{ |
| + {"create", form("/sheets", url.Values{"title": {"Another"}})}, |
| + {"cell", js(api+"/cells", `{"r":0,"c":0,"raw":"lost"}`)}, |
| + {"batch", js(api+"/cells/batch", `{"cells":[{"r":0,"c":0,"raw":"lost"}]}`)}, |
| + {"format", js(api+"/format", `{"r1":0,"c1":0,"r2":0,"c2":0,"bold":true}`)}, |
| + {"size", js(api+"/size", `{"col":0,"size":120}`)}, |
| + {"table", form(sheet+"/table", url.Values{"r": {"0"}, "c": {"0"}, "raw": {"lost"}})}, |
| + {"undo", form(sheet+"/undo", url.Values{})}, |
| + {"rename", form(sheet+"/rename", url.Values{"title": {"Lost"}})}, |
| + {"comment", form(sheet+"/comments", url.Values{"r": {"0"}, "c": {"0"}, "body": {"lost"}})}, |
| + {"resolve", form(sheet+"/comments/resolve", url.Values{"r": {"0"}, "c": {"0"}})}, |
| + {"view", form(sheet+"/view", url.Values{"sortCol": {"0"}})}, |
| + {"share", form(sheet+"/share", url.Values{"address": {"new@example.com"}, "role": {"viewer"}})}, |
| + {"revoke", form(sheet+"/share/revoke", url.Values{"member": {fmt.Sprint(guest.ID)}})}, |
| + {"link", form(sheet+"/share/link", url.Values{"role": {"viewer"}})}, |
| + {"link revoke", form(sheet+"/share/link/revoke", url.Values{"link": {fmt.Sprint(links[0].ID)}})}, |
| + {"import", func() *httptest.ResponseRecorder { |
| + up := uploadRequest(t, "lost.xlsx", corpusFile(t, "formulas.xlsx")) |
| + req := httptest.NewRequest(http.MethodPost, testOrigin+"/sheets/import", up.Body) |
| + req.Header = up.Header |
| + req.Header.Set("Origin", testOrigin) |
| + for _, c := range f.jar { |
| + req.AddCookie(c) |
| + } |
| + return do(t, f.app, req) |
| + }}, |
| + } { |
| + f.refreshed(t) |
| + lapse() |
| + rec := c.do() |
| + teamGuard = teammode.Guard |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Errorf("%s with the lease lapsing before commit = %d, want 503", c.name, rec.Code) |
| + } |
| + } |
| + |
| + // Nothing any of them wrote survived. |
| + f.refreshed(t) |
| + list := mustList(t, f) |
| + if len(list) != 1 || list[0].Title != "Mine" { |
| + t.Errorf("sheets after refused writes = %+v, want Mine alone", list) |
| + } |
| + h, err := store.Open(f.app.db, f.app.sealer, s.TabID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Release() |
| + idx := newPosIndex(h) |
| + if raw, _ := h.RawInput(idx.rowID[0], idx.colID[0]); raw != "kept" { |
| + t.Errorf("cell after refused writes = %q, want kept", raw) |
| + } |
| + var n int64 |
| + if f.app.db.Model(&Comment{}).Count(&n); n != 0 { |
| + t.Errorf("comments after a refused comment = %d, want 0", n) |
| + } |
| + if f.app.db.Model(&Grant{}).Where("sheet_id = ?", s.ID).Count(&n); n != 2 { |
| + t.Errorf("grants after refused share and revoke = %d, want 2", n) |
| + } |
| + if live, _ := f.app.linksOn(s.ID); len(live) != 1 { |
| + t.Errorf("links after refused create and revoke = %d, want 1", len(live)) |
| + } |
| +} |
| + |
| +func mustList(t *testing.T, f *teamFixture) []SheetSummary { |
| + t.Helper() |
| + _, me := f.teamWriter(t) |
| + list, err := f.app.listSheets(me) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return list |
| +} |
| + |
| +// A Home-only lookup that cannot read storage is "cannot decide", never |
| +// "nobody": connect would otherwise go on to allocate a member for a |
| +// subject that may already have one. |
| +func TestTeamHomeOnlyStorageFailureIsNotNobody(t *testing.T) { |
| + f := newTeamFixture(t) |
| + d, err := f.app.db.DB() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + closed, err := rdb.Open(filepath.Join(t.TempDir(), "closed.db"), quietLogger()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + closed.Close() |
| + if _, err := f.app.teamHomeOnly(closed.Writer())(t.Context(), homeTestIssuer, teamSubject('a')); err == nil || errors.Is(err, connect.ErrNoPerson) { |
| + t.Errorf("HomeOnly over unreadable storage = %v, want unavailable", err) |
| + } |
| + if _, err := f.app.teamHomeOnly(d)(t.Context(), homeTestIssuer, teamSubject('a')); !errors.Is(err, connect.ErrNoPerson) { |
| + t.Errorf("HomeOnly for nobody = %v, want ErrNoPerson", err) |
| + } |
| +} |
diff --git a/internal/sheets/team_home.go b/internal/sheets/team_home.go| deleted file mode 100644 |
| index 3f99ac9..0000000 |
| --- a/internal/sheets/team_home.go |
| +++ /dev/null |
| @@ -1,174 +0,0 @@ |
| -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_home_only.go b/internal/sheets/team_home_only.go| new file mode 100644 |
| index 0000000..fce41cf |
| --- /dev/null |
| +++ b/internal/sheets/team_home_only.go |
| @@ -0,0 +1,68 @@ |
| +package sheets |
| + |
| +// Home sign-in for a roster member with no account here: connect's two |
| +// team-mode hooks over Sheets' people table. connect completes an |
| +// ordinary Home sign-in only for a subject with an account link, 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 ConfigureHome |
| +// gives connect these, and connect's own completion does the rest (its |
| +// cookie checks, the same-person rule, the link flow). |
| +// |
| +// The member Unlinked creates is identity, never standing: every request |
| +// after this one asks the roster again (team_access.go). |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/teamstate" |
| +) |
| + |
| +// teamHomeOnly is connect's HomeOnly: the addressless member Unlinked |
| +// gave a subject, read and never created. |
| +func (a *App) teamHomeOnly(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + id, err := teamstate.HomeMember(ctx, d, issuer, subject) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
| + |
| +// teamUnlinked is connect's Unlinked, asked only when nobody is signed in |
| +// and the subject has neither a link nor a Home-only member: an |
| +// addressless member for a subject the roster says is a Member now, with |
| +// the lease on that answer still valid (Runtime.AdmitUnlinked). A |
| +// stranger is connect's "unknown"; an undecidable roster is a 503. |
| +func (a *App) teamUnlinked(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + if a.team == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if err := a.team.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + id, err := teamstate.EnsureHomeMember(ctx, d, issuer, subject) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + // Linked to a local account in the meantime: that person signs |
| + // in as that account, not as a new one. |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
diff --git a/internal/sheets/team_probe.go b/internal/sheets/team_probe.go| index 92bc4df..bc588ff 100644 |
| --- a/internal/sheets/team_probe.go |
| +++ b/internal/sheets/team_probe.go |
| @@ -1,77 +1,21 @@ |
| package sheets |
| import ( |
| - "context" |
| - "encoding/json" |
| "net/http" |
| - "strings" |
| - "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| ) |
| -// 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" |
| -} |
| +// teamProbePath is the readiness probe Alta polls at provisioning step 11 |
| +// before it activates this instance in Home's directory: teammode's |
| +// Probe, unauthenticated, no-store, {team_mode, consumer, roster} and no |
| +// account data, {"team_mode":false} with team mode off. |
| +const teamProbePath = teammode.ProbePath |
| func (a *App) handleTeamProbe(w http.ResponseWriter, r *http.Request) { |
| - probe := teamProbe{} |
| + var rt *teammode.Runtime |
| 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 |
| + rt = a.team.Runtime |
| } |
| - 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) |
| + teammode.Probe(rt).ServeHTTP(w, r) |
| } |
diff --git a/internal/sheets/team_probe_test.go b/internal/sheets/team_probe_test.go| index 1bef1fa..c8c7229 100644 |
| --- a/internal/sheets/team_probe_test.go |
| +++ b/internal/sheets/team_probe_test.go |
| @@ -38,13 +38,13 @@ func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| f := newTeamFixture(t) |
| a := teamSubject('a') |
| - f.dir.set(a, "owner") |
| - f.dir.setDown(true) |
| + 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) |
| + 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) |
diff --git a/internal/sheets/team_review_test.go b/internal/sheets/team_review_test.go| index 822ca8b..deaa10d 100644 |
| --- a/internal/sheets/team_review_test.go |
| +++ b/internal/sheets/team_review_test.go |
| @@ -35,7 +35,7 @@ func (f *teamFixture) getHTML(t *testing.T, path string) *httptest.ResponseRecor |
| // 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.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"`) { |
| @@ -55,7 +55,7 @@ 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.dir.Set(a, "member") |
| f.signInHome(t, a) |
| teamSheet(t, f, "Team plan") |
| shared := teamSheet(t, f, "Shared") |
| @@ -91,12 +91,12 @@ func TestTeamDashboardFeedFollowsTheRoster(t *testing.T) { |
| 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.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.dir.Set(a, "member") |
| f.refreshed(t) |
| f.expired(t) |
| if code, titles := feed(); code == http.StatusOK || len(titles) != 0 { |
| @@ -107,8 +107,8 @@ func TestTeamDashboardFeedFollowsTheRoster(t *testing.T) { |
| // 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, "") |
| + f := newTeamApp(t, "", signedInAddress) |
| + app := f.app |
| m, err := app.memberFor("linked@example.com") |
| if err != nil { |
| t.Fatal(err) |
| @@ -116,12 +116,11 @@ func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| 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) { |
| + if err := app.ConfigureTeam(); !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 { |
| + if _, activated, err := teamState.Required(t.Context(), d); err != nil || activated { |
| t.Fatal("a refused activation left a marker") |
| } |
| } |
| @@ -131,7 +130,7 @@ func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| f := newTeamFixture(t) |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + f.dir.Set(a, "member") |
| f.signInHome(t, a) |
| f.jar = map[string]*http.Cookie{} |
| f.local(t, "x@example.com") |
| @@ -156,9 +155,9 @@ func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| 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") |
| + 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) |
| @@ -169,7 +168,7 @@ func TestTeamRosterOwnerSharesOrphanedSheets(t *testing.T) { |
| } |
| orphan := create(a, "Orphan") |
| live := create(m, "Live") |
| - f.dir.set(a, "") |
| + f.dir.Set(a, "") |
| f.refreshed(t) |
| f.signInHome(t, m) |
| @@ -200,7 +199,7 @@ func TestTeamRosterOwnerSharesOrphanedSheets(t *testing.T) { |
| func TestTeamRevokeNoticeNamesAHomeOnlyMember(t *testing.T) { |
| f := newTeamFixture(t) |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + 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") |
| @@ -230,7 +229,7 @@ func TestTeamRevokeNoticeNamesAHomeOnlyMember(t *testing.T) { |
| func TestTeamRosterOwnerRuleSkipsDeletedSheets(t *testing.T) { |
| f := newTeamFixture(t) |
| o := teamSubject('o') |
| - f.dir.set(o, "owner") |
| + 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 { |
diff --git a/internal/sheets/team_stream_test.go b/internal/sheets/team_stream_test.go| index d2341b0..aacc080 100644 |
| --- a/internal/sheets/team_stream_test.go |
| +++ b/internal/sheets/team_stream_test.go |
| @@ -42,15 +42,15 @@ func TestTeamStreamClosesAtLeaseExpiry(t *testing.T) { |
| f := newTeamFixture(t) |
| plan := teamSheet(t, f, "Team plan") |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + f.dir.Set(a, "member") |
| f.signInHome(t, a) |
| - f.dir.setDown(true) |
| - f.clock.step(59 * time.Second) |
| + 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) |
| + 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) |
| } |
| @@ -68,19 +68,19 @@ func TestTeamStreamRenewsWhileStillAMember(t *testing.T) { |
| f := newTeamFixture(t) |
| plan := teamSheet(t, f, "Team plan") |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + 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 { |
| + f.clock.Step(59 * time.Second) |
| + f.dir.SetDown(true) |
| + if err := f.app.team.Refresh(t.Context()); err == nil { |
| t.Fatal("refresh succeeded with the directory down") |
| } |
| - f.dir.setDown(false) |
| + 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 |
| + 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 { |
| @@ -108,18 +108,18 @@ func TestTeamLeaseEndsAHeldDecision(t *testing.T) { |
| f := newTeamFixture(t) |
| plan := teamSheet(t, f, "Team plan") |
| a := teamSubject('a') |
| - f.dir.set(a, "member") |
| + 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) |
| + 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) |
| + 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") |
| } |
diff --git a/internal/sheets/teamstate/store.go b/internal/sheets/teamstate/store.go| index d9c8ce4..fc19906 100644 |
| --- a/internal/sheets/teamstate/store.go |
| +++ b/internal/sheets/teamstate/store.go |
| @@ -1,9 +1,10 @@ |
| -// 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. |
| +// Package teamstate keeps team mode's schema and the Home-only members a |
| +// roster admitted. The schema (sheets_team, 0001_team.sql) holds the |
| +// mandatory-mode marker and the roster evidence, which home/teammode's |
| +// State reads and writes (sheets.teamState), and the Home-only identity |
| +// table this package owns: Sheets' local people are its members table, so |
| +// a Home-only person is a members row with no address. The file stays |
| +// Sheets' own because the migration ledger checksums it whole. |
| // |
| // 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 |
| @@ -14,13 +15,11 @@ import ( |
| "context" |
| "database/sql" |
| "embed" |
| - "encoding/base64" |
| "errors" |
| "strings" |
| "time" |
| "unicode/utf8" |
| - "amadan.net/oficina/home/roster" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| ) |
| @@ -36,93 +35,6 @@ var ( |
| 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) { |
diff --git a/internal/sheets/teamstate/store_test.go b/internal/sheets/teamstate/store_test.go| index 2572ddc..a9f12d2 100644 |
| --- a/internal/sheets/teamstate/store_test.go |
| +++ b/internal/sheets/teamstate/store_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "strings" |
| "testing" |
| + "amadan.net/oficina/home/teammode" |
| rdb "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| @@ -115,7 +116,8 @@ func TestTeamTriggersRefuseDirectWrites(t *testing.T) { |
| t.Errorf("%s: allowed", name) |
| } |
| } |
| - if err := teamstate.Activate(ctx, db, "short"); !errors.Is(err, teamstate.ErrRefused) { |
| + // The marker is teammode's State over this schema's table. |
| + if err := teammode.MustState("sheets").Activate(ctx, db, "short"); !errors.Is(err, teammode.ErrConfig) { |
| t.Error("a malformed binding activated") |
| } |
| } |
diff --git a/internal/sheets/templates/sheets.html b/internal/sheets/templates/sheets.html| index c6881b6..099ba40 100644 |
| --- a/internal/sheets/templates/sheets.html |
| +++ b/internal/sheets/templates/sheets.html |
| @@ -43,7 +43,16 @@ |
| </div> |
| </header> |
| -{{if .Data.Sheets}} |
| +{{if .Data.Partial}}{{/* Team mode, standing Unknown (Paul, 2026-10-28): |
| + the list is what this person reaches without the team — their |
| + shares — and says so, rather than the whole page answering 503. |
| + Rendered only then, and nothing at all otherwise. */}}<div rst-callout rst-tone="warning" data-partial> |
| +<span rst-callout-ic aria-hidden="true">{{icon "alert-triangle"}}</span> |
| +<div rst-callout-body> |
| +<p>We couldn’t check your team access. Only sheets shared with you are shown.</p> |
| +</div> |
| +</div> |
| +{{end}}{{if .Data.Sheets}} |
| <ul rst-list data-sheet-list> |
| {{range .Data.Sheets}} |
| <li rst-lrow> |
| @@ -63,7 +72,7 @@ |
| </li> |
| {{end}} |
| </ul> |
| -{{else}} |
| +{{else if not .Data.Partial}} |
| {{/* The empty state points at the two controls in the top bar. It |
| used to say "make one above", which was true when the form was |
| directly above it and would now be a sentence pointing at a |
diff --git a/internal/sheets/viewspec.go b/internal/sheets/viewspec.go| index d9aafd0..1a4b50d 100644 |
| --- a/internal/sheets/viewspec.go |
| +++ b/internal/sheets/viewspec.go |
| @@ -7,6 +7,7 @@ import ( |
| "strconv" |
| "strings" |
| + "gorm.io/gorm" |
| "gorm.io/gorm/clause" |
| "amadan.net/oficina/sheets/internal/sheets/store" |
| @@ -103,7 +104,7 @@ func (a *App) loadView(tabID uint64) ViewSpec { |
| } |
| // saveView stores a tab's view, sealed. |
| -func (a *App) saveView(tabID uint64, spec ViewSpec, by Member) error { |
| +func (a *App) saveView(g store.Guard, tabID uint64, spec ViewSpec, by Member) error { |
| if a.db == nil { |
| return errNoDB |
| } |
| @@ -121,10 +122,12 @@ func (a *App) saveView(tabID uint64, spec ViewSpec, by Member) error { |
| if err != nil { |
| return err |
| } |
| - return a.db.Clauses(clause.OnConflict{ |
| - Columns: []clause.Column{{Name: "tab_id"}}, |
| - DoUpdates: clause.AssignmentColumns([]string{"spec_sealed", "updated_by", "updated_at"}), |
| - }).Create(&TabView{TabID: tabID, SpecSealed: sealed, UpdatedBy: by.ID}).Error |
| + return a.guarded(g, func(db *gorm.DB) error { |
| + return db.Clauses(clause.OnConflict{ |
| + Columns: []clause.Column{{Name: "tab_id"}}, |
| + DoUpdates: clause.AssignmentColumns([]string{"spec_sealed", "updated_by", "updated_at"}), |
| + }).Create(&TabView{TabID: tabID, SpecSealed: sealed, UpdatedBy: by.ID}).Error |
| + }) |
| } |
| // applyView turns a stored spec into the order rows should be shown in. |