Slides: roster team mode on home/teammode (Home team-members.md Part B; teammode-package.md §7.1), pinned with roster and connect at Home main 67c12e3. With the five SLIDES_TEAM_* variables set (all or none, only beside SLIDES_HOME_*), Home's roster decides standing on every request. Member gets the team rung, NotMember gets grants only, and Unknown gets grants with a retryable 503 elsewhere. SLIDES_ALLOWED_ADDRESSES becomes optional and only admits local sign-in. The marker (slides_team) is read before migrations, with a foreign-issuer census. Home-only members come in through connect's Unlinked/HomeOnly hooks, as addressless users. teammode.Guard runs inside every write transaction. Removal is revoked within the lease for sessions, agents, the deck stream and presentations; while standing is unknown, streams are held open delivering nothing rather than ended. GET /api/team is teammode.Probe. Paul's rulings: under Unknown the deck list is partial with a notice, the empty list included, never for NotMember, the dashboard feed and API list are unavailable, and items return a retryable 503 (2026-10-28). On an orphaned deck — team-rung only, owner definitely off the team — a roster owner may share it and change its title and theme, but may not delete it or narrow its rung (2026-10-30). Team mode off is byte-identical except /api/team returning {"team_mode":false}. Reviewed by Claude Fable 5.1 (claude-fable-5-1) on oficina/slides #33, APPROVED at 80fd3c9. Verified canary of 80fd3c9 on team-mode-slides.bds.oncarlos.com (own bundle, fresh instance key, Home and dashboard blanked, team mode off; production untouched at f1141cd): /api/version served v0.1.0-32-g80fd3c9, /api/team returned {"team_mode":false} with no-store, the local sign-in form rendered and a same-origin POST for a non-admitted address returned 303 ?sent=1, a cross-origin POST was 403, signed-out pages redirected to /signin with return_to, signed-out POSTs were 403, bad capabilities were 404, and the API without a valid token was 401. Team mode ON is verified only by the test suite until Home's roster serve is live. Canary removed and bundle cleared. Not deployed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Squashed from team-mode into main.
49 files changed,
+4,072
−242
AGENTS.md+88 −4cmd/slides/main.go+5 −0docs/api.md+9 −0docs/superpowers/specs/2026-09-07-slides-design.md+68 −0go.mod+3 −1go.sum+6 −2internal/slides/agents.go+18 −9internal/slides/api.go+41 −9internal/slides/app.go+24 −0internal/slides/assets.go+19 −7internal/slides/auth.go+17 −2internal/slides/chrome.go+23 −8internal/slides/config.go+15 −0internal/slides/dashboard.go+14 −1internal/slides/decks.go+183 −91internal/slides/decks_test.go+8 −8internal/slides/editor.go+1 −4internal/slides/exports.go+18 −7internal/slides/handlers.go+7 −0internal/slides/home.go+32 −7internal/slides/live.go+136 −45internal/slides/locales/en.toml+4 −0internal/slides/models.go+5 −0internal/slides/presentation.go+132 −9internal/slides/replay_long_test.go+1 −1internal/slides/sample.go+5 −2internal/slides/share.go+22 −11internal/slides/snapshot_fallback_test.go+3 −3internal/slides/snapshot_test.go+3 −3internal/slides/team_access.go+304 −0internal/slides/team_access_test.go+302 −0internal/slides/team_answers.go+128 −0internal/slides/team_config.go+109 −0internal/slides/team_config_test.go+197 −0internal/slides/team_fixture_test.go+256 −0internal/slides/team_guard.go+135 −0internal/slides/team_guard_test.go+292 −0internal/slides/team_home_only.go+82 −0internal/slides/team_owner.go+90 −0internal/slides/team_present.go+131 −0internal/slides/team_review_test.go+348 −0internal/slides/team_stream_test.go+351 −0internal/slides/team_survivors_test.go+248 −0internal/slides/teamstate/migrations/0001_home_users.sql+13 −0internal/slides/teamstate/store.go+162 −0internal/slides/templates/deck_settings.html+4 −4internal/slides/templates/decks.html+8 −2internal/slides/viewer.go+1 −1scripts/credits.py+1 −1
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index 69bb1aa..eabafad 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -64,7 +64,8 @@ seeded on first sign-in — and comes back out as a PDF. |
| every request** that resolves a principal, so taking an address off it |
| signs that person out of every device and refuses their agents' tokens |
| rather than leaving them everything they already held (spec §6.1, |
| - ruling 16, codex 6). |
| + ruling 16, codex 6). On a team instance Home's roster replaces that |
| + recheck (spec §6.4, "Team mode" below). |
| - **Decks**: list, create, settings, delete, three rungs (private, |
| granted, team) per suite ruling 15. |
| - **The viewer** (`internal/slides/viewer.go`): one slide per page, |
| @@ -140,13 +141,14 @@ plus `templates/` — with one file per screen area beside them (`auth.go`, |
| `decks.go`, `viewer.go`, `share.go`, `presentation.go`, `sample.go`, |
| `live.go`, `editor.go`, `snapshot.go`, `assets.go`, `svg.go`, |
| `thumbs.go`, `export.go`, `exports.go`, `api.go`, `agents.go`, |
| -`assets_embed.go`) and one |
| +`assets_embed.go`, and team mode's `team_*.go`) and one |
| package per concern nested underneath: `core` (the wazero host), `deck` |
| (Go types for the core's JSON view), `render` (slide HTML), `layout` |
| (the paint list), `svg` (the paint list as a picture), `fonts` (the |
| embedded faces and their metrics), `pdfcore` (the PDF module's wazero |
| host), `present` (the presentation SSE hub), `live` (the deck's own |
| -hub: seqs and presence). `internal/slides/static/` holds the vendored |
| +hub: seqs and presence), `teamstate` (team mode's Home-only users). |
| +`internal/slides/static/` holds the vendored |
| stylesheets and the committed editor bundle. `core/` at the repo root is |
| the Rust crate. `manifest/` and `gen/` are rastrillo's declarative path, |
| unused here. |
| @@ -556,6 +558,87 @@ rather than serving an editor that disagrees with the server. |
| EventSource for good. Any new long-lived handler must also return on |
| `a.draining.done()`. |
| +## Team mode (roster, `SLIDES_TEAM_*`) |
| + |
| +Home `implementation/team-members.md` Part B and |
| +`implementation/teammode-package.md` §7.1 ("Slides. As Sheets."), on the |
| +shared `home/teammode` package; Sheets main `8e28205` is the reference |
| +port. With the five `SLIDES_TEAM_*` variables set (`_ID`, |
| +`_DIRECTORY_ORIGIN`, `_PROVISIONING_BASE64`, `_OPERATOR_KEYS_BASE64`, |
| +`_ROSTER_TOKEN`; all or none, and only beside `SLIDES_HOME_*`), Home's |
| +roster decides standing on every request and `SLIDES_ALLOWED_ADDRESSES` |
| +becomes optional: if set it only admits local sign-in, empty it admits |
| +nobody locally, and it gives nobody standing. Without them nothing in |
| +`team_*.go` runs and every rule above stands; the one difference on a |
| +non-team instance is `GET /api/team` answering `{"team_mode":false}` |
| +(Paul's ruling on Sheets #52). |
| + |
| +- **Configuration, the marker, the runtime and the probe are |
| + `home/teammode`'s** (`team_config.go`): `teamSettings` verifies the |
| + record against the Home credentials `newApp` decoded, before anything |
| + migrates; `teamBootSchema` reads `slides_team_required` first and |
| + refuses an activated database without the same binding; `teamBoot` |
| + merges teammode's `slides_team` set and this repo's |
| + `slides_team_home` (`teamstate/`) after Slides' and linkstore's; |
| + `configureTeam` opens the runtime with the census over |
| + `home_identity_links` and `slides_team_home_users`. Do not grow a |
| + private copy back. A team-mode database stays in team mode: do not |
| + "fix" a refused boot by deleting the marker (its triggers refuse that |
| + anyway). |
| +- **Standing is the roster's, per request** (`team_access.go`): |
| + `currentUser` hands team mode to `teamCurrentUser`, which resolves the |
| + session to its user and Home subject and attaches `teammode.Access` as |
| + `User.team` (never a column). That replaces the allowlist recheck: |
| + Member is the team rung (own decks, team-rung decks, ownership of |
| + their own); NotMember reaches grants only; Unknown reaches grants with |
| + a partial list and answers a retryable 503 for anything else |
| + (`deckFor`, `ownedDeckFor`, create). Removed people keep their session, |
| + as in Docs and Sheets; a session whose identity cannot be read is a |
| + 503, never a sign-out. The bearer middleware does the same for an |
| + agent's operator. |
| +- **Home-only members** (`team_home_only.go`, `teamstate/`): connect's |
| + `Unlinked`/`HomeOnly` hooks, set only in team mode, give a roster |
| + Member with no account an addressless `users` row (`email NULL`), and |
| + the sample deck. Identity, never standing. They are shown as "Oficina |
| + account …xxxx" wherever an address would be (`homeOnlyLabel`). |
| +- **Every write is guarded inside its own transaction** |
| + (`team_guard.go`): `deckFor`/`ownedDeckFor` decide whether a write may |
| + start, `teammode.Guard` re-checks standing before and after it in the |
| + writer transaction. `applyOps`, `editDeck`, `appendUpdate` and |
| + `createDeckRow` take a `writeGuard`; app writes go through |
| + `a.guarded`. `deckGuard` for a write any reader makes (a grant carries |
| + it without standing), `memberGuard` for create and every owner action. |
| + Refusals answer through `guardRefused`. Nil outside team mode, and the |
| + write is then its old path exactly. |
| + `TestTeamEveryWriteRouteRefusesALapseBeforeCommit` lists every write |
| + route and reads the database back; add yours to it. |
| +- **Streams and talks re-decide.** The deck stream re-asks before every |
| + delivery and when a Member lease runs out (`teamStreamAccess`). A |
| + presentation stands on its presenter's reach (`team_present.go`): every |
| + `/p/…` request and every projector or follower delivery re-decides; a |
| + presenter who is gone ends the talk (as offboarding does), one whose |
| + standing is unknown gets a 503 on pages and the talk waits. While |
| + standing is unknown both streams are **held**, not ended: open, |
| + delivering nothing but comment pings, re-asked at `streamHoldRetry` |
| + (the roster's `RetryAfter`), and caught up when standing returns — a |
| + projector's EventSource fails for good on a 503, so `presentStream` |
| + opens under Unknown too. Without a Member lease only a grant holds — |
| + asked after the reach query, because `State` latches. |
| +- **Ownership and orphans** (`team_owner.go`; Paul, 2026-10-30, #33): an |
| + owner owns their deck only while Member. On an orphan — a team-rung |
| + deck whose owner the roster says is gone — a roster owner may share it |
| + and change its title and theme, and may not delete it or change its |
| + rung. One predicate per power (`mayShareDeck`, `mayRetitleDeck`, |
| + `mayChangeRung`, `mayDeleteDeck`), passed to `ownedDeckFor`: an owner |
| + screen asks for the one power it needs. A departed member's private |
| + deck is nobody's orphan. |
| +- **Lists under Unknown** (Paul, 2026-10-28): the deck list shows the |
| + grants with a notice (`teamPartial`, asked after listing, never for |
| + NotMember); the dashboard feed and the API's JSON list are unavailable |
| + instead, since neither can carry the notice. |
| +- **No object store on team instances.** When one is bound, presigned |
| + GETs are capped at the standing they were minted on (`presignTTLFor`). |
| + |
| ## Fonts: never a flash (Paul, 2026-10-26) |
| **"No flashing, ever!"** Slide text is never painted in one face and |
| @@ -811,7 +894,8 @@ beside the real ones would otherwise be a production-reachable path to a |
| public instance key and to every magic link landing in the instance log. |
| Anywhere but development, a missing `SLIDES_ORIGIN`, |
| `SLIDES_INSTANCE_KEY`, `SLIDES_SMTP_*` or `SLIDES_ALLOWED_ADDRESSES` is a |
| -startup refusal rather than a default. |
| +startup refusal rather than a default — except the allowlist in team |
| +mode, where it is optional and empty admits nobody locally. |
| ## The gate |
diff --git a/cmd/slides/main.go b/cmd/slides/main.go| index 028417d..8d591fa 100644 |
| --- a/cmd/slides/main.go |
| +++ b/cmd/slides/main.go |
| @@ -4,6 +4,7 @@ package main |
| import ( |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| "fmt" |
| "log/slog" |
| "os" |
| @@ -237,6 +238,10 @@ func main() { |
| homeConfig = &hc |
| } |
| mux, a, err := slides.New(d, slides.Config{Home: homeConfig, |
| + // Roster team mode: the five SLIDES_TEAM_* variables, all or |
| + // none (nil when all are empty), verified against the Home |
| + // credentials above before anything migrates (team_config.go). |
| + Team: teammode.ConfigFromEnv("SLIDES"), |
| Origin: origin, |
| Env: env, |
| InstanceKey: os.Getenv("SLIDES_INSTANCE_KEY"), |
diff --git a/docs/api.md b/docs/api.md| index 0322fa3..1e8925d 100644 |
| --- a/docs/api.md |
| +++ b/docs/api.md |
| @@ -76,6 +76,7 @@ Every answer with a body is JSON. Every error is: |
| | Status | `error` | What happened | |
| |--------|--------------------------|---------------| |
| | 401 | `unauthorized` | No token, an unknown token, a revoked one, or one whose operator is no longer admitted on this instance. All four answer identically. | |
| +| 403 | `forbidden` | Team mode only: making a deck when the roster says the operator is not on the team. | |
| | 404 | `not_found` | No such deck, slide or path — including a deck the operator cannot see. A deck that is not yours does not exist. | |
| | 405 | `method_not_allowed` | Right path, wrong verb. | |
| | 409 | `conflict` | Somebody else wrote to the deck while this batch was landing, twice. Re-read the deck and decide what your batch now means. | |
| @@ -84,6 +85,14 @@ Every answer with a body is JSON. Every error is: |
| | 422 | `invalid` | The request was read and refused. `message` says why; `op` is the index of the operation at fault, when the failure was about one. A body carrying anything after its JSON value is refused here too, rather than half-read. | |
| | 429 | `busy` | You already have four exports running. Wait for one to finish; nothing was started. | |
| | 500 | `internal` | Our fault. The server log has a matching line. | |
| +| 503 | `unavailable` | Team mode only: the operator's team standing cannot be read right now (Home's roster is out of reach). Retry after `Retry-After` seconds. A deck list is never answered short in its place: it is all of it, or this. | |
| + |
| +On a **team instance** (one whose people come from Home's team roster), |
| +an agent reaches exactly what its operator's roster standing reaches, asked |
| +on every request: a team member's own decks, the team's decks and their |
| +grants; somebody off the team only their grants. Taking the operator off |
| +the team takes the agent's reach with it within a minute, without revoking |
| +the token. |
| --- |
diff --git a/docs/superpowers/specs/2026-09-07-slides-design.md b/docs/superpowers/specs/2026-09-07-slides-design.md| index 29267e1..06393ed 100644 |
| --- a/docs/superpowers/specs/2026-09-07-slides-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-slides-design.md |
| @@ -776,6 +776,74 @@ rest via `carlos env`, mirroring Docs' set. |
| --- |
| +### 6.4 Team mode (roster) |
| + |
| +Home `implementation/team-members.md` Part B, on Home's shared |
| +`home/teammode` package (`implementation/teammode-package.md` §7.1), |
| +ported after Sheets in Paul's order. A team instance (Alta's |
| +`lagged.slides.oficina.works` and its like) sets the five |
| +`SLIDES_TEAM_*` variables beside `SLIDES_HOME_*`; Paul's |
| +`slides.oficina.works` sets none and is the lone shape above, unchanged. |
| + |
| +- **Standing is Home's roster, on every request**, never anything stored: |
| + Member (the roster's role, owner or member), NotMember (a guest), or |
| + Unknown (the roster could not be read within its 60 s lease). It |
| + replaces §6.1's allowlist recheck; `SLIDES_ALLOWED_ADDRESSES` is |
| + optional and only admits local sign-in. |
| +- **The rungs in team mode.** Member: the person's own decks, every deck |
| + on the team rung, and grants. NotMember and Unknown: grants only. |
| + Ownership (`owner_id`) holds only while Member, as Docs' `owner_id` |
| + rule does. |
| +- **Removal** takes effect within the lease, for existing sessions, |
| + agents, the deck stream and presentations alike. While standing cannot |
| + be read, the deck stream and a projector's stream are held open |
| + delivering nothing and re-asked every 5 s, then caught up, rather than |
| + ended: a projector's EventSource does not survive a 503. Sessions and agent |
| + tokens are kept and reach grants only (Docs' and Sheets' rule, not |
| + §6.1's revocation: the roster can re-add somebody at any moment, and a |
| + removed person's grants are still theirs). A presentation stands on |
| + its presenter's reach: a presenter the roster removed has their talks |
| + ended, as §6.1 ends them; one whose standing cannot be read leaves the |
| + talk waiting behind a retryable 503. Share links are unchanged (§5). |
| +- **Unknown on the deck list** (Paul, 2026-10-28): the grants, with a |
| + notice saying the list is partial, an empty one included; never for |
| + NotMember. The dashboard feed and the API's JSON list are unavailable |
| + rather than short. A deck page that needs standing is a retryable 503, |
| + never a 404; creating a deck is members only (403 guest, 503 |
| + Unknown). |
| +- **Orphaned decks — RULED 2026-10-30 by Paul** (oficina/slides #33, |
| + after his Sheets ruling of 2026-10-28 on oficina/sheets #52): "share |
| + only, no delete for now (may change his mind later)", and "team-visible |
| + decks only". An orphan is a deck **on the team rung** whose owner the |
| + roster definitely says is gone (NotMember, or no owner row at all; an |
| + owner whose standing cannot be read is not gone). On an orphan a |
| + roster owner may **share** it (the share page, minting and revoking |
| + links) and **change its title and theme**. A roster owner may **not |
| + delete** it (delete stays `owner_id`, while Member), and may **not |
| + change its rung**: making it private hides it from everybody, the |
| + roster owner included, which Paul treats as a soft-delete. A departed |
| + member's private deck is no orphan, even to a roster owner holding a |
| + grant to read it. Nothing is written: the owner's return ends it. Each |
| + power is its own predicate in `team_owner.go` (`mayShareDeck`, |
| + `mayRetitleDeck`, `mayChangeRung`, `mayDeleteDeck`), so widening one |
| + later is one line. |
| +- **The allowlist in team mode** (Fable's ruling on deviation 4, #33): |
| + `SLIDES_ALLOWED_ADDRESSES` only decides who may use the local door. Two |
| + consequences, accepted: (1) an address taken off the list keeps its |
| + session, as a guest reaching grants only (or as the roster says, if |
| + linked), until it expires — where §6.1 signs it out of every device; |
| + (2) Alta must not write the owner's address into it, or that address |
| + is the instance's one local door. |
| +- **Home-only members**: a roster Member with no account here signs in |
| + with Home alone as an addressless `users` row, shown as "Oficina |
| + account …xxxx". Nothing can be granted to them by address, since they |
| + have none; grants have no screen yet (§5) anyway. |
| +- **Writes** re-check standing inside their own transaction, before and |
| + after, so a lease that lapses mid-write fails the commit. |
| +- **Uploads**: team instances have no object store (Paul). When one is |
| + bound, a presigned GET lives no longer than the standing it was minted |
| + on. |
| + |
| ## 7. The drive surface |
| ### 7.1 Principals |
diff --git a/go.mod b/go.mod| index 2cdc88e..bcb5fb3 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -6,9 +6,11 @@ toolchain go1.26.5 |
| 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-20261028171508-67c12e39a9d2 |
| + amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
| github.com/chromedp/chromedp v0.14.2 |
diff --git a/go.sum b/go.sum| index b21af90..9ccbfea 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,11 +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-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/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608= |
| amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM= |
diff --git a/internal/slides/agents.go b/internal/slides/agents.go| index 337b48b..c3d3ff3 100644 |
| --- a/internal/slides/agents.go |
| +++ b/internal/slides/agents.go |
| @@ -224,7 +224,15 @@ func (a *app) bearerActor(next http.Handler) http.Handler { |
| // one path out of this instance that survives a browser being |
| // signed out. Fail closed, and the same 401 a revoked token |
| // gets: an agent learns nothing about why. |
| - if !a.allowed.allows(operator.Email) { |
| + // |
| + // In team mode the roster replaces that recheck, as it does for |
| + // the operator's own sessions (team_access.go): the operator |
| + // carries the roster's standing, asked on this request, and the |
| + // agent reaches exactly what that standing reaches — the team |
| + // rung while Member, grants alone otherwise. |
| + if a.team != nil { |
| + operator = a.withStanding(r.Context(), operator) |
| + } else if !a.allowed.allows(operator.Email) { |
| a.logger.Warn("slides: an agent's operator is no longer admitted; refusing the token", |
| "agent", agent.ID, "operator", operator.ID) |
| apiFail(w, http.StatusUnauthorized, errUnauthorized) |
| @@ -302,12 +310,9 @@ func (a *app) actorLabels(ctx context.Context, actors []string) map[string]strin |
| if err := a.db.G.WithContext(ctx).Where("id IN ?", personIDs).Find(&people).Error; err != nil { |
| a.logger.Error("slides: resolve person actors", "err", err) |
| } |
| + homeOnly := a.homeOnlySubjects(ctx) |
| for _, u := range people { |
| - name := u.Name |
| - if name == "" { |
| - name = u.Email |
| - } |
| - out[actorFor(u)] = name |
| + out[actorFor(u)] = u.label(homeOnly[u.ID]) |
| } |
| } |
| if len(agentIDs) > 0 { |
| @@ -326,8 +331,12 @@ func (a *app) actorLabels(ctx context.Context, actors []string) map[string]strin |
| if err := a.db.G.WithContext(ctx).Where("id IN ?", ids).Find(&operators).Error; err != nil { |
| a.logger.Error("slides: resolve agent operators", "err", err) |
| } |
| + homeOnly := a.homeOnlySubjects(ctx) |
| for _, u := range operators { |
| emails[u.ID] = u.Email |
| + if u.Email == "" && homeOnly[u.ID] != "" { |
| + emails[u.ID] = homeOnlyLabel(homeOnly[u.ID]) |
| + } |
| } |
| for _, ag := range agents { |
| out[agentActor(ag.ID)] = agentMark + agentPrincipal(ag.Name, emails[ag.OperatorID]) |
| @@ -433,11 +442,11 @@ func (a *app) renderAgentsPage(w http.ResponseWriter, r *http.Request, u User, n |
| var minted Agent |
| if err := a.db.G.WithContext(r.Context()). |
| Where("token_hash = ?", hashAgentToken(newToken)).Take(&minted).Error; err == nil { |
| - page.NewPrincipal = agentPrincipal(minted.Name, u.Email) |
| + page.NewPrincipal = agentPrincipal(minted.Name, u.address()) |
| } |
| } |
| for _, ag := range rows { |
| - principal := agentPrincipal(ag.Name, u.Email) |
| + principal := agentPrincipal(ag.Name, u.address()) |
| row := agentRow{ |
| Principal: principal, |
| Created: rastrillo.Tf(r, "slides.agents.row.created", "when", whenWords(r, ag.CreatedAt)), |
| @@ -522,7 +531,7 @@ func (a *app) createAgent(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| a.logger.Info("slides: agent minted", |
| - "agent", agent.ID, "principal", agentPrincipal(agent.Name, u.Email)) |
| + "agent", agent.ID, "principal", agentPrincipal(agent.Name, u.address())) |
| // The one response that carries a credential, so no cache — shared |
| // or the browser's own back/forward store — may keep it. |
| w.Header().Set("Cache-Control", "no-store") |
diff --git a/internal/slides/api.go b/internal/slides/api.go| index 371f63d..b84a6d4 100644 |
| --- a/internal/slides/api.go |
| +++ b/internal/slides/api.go |
| @@ -238,6 +238,10 @@ func (a *app) apiDeckFor(w http.ResponseWriter, r *http.Request, p principal) (D |
| switch { |
| case err == nil: |
| return d, true |
| + case errors.Is(err, gorm.ErrRecordNotFound) && a.teamUnknown(p.operator): |
| + // Team mode, the operator's standing unknown: deckFor's |
| + // retryable answer, in JSON. |
| + teamUnavailableJSON(w) |
| case errors.Is(err, gorm.ErrRecordNotFound): |
| apiFail(w, http.StatusNotFound, errNotFound) |
| default: |
| @@ -281,6 +285,14 @@ func (a *app) apiListDecks(w http.ResponseWriter, r *http.Request) { |
| apiFail(w, http.StatusInternalServerError, errInternal) |
| return |
| } |
| + // Team mode, standing unknown: a JSON list cannot carry the deck |
| + // list's partial notice, and an agent would take a short list for |
| + // the whole one, so it is unavailable rather than short (Fable on |
| + // Docs #100). Asked after listing, of the same Access. |
| + if a.teamPartial(p.operator) { |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| out := make([]apiDeckSummary, 0, len(rows)) |
| for _, d := range rows { |
| slides, _ := a.slideCount(r.Context(), d) |
| @@ -311,6 +323,9 @@ func (a *app) apiCreateDeck(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if !a.teamMemberOnlyJSON(w, p.operator) { |
| + return |
| + } |
| var body struct { |
| Title string `json:"title"` |
| Theme string `json:"theme"` |
| @@ -332,7 +347,11 @@ func (a *app) apiCreateDeck(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - d, err := a.createDeckRow(r.Context(), p.operator, title, theme) |
| + g := a.memberGuard(r.Context(), p.operator) |
| + d, err := a.createDeckRow(r.Context(), p.operator, title, theme, g) |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("slides: create a deck for the API", "err", err) |
| apiFail(w, http.StatusInternalServerError, errInternal) |
| @@ -344,7 +363,10 @@ func (a *app) apiCreateDeck(w http.ResponseWriter, r *http.Request) { |
| apiFail(w, http.StatusInternalServerError, errInternal) |
| return |
| } |
| - if err := a.editDeck(r.Context(), &d, p.actor(), ops, nil); err != nil { |
| + if err := a.editDeck(r.Context(), &d, p.actor(), ops, nil, g); err != nil { |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| a.logger.Error("slides: write the opening ops for the API", "err", err) |
| apiFail(w, http.StatusInternalServerError, errInternal) |
| return |
| @@ -478,10 +500,11 @@ func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - ids, err := a.applyAgentOps(r.Context(), &d, p.actor(), body.Ops) |
| + ids, err := a.applyAgentOps(r.Context(), &d, p.actor(), body.Ops, a.deckGuard(r.Context(), p.operator, d)) |
| switch { |
| case err == nil: |
| a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| + case guardRefusedJSON(w, err): |
| case errors.Is(err, errDeckBusy): |
| // Two attempts have already been made; a third would be |
| // spinning. 409 is the honest answer, and the caller re-reads |
| @@ -515,7 +538,7 @@ func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| // the row and reopens — the ids minted on the first attempt are |
| // already written into the ops, so it mints nothing new and the caller |
| // is told the same ids either way. |
| -func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []map[string]json.RawMessage) (map[string]string, error) { |
| +func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []map[string]json.RawMessage, g writeGuard) (map[string]string, error) { |
| var ids map[string]string |
| var lastErr error |
| for attempt := 0; attempt < 2; attempt++ { |
| @@ -536,7 +559,7 @@ func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []ma |
| h.Close(ctx) |
| return nil, fmt.Errorf("slides: encode ops: %w", err) |
| } |
| - _, err = a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops)) |
| + _, err = a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| h.Close(ctx) |
| if err == nil { |
| return ids, nil |
| @@ -815,21 +838,30 @@ func (a *app) apiPresent(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| actor := p.actor() |
| + g := a.deckGuard(r.Context(), p.operator, d) |
| var live Presentation |
| err = a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor). |
| Order("started_at DESC").Take(&live).Error |
| switch { |
| case err == nil: |
| - if err := a.db.G.WithContext(r.Context()).Model(&Presentation{}). |
| - Where("id = ? AND ended_at IS NULL", live.ID). |
| - Update("remote_token_hash", hashRemoteToken(token)).Error; err != nil { |
| + if err := a.guarded(r.Context(), g, func(db *gorm.DB) error { |
| + return db.Model(&Presentation{}). |
| + Where("id = ? AND ended_at IS NULL", live.ID). |
| + Update("remote_token_hash", hashRemoteToken(token)).Error |
| + }); err != nil { |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| a.logger.Error("slides: re-pair a presentation for the API", "err", err) |
| apiFail(w, http.StatusInternalServerError, errInternal) |
| return |
| } |
| case errors.Is(err, gorm.ErrRecordNotFound): |
| - live, err = a.createPresentation(r, d, actor, token) |
| + live, err = a.createPresentation(r, d, actor, token, g) |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("slides: start a presentation for the API", "err", err) |
| apiFail(w, http.StatusInternalServerError, errInternal) |
diff --git a/internal/slides/app.go b/internal/slides/app.go| index 5a19c96..8f28cad 100644 |
| --- a/internal/slides/app.go |
| +++ b/internal/slides/app.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/estilo.git/theme" |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/oficina/slides/internal/slides/core" |
| "amadan.net/oficina/slides/internal/slides/live" |
| "amadan.net/oficina/slides/internal/slides/present" |
| @@ -71,6 +72,10 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) { |
| if a.dashboard != nil { |
| r.Handle("/api/oficina/dashboard", a.dashboard) |
| } |
| + // Team mode's readiness probe (team_answers.go), unauthenticated: |
| + // {"team_mode":false} with team mode off, as Docs' and Sheets' are |
| + // (Paul's ruling on oficina/sheets #52, deviation 5). |
| + r.Get(teammode.ProbePath, a.teamProbe) |
| r.Get("/help/open-source", a.credits) |
| // The account menu's Appearance (estilo chrome). Inside the app-wide |
| // CSRF check above and outside the session group below: a session |
| @@ -304,6 +309,19 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| if homeConfig != nil { |
| boot = migrate.Merge(BootSchema, homeSchema) |
| } |
| + // Team mode (team_config.go): the configuration is verified against |
| + // the Home credentials just decoded, and the marker read, before |
| + // anything migrates. Off, this is one sqlite_master read and boot |
| + // is unchanged; an activated database without the same binding |
| + // refuses here. |
| + team, err := teamSettings(cfg.Team, homeConfig, cfg.Origin) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + boot, err = teamBootSchema(context.Background(), d.Writer(), team, boot) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| migrated, err := migrate.Apply(context.Background(), d, boot) |
| if err != nil { |
| return nil, nil, err |
| @@ -361,6 +379,7 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| jobs: jobs.New(logger), |
| exports: newExportStore(), |
| pdf: &pdfRuntime{}, |
| + teamOn: team, |
| } |
| // The optional session read behind every page outside the signed-in |
| @@ -379,6 +398,11 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| mailer.close() |
| return nil, nil, err |
| } |
| + if err := a.configureTeam(team, homeConfig); err != nil { |
| + rt.Close(context.Background()) |
| + mailer.close() |
| + return nil, nil, err |
| + } |
| // The export's status page, its polled fragment and its SSE stream |
| // (exports.go). rastrillo/jobs owns the lifecycle and the |
diff --git a/internal/slides/assets.go b/internal/slides/assets.go| index 707a62d..b6f840f 100644 |
| --- a/internal/slides/assets.go |
| +++ b/internal/slides/assets.go |
| @@ -318,7 +318,10 @@ func (a *app) signUpload(w http.ResponseWriter, r *http.Request) { |
| // records which one. |
| out["url"] = "/d/" + d.Sqid + "/uploads/" + key |
| } |
| - if err := a.db.G.WithContext(r.Context()).Create(&up).Error; err != nil { |
| + if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { return db.Create(&up).Error }); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "record a staged upload", err) |
| return |
| } |
| @@ -400,9 +403,14 @@ func (a *app) putUpload(w http.ResponseWriter, r *http.Request) { |
| // and has no way to write a key of somebody else's choosing, so the |
| // receipt records the key it chose rather than pretending the |
| // staging key holds anything. |
| - if err := a.db.G.WithContext(r.Context()).Model(&AssetUpload{}). |
| - Where("id = ?", up.ID). |
| - Updates(map[string]any{"object_key": stored.Hash, "size": stored.Size}).Error; err != nil { |
| + if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| + return db.Model(&AssetUpload{}). |
| + Where("id = ?", up.ID). |
| + Updates(map[string]any{"object_key": stored.Hash, "size": stored.Size}).Error |
| + }); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "record where an upload landed", err) |
| return |
| } |
| @@ -556,9 +564,13 @@ func (a *app) registerAsset(w http.ResponseWriter, r *http.Request) { |
| // answer, and a failure to write it fails the request: a record |
| // the browser registers without this row is a picture that will |
| // never be served. |
| - if err := a.db.G.WithContext(r.Context()). |
| - Clauses(clause.OnConflict{DoNothing: true}). |
| - Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error; err != nil { |
| + if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| + return db.Clauses(clause.OnConflict{DoNothing: true}). |
| + Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| + }); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "record a verified asset", err) |
| return |
| } |
diff --git a/internal/slides/auth.go b/internal/slides/auth.go| index 8d5a0a1..3f8e117 100644 |
| --- a/internal/slides/auth.go |
| +++ b/internal/slides/auth.go |
| @@ -114,8 +114,10 @@ func normalizeAddress(address string) string { |
| // A nil addrs map means "admit every address" — resolveAllowlist's |
| // development-only default, spelled out here rather than left as an |
| // accidental nil. A non-nil one means "admit nothing but exactly this |
| -// set"; resolveAllowlist never returns a non-nil-but-empty map, since |
| -// an empty parse outside development is a refusal rather than a value. |
| +// set"; resolveAllowlist returns a non-nil-but-empty map only in team |
| +// mode (admit nobody locally: the roster decides, and Home signs people |
| +// in), since an empty parse outside development is otherwise a refusal |
| +// rather than a value. |
| type allowlist struct { |
| addrs map[string]struct{} |
| } |
| @@ -142,6 +144,13 @@ func resolveAllowlist(cfg Config) (allowlist, error) { |
| if len(addrs) > 0 { |
| return allowlist{addrs: addrs}, nil |
| } |
| + if cfg.Team != nil { |
| + // Team mode: the roster decides standing, and the list is only |
| + // local sign-in's admission. Empty admits nobody locally, in |
| + // every Env: a team instance never takes the development |
| + // default that admits everyone. |
| + return allowlist{addrs: addrs}, nil |
| + } |
| if cfg.development() { |
| return allowlist{}, nil // addrs stays nil: admit everyone |
| } |
| @@ -503,6 +512,12 @@ func (a *app) currentUser(w http.ResponseWriter, r *http.Request) (User, session |
| if !ok || s.Subject == "" { |
| return User{}, sessionNone |
| } |
| + if a.team != nil { |
| + // Team mode: the roster replaces the allowlist recheck below. |
| + // The user comes back carrying their standing, asked of the |
| + // roster on this request (team_access.go). |
| + return a.teamCurrentUser(w, r, s) |
| + } |
| if s.Method == connect.HomeMethod { |
| u, err := a.homeUser(r, s) |
| if err != nil { |
diff --git a/internal/slides/chrome.go b/internal/slides/chrome.go| index 2c6c1eb..32860e1 100644 |
| --- a/internal/slides/chrome.go |
| +++ b/internal/slides/chrome.go |
| @@ -97,6 +97,10 @@ type viewerState struct { |
| user User |
| method string |
| ok bool |
| + // homeSubject is the session's Home subject when it is a Home |
| + // session: what names a Home-only user in the account menu, who has |
| + // no address (team mode only; homeOnlyLabel). |
| + homeSubject string |
| } |
| // optionalViewer resolves whoever is signed in on r without requiring |
| @@ -118,9 +122,11 @@ func (a *app) optionalViewer(r *http.Request) viewerState { |
| if err != nil { |
| return viewerState{} |
| } |
| - return viewerState{user: u, method: s.Method, ok: true} |
| + return viewerState{user: u, method: s.Method, ok: true, homeSubject: s.Subject} |
| } |
| - if !a.allowed.allows(s.Subject) { |
| + // In team mode the roster, not the list, decides standing, and a |
| + // local session admitted at sign-in stays signed in (team_access.go). |
| + if a.team == nil && !a.allowed.allows(s.Subject) { |
| return viewerState{} |
| } |
| var u User |
| @@ -133,11 +139,14 @@ func (a *app) optionalViewer(r *http.Request) viewerState { |
| // shellFor is the shell of a page behind the session gate: u is the |
| // person currentUser resolved. |
| func (a *app) shellFor(r *http.Request, u User, f frame) shell { |
| - method := "" |
| + method, subject := "", "" |
| if s, ok := sessions.Current(r); ok { |
| method = s.Method |
| + if method == connect.HomeMethod { |
| + subject = s.Subject |
| + } |
| } |
| - return shell{Frame: a.frameFor(r, viewerState{user: u, method: method, ok: true}, f)} |
| + return shell{Frame: a.frameFor(r, viewerState{user: u, method: method, ok: true, homeSubject: subject}, f)} |
| } |
| // publicShell is the shell of a page reachable signed out: the viewer is |
| @@ -204,10 +213,16 @@ func (a *app) account(r *http.Request, v viewerState, ret string) *chrome.Accoun |
| ret = returnTarget(r) |
| } |
| u := v.user |
| + // who is the address; only a team-mode Home-only user has none, and |
| + // is named by their person ref instead (homeOnlyLabel). |
| + who := u.Email |
| + if who == "" && v.homeSubject != "" { |
| + who = homeOnlyLabel(v.homeSubject) |
| + } |
| acc := &chrome.Account{ |
| TriggerLabel: rastrillo.T(r, "slides.chrome.account"), |
| - Initials: chrome.Initials(u.Name, u.Email), |
| - Address: u.Email, |
| + Initials: chrome.Initials(u.Name, who), |
| + Address: who, |
| Labels: chrome.AccountLabels{ |
| SignedInAs: rastrillo.T(r, "slides.chrome.signed_in_as"), |
| Appearance: rastrillo.T(r, "slides.chrome.appearance"), |
| @@ -227,8 +242,8 @@ func (a *app) account(r *http.Request, v viewerState, ret string) *chrome.Accoun |
| if u.Name != "" { |
| acc.Name = u.Name |
| } |
| - if u.Email != "" { |
| - acc.TriggerLabel = rastrillo.Tf(r, "slides.chrome.account.who", "address", u.Email) |
| + if who != "" { |
| + acc.TriggerLabel = rastrillo.Tf(r, "slides.chrome.account.who", "address", who) |
| } |
| // Agents (agents.go): the tokens that let a program drive this |
| // person's decks. A page, so a link and no ellipsis. |
diff --git a/internal/slides/config.go b/internal/slides/config.go| index 89bcff4..cdaed02 100644 |
| --- a/internal/slides/config.go |
| +++ b/internal/slides/config.go |
| @@ -15,10 +15,13 @@ package slides |
| import ( |
| "fmt" |
| "log/slog" |
| + "net/http" |
| "net/url" |
| "strings" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/blobs" |
| "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| @@ -42,6 +45,18 @@ const DefaultOrigin = "http://localhost:8091" |
| // it from the environment; the test harness fills it directly. |
| type Config struct { |
| Home *connect.Credentials |
| + |
| + // Team is roster team mode's configuration (teammode.ConfigFromEnv |
| + // with prefix SLIDES: the five SLIDES_TEAM_* variables, all or none), |
| + // nil with team mode off. It exists only beside Home, and in team |
| + // mode AllowedAddresses is optional: if set, it only admits local |
| + // sign-in, and gives nobody team standing (team_config.go). |
| + Team *teammode.Config |
| + // teamTransport and teamClock are for tests: a directory that |
| + // answers in memory and a clock a test can step (teammodetest). |
| + // Production leaves both nil. |
| + teamTransport http.RoundTripper |
| + teamClock roster.Clock |
| // Origin is this instance's external origin, scheme included — |
| // "https://slides.oficina.works". It is three things at once: |
| // csrf.Protect's yardstick for the legacy Origin/Referer fallback |
diff --git a/internal/slides/dashboard.go b/internal/slides/dashboard.go| index 05eda2e..5131a29 100644 |
| --- a/internal/slides/dashboard.go |
| +++ b/internal/slides/dashboard.go |
| @@ -29,15 +29,28 @@ func (a *app) configureDashboard(c *connect.DecodedCredentials) error { |
| a.dashboard = h |
| return nil |
| } |
| -func (a *app) dashboardDocuments(ctx context.Context, id int64, _ string, _ time.Time) (dashboard.Response, error) { |
| +func (a *app) dashboardDocuments(ctx context.Context, id int64, subject string, _ time.Time) (dashboard.Response, error) { |
| var viewer User |
| if e := a.db.G.WithContext(ctx).First(&viewer, id).Error; e != nil { |
| return dashboard.Response{}, e |
| } |
| + if a.team != nil { |
| + // The roster's standing for the verified subject that asked |
| + // (Resolve found a link or a Home-only user for it; identity |
| + // only), never anything stored (team_access.go). |
| + viewer.team = &teamAccess{Access: a.team.Access(ctx, subject)} |
| + } |
| var rows []Deck |
| if e := a.visibleDecks(ctx, viewer).Order("decks.updated_at DESC, decks.id DESC").Limit(dashboard.MaxItems + 1).Find(&rows).Error; e != nil { |
| return dashboard.Response{}, e |
| } |
| + // Unknown standing is unavailable, not a short list: the feed is read |
| + // on another origin, by a reader who never sees the deck list's |
| + // partial notice (teammode-package.md §4, condition 3). Asked after |
| + // listing, as the deck list does, because a lease can lapse during it. |
| + if a.teamPartial(viewer) { |
| + return dashboard.Response{}, dashboard.ErrUnavailable |
| + } |
| out := dashboard.Response{Truncated: len(rows) > dashboard.MaxItems} |
| if out.Truncated { |
| rows = rows[:dashboard.MaxItems] |
diff --git a/internal/slides/decks.go b/internal/slides/decks.go| index ce4e3e1..9b1d381 100644 |
| --- a/internal/slides/decks.go |
| +++ b/internal/slides/decks.go |
| @@ -170,6 +170,12 @@ func (a *app) visibleDecks(ctx context.Context, viewer User) *gorm.DB { |
| // backfill had ever left ownerless. |
| return g.Where("1 = 0") |
| } |
| + if !a.member(viewer) { |
| + // Team mode, and the roster does not say Member (a guest, or a |
| + // standing that cannot be read now): the team rung is withheld, |
| + // own decks included, and only grants reach (team_access.go). |
| + return g.Where("EXISTS (SELECT 1 FROM deck_grants WHERE deck_grants.deck_id = decks.id AND deck_grants.user_id = ?)", viewer.ID) |
| + } |
| return g.Where( |
| "(decks.owner_id = ? OR decks.rung = ? OR EXISTS ("+ |
| "SELECT 1 FROM deck_grants WHERE deck_grants.deck_id = decks.id AND deck_grants.user_id = ?))", |
| @@ -319,46 +325,52 @@ var errDeckBusy = errors.New("slides: the deck moved while this update was being |
| // failure applying rowUpdates (a rejected rung, a constraint) now rolls |
| // back h.Ops' own DeckUpdate row too, rather than leaving the row |
| // diverged from the document's meta. |
| -func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any) (*deck.Deck, error) { |
| +// |
| +// g is the team-mode write guard (team_guard.go), run inside the |
| +// transaction around everything it writes; nil outside team mode, and |
| +// then the transaction is exactly what it always was. |
| +func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any, g writeGuard) (*deck.Deck, error) { |
| err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - update, err := h.Ops(ctx, ops) |
| - if err != nil { |
| - return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err) |
| - } |
| + return g.run(func() error { |
| + update, err := h.Ops(ctx, ops) |
| + if err != nil { |
| + return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err) |
| + } |
| - next := d.Seq + 1 |
| - if err := tx.Create(&DeckUpdate{ |
| - DeckID: d.ID, |
| - Seq: next, |
| - Actor: actor, |
| - Bytes: update, |
| - CreatedAt: time.Now().UTC(), |
| - }).Error; err != nil { |
| - if errors.Is(err, gorm.ErrDuplicatedKey) { |
| - // Somebody else's update is already sitting at this |
| - // seq: the lost race, reported as the lost race. |
| - return errDeckBusy |
| + next := d.Seq + 1 |
| + if err := tx.Create(&DeckUpdate{ |
| + DeckID: d.ID, |
| + Seq: next, |
| + Actor: actor, |
| + Bytes: update, |
| + CreatedAt: time.Now().UTC(), |
| + }).Error; err != nil { |
| + if errors.Is(err, gorm.ErrDuplicatedKey) { |
| + // Somebody else's update is already sitting at this |
| + // seq: the lost race, reported as the lost race. |
| + return errDeckBusy |
| + } |
| + return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| } |
| - return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| - } |
| - // Named columns off a map, never a bound struct (SKILL.md §4): |
| - // "seq" is always present so the WHERE ... AND seq = ? clause |
| - // above stays the sole optimistic lock, whether or not this |
| - // call is also renaming the deck. |
| - fields := map[string]any{"seq": next} |
| - for k, v := range rowUpdates { |
| - fields[k] = v |
| - } |
| - res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| - Updates(fields) |
| - if res.Error != nil { |
| - return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| - } |
| - if res.RowsAffected != 1 { |
| - return errDeckBusy |
| - } |
| - return nil |
| + // Named columns off a map, never a bound struct (SKILL.md §4): |
| + // "seq" is always present so the WHERE ... AND seq = ? clause |
| + // above stays the sole optimistic lock, whether or not this |
| + // call is also renaming the deck. |
| + fields := map[string]any{"seq": next} |
| + for k, v := range rowUpdates { |
| + fields[k] = v |
| + } |
| + res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| + Updates(fields) |
| + if res.Error != nil { |
| + return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| + } |
| + if res.RowsAffected != 1 { |
| + return errDeckBusy |
| + } |
| + return nil |
| + }) |
| }) |
| if err != nil { |
| return nil, err |
| @@ -395,14 +407,14 @@ func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor strin |
| // document — the batch applied nothing, so replaying it against the |
| // state that beat us is the correct thing to do, and a second conflict |
| // means real contention rather than a race worth spinning on. |
| -func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, rowUpdates map[string]any) error { |
| +func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, rowUpdates map[string]any, g writeGuard) error { |
| var lastErr error |
| for attempt := 0; attempt < 2; attempt++ { |
| h, _, err := a.openDeck(ctx, *d) |
| if err != nil { |
| return err |
| } |
| - _, err = a.applyOps(ctx, h, d, actor, ops, rowUpdates) |
| + _, err = a.applyOps(ctx, h, d, actor, ops, rowUpdates, g) |
| h.Close(ctx) |
| if err == nil { |
| return nil |
| @@ -422,7 +434,10 @@ func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, r |
| // createDeckRow inserts the row, retrying on a sqid collision. The |
| // document itself is empty at this point — the caller's first op batch |
| // is what puts anything in it. |
| -func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string) (Deck, error) { |
| +// |
| +// g is the team-mode guard (memberGuard: making a deck rests on standing |
| +// alone); nil outside team mode. |
| +func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string, g writeGuard) (Deck, error) { |
| now := time.Now().UTC() |
| var lastErr error |
| for attempt := 0; attempt < maxSqidAttempts; attempt++ { |
| @@ -439,7 +454,7 @@ func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string |
| CreatedAt: now, |
| UpdatedAt: now, |
| } |
| - err = a.db.G.WithContext(ctx).Create(&d).Error |
| + err = a.guarded(ctx, g, func(db *gorm.DB) error { return db.Create(&d).Error }) |
| if err == nil { |
| return d, nil |
| } |
| @@ -497,6 +512,12 @@ func (a *app) deckFor(w http.ResponseWriter, r *http.Request, u User) (Deck, boo |
| switch { |
| case err == nil: |
| return d, true |
| + case errors.Is(err, gorm.ErrRecordNotFound) && a.teamUnknown(u): |
| + // Team mode, standing unknown: the team rung was withheld, so |
| + // "not here" cannot be told from "not readable right now". The |
| + // retryable answer, for a deck that exists and one that does not |
| + // alike. |
| + a.teamUnavailable(w, r) |
| case errors.Is(err, gorm.ErrRecordNotFound): |
| a.notFound(w, r) |
| default: |
| @@ -505,15 +526,22 @@ func (a *app) deckFor(w http.ResponseWriter, r *http.Request, u User) (Deck, boo |
| return Deck{}, false |
| } |
| -// ownedDeckFor is deckFor for a write: settings and delete are the |
| -// owner's alone, and a team member who can read the deck gets the same |
| -// 404 as a stranger rather than a 403 that would confirm it exists. |
| -func (a *app) ownedDeckFor(w http.ResponseWriter, r *http.Request, u User) (Deck, bool) { |
| +// ownedDeckFor is deckFor for an owner's screen: settings, sharing and |
| +// delete are the owner's, and a team member who can read the deck gets |
| +// the same 404 as a stranger rather than a 403 that would confirm it |
| +// exists. may is the one power the screen needs (team_owner.go): outside |
| +// team mode every one of them is the owner's alone; in team mode a |
| +// roster owner holds some of them on an orphan. |
| +func (a *app) ownedDeckFor(w http.ResponseWriter, r *http.Request, u User, may func(context.Context, User, Deck) bool) (Deck, bool) { |
| d, ok := a.deckFor(w, r, u) |
| if !ok { |
| return Deck{}, false |
| } |
| - if d.OwnerID != u.ID { |
| + if !may(r.Context(), u, d) { |
| + if a.teamUnknown(u) { |
| + a.teamUnavailable(w, r) |
| + return Deck{}, false |
| + } |
| a.notFound(w, r) |
| return Deck{}, false |
| } |
| @@ -626,6 +654,13 @@ type decksPage struct { |
| EmptyTitle string |
| EmptyBody string |
| Decks []deckRow |
| + // Partial is team mode's "we could not check your team access": |
| + // the list holds the decks granted to this person and nothing on |
| + // the team rung (team_answers.go's teamPartial). Always false |
| + // outside team mode, where the template emits nothing for it. |
| + Partial bool |
| + PartialTitle string |
| + PartialBody string |
| } |
| // decks serves GET /: every deck this person may open, most recently |
| @@ -671,6 +706,13 @@ func (a *app) decks(w http.ResponseWriter, r *http.Request) { |
| RungTone: rungTone(d.Rung), |
| }) |
| } |
| + // After listing, of the same Access the list was built with |
| + // (teamPartial): a lease that lapsed while listing marks it partial. |
| + if a.teamPartial(u) { |
| + page.Partial = true |
| + page.PartialTitle = rastrillo.T(r, "slides.decks.partial.title") |
| + page.PartialBody = rastrillo.T(r, "slides.decks.partial.body") |
| + } |
| render(w, "decks", page) |
| } |
| @@ -801,6 +843,9 @@ func (a *app) newDeck(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if !a.teamMemberOnly(w, r, u) { |
| + return |
| + } |
| render(w, "deck_new", a.newDeckPage(r, u, "", defaultTheme, nil)) |
| } |
| @@ -828,6 +873,9 @@ func (a *app) createDeck(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if !a.teamMemberOnly(w, r, u) { |
| + return |
| + } |
| p := form.Parse(r, form.Field{Name: "title", Required: true}) |
| title := p.String("title") |
| @@ -848,7 +896,11 @@ func (a *app) createDeck(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - d, err := a.createDeckRow(r.Context(), u, title, theme) |
| + g := a.memberGuard(r.Context(), u) |
| + d, err := a.createDeckRow(r.Context(), u, title, theme, g) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, "create deck", err) |
| return |
| @@ -858,7 +910,10 @@ func (a *app) createDeck(w http.ResponseWriter, r *http.Request) { |
| a.fail(w, r, "build the opening ops", err) |
| return |
| } |
| - if err := a.editDeck(r.Context(), &d, actorFor(u), ops, nil); err != nil { |
| + if err := a.editDeck(r.Context(), &d, actorFor(u), ops, nil, g); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "write the opening ops", err) |
| return |
| } |
| @@ -909,7 +964,7 @@ type deckSettingsPage struct { |
| func (a *app) settingsPage(r *http.Request, u User, d Deck, title, theme, rung string, errs map[string]string) deckSettingsPage { |
| base := "/d/" + d.Sqid |
| - return deckSettingsPage{ |
| + page := deckSettingsPage{ |
| shell: a.shellFor(r, u, onDeck(rastrillo.T(r, "slides.deck.settings"), d.Title)), |
| Title: rastrillo.T(r, "slides.deck.settings"), |
| Action: base + "/settings", |
| @@ -929,6 +984,16 @@ func (a *app) settingsPage(r *http.Request, u User, d Deck, title, theme, rung s |
| BackLabel: rastrillo.T(r, "slides.deck.back"), |
| Errors: errs, |
| } |
| + // A roster owner on an orphan (team_owner.go) is offered what they |
| + // may change and nothing more: no rung, no delete. Outside team mode |
| + // the owner may do both and the page is as it always was. |
| + if !a.mayChangeRung(r.Context(), u, d) { |
| + page.Rungs = nil |
| + } |
| + if !a.mayDeleteDeck(r.Context(), u, d) { |
| + page.DeleteHref = "" |
| + } |
| + return page |
| } |
| func (a *app) deckSettings(w http.ResponseWriter, r *http.Request) { |
| @@ -936,7 +1001,7 @@ func (a *app) deckSettings(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayRetitleDeck) |
| if !ok { |
| return |
| } |
| @@ -957,7 +1022,7 @@ func (a *app) saveDeckSettings(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayRetitleDeck) |
| if !ok { |
| return |
| } |
| @@ -966,6 +1031,18 @@ func (a *app) saveDeckSettings(w http.ResponseWriter, r *http.Request) { |
| title := p.String("title") |
| theme := r.PostFormValue("theme") |
| rung := r.PostFormValue("rung") |
| + if !a.mayChangeRung(r.Context(), u, d) { |
| + // Team mode, a roster owner on an orphan (team_owner.go): title |
| + // and theme only. The page offers no rung; one posted anyway |
| + // must be the deck's own, never a narrowing. |
| + if rung == "" { |
| + rung = d.Rung |
| + } |
| + if rung != d.Rung { |
| + a.errorPage(w, r, http.StatusForbidden, kindStatus, "") |
| + return |
| + } |
| + } |
| errs := map[string]string{} |
| if !p.OK() { |
| errs["Title"] = rastrillo.T(r, "slides.deck.title.required") |
| @@ -988,7 +1065,10 @@ func (a *app) saveDeckSettings(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| rowUpdates := map[string]any{"title": title, "theme": theme, "rung": rung} |
| - if err := a.editDeck(r.Context(), &d, actorFor(u), ops, rowUpdates); err != nil { |
| + if err := a.editDeck(r.Context(), &d, actorFor(u), ops, rowUpdates, a.memberGuard(r.Context(), u)); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "write the settings ops", err) |
| return |
| } |
| @@ -1017,7 +1097,7 @@ func (a *app) confirmDeleteDeck(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayDeleteDeck) |
| if !ok { |
| return |
| } |
| @@ -1053,52 +1133,19 @@ func (a *app) deleteDeck(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayDeleteDeck) |
| if !ok { |
| return |
| } |
| var live []Presentation |
| + g := a.memberGuard(r.Context(), u) |
| err := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error { |
| - live = nil |
| - if err := tx.Where("deck_id = ? AND ended_at IS NULL", d.ID). |
| - Find(&live).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&Presentation{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckUpdate{}).Error; err != nil { |
| - return err |
| - } |
| - // The snapshots and the verified-asset rows are derived from |
| - // the deck and read by nothing but it: a snapshot left behind |
| - // is a whole copy of the document nothing can reach, and an |
| - // asset row a verification for a deck that no longer exists. |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckSnapshot{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckAsset{}).Error; err != nil { |
| - return err |
| - } |
| - // And the upload receipts (models.go's AssetUpload): a receipt |
| - // is registrable only into the deck it was staged for, so one |
| - // whose deck is gone is a row nothing can ever spend. |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&AssetUpload{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckGrant{}).Error; err != nil { |
| - return err |
| - } |
| - // The share links go too. A link outliving its deck is a live |
| - // URL that can only ever answer 404, and leaving one behind |
| - // would mean the one row in this database that grants |
| - // unauthenticated read is also the one nothing cleans up. |
| - if err := tx.Where("deck_id = ?", d.ID).Delete(&ShareLink{}).Error; err != nil { |
| - return err |
| - } |
| - return tx.Where("id = ? AND owner_id = ?", d.ID, u.ID).Delete(&Deck{}).Error |
| + return g.run(func() error { return deleteDeckTx(tx, d, &live) }) |
| }) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, "delete deck", err) |
| return |
| @@ -1110,3 +1157,48 @@ func (a *app) deleteDeck(w http.ResponseWriter, r *http.Request) { |
| } |
| http.Redirect(w, r, "/", http.StatusSeeOther) |
| } |
| + |
| +// deleteDeckTx is deleteDeck's transaction: every row of d, and the live |
| +// presentations it ended in live, to be told after the commit. The deck |
| +// row goes by its own owner_id, which ownedDeckFor (mayDeleteDeck) |
| +// confirmed is the viewer's. |
| +func deleteDeckTx(tx *gorm.DB, d Deck, live *[]Presentation) error { |
| + *live = nil |
| + if err := tx.Where("deck_id = ? AND ended_at IS NULL", d.ID). |
| + Find(live).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&Presentation{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckUpdate{}).Error; err != nil { |
| + return err |
| + } |
| + // The snapshots and the verified-asset rows are derived from |
| + // the deck and read by nothing but it: a snapshot left behind |
| + // is a whole copy of the document nothing can reach, and an |
| + // asset row a verification for a deck that no longer exists. |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckSnapshot{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckAsset{}).Error; err != nil { |
| + return err |
| + } |
| + // And the upload receipts (models.go's AssetUpload): a receipt |
| + // is registrable only into the deck it was staged for, so one |
| + // whose deck is gone is a row nothing can ever spend. |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&AssetUpload{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckGrant{}).Error; err != nil { |
| + return err |
| + } |
| + // The share links go too. A link outliving its deck is a live |
| + // URL that can only ever answer 404, and leaving one behind |
| + // would mean the one row in this database that grants |
| + // unauthenticated read is also the one nothing cleans up. |
| + if err := tx.Where("deck_id = ?", d.ID).Delete(&ShareLink{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Where("id = ? AND owner_id = ?", d.ID, d.OwnerID).Delete(&Deck{}).Error |
| +} |
diff --git a/internal/slides/decks_test.go b/internal/slides/decks_test.go| index 8dfc63b..2a2e37f 100644 |
| --- a/internal/slides/decks_test.go |
| +++ b/internal/slides/decks_test.go |
| @@ -34,7 +34,7 @@ func TestSettingsRowAndDocumentChangeTogether(t *testing.T) { |
| t.Fatalf("ensureUser: %v", err) |
| } |
| - row, err := a.createDeckRow(ctx, owner, "Original title", defaultTheme) |
| + row, err := a.createDeckRow(ctx, owner, "Original title", defaultTheme, nil) |
| if err != nil { |
| t.Fatalf("createDeckRow: %v", err) |
| } |
| @@ -42,7 +42,7 @@ func TestSettingsRowAndDocumentChangeTogether(t *testing.T) { |
| if err != nil { |
| t.Fatalf("openingOps: %v", err) |
| } |
| - if err := a.editDeck(ctx, &row, actorFor(owner), ops, nil); err != nil { |
| + if err := a.editDeck(ctx, &row, actorFor(owner), ops, nil, nil); err != nil { |
| t.Fatalf("seed editDeck: %v", err) |
| } |
| seqBefore := row.Seq |
| @@ -54,7 +54,7 @@ func TestSettingsRowAndDocumentChangeTogether(t *testing.T) { |
| // No column named this, so the Updates call inside applyOps' own |
| // transaction fails — the row write, not h.Ops, is what breaks. |
| badRowUpdates := map[string]any{"no_such_column": "boom"} |
| - if err := a.editDeck(ctx, &row, actorFor(owner), renameOps, badRowUpdates); err == nil { |
| + if err := a.editDeck(ctx, &row, actorFor(owner), renameOps, badRowUpdates, nil); err == nil { |
| t.Fatal("editDeck with an invalid row update returned no error") |
| } |
| @@ -107,7 +107,7 @@ func TestConcurrentWritersConflictThenRetry(t *testing.T) { |
| if err != nil { |
| t.Fatalf("ensureUser: %v", err) |
| } |
| - row, err := a.createDeckRow(ctx, owner, "Two writers", defaultTheme) |
| + row, err := a.createDeckRow(ctx, owner, "Two writers", defaultTheme, nil) |
| if err != nil { |
| t.Fatalf("createDeckRow: %v", err) |
| } |
| @@ -115,7 +115,7 @@ func TestConcurrentWritersConflictThenRetry(t *testing.T) { |
| if err != nil { |
| t.Fatalf("openingOps: %v", err) |
| } |
| - if err := a.editDeck(ctx, &row, actorFor(owner), opening, nil); err != nil { |
| + if err := a.editDeck(ctx, &row, actorFor(owner), opening, nil, nil); err != nil { |
| t.Fatalf("seed editDeck: %v", err) |
| } |
| @@ -143,10 +143,10 @@ func TestConcurrentWritersConflictThenRetry(t *testing.T) { |
| t.Fatalf("opsJSON: %v", err) |
| } |
| - if _, err := a.applyOps(ctx, h1, &first, actorFor(owner), firstOps, nil); err != nil { |
| + if _, err := a.applyOps(ctx, h1, &first, actorFor(owner), firstOps, nil, nil); err != nil { |
| t.Fatalf("the first writer failed: %v", err) |
| } |
| - _, err = a.applyOps(ctx, h2, &second, actorFor(owner), secondOps, nil) |
| + _, err = a.applyOps(ctx, h2, &second, actorFor(owner), secondOps, nil, nil) |
| if !errors.Is(err, errDeckBusy) { |
| t.Fatalf("the second writer got %v, want errDeckBusy", err) |
| } |
| @@ -154,7 +154,7 @@ func TestConcurrentWritersConflictThenRetry(t *testing.T) { |
| // The losing request's own next move: editDeck reopens, replays the |
| // batch against the state that beat it, and lands. |
| stale := second |
| - if err := a.editDeck(ctx, &stale, actorFor(owner), secondOps, nil); err != nil { |
| + if err := a.editDeck(ctx, &stale, actorFor(owner), secondOps, nil, nil); err != nil { |
| t.Fatalf("editDeck did not recover from the conflict: %v", err) |
| } |
diff --git a/internal/slides/editor.go b/internal/slides/editor.go| index 1788d9f..aecac71 100644 |
| --- a/internal/slides/editor.go |
| +++ b/internal/slides/editor.go |
| @@ -190,10 +190,7 @@ func (a *app) deckEditor(w http.ResponseWriter, r *http.Request) { |
| defer h.Close(r.Context()) |
| base := "/d/" + d.Sqid |
| - person := u.Name |
| - if person == "" { |
| - person = u.Email |
| - } |
| + person := u.viewerLabel() |
| sh := a.shellFor(r, u, titled(view.Meta.Title)) |
| sh.Fonts = newFontGate(r, view) |
| page := editorPage{ |
diff --git a/internal/slides/exports.go b/internal/slides/exports.go| index 01b9cbe..b57454e 100644 |
| --- a/internal/slides/exports.go |
| +++ b/internal/slides/exports.go |
| @@ -733,13 +733,16 @@ func (a *app) exportPDF(w http.ResponseWriter, r *http.Request, id string) { |
| a.notFound(w, r) |
| return |
| } |
| - a.serveExport(w, r, held, func() { a.notFound(w, r) }) |
| + a.serveExport(w, r, held, a.presignTTLFor(u), func() { a.notFound(w, r) }) |
| } |
| // serveExport writes one finished export, whichever of the two places |
| // it is in. missing is how the surface asking says "no longer here" — |
| // the app's 404 page on a screen, the API's JSON on the other side. |
| -func (a *app) serveExport(w http.ResponseWriter, r *http.Request, held heldExport, missing func()) { |
| +// |
| +// ttl is how long a presigned URL may live: presignTTL, or in team mode |
| +// no longer than the standing it was minted on (presignTTLFor). |
| +func (a *app) serveExport(w http.ResponseWriter, r *http.Request, held heldExport, ttl time.Duration, missing func()) { |
| if held.hash != "" { |
| store := a.cfg.Blobs |
| if store == nil { |
| @@ -751,7 +754,7 @@ func (a *app) serveExport(w http.ResponseWriter, r *http.Request, held heldExpor |
| // them there. One that cannot (blobs.Dir, in development) is |
| // streamed back through here, so the same page works either way. |
| if p, canPresign := store.(presigner); canPresign { |
| - url, err := p.PresignGet(held.hash, presignTTL) |
| + url, err := p.PresignGet(held.hash, ttl) |
| if err != nil { |
| a.fail(w, r, "presign an export", err) |
| return |
| @@ -996,7 +999,15 @@ func (a *app) exportWarningsFor(r *http.Request, held heldExport) []exportWarnin |
| // apiExportOwner is that string. An agent owns nothing (agents.go): a |
| // token can be revoked and a job it started must not become |
| // unwatchable because it was. |
| -func apiExportOwner(p principal) string { return p.operator.Email } |
| +// |
| +// In team mode it is the operator's user (teamJobOwner), as every |
| +// team-mode session's is: a Home-only operator has no address. |
| +func (a *app) apiExportOwner(p principal) string { |
| + if a.team != nil { |
| + return teamJobOwner(p.operator.ID) |
| + } |
| + return p.operator.Email |
| +} |
| // apiStartExport serves POST /api/v1/decks/{sqid}/export. 202, because |
| // nothing is ready yet: what comes back is where to watch and where |
| @@ -1023,7 +1034,7 @@ func (a *app) apiStartExport(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - owner := apiExportOwner(p) |
| + owner := a.apiExportOwner(p) |
| words := exportWordsFor(r, d.Title) |
| id := make(chan string, 1) |
| job, err := a.jobs.Start(owner, words.name, "", a.exportJob(id, d, p.actor(), body.Notes, words)) |
| @@ -1062,7 +1073,7 @@ func (a *app) apiExportStatus(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| id, wantsPDF := strings.CutSuffix(chi.URLParam(r, "id"), ".pdf") |
| - owner := apiExportOwner(p) |
| + owner := a.apiExportOwner(p) |
| held, dropped, found := a.exports.get(id) |
| a.dropObjects(r.Context(), dropped) |
| if found && (held.deck != d.Sqid || held.owner != owner) { |
| @@ -1080,7 +1091,7 @@ func (a *app) apiExportStatus(w http.ResponseWriter, r *http.Request) { |
| apiFail(w, http.StatusNotFound, errNotFound) |
| return |
| } |
| - a.serveExport(w, r, held, func() { apiFail(w, http.StatusNotFound, errNotFound) }) |
| + a.serveExport(w, r, held, a.presignTTLFor(p.operator), func() { apiFail(w, http.StatusNotFound, errNotFound) }) |
| return |
| } |
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go| index 8d51eff..e2f432d 100644 |
| --- a/internal/slides/handlers.go |
| +++ b/internal/slides/handlers.go |
| @@ -8,6 +8,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/oficina/slides/internal/slides/core" |
| "amadan.net/oficina/slides/internal/slides/live" |
| "amadan.net/oficina/slides/internal/slides/present" |
| @@ -88,6 +89,12 @@ type app struct { |
| // closed with the app. See pdfRuntime for why it is lazy where the |
| // deck core is not. |
| pdf *pdfRuntime |
| + // teamOn is the verified team configuration (team_config.go), set |
| + // before Home is wired so connect gets its Home-only hooks; team is |
| + // the roster runtime built from it once the schema is applied. Both |
| + // nil with team mode off, and then nothing team_*.go holds runs. |
| + teamOn *teammode.Settings |
| + team *teamRuntime |
| // live is the in-process fan-out behind every deck being EDITED: |
| // one accepted update announced as a seq, plus who is currently in |
| // the deck (internal/slides/live). Separate from hub above because |
diff --git a/internal/slides/home.go b/internal/slides/home.go| index 1140c98..6ace455 100644 |
| --- a/internal/slides/home.go |
| +++ b/internal/slides/home.go |
| @@ -43,7 +43,7 @@ func (a *app) initHome(c *connect.DecodedCredentials) error { |
| n := neutralSession(s) |
| return &n, nil |
| } |
| - b, err := connect.New(connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: c.Issuer, ConsumerID: c.ConsumerID, Namespace: "oficina/slides", SessionCookie: sess.CookieName(), Keys: c.Keys, DEK: c.DEK, ReadSession: read, |
| + cfg := connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: c.Issuer, ConsumerID: c.ConsumerID, Namespace: homeNamespace, SessionCookie: sess.CookieName(), Keys: c.Keys, DEK: c.DEK, 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}) |
| }, |
| @@ -58,7 +58,11 @@ func (a *app) initHome(c *connect.DecodedCredentials) error { |
| } |
| return connect.Person{}, err |
| } |
| - if !a.allowed.allows(u.Email) { |
| + // Team mode: a link names who somebody is, not whether they |
| + // may enter. The roster decides that on every request |
| + // (team_access.go), so a linked person needs no place on |
| + // SLIDES_ALLOWED_ADDRESSES to resolve. |
| + if a.teamOn == nil && !a.allowed.allows(u.Email) { |
| return connect.Person{}, sql.ErrNoRows |
| } |
| return connect.Person{ID: u.ID, Label: u.Email}, nil |
| @@ -67,11 +71,17 @@ func (a *app) initHome(c *connect.DecodedCredentials) error { |
| if err := q.QueryRowContext(ctx, "SELECT email FROM users WHERE id = ?", id).Scan(&email); err != nil { |
| return "", err |
| } |
| - if !a.allowed.allows(email) { |
| + if a.teamOn == nil && !a.allowed.allows(email) { |
| return "", sql.ErrNoRows |
| } |
| return email, nil |
| - }, Render: a.renderHome}) |
| + }, Render: a.renderHome} |
| + if a.teamOn != nil { |
| + // Team mode only: with both hooks nil connect is exactly what it |
| + // was (team_home_only.go). |
| + cfg.HomeOnly, cfg.Unlinked = a.teamHomeOnly(a.db.Writer()), a.teamUnlinked(a.db.Writer()) |
| + } |
| + b, err := connect.New(cfg) |
| if err != nil { |
| return err |
| } |
| @@ -80,7 +90,7 @@ func (a *app) initHome(c *connect.DecodedCredentials) error { |
| if err := a.configureDashboard(c); err != nil { |
| return err |
| } |
| - a.homeRoutes, err = connect.NewRoutes(b, connect.RoutesConfig{Namespace: "oficina/slides", Origin: a.cfg.Origin, Issuer: c.Issuer, DEK: c.DEK, SessionCookie: sess.CookieName(), ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signin, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome, FormPolicy: connect.FormPolicy(c.Issuer)}) |
| + a.homeRoutes, err = connect.NewRoutes(b, connect.RoutesConfig{Namespace: homeNamespace, Origin: a.cfg.Origin, Issuer: c.Issuer, DEK: c.DEK, SessionCookie: sess.CookieName(), ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signin, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome, FormPolicy: connect.FormPolicy(c.Issuer)}) |
| return err |
| } |
| @@ -133,7 +143,7 @@ func (a *app) homeUser(r *http.Request, s sessions.Session) (User, error) { |
| } |
| return User{}, fmt.Errorf("%w: %v", linkstore.ErrStorage, err) |
| } |
| - if !a.allowed.allows(u.Email) { |
| + if a.team == nil && !a.allowed.allows(u.Email) { |
| return User{}, linkstore.ErrRefused |
| } |
| return u, nil |
| @@ -141,7 +151,7 @@ func (a *app) homeUser(r *http.Request, s sessions.Session) (User, error) { |
| func (a *app) revokeHome(w http.ResponseWriter, r *http.Request, subject string) { |
| var u User |
| - if a.home != nil && a.db.G.WithContext(r.Context()).Raw("SELECT u.* FROM users u JOIN home_identity_links l ON l.person_id=u.id WHERE l.issuer=? AND l.subject=?", a.cfg.Home.Issuer, subject).Scan(&u).Error == nil && u.ID != 0 && !a.allowed.allows(u.Email) { |
| + if a.team == nil && a.home != nil && a.db.G.WithContext(r.Context()).Raw("SELECT u.* FROM users u JOIN home_identity_links l ON l.person_id=u.id WHERE l.issuer=? AND l.subject=?", a.cfg.Home.Issuer, subject).Scan(&u).Error == nil && u.ID != 0 && !a.allowed.allows(u.Email) { |
| a.offboard(w, r, u.Email) |
| return |
| } |
| @@ -162,6 +172,17 @@ type exportSessionKey struct{} |
| func (a *app) exportPrincipal(r *http.Request) *http.Request { |
| s, ok := sessions.Current(r) |
| + if ok && a.team != nil { |
| + // Team mode: every session keys its jobs on the user, since a |
| + // Home-only user has no address (teamJobOwner). |
| + u, _, err := a.teamIdentify(r.Context(), s) |
| + if err != nil { |
| + return r |
| + } |
| + original := s |
| + s.Subject = teamJobOwner(u.ID) |
| + return sessions.WithSession(r.WithContext(context.WithValue(r.Context(), exportSessionKey{}, original)), s) |
| + } |
| if !ok || s.Method != connect.HomeMethod { |
| return r |
| } |
| @@ -196,6 +217,10 @@ func (a *app) homeLocalComplete(w http.ResponseWriter, r *http.Request) { |
| switch { |
| case err != nil: |
| a.logger.Error("slides: create user before resuming a Home link", "err", err) |
| + case created && a.team != nil: |
| + // Team mode: a local account made here has no link yet, |
| + // so it is a guest, and guests create nothing; no sample |
| + // deck (team_access.go's teamIdentify says the same). |
| case created: |
| if has, err := hasDeck(r.Context(), a.db.G, u); err != nil { |
| a.logger.Error("slides: check for an existing deck before seeding", "user", u.ID, "err", err) |
diff --git a/internal/slides/live.go b/internal/slides/live.go| index 185cd9e..59ef67a 100644 |
| --- a/internal/slides/live.go |
| +++ b/internal/slides/live.go |
| @@ -283,8 +283,11 @@ func (a *app) updatesPost(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - seq, err := a.appendUpdate(r.Context(), &d, actorFor(u), update) |
| + seq, err := a.appendUpdate(r.Context(), &d, actorFor(u), update, a.deckGuard(r.Context(), u, d)) |
| if err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if errors.Is(err, errUpdateRefused) { |
| a.logger.Info("slides: refuse a posted update", "deck", d.Sqid, "err", err) |
| http.Error(w, rastrillo.T(r, "slides.live.error.invalid"), http.StatusUnprocessableEntity) |
| @@ -333,7 +336,10 @@ func (a *app) updatesPost(w http.ResponseWriter, r *http.Request) { |
| // |
| // d is a pointer because its Seq is updated in place on success and |
| // re-read on a conflict, exactly as editDeck does. |
| -func (a *app) appendUpdate(ctx context.Context, d *Deck, actor string, update []byte) (int64, error) { |
| +// |
| +// g is the team-mode write guard, run inside commitUpdate's transaction; |
| +// nil outside team mode. |
| +func (a *app) appendUpdate(ctx context.Context, d *Deck, actor string, update []byte, g writeGuard) (int64, error) { |
| var lastErr error |
| for attempt := 0; attempt < 2; attempt++ { |
| h, _, err := a.openDeck(ctx, *d) |
| @@ -345,7 +351,7 @@ func (a *app) appendUpdate(ctx context.Context, d *Deck, actor string, update [] |
| h.Close(ctx) |
| return 0, err |
| } |
| - seq, err := a.commitUpdate(ctx, d, actor, update) |
| + seq, err := a.commitUpdate(ctx, d, actor, update, g) |
| if err == nil { |
| // After the commit, in this order and for the same reasons |
| // applyOps has: nobody is told about a seq a rolled-back |
| @@ -425,40 +431,10 @@ func (a *app) previewUpdate(ctx context.Context, h *core.Handle, d *Deck, update |
| // transaction with the update already applied and checked by |
| // previewUpdate, so the transaction holds SQLite's single writer for |
| // two statements and no guest calls. |
| -func (a *app) commitUpdate(ctx context.Context, d *Deck, actor string, update []byte) (int64, error) { |
| +func (a *app) commitUpdate(ctx context.Context, d *Deck, actor string, update []byte, g writeGuard) (int64, error) { |
| next := d.Seq + 1 |
| err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - if err := tx.Create(&DeckUpdate{ |
| - DeckID: d.ID, |
| - Seq: next, |
| - Actor: actor, |
| - Bytes: update, |
| - CreatedAt: time.Now().UTC(), |
| - }).Error; err != nil { |
| - if errors.Is(err, gorm.ErrDuplicatedKey) { |
| - // Somebody else's update is already at this seq: the |
| - // lost race, reported as the lost race. |
| - return errDeckBusy |
| - } |
| - return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| - } |
| - |
| - // Only the seq here. The row's title and theme follow the |
| - // document too, but that is mirrorMeta's job AFTER the commit: |
| - // it costs a read of the whole deck out of the wasm module, |
| - // and metaRowUpdates' own comment says why that must not |
| - // happen inside this transaction — it would hold SQLite's |
| - // single writer for the length of a guest call on the path of |
| - // every keystroke batch in the app. |
| - res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| - Updates(map[string]any{"seq": next}) |
| - if res.Error != nil { |
| - return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| - } |
| - if res.RowsAffected != 1 { |
| - return errDeckBusy |
| - } |
| - return nil |
| + return g.run(func() error { return commitUpdateTx(tx, d, actor, update, next) }) |
| }) |
| if err != nil { |
| return 0, err |
| @@ -467,6 +443,41 @@ func (a *app) commitUpdate(ctx context.Context, d *Deck, actor string, update [] |
| return next, nil |
| } |
| +// commitUpdateTx is commitUpdate's transaction body. |
| +func commitUpdateTx(tx *gorm.DB, d *Deck, actor string, update []byte, next int64) error { |
| + if err := tx.Create(&DeckUpdate{ |
| + DeckID: d.ID, |
| + Seq: next, |
| + Actor: actor, |
| + Bytes: update, |
| + CreatedAt: time.Now().UTC(), |
| + }).Error; err != nil { |
| + if errors.Is(err, gorm.ErrDuplicatedKey) { |
| + // Somebody else's update is already at this seq: the |
| + // lost race, reported as the lost race. |
| + return errDeckBusy |
| + } |
| + return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| + } |
| + |
| + // Only the seq here. The row's title and theme follow the |
| + // document too, but that is mirrorMeta's job AFTER the commit: |
| + // it costs a read of the whole deck out of the wasm module, |
| + // and metaRowUpdates' own comment says why that must not |
| + // happen inside this transaction — it would hold SQLite's |
| + // single writer for the length of a guest call on the path of |
| + // every keystroke batch in the app. |
| + res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| + Updates(map[string]any{"seq": next}) |
| + if res.Error != nil { |
| + return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| + } |
| + if res.RowsAffected != 1 { |
| + return errDeckBusy |
| + } |
| + return nil |
| +} |
| + |
| // mirrorMeta makes the deck row follow the document's meta after an |
| // update posted over the wire: the editor's Deck section writes |
| // meta.title and meta.theme this way, and the deck list, the settings |
| @@ -591,11 +602,54 @@ func (a *app) deckStream(w http.ResponseWriter, r *http.Request) { |
| w.WriteHeader(http.StatusOK) |
| fl.Flush() |
| - // write is every byte's one exit: deadline armed, bytes, flush. The |
| + // Team mode: the stream stands on the viewer's standing, so it is |
| + // re-decided before every delivery and again when a Member lease |
| + // runs out (teamStreamAccess), and ends on a definite "no". A silent |
| + // stream cannot outlive a removal. While standing cannot be read the |
| + // stream is HELD: open, delivering nothing but comment pings, re-asking |
| + // at streamHoldRetry (the roster's RetryAfter), and caught up (the current seq and presence) |
| + // the moment standing returns — so a Home blip neither leaks an |
| + // update nor strands a tab on a failed reconnect (Fable #33, note 1). |
| + // Outside team mode renewC is nil, never ready, and nothing here runs. |
| + var renew *time.Timer |
| + var renewC <-chan time.Time |
| + defer func() { |
| + if renew != nil { |
| + renew.Stop() |
| + } |
| + }() |
| + held := false |
| + stillReaches := func() bool { |
| + if a.team == nil { |
| + return true |
| + } |
| + decision, next := a.teamStreamAccess(r, d.ID) |
| + switch decision { |
| + case streamEnds: |
| + return false |
| + case streamHolds: |
| + held, next = true, streamHoldRetry |
| + default: |
| + held = false |
| + } |
| + switch { |
| + case next <= 0: |
| + renewC = nil |
| + case renew == nil: |
| + renew = time.NewTimer(next) |
| + renewC = renew.C |
| + default: |
| + renew.Reset(next) |
| + renewC = renew.C |
| + } |
| + return true |
| + } |
| + |
| + // send is every byte's one exit: deadline armed, bytes, flush. The |
| // deadline error is ignored deliberately — a ResponseWriter that |
| // cannot set deadlines still streams, unbounded — while a write |
| // error ends the handler, because it means the client is gone. |
| - write := func(text string) bool { |
| + send := func(text string) bool { |
| _ = rc.SetWriteDeadline(time.Now().Add(streamWriteDeadline)) |
| if _, err := io.WriteString(w, text); err != nil { |
| return false |
| @@ -603,10 +657,10 @@ func (a *app) deckStream(w http.ResponseWriter, r *http.Request) { |
| fl.Flush() |
| return true |
| } |
| - seqEvent := func(seq int64) bool { |
| - return write("event: update\ndata: " + strconv.FormatInt(seq, 10) + "\n\n") |
| + seqText := func(seq int64) string { |
| + return "event: update\ndata: " + strconv.FormatInt(seq, 10) + "\n\n" |
| } |
| - presenceEvent := func(set live.PresenceSet) bool { |
| + presenceText := func(set live.PresenceSet) (string, bool) { |
| // A nil set must go out as `[]`, not `null`: the client reads |
| // this as "everybody here", and null is a different sentence. |
| if set == nil { |
| @@ -615,9 +669,39 @@ func (a *app) deckStream(w http.ResponseWriter, r *http.Request) { |
| body, err := json.Marshal(set) |
| if err != nil { |
| a.logger.Error("slides: encode presence", "deck", d.Sqid, "err", err) |
| + return "", false |
| + } |
| + return "event: presence\ndata: " + string(body) + "\n\n", true |
| + } |
| + // catchUp is what a held stream owes when standing returns: what the |
| + // connect events say, read afresh. |
| + catchUp := func() bool { |
| + var now Deck |
| + if err := a.db.G.WithContext(r.Context()).Take(&now, d.ID).Error; err != nil { |
| return false |
| } |
| - return write("event: presence\ndata: " + string(body) + "\n\n") |
| + presence, ok := presenceText(a.live.Snapshot(d.Sqid)) |
| + return ok && send(seqText(now.Seq)) && send(presence) |
| + } |
| + // write re-decides (team mode) and then sends; while held only a |
| + // comment carries, since it says nothing about the deck. |
| + write := func(text string) bool { |
| + wasHeld := held |
| + if !stillReaches() { |
| + return false |
| + } |
| + if held { |
| + return !strings.HasPrefix(text, ":") || send(text) |
| + } |
| + if wasHeld && !catchUp() { |
| + return false |
| + } |
| + return send(text) |
| + } |
| + seqEvent := func(seq int64) bool { return write(seqText(seq)) } |
| + presenceEvent := func(set live.PresenceSet) bool { |
| + text, ok := presenceText(set) |
| + return ok && write(text) |
| } |
| if !seqEvent(current.Seq) { |
| @@ -669,6 +753,16 @@ func (a *app) deckStream(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| heartbeat.Reset(streamHeartbeat) |
| + case <-renewC: |
| + // The Member lease this stream stood on is up, or a held |
| + // stream's retry is due: renewed, still held, or ended. |
| + wasHeld := held |
| + if !stillReaches() { |
| + return |
| + } |
| + if wasHeld && !held && !catchUp() { |
| + return |
| + } |
| } |
| } |
| } |
| @@ -721,10 +815,7 @@ func (a *app) deckPresence(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - name := u.Name |
| - if name == "" { |
| - name = u.Email |
| - } |
| + name := u.viewerLabel() |
| a.live.PublishPresence(d.Sqid, live.Presence{ |
| Client: body.Client, |
| Name: name, |
diff --git a/internal/slides/locales/en.toml b/internal/slides/locales/en.toml| index 7ec848d..8f0b451 100644 |
| --- a/internal/slides/locales/en.toml |
| +++ b/internal/slides/locales/en.toml |
| @@ -86,6 +86,10 @@ slides.error.back = "Back" |
| slides.decks.title = "Decks" |
| slides.decks.empty.title = "No decks yet" |
| slides.decks.empty.body = "A deck is a set of slides you write, present and share. Start one and it will show up here." |
| +# The deck list in team mode when Home's roster cannot be read (Paul, |
| +# 2026-10-28): what is listed is only what was granted to the person. |
| +slides.decks.partial.title = "We couldn’t check your team access" |
| +slides.decks.partial.body = "Only decks shared with you are shown. Try again in a moment for the rest." |
| slides.decks.new = "New deck" |
| slides.decks.new.body = "Give it a name and a look. Both are easy to change later." |
| slides.decks.new.submit = "Create deck" |
diff --git a/internal/slides/models.go b/internal/slides/models.go| index 3a85126..1ba8768 100644 |
| --- a/internal/slides/models.go |
| +++ b/internal/slides/models.go |
| @@ -50,6 +50,11 @@ type User struct { |
| // commitment. |
| Colour string |
| CreatedAt time.Time |
| + |
| + // team is this request's roster standing for the person, in team |
| + // mode only (team_access.go). Never a column, never stored: a user |
| + // read without it has no team standing until a request asks. |
| + team *teamAccess `gorm:"-"` |
| } |
| // Deck is one presentation: the row that owns a Y.Doc, not the document |
diff --git a/internal/slides/presentation.go b/internal/slides/presentation.go| index 2964717..aa5c20b 100644 |
| --- a/internal/slides/presentation.go |
| +++ b/internal/slides/presentation.go |
| @@ -189,6 +189,28 @@ func eventFor(p Presentation) present.Event { |
| // dead pairing code is a 404 too (remotePair), because neither should |
| // confirm anything to a stranger who is guessing. |
| func (a *app) presentationFor(w http.ResponseWriter, r *http.Request) (Presentation, bool) { |
| + p, ok := a.presentationRow(w, r) |
| + if !ok { |
| + return Presentation{}, false |
| + } |
| + // Team mode: the talk stands on its presenter's reach to the deck |
| + // (team_present.go). Gone ends it, and it is over like any other. |
| + switch reach, _ := a.presentationStands(r.Context(), p); reach { |
| + case presenterGone: |
| + a.gone(w, r) |
| + return Presentation{}, false |
| + case presenterUnknown: |
| + a.teamUnavailable(w, r) |
| + return Presentation{}, false |
| + } |
| + return p, true |
| +} |
| + |
| +// presentationRow is presentationFor before team mode's presenter check: |
| +// the row, 404 or 410. The projector's stream starts here, because it |
| +// holds rather than refuses while the presenter's standing is unknown |
| +// (streamPresentation). |
| +func (a *app) presentationRow(w http.ResponseWriter, r *http.Request) (Presentation, bool) { |
| var p Presentation |
| err := a.db.G.WithContext(r.Context()). |
| Where("sqid = ?", chi.URLParam(r, "session")).Take(&p).Error |
| @@ -297,6 +319,7 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| actor := actorFor(u) |
| + g := a.deckGuard(r.Context(), u, d) |
| var p Presentation |
| err = a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor). |
| @@ -306,14 +329,22 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) { |
| // Re-pairing an open session: the row keeps its sqid, its |
| // slide and its code, so every page already watching it stays |
| // watching the same talk. |
| - if err := a.db.G.WithContext(r.Context()).Model(&Presentation{}). |
| - Where("id = ? AND ended_at IS NULL", p.ID). |
| - Update("remote_token_hash", hashRemoteToken(token)).Error; err != nil { |
| + if err := a.guarded(r.Context(), g, func(db *gorm.DB) error { |
| + return db.Model(&Presentation{}). |
| + Where("id = ? AND ended_at IS NULL", p.ID). |
| + Update("remote_token_hash", hashRemoteToken(token)).Error |
| + }); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "re-pair a presentation", err) |
| return |
| } |
| case errors.Is(err, gorm.ErrRecordNotFound): |
| - p, err = a.createPresentation(r, d, actor, token) |
| + p, err = a.createPresentation(r, d, actor, token, g) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.fail(w, r, "start a presentation", err) |
| return |
| @@ -329,7 +360,10 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) { |
| // createPresentation writes the row, retrying on a code already in use |
| // by another live session and on the vanishingly unlikely sqid |
| // collision the unique index would refuse. |
| -func (a *app) createPresentation(r *http.Request, d Deck, actor, token string) (Presentation, error) { |
| +// |
| +// g is the team-mode write guard for the presenter on d, around the |
| +// insert; nil outside team mode. |
| +func (a *app) createPresentation(r *http.Request, d Deck, actor, token string, g writeGuard) (Presentation, error) { |
| for attempt := 0; attempt < maxCodeAttempts; attempt++ { |
| sqid, err := newSqid() |
| if err != nil { |
| @@ -354,7 +388,7 @@ func (a *app) createPresentation(r *http.Request, d Deck, actor, token string) ( |
| RemoteTokenHash: hashRemoteToken(token), |
| StartedAt: time.Now().UTC(), |
| } |
| - err = a.db.G.WithContext(r.Context()).Create(&p).Error |
| + err = a.guarded(r.Context(), g, func(db *gorm.DB) error { return db.Create(&p).Error }) |
| if err == nil { |
| return p, nil |
| } |
| @@ -1096,10 +1130,18 @@ const ( |
| // (internal/slides/present), and why the connect event matters: a |
| // dropped page reconnects and is immediately right again. |
| func (a *app) presentStream(w http.ResponseWriter, r *http.Request) { |
| - p, ok := a.presentationFor(w, r) |
| + // Not presentationFor: a projector's EventSource that is answered a |
| + // 503 fails for good, so in team mode the stream opens while the |
| + // presenter's standing is unknown and holds (streamPresentation). A |
| + // presenter who is gone is still the 410. |
| + p, ok := a.presentationRow(w, r) |
| if !ok { |
| return |
| } |
| + if reach, _ := a.presentationStands(r.Context(), p); reach == presenterGone { |
| + a.gone(w, r) |
| + return |
| + } |
| a.streamPresentation(w, r, p, nil) |
| } |
| @@ -1141,10 +1183,51 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese |
| w.WriteHeader(http.StatusOK) |
| fl.Flush() |
| - write := func(text string) bool { |
| - if alive != nil && !alive() { |
| + // Team mode: the talk stands on its presenter's reach, re-decided |
| + // before every delivery and again when the presenter's Member lease |
| + // runs out (team_present.go). A presenter who is gone ends the talk |
| + // and the stream. While the presenter's standing cannot be read the |
| + // stream is HELD: open, delivering nothing but comment pings, |
| + // re-asking at streamHoldRetry (the roster's RetryAfter), and sent the talk's current state |
| + // the moment it can be read again — a projector's EventSource fails |
| + // for good on a 503, so ending the stream would blank the room |
| + // (Fable #33, note 1). Outside team mode renewC is nil and |
| + // presentationStands always stands. |
| + var renew *time.Timer |
| + var renewC <-chan time.Time |
| + defer func() { |
| + if renew != nil { |
| + renew.Stop() |
| + } |
| + }() |
| + held := false |
| + stands := func() bool { |
| + if a.team == nil { |
| + return true |
| + } |
| + reach, next := a.presentationStands(r.Context(), p) |
| + switch reach { |
| + case presenterGone: |
| return false |
| + case presenterUnknown: |
| + held, next = true, streamHoldRetry |
| + default: |
| + held = false |
| } |
| + switch { |
| + case next <= 0: |
| + renewC = nil |
| + case renew == nil: |
| + renew = time.NewTimer(next) |
| + renewC = renew.C |
| + default: |
| + renew.Reset(next) |
| + renewC = renew.C |
| + } |
| + return true |
| + } |
| + |
| + send := func(text string) bool { |
| // The deadline error is ignored deliberately: a |
| // ResponseWriter that cannot set deadlines still streams, |
| // unbounded. A write error ends the handler, because it means |
| @@ -1156,6 +1239,32 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese |
| fl.Flush() |
| return true |
| } |
| + // catchUp is what a held stream owes when the presenter's standing |
| + // returns: the talk as it is now, read afresh. |
| + catchUp := func() bool { |
| + var now Presentation |
| + if err := a.db.G.WithContext(r.Context()).Take(&now, p.ID).Error; err != nil { |
| + return false |
| + } |
| + body, err := json.Marshal(eventFor(now)) |
| + return err == nil && send("event: slide\ndata: "+string(body)+"\n\n") |
| + } |
| + write := func(text string) bool { |
| + if alive != nil && !alive() { |
| + return false |
| + } |
| + wasHeld := held |
| + if !stands() { |
| + return false |
| + } |
| + if held { |
| + return !strings.HasPrefix(text, ":") || send(text) |
| + } |
| + if wasHeld && !catchUp() { |
| + return false |
| + } |
| + return send(text) |
| + } |
| event := func(e present.Event) bool { |
| body, err := json.Marshal(e) |
| if err != nil { |
| @@ -1204,6 +1313,14 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese |
| return |
| } |
| heartbeat.Reset(streamHeartbeat) |
| + case <-renewC: |
| + wasHeld := held |
| + if !stands() { |
| + return |
| + } |
| + if wasHeld && !held && !catchUp() { |
| + return |
| + } |
| } |
| } |
| } |
| @@ -1413,6 +1530,12 @@ func (a *app) liveSessionFor(r *http.Request, deckID int64) (Presentation, bool) |
| } |
| return Presentation{}, false |
| } |
| + // Team mode: a talk whose presenter no longer reaches the deck is no |
| + // talk to follow (team_present.go), and one that cannot be decided |
| + // now is not followed either; the share link's own deck still is. |
| + if reach, _ := a.presentationStands(r.Context(), p); reach != presenterReaches { |
| + return Presentation{}, false |
| + } |
| return p, true |
| } |
diff --git a/internal/slides/replay_long_test.go b/internal/slides/replay_long_test.go| index 4229d81..1c6abf7 100644 |
| --- a/internal/slides/replay_long_test.go |
| +++ b/internal/slides/replay_long_test.go |
| @@ -23,7 +23,7 @@ func TestAuthoritativeLogBeyondCoreRetentionLimit(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - row, err := a.createDeckRow(ctx, owner, "Long history", defaultTheme) |
| + row, err := a.createDeckRow(ctx, owner, "Long history", defaultTheme, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/slides/sample.go b/internal/slides/sample.go| index db195eb..61469ed 100644 |
| --- a/internal/slides/sample.go |
| +++ b/internal/slides/sample.go |
| @@ -33,7 +33,10 @@ const sampleTheme = defaultTheme |
| // One row, then one op batch: the whole deck is a single DeckUpdate, so |
| // the log a later request replays is one entry rather than forty. |
| func (a *app) seedSampleDeck(ctx context.Context, u User) error { |
| - d, err := a.createDeckRow(ctx, u, sampleDeckTitle, sampleTheme) |
| + // Making a deck rests on standing in team mode, the sample one too: |
| + // u carries the Access it was admitted on (team_home_only.go). |
| + g := a.memberGuard(ctx, u) |
| + d, err := a.createDeckRow(ctx, u, sampleDeckTitle, sampleTheme, g) |
| if err != nil { |
| return err |
| } |
| @@ -45,7 +48,7 @@ func (a *app) seedSampleDeck(ctx context.Context, u User) error { |
| if err != nil { |
| return err |
| } |
| - return a.editDeck(ctx, &d, actorFor(u), encoded, nil) |
| + return a.editDeck(ctx, &d, actorFor(u), encoded, nil, g) |
| } |
| // slideIDs mints the ids one slide's ops need: the slide's own and n |
diff --git a/internal/slides/share.go b/internal/slides/share.go| index 3e921d0..631ff9d 100644 |
| --- a/internal/slides/share.go |
| +++ b/internal/slides/share.go |
| @@ -121,7 +121,7 @@ func (a *app) deckShare(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck) |
| if !ok { |
| return |
| } |
| @@ -219,7 +219,7 @@ func (a *app) mintShareLink(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck) |
| if !ok { |
| return |
| } |
| @@ -235,7 +235,10 @@ func (a *app) mintShareLink(w http.ResponseWriter, r *http.Request) { |
| Actor: actorFor(u), |
| CreatedAt: time.Now().UTC(), |
| } |
| - if err := a.db.G.WithContext(r.Context()).Create(&link).Error; err != nil { |
| + if err := a.guarded(r.Context(), a.memberGuard(r.Context(), u), func(db *gorm.DB) error { return db.Create(&link).Error }); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.fail(w, r, "create share link", err) |
| return |
| } |
| @@ -248,7 +251,7 @@ func (a *app) mintShareLink(w http.ResponseWriter, r *http.Request) { |
| // |
| // Scoped by deck as well as by id, so an id belonging to another deck |
| // is a 404 rather than a revocation somebody was not entitled to make; |
| -// the deck itself is already the owner's (ownedDeckFor). |
| +// the deck itself is already one this person may share (ownedDeckFor). |
| // |
| // Revoking twice is not an error. The URL is off either way, and a |
| // second POST from a double-clicked button should not look like a |
| @@ -258,7 +261,7 @@ func (a *app) revokeShareLink(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - d, ok := a.ownedDeckFor(w, r, u) |
| + d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck) |
| if !ok { |
| return |
| } |
| @@ -272,14 +275,22 @@ func (a *app) revokeShareLink(w http.ResponseWriter, r *http.Request) { |
| // revoked_at IS NULL in the WHERE, so a second POST cannot move the |
| // timestamp: when a link was turned off is a fact about it, and a |
| // double-clicked button must not rewrite it. |
| - res := a.db.G.WithContext(r.Context()).Model(&ShareLink{}). |
| - Where("id = ? AND deck_id = ? AND revoked_at IS NULL", id, d.ID). |
| - Update("revoked_at", now) |
| - if res.Error != nil { |
| - a.fail(w, r, "revoke share link", res.Error) |
| + var revoked int64 |
| + err = a.guarded(r.Context(), a.memberGuard(r.Context(), u), func(db *gorm.DB) error { |
| + res := db.Model(&ShareLink{}). |
| + Where("id = ? AND deck_id = ? AND revoked_at IS NULL", id, d.ID). |
| + Update("revoked_at", now) |
| + revoked = res.RowsAffected |
| + return res.Error |
| + }) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| + if err != nil { |
| + a.fail(w, r, "revoke share link", err) |
| return |
| } |
| - if res.RowsAffected == 0 { |
| + if revoked == 0 { |
| // Either the link is already revoked — in which case the URL is |
| // off, the person got what they asked for, and an error page |
| // would be a lie — or the id is not this deck's, which is a 404 |
diff --git a/internal/slides/snapshot_fallback_test.go b/internal/slides/snapshot_fallback_test.go| index eb845f7..18432a6 100644 |
| --- a/internal/slides/snapshot_fallback_test.go |
| +++ b/internal/slides/snapshot_fallback_test.go |
| @@ -18,7 +18,7 @@ func TestUnreadableSnapshotFallsBackToAuthoritativeLog(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - row, err := a.createDeckRow(ctx, owner, "Preserved deck", defaultTheme) |
| + row, err := a.createDeckRow(ctx, owner, "Preserved deck", defaultTheme, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -26,14 +26,14 @@ func TestUnreadableSnapshotFallsBackToAuthoritativeLog(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := a.editDeck(ctx, &row, actorFor(owner), opening, nil); err != nil { |
| + if err := a.editDeck(ctx, &row, actorFor(owner), opening, nil, nil); err != nil { |
| t.Fatal(err) |
| } |
| batch, err := opsJSON([]op{{"op": "set_meta", "title": "Newest log title"}}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := a.editDeck(ctx, &row, actorFor(owner), batch, nil); err != nil { |
| + if err := a.editDeck(ctx, &row, actorFor(owner), batch, nil, nil); err != nil { |
| t.Fatal(err) |
| } |
| want := viewJSON(t, a, row) |
diff --git a/internal/slides/snapshot_test.go b/internal/slides/snapshot_test.go| index c25f4c0..ab6fae9 100644 |
| --- a/internal/slides/snapshot_test.go |
| +++ b/internal/slides/snapshot_test.go |
| @@ -29,7 +29,7 @@ func TestSnapshotWrittenAtBoundaryAndUsedOnOpen(t *testing.T) { |
| } |
| actor := actorFor(owner) |
| - row, err := a.createDeckRow(ctx, owner, "Long deck", defaultTheme) |
| + row, err := a.createDeckRow(ctx, owner, "Long deck", defaultTheme, nil) |
| if err != nil { |
| t.Fatalf("createDeckRow: %v", err) |
| } |
| @@ -37,7 +37,7 @@ func TestSnapshotWrittenAtBoundaryAndUsedOnOpen(t *testing.T) { |
| if err != nil { |
| t.Fatalf("openingOps: %v", err) |
| } |
| - if err := a.editDeck(ctx, &row, actor, opening, nil); err != nil { |
| + if err := a.editDeck(ctx, &row, actor, opening, nil, nil); err != nil { |
| t.Fatalf("editDeck: %v", err) |
| } |
| @@ -54,7 +54,7 @@ func TestSnapshotWrittenAtBoundaryAndUsedOnOpen(t *testing.T) { |
| if err != nil { |
| t.Fatalf("opsJSON: %v", err) |
| } |
| - if _, err := a.applyOps(ctx, h, &row, actor, batch, nil); err != nil { |
| + if _, err := a.applyOps(ctx, h, &row, actor, batch, nil, nil); err != nil { |
| t.Fatalf("applyOps at seq %d: %v", row.Seq, err) |
| } |
| } |
diff --git a/internal/slides/team_access.go b/internal/slides/team_access.go| new file mode 100644 |
| index 0000000..d7907a0 |
| --- /dev/null |
| +++ b/internal/slides/team_access.go |
| @@ -0,0 +1,304 @@ |
| +package slides |
| + |
| +// Team mode's per-request standing. With a.team nil nothing here runs: |
| +// every helper below returns today's answer unchanged. |
| +// |
| +// Standing itself is home/teammode's Access. Identity is resolved from |
| +// the actual session (a local address, an account link, or a Home-only |
| +// user); the roster is asked about the Home subject, if there is one; |
| +// and the answer is one of three: |
| +// |
| +// - Member: the team rung of visibleDecks — the person's own decks and |
| +// every deck on the team rung — and ownership of their own decks. |
| +// The roster's role says owner or member, and only the roster's. |
| +// - NotMember: a guest. Only decks a grant names them on. |
| +// - Unknown: the roster could not be read within its lease. Grants |
| +// still work, and the deck 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 |
| +// deck is not theirs. |
| +// |
| +// A Member decision carries a lease. teamAccess.state() checks it every |
| +// time it is asked, and a write checks it again inside its own |
| +// transaction, before and after the write (team_guard.go). Streams |
| +// re-decide before each delivery and at the lease (teamStreamAccess). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "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" |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/slides/internal/slides/teamstate" |
| +) |
| + |
| +// teamAccess is one request's standing for one user: 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 teamAccess, |
| +// or one with a nil Access, is Unknown. |
| +type teamAccess struct { |
| + *teammode.Access |
| +} |
| + |
| +var errNoIdentity = errors.New("slides: no team identity") |
| + |
| +func (t *teamAccess) state() roster.State { |
| + if t == nil { |
| + return roster.Unknown |
| + } |
| + return t.State() |
| +} |
| + |
| +func (t *teamAccess) access() *teammode.Access { |
| + if t == nil { |
| + return nil |
| + } |
| + return t.Access |
| +} |
| + |
| +// rosterOwner reports whether the roster says this person is one of the |
| +// team's owners, now. "" (anything but Member) is not. |
| +func (t *teamAccess) rosterOwner() bool { |
| + return t != nil && t.Role() == "owner" |
| +} |
| + |
| +// member reports whether u stands on the team rung: always outside team |
| +// mode (the rung was never the roster's), and only while the roster says |
| +// Member inside it. |
| +func (a *app) member(u User) bool { |
| + return a.team == nil || u.team.state() == roster.Member |
| +} |
| + |
| +// teamIdentify resolves a session to its users row and the Home subject |
| +// the roster knows them by ("" when there is none: a local account with |
| +// no link, which is no team standing). A local session's row is created |
| +// on first sight, exactly as currentUser always has; nothing else is. |
| +func (a *app) teamIdentify(ctx context.Context, s sessions.Session) (User, string, error) { |
| + switch s.Method { |
| + case connect.HomeMethod: |
| + if a.home == nil { |
| + return User{}, "", errNoIdentity |
| + } |
| + p, err := a.home.Resolve(ctx, s.Subject) |
| + if errors.Is(err, linkstore.ErrStorage) { |
| + return User{}, "", errTeamUnavailable |
| + } |
| + if err != nil { |
| + return User{}, "", errNoIdentity |
| + } |
| + var u User |
| + if err := a.db.G.WithContext(ctx).Take(&u, p.ID).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return User{}, "", errNoIdentity |
| + } |
| + return User{}, "", errTeamUnavailable |
| + } |
| + return u, s.Subject, nil |
| + case "magiclink", "keymail": |
| + // No sample deck here: a local account made in team mode has no |
| + // link yet, so it is a guest, and guests create nothing |
| + // (teamMemberOnly). A Home-only member gets theirs at sign-in |
| + // (team_home_only.go). |
| + u, _, err := ensureUser(ctx, a.db.G, s.Subject) |
| + if err != nil { |
| + return User{}, "", errTeamUnavailable |
| + } |
| + subject, err := a.homeSubjectOf(ctx, u.ID) |
| + if err != nil { |
| + return User{}, "", err |
| + } |
| + return u, subject, nil |
| + } |
| + return User{}, "", errNoIdentity |
| +} |
| + |
| +// homeSubjectOf is the Home subject the roster knows a user by: a |
| +// Home-only row or an account link, "" for neither. |
| +func (a *app) homeSubjectOf(ctx context.Context, id int64) (string, error) { |
| + subject, err := teamstate.HomeSubject(ctx, a.team.db, a.team.issuer(), id) |
| + switch { |
| + case err == nil: |
| + return subject, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + return "", nil |
| + } |
| + return "", errTeamUnavailable |
| +} |
| + |
| +// teamCurrentUser is currentUser in team mode: the session's user with |
| +// the roster's standing attached. It signs nobody out for lacking |
| +// standing — a removed member keeps a session that reaches only what was |
| +// shared with them — but a session that resolves to nobody is ended as |
| +// before, and one that cannot be resolved now is a retryable 503. |
| +func (a *app) teamCurrentUser(w http.ResponseWriter, r *http.Request, s sessions.Session) (User, sessionOutcome) { |
| + u, subject, err := a.teamIdentify(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + a.teamUnavailable(w, r) |
| + return User{}, sessionOffboarded |
| + case err != nil && s.Method == connect.HomeMethod: |
| + a.revokeHome(w, r, s.Subject) |
| + return User{}, sessionOffboarded |
| + case err != nil: |
| + return User{}, sessionNone |
| + } |
| + u.team = &teamAccess{Access: a.team.Access(r.Context(), subject)} |
| + return u, sessionOK |
| +} |
| + |
| +// withStanding asks the roster about somebody other than the viewer — |
| +// a deck's owner (team_owner.go), a presenter (team_present.go), an |
| +// agent's operator — so what it says about them is what visibleDecks |
| +// would decide for them. |
| +func (a *app) withStanding(ctx context.Context, u User) User { |
| + if a.team == nil { |
| + return u |
| + } |
| + subject, err := a.homeSubjectOf(ctx, u.ID) |
| + if err != nil { |
| + u.team = nil // Unknown |
| + return u |
| + } |
| + u.team = &teamAccess{Access: a.team.Access(ctx, subject)} |
| + return u |
| +} |
| + |
| +// streamDecision is what one stream delivery may do: deliver, hold (the |
| +// stream stays open and delivers nothing, because standing cannot be read |
| +// right now), or end (a definite "no"). |
| +type streamDecision int |
| + |
| +const ( |
| + streamDelivers streamDecision = iota |
| + streamHolds |
| + streamEnds |
| +) |
| + |
| +// streamHoldRetry is how often a held stream re-asks: the roster's own |
| +// retry interval. A variable only so a test need not wait it out. |
| +var streamHoldRetry = roster.RetryAfter |
| + |
| +// teamStreamAccess decides one deck-stream delivery afresh — session, |
| +// user, roster, reach — and says how long a standing-backed answer may |
| +// stand before it must be asked again: the Member lease's remaining |
| +// time, or 0 when nothing expires on a timer (the answer rested on a |
| +// grant). Unknown standing that a grant does not cover holds rather than |
| +// ends: nothing is delivered, and nothing is decided against the person |
| +// either. Team mode only. |
| +func (a *app) teamStreamAccess(r *http.Request, deckID int64) (streamDecision, time.Duration) { |
| + s, ok := sessions.Current(r) |
| + if !ok { |
| + return streamEnds, 0 |
| + } |
| + u, subject, err := a.teamIdentify(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + return streamHolds, 0 |
| + case err != nil: |
| + return streamEnds, 0 |
| + } |
| + u.team = &teamAccess{Access: a.team.Access(r.Context(), subject)} |
| + var n int64 |
| + if err := a.visibleDecks(r.Context(), u).Where("decks.id = ?", deckID).Count(&n).Error; err != nil { |
| + return streamHolds, 0 |
| + } |
| + // Asked after the reach, of the same Access: State latches, so a |
| + // lease that lapsed (or was contended) after the query was built |
| + // reads Unknown here, and then the deck may have been reached |
| + // through the team rung that no longer stands. Without a lease only |
| + // a grant holds, and nothing then expires on a timer. |
| + state := u.team.state() |
| + if state != roster.Member { |
| + switch { |
| + case a.grantedTo(r.Context(), u, Deck{ID: deckID}): |
| + return streamDelivers, 0 |
| + case state == roster.Unknown: |
| + return streamHolds, 0 |
| + } |
| + return streamEnds, 0 |
| + } |
| + if n == 0 { |
| + return streamEnds, 0 |
| + } |
| + renew := u.team.Remaining() |
| + if renew <= 0 { |
| + renew = time.Second |
| + } |
| + return streamDelivers, renew |
| +} |
| + |
| +// teamJobOwner is the jobs registry's owner key in team mode. A |
| +// Home-only user has no address to key on, so every team-mode session |
| +// and every agent's operator keys on the user instead. |
| +func teamJobOwner(id int64) string { return "slides-user:" + strconv.FormatInt(id, 10) } |
| + |
| +// teamLabel is how an addressless (Home-only) user is shown where an |
| +// address would be: presence, a deck's last change, the account menu. |
| +const teamLabel = "Oficina account" |
| + |
| +// homeOnlyLabel is teamLabel and the last four characters of the person |
| +// ref ("Oficina account …k7qz"), as Home's Team page shows a ref, so two |
| +// Home-only people are told apart. |
| +func homeOnlyLabel(subject string) string { |
| + if len(subject) <= 4 { |
| + return teamLabel |
| + } |
| + return teamLabel + " …" + subject[len(subject)-4:] |
| +} |
| + |
| +// label is how a person is shown: their name, else their address, else |
| +// (only a team-mode Home-only user has neither) the Home-only label for |
| +// subject. Outside team mode this is exactly the old Name-then-Email. |
| +func (u User) label(subject string) string { |
| + if u.Name != "" { |
| + return u.Name |
| + } |
| + if strings.TrimSpace(u.Email) != "" || subject == "" { |
| + return u.Email |
| + } |
| + return homeOnlyLabel(subject) |
| +} |
| + |
| +// address is where a person's address is shown (an agent's principal): |
| +// the address, or for a Home-only user, who has none, the Home-only |
| +// label for the subject their own Access was asked about. Outside team |
| +// mode it is exactly Email. |
| +func (u User) address() string { |
| + if u.Email != "" || u.team == nil || u.team.Access == nil { |
| + return u.Email |
| + } |
| + return homeOnlyLabel(u.team.Subject()) |
| +} |
| + |
| +// viewerLabel is u.label with the subject the request's own Access was |
| +// asked about. |
| +func (u User) viewerLabel() string { |
| + if u.Email != "" || u.team == nil || u.team.Access == nil { |
| + return u.label("") |
| + } |
| + return u.label(u.team.Subject()) |
| +} |
| + |
| +// homeOnlySubjects maps each Home-only user to its subject, for labels on |
| +// pages that name people without asking the roster. Nil outside team |
| +// mode or on a read failure, which only costs the suffix. |
| +func (a *app) homeOnlySubjects(ctx context.Context) map[int64]string { |
| + if a.team == nil { |
| + return nil |
| + } |
| + out, err := teamstate.HomeSubjects(ctx, a.team.db, a.team.issuer()) |
| + if err != nil { |
| + return nil |
| + } |
| + return out |
| +} |
diff --git a/internal/slides/team_access_test.go b/internal/slides/team_access_test.go| new file mode 100644 |
| index 0000000..b9a9b76 |
| --- /dev/null |
| +++ b/internal/slides/team_access_test.go |
| @@ -0,0 +1,302 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| +) |
| + |
| +func deckPath(d Deck) string { return "/d/" + d.Sqid } |
| + |
| +func countRows(t *testing.T, f *teamFixture, model any) int64 { |
| + t.Helper() |
| + var n int64 |
| + if err := f.d.G.Model(model).Count(&n).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// A roster member with no account here signs in with Home alone: an |
| +// addressless user, the sample deck, the team rung, and the chrome of a |
| +// signed-in person named by their person ref. |
| +func TestTeamHomeOnlyMemberSignsInAndReachesTheTeamRung(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + private := f.deck(colleague, "Colleague's own", rungPrivate) |
| + |
| + u := f.member(teamSubject('a'), "member") |
| + var email sql.NullString |
| + if err := f.d.Writer().QueryRow("SELECT email FROM users WHERE id=?", u.ID).Scan(&email); err != nil || email.Valid { |
| + t.Fatalf("Home-only user email = %v, %v; want NULL", email, err) |
| + } |
| + list := f.get("/") |
| + body := list.Body.String() |
| + if list.Code != 200 || !strings.Contains(body, "Team plan") || !strings.Contains(body, sampleDeckTitle) || strings.Contains(body, "Colleague's own") { |
| + t.Fatalf("member list = %d, want the team deck and their sample deck only:\n%s", list.Code, body) |
| + } |
| + if strings.Contains(body, "data-partial") { |
| + t.Fatal("a member's list was marked partial") |
| + } |
| + // Signed-in chrome, named by the ref: a sign-out form, no Sign in. |
| + if !strings.Contains(body, `action="/signout"`) || !strings.Contains(body, homeOnlyLabel(teamSubject('a'))) { |
| + t.Fatalf("Home-only member's chrome is not signed in as %q", homeOnlyLabel(teamSubject('a'))) |
| + } |
| + if got := f.get(deckPath(plan)); got.Code != 200 { |
| + t.Fatalf("team deck = %d", got.Code) |
| + } |
| + if got := f.get(deckPath(private)); got.Code != 404 { |
| + t.Fatalf("another member's private deck = %d, want 404", got.Code) |
| + } |
| +} |
| + |
| +// Allocation only for a current Member: a stranger is connect's |
| +// "unknown", an undecidable roster is a 503, and a live session for |
| +// somebody else is refused before anything is allocated. |
| +func TestTeamSignInAllocatesOnlyForACurrentMember(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.com") |
| + users := countRows(t, f, &User{}) |
| + |
| + if got := f.freshHomeSignIn(teamSubject('s')); got.Code != http.StatusForbidden { |
| + t.Fatalf("stranger = %d, want connect's 403", got.Code) |
| + } |
| + if countRows(t, f, &User{}) != users { |
| + t.Fatal("a stranger was allocated a user") |
| + } |
| + |
| + f.dir.Set(teamSubject('u'), "member") |
| + f.expired() |
| + if got := f.freshHomeSignIn(teamSubject('u')); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("Unknown roster = %d, want 503", got.Code) |
| + } |
| + if countRows(t, f, &User{}) != users { |
| + t.Fatal("an undecidable roster allocated a user") |
| + } |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| + |
| + f.jar = map[string]*http.Cookie{} |
| + f.localUser("x@example.com") |
| + users = countRows(t, f, &User{}) |
| + f.localSession("x@example.com") |
| + if got := f.signInHome(teamSubject('u')); got.Code != http.StatusForbidden { |
| + t.Fatalf("member arriving over another session = %d, want 403", got.Code) |
| + } |
| + if countRows(t, f, &User{}) != users { |
| + t.Fatal("an arrival over a live session allocated a user") |
| + } |
| +} |
| + |
| +// A known Home-only member arriving over somebody else's live session is |
| +// connect's same-person refusal, and that session survives. |
| +func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.com") |
| + f.member(teamSubject('a'), "member") |
| + f.jar = map[string]*http.Cookie{} |
| + f.localUser("x@example.com") |
| + f.localSession("x@example.com") |
| + before := map[string]string{} |
| + for n, c := range f.jar { |
| + before[n] = c.Value |
| + } |
| + if got := f.signInHome(teamSubject('a')); got.Code != http.StatusForbidden { |
| + t.Fatalf("known arrival over another session = %d, want 403", got.Code) |
| + } |
| + name := f.a.homeSessions.CookieName() |
| + if f.jar[name] == nil || f.jar[name].Value != before[name] { |
| + t.Fatal("the local session was replaced") |
| + } |
| + s, ok := f.sessionNow() |
| + if !ok || s.Subject != "x@example.com" { |
| + t.Fatalf("session now = %+v, want the local one", s) |
| + } |
| +} |
| + |
| +// Removal reaches an existing session within the lease: the team deck |
| +// and their own deck are gone, the list is complete (not partial) and |
| +// empty, create is 403, and they are not signed out. |
| +func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + u := f.member(teamSubject('a'), "member") |
| + own := f.deck(u, "My own", rungPrivate) |
| + for _, d := range []Deck{plan, own} { |
| + if got := f.get(deckPath(d)); got.Code != 200 { |
| + t.Fatalf("before removal %s = %d", d.Title, got.Code) |
| + } |
| + } |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + for _, d := range []Deck{plan, own} { |
| + if got := f.get(deckPath(d)); got.Code != 404 { |
| + t.Fatalf("after removal %s = %d, want 404", d.Title, got.Code) |
| + } |
| + } |
| + list := f.get("/") |
| + if list.Code != 200 || strings.Contains(list.Body.String(), "data-partial") || strings.Contains(list.Body.String(), "Team plan") { |
| + t.Fatalf("removed member's list = %d (partial or team deck shown)", list.Code) |
| + } |
| + if got := f.get("/decks/new"); got.Code != http.StatusForbidden { |
| + t.Fatalf("removed member's new deck page = %d, want 403", got.Code) |
| + } |
| + if got := f.post("/decks", url.Values{"title": {"x"}, "theme": {defaultTheme}}); got.Code != http.StatusForbidden { |
| + t.Fatalf("removed member's create = %d, want 403", got.Code) |
| + } |
| + if _, ok := f.sessionNow(); !ok { |
| + t.Fatal("a removed member was signed out") |
| + } |
| + // And a grant somebody else gave still reaches. |
| + f.grant(plan, u, colleague) |
| + if got := f.get(deckPath(plan)); got.Code != 200 { |
| + t.Fatalf("granted deck after removal = %d, want 200", got.Code) |
| + } |
| +} |
| + |
| +// The role is the roster's: a member is no owner of a colleague's deck, |
| +// and a local account with no Home identity is a guest however the |
| +// allowlist admitted it. |
| +func TestTeamStandingIsTheRostersNeverTheAllowlists(t *testing.T) { |
| + f := newTeamFixture(t, "local@example.com") |
| + owner := f.member(teamSubject('o'), "owner") |
| + plan := f.deck(owner, "Team plan", rungTeam) |
| + |
| + f.jar = map[string]*http.Cookie{} |
| + f.localSession("local@example.com") |
| + if got := f.get(deckPath(plan)); got.Code != 404 { |
| + t.Fatalf("unlinked local account on a team deck = %d, want 404", got.Code) |
| + } |
| + if got := f.get("/decks/new"); got.Code != http.StatusForbidden { |
| + t.Fatalf("unlinked local account's create = %d, want 403", got.Code) |
| + } |
| + |
| + f.member(teamSubject('m'), "member") |
| + if got := f.get(deckPath(plan) + "/settings"); got.Code != 404 { |
| + t.Fatalf("a member's settings on a colleague's deck = %d, want 404", got.Code) |
| + } |
| + if got := f.get(deckPath(plan)); got.Code != 200 { |
| + t.Fatalf("a member's team deck = %d", got.Code) |
| + } |
| +} |
| + |
| +// A held decision ends at the lease under a failing refresh: 59 s still |
| +// a member, 61 s a retryable 503 rather than a 404. |
| +func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + f.dir.SetDown(true) |
| + f.clock.Step(59 * time.Second) |
| + if got := f.get(deckPath(plan)); got.Code != 200 { |
| + t.Fatalf("at 59 s = %d, want 200", got.Code) |
| + } |
| + f.clock.Step(2 * time.Second) |
| + got := f.get(deckPath(plan)) |
| + if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("at 61 s = %d %v, want a retryable no-store 503", got.Code, got.Header()) |
| + } |
| + // The same answer for a deck that does not exist: no oracle. |
| + if got := f.get("/d/2222222222"); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("missing deck under Unknown = %d, want 503", got.Code) |
| + } |
| +} |
| + |
| +// Unknown: the list is the grants with a partial notice, the team rung |
| +// withheld; a granted deck still opens and a team deck is a retryable |
| +// 503; create is a 503 too. |
| +func TestTeamUnknownListIsPartialAndItemsAreRetryable(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + shared := f.deck(colleague, "Shared with you", rungPrivate) |
| + u := f.member(teamSubject('a'), "member") |
| + f.grant(shared, u, colleague) |
| + f.expired() |
| + |
| + list := f.get("/") |
| + body := list.Body.String() |
| + if list.Code != 200 || !strings.Contains(body, "data-partial") || !strings.Contains(body, "Shared with you") || strings.Contains(body, "Team plan") || strings.Contains(body, sampleDeckTitle) { |
| + t.Fatalf("Unknown list = %d, want the grant alone, marked partial:\n%s", list.Code, body) |
| + } |
| + if got := f.get(deckPath(shared)); got.Code != 200 { |
| + t.Fatalf("granted deck under Unknown = %d", got.Code) |
| + } |
| + if got := f.get(deckPath(plan)); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("team deck under Unknown = %d, want 503", got.Code) |
| + } |
| + if got := f.get("/decks/new"); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("create under Unknown = %d, want 503", got.Code) |
| + } |
| +} |
| + |
| +// Fable's #53 required test 3, for Slides: a Home-only member who holds |
| +// no grants, under Unknown, gets 200, the notice, and not the "No decks |
| +// yet" empty state. |
| +func TestTeamEmptyPartialListSaysPartialNotEmpty(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('a'), "member") |
| + f.expired() |
| + list := f.get("/") |
| + body := list.Body.String() |
| + if list.Code != 200 || !strings.Contains(body, "data-partial") || strings.Contains(body, "rst-empty") || strings.Contains(body, "slides.decks.empty.title") || strings.Contains(body, sampleDeckTitle) { |
| + t.Fatalf("empty Unknown list = %d, want the partial notice and no empty state:\n%s", list.Code, body) |
| + } |
| +} |
| + |
| +// A storage failure resolving the session's identity is a retryable 503, |
| +// never a sign-out. |
| +func TestTeamIdentityStorageFailureIsUnavailableNotSignOut(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.com") |
| + f.localUser("x@example.com") |
| + f.localSession("x@example.com") |
| + broken, err := sql.Open("sqlite", "file:closed?mode=memory") |
| + if err == nil { |
| + broken.Close() |
| + } |
| + real := f.a.team.db |
| + f.a.team.db = broken |
| + got := f.get("/") |
| + f.a.team.db = real |
| + if got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("identity storage failure = %d, want 503", got.Code) |
| + } |
| + if _, ok := f.sessionNow(); !ok { |
| + t.Fatal("a storage failure signed the person out") |
| + } |
| +} |
| + |
| +// connect's HomeOnly hook: a storage failure is not "nobody". |
| +func TestTeamHomeOnlyStorageFailureIsNotNobody(t *testing.T) { |
| + f := newTeamFixture(t) |
| + broken, err := sql.Open("sqlite", "file:closed2?mode=memory") |
| + if err == nil { |
| + broken.Close() |
| + } |
| + _, err = f.a.teamHomeOnly(broken)(context.Background(), teamTestIssuer, teamSubject('a')) |
| + if err == nil || err == connect.ErrNoPerson { |
| + t.Fatalf("HomeOnly over broken storage = %v, want an error that is not ErrNoPerson", err) |
| + } |
| +} |
| + |
| +// sessionNow is the session the jar's cookie currently resolves to. |
| +func (f *teamFixture) sessionNow() (struct{ Subject, Method string }, bool) { |
| + r, _ := http.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + s, ok := f.a.homeSessions.From(r) |
| + return struct{ Subject, Method string }{s.Subject, s.Method}, ok |
| +} |
| + |
| +var _ = roster.Unknown |
| +var _ = teammodetest.Team |
diff --git a/internal/slides/team_answers.go b/internal/slides/team_answers.go| new file mode 100644 |
| index 0000000..4ce3c7d |
| --- /dev/null |
| +++ b/internal/slides/team_answers.go |
| @@ -0,0 +1,128 @@ |
| +package slides |
| + |
| +// Team mode's answers: the retryable 503 for Unknown standing, the |
| +// partial list, the member-only gate and the probe. Each is a no-op |
| +// outside team mode. |
| + |
| +import ( |
| + "net/http" |
| + "strconv" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// The drive API's two team-mode error ids, beside api.go's own. |
| +const ( |
| + errForbidden = "forbidden" |
| + errUnavailable = "unavailable" |
| +) |
| + |
| +// teamUnavailable is the retryable answer for Unknown standing: the app's |
| +// own 503 page (or the plain status for a fetch), never cached, with |
| +// Retry-After. A 404 would tell a team member their deck is gone because |
| +// Home was slow. |
| +func (a *app) teamUnavailable(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", strconv.Itoa(int(roster.RetryAfter/time.Second))) |
| + a.errorPage(w, r, http.StatusServiceUnavailable, kindStatus, "") |
| +} |
| + |
| +// teamUnavailableJSON is the drive API's: the same status and headers in |
| +// the API's own error shape. |
| +func teamUnavailableJSON(w http.ResponseWriter) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", strconv.Itoa(int(roster.RetryAfter/time.Second))) |
| + apiFail(w, http.StatusServiceUnavailable, errUnavailable) |
| +} |
| + |
| +// teamUnknown reports whether u's standing could not be decided. Always |
| +// false outside team mode. |
| +func (a *app) teamUnknown(u User) bool { |
| + return a.team != nil && u.team.state() == roster.Unknown |
| +} |
| + |
| +// teamPartial reports whether a list built for u 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. visibleDecks has already withheld the team rung, so |
| +// the list holds the decks granted to them 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 grants are their whole list. |
| +// Always false outside team mode. |
| +func (a *app) teamPartial(u User) bool { |
| + if a.team == nil { |
| + return false |
| + } |
| + return u.team == nil || u.team.Partial() |
| +} |
| + |
| +// teamMemberOnly gates what makes something new on the instance (a deck, |
| +// by hand or by an agent): team members only, as Docs' and Sheets' |
| +// create. A guest gets 403, Unknown a retryable 503. Outside team mode it |
| +// lets everybody through, as before. |
| +func (a *app) teamMemberOnly(w http.ResponseWriter, r *http.Request, u User) bool { |
| + if a.team == nil { |
| + return true |
| + } |
| + switch u.team.state() { |
| + case roster.Member: |
| + return true |
| + case roster.NotMember: |
| + a.errorPage(w, r, http.StatusForbidden, kindStatus, "") |
| + default: |
| + a.teamUnavailable(w, r) |
| + } |
| + return false |
| +} |
| + |
| +// teamMemberOnlyJSON is teamMemberOnly for the drive API. |
| +func (a *app) teamMemberOnlyJSON(w http.ResponseWriter, u User) bool { |
| + if a.team == nil { |
| + return true |
| + } |
| + switch u.team.state() { |
| + case roster.Member: |
| + return true |
| + case roster.NotMember: |
| + apiFail(w, http.StatusForbidden, errForbidden) |
| + default: |
| + teamUnavailableJSON(w) |
| + } |
| + return false |
| +} |
| + |
| +// presignTTLFor is how long a presigned GET minted for u may live. Off |
| +// team mode, presignTTL. In team mode no longer than the standing it was |
| +// minted on: the Member lease's remaining time, and never beyond the |
| +// roster's own 60 s otherwise (Home implementation/teammode-package.md |
| +// §7.1: a URL must not outlive a removal). Team instances have no store |
| +// today, so nothing presigns there yet; this is what will hold when one |
| +// is bound. |
| +func (a *app) presignTTLFor(u User) time.Duration { |
| + if a.team == nil { |
| + return presignTTL |
| + } |
| + ttl := roster.MaximumAge |
| + if u.team.state() == roster.Member { |
| + if left := u.team.Remaining(); left > 0 && left < ttl { |
| + ttl = left |
| + } |
| + } |
| + return ttl |
| +} |
| + |
| +// teamProbe is GET /api/team, 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, and |
| +// {"team_mode":false} with team mode off. |
| +func (a *app) teamProbe(w http.ResponseWriter, r *http.Request) { |
| + var rt *teammode.Runtime |
| + if a.team != nil { |
| + rt = a.team.Runtime |
| + } |
| + teammode.Probe(rt).ServeHTTP(w, r) |
| +} |
diff --git a/internal/slides/team_config.go b/internal/slides/team_config.go| new file mode 100644 |
| index 0000000..988a10d |
| --- /dev/null |
| +++ b/internal/slides/team_config.go |
| @@ -0,0 +1,109 @@ |
| +package slides |
| + |
| +// Team mode: Home's roster decides standing (Home implementation/ |
| +// team-members.md Part B §7; implementation/teammode-package.md §7.1, |
| +// "Slides. As Sheets."). Configuration, the marker, the roster runtime |
| +// and the probe are home/teammode's: SLIDES_TEAM_ID, |
| +// _DIRECTORY_ORIGIN, _PROVISIONING_BASE64, _OPERATOR_KEYS_BASE64 and |
| +// _ROSTER_TOKEN, all or none, and only beside SLIDES_HOME_*. Without |
| +// them nothing in this file runs and Slides is the allowlist app it has |
| +// always been. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/slides/internal/slides/teamstate" |
| +) |
| + |
| +var ( |
| + errTeamConfig = teammode.ErrConfig |
| + errTeamUnavailable = teammode.ErrUnavailable |
| +) |
| + |
| +// homeNamespace is Slides' Home storage namespace: connect's link and |
| +// handoff sealing, and in team mode the roster evidence's. |
| +const homeNamespace = "oficina/slides" |
| + |
| +// teamState is the activation marker and the roster evidence, in |
| +// slides_team_required and slides_team_roster_evidence (migration set |
| +// slides_team, teammode's own SQL). The marker is read before anything |
| +// migrates (teamBootSchema). |
| +var teamState = teammode.MustState("slides") |
| + |
| +// teamIssuerTables are the tables holding Home identities in an issuer |
| +// column: connect's links and Slides' Home-only users. teammode.Open |
| +// refuses activation while any row names another issuer. |
| +var teamIssuerTables = []string{"home_identity_links", "slides_team_home_users"} |
| + |
| +// teamBoot is base plus team state: teammode's marker set, then Slides' |
| +// Home-only users (whose triggers name users and home_identity_links, so |
| +// it follows both). Applied only in team mode; once applied it stays, |
| +// because the marker in it is what keeps the database in team mode. |
| +func teamBoot(base *migrate.Set) *migrate.Set { |
| + return migrate.Merge(base, teamState.Schema(), teamstate.Schema) |
| +} |
| + |
| +// 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, and the record is verified against the |
| +// same Home issuer, consumer ID and origin the bridge is built with. It |
| +// touches no database, which is what lets newApp decide the schema |
| +// before anything migrates. |
| +func teamSettings(cfg *teammode.Config, home *connect.DecodedCredentials, origin string) (*teammode.Settings, error) { |
| + if cfg == nil { |
| + return nil, nil |
| + } |
| + if home == nil { |
| + return nil, errTeamConfig |
| + } |
| + return teammode.Verify(cfg, &teammode.Home{Issuer: home.Issuer, ConsumerID: home.ConsumerID}, "slides", origin) |
| +} |
| + |
| +// teamBootSchema is the schema newApp 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 |
| +// SLIDES_ALLOWED_ADDRESSES. |
| +func teamBootSchema(ctx context.Context, db *sql.DB, settings *teammode.Settings, base *migrate.Set) (*migrate.Set, error) { |
| + return teamState.BootSchema(ctx, db, settings, base, teamBoot(base)) |
| +} |
| + |
| +// teamRuntime is the process's roster runtime and the database the |
| +// Home-only users table lives in. |
| +type teamRuntime struct { |
| + *teammode.Runtime |
| + db *sql.DB |
| +} |
| + |
| +func (t *teamRuntime) issuer() string { return t.Bindings().Issuer } |
| + |
| +// configureTeam runs after the schema is applied and Home is configured, |
| +// before serving. Without settings 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(settings *teammode.Settings, home *connect.DecodedCredentials) error { |
| + if settings == nil { |
| + return nil |
| + } |
| + if a.home == nil || home == nil { |
| + return errTeamConfig |
| + } |
| + sealer, err := seal.New(home.DEK, homeNamespace) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + w := a.db.Writer() |
| + rt, err := teammode.Open(context.Background(), teammode.RuntimeConfig{Settings: settings, State: teamState, DB: w, Sealer: sealer, |
| + IssuerTables: teamIssuerTables, Transport: a.cfg.teamTransport, Clock: a.cfg.teamClock}) |
| + if err != nil { |
| + return err |
| + } |
| + a.team = &teamRuntime{Runtime: rt, db: w} |
| + return nil |
| +} |
diff --git a/internal/slides/team_config_test.go b/internal/slides/team_config_test.go| new file mode 100644 |
| index 0000000..9439445 |
| --- /dev/null |
| +++ b/internal/slides/team_config_test.go |
| @@ -0,0 +1,197 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +func teamKey(t *testing.T) *assertioncrypto.Keypair { |
| + t.Helper() |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return key |
| +} |
| + |
| +// bootTeam is New over d with cfg, closing the app it built. |
| +func bootTeam(t *testing.T, d *db.DB, cfg Config) error { |
| + t.Helper() |
| + _, a, err := New(d, cfg) |
| + if a != nil { |
| + a.Close() |
| + } |
| + return err |
| +} |
| + |
| +// The record is verified against bindings built only from configuration: |
| +// Home's issuer and consumer ID, the app, the team, the directory and |
| +// this instance's origin. A record signed for any other value of any one |
| +// of them refuses boot, before anything migrates. |
| +func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| + key := teamKey(t) |
| + cases := map[string]func(*roster.Bindings, *teammode.Config){ |
| + "issuer": func(b *roster.Bindings, _ *teammode.Config) { b.Issuer = "https://id.other.example" }, |
| + "consumer": func(b *roster.Bindings, _ *teammode.Config) { b.Consumer = "another-consumer" }, |
| + "app": func(b *roster.Bindings, _ *teammode.Config) { b.App = "sheets" }, |
| + "origin": func(b *roster.Bindings, _ *teammode.Config) { b.Audience = "https://other.example.com" }, |
| + "team": func(_ *roster.Bindings, c *teammode.Config) { c.TeamID = "TeamB" }, |
| + "directory": func(_ *roster.Bindings, c *teammode.Config) { c.DirectoryOrigin = "https://dir.other.example" }, |
| + } |
| + for name, change := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + b := teamTestBindings() |
| + change(&b, &teammode.Config{}) |
| + cfg, _, _ := teamConfigFor(t, b, key) |
| + change(&roster.Bindings{}, cfg.Team) |
| + d := testDB(t) |
| + if err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a record for another %s = %v, want ErrConfig", name, err) |
| + } |
| + if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| + t.Fatal("a refused record left a marker") |
| + } |
| + var tables int |
| + d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users'").Scan(&tables) |
| + if tables != 0 { |
| + t.Fatal("a refused record migrated the database") |
| + } |
| + }) |
| + } |
| + // And the right record boots. |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + if err := bootTeam(t, testDB(t), cfg); err != nil { |
| + t.Fatalf("the instance's own record: %v", err) |
| + } |
| +} |
| + |
| +// Five variables, all or none, and only beside Home. One present is a |
| +// configuration, and an invalid one: there is no falling back to the |
| +// allowlist. In team mode SLIDES_ALLOWED_ADDRESSES is optional even |
| +// outside development, and empty admits nobody locally. |
| +func TestTeamEnvIsAllOrNoneAndTheAllowlistBecomesOptional(t *testing.T) { |
| + key := teamKey(t) |
| + names := teammode.EnvNames("SLIDES") |
| + if names != [5]string{"SLIDES_TEAM_ID", "SLIDES_TEAM_DIRECTORY_ORIGIN", "SLIDES_TEAM_PROVISIONING_BASE64", "SLIDES_TEAM_OPERATOR_KEYS_BASE64", "SLIDES_TEAM_ROSTER_TOKEN"} { |
| + t.Fatalf("env names = %v", names) |
| + } |
| + for _, only := range names { |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + cfg.Team = teammode.ConfigFromLookup("SLIDES", func(n string) string { |
| + if n == only { |
| + return "x" |
| + } |
| + return "" |
| + }) |
| + if cfg.Team == nil { |
| + t.Fatalf("%s alone read as team mode off", only) |
| + } |
| + if err := bootTeam(t, testDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("%s alone = %v, want ErrConfig", only, err) |
| + } |
| + } |
| + if teammode.ConfigFromLookup("SLIDES", func(string) string { return "" }) != nil { |
| + t.Fatal("no variables read as team mode on") |
| + } |
| + |
| + // Team mode requires Home. |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + cfg.Home = nil |
| + if err := bootTeam(t, testDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("team mode without Home = %v, want ErrConfig", err) |
| + } |
| + |
| + // Production, no allowlist: boots in team mode, admits nobody locally. |
| + cfg, _, _ = teamConfigFor(t, teamTestBindings(), key) |
| + cfg.Env, cfg.InstanceKey, cfg.AllowedAddresses = EnvProduction, "a-real-instance-key", nil |
| + _, a, err := New(testDB(t), cfg) |
| + if err != nil { |
| + t.Fatalf("team mode with no allowlist in production: %v", err) |
| + } |
| + defer a.Close() |
| + if a.allowed.allows("anyone@example.com") { |
| + t.Fatal("an empty team-mode allowlist admits an address") |
| + } |
| + // Without team mode the same is still a refusal. |
| + cfg.Team = nil |
| + if err := bootTeam(t, testDB(t), cfg); err == nil { |
| + t.Fatal("no allowlist outside team mode booted") |
| + } |
| +} |
| + |
| +// The marker locks a database into team mode: once activated it refuses |
| +// to boot without team configuration, or with another binding, before |
| +// anything migrates; the same binding boots again. |
| +func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| + key := teamKey(t) |
| + d := testDB(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + if err := bootTeam(t, d, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + fp, activated, err := teamState.Required(context.Background(), d.Writer()) |
| + if err != nil || !activated || fp != teammode.Fingerprint(teamTestBindings()) { |
| + t.Fatalf("marker = %q %v %v", fp, activated, err) |
| + } |
| + |
| + off := cfg |
| + off.Team = nil |
| + if err := bootTeam(t, d, off); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database without team configuration = %v, want ErrConfig", err) |
| + } |
| + other := teamTestBindings() |
| + other.Team = "TeamB" |
| + rebound, _, _ := teamConfigFor(t, other, key) |
| + if err := bootTeam(t, d, rebound); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database with another binding = %v, want ErrConfig", err) |
| + } |
| + if err := bootTeam(t, d, cfg); err != nil { |
| + t.Fatalf("the same binding again: %v", err) |
| + } |
| + // The marker's triggers refuse a rewrite. |
| + if _, err := d.Writer().Exec("UPDATE slides_team_required SET bindings='x'"); err == nil { |
| + t.Fatal("the marker was rewritten") |
| + } |
| + if _, err := d.Writer().Exec("DELETE FROM slides_team_required"); err == nil { |
| + t.Fatal("the marker was deleted") |
| + } |
| +} |
| + |
| +// The census: a Home identity from another issuer, in either table that |
| +// holds one, refuses activation, and no marker is written. |
| +func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| + key := teamKey(t) |
| + for _, table := range []string{"home_identity_links", "slides_team_home_users"} { |
| + t.Run(table, func(t *testing.T) { |
| + d := testDB(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + // The team schema applied and never activated: what a boot |
| + // refused after migrating leaves behind. |
| + if _, err := migrate.Apply(context.Background(), d, teamBoot(migrate.Merge(BootSchema, homeSchema))); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec("INSERT INTO users(email,name,colour,created_at) VALUES(NULL,'','#000000',CURRENT_TIMESTAMP)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec("INSERT INTO "+table+"(issuer,subject,"+map[string]string{"home_identity_links": "person_id", "slides_team_home_users": "user_id"}[table]+") VALUES('https://id.other.example',?,1)", teamSubject('f')); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a %s row from another issuer = %v, want ErrConfig", table, err) |
| + } |
| + if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| + t.Fatal("a refused census left a marker") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +var _ = teammodetest.Team |
diff --git a/internal/slides/team_fixture_test.go b/internal/slides/team_fixture_test.go| new file mode 100644 |
| index 0000000..0ea7838 |
| --- /dev/null |
| +++ b/internal/slides/team_fixture_test.go |
| @@ -0,0 +1,256 @@ |
| +package slides |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// Team mode's fixture: Home configured exactly as homeFixture 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 ( |
| + teamTestIssuer = "https://home.example.com" |
| + teamTestConsumer = "slides-test" |
| +) |
| + |
| +// teamSubject is a well-formed person ref: "pr_" and 26 copies of c. |
| +func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| + |
| +// teamTestBindings are this instance's: Home's issuer and consumer ID as |
| +// homeFixture configures them, the test directory and team, Slides, and |
| +// the test origin. |
| +func teamTestBindings() roster.Bindings { |
| + b := teammodetest.Bindings("slides", teamTestConsumer, homeTestOrigin) |
| + b.Issuer = teamTestIssuer |
| + return b |
| +} |
| + |
| +type teamFixture struct { |
| + t *testing.T |
| + mux *http.ServeMux |
| + a *app |
| + d *db.DB |
| + key *assertioncrypto.Keypair |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| + cfg *teammode.Config |
| + jar map[string]*http.Cookie |
| +} |
| + |
| +// teamConfigFor builds a Config for a team-mode instance on bindings b, |
| +// over d: Home as homeFixture has it, the record signed for b, and the |
| +// test directory and clock. allowed is SLIDES_ALLOWED_ADDRESSES, which in |
| +// team mode only admits local sign-in; none is Alta's shape. |
| +func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, allowed ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) { |
| + t.Helper() |
| + tcfg, dir := teammodetest.Provision(t, b) |
| + clock := teammodetest.NewClock() |
| + raw, _ := json.Marshal(map[string]string{"test": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| + cfg := Config{Mailer: &homeTestMail{}, Env: EnvDevelopment, Origin: homeTestOrigin, Logger: quietLogger(), AllowedAddresses: allowed, |
| + Home: &connect.Credentials{Issuer: teamTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: base64.StdEncoding.EncodeToString(raw), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{8}, 32))}, |
| + Team: tcfg, teamTransport: dir, teamClock: clock} |
| + return cfg, dir, clock |
| +} |
| + |
| +func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { |
| + t.Helper() |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + d := testDB(t) |
| + cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, allowed...) |
| + mux, a, err := New(d, cfg) |
| + if err != nil { |
| + t.Fatalf("New in team mode: %v", err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + return &teamFixture{t: t, mux: mux, a: a, d: d, key: key, dir: dir, clock: clock, cfg: cfg.Team, jar: map[string]*http.Cookie{}} |
| +} |
| + |
| +// do runs one request with the jar's cookies and keeps what it sets. |
| +// origin, when set, is sent as Origin (a same-origin form POST). |
| +func (f *teamFixture) do(method, path, body, contentType, origin string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body)) |
| + if origin != "" { |
| + r.Header.Set("Origin", origin) |
| + r.Header.Set("Sec-Fetch-Site", "same-origin") |
| + } |
| + if contentType != "" { |
| + r.Header.Set("Content-Type", contentType) |
| + } |
| + r.Header.Set("Accept", "text/html") |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + f.mux.ServeHTTP(w, r) |
| + for _, c := range w.Result().Cookies() { |
| + if c.MaxAge < 0 { |
| + delete(f.jar, c.Name) |
| + } else { |
| + f.jar[c.Name] = c |
| + } |
| + } |
| + return w |
| +} |
| + |
| +func (f *teamFixture) get(path string) *httptest.ResponseRecorder { |
| + return f.do("GET", path, "", "", "") |
| +} |
| + |
| +func (f *teamFixture) post(path string, form url.Values) *httptest.ResponseRecorder { |
| + return f.do("POST", path, form.Encode(), "application/x-www-form-urlencoded", homeTestOrigin) |
| +} |
| + |
| +// signInHome runs a full Home exchange for subject — start, a signed |
| +// assertion, callback, finish — keeping whatever is already in the jar |
| +// (a live local session, say), and returns the finish response. |
| +func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + start := f.get(handoff.StartPath) |
| + if start.Code != http.StatusSeeOther { |
| + f.t.Fatalf("start = %d %s", start.Code, start.Body.String()) |
| + } |
| + target, err := url.Parse(start.Header().Get("Location")) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + id, _ := assertion.RandomID() |
| + now := time.Now().Unix() |
| + token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: teamTestIssuer, Audience: homeTestOrigin, Subject: subject, KeyID: "test", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + callback := f.do("POST", handoff.CallbackPath, url.Values{"assertion": {token}}.Encode(), "application/x-www-form-urlencoded", teamTestIssuer) |
| + if callback.Code != http.StatusSeeOther { |
| + f.t.Fatalf("callback = %d %s", callback.Code, callback.Body.String()) |
| + } |
| + return f.get(handoff.FinishPath) |
| +} |
| + |
| +// freshHomeSignIn is signInHome from an empty jar. |
| +func (f *teamFixture) freshHomeSignIn(subject string) *httptest.ResponseRecorder { |
| + f.jar = map[string]*http.Cookie{} |
| + return f.signInHome(subject) |
| +} |
| + |
| +// member adds subject to the roster with role, refreshes, and signs them |
| +// in with Home from an empty jar, failing unless they got a session. |
| +func (f *teamFixture) member(subject, role string) User { |
| + f.t.Helper() |
| + f.dir.Set(subject, role) |
| + f.refreshed() |
| + finish := f.freshHomeSignIn(subject) |
| + if finish.Code != http.StatusSeeOther { |
| + f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) |
| + } |
| + return f.userFor(subject) |
| +} |
| + |
| +// userFor is the user a Home subject signs in as. |
| +func (f *teamFixture) userFor(subject string) User { |
| + f.t.Helper() |
| + p, err := f.a.home.Resolve(context.Background(), subject) |
| + if err != nil { |
| + f.t.Fatalf("resolve %s: %v", subject, err) |
| + } |
| + var u User |
| + if err := f.d.G.Take(&u, p.ID).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return u |
| +} |
| + |
| +// localSession puts a local (magic link) session for address in the jar, |
| +// as a sign-in the allowlist admitted would. |
| +func (f *teamFixture) localSession(address string) { |
| + f.t.Helper() |
| + w := httptest.NewRecorder() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + if err := f.a.homeSessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + f.jar[c.Name] = c |
| + } |
| +} |
| + |
| +// refreshed steps the roster clock past the refresh point and waits for |
| +// the refresh, so the next request sees the directory's current list. |
| +func (f *teamFixture) refreshed() { |
| + f.t.Helper() |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + if err := f.a.team.Refresh(context.Background()); err != nil { |
| + f.t.Fatalf("roster refresh: %v", err) |
| + } |
| +} |
| + |
| +// expired takes the directory down and steps past the lease: Unknown. |
| +func (f *teamFixture) expired() { |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| +} |
| + |
| +// deck makes a deck owned by u directly (no request), on rung, with its |
| +// opening ops, and returns it. |
| +func (f *teamFixture) deck(u User, title, rung string) Deck { |
| + f.t.Helper() |
| + ctx := context.Background() |
| + d, err := f.a.createDeckRow(ctx, u, title, defaultTheme, nil) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + ops, err := openingOps(title, defaultTheme) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := f.a.editDeck(ctx, &d, actorFor(u), ops, nil, nil); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if rung != rungPrivate { |
| + if err := f.d.G.Model(&Deck{}).Where("id = ?", d.ID).Update("rung", rung).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + d.Rung = rung |
| + } |
| + return d |
| +} |
| + |
| +// grant names u on d, given by somebody else. |
| +func (f *teamFixture) grant(d Deck, u User, by User) { |
| + f.t.Helper() |
| + if err := f.d.G.Create(&DeckGrant{DeckID: d.ID, UserID: u.ID, Actor: actorFor(by), CreatedAt: time.Now().UTC()}).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| +} |
| + |
| +// localUser makes a users row for address, as a first local sign-in does. |
| +func (f *teamFixture) localUser(address string) User { |
| + f.t.Helper() |
| + u, _, err := ensureUser(context.Background(), f.d.G, address) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return u |
| +} |
diff --git a/internal/slides/team_guard.go b/internal/slides/team_guard.go| new file mode 100644 |
| index 0000000..e3245f7 |
| --- /dev/null |
| +++ b/internal/slides/team_guard.go |
| @@ -0,0 +1,135 @@ |
| +package slides |
| + |
| +// Team mode's write guard: the request's standing checked again inside |
| +// the transaction that commits a write, before and after it |
| +// (teammode.Guard; Home implementation/teammode-package.md §3, |
| +// invariant 13, and Fable's deviation 7 on oficina/sheets #52). The |
| +// handler's deckFor or ownedDeckFor 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 the request's user carries, 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 writeGuard 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" |
| +) |
| + |
| +// writeGuard runs one write inside that write's own transaction, and may |
| +// refuse it, before the write or after it. A refusal rolls the |
| +// transaction back. Nil is no guard. |
| +type writeGuard func(write func() error) error |
| + |
| +// run is write under g, or write alone when there is no guard. |
| +func (g writeGuard) run(write func() error) error { |
| + if g == nil { |
| + return write() |
| + } |
| + return g(write) |
| +} |
| + |
| +// teamGuard is teammode.Guard. A variable only so a test can let the |
| +// lease run out between a write and its commit on every write route. |
| +var teamGuard = teammode.Guard |
| + |
| +// guardFor is the guard for u under authorize, reading u's own Access: the |
| +// one the handler's deckFor latched. A user with none reads Unknown. |
| +func (a *app) guardFor(ctx context.Context, u User, authorize func(roster.State) error) writeGuard { |
| + if a.team == nil { |
| + return nil |
| + } |
| + gctx := teammode.WithAccess(ctx, u.team.access()) |
| + return func(write func() error) error { return teamGuard(gctx, authorize, write) } |
| +} |
| + |
| +// deckGuard is the guard for u writing to d, a write any reader of d may |
| +// make (the document, a presentation, an upload). When a grant names u on |
| +// d, the write does not rest on standing, and Unknown or NotMember may |
| +// still make it (the rule teammode leaves to the app). Otherwise d was |
| +// reached through the team rung — u's own deck, or one on the team rung |
| +// — and that holds only while the roster says Member. |
| +// |
| +// The grant is read here, before any transaction, never under the |
| +// writer. |
| +func (a *app) deckGuard(ctx context.Context, u User, d Deck) writeGuard { |
| + if a.team == nil { |
| + return nil |
| + } |
| + if a.grantedTo(ctx, u, d) { |
| + return a.guardFor(ctx, u, func(roster.State) error { return nil }) |
| + } |
| + return a.guardFor(ctx, u, teammode.RequireMember) |
| +} |
| + |
| +// memberGuard is the guard for a write that rests on standing alone: |
| +// making a deck, and everything an owner does (settings, delete, share |
| +// links), since ownership in team mode is the team rung's too — a deck's |
| +// owner owns it only while Member, and a roster owner's hold on an |
| +// orphaned deck is the roster's (team_owner.go). |
| +func (a *app) memberGuard(ctx context.Context, u User) writeGuard { |
| + return a.guardFor(ctx, u, teammode.RequireMember) |
| +} |
| + |
| +// grantedTo reports whether a grant names u on d. A read failure is "no": |
| +// the write then needs standing, which is the stricter answer. |
| +func (a *app) grantedTo(ctx context.Context, u User, d Deck) bool { |
| + var n int64 |
| + if err := a.db.G.WithContext(ctx).Model(&DeckGrant{}). |
| + Where("deck_id = ? AND user_id = ?", d.ID, u.ID).Count(&n).Error; err != nil { |
| + return false |
| + } |
| + return n > 0 |
| +} |
| + |
| +// 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(ctx context.Context, g writeGuard, write func(db *gorm.DB) error) error { |
| + if g == nil { |
| + return write(a.db.G.WithContext(ctx)) |
| + } |
| + return a.db.G.WithContext(ctx).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.teamUnavailable(w, r) |
| + case errors.Is(err, teammode.ErrNotMember): |
| + a.notFound(w, r) |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// guardRefusedJSON is guardRefused for the drive API. |
| +func guardRefusedJSON(w http.ResponseWriter, err error) bool { |
| + switch { |
| + case errors.Is(err, teammode.ErrUnavailable): |
| + teamUnavailableJSON(w) |
| + case errors.Is(err, teammode.ErrNotMember): |
| + apiFail(w, http.StatusNotFound, errNotFound) |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
diff --git a/internal/slides/team_guard_test.go b/internal/slides/team_guard_test.go| new file mode 100644 |
| index 0000000..834bdd2 |
| --- /dev/null |
| +++ b/internal/slides/team_guard_test.go |
| @@ -0,0 +1,292 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "image/color" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/blobs" |
| +) |
| + |
| +// lapsingGuard makes every team-mode write's lease run out between the |
| +// write and its commit: the directory goes down and the clock passes the |
| +// lease inside the transaction, so the guard's after-check reads Unknown. |
| +func lapsingGuard(t *testing.T, f *teamFixture) { |
| + t.Helper() |
| + teamGuard = lapsing(f) |
| + t.Cleanup(func() { teamGuard = teammode.Guard }) |
| +} |
| + |
| +// lapsing is the guard lapsingGuard installs. |
| +func lapsing(f *teamFixture) func(context.Context, func(roster.State) error, func() error) error { |
| + return func(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + return teammode.Guard(ctx, authorize, func() error { |
| + err := write() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return err |
| + }) |
| + } |
| +} |
| + |
| +// renewed brings the directory back and refreshes, so the next request |
| +// starts on a fresh Member lease. |
| +func (f *teamFixture) renewed() { |
| + f.t.Helper() |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| +} |
| + |
| +// update is a valid Yjs update for d made by the core itself: ops on a |
| +// freshly replayed handle, as the editor's would be. |
| +func (f *teamFixture) update(d Deck, title string) []byte { |
| + f.t.Helper() |
| + ctx := context.Background() |
| + var fresh Deck |
| + if err := f.d.G.Take(&fresh, d.ID).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + h, _, err := f.a.openDeck(ctx, fresh) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + defer h.Close(ctx) |
| + ops, err := opsJSON([]op{{"op": "set_meta", "title": title, "theme": defaultTheme}}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + b, err := h.Ops(ctx, ops) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// agent mints a live agent for u and returns its token. |
| +func (f *teamFixture) agent(u User) string { |
| + f.t.Helper() |
| + token, err := newAgentToken() |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := f.d.G.Create(&Agent{Name: "claude", OperatorID: u.ID, TokenHash: hashAgentToken(token), CreatedAt: time.Now().UTC()}).Error; err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return token |
| +} |
| + |
| +func (f *teamFixture) api(token, method, path, body string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body)) |
| + r.Header.Set("Authorization", "Bearer "+token) |
| + if body != "" { |
| + r.Header.Set("Content-Type", "application/json") |
| + } |
| + w := httptest.NewRecorder() |
| + f.mux.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +// snapshot is what a refused write must leave exactly as it was. |
| +type teamSnapshot struct { |
| + decks, updates, links, revoked, presentations int64 |
| + uploads, uploadsLanded, uploadsSpent, assets int64 |
| + title string |
| + seq int64 |
| +} |
| + |
| +func (f *teamFixture) snapshot(d Deck) teamSnapshot { |
| + f.t.Helper() |
| + var s teamSnapshot |
| + g := f.d.G |
| + g.Model(&Deck{}).Count(&s.decks) |
| + g.Model(&DeckUpdate{}).Count(&s.updates) |
| + g.Model(&ShareLink{}).Count(&s.links) |
| + g.Model(&ShareLink{}).Where("revoked_at IS NOT NULL").Count(&s.revoked) |
| + g.Model(&Presentation{}).Count(&s.presentations) |
| + g.Model(&AssetUpload{}).Count(&s.uploads) |
| + g.Model(&AssetUpload{}).Where("object_key != ''").Count(&s.uploadsLanded) |
| + g.Model(&AssetUpload{}).Where("consumed_at IS NOT NULL").Count(&s.uploadsSpent) |
| + g.Model(&DeckAsset{}).Count(&s.assets) |
| + var row Deck |
| + if err := g.Take(&row, d.ID).Error; err != nil { |
| + f.t.Fatalf("deck %d gone: %v", d.ID, err) |
| + } |
| + s.title, s.seq = row.Title, row.Seq |
| + return s |
| +} |
| + |
| +// Every write route, with the lease lapsing between the write and its |
| +// commit: each answers the retryable 503, and nothing any of them wrote |
| +// survived (Fable's #53 required test 2, for Slides: the database is |
| +// read back, not just the status). |
| +func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| + f := newTeamFixture(t) |
| + store, err := blobs.Dir(t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.cfg.Blobs = store |
| + u := f.member(teamSubject('a'), "member") |
| + plan := f.deck(u, "Team plan", rungTeam) |
| + token := f.agent(u) |
| + link := ShareLink{DeckID: plan.ID, TokenHash: "h", Actor: actorFor(u), CreatedAt: time.Now().UTC()} |
| + if err := f.d.G.Create(&link).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + lapsingGuard(t, f) |
| + |
| + // The picture the upload routes carry, and its staging: signed (and |
| + // for registration also landed) under the real guard, so only the |
| + // route under test meets the lapse. |
| + png := pngBytes(t, 4, 4, color.Black) |
| + sum := sha256.Sum256(png) |
| + signBody := fmt.Sprintf(`{"name":"a.png","size":%d,"type":"image/png","hash":%q}`, len(png), hex.EncodeToString(sum[:])) |
| + var staged struct { |
| + Ref string `json:"ref"` |
| + URL string `json:"url"` |
| + } |
| + stage := func(land bool) { |
| + teamGuard = teammode.Guard |
| + defer func() { teamGuard = lapsing(f) }() |
| + f.renewed() |
| + got := f.do("POST", deckPath(plan)+"/uploads", signBody, "application/json", homeTestOrigin) |
| + if got.Code != 200 || json.Unmarshal(got.Body.Bytes(), &staged) != nil { |
| + t.Fatalf("staging an upload = %d %s", got.Code, got.Body.String()) |
| + } |
| + if land { |
| + if put := f.do("PUT", staged.URL, string(png), "image/png", homeTestOrigin); put.Code != http.StatusNoContent { |
| + t.Fatalf("landing an upload = %d %s", put.Code, put.Body.String()) |
| + } |
| + } |
| + } |
| + |
| + routes := []struct { |
| + name string |
| + setup func() |
| + do func() *httptest.ResponseRecorder |
| + }{ |
| + {"create", nil, func() *httptest.ResponseRecorder { |
| + return f.post("/decks", url.Values{"title": {"New"}, "theme": {defaultTheme}}) |
| + }}, |
| + {"live update", nil, func() *httptest.ResponseRecorder { |
| + return f.do("POST", deckPath(plan)+"/updates", string(f.update(plan, "Typed")), "application/octet-stream", homeTestOrigin) |
| + }}, |
| + {"settings", nil, func() *httptest.ResponseRecorder { |
| + return f.post(deckPath(plan)+"/settings", url.Values{"title": {"Renamed"}, "theme": {defaultTheme}, "rung": {rungPrivate}}) |
| + }}, |
| + {"delete", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/delete", nil) }}, |
| + {"share link", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/share", nil) }}, |
| + {"share revoke", nil, func() *httptest.ResponseRecorder { |
| + return f.post(fmt.Sprintf("%s/share/%d/revoke", deckPath(plan), link.ID), nil) |
| + }}, |
| + {"present", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/present", nil) }}, |
| + {"upload", nil, func() *httptest.ResponseRecorder { |
| + return f.do("POST", deckPath(plan)+"/uploads", signBody, "application/json", homeTestOrigin) |
| + }}, |
| + {"upload put", func() { stage(false) }, func() *httptest.ResponseRecorder { |
| + return f.do("PUT", staged.URL, string(png), "image/png", homeTestOrigin) |
| + }}, |
| + {"asset register", func() { stage(true) }, func() *httptest.ResponseRecorder { |
| + return f.do("POST", deckPath(plan)+"/assets", fmt.Sprintf(`{"ref":%q,"name":"a.png","width":4,"height":4,"alt":"a dot"}`, staged.Ref), "application/json", homeTestOrigin) |
| + }}, |
| + {"api create", nil, func() *httptest.ResponseRecorder { |
| + return f.api(token, "POST", apiPrefix+"/decks", `{"title":"By agent"}`) |
| + }}, |
| + {"api ops", nil, func() *httptest.ResponseRecorder { |
| + return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/ops", `{"ops":[{"op":"set_meta","title":"Agent title"}]}`) |
| + }}, |
| + {"api present", nil, func() *httptest.ResponseRecorder { |
| + return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/present", "") |
| + }}, |
| + } |
| + for _, route := range routes { |
| + if route.setup != nil { |
| + route.setup() |
| + } |
| + f.renewed() |
| + before := f.snapshot(plan) |
| + got := route.do() |
| + if got.Code != http.StatusServiceUnavailable { |
| + t.Errorf("%s with a lapsing lease = %d %s, want 503", route.name, got.Code, got.Body.String()) |
| + } |
| + if after := f.snapshot(plan); after != before { |
| + t.Errorf("%s: something a refused write made survived: %+v -> %+v", route.name, before, after) |
| + } |
| + } |
| +} |
| + |
| +// The rule teammode leaves to the app: a write a grant reaches does not |
| +// rest on standing, so it is made under Unknown; one that rests on the |
| +// team rung is the retryable 503. |
| +func TestTeamGrantStillWritesUnderUnknownStanding(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + shared := f.deck(colleague, "Shared", rungPrivate) |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + u := f.member(teamSubject('a'), "member") |
| + f.grant(shared, u, colleague) |
| + sharedUpdate, planUpdate := f.update(shared, "Typed"), f.update(plan, "Typed") |
| + f.expired() |
| + if got := f.do("POST", deckPath(shared)+"/updates", string(sharedUpdate), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent { |
| + t.Fatalf("granted deck write under Unknown = %d %s", got.Code, got.Body.String()) |
| + } |
| + if got := f.do("POST", deckPath(plan)+"/updates", string(planUpdate), "application/octet-stream", homeTestOrigin); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("team deck write under Unknown = %d, want 503", got.Code) |
| + } |
| + // And the grant carries a write through a lapse too: nothing about it |
| + // rested on the lease. |
| + f.renewed() |
| + lapsingGuard(t, f) |
| + if got := f.do("POST", deckPath(shared)+"/updates", string(f.update(shared, "Again")), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent { |
| + t.Fatalf("granted deck write through a lapse = %d", got.Code) |
| + } |
| +} |
| + |
| +// A standing already Unknown refuses before anything is written, and a |
| +// user with no Access at all reads Unknown. |
| +func TestTeamGuardRefusesBeforeTheWrite(t *testing.T) { |
| + f := newTeamFixture(t) |
| + u := f.member(teamSubject('a'), "member") |
| + check := func(name string) { |
| + t.Helper() |
| + called := false |
| + err := f.a.memberGuard(context.Background(), u).run(func() error { called = true; return nil }) |
| + if !errors.Is(err, teammode.ErrUnavailable) || called { |
| + t.Fatalf("%s: guard = %v, write called %v", name, err, called) |
| + } |
| + } |
| + u.team = nil |
| + check("no access") |
| + f.expired() |
| + u.team = &teamAccess{Access: f.a.team.Access(context.Background(), teamSubject('a'))} |
| + check("unknown") |
| +} |
| + |
| +// Outside team mode there is no guard, and every write takes its old path. |
| +func TestNoGuardOutsideTeamMode(t *testing.T) { |
| + _, a, u := homeFixture(t) |
| + if a.memberGuard(context.Background(), u) != nil || a.deckGuard(context.Background(), u, Deck{ID: 1}) != nil { |
| + t.Fatal("a guard outside team mode") |
| + } |
| + if a.team != nil || a.teamOn != nil { |
| + t.Fatal("team mode on without configuration") |
| + } |
| + if !a.member(u) || a.teamPartial(u) || a.teamUnknown(u) { |
| + t.Fatal("team answers outside team mode") |
| + } |
| + if a.presignTTLFor(u) != presignTTL { |
| + t.Fatal("presign TTL changed outside team mode") |
| + } |
| +} |
diff --git a/internal/slides/team_home_only.go b/internal/slides/team_home_only.go| new file mode 100644 |
| index 0000000..8f235c6 |
| --- /dev/null |
| +++ b/internal/slides/team_home_only.go |
| @@ -0,0 +1,82 @@ |
| +package slides |
| + |
| +// Home sign-in for a roster member with no account here: connect's two |
| +// team-mode hooks over Slides' users 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 initHome gives |
| +// connect these, and connect's own completion does the rest (its cookie |
| +// checks, the same-person rule, the link flow). |
| +// |
| +// The user 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/slides/internal/slides/teamstate" |
| +) |
| + |
| +// teamHomeOnly is connect's HomeOnly: the addressless user 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.HomeUser(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 user: an addressless |
| +// user 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. |
| +// |
| +// A user made here gets the sample deck, as a first local sign-in does |
| +// (currentUser): it is their first sign-in, and an empty list would be a |
| +// worse welcome than the one everybody else gets. |
| +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, created, err := teamstate.EnsureHomeUser(ctx, d, issuer, subject, colourFor(subject)) |
| + switch { |
| + case err == 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 |
| + default: |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if created { |
| + var u User |
| + if err := a.db.G.WithContext(ctx).Take(&u, id).Error; err != nil { |
| + a.logger.Error("slides: read a new Home-only user to seed", "user", id, "err", err) |
| + } else { |
| + u.team = &teamAccess{Access: a.team.Access(ctx, subject)} |
| + a.seedSampleDeckFor(ctx, u) |
| + } |
| + } |
| + return connect.Person{ID: id}, nil |
| + } |
| +} |
diff --git a/internal/slides/team_owner.go b/internal/slides/team_owner.go| new file mode 100644 |
| index 0000000..0e599ba |
| --- /dev/null |
| +++ b/internal/slides/team_owner.go |
| @@ -0,0 +1,90 @@ |
| +package slides |
| + |
| +// Team mode's ownership, and the roster-owner rule for orphaned decks — |
| +// RULED by Paul, 2026-10-30, on oficina/slides #33 ("share only, no |
| +// delete for now (may change his mind later)"; "team-visible decks |
| +// only"), after his Sheets ruling of 2026-10-28 on oficina/sheets #52. |
| +// |
| +// A deck's owner is decks.owner_id. In team mode that is the team rung's, |
| +// as Docs' owner_id rule is: the owner owns the deck only while the |
| +// roster says Member. Removing a deck's owner from the team therefore |
| +// leaves a team-rung deck the team can still read, edit and present, and |
| +// nobody can share. The rule: on an ORPHAN — a deck on the team rung |
| +// whose owner the roster definitely says is gone (NotMember, which |
| +// includes a local account with no Home identity, or an owner row that |
| +// no longer exists) — a roster owner may |
| +// |
| +// - share it: the share page and its links (mayShareDeck); |
| +// - change its title and theme (mayRetitleDeck); |
| +// |
| +// and may NOT |
| +// |
| +// - delete it (mayDeleteDeck), nor |
| +// - change its rung (mayChangeRung): making it private hides it from |
| +// everybody, the roster owner included, which Paul treats as a |
| +// soft-delete. |
| +// |
| +// Only the team rung: a departed member's private deck is no orphan, |
| +// even to a roster owner who holds a grant to read it. An owner whose |
| +// standing cannot be read right now is not "gone". Nothing is written: |
| +// the moment the departed owner is re-added, the deck has a live owner |
| +// again and the rule stops applying. |
| +// |
| +// Each power is its own predicate, so widening one later (Paul may |
| +// rule delete back in) is one line in one place. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// ownsDeck reports whether u is d's owner: d.OwnerID, while Member in |
| +// team mode. Outside team mode it is exactly d.OwnerID == u.ID. |
| +func (a *app) ownsDeck(u User, d Deck) bool { |
| + return d.OwnerID == u.ID && a.member(u) |
| +} |
| + |
| +// mayShareDeck: the share page, minting and revoking share links. The |
| +// owner, or a roster owner on an orphan. |
| +func (a *app) mayShareDeck(ctx context.Context, u User, d Deck) bool { |
| + return a.ownsDeck(u, d) || a.orphanedForRosterOwner(ctx, u, d) |
| +} |
| + |
| +// mayRetitleDeck: the settings page and its title and theme. The owner, |
| +// or a roster owner on an orphan. |
| +func (a *app) mayRetitleDeck(ctx context.Context, u User, d Deck) bool { |
| + return a.ownsDeck(u, d) || a.orphanedForRosterOwner(ctx, u, d) |
| +} |
| + |
| +// mayChangeRung: who can open the deck. The owner alone. |
| +func (a *app) mayChangeRung(_ context.Context, u User, d Deck) bool { |
| + return a.ownsDeck(u, d) |
| +} |
| + |
| +// mayDeleteDeck: the delete page and the delete. The owner alone. |
| +func (a *app) mayDeleteDeck(_ context.Context, u User, d Deck) bool { |
| + return a.ownsDeck(u, d) |
| +} |
| + |
| +// orphanedForRosterOwner reports whether u is a roster owner, now, and d |
| +// is an orphan: on the team rung, its owner definitely off the team. It |
| +// asks the roster about the owner, never under the SQLite writer: no |
| +// owner check runs inside a transaction. Always false outside team mode. |
| +func (a *app) orphanedForRosterOwner(ctx context.Context, u User, d Deck) bool { |
| + if a.team == nil || d.Rung != rungTeam || !u.team.rosterOwner() || d.OwnerID == u.ID { |
| + return false |
| + } |
| + var owner User |
| + err := a.db.G.WithContext(ctx).Take(&owner, d.OwnerID).Error |
| + switch { |
| + case errors.Is(err, gorm.ErrRecordNotFound): |
| + return true // nobody owns it at all: the one repair path there is |
| + case err != nil: |
| + return false // cannot tell is not orphaned |
| + } |
| + return a.withStanding(ctx, owner).team.state() == roster.NotMember |
| +} |
diff --git a/internal/slides/team_present.go b/internal/slides/team_present.go| new file mode 100644 |
| index 0000000..ef6fdf6 |
| --- /dev/null |
| +++ b/internal/slides/team_present.go |
| @@ -0,0 +1,131 @@ |
| +package slides |
| + |
| +// Team mode and live presentations. A presentation is a capability like a |
| +// share link — the session sqid reaches the projector, the remote token |
| +// drives it, and none of the screens has a session — but unlike a share |
| +// link it is a person's, not the deck's: it reads the deck out on the |
| +// authority of whoever started it, which is why offboarding has always |
| +// ended a removed person's talks (auth.go's offboard). In team mode the |
| +// roster replaces the allowlist, so every request a presentation answers |
| +// and every delivery its streams make re-decide whether the presenter |
| +// still reaches the deck: |
| +// |
| +// - they do: the talk goes on, and a stream that rests on their Member |
| +// lease re-decides when it runs out; |
| +// - they definitely do not (the roster removed them, and no grant names |
| +// them on the deck): the talk is ended, as offboard ends it, and |
| +// every screen on it is told; |
| +// - their standing cannot be read now: a retryable 503, and the talk is |
| +// left running for when it can. |
| + |
| +import ( |
| + "context" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + |
| + "amadan.net/oficina/slides/internal/slides/present" |
| +) |
| + |
| +// presenterReach is what a presentation's presenter reaches now. |
| +type presenterReach int |
| + |
| +const ( |
| + presenterReaches presenterReach = iota |
| + presenterUnknown |
| + presenterGone |
| +) |
| + |
| +// presenterOf is the user a presentation's actor stands for: the person, |
| +// or an agent's operator. ok is false when the actor names nobody here. |
| +func (a *app) presenterOf(ctx context.Context, actor string) (User, bool) { |
| + kind, raw, found := strings.Cut(actor, ":") |
| + if !found { |
| + return User{}, false |
| + } |
| + id, err := strconv.ParseInt(raw, 10, 64) |
| + if err != nil { |
| + return User{}, false |
| + } |
| + if kind == "agent" { |
| + var ag Agent |
| + if err := a.db.G.WithContext(ctx).Take(&ag, id).Error; err != nil { |
| + return User{}, false |
| + } |
| + id = ag.OperatorID |
| + } else if kind != "person" { |
| + return User{}, false |
| + } |
| + var u User |
| + if err := a.db.G.WithContext(ctx).Take(&u, id).Error; err != nil { |
| + return User{}, false |
| + } |
| + return u, true |
| +} |
| + |
| +// presenterStanding decides p's presenter's reach to p's deck now, and |
| +// how long a Member answer may stand (0 when it does not rest on a |
| +// lease). Team mode only; it asks the roster, so never under the writer. |
| +func (a *app) presenterStanding(ctx context.Context, p Presentation) (presenterReach, time.Duration) { |
| + u, ok := a.presenterOf(ctx, p.Actor) |
| + if !ok { |
| + return presenterGone, 0 |
| + } |
| + u = a.withStanding(ctx, u) |
| + var n int64 |
| + if err := a.visibleDecks(ctx, u).Where("decks.id = ?", p.DeckID).Count(&n).Error; err != nil { |
| + return presenterUnknown, 0 |
| + } |
| + // Asked after the reach, of the same Access (teamStreamAccess says |
| + // why): without a Member lease only a grant holds. |
| + state := u.team.state() |
| + if n > 0 && state != roster.Member && !a.grantedTo(ctx, u, Deck{ID: p.DeckID}) { |
| + n = 0 |
| + } |
| + switch { |
| + case n == 0 && state == roster.Unknown: |
| + return presenterUnknown, 0 |
| + case n == 0: |
| + return presenterGone, 0 |
| + case state != roster.Member: |
| + return presenterReaches, 0 |
| + } |
| + renew := u.team.Remaining() |
| + if renew <= 0 { |
| + renew = time.Second |
| + } |
| + return presenterReaches, renew |
| +} |
| + |
| +// endPresentation ends p because its presenter no longer reaches the |
| +// deck, and tells every screen watching it, as offboard's |
| +// endPresentationsOf does. Best effort and logged: the request that found |
| +// out answers 410 either way. |
| +func (a *app) endPresentation(ctx context.Context, p Presentation) { |
| + res := a.db.G.WithContext(ctx).Model(&Presentation{}). |
| + Where("id = ? AND ended_at IS NULL", p.ID).Update("ended_at", time.Now().UTC()) |
| + if res.Error != nil { |
| + a.logger.Error("slides: end a presentation whose presenter left the team", "session", p.Sqid, "err", res.Error) |
| + return |
| + } |
| + a.logger.Warn("slides: a presenter no longer reaches the deck; ending the presentation", "session", p.Sqid, "actor", p.Actor) |
| + if res.RowsAffected > 0 { |
| + a.hub.Publish(p.Sqid, present.Event{Ended: true}) |
| + } |
| +} |
| + |
| +// presentationStands is presenterStanding with its consequence: a talk |
| +// whose presenter is gone is ended here. Outside team mode it always |
| +// stands, with nothing to renew. |
| +func (a *app) presentationStands(ctx context.Context, p Presentation) (presenterReach, time.Duration) { |
| + if a.team == nil { |
| + return presenterReaches, 0 |
| + } |
| + reach, renew := a.presenterStanding(ctx, p) |
| + if reach == presenterGone { |
| + a.endPresentation(ctx, p) |
| + } |
| + return reach, renew |
| +} |
diff --git a/internal/slides/team_review_test.go b/internal/slides/team_review_test.go| new file mode 100644 |
| index 0000000..f630ec9 |
| --- /dev/null |
| +++ b/internal/slides/team_review_test.go |
| @@ -0,0 +1,348 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/dashboard" |
| +) |
| + |
| +// probe answers GET /api/team through the whole router, unauthenticated. |
| +func probe(t *testing.T, mux *http.ServeMux) (*httptest.ResponseRecorder, map[string]any) { |
| + t.Helper() |
| + w := httptest.NewRecorder() |
| + mux.ServeHTTP(w, httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil)) |
| + var body map[string]any |
| + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { |
| + t.Fatalf("probe body %q: %v", w.Body.String(), err) |
| + } |
| + return w, body |
| +} |
| + |
| +// Team mode off: the probe says only that. |
| +func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| + mux, _, _ := homeFixture(t) |
| + w, body := probe(t, mux) |
| + if w.Code != 200 || w.Header().Get("Cache-Control") != "no-store" || len(body) != 1 || body["team_mode"] != false { |
| + t.Fatalf("probe off = %d %v %v", w.Code, w.Header(), body) |
| + } |
| +} |
| + |
| +// Team mode on: unknown before any roster, ok once one is held, stale |
| +// once it ages out — the same body whoever asks, and no account data. |
| +func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.dir.SetDown(true) |
| + _, body := probe(t, f.mux) |
| + if body["roster"] != "unknown" || body["team_mode"] != true || body["consumer"] != teamTestConsumer || len(body) != 3 { |
| + t.Fatalf("probe before any roster = %v", body) |
| + } |
| + f.dir.SetDown(false) |
| + f.clock.Step(10 * time.Second) |
| + f.dir.Set(teamSubject('a'), "member") |
| + if _, body = probe(t, f.mux); body["roster"] != "ok" { |
| + t.Fatalf("probe with a roster = %v", body) |
| + } |
| + f.member(teamSubject('a'), "member") |
| + _, signedOut := probe(t, f.mux) |
| + w := f.do("GET", "/api/team", "", "", "") |
| + if w.Body.String() == "" || !strings.Contains(w.Body.String(), `"roster":"ok"`) || strings.Contains(w.Body.String(), teamSubject('a')) || strings.Contains(w.Body.String(), "TeamA") { |
| + t.Fatalf("probe signed in = %s", w.Body.String()) |
| + } |
| + if len(signedOut) != 3 { |
| + t.Fatalf("probe body = %v", signedOut) |
| + } |
| + f.expired() |
| + if _, body = probe(t, f.mux); body["roster"] != "stale" { |
| + t.Fatalf("probe aged out = %v", body) |
| + } |
| +} |
| + |
| +// Paul's ruling on #33 (2026-10-30): on an orphan — a team-rung deck |
| +// whose owner the roster says is gone — a roster owner may share it |
| +// (the share page, minting and revoking links) and change its title and |
| +// theme; may not delete it, nor narrow its rung (private hides it from |
| +// everybody: a soft-delete). A member may do none of it, a live owner's |
| +// deck is not an orphan, nor is a departed member's private deck, even |
| +// one the roster owner holds a read grant on. |
| +func TestTeamRosterOwnerSharesAndRetitlesOrphansOnly(t *testing.T) { |
| + f := newTeamFixture(t) |
| + departed := f.member(teamSubject('d'), "member") |
| + orphan := f.deck(departed, "Departed's team deck", rungTeam) |
| + private := f.deck(departed, "Departed's private deck", rungPrivate) |
| + live := f.member(teamSubject('l'), "member") |
| + kept := f.deck(live, "Live owner's deck", rungTeam) |
| + f.member(teamSubject('m'), "member") |
| + rosterOwner := f.member(teamSubject('o'), "owner") |
| + f.grant(private, rosterOwner, departed) |
| + f.dir.Set(teamSubject('d'), "") |
| + f.refreshed() |
| + |
| + // Share: the page, a link minted and revoked. |
| + if got := f.get(deckPath(orphan) + "/share"); got.Code != 200 { |
| + t.Fatalf("roster owner's share page on an orphan = %d, want 200", got.Code) |
| + } |
| + if got := f.post(deckPath(orphan)+"/share", nil); got.Code != http.StatusSeeOther { |
| + t.Fatalf("roster owner minting a link on an orphan = %d", got.Code) |
| + } |
| + var link ShareLink |
| + if err := f.d.G.Where("deck_id = ?", orphan.ID).Take(&link).Error; err != nil { |
| + t.Fatal("no link minted") |
| + } |
| + if got := f.post(fmt.Sprintf("%s/share/%d/revoke", deckPath(orphan), link.ID), nil); got.Code != http.StatusSeeOther { |
| + t.Fatalf("roster owner revoking a link on an orphan = %d", got.Code) |
| + } |
| + // Title and theme: the settings page, with no rung and no delete. |
| + page := f.get(deckPath(orphan) + "/settings") |
| + if page.Code != 200 || strings.Contains(page.Body.String(), `name="rung"`) || strings.Contains(page.Body.String(), deckPath(orphan)+"/delete") { |
| + t.Fatalf("roster owner's settings on an orphan = %d (rung or delete offered?)", page.Code) |
| + } |
| + if got := f.get(deckPath(orphan)); !strings.Contains(got.Body.String(), deckPath(orphan)+"/settings") || !strings.Contains(got.Body.String(), deckPath(orphan)+"/share") { |
| + t.Fatal("the roster owner's viewer of an orphan offers no settings or share") |
| + } |
| + if got := f.post(deckPath(orphan)+"/settings", url.Values{"title": {"Rescued"}, "theme": {"ink"}}); got.Code != http.StatusSeeOther { |
| + t.Fatalf("roster owner retitling an orphan = %d %s", got.Code, got.Body.String()) |
| + } |
| + var row Deck |
| + f.d.G.Take(&row, orphan.ID) |
| + if row.Title != "Rescued" || row.Theme != "ink" || row.Rung != rungTeam { |
| + t.Fatalf("orphan after retitling = %q %q %q", row.Title, row.Theme, row.Rung) |
| + } |
| + // Not the rung, not delete. |
| + if got := f.post(deckPath(orphan)+"/settings", url.Values{"title": {"Hidden"}, "theme": {"ink"}, "rung": {rungPrivate}}); got.Code != http.StatusForbidden { |
| + t.Fatalf("roster owner making an orphan private = %d, want 403", got.Code) |
| + } |
| + if got := f.get(deckPath(orphan) + "/delete"); got.Code != 404 { |
| + t.Fatalf("roster owner's delete page on an orphan = %d, want 404", got.Code) |
| + } |
| + if got := f.post(deckPath(orphan)+"/delete", nil); got.Code != 404 { |
| + t.Fatalf("roster owner deleting an orphan = %d, want 404", got.Code) |
| + } |
| + f.d.G.Take(&row, orphan.ID) |
| + if row.Rung != rungTeam || row.Title != "Rescued" { |
| + t.Fatalf("a refused narrowing changed the orphan: %q %q", row.Title, row.Rung) |
| + } |
| + // A departed member's private deck, readable by grant: no owner powers. |
| + if got := f.get(deckPath(private)); got.Code != 200 || strings.Contains(got.Body.String(), deckPath(private)+"/settings") { |
| + t.Fatalf("roster owner's granted private orphan = %d (owner mode?)", got.Code) |
| + } |
| + for _, p := range []string{"/settings", "/share", "/delete"} { |
| + if got := f.get(deckPath(private) + p); got.Code != 404 { |
| + t.Fatalf("roster owner's %s on a private orphan = %d, want 404", p, got.Code) |
| + } |
| + } |
| + if got := f.get(deckPath(kept) + "/settings"); got.Code != 404 { |
| + t.Fatalf("roster owner's settings on a live owner's deck = %d, want 404", got.Code) |
| + } |
| + |
| + // A member is no owner of anything but their own. |
| + f.freshHomeSignIn(teamSubject('m')) |
| + for _, p := range []string{"/settings", "/share"} { |
| + if got := f.get(deckPath(orphan) + p); got.Code != 404 { |
| + t.Fatalf("a member's %s on an orphan = %d, want 404", p, got.Code) |
| + } |
| + } |
| + |
| + // The departed owner re-added: the deck has a live owner again. |
| + f.dir.Set(teamSubject('d'), "member") |
| + f.refreshed() |
| + f.freshHomeSignIn(teamSubject('o')) |
| + if got := f.get(deckPath(orphan) + "/share"); got.Code != 404 { |
| + t.Fatalf("roster owner after the owner's return = %d, want 404", got.Code) |
| + } |
| + |
| + // And the owner themselves still has every power, delete included. |
| + f.freshHomeSignIn(teamSubject('d')) |
| + if got := f.post(deckPath(orphan)+"/settings", url.Values{"title": {"Mine"}, "theme": {"ink"}, "rung": {rungPrivate}}); got.Code != http.StatusSeeOther { |
| + t.Fatalf("the owner's own rung change = %d", got.Code) |
| + } |
| + if got := f.post(deckPath(orphan)+"/delete", nil); got.Code != http.StatusSeeOther { |
| + t.Fatalf("the owner's own delete = %d", got.Code) |
| + } |
| +} |
| + |
| +// The dashboard feed follows the roster: a member's team decks, a removed |
| +// member's grants alone, and under Unknown unavailable — not a short list. |
| +func TestTeamDashboardFeedFollowsTheRoster(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + f.deck(colleague, "Team plan", rungTeam) |
| + shared := f.deck(colleague, "Shared", rungPrivate) |
| + u := f.member(teamSubject('a'), "member") |
| + f.grant(shared, u, colleague) |
| + ctx := context.Background() |
| + titles := func(r dashboard.Response) string { |
| + var out []string |
| + for _, it := range r.Items { |
| + out = append(out, it.Title) |
| + } |
| + return strings.Join(out, ",") |
| + } |
| + got, err := f.a.dashboardDocuments(ctx, u.ID, teamSubject('a'), time.Now()) |
| + if err != nil || !strings.Contains(titles(got), "Team plan") || !strings.Contains(titles(got), "Shared") { |
| + t.Fatalf("member's feed = %v %v", titles(got), err) |
| + } |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + got, err = f.a.dashboardDocuments(ctx, u.ID, teamSubject('a'), time.Now()) |
| + if err != nil || titles(got) != "Shared" { |
| + t.Fatalf("removed member's feed = %q %v, want the grant alone", titles(got), err) |
| + } |
| + f.dir.Set(teamSubject('a'), "member") |
| + f.refreshed() |
| + f.expired() |
| + if got, err = f.a.dashboardDocuments(ctx, u.ID, teamSubject('a'), time.Now()); err != dashboard.ErrUnavailable || len(got.Items) != 0 { |
| + t.Fatalf("Unknown feed = %v %v, want unavailable", titles(got), err) |
| + } |
| +} |
| + |
| +// The drive API stands on its operator's standing: a member's agent |
| +// lists and creates; under Unknown the JSON list is unavailable (it |
| +// cannot carry the notice) and create is a 503; a removed operator's |
| +// agent reaches their grants and creates nothing. |
| +func TestTeamAgentStandsOnItsOperator(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + f.deck(colleague, "Team plan", rungTeam) |
| + shared := f.deck(colleague, "Shared", rungPrivate) |
| + u := f.member(teamSubject('a'), "member") |
| + f.grant(shared, u, colleague) |
| + token := f.agent(u) |
| + |
| + list := f.api(token, "GET", apiPrefix+"/decks", "") |
| + if list.Code != 200 || !strings.Contains(list.Body.String(), "Team plan") { |
| + t.Fatalf("member's agent list = %d %s", list.Code, list.Body.String()) |
| + } |
| + if got := f.api(token, "POST", apiPrefix+"/decks", `{"title":"By agent"}`); got.Code != http.StatusCreated { |
| + t.Fatalf("member's agent create = %d", got.Code) |
| + } |
| + |
| + f.expired() |
| + if got := f.api(token, "GET", apiPrefix+"/decks", ""); got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" { |
| + t.Fatalf("agent list under Unknown = %d, want a retryable 503", got.Code) |
| + } |
| + if got := f.api(token, "POST", apiPrefix+"/decks", `{"title":"x"}`); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("agent create under Unknown = %d, want 503", got.Code) |
| + } |
| + if got := f.api(token, "GET", apiPrefix+"/decks/"+shared.Sqid, ""); got.Code != 200 { |
| + t.Fatalf("agent read of a grant under Unknown = %d", got.Code) |
| + } |
| + |
| + f.dir.Set(teamSubject('a'), "") |
| + f.renewed() |
| + list = f.api(token, "GET", apiPrefix+"/decks", "") |
| + if list.Code != 200 || strings.Contains(list.Body.String(), "Team plan") || !strings.Contains(list.Body.String(), "Shared") { |
| + t.Fatalf("removed operator's agent list = %d %s, want the grant alone", list.Code, list.Body.String()) |
| + } |
| + if got := f.api(token, "POST", apiPrefix+"/decks", `{"title":"x"}`); got.Code != http.StatusForbidden { |
| + t.Fatalf("removed operator's agent create = %d, want 403", got.Code) |
| + } |
| +} |
| + |
| +// A Home-only person is named by their ref wherever an address would be: |
| +// the deck list's last change, presence, and an agent's principal. |
| +func TestTeamHomeOnlyPeopleAreNamedByTheirRef(t *testing.T) { |
| + f := newTeamFixture(t) |
| + u := f.member(teamSubject('a'), "member") |
| + plan := f.deck(u, "Team plan", rungTeam) |
| + want := homeOnlyLabel(teamSubject('a')) |
| + if !strings.HasSuffix(want, "…aaaa") { |
| + t.Fatalf("label = %q", want) |
| + } |
| + labels := f.a.actorLabels(context.Background(), []string{actorFor(u)}) |
| + if labels[actorFor(u)] != want { |
| + t.Fatalf("actor label = %q, want %q", labels[actorFor(u)], want) |
| + } |
| + if got := f.get("/"); !strings.Contains(got.Body.String(), want) { |
| + t.Fatal("the deck list does not name the Home-only author") |
| + } |
| + if got := f.do("POST", deckPath(plan)+"/presence", `{"client":"c1","slide":"","block":""}`, "application/json", homeTestOrigin); got.Code != http.StatusNoContent { |
| + t.Fatalf("presence = %d", got.Code) |
| + } |
| + set := f.a.live.Snapshot(plan.Sqid) |
| + if len(set) != 1 || set[0].Name != want { |
| + t.Fatalf("presence = %+v, want named %q", set, want) |
| + } |
| + f.agent(u) |
| + if got := f.get("/agents"); !strings.Contains(got.Body.String(), "claude~"+want) { |
| + t.Fatal("an agent's principal does not name its Home-only operator") |
| + } |
| +} |
| + |
| +// A local account linked to a Home identity, on a team instance with no |
| +// allowlist: the link names who they are, and the roster decides what |
| +// they reach — neither needs SLIDES_ALLOWED_ADDRESSES. |
| +func TestTeamLinkedAccountStandsOnTheRoster(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + linked := f.localUser("linked@example.com") |
| + homeLinkedSubject(t, f.a, linked, teamSubject('k')) |
| + f.dir.Set(teamSubject('k'), "member") |
| + f.refreshed() |
| + if got := f.freshHomeSignIn(teamSubject('k')); got.Code != http.StatusSeeOther { |
| + t.Fatalf("linked member's Home sign-in = %d %s", got.Code, got.Body.String()) |
| + } |
| + if f.userFor(teamSubject('k')).ID != linked.ID { |
| + t.Fatal("the linked account signed in as somebody else") |
| + } |
| + page := f.get(deckPath(plan)) |
| + if page.Code != 200 || !strings.Contains(page.Body.String(), "linked@example.com") { |
| + t.Fatalf("linked member on a team deck = %d (signed in as the account?)", page.Code) |
| + } |
| + f.dir.Set(teamSubject('k'), "") |
| + f.refreshed() |
| + if got := f.get(deckPath(plan)); got.Code != 404 { |
| + t.Fatalf("linked account after removal = %d, want 404", got.Code) |
| + } |
| +} |
| + |
| +// A Home-only member exports like anybody: their jobs are keyed on the |
| +// user, since there is no address to key on, and so are their agents'. |
| +func TestTeamHomeOnlyMemberExports(t *testing.T) { |
| + f := newTeamFixture(t) |
| + u := f.member(teamSubject('a'), "member") |
| + plan := f.deck(u, "Team plan", rungTeam) |
| + got := f.post(deckPath(plan)+"/export", nil) |
| + if got.Code != http.StatusSeeOther || !strings.Contains(got.Header().Get("Location"), "/export/") { |
| + t.Fatalf("Home-only member's export = %d %s", got.Code, got.Body.String()) |
| + } |
| + status := f.get(got.Header().Get("Location")) |
| + if status.Code != 200 { |
| + t.Fatalf("their export's status page = %d", status.Code) |
| + } |
| + token := f.agent(u) |
| + if got := f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/export", ""); got.Code != http.StatusAccepted { |
| + t.Fatalf("their agent's export = %d %s", got.Code, got.Body.String()) |
| + } |
| + if owner := f.a.apiExportOwner(principal{operator: u}); owner != teamJobOwner(u.ID) { |
| + t.Fatalf("agent export owner = %q", owner) |
| + } |
| +} |
| + |
| +// A presigned GET never outlives the standing it was minted on: the |
| +// Member lease, and never beyond the roster's 60 s otherwise. |
| +func TestTeamPresignedURLsAreCappedAtTheLease(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('a'), "member") |
| + u := f.userFor(teamSubject('a')) |
| + u.team = &teamAccess{Access: f.a.team.Access(context.Background(), teamSubject('a'))} |
| + if ttl := f.a.presignTTLFor(u); ttl <= 0 || ttl > 60*time.Second { |
| + t.Fatalf("member's presign TTL = %v", ttl) |
| + } |
| + f.clock.Step(50 * time.Second) |
| + if ttl := f.a.presignTTLFor(u); ttl > 10*time.Second { |
| + t.Fatalf("presign TTL with 10 s of lease left = %v", ttl) |
| + } |
| + u.team = &teamAccess{Access: f.a.team.Access(context.Background(), "")} |
| + if ttl := f.a.presignTTLFor(u); ttl != 60*time.Second { |
| + t.Fatalf("guest's presign TTL = %v, want the roster's 60 s", ttl) |
| + } |
| +} |
diff --git a/internal/slides/team_stream_test.go b/internal/slides/team_stream_test.go| new file mode 100644 |
| index 0000000..b8bb8eb |
| --- /dev/null |
| +++ b/internal/slides/team_stream_test.go |
| @@ -0,0 +1,351 @@ |
| +package slides |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "strconv" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/slides/internal/slides/present" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// openStream opens path on a real server with the jar's cookies and |
| +// reads up to and including its connect events (the deck stream sends |
| +// two, update and presence; a presentation's one), so the handler is |
| +// known to be past its checks, subscribed, and waiting. |
| +func (f *teamFixture) openStream(t *testing.T, path string, withCookies bool) *bufio.Reader { |
| + t.Helper() |
| + srv := httptest.NewServer(f.mux) |
| + t.Cleanup(srv.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + t.Cleanup(cancel) |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The instance's own host: rastrillo serves the origin it resolved. |
| + req.Host = strings.TrimPrefix(homeTestOrigin, "https://") |
| + if withCookies { |
| + for _, c := range f.jar { |
| + req.AddCookie(c) |
| + } |
| + } |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("stream %s = %d", path, resp.StatusCode) |
| + } |
| + br := bufio.NewReader(resp.Body) |
| + events := 1 |
| + if strings.HasPrefix(path, "/d/") { |
| + events = 2 |
| + } |
| + for events > 0 { |
| + line, err := br.ReadString('\n') |
| + if err != nil { |
| + t.Fatalf("stream ended before its connect events: %v", err) |
| + } |
| + if line == "\n" { |
| + events-- |
| + } |
| + } |
| + return br |
| +} |
| + |
| +// endsWithin reports whether the stream's body ends within d, reading |
| +// whatever it sends meanwhile. |
| +func endsWithin(br *bufio.Reader, d time.Duration) (string, bool) { |
| + done := make(chan error, 1) |
| + var got strings.Builder |
| + go func() { |
| + _, err := io.Copy(&got, br) |
| + done <- err |
| + }() |
| + select { |
| + case err := <-done: |
| + return got.String(), err == nil || errors.Is(err, io.EOF) |
| + case <-time.After(d): |
| + return got.String(), false |
| + } |
| +} |
| + |
| +// Renewal: at the lease the stream asks again, and while the roster still |
| +// says Member it carries on, and still delivers. |
| +func TestTeamDeckStreamRenewsWhileStillAMember(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + f.clock.Step(59 * time.Second) |
| + f.dir.SetDown(true) |
| + if err := f.a.team.Refresh(context.Background()); err == nil { |
| + t.Fatal("refresh succeeded with the directory down") |
| + } |
| + f.dir.SetDown(false) |
| + br := f.openStream(t, deckPath(plan)+"/stream", true) |
| + f.clock.Step(6 * time.Second) // past the lease and the backoff |
| + time.Sleep(1500 * time.Millisecond) // past the stream's lease timer |
| + if got := f.do("POST", deckPath(plan)+"/updates", string(f.update(plan, "Still here")), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent { |
| + t.Fatalf("member write = %d", got.Code) |
| + } |
| + line := make(chan string, 1) |
| + go func() { |
| + for { |
| + l, err := br.ReadString('\n') |
| + if err != nil { |
| + line <- "EOF" |
| + return |
| + } |
| + if strings.HasPrefix(l, "event: update") { |
| + line <- l |
| + return |
| + } |
| + } |
| + }() |
| + select { |
| + case got := <-line: |
| + if got == "EOF" { |
| + t.Fatal("the renewed stream ended") |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the renewed stream delivered nothing") |
| + } |
| +} |
| + |
| +// Removal reaches a deck stream at its next delivery: a write by |
| +// somebody else after the removal ends the removed member's stream |
| +// rather than telling them about it. |
| +func TestTeamDeckStreamEndsOnRemoval(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + br := f.openStream(t, deckPath(plan)+"/stream", true) |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + if err := f.a.editDeck(context.Background(), &plan, actorFor(colleague), mustOps(t, "After"), nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ended := endsWithin(br, 5*time.Second); !ended || strings.Contains(got, "event: update") { |
| + t.Fatalf("a removed member's stream = %q (ended %v), want it ended with nothing delivered", got, ended) |
| + } |
| +} |
| + |
| +func mustOps(t *testing.T, title string) []byte { |
| + t.Helper() |
| + b, err := opsJSON([]op{{"op": "set_meta", "title": title, "theme": defaultTheme}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// startTalk has the jar's person present d and returns the session sqid. |
| +func (f *teamFixture) startTalk(t *testing.T, d Deck) string { |
| + t.Helper() |
| + got := f.post(deckPath(d)+"/present", nil) |
| + if got.Code != http.StatusSeeOther { |
| + t.Fatalf("present = %d %s", got.Code, got.Body.String()) |
| + } |
| + loc, _ := url.Parse(got.Header().Get("Location")) |
| + return strings.Split(strings.TrimPrefix(loc.Path, "/p/"), "/")[0] |
| +} |
| + |
| +// A presentation stands on its presenter's reach. Removed, the projector |
| +// is told the talk is over and the row is ended; with their standing |
| +// unknown, the projector gets a retryable 503 and the talk is left |
| +// running. |
| +func TestTeamPresentationStandsOnThePresenter(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + session := f.startTalk(t, plan) |
| + f.jar = map[string]*http.Cookie{} // the projector has no session |
| + if got := f.get("/p/" + session); got.Code != 200 { |
| + t.Fatalf("projector = %d", got.Code) |
| + } |
| + |
| + f.expired() |
| + if got := f.get("/p/" + session); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("projector with the presenter's standing unknown = %d, want 503", got.Code) |
| + } |
| + var p Presentation |
| + f.d.G.Where("sqid = ?", session).Take(&p) |
| + if p.EndedAt != nil { |
| + t.Fatal("an unknown standing ended the talk") |
| + } |
| + |
| + f.dir.Set(teamSubject('a'), "") |
| + f.renewed() |
| + if got := f.get("/p/" + session); got.Code != http.StatusGone { |
| + t.Fatalf("projector after the presenter's removal = %d, want 410", got.Code) |
| + } |
| + f.d.G.Where("sqid = ?", session).Take(&p) |
| + if p.EndedAt == nil { |
| + t.Fatal("the removed presenter's talk was not ended") |
| + } |
| +} |
| + |
| +// lines feeds a stream's lines to a channel, closed when the body ends. |
| +func lines(br *bufio.Reader) <-chan string { |
| + ch := make(chan string, 64) |
| + go func() { |
| + defer close(ch) |
| + for { |
| + l, err := br.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + ch <- l |
| + } |
| + }() |
| + return ch |
| +} |
| + |
| +// within reads ch for d: the first line containing want (found), or |
| +// whether the stream ended, with every line seen. |
| +func within(ch <-chan string, want string, d time.Duration) (seen string, found, ended bool) { |
| + deadline := time.After(d) |
| + for { |
| + select { |
| + case l, ok := <-ch: |
| + if !ok { |
| + return seen, false, true |
| + } |
| + seen += l |
| + if want != "" && strings.Contains(l, want) { |
| + return seen, true, false |
| + } |
| + case <-deadline: |
| + return seen, false, false |
| + } |
| + } |
| +} |
| + |
| +// shortHold makes a held stream re-ask every 100 ms instead of the |
| +// roster's 5 s. |
| +func shortHold(t *testing.T) { |
| + streamHoldRetry = 100 * time.Millisecond |
| + t.Cleanup(func() { streamHoldRetry = roster.RetryAfter }) |
| +} |
| + |
| +// A deck stream whose Member lease runs out while the roster cannot be |
| +// read is held, not ended (Fable #33, note 1): it stays open and delivers |
| +// nothing about the deck, and the moment standing returns it is caught |
| +// up with the deck's current seq. |
| +func TestTeamDeckStreamHoldsWhileStandingIsUnknown(t *testing.T) { |
| + shortHold(t) |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + f.dir.SetDown(true) |
| + f.clock.Step(59 * time.Second) |
| + feed := lines(f.openStream(t, deckPath(plan)+"/stream", true)) |
| + f.clock.Step(2 * time.Second) |
| + time.Sleep(1500 * time.Millisecond) // past the stream's lease timer: held |
| + if err := f.a.editDeck(context.Background(), &plan, actorFor(colleague), mustOps(t, "While held"), nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if seen, found, ended := within(feed, "event:", time.Second); found || ended { |
| + t.Fatalf("a held deck stream delivered or ended: %q (ended %v)", seen, ended) |
| + } |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| + seen, found, _ := within(feed, "data: "+strconv.FormatInt(plan.Seq, 10), 3*time.Second) |
| + if !found || !strings.Contains(seen, "event: update") { |
| + t.Fatalf("the held stream was not caught up to seq %d: %q", plan.Seq, seen) |
| + } |
| +} |
| + |
| +// A projector stream whose presenter's lease runs out while the roster |
| +// cannot be read is held, delivering nothing; when it can be read again |
| +// the projector gets the talk's current state, never what was published |
| +// while held. |
| +func TestTeamPresentationStreamHoldsWhileThePresenterIsUnknown(t *testing.T) { |
| + shortHold(t) |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + session := f.startTalk(t, plan) |
| + f.dir.SetDown(true) |
| + f.clock.Step(59 * time.Second) |
| + feed := lines(f.openStream(t, "/p/"+session+"/stream", false)) |
| + f.clock.Step(2 * time.Second) |
| + time.Sleep(1500 * time.Millisecond) |
| + f.a.hub.Publish(session, present.Event{Slide: 9}) |
| + if seen, found, ended := within(feed, "event:", time.Second); found || ended { |
| + t.Fatalf("a held projector stream delivered or ended: %q (ended %v)", seen, ended) |
| + } |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| + seen, found, _ := within(feed, "event: slide", 3*time.Second) |
| + if !found { |
| + t.Fatalf("the held projector was not caught up: %q", seen) |
| + } |
| + if rest, _, _ := within(feed, "", 200*time.Millisecond); strings.Contains(seen+rest, `"slide":9`) { |
| + t.Fatal("a held projector was sent what was published while it was held") |
| + } |
| +} |
| + |
| +// A projector that connects while its presenter's standing is unknown is |
| +// not refused (an EventSource answered 503 fails for good): it is held, |
| +// and served once the roster can be read. The page itself is still the |
| +// retryable 503; a removed presenter's stream is the 410. |
| +func TestTeamProjectorConnectsWhileThePresenterIsUnknown(t *testing.T) { |
| + shortHold(t) |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + session := f.startTalk(t, plan) |
| + f.expired() |
| + srv := httptest.NewServer(f.mux) |
| + t.Cleanup(srv.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + t.Cleanup(cancel) |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+session+"/stream", nil) |
| + req.Host = strings.TrimPrefix(homeTestOrigin, "https://") |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("projector stream under Unknown = %d, want a held 200", resp.StatusCode) |
| + } |
| + feed := lines(bufio.NewReader(resp.Body)) |
| + if seen, found, ended := within(feed, "event:", 500*time.Millisecond); found || ended { |
| + t.Fatalf("a held projector delivered or ended: %q", seen) |
| + } |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| + if seen, found, _ := within(feed, "event: slide", 3*time.Second); !found { |
| + t.Fatalf("the projector was not served once the roster returned: %q", seen) |
| + } |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + r2, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+session+"/stream", nil) |
| + r2.Host = req.Host |
| + gone, err := http.DefaultClient.Do(r2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + gone.Body.Close() |
| + if gone.StatusCode != http.StatusGone { |
| + t.Fatalf("projector stream for a removed presenter = %d, want 410", gone.StatusCode) |
| + } |
| +} |
diff --git a/internal/slides/team_survivors_test.go b/internal/slides/team_survivors_test.go| new file mode 100644 |
| index 0000000..d4fd998 |
| --- /dev/null |
| +++ b/internal/slides/team_survivors_test.go |
| @@ -0,0 +1,248 @@ |
| +package slides |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "log/slog" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "database/sql" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// Ownership is the team rung's: a removed owner whom somebody has granted |
| +// their own deck reads it, and owns nothing. |
| +func TestTeamRemovedOwnerOwnsNothing(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + u := f.member(teamSubject('a'), "member") |
| + own := f.deck(u, "My own", rungTeam) |
| + f.grant(own, u, colleague) |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + page := f.get(deckPath(own)) |
| + if page.Code != 200 || strings.Contains(page.Body.String(), deckPath(own)+"/settings") { |
| + t.Fatalf("removed owner's granted deck = %d (owner mode?)", page.Code) |
| + } |
| + for _, p := range []string{"/settings", "/share", "/delete"} { |
| + if got := f.get(deckPath(own) + p); got.Code != 404 { |
| + t.Fatalf("removed owner's %s = %d, want 404", p, got.Code) |
| + } |
| + } |
| +} |
| + |
| +// Under Unknown, an owner's screen on a deck reached by grant cannot be |
| +// decided either way (the viewer might be a roster owner of an orphan): |
| +// the retryable 503, not a 404. |
| +func TestTeamOwnerScreensUnderUnknownAreRetryable(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + shared := f.deck(colleague, "Shared", rungPrivate) |
| + u := f.member(teamSubject('a'), "member") |
| + f.grant(shared, u, colleague) |
| + f.expired() |
| + if got := f.get(deckPath(shared) + "/settings"); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("settings on a granted deck under Unknown = %d, want 503", got.Code) |
| + } |
| +} |
| + |
| +// An owner whose standing cannot be read is not gone: the roster owner |
| +// does not take their deck. |
| +func TestTeamOwnerOfUnknownStandingIsNotAnOrphan(t *testing.T) { |
| + f := newTeamFixture(t) |
| + owner := f.member(teamSubject('l'), "member") |
| + kept := f.deck(owner, "Live owner's deck", rungTeam) |
| + f.member(teamSubject('o'), "owner") |
| + broken, err := sql.Open("sqlite", "file:closed3?mode=memory") |
| + if err == nil { |
| + broken.Close() |
| + } |
| + real := f.a.team.db |
| + f.a.team.db = broken |
| + got := f.get(deckPath(kept) + "/settings") |
| + f.a.team.db = real |
| + if got.Code != 404 { |
| + t.Fatalf("roster owner on a deck whose owner's standing cannot be read = %d, want 404", got.Code) |
| + } |
| +} |
| + |
| +// A reach through the team rung never stands without a lease: whenever |
| +// the lease lapses — before the reach query, between it and the standing |
| +// check, or after — a stream or a talk that rested on it either ends or |
| +// re-decides on a timer, never "reaches, nothing to renew". The roster |
| +// clock ticks on every reading, and the lapse is swept across each |
| +// reading in turn, so one of them lands between the query and the check. |
| +func TestTeamTeamRungReachNeverStandsWithoutALease(t *testing.T) { |
| + for _, what := range []string{"deck stream", "talk"} { |
| + for k := 1; k <= 12; k++ { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + u := f.member(teamSubject('a'), "member") |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + s, _ := f.a.homeSessions.From(r) |
| + r = sessions.WithSession(r, s) |
| + |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + var stands bool |
| + if what == "deck stream" { |
| + decision, renew := f.a.teamStreamAccess(r, plan.ID) |
| + stands = decision == streamDelivers && renew == 0 |
| + } else { |
| + reach, renew := f.a.presenterStanding(context.Background(), Presentation{Actor: actorFor(u), DeckID: plan.ID}) |
| + stands = reach == presenterReaches && renew == 0 |
| + } |
| + if stands { |
| + t.Fatalf("k=%d: a %s on the team rung stands with nothing to renew", k, what) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// A share-link follower follows only a talk whose presenter still reaches |
| +// the deck: a removed presenter's talk is not followed, and is ended. |
| +func TestTeamFollowersDoNotFollowARemovedPresenter(t *testing.T) { |
| + f := newTeamFixture(t) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.member(teamSubject('a'), "member") |
| + session := f.startTalk(t, plan) |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + if _, ok := f.a.liveSessionFor(r, plan.ID); !ok { |
| + t.Fatal("the talk is not followable") |
| + } |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + if _, ok := f.a.liveSessionFor(r, plan.ID); ok { |
| + t.Fatal("a removed presenter's talk is followable") |
| + } |
| + var p Presentation |
| + f.d.G.Where("sqid = ?", session).Take(&p) |
| + if p.EndedAt == nil { |
| + t.Fatal("the removed presenter's talk was not ended") |
| + } |
| +} |
| + |
| +// Off the list is not off the team: in team mode a local or linked |
| +// account the allowlist no longer names keeps its signed-in chrome, its |
| +// presenter identity and its link flow; the roster decides what it |
| +// reaches. And a team instance in development never admits everybody. |
| +func TestTeamTheAllowlistDecidesNothingButLocalSignIn(t *testing.T) { |
| + f := newTeamFixture(t, "other@example.com") |
| + if f.a.allowed.allows("anyone@example.com") { |
| + t.Fatal("a team allowlist admits an address it does not name") |
| + } |
| + g := newTeamFixture(t) |
| + if g.a.allowed.allows("anyone@example.com") { |
| + t.Fatal("an empty team allowlist in development admits everybody") |
| + } |
| + |
| + // A local session the list no longer names: signed-in chrome. |
| + f.localUser("x@example.com") |
| + f.localSession("x@example.com") |
| + if got := f.get("/nope"); !strings.Contains(got.Body.String(), `action="/signout"`) { |
| + t.Fatal("an unlisted local session's error page is signed out") |
| + } |
| + // It links its Home identity. |
| + f.linkHome(t, teamSubject('x')) |
| + if p, err := f.a.home.Resolve(context.Background(), teamSubject('x')); err != nil || p.ID != f.userFor(teamSubject('x')).ID { |
| + t.Fatalf("link from an unlisted local session: %v", err) |
| + } |
| + // Signed in with Home, the linked account is the presenter of its talk |
| + // and has signed-in chrome on pages outside the session gate. |
| + f.dir.Set(teamSubject('x'), "member") |
| + f.refreshed() |
| + f.freshHomeSignIn(teamSubject('x')) |
| + colleague := f.member(teamSubject('b'), "member") |
| + plan := f.deck(colleague, "Team plan", rungTeam) |
| + f.freshHomeSignIn(teamSubject('x')) |
| + session := f.startTalk(t, plan) |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range f.jar { |
| + r.AddCookie(c) |
| + } |
| + if got := f.a.presenterActor(r); got == "" { |
| + t.Fatal("an unlisted linked account is nobody to presentation.go") |
| + } |
| + if got := f.get("/p/" + session + "/notes"); got.Code != 200 { |
| + t.Fatalf("the presenter's notes by session = %d", got.Code) |
| + } |
| + if got := f.get("/nope"); !strings.Contains(got.Body.String(), `action="/signout"`) { |
| + t.Fatal("an unlisted linked account's error page is signed out") |
| + } |
| +} |
| + |
| +// linkHome runs connect's explicit link flow for the jar's local session |
| +// and subject, as TestHomeRealSignedExchangeExplicitLinkAndReplay does. |
| +func (f *teamFixture) linkHome(t *testing.T, subject string) { |
| + t.Helper() |
| + start := f.post("/account/home", nil) |
| + if start.Code != http.StatusSeeOther { |
| + t.Fatalf("link start = %d %s", start.Code, start.Body.String()) |
| + } |
| + auth := f.get(start.Header().Get("Location")) |
| + target, err := url.Parse(auth.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, _ := assertion.RandomID() |
| + now := time.Now().Unix() |
| + token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: teamTestIssuer, Audience: homeTestOrigin, Subject: subject, KeyID: "test", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cb := f.do("POST", handoff.CallbackPath, url.Values{"assertion": {token}}.Encode(), "application/x-www-form-urlencoded", teamTestIssuer); cb.Code != http.StatusSeeOther { |
| + t.Fatalf("link callback = %d", cb.Code) |
| + } |
| + if fin := f.get(handoff.FinishPath); fin.Code != http.StatusSeeOther { |
| + t.Fatalf("link finish = %d %s", fin.Code, fin.Body.String()) |
| + } |
| + if c := f.post("/account/home/confirm", nil); c.Code != http.StatusSeeOther { |
| + t.Fatalf("link confirm = %d %s", c.Code, c.Body.String()) |
| + } |
| +} |
| + |
| +// A first local sign-in on a team instance seeds no sample deck — the |
| +// account is a guest until it links — and so logs no failed seed |
| +// (Fable #33, note 3). |
| +func TestTeamFirstLocalSignInSeedsNothingAndLogsNothing(t *testing.T) { |
| + var logged bytes.Buffer |
| + key := teamKey(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key, "new@example.com") |
| + cfg.Logger = slog.New(slog.NewTextHandler(&logged, nil)) |
| + d := testDB(t) |
| + mux, a, err := New(d, cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + f := &teamFixture{t: t, mux: mux, a: a, d: d, key: key, jar: map[string]*http.Cookie{}} |
| + f.localSession("new@example.com") |
| + if got := f.get(connect.LocalCompletePath); got.Code >= 500 { |
| + t.Fatalf("local complete = %d", got.Code) |
| + } |
| + var users, decks int64 |
| + d.G.Model(&User{}).Count(&users) |
| + d.G.Model(&Deck{}).Count(&decks) |
| + if users != 1 || decks != 0 { |
| + t.Fatalf("first local sign-in made users=%d decks=%d, want 1 and 0", users, decks) |
| + } |
| + if strings.Contains(logged.String(), "level=ERROR") { |
| + t.Fatalf("a first local sign-in logged an error:\n%s", logged.String()) |
| + } |
| +} |
diff --git a/internal/slides/teamstate/migrations/0001_home_users.sql b/internal/slides/teamstate/migrations/0001_home_users.sql| new file mode 100644 |
| index 0000000..5f37af1 |
| --- /dev/null |
| +++ b/internal/slides/teamstate/migrations/0001_home_users.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE slides_team_home_users ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + user_id INTEGER NOT NULL UNIQUE REFERENCES users(id), |
| + PRIMARY KEY(issuer,subject) |
| +); |
| +CREATE TRIGGER slides_team_home_user_addressless BEFORE INSERT ON slides_team_home_users WHEN NOT EXISTS(SELECT 1 FROM users WHERE id=NEW.user_id AND email IS NULL) BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_home_user_unlinked BEFORE INSERT ON slides_team_home_users WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_home_users_keep_update BEFORE UPDATE ON slides_team_home_users BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_home_users_keep_delete BEFORE DELETE ON slides_team_home_users BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_link_not_home_only BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM slides_team_home_users WHERE (issuer=NEW.issuer AND subject=NEW.subject) OR user_id=NEW.person_id) BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_home_user_keeps_no_address BEFORE UPDATE OF email ON users WHEN EXISTS(SELECT 1 FROM slides_team_home_users WHERE user_id=OLD.id) BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
| +CREATE TRIGGER slides_team_home_user_keep_row BEFORE DELETE ON users WHEN EXISTS(SELECT 1 FROM slides_team_home_users WHERE user_id=OLD.id) BEGIN SELECT RAISE(ABORT,'slides team: refused'); END; |
diff --git a/internal/slides/teamstate/store.go b/internal/slides/teamstate/store.go| new file mode 100644 |
| index 0000000..9c5ea31 |
| --- /dev/null |
| +++ b/internal/slides/teamstate/store.go |
| @@ -0,0 +1,162 @@ |
| +// Package teamstate keeps the Home-only people a roster admitted in team |
| +// mode, and the reverse lookup from a person to the Home subject the |
| +// roster knows them by. |
| +// |
| +// The marker and the roster evidence are not here: they are |
| +// home/teammode's State ("slides", set slides_team), merged beside this |
| +// package's own set (slides_team_home). Slides' local people are its |
| +// users table, so a Home-only person is a users row with no address, |
| +// and this package's table says which Home subject it belongs to. |
| +// |
| +// None of it is standing. A Home-only row says who a Home subject is on |
| +// this instance, never whether they are on the team: that is the |
| +// roster's answer, asked again on every request. |
| +package teamstate |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "errors" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema is the Home-only users table and its triggers. They name users |
| +// and home_identity_links, so it is merged after Slides' own schema and |
| +// linkstore's (team_config.go's teamBoot). |
| +var Schema = migrate.MustFromFS(migrations, "slides_team_home") |
| + |
| +var ( |
| + // ErrRefused is a definite "no": no such person, or a subject that |
| + // cannot be one. |
| + ErrRefused = errors.New("slides team: refused") |
| + // ErrUnavailable is "cannot read it now". |
| + ErrUnavailable = errors.New("slides team: unavailable") |
| +) |
| + |
| +// HomeUser reads the user a Home-only identity was given. It never |
| +// creates one: ErrRefused means there is none. |
| +func HomeUser(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e := db.QueryRowContext(ctx, "SELECT user_id FROM slides_team_home_users WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrRefused |
| + } |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// HomeSubject is the reverse: the Home subject a user is known by on this |
| +// instance, through a Home-only row or an explicit account link. |
| +// ErrRefused means neither, which is no team standing, never an error. |
| +func HomeSubject(ctx context.Context, db *sql.DB, issuer string, user int64) (string, error) { |
| + var subject string |
| + e := db.QueryRowContext(ctx, `SELECT subject FROM slides_team_home_users WHERE issuer=? AND user_id=? |
| + UNION ALL SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=? LIMIT 1`, issuer, user, issuer, user).Scan(&subject) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", ErrRefused |
| + } |
| + if e != nil { |
| + return "", ErrUnavailable |
| + } |
| + return subject, nil |
| +} |
| + |
| +// HomeSubjects maps every Home-only user to its subject, for labels on |
| +// pages that name people without asking the roster. |
| +func HomeSubjects(ctx context.Context, db *sql.DB, issuer string) (map[int64]string, error) { |
| + rows, err := db.QueryContext(ctx, "SELECT user_id, subject FROM slides_team_home_users WHERE issuer=?", issuer) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + defer rows.Close() |
| + out := map[int64]string{} |
| + for rows.Next() { |
| + var id int64 |
| + var subject string |
| + if rows.Scan(&id, &subject) != nil { |
| + return nil, ErrUnavailable |
| + } |
| + out[id] = subject |
| + } |
| + if rows.Err() != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return out, nil |
| +} |
| + |
| +// EnsureHomeUser gives a Home subject an addressless user, or returns the |
| +// one it already has; created says which. The caller must have just had |
| +// a current roster answer of Member for this subject: this records |
| +// identity, not standing, and a later request asks the roster again. A |
| +// subject already linked to a local account is refused — that person |
| +// signs in as that account. |
| +func EnsureHomeUser(ctx context.Context, db *sql.DB, issuer, subject, colour string) (id int64, created bool, err error) { |
| + if !Opaque(subject) || issuer == "" { |
| + return 0, false, ErrRefused |
| + } |
| + tx, e := db.BeginTx(ctx, nil) |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + var linked int |
| + if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_identity_links WHERE issuer=? AND subject=?", issuer, subject).Scan(&linked); e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if linked != 0 { |
| + return 0, false, ErrRefused |
| + } |
| + e = tx.QueryRowContext(ctx, "SELECT user_id FROM slides_team_home_users WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if e == nil { |
| + if tx.Commit() != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + return id, false, nil |
| + } |
| + if !errors.Is(e, sql.ErrNoRows) { |
| + return 0, false, ErrUnavailable |
| + } |
| + // email NULL, never "": the unique index on users.email admits any |
| + // number of NULLs and exactly one empty string. |
| + res, e := tx.ExecContext(ctx, "INSERT INTO users(email,name,colour,created_at) VALUES(NULL,'',?,?)", colour, time.Now().UTC()) |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if id, e = res.LastInsertId(); e != nil || id <= 0 { |
| + return 0, false, ErrUnavailable |
| + } |
| + if _, e = tx.ExecContext(ctx, "INSERT INTO slides_team_home_users(issuer,subject,user_id) VALUES(?,?,?)", issuer, subject, id); e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if tx.Commit() != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + return id, true, nil |
| +} |
| + |
| +// Opaque is a Home subject's shape: bounded, printable, and never an |
| +// address, so a subject can never be mistaken for one. |
| +func Opaque(s string) bool { |
| + if s == "" || len(s) > 512 || !utf8.ValidString(s) || strings.Contains(s, "@") { |
| + return false |
| + } |
| + for _, r := range s { |
| + if r <= 32 || r == 127 { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/slides/templates/deck_settings.html b/internal/slides/templates/deck_settings.html| index 71225c8..fad4935 100644 |
| --- a/internal/slides/templates/deck_settings.html |
| +++ b/internal/slides/templates/deck_settings.html |
| @@ -22,16 +22,16 @@ |
| "ID" "theme" "Name" "theme" "Label" .ThemeLabel |
| "Options" .Themes "Required" true |
| "Error" (index .Errors "Theme")}} |
| - {{template "choice-field" dict |
| + {{if .Rungs}}{{template "choice-field" dict |
| "Legend" .RungLegend "Name" "rung" "Options" .Rungs}} |
| {{template "form-error" (index .Errors "Rung")}} |
| - {{template "form-foot" dict |
| + {{end}}{{template "form-foot" dict |
| "Submit" .Submit "CancelHref" .CancelHref "CancelLabel" .CancelLabel}} |
| </form> |
| </div> |
| -<div rst-box-head><h2>{{.DeleteLabel}}</h2></div> |
| +{{if .DeleteHref}}<div rst-box-head><h2>{{.DeleteLabel}}</h2></div> |
| <div rst-box> |
| <p>{{.DeleteBody}}</p> |
| <p><a rst-btn href="{{.DeleteHref}}">{{.DeleteLabel}}</a></p> |
| </div> |
| -{{end}} |
| +{{end}}{{end}} |
diff --git a/internal/slides/templates/decks.html b/internal/slides/templates/decks.html| index 0f5e27f..dddbf1f 100644 |
| --- a/internal/slides/templates/decks.html |
| +++ b/internal/slides/templates/decks.html |
| @@ -13,7 +13,13 @@ |
| {{template "page-header" dict |
| "Title" .Title |
| "ActionHref" .NewHref "ActionLabel" .NewLabel "ActionIcon" "plus"}} |
| -{{if .Decks}} |
| +{{if .Partial}}{{/* Team mode, standing Unknown (Paul, 2026-10-28): the |
| + list is what this person reaches without the team — the decks |
| + granted to them — and says so, rather than the whole page |
| + answering 503. Rendered only then, and nothing at all otherwise. */}}<div data-partial> |
| +{{template "callout" dict "Tone" "warning" "Title" .PartialTitle "Body" .PartialBody}} |
| +</div> |
| +{{end}}{{if .Decks}} |
| <div rst-list> |
| {{range .Decks}} |
| {{template "list-row-action" dict |
| @@ -21,7 +27,7 @@ |
| "StatusLabel" .RungLabel "StatusTone" .RungTone}} |
| {{end}} |
| </div> |
| -{{else}} |
| +{{else if not .Partial}} |
| <div rst-box> |
| {{template "empty-state" dict |
| "Title" .EmptyTitle "Body" .EmptyBody |
diff --git a/internal/slides/viewer.go b/internal/slides/viewer.go| index da0d311..afaaead 100644 |
| --- a/internal/slides/viewer.go |
| +++ b/internal/slides/viewer.go |
| @@ -141,7 +141,7 @@ func (a *app) showDeck(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| mode := modeMember |
| - if d.OwnerID == u.ID { |
| + if a.mayShareDeck(r.Context(), u, d) { |
| mode = modeOwner |
| } |
| a.renderViewer(w, r, d, mode, "/d/"+d.Sqid, a.shellFor(r, u, titled(d.Title))) |
diff --git a/scripts/credits.py b/scripts/credits.py| index 5901aab..ebe2f0c 100755 |
| --- a/scripts/credits.py |
| +++ b/scripts/credits.py |
| @@ -12,7 +12,7 @@ from html.parser import HTMLParser |
| ROOT = Path(__file__).resolve().parent.parent |
| OUT = ROOT / 'internal/slides/credits' |
| ENV = os.environ | {'GOPRIVATE': 'amadan.net/oficina/estilo.git'} |
| -EXCLUDE = ','.join(['amadan.net/oficina/home/dashboard', 'amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect']) |
| +EXCLUDE = ','.join(['amadan.net/oficina/home/dashboard', 'amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect', 'amadan.net/oficina/home/roster', 'amadan.net/oficina/home/teammode']) |
| def run(args, cwd=ROOT, env=ENV): |