Merge branch 'team-mode' into main
Calls: roster team mode on home/teammode (Home team-members.md Part B; teammode-package.md §7.4), the last of Paul's port order, pinned with teammode, roster and connect at Home main 67c12e3. With the five CALLS_TEAM_* variables (all or none, only beside CALLS_HOME_*), Home's roster decides standing on every request and CALLS_ALLOWED_ADDRESSES only admits local sign-in; the calls_team marker is read before migrations, with a foreign-issuer census; Home-only members come in through connect's Unlinked/HomeOnly hooks with no address; a meeting stands on its host (its creator, or an agent's operator): a removed host's meeting ends for everyone in it, as Paul ruled on 2026-11-01, and its links stop admitting anybody, while an undecidable host refuses new entries with a retryable 503 (the sign-in form under its link included) and holds the call; the call stream re-decides before every delivery and at the lease's end and holds under Unknown; every write that rests on standing runs inside teammode.Guard; Unknown lists are the empty partial list with a notice and items, signalling and the native API retryable no-store 503s. Team mode off is byte-identical (212 responses) except /api/team. Reviewed by Claude Fable 5.1 (claude-fable-5-1) on oficina/meet #31: CHANGES REQUIRED at 8baa6f5, APPROVED at 3414798 (CI passed). Verified canary of 3414798 on team-mode-calls.bds.oncarlos.com with its own bundle and fresh keys, team mode off, Home and APNs off: /api/version v0.1.0-275-g3414798, /api/team {"team_mode":false} no-store, the local sign-in door, signed-out redirects and 403s; team mode on is verified only by the test suite until Home's roster serve is live. Not deployed.
49 files changed,
+4,823
−165
AGENTS.md+38 −0Makefile+1 −1cmd/calls/main.go+6 −1docs/superpowers/specs/2026-09-07-meet-design.md+202 −0go.mod+3 −1go.sum+6 −2internal/calls/agents.go+32 −25internal/calls/api.go+55 −1internal/calls/app.go+33 −2internal/calls/auth.go+32 −3internal/calls/chrome.go+11 −5internal/calls/config.go+25 −1internal/calls/credits_inventory_test.go+1 −1internal/calls/errors.go+5 −0internal/calls/guest.go+27 −5internal/calls/handlers_join.go+13 −0internal/calls/handlers_meetings.go+60 −6internal/calls/handlers_room.go+15 −0internal/calls/handlers_settings.go+10 −0internal/calls/home.go+44 −8internal/calls/hub/authorize.go+11 −0internal/calls/hub/hub.go+16 −1internal/calls/hub/relay.go+10 −2internal/calls/hub/standing_unknown_test.go+50 −0internal/calls/ice.go+20 −0internal/calls/knockpush.go+13 −1internal/calls/native_auth.go+4 −0internal/calls/signal.go+13 −0internal/calls/standing.go+44 −0internal/calls/store.go+172 −98internal/calls/stream.go+31 −0internal/calls/team_access.go+311 −0internal/calls/team_answers.go+94 −0internal/calls/team_call_test.go+849 −0internal/calls/team_config.go+129 −0internal/calls/team_config_test.go+265 −0internal/calls/team_fixture_test.go+290 −0internal/calls/team_guard.go+74 −0internal/calls/team_guard_test.go+300 −0internal/calls/team_home_only.go+76 −0internal/calls/team_host.go+173 −0internal/calls/team_identity_test.go+276 −0internal/calls/team_lease_test.go+287 −0internal/calls/team_links.go+167 −0internal/calls/team_push.go+35 −0internal/calls/team_stream.go+276 −0internal/calls/teamstate/migrations/0001_home_persons.sql+13 −0internal/calls/teamstate/store.go+203 −0internal/calls/templates/index.html+2 −1
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index 98a495a..49a00e7 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -89,6 +89,44 @@ mechanically. |
| candidates and every call fails with `frames` stuck at 0, which reads |
| exactly like a client bug and is not one. |
| +## Team mode (roster, `CALLS_TEAM_*`) |
| + |
| +Spec §16 "Roster team mode" is the whole of it; Home |
| +`implementation/teammode-package.md` §7.4 and `team-members.md` Part B |
| +are its design. With the five `CALLS_TEAM_*` variables set (all or none, |
| +only beside `CALLS_HOME_*`), Home's roster decides standing on every |
| +request and `CALLS_ALLOWED_ADDRESSES` only admits local sign-in (empty |
| +admits nobody, in every Env). Without them nothing in `team_*.go` runs, |
| +every rule above stands, and the one difference is `GET /api/team` |
| +answering `{"team_mode":false}`. Paul's calls.oficina.works and the Mac |
| +and iPhone apps run with team mode off. |
| + |
| +- **Configuration, marker, runtime and probe are `home/teammode`'s** |
| + (`team_config.go`). The marker is read before anything migrates; a team |
| + database stays one. Never "fix" a refused boot by deleting the marker. |
| +- **Standing is the roster's, never the allowlist's or a stored role's** |
| + (`team_access.go`): one `Access` per request, carried on the context. |
| + A removed Home identity is signed out; a guest, and a local account |
| + with no Oficina link, are the non-members they always were. |
| +- **A meeting stands on its host** (`team_host.go`): its creator, or an |
| + agent's operator. A host the roster removes ends the meeting (a system |
| + write) and the call in it; a host it cannot decide refuses new entries |
| + with a retryable 503 and holds the call. Any new path that lets |
| + somebody into a meeting asks `meetingStands` first. |
| +- **Every write that rests on standing runs inside `store.guard`** |
| + (`team_guard.go`), on the Access the caller put on the context: the |
| + member's own, an agent's operator's, or — for a guest's grant — the |
| + host's. `TestTeamEveryWriteRouteRefusesALapseBeforeCommit` lists every |
| + write route; add yours. |
| +- **The call stream re-decides before every delivery and at the lease's |
| + end** (`team_stream.go`), on fresh Accesses (`freshStanding`), and |
| + holds under Unknown: open, heartbeats only, nothing delivered. Its |
| + re-decision timer is set when a decision is made and never by a |
| + heartbeat. Run `make race` for any change to it. |
| +- **Unknown is never "not found"**: lists are the empty partial list with |
| + the notice; items, forms, writes, the native API and the signalling |
| + endpoints are retryable no-store 503s. |
| + |
| ## Serving |
| `rastrillo.Resolve` + `Serve` speak the CARLOS activation contract |
diff --git a/Makefile b/Makefile| index ca6859b..5e8fe46 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -234,6 +234,6 @@ credits: |
| go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \ |
| GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \ |
| -package ./cmd/calls -lucide -onest \ |
| - -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff \ |
| + -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode \ |
| > "$$notices_tmp/notices.json"; \ |
| mv "$$notices_tmp/notices.json" internal/calls/credits/notices.json |
diff --git a/cmd/calls/main.go b/cmd/calls/main.go| index c3695d0..b40f905 100644 |
| --- a/cmd/calls/main.go |
| +++ b/cmd/calls/main.go |
| @@ -18,6 +18,7 @@ import ( |
| "amadan.net/oficina/calls/internal/calls" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| ) |
| func main() { |
| @@ -73,7 +74,11 @@ func run(logger, reportLogger *slog.Logger) error { |
| mailer := newMailer(logger) |
| cfg := calls.Config{ |
| - Home: connect.CredentialsFromEnv("CALLS"), |
| + Home: connect.CredentialsFromEnv("CALLS"), |
| + // Roster team mode: the five CALLS_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("CALLS"), |
| Env: *env, |
| Origin: os.Getenv("CALLS_ORIGIN"), |
| InstanceKey: os.Getenv("CALLS_INSTANCE_KEY"), |
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md| index ec2e073..58b20d4 100644 |
| --- a/docs/superpowers/specs/2026-09-07-meet-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-meet-design.md |
| @@ -3452,3 +3452,205 @@ when not zero or Auto. `quality-summary` prints them per person and, under |
| **Not logged, not stored.** As §15.19; the levels are logged on the device |
| (the browser's console, the apps' `connection` log) with six characters of |
| the peer id. |
| + |
| +--- |
| + |
| +## 16. Roster team mode (2026-11-01) |
| + |
| +🤖 Claude Opus 5.5, for Paul. Home `implementation/team-members.md` Part B |
| +and `implementation/teammode-package.md` §7.4, on `home/teammode` (Home |
| +main 67c12e3). Calls is the last of Paul's port order (Sheets, Slides, |
| +Memoria, Calendar, Calls). Questions for Paul are marked **Paul**. |
| +Reviewed by Claude Fable 5.1 on oficina/meet #31 (CHANGES REQUIRED at |
| +8baa6f5 for the sign-in form under an Unknown host, fixed below; every |
| +deviation accepted). |
| + |
| +### 16.1 What turns it on |
| + |
| +The five `CALLS_TEAM_*` variables (`teammode.EnvNames("CALLS")`): all or |
| +none, and only beside `CALLS_HOME_*`. They are verified against the Home |
| +issuer and consumer and `CALLS_ORIGIN` before anything migrates; the |
| +activation marker (`calls_team`) is read before every boot's migrations, |
| +so an activated database refuses to boot without team configuration or |
| +with another binding. Activation refuses a census that finds a Home |
| +identity from another issuer in `home_identity_links` or |
| +`calls_team_home_persons`. `GET /api/team` is teammode's probe. |
| + |
| +Without the variables nothing below runs. Team mode off answers every |
| +request byte for byte as before (212 responses compared, standalone and |
| +with Home, the native API and the signalling endpoints included), except |
| +`GET /api/team`, which answers `{"team_mode":false}` where it was a 404. |
| + |
| +### 16.2 Standing (§2.3 in team mode) |
| + |
| +`member` standing is the roster's Member, asked on every request through |
| +one `teammode.Access` carried on the request, never an allowlist and |
| +never a stored role (Calls consults no role: it has no owner-only power). |
| +`CALLS_ALLOWED_ADDRESSES` is the local sign-in door and nothing more: an |
| +address on it signs in locally, and stands on the roster only once linked |
| +to an Oficina account (`/account/home`, open in team mode to an |
| +allowlisted, unlinked local account). Alta writes no allowlist for a team |
| +instance, so in practice everybody signs in through Oficina. |
| + |
| +- **NotMember, for a Home identity** (a Home session, or a local account |
| + linked to one): removal. The session is signed out and told so |
| + (`/signin/local?err=removed`), on every page, write, signalling request |
| + and `/signin`. A member never holds a guest grant (§3.2 mints none for |
| + a member), so a guest session would reach nothing. **Paul**: a removed |
| + member can still come back to a meeting as a guest, but only by name |
| + (a meeting that does not require sign-in) or under an address not |
| + linked to their Oficina account; their own linked address signs them |
| + straight out again. |
| +- **NotMember, for anyone the roster does not know** — a named guest, a |
| + local account with no link (an outsider who signed in through a |
| + meeting link): what a non-member always was, a guest standing on the |
| + grants the team's links gave them. |
| +- **Unknown**: the roster could not be read within its lease. Ends |
| + nothing (§16.5). |
| + |
| +A Home-only member (a roster Member with no account here) is created by |
| +connect's `Unlinked` hook on a current Member decision, with no address: |
| +`persons.email` holds a random `home-only:` placeholder (NOT NULL UNIQUE, |
| +additive-only migrations), triggers keep it addressless, undeletable and |
| +disjoint from account links, and their name — what a call's roster shows |
| +the others — is "Oficina account …xxxx". Nothing mails or shows the |
| +placeholder. Calls mails nobody but a person signing in by link, so the |
| +only thing it costs them is local sign-in. |
| + |
| +### 16.3 A meeting stands on its host |
| + |
| +A meeting's links are invitations somebody on the team gave out, so a |
| +meeting stands on its **host**: its creator (`created_by`), or for a |
| +meeting an agent made, the agent's operator — as a Calendar booking page |
| +stands on its host and a Slides presentation on its presenter. |
| + |
| +- Host **Member**: as before. |
| +- Host **NotMember**: the meeting is over. The instance ends it (a system |
| + write, `ended_by = system:host-removed`, every link revoked) and tells |
| + every open stream `lost {reason: "ended"}`, exactly as a member's End. |
| + Its links 404 like any ended meeting's, nobody new is let in, no grant |
| + is minted through them, and no pending join is written for them (the |
| + sign-in form, under a join cookie for one, asks the host before it |
| + reads the address, and settles it too). It is |
| + noticed on the first thing that touches the meeting — a link followed, |
| + a page, a stream's decision, a signal, an ICE fetch, the list (which |
| + settles every listed meeting's host), or the hub's fifteen-second tick |
| + for a quiet call — so within the lease plus a tick. Re-adding the host |
| + does not revive it. |
| +- Host **Unknown**: nothing is ended; every new entry (following a link, |
| + joining by name, signing in through the link — `POST /signin` under its |
| + join cookie, decided before the address is read, so nothing is written |
| + and nothing mailed — a fresh stream, `join`, an ICE fetch, a signal) is |
| + a retryable no-store 503; the call in progress is held (§16.5). |
| + |
| +**The call in progress when its host is removed — RULED 2026-11-01 by |
| +Paul: it ends for everyone in it**, members included, as Slides ends a |
| +removed presenter's talk; the members can start another in one click. |
| +(Fable on #31: after removal the meeting has no host, and keeping it for |
| +the members would need a re-host write that nobody's standing makes |
| +cleanly; if that is ever wanted it is "a present member takes the meeting |
| +over", not "end only the guests".) The host is the creator, not a link's |
| +minter (Fable, accepted): a link is what the meeting hands out. A creator |
| +Calls cannot resolve to a person (anything but `person:` or `agent:`) |
| +stands on nobody and the meeting ends; no such meeting exists in a team |
| +database, which is new. |
| + |
| +### 16.4 Writes |
| + |
| +Every write that rests on standing runs inside `teammode.Guard`, in its |
| +own transaction (`store.guard`): a meeting, a call, a link replaced or |
| +shared, an ending, meeting settings and team defaults, an agent token |
| +minted or revoked, a device registered, a guest's grant (followed link, |
| +named guest, pending join). Whose standing: the member's own; an agent's |
| +operator's; for a guest's grant, the **host's**. A lapse between the |
| +route's gate and the commit is a retryable 503 with nothing written. A |
| +named guest and their grant are one transaction in team mode, so a |
| +refusal leaves neither. Identity rows (a person on first sign-in, a |
| +Home-only person) and sign-in bookkeeping are not guarded. |
| + |
| +### 16.5 Signalling and media (§4, §5 in team mode) |
| + |
| +A participation stands on the meeting's host, and a member-kind one on |
| +the member's own standing too; a guest's own standing is not asked (ruling |
| +14 stands: the participation is the authority once admitted). |
| + |
| +- **The stream** (`GET /m/{sqid}/stream`) re-decides before every delivery |
| + and at the end of every lease (`Access.Remaining`, never under a |
| + second), on fresh Accesses. Member: delivers. NotMember: a removed |
| + member is ended by the hub (`lost {reason: "standing"}`, `gone` to the |
| + room); a removed host ends the meeting. **Unknown: held** — the |
| + connection stays open, carries heartbeats and nothing else, and asks |
| + again every five seconds; what arrives meanwhile is kept and delivered, |
| + in order, only on a Member answer (past 64 events the stream ends |
| + `lost {reason: "buffer"}` and the browser resumes, replaying from the |
| + ring on standing it must have again). A resume under Unknown attaches |
| + and is held too (the hub's `Resume` tolerates `ErrStandingUnknown`), so |
| + the browser's stall counter never reaches "unreachable" during a Home |
| + blip. Terminal events (`lost`, `ended`) are delivered whatever the |
| + standing. |
| +- **Logs.** The hub's tick and the resume probe log a standing read that |
| + failed; one that is merely undecidable (`ErrStandingUnknown`, every |
| + peer every fifteen seconds through a blip) is logged at Debug, a failed |
| + read still at Warn. |
| +- **`POST /m/{sqid}/signal`** and **`GET /m/{sqid}/ice`** are refused with |
| + a retryable 503 under Unknown (the host's or the member's own) — the |
| + browser's queue retries 5xx (§4.6) — and with the not-found body for a |
| + removed host. `leave` is always accepted. |
| +- **What Calls cannot do, said plainly.** Calls signals; it does not carry |
| + media. A peer connection already established — directly, or through |
| + the platform relay on credentials `/ice` minted for up to three hours — |
| + is not Calls' to cut. Ending a participation tells every other browser |
| + `gone`, and they close their connections to it, which is what stops the |
| + media in practice. A modified client that ignored `gone` could keep a |
| + connection to a colluding peer until its relay credentials expire, and |
| + those credentials stay valid for relaying until then. |
| + |
| +### 16.6 Lists, items and the native API (Paul's ruling, 2026-10-28) |
| + |
| +- **The meeting list** (`/`) under Unknown is the partial list with the |
| + notice ("We couldn't check your team access"), and it is always empty: |
| + without standing a member reaches no meeting (Calls has no per-person |
| + shares of a meeting; a guest's grant is for one call, and a guest has |
| + no list). The empty state is withheld. The list asks again after it is |
| + built, of the same Access, and a list built on standing that ran out |
| + since is withheld, not shown beside the notice. |
| +- **NotMember is never partial**: a removed member is signed out, a guest |
| + is sent to `/welcome`. |
| +- **No cross-origin feed exists** in Calls; nothing to make unavailable. |
| +- **Item pages, forms and writes** are retryable no-store 503s under |
| + Unknown (a missing meeting too: never "not found"). |
| +- **The drive surface's JSON list** (`GET /api/v1/meetings`) is a |
| + retryable 503 when partial; an agent stands on its operator's standing, |
| + asked on every request (removed: the one not-found body; Unknown: a |
| + retryable 503 at the gate, for the list and every item alike). |
| +- **Native**: the Mac and iPhone apps point at Paul's server and are |
| + unchanged. Every route they use is standing-checked: `/native/meetings/ |
| + start` and `/native/devices` are member routes (503 under Unknown, |
| + signed out when removed), `/m/{sqid}/info` is an item, and the stream, |
| + signal and ICE endpoints are §16.5's. `/native/exchange` mints a copy of |
| + a browser session as before; standing is asked on every request after. |
| + |
| +### 16.7 Push |
| + |
| +A knock's push (§3.3, `knockpush.go`) is decided on each recipient's |
| +standing when it is sent: only people the roster says are Members now, |
| +never a removed member, nobody under Unknown (a push is said once and |
| +never retried). With no push key configured — every team instance at |
| +first, and today every deployment (`cmd/calls` does not read |
| +`CALLS_APNS_*`) — nothing is sent and nothing breaks. |
| + |
| +### 16.8 Quality telemetry |
| + |
| +Unchanged (§15.26): the reports are keyed by random tags and carry no |
| +person. Team mode adds no identifier to any log line; a Home-only |
| +member's label is a name like any other in a call's roster, which the |
| +reports already never carry. Alta's recipe keeps |
| +`CALLS_QUALITY_REPORTS=off` for team instances until the team's owner and |
| +Paul agree. |
| + |
| +### 16.9 Alta |
| + |
| +`provision/apps.go`: `Roster: true` on Calls; `teamKeys(p, in)` in the |
| +`calls` case (exactly `teammode.EnvNames("CALLS")`); drop |
| +`owner("CALLS_ALLOWED_ADDRESSES")`. `CALLS_DEK`, `CALLS_ZONE`, |
| +`CALLS_QUALITY_REPORTS=off`, the relay and `CALLS_HOME_*` stay. |
diff --git a/go.mod b/go.mod| index 182cd67..7878397 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -4,8 +4,10 @@ go 1.26.0 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| - amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d |
| + amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/oficina/home/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/go-chi/chi/v5 v5.3.2 |
| github.com/keymaildev/signin v0.1.1 |
diff --git a/go.sum b/go.sum| index 3b61db1..47975ca 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,9 +1,13 @@ |
| 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/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/calls/agents.go b/internal/calls/agents.go| index 7513e9f..059ca15 100644 |
| --- a/internal/calls/agents.go |
| +++ b/internal/calls/agents.go |
| @@ -58,7 +58,7 @@ func hashAgentToken(token string) string { |
| // principal is the identity a meeting's creator string is rendered as |
| // on the list (§8.1): the agent's own name, then the operator whose |
| // reach it borrows. |
| -func principal(ag Agent, operator Person) string { return ag.Name + "~" + operator.Email } |
| +func principal(ag Agent, operator Person) string { return ag.Name + "~" + operator.shown() } |
| func actorForAgent(ag Agent) string { return "agent:" + strconv.FormatInt(ag.ID, 10) } |
| @@ -81,26 +81,28 @@ func (s *store) createAgent(ctx context.Context, name string, operator Person) ( |
| } |
| var ag Agent |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var live int64 |
| - if err := agentsOwnedBy(tx.Model(&Agent{}), operator). |
| - Where("revoked_at IS NULL"). |
| - Count(&live).Error; err != nil { |
| - return err |
| - } |
| - if live >= maxLiveAgents { |
| - return errAgentLimit |
| - } |
| - var dup int64 |
| - if err := agentsOwnedBy(tx.Model(&Agent{}), operator). |
| - Where("name = ? AND revoked_at IS NULL", name). |
| - Count(&dup).Error; err != nil { |
| - return err |
| - } |
| - if dup > 0 { |
| - return errAgentDuplicate |
| - } |
| - ag = Agent{Name: name, OperatorPersonID: operator.ID, TokenHash: hash, CreatedAt: s.now().UTC()} |
| - return tx.Create(&ag).Error |
| + return s.guard(ctx, func() error { |
| + var live int64 |
| + if err := agentsOwnedBy(tx.Model(&Agent{}), operator). |
| + Where("revoked_at IS NULL"). |
| + Count(&live).Error; err != nil { |
| + return err |
| + } |
| + if live >= maxLiveAgents { |
| + return errAgentLimit |
| + } |
| + var dup int64 |
| + if err := agentsOwnedBy(tx.Model(&Agent{}), operator). |
| + Where("name = ? AND revoked_at IS NULL", name). |
| + Count(&dup).Error; err != nil { |
| + return err |
| + } |
| + if dup > 0 { |
| + return errAgentDuplicate |
| + } |
| + ag = Agent{Name: name, OperatorPersonID: operator.ID, TokenHash: hash, CreatedAt: s.now().UTC()} |
| + return tx.Create(&ag).Error |
| + }) |
| }) |
| if err != nil { |
| return Agent{}, "", err |
| @@ -128,10 +130,15 @@ func (s *store) agentsFor(ctx context.Context, operator Person) ([]Agent, error) |
| // revokeAgent revokes one of the operator's own agents. False when the |
| // row is not theirs or is already revoked: a 404 shape, never a 403. |
| func (s *store) revokeAgent(ctx context.Context, id int64, operator Person) (bool, error) { |
| - res := agentsOwnedBy(s.g.WithContext(ctx).Model(&Agent{}), operator). |
| - Where("id = ? AND revoked_at IS NULL", id). |
| - Update("revoked_at", s.now().UTC()) |
| - return res.RowsAffected == 1, res.Error |
| + var revoked bool |
| + err := s.guarded(ctx, func(g *gorm.DB) error { |
| + res := agentsOwnedBy(g.Model(&Agent{}), operator). |
| + Where("id = ? AND revoked_at IS NULL", id). |
| + Update("revoked_at", s.now().UTC()) |
| + revoked = res.RowsAffected == 1 |
| + return res.Error |
| + }) |
| + return revoked && err == nil, err |
| } |
| // agentByToken resolves a bearer to its agent and operator. Unknown, |
diff --git a/internal/calls/api.go b/internal/calls/api.go| index be488a0..a694ebb 100644 |
| --- a/internal/calls/api.go |
| +++ b/internal/calls/api.go |
| @@ -1,6 +1,8 @@ |
| package calls |
| import ( |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| "context" |
| "encoding/json" |
| "errors" |
| @@ -144,7 +146,23 @@ func (a *app) requireAgent(next http.Handler) http.Handler { |
| a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "token") |
| return |
| } |
| - if !a.isMember(operator) { |
| + if a.team != nil { |
| + // Team mode: the operator's standing is the roster's, asked |
| + // now; it is carried for the writes' guard and the list's |
| + // after-check (team_guard.go, apiListMeetings). |
| + acc := a.standingOf(r.Context(), operator.ID) |
| + switch acc.State() { |
| + case roster.NotMember: |
| + a.refuseAPI(w, r.WithContext(withAgent(r.Context(), ag, operator)), |
| + http.StatusNotFound, apiNotFound(), "reach") |
| + return |
| + case roster.Unknown: |
| + a.logger.Warn("calls: api refused", "agent_id", ag.ID, "outcome", "standing-unknown") |
| + teamUnavailableAPI(w) |
| + return |
| + } |
| + r = r.WithContext(teammode.WithAccess(r.Context(), acc)) |
| + } else if !a.isMember(operator) { |
| a.refuseAPI(w, r.WithContext(withAgent(r.Context(), ag, operator)), |
| http.StatusNotFound, apiNotFound(), "reach") |
| return |
| @@ -248,6 +266,16 @@ func (a *app) apiListMeetings(w http.ResponseWriter, r *http.Request) { |
| a.apiServerError(w, r, "list meetings", err) |
| return |
| } |
| + if a.team != nil { |
| + views = a.settleHosts(r.Context(), views) |
| + // A JSON list cannot carry the partial notice, so a list built |
| + // while standing lapsed is a retryable 503, never a short one |
| + // (Paul's ruling; asked after building, of the same Access). |
| + if acc, _ := teammode.FromContext(r.Context()); acc.Partial() { |
| + teamUnavailableAPI(w) |
| + return |
| + } |
| + } |
| out := make([]apiMeetingBody, 0, len(views)) |
| for _, v := range views { |
| out = append(out, a.apiBody(v)) |
| @@ -287,6 +315,10 @@ func (a *app) apiCreateMeeting(w http.ResponseWriter, r *http.Request) { |
| ap, _ := currentAgent(r) |
| m, token, err := a.store.createMeeting(r.Context(), title, start, actorForAgent(ap.agent)) |
| + if isTeamUnavailable(err) { |
| + teamUnavailableAPI(w) |
| + return |
| + } |
| if err != nil { |
| a.apiServerError(w, r, "create meeting", err) |
| return |
| @@ -335,6 +367,10 @@ func (a *app) apiReplaceLink(w http.ResponseWriter, r *http.Request) { |
| // transaction, which answers errMeetingEnded. |
| ap, _ := currentAgent(r) |
| token, err := a.store.replaceLink(r.Context(), m.ID, actorForAgent(ap.agent)) |
| + if isTeamUnavailable(err) { |
| + teamUnavailableAPI(w) |
| + return |
| + } |
| if errors.Is(err, errMeetingEnded) { |
| a.refuseAPI(w, r, http.StatusConflict, map[string]any{"error": "ended"}, "ended") |
| return |
| @@ -368,6 +404,10 @@ func (a *app) apiEndMeeting(w http.ResponseWriter, r *http.Request) { |
| // ends gets the 200. |
| ap, _ := currentAgent(r) |
| ended, err := a.store.endMeeting(r.Context(), m.ID, actorForAgent(ap.agent)) |
| + if isTeamUnavailable(err) { |
| + teamUnavailableAPI(w) |
| + return |
| + } |
| if err != nil { |
| a.apiServerError(w, r, "end meeting", err) |
| return |
| @@ -418,6 +458,20 @@ func (a *app) apiMeetingFor(w http.ResponseWriter, r *http.Request) (Meeting, bo |
| a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "meeting") |
| return Meeting{}, false |
| } |
| + if a.team != nil && m.EndedAt == nil { |
| + // A meeting stands on its host (team_host.go): one whose host |
| + // has left is ended now, and read again so the answer says so. |
| + switch _, st := a.meetingStands(r.Context(), m); st { |
| + case roster.Unknown: |
| + teamUnavailableAPI(w) |
| + return Meeting{}, false |
| + case roster.NotMember: |
| + if m, ok, err = a.store.meetingBySqid(r.Context(), sqid); err != nil || !ok { |
| + a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "meeting") |
| + return Meeting{}, false |
| + } |
| + } |
| + } |
| return m, true |
| } |
diff --git a/internal/calls/app.go b/internal/calls/app.go| index 65693ca..ec624b2 100644 |
| --- a/internal/calls/app.go |
| +++ b/internal/calls/app.go |
| @@ -5,6 +5,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/estilo.git/sky" |
| "amadan.net/oficina/estilo.git/theme" |
| + "amadan.net/oficina/home/teammode" |
| "context" |
| "crypto/rand" |
| "encoding/hex" |
| @@ -104,6 +105,11 @@ type app struct { |
| // while a request is reading it. build stores rc.relay once; |
| // production never stores again. Read it with relayRegions(). |
| relay atomic.Value |
| + |
| + // team is the roster runtime with team mode on, nil off |
| + // (team_config.go). Every team-mode branch keys on it, so with team |
| + // mode off none of them runs. |
| + team *teamRuntime |
| } |
| // relayRegions is the parsed contract, swapped atomically so a test can |
| @@ -381,7 +387,14 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| ParameterizedQueries: true, |
| }) |
| - migrated, err := migrate.Apply(context.Background(), d, BootSchema) |
| + // The team marker is 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_config.go). |
| + boot, err := teamBootSchema(context.Background(), d.Writer(), rc.team, BootSchema) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("calls: team mode: %w", err) |
| + } |
| + migrated, err := migrate.Apply(context.Background(), d, boot) |
| if err != nil { |
| return nil, nil, err |
| } |
| @@ -465,6 +478,10 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| a.signinMail.close() |
| return nil, nil, err |
| } |
| + if err := a.configureTeam(); err != nil { |
| + a.signinMail.close() |
| + return nil, nil, fmt.Errorf("calls: team mode: %w", err) |
| + } |
| if err := a.wireNativeAuth(); err != nil { |
| a.signinMail.close() |
| @@ -494,6 +511,9 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| // page. apiRoutes says why that is safe — this surface honours no |
| // cookie, so there is no ambient credential for CSRF to protect. |
| r.Group(a.apiRoutes) |
| + // The team readiness probe: unauthenticated, outside every session |
| + // middleware, and {"team_mode":false} with team mode off. |
| + r.Get(teammode.ProbePath, a.teamProbe) |
| r.Post("/native/request", a.nativeRequest) |
| r.Post("/native/exchange", a.nativeExchange) |
| @@ -561,9 +581,20 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| r.Post("/m/{sqid}/remove/{peer}", a.remove) |
| r.Get("/m/{sqid}/takeover", a.confirmTakeover) |
| r.Post("/m/{sqid}/takeover", a.takeover) |
| + if a.team != nil { |
| + // Team mode: linking a local account is the local door's |
| + // business, not standing's (team_access.go). |
| + r.Group(func(r chi.Router) { |
| + r.Use(a.requireLinkable) |
| + r.Get("/account/home", a.home.routes.Account) |
| + r.Post("/account/home", a.home.routes.LinkStart) |
| + r.Get("/account/home/confirm", a.home.bridge.ConfirmPage) |
| + r.Post("/account/home/confirm", a.home.routes.ConfirmPost) |
| + }) |
| + } |
| r.Group(func(r chi.Router) { |
| r.Use(a.requireMember) |
| - if a.home != nil { |
| + if a.home != nil && a.team == nil { |
| r.Get("/account/home", a.home.routes.Account) |
| r.Post("/account/home", a.home.routes.LinkStart) |
| r.Get("/account/home/confirm", a.home.bridge.ConfirmPage) |
diff --git a/internal/calls/auth.go b/internal/calls/auth.go| index f72f8c5..0fd103f 100644 |
| --- a/internal/calls/auth.go |
| +++ b/internal/calls/auth.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/estilo.git/sky" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/keymaildev/signin" |
| @@ -98,6 +99,9 @@ func (a *app) authorize(address string) bool { |
| func (a *app) gateBegin(next http.HandlerFunc) http.HandlerFunc { |
| return func(w http.ResponseWriter, r *http.Request) { |
| _ = r.ParseForm() |
| + if a.team != nil && !a.teamJoinCookieStands(w, r) { |
| + return |
| + } |
| address := r.FormValue("address") |
| // Syntax first. The gate below answers every refusal as "sent", so |
| // a malformed address used to go straight to "Check your email" |
| @@ -166,7 +170,7 @@ func (a *app) mayRequestLink(w http.ResponseWriter, r *http.Request, address str |
| if !hasCookie { |
| return member |
| } |
| - link, _, live, err := a.store.liveLinkByHash(r.Context(), ck.TokenHash) |
| + link, m, live, err := a.store.liveLinkByHash(r.Context(), ck.TokenHash) |
| if err != nil { |
| a.logger.Error("calls: link for cookie", "err", err) |
| return member |
| @@ -174,6 +178,12 @@ func (a *app) mayRequestLink(w http.ResponseWriter, r *http.Request, address str |
| if !live { |
| return member |
| } |
| + if a.team != nil && a.hostAccess(r.Context(), m).State() != roster.Member { |
| + // Team mode: a link whose host does not stand now admits nobody |
| + // new, so it is answered as a dead link is (team_host.go). The |
| + // work does not depend on the address. |
| + return member |
| + } |
| may := true |
| if !member { |
| now := a.store.now() |
| @@ -235,6 +245,12 @@ func (a *app) requirePerson(next http.Handler) http.Handler { |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| return |
| } |
| + if a.team != nil { |
| + // Team mode: the roster's standing, asked once and carried on |
| + // the request (team_access.go). |
| + a.teamRequirePerson(w, r, s, next) |
| + return |
| + } |
| p, err := a.personForSession(r.Context(), s) |
| if errors.Is(err, errHomeRemoved) { |
| // A Home identity that is definitely no longer admitted: end |
| @@ -265,6 +281,10 @@ func currentPerson(r *http.Request) (Person, bool) { |
| // requireMember is spec §2.5's first row: current member standing. |
| func (a *app) requireMember(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if a.team != nil { |
| + a.requireTeamMember(w, r, next) |
| + return |
| + } |
| p, ok := currentPerson(r) |
| if !ok || !a.isMember(p) { |
| a.notFound(w, r) |
| @@ -447,6 +467,10 @@ func (a *app) continueSignedIn(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if dest, handled := a.continuePending(w, r, p); handled { |
| + if dest == "" { |
| + // Team mode answered it (a retryable 503). |
| + return |
| + } |
| http.Redirect(w, r, dest, http.StatusSeeOther) |
| return |
| } |
| @@ -458,7 +482,9 @@ func (a *app) continueSignedIn(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, ret, http.StatusSeeOther) |
| return |
| } |
| - if a.isMember(p) { |
| + // In team mode Unknown goes to the list too, which says it is |
| + // partial; only a definite non-member is sent to /welcome. |
| + if a.memberState(r.Context(), p) != roster.NotMember { |
| http.Redirect(w, r, "/", http.StatusSeeOther) |
| return |
| } |
| @@ -478,6 +504,9 @@ func (a *app) continuePending(w http.ResponseWriter, r *http.Request, p Person) |
| if !ok { |
| return "", false |
| } |
| + if a.team != nil { |
| + return a.teamContinuePending(w, r, p, pend) |
| + } |
| dest, err := a.store.consumePending(r.Context(), p, pend, a.isMember(p)) |
| if err != nil { |
| a.logger.Error("calls: consume pending", "err", err) |
| @@ -488,7 +517,7 @@ func (a *app) continuePending(w http.ResponseWriter, r *http.Request, p Person) |
| func (a *app) welcome(w http.ResponseWriter, r *http.Request) { |
| p, _ := currentPerson(r) |
| - render(w, "welcome", a.page(r, titled("You’re signed in"), map[string]any{"Email": p.Email})) |
| + render(w, "welcome", a.page(r, titled("You’re signed in"), map[string]any{"Email": p.shown()})) |
| } |
| // signedOut serves GET /signed-out standalone: where Sign out lands. |
diff --git a/internal/calls/chrome.go b/internal/calls/chrome.go| index 844fe7d..8df438d 100644 |
| --- a/internal/calls/chrome.go |
| +++ b/internal/calls/chrome.go |
| @@ -125,7 +125,7 @@ func (a *app) page(r *http.Request, f frame, data map[string]any) map[string]any |
| v = a.viewerOf(r) |
| } |
| if v.signedIn() { |
| - data["Viewer"] = Viewer{Email: v.person.Email, Member: a.isMember(v.person)} |
| + data["Viewer"] = Viewer{Email: v.person.shown(), Member: a.memberNow(r.Context(), v.person)} |
| } |
| data["Frame"] = a.frameFor(r, v, f) |
| return data |
| @@ -156,7 +156,7 @@ func (a *app) frameFor(r *http.Request, v viewer, f frame) Frame { |
| case v.signedIn(): |
| bar.Account = a.account(r, v) |
| bar.Switcher = a.switcher() |
| - if a.isMember(v.person) { |
| + if a.memberNow(r.Context(), v.person) { |
| bar.Nav = a.nav(r) |
| bar.NavLabel = "Calls" |
| } |
| @@ -200,9 +200,9 @@ func returnTarget(r *http.Request) string { |
| // be a second label to keep in step. |
| func (a *app) account(r *http.Request, v viewer) *chrome.Account { |
| acc := &chrome.Account{ |
| - TriggerLabel: "Account: " + v.person.Email, |
| - Initials: chrome.Initials("", v.person.Email), |
| - Address: v.person.Email, |
| + TriggerLabel: "Account: " + v.person.shown(), |
| + Initials: chrome.Initials("", v.person.shown()), |
| + Address: v.person.shown(), |
| Labels: chrome.AccountLabels{SignedInAs: "Signed in as", Appearance: "Appearance", Help: "Help"}, |
| Appearance: &chrome.AppearanceMenu{ |
| Action: "/appearance", |
| @@ -226,6 +226,12 @@ func (a *app) account(r *http.Request, v viewer) *chrome.Account { |
| // emailed link still signs in a linked account). The link lookup is one |
| // query on the UNIQUE (issuer, person_id) index; an error offers nothing. |
| func (a *app) offersHomeLink(r *http.Request, v viewer) bool { |
| + if a.team != nil { |
| + // Team mode: the link page is the local door's admitted, unlinked |
| + // accounts' (team_access.go's linkable). |
| + t, ok := teamReqFrom(r.Context()) |
| + return ok && t.person.ID == v.person.ID && a.linkable(t) |
| + } |
| if a.home == nil || !v.signedIn() || !a.isMember(v.person) || (v.method != "magiclink" && v.method != "keymail") { |
| return false |
| } |
diff --git a/internal/calls/config.go b/internal/calls/config.go| index 6f93536..34136a7 100644 |
| --- a/internal/calls/config.go |
| +++ b/internal/calls/config.go |
| @@ -5,10 +5,13 @@ import ( |
| "encoding/base64" |
| "fmt" |
| "log/slog" |
| + "net/http" |
| "strings" |
| "time" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/mail" |
| "amadan.net/oficina/calls/internal/calls/relay" |
| @@ -25,6 +28,17 @@ const EnvDevelopment = "development" |
| // development, per spec §7.1. |
| type Config struct { |
| Home *connect.Credentials |
| + // Team is roster team mode's configuration (teammode.ConfigFromEnv |
| + // with prefix CALLS: the five CALLS_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 |
| // Env is "development" or anything else (treated as production). |
| Env string |
| // Origin is the app's external origin, scheme included |
| @@ -37,7 +51,9 @@ type Config struct { |
| // CALLS_DEK, set with `carlos secrets set`. |
| DEK string |
| // AllowedAddresses is the team: the addresses that are members. |
| - // CALLS_ALLOWED_ADDRESSES, comma-separated. |
| + // CALLS_ALLOWED_ADDRESSES, comma-separated. In team mode it is |
| + // optional and only admits local sign-in: empty admits nobody |
| + // locally, in every Env, and the roster decides standing. |
| AllowedAddresses []string |
| // The Apple push key, for telling a member who is not in the room |
| @@ -96,6 +112,8 @@ var devDEK = make([]byte, 32) |
| // default applied. |
| type resolved struct { |
| home *connect.DecodedCredentials |
| + // team is the verified team configuration, nil with team mode off. |
| + team *teammode.Settings |
| Config |
| instanceKey string |
| dek []byte |
| @@ -205,6 +223,12 @@ func resolve(cfg Config) (resolved, error) { |
| if err != nil { |
| return out, err |
| } |
| + // Team mode (team_config.go): verified against the Home credentials |
| + // just decoded, before anything is migrated. Off, this is nil. |
| + out.team, err = teamSettings(cfg.Team, out.home, out.Origin) |
| + if err != nil { |
| + return out, fmt.Errorf("calls: team configuration: %w", err) |
| + } |
| return out, nil |
| } |
diff --git a/internal/calls/credits_inventory_test.go b/internal/calls/credits_inventory_test.go| index ec91635..bd4821e 100644 |
| --- a/internal/calls/credits_inventory_test.go |
| +++ b/internal/calls/credits_inventory_test.go |
| @@ -60,7 +60,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) { |
| if err != nil { |
| t.Fatal("production dependency graph unavailable", err) |
| } |
| - inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true}) |
| + inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/calls/errors.go b/internal/calls/errors.go| index a3c778f..d856eb5 100644 |
| --- a/internal/calls/errors.go |
| +++ b/internal/calls/errors.go |
| @@ -41,6 +41,9 @@ const ( |
| kindMeeting |
| // kindStatus: the page for the status itself (5xx). |
| kindStatus |
| + // kindTeam: team mode's retryable 503, when the roster could not be |
| + // read within its lease (team_answers.go). |
| + kindTeam |
| ) |
| // errorWords is one row of §3.2: the title part, the heading, the body. |
| @@ -50,6 +53,8 @@ type errorWords struct { |
| func errorCopy(status int, kind errorKind) errorWords { |
| switch { |
| + case kind == kindTeam: |
| + return errorWords{"Try again in a moment", "We couldn’t check your team access", "Calls couldn’t confirm you’re on this team just now. Try again in a moment."} |
| case status == http.StatusNotFound && kind == kindMeeting: |
| return errorWords{"Meeting not available", "This meeting isn’t available", "It may have ended, or it hasn’t been shared with you."} |
| case status == http.StatusNotFound: |
diff --git a/internal/calls/guest.go b/internal/calls/guest.go| index 9617b5a..abd4674 100644 |
| --- a/internal/calls/guest.go |
| +++ b/internal/calls/guest.go |
| @@ -1,6 +1,7 @@ |
| package calls |
| import ( |
| + "amadan.net/oficina/home/teammode" |
| "net/http" |
| "strconv" |
| "strings" |
| @@ -46,6 +47,16 @@ func (a *app) joinGuest(w http.ResponseWriter, r *http.Request) { |
| a.ErrorPage(w, r, 404, "") |
| return |
| } |
| + ctx := r.Context() |
| + if a.team != nil { |
| + // A link stands on its meeting's host, and so does the grant |
| + // it gives (team_links.go). |
| + host, ok := a.teamLinkHost(w, r, m) |
| + if !ok { |
| + return |
| + } |
| + ctx = teammode.WithAccess(ctx, host) |
| + } |
| if m.RequireSignin { |
| a.setJoinCookie(w, link.TokenHash) |
| http.Redirect(w, r, signinPath, 303) |
| @@ -57,12 +68,23 @@ func (a *app) joinGuest(w http.ResponseWriter, r *http.Request) { |
| a.guestPage(w, r, m, token, name, "Enter your name (up to 80 characters).") |
| return |
| } |
| - p, err := a.store.createGuest(r.Context(), name) |
| - if err != nil { |
| - a.ErrorPage(w, r, 500, "") |
| - return |
| + var p Person |
| + if a.team != nil { |
| + // The guest and their grant in one transaction, on the host's |
| + // standing: a refusal leaves neither (team_links.go). |
| + p, live, err = a.store.guestWithGrant(ctx, name, link.ID) |
| + if isTeamUnavailable(err) { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + } else { |
| + p, err = a.store.createGuest(r.Context(), name) |
| + if err != nil { |
| + a.ErrorPage(w, r, 500, "") |
| + return |
| + } |
| + _, live, err = a.store.mintGrantViaLink(ctx, link.ID, p.ID) |
| } |
| - _, live, err = a.store.mintGrantViaLink(r.Context(), link.ID, p.ID) |
| if err != nil { |
| a.ErrorPage(w, r, 500, "") |
| return |
diff --git a/internal/calls/handlers_join.go b/internal/calls/handlers_join.go| index b84390f..9b3ca00 100644 |
| --- a/internal/calls/handlers_join.go |
| +++ b/internal/calls/handlers_join.go |
| @@ -1,6 +1,7 @@ |
| package calls |
| import ( |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "errors" |
| "html/template" |
| @@ -24,6 +25,14 @@ func (a *app) followLink(w http.ResponseWriter, r *http.Request) { |
| a.ErrorPage(w, r, http.StatusNotFound, "") |
| return |
| } |
| + var host *teammode.Access |
| + if a.team != nil { |
| + // A link stands on its meeting's host (team_links.go). |
| + var ok bool |
| + if host, ok = a.teamLinkHost(w, r, m); !ok { |
| + return |
| + } |
| + } |
| id, signedIn := a.auth.SessionFrom(r) |
| if !signedIn { |
| a.setJoinCookie(w, link.TokenHash) |
| @@ -34,6 +43,10 @@ func (a *app) followLink(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, signinPath, http.StatusSeeOther) |
| return |
| } |
| + if a.team != nil { |
| + a.teamFollowSignedIn(w, r, sessions.Session{Subject: id.Address, Method: string(id.Method), AuthTime: id.AuthTime, At: id.At}, link, m, host) |
| + return |
| + } |
| p, err := a.personForSession(r.Context(), sessions.Session{Subject: id.Address, Method: string(id.Method), AuthTime: id.AuthTime, At: id.At}) |
| if errors.Is(err, errHomeIdentity) { |
| a.ErrorPage(w, r, http.StatusNotFound, "") |
diff --git a/internal/calls/handlers_meetings.go b/internal/calls/handlers_meetings.go| index e1604d7..2b6c118 100644 |
| --- a/internal/calls/handlers_meetings.go |
| +++ b/internal/calls/handlers_meetings.go |
| @@ -1,6 +1,7 @@ |
| package calls |
| import ( |
| + "amadan.net/oficina/home/roster" |
| "errors" |
| "net/http" |
| "net/url" |
| @@ -59,7 +60,9 @@ func (a *app) fmtStart(t *time.Time) string { |
| func (a *app) index(w http.ResponseWriter, r *http.Request) { |
| p, ok := currentPerson(r) |
| - if !ok || !a.isMember(p) { |
| + // In team mode Unknown is the partial list (renderIndex), never |
| + // /welcome, which would tell a member they are not one. |
| + if !ok || a.memberState(r.Context(), p) == roster.NotMember { |
| http.Redirect(w, r, "/welcome", http.StatusSeeOther) |
| return |
| } |
| @@ -67,11 +70,23 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) { |
| } |
| func (a *app) renderIndex(w http.ResponseWriter, r *http.Request, titleErr, startErr string) { |
| - views, err := a.store.listMeetings(r.Context()) |
| - if err != nil { |
| - a.logger.Error("calls: list meetings", "err", err) |
| - a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| - return |
| + var views []meetingView |
| + if p, _ := currentPerson(r); a.memberNow(r.Context(), p) { |
| + var err error |
| + views, err = a.store.listMeetings(r.Context()) |
| + if err != nil { |
| + a.logger.Error("calls: list meetings", "err", err) |
| + a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| + return |
| + } |
| + views = a.settleHosts(r.Context(), views) |
| + } |
| + // Asked after the list is built, of the same Access (team_answers.go): |
| + // a lease that lapsed while listing makes the page partial, and a |
| + // partial page lists nothing. |
| + partial := a.requestPartial(r) |
| + if partial { |
| + views = nil |
| } |
| type row struct { |
| Sqid, Title, Starts string |
| @@ -93,6 +108,7 @@ func (a *app) renderIndex(w http.ResponseWriter, r *http.Request, titleErr, star |
| } |
| } |
| render(w, "index", a.page(r, frame{}, map[string]any{ |
| + "Partial": partial, "PartialTitle": partialTitle, "PartialBody": partialBody, |
| "Upcoming": upcoming, "Ended": ended, "Zone": a.cfg.Zone, |
| "TitleError": titleErr, "StartError": startErr, "HomeEnabled": a.showHomeConnection(r), |
| })) |
| @@ -116,6 +132,9 @@ func (a *app) createMeeting(w http.ResponseWriter, r *http.Request) { |
| } |
| p, _ := currentPerson(r) |
| m, token, err := a.store.createMeeting(r.Context(), title, start, actorFor(p)) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("calls: create meeting", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| @@ -174,6 +193,9 @@ func (a *app) startCall(w http.ResponseWriter, r *http.Request) { |
| p, _ := currentPerson(r) |
| title := callTitle(a.store.now(), callZone(r.PostFormValue("zone")), a.cfg.zone) |
| m, token, err := a.store.createCall(r.Context(), title, actorFor(p)) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("calls: start call", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| @@ -200,6 +222,13 @@ func (a *app) shareMeeting(w http.ResponseWriter, r *http.Request) { |
| } |
| p, _ := currentPerson(r) |
| token, err := a.store.shareLink(r.Context(), m.ID, actorFor(p)) |
| + if a.team != nil && isTeamUnavailable(err) && r.Header.Get("Accept") == "application/json" { |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if errors.Is(err, errMeetingEnded) { |
| a.ErrorPage(w, r, http.StatusNotFound, "") |
| return |
| @@ -232,9 +261,28 @@ func (a *app) meetingForMember(w http.ResponseWriter, r *http.Request) (Meeting, |
| return Meeting{}, false |
| } |
| if !ok { |
| + if a.requestPartial(r) { |
| + a.teamUnavailable(w, r) |
| + return Meeting{}, false |
| + } |
| a.ErrorPage(w, r, http.StatusNotFound, "") |
| return Meeting{}, false |
| } |
| + if a.team != nil && m.EndedAt == nil { |
| + // A meeting stands on its host (team_host.go): one whose host |
| + // has left is ended now, and read again so this screen sees it. |
| + switch _, st := a.meetingStands(r.Context(), m); st { |
| + case roster.Unknown: |
| + a.teamUnavailable(w, r) |
| + return Meeting{}, false |
| + case roster.NotMember: |
| + m, ok, err = a.store.meetingBySqid(r.Context(), m.Sqid) |
| + if err != nil || !ok { |
| + a.ErrorPage(w, r, http.StatusNotFound, "") |
| + return Meeting{}, false |
| + } |
| + } |
| + } |
| return m, true |
| } |
| @@ -262,6 +310,9 @@ func (a *app) replaceLink(w http.ResponseWriter, r *http.Request) { |
| } |
| p, _ := currentPerson(r) |
| token, err := a.store.replaceLink(r.Context(), m.ID, actorFor(p)) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| // The screen's own answer for an ended meeting is the not-found |
| // page, above; a meeting that ended between that read and the write |
| // gets the same page rather than a 500, since the store now settles |
| @@ -303,6 +354,9 @@ func (a *app) endMeeting(w http.ResponseWriter, r *http.Request) { |
| // bool endMeeting now returns is the API's 409 (review S5-2), which |
| // this side has never had and does not gain here. |
| if _, err := a.store.endMeeting(r.Context(), m.ID, actorFor(p)); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.logger.Error("calls: end meeting", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| return |
diff --git a/internal/calls/handlers_room.go b/internal/calls/handlers_room.go| index fd61ea1..c0705ef 100644 |
| --- a/internal/calls/handlers_room.go |
| +++ b/internal/calls/handlers_room.go |
| @@ -22,11 +22,22 @@ func (a *app) roomAccess(w http.ResponseWriter, r *http.Request) (Meeting, Perso |
| return Meeting{}, Person{}, StandingNone, false |
| } |
| if !ok || m.EndedAt != nil { |
| + if a.requestPartial(r) { |
| + // Team mode, standing Unknown: whether this meeting is |
| + // there for this person cannot be said, so neither can |
| + // "not found" (team_answers.go). |
| + a.teamUnavailable(w, r) |
| + return Meeting{}, Person{}, StandingNone, false |
| + } |
| a.ErrorPage(w, r, http.StatusNotFound, "") |
| return Meeting{}, Person{}, StandingNone, false |
| } |
| p, _ := currentPerson(r) |
| st, err := a.standingFor(r.Context(), p, m) |
| + if a.team != nil && isTeamUnavailable(err) { |
| + a.teamUnavailable(w, r) |
| + return Meeting{}, Person{}, StandingNone, false |
| + } |
| if err != nil { |
| a.logger.Error("calls: standing", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| @@ -231,6 +242,10 @@ func (a *app) takeover(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| st, err := a.standingFor(r.Context(), p, m) |
| + if a.team != nil && isTeamUnavailable(err) { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("calls: takeover: standing", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
diff --git a/internal/calls/handlers_settings.go b/internal/calls/handlers_settings.go| index 5d22145..bcf3c0a 100644 |
| --- a/internal/calls/handlers_settings.go |
| +++ b/internal/calls/handlers_settings.go |
| @@ -80,6 +80,7 @@ func (a *app) createAgentHandler(w http.ResponseWriter, r *http.Request) { |
| a.renderSettings(w, r, http.StatusUnprocessableEntity, name, "You already have 20 live agents. Revoke one before creating another.") |
| case errors.Is(err, errAgentDuplicate): |
| a.renderSettings(w, r, http.StatusUnprocessableEntity, name, "You already have a live agent with that name.") |
| + case a.guardRefused(w, r, err): |
| default: |
| a.logger.Error("calls: create agent", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| @@ -145,6 +146,9 @@ func (a *app) revokeAgentHandler(w http.ResponseWriter, r *http.Request) { |
| // error, and that is not this handler's business to distinguish |
| // from the first — ownership was already settled above. |
| if _, err := a.store.revokeAgent(r.Context(), ag.ID, p); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.logger.Error("calls: revoke agent", "err", err) |
| a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| return |
| @@ -154,6 +158,9 @@ func (a *app) revokeAgentHandler(w http.ResponseWriter, r *http.Request) { |
| func (a *app) saveDefaults(w http.ResponseWriter, r *http.Request) { |
| if err := a.store.saveMeetingDefaults(r.Context(), r.PostFormValue("require_signin") == "on", r.PostFormValue("waiting_room") == "on"); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.ErrorPage(w, r, 500, "") |
| return |
| } |
| @@ -181,6 +188,9 @@ func (a *app) saveSettings(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if err := a.store.saveMeetingSettings(r.Context(), m.ID, r.PostFormValue("require_signin") == "on", r.PostFormValue("waiting_room") == "on"); err != nil { |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| a.ErrorPage(w, r, 500, "") |
| return |
| } |
diff --git a/internal/calls/home.go b/internal/calls/home.go| index 647b4d5..e4e0bee 100644 |
| --- a/internal/calls/home.go |
| +++ b/internal/calls/home.go |
| @@ -11,7 +11,6 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| - "amadan.net/oficina/home/handoff" |
| "amadan.net/rastrillo/rastrillo/csrf" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -36,7 +35,7 @@ func (a *app) wireHome() error { |
| if h == nil { |
| return nil |
| } |
| - if _, err := migrate.Apply(context.Background(), a.db, migrate.Merge(migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace))); err != nil { |
| + if _, err := migrate.Apply(context.Background(), a.db, homeSchema()); err != nil { |
| return errHomeIdentity |
| } |
| sess, err := sessions.New(sessions.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, SigninPath: signinPath, Logger: a.logger}) |
| @@ -50,7 +49,8 @@ func (a *app) wireHome() error { |
| } |
| return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil |
| } |
| - b, err := connect.New(connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: h.Issuer, ConsumerID: h.ConsumerID, Namespace: "oficina/calls", SessionCookie: sess.CookieName(), Keys: h.Keys, DEK: h.DEK, ReadSession: read, |
| + teamOn := a.cfg.team != nil |
| + cfg := connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: h.Issuer, ConsumerID: h.ConsumerID, Namespace: homeNamespace, SessionCookie: sess.CookieName(), Keys: h.Keys, DEK: h.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}) |
| }, |
| @@ -59,7 +59,16 @@ func (a *app) wireHome() error { |
| return connect.Person{}, errHomeIdentity |
| } |
| p, err := a.store.existingHomePerson(ctx, s.Subject) |
| - if err != nil || !a.isMember(p) { |
| + if err != nil { |
| + return connect.Person{}, errHomeIdentity |
| + } |
| + // Team mode: the allowlist is the local door, and a local |
| + // account it admits may link (team_access.go's linkable); |
| + // standing is the roster's, asked on every request. |
| + if teamOn && !a.allowNow().allows(p.Email) { |
| + return connect.Person{}, errHomeIdentity |
| + } |
| + if !teamOn && !a.isMember(p) { |
| return connect.Person{}, errHomeIdentity |
| } |
| return connect.Person{ID: p.ID, Label: p.Email}, nil |
| @@ -69,15 +78,25 @@ func (a *app) wireHome() error { |
| if err != nil { |
| return "", err |
| } |
| - if !a.isMember(p) { |
| + // 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 |
| + // CALLS_ALLOWED_ADDRESSES to resolve. |
| + if !teamOn && !a.isMember(p) { |
| return "", sql.ErrNoRows |
| } |
| return p.Email, nil |
| - }, Render: a.renderHome}) |
| + }, Render: a.renderHome} |
| + if teamOn { |
| + // 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 errHomeIdentity |
| } |
| - routes, err := connect.NewRoutes(b, connect.RoutesConfig{LocalLandingPath: "/continue", Namespace: "oficina/calls", Origin: a.cfg.Origin, Issuer: h.Issuer, FormPolicy: homeFormPolicy(h.Issuer), SessionCookie: sess.CookieName(), DEK: h.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.localSignin, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome}) |
| + routes, err := connect.NewRoutes(b, connect.RoutesConfig{LocalLandingPath: "/continue", Namespace: homeNamespace, Origin: a.cfg.Origin, Issuer: h.Issuer, FormPolicy: homeFormPolicy(h.Issuer), SessionCookie: sess.CookieName(), DEK: h.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.localSignin, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome}) |
| if err != nil { |
| return errHomeIdentity |
| } |
| @@ -106,6 +125,11 @@ func (a *app) personForSession(ctx context.Context, s sessions.Session) (Person, |
| return Person{}, errHomeRemoved |
| } |
| if err != nil { |
| + if a.team != nil { |
| + // Storage, not a refusal: a retryable 503, never a |
| + // sign-out (team_access.go). |
| + return Person{}, errTeamUnavailable |
| + } |
| return Person{}, errHomeIdentity |
| } |
| p, err := a.store.homePersonByID(ctx, a.db.Writer(), linked.ID) |
| @@ -113,8 +137,16 @@ func (a *app) personForSession(ctx context.Context, s sessions.Session) (Person, |
| return Person{}, errHomeRemoved |
| } |
| if err != nil { |
| + if a.team != nil { |
| + return Person{}, errTeamUnavailable |
| + } |
| return Person{}, errHomeIdentity |
| } |
| + if a.team != nil { |
| + // Identity only: who this subject is here. Whether they may |
| + // enter is the roster's, asked by the caller. |
| + return p, nil |
| + } |
| if !a.isMember(p) { |
| return Person{}, errHomeRemoved |
| } |
| @@ -132,7 +164,11 @@ func (a *app) personForSession(ctx context.Context, s sessions.Session) (Person, |
| // session cookie, and the destination would refuse it again — the loop |
| // Astra found in Docs (#65, finding 1) and Sheets (#39, finding 2). |
| func (a *app) signin(w http.ResponseWriter, r *http.Request) { |
| - if id, ok := a.auth.SessionFrom(r); ok { |
| + if a.team != nil { |
| + if a.teamSignin(w, r) { |
| + return |
| + } |
| + } else if id, ok := a.auth.SessionFrom(r); ok { |
| if _, err := a.lookupPerson(r, sessions.Session{Subject: id.Address, Method: string(id.Method)}); errors.Is(err, errHomeRemoved) { |
| a.endRemovedSession(w, r) |
| return |
diff --git a/internal/calls/hub/authorize.go b/internal/calls/hub/authorize.go| index 9e5dbe8..06de9a1 100644 |
| --- a/internal/calls/hub/authorize.go |
| +++ b/internal/calls/hub/authorize.go |
| @@ -36,3 +36,14 @@ func (h *Hub) Authorize(ctx context.Context, sqid, session string, peer PeerID) |
| } |
| return nil |
| } |
| + |
| +// Recheck re-derives a participation's standing now and applies it, as |
| +// the next mutating request would (§2.4, §15.12): a member whose |
| +// standing is gone is ended with lost{standing} and the departure the |
| +// room is owed, and a changed kind is recorded. It reports whether the |
| +// participation ended. A guest is never touched (ruling 14). The app's |
| +// held stream calls it when its own decision says a member has left, so |
| +// the ending is the hub's, in the hub's words. |
| +func (h *Hub) Recheck(ctx context.Context, sqid, session string, peer PeerID) (bool, error) { |
| + return h.memberStandingGone(ctx, sqid, session, peer, true) |
| +} |
diff --git a/internal/calls/hub/hub.go b/internal/calls/hub/hub.go| index ffd9892..0e1575a 100644 |
| --- a/internal/calls/hub/hub.go |
| +++ b/internal/calls/hub/hub.go |
| @@ -63,6 +63,14 @@ var ( |
| ErrNotTargeted = errors.New("hub: not a targeted message type") |
| ErrStaleGen = errors.New("hub: stale generation") |
| ErrTooManyWaiting = errors.New("hub: eight already waiting") |
| + // ErrStandingUnknown is a StandingFor answer that cannot be decided |
| + // now — team mode's roster outside its lease — as distinct from a |
| + // failed read. Every caller treats it as the error it is, except |
| + // Resume, which attaches the stream anyway: the participation is |
| + // kept, and the app's stream holds it, delivering nothing, until |
| + // standing is known again (a Home blip must not drop the call). The |
| + // app never returns it outside team mode. |
| + ErrStandingUnknown = errors.New("hub: standing cannot be decided now") |
| ) |
| type Config struct { |
| @@ -485,7 +493,14 @@ func (h *Hub) Tick(ctx context.Context) { |
| for _, c := range checks { |
| kind, ok, err := h.cfg.StandingFor(ctx, c.room, c.personID) |
| if err != nil { |
| - h.cfg.Logger.Warn("hub: standing lookup failed on tick", |
| + level := slog.LevelWarn |
| + if errors.Is(err, ErrStandingUnknown) { |
| + // A roster blip: every joined participation, every |
| + // fifteen seconds, for as long as it lasts. Expected, so |
| + // not a warning; nothing changes until it is decided. |
| + level = slog.LevelDebug |
| + } |
| + h.cfg.Logger.Log(ctx, level, "hub: standing lookup failed on tick", |
| "room", c.room, "peer", c.peer, "error", err) |
| continue // this participation waits for the next tick |
| } |
diff --git a/internal/calls/hub/relay.go b/internal/calls/hub/relay.go| index 9745e7b..0e760dd 100644 |
| --- a/internal/calls/hub/relay.go |
| +++ b/internal/calls/hub/relay.go |
| @@ -2,7 +2,9 @@ package hub |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| + "log/slog" |
| "time" |
| ) |
| @@ -195,7 +197,13 @@ func (h *Hub) CanResume(ctx context.Context, sqid, session string, peer PeerID) |
| // A standing read that failed is not evidence of anything. The |
| // participation answers for itself, as it did before §15.12, and |
| // the tick will re-read standing in fifteen seconds. |
| - h.cfg.Logger.Warn("hub: standing lookup failed on a resume probe", "room", sqid, "peer", peer, "error", err) |
| + level := slog.LevelWarn |
| + if errors.Is(err, ErrStandingUnknown) { |
| + // A roster blip, said once per probe for every peer in every |
| + // call: expected while it lasts, so not a warning. |
| + level = slog.LevelDebug |
| + } |
| + h.cfg.Logger.Log(ctx, level, "hub: standing lookup failed on a resume probe", "room", sqid, "peer", peer, "error", err) |
| } |
| h.mu.Lock() |
| defer h.mu.Unlock() |
| @@ -224,7 +232,7 @@ func (h *Hub) Resume(ctx context.Context, sqid, session string, peer PeerID, las |
| h.mu.Unlock() |
| gone, err := h.memberStandingGone(ctx, sqid, session, peer, true) |
| - if err != nil { |
| + if err != nil && !errors.Is(err, ErrStandingUnknown) { |
| return ResumeResult{}, err |
| } |
| if gone { |
diff --git a/internal/calls/hub/standing_unknown_test.go b/internal/calls/hub/standing_unknown_test.go| new file mode 100644 |
| index 0000000..9bd8ac4 |
| --- /dev/null |
| +++ b/internal/calls/hub/standing_unknown_test.go |
| @@ -0,0 +1,50 @@ |
| +package hub |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "log/slog" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +// Standing that cannot be decided now (team mode's roster outside its |
| +// lease) is expected for as long as a Home blip lasts, for every peer on |
| +// every tick and every resume probe: it is logged below Warn, while a |
| +// failed read stays a warning. |
| +func TestStandingUnknownIsNotAWarning(t *testing.T) { |
| + var answer atomic.Pointer[error] |
| + var logs bytes.Buffer |
| + h := New(Config{ |
| + Logger: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})), |
| + StandingFor: func(context.Context, string, int64) (Kind, bool, error) { |
| + if err := answer.Load(); err != nil { |
| + return 0, false, *err |
| + } |
| + return KindMember, true, nil |
| + }, |
| + }) |
| + res, err := h.Open("room", "session", 1, "A", KindMember) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := h.Join(context.Background(), "room", "session", res.Peer); err != nil { |
| + t.Fatal(err) |
| + } |
| + unknown := ErrStandingUnknown |
| + answer.Store(&unknown) |
| + h.Tick(context.Background()) |
| + h.CanResume(context.Background(), "room", "session", res.Peer) |
| + if logs.Len() != 0 { |
| + t.Fatalf("Unknown standing logged a warning:\n%s", logs.String()) |
| + } |
| + locked := errors.New("database is locked") |
| + answer.Store(&locked) |
| + h.Tick(context.Background()) |
| + h.CanResume(context.Background(), "room", "session", res.Peer) |
| + if strings.Count(logs.String(), "level=WARN") != 2 { |
| + t.Fatalf("a failed read is no longer a warning:\n%s", logs.String()) |
| + } |
| +} |
diff --git a/internal/calls/ice.go b/internal/calls/ice.go| index 5e577c2..7e2906f 100644 |
| --- a/internal/calls/ice.go |
| +++ b/internal/calls/ice.go |
| @@ -8,6 +8,8 @@ import ( |
| "github.com/go-chi/chi/v5" |
| + "amadan.net/oficina/home/roster" |
| + |
| "amadan.net/oficina/calls/internal/calls/hub" |
| "amadan.net/oficina/calls/internal/calls/relay" |
| ) |
| @@ -99,6 +101,20 @@ func (a *app) ice(w http.ResponseWriter, r *http.Request) { |
| streamJSON(w, http.StatusNotFound, a.notFoundBody()) |
| return |
| } |
| + if a.team != nil { |
| + // No relay credential on a host who has left (the meeting is |
| + // ended now) or who cannot be decided now (team_host.go). |
| + switch _, st := a.meetingStands(r.Context(), m); st { |
| + case roster.NotMember: |
| + a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "meeting") |
| + streamJSON(w, http.StatusNotFound, a.notFoundBody()) |
| + return |
| + case roster.Unknown: |
| + a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "standing-unknown") |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| + } |
| switch err := a.hub.Authorize(r.Context(), sqid, session, hub.PeerID(peer)); { |
| case err == nil: |
| @@ -106,6 +122,10 @@ func (a *app) ice(w http.ResponseWriter, r *http.Request) { |
| a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "authority") |
| streamJSON(w, http.StatusNotFound, a.notFoundBody()) |
| return |
| + case a.team != nil && isTeamUnavailable(err): |
| + a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "standing-unknown") |
| + teamUnavailableJSON(w) |
| + return |
| default: |
| a.logger.Error("calls: ice: authorize", "room", sqid, "peer", peer, "outcome", "internal", "err", err) |
| streamJSON(w, http.StatusInternalServerError, nil) |
diff --git a/internal/calls/knockpush.go b/internal/calls/knockpush.go| index 84c4277..b6b5476 100644 |
| --- a/internal/calls/knockpush.go |
| +++ b/internal/calls/knockpush.go |
| @@ -63,6 +63,10 @@ func (a *app) registerDevice(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if err := a.store.saveDeviceToken(r.Context(), p.ID, token, input.Platform); err != nil { |
| + if a.team != nil && isTeamUnavailable(err) { |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| a.logger.Error("calls: register device", "err", err) |
| http.Error(w, "cannot register this device", http.StatusInternalServerError) |
| return |
| @@ -88,7 +92,15 @@ func (a *app) knocked(room string, watching []int64, name string) { |
| } |
| ctx, cancel := context.WithTimeout(context.Background(), knockPushDeadline) |
| defer cancel() |
| - members, err := a.store.memberPersonIDs(ctx, a.allowNow()) |
| + var members []int64 |
| + var err error |
| + if a.team != nil { |
| + // Team mode: decided on each recipient's standing now, at send |
| + // time (team_push.go). |
| + members, err = a.teamMemberPersonIDs(ctx) |
| + } else { |
| + members, err = a.store.memberPersonIDs(ctx, a.allowNow()) |
| + } |
| if err != nil { |
| a.logger.Error("calls: knock push members", "err", err, "room", room) |
| return |
diff --git a/internal/calls/native_auth.go b/internal/calls/native_auth.go| index 4222aaa..dadd0e2 100644 |
| --- a/internal/calls/native_auth.go |
| +++ b/internal/calls/native_auth.go |
| @@ -331,6 +331,10 @@ func (a *app) nativeStartMeeting(w http.ResponseWriter, r *http.Request) { |
| p, _ := currentPerson(r) |
| title := callTitle(a.store.now(), callZone(input.Zone), a.cfg.zone) |
| m, _, err := a.store.createCall(r.Context(), title, actorFor(p)) |
| + if a.team != nil && isTeamUnavailable(err) { |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("calls: native start meeting", "err", err) |
| http.Error(w, "cannot start a meeting", http.StatusInternalServerError) |
diff --git a/internal/calls/signal.go b/internal/calls/signal.go| index 9843d96..df3d81a 100644 |
| --- a/internal/calls/signal.go |
| +++ b/internal/calls/signal.go |
| @@ -519,6 +519,14 @@ func (a *app) signal(w http.ResponseWriter, r *http.Request) { |
| // From here body.Peer is known to be exactly 32 lowercase hex — |
| // bounded and safe to use as a log argument and as the hub's lookup |
| // key. |
| + if a.team != nil && body.Type != hub.TypeLeave { |
| + // A call stands on its host (team_host.go), and nothing is |
| + // relayed on a host who cannot be decided now. Leaving is always |
| + // allowed: it delivers nothing to the one who leaves. |
| + if !a.teamRoomStands(w, r, sqid, body.Peer, body.Type) { |
| + return |
| + } |
| + } |
| var herr error |
| switch body.Type { |
| case hub.TypeJoin: |
| @@ -594,6 +602,11 @@ func (a *app) signal(w http.ResponseWriter, r *http.Request) { |
| // same defence for Fanout, which this dispatch only ever calls |
| // for chat/share — already fan-out types. |
| a.refuseSignal(w, sqid, body.Peer, body.Type, http.StatusBadRequest, "type", map[string]any{"error": "bad-request"}) |
| + case a.team != nil && isTeamUnavailable(herr): |
| + // A member's own standing (or a target's) cannot be decided now: |
| + // nothing was relayed, and the browser's queue retries. |
| + a.logRefusal(sqid, body.Peer, body.Type, "standing-unknown") |
| + teamUnavailableJSON(w) |
| case errors.Is(herr, hub.ErrNotYours), errors.Is(herr, hub.ErrUnknownPeer), |
| errors.Is(herr, hub.ErrNotAdmitted), errors.Is(herr, hub.ErrNotMember): |
| // A meeting, or a peer, that is not yours does not exist (§2.5). |
diff --git a/internal/calls/standing.go b/internal/calls/standing.go| index 21f43c9..45b8028 100644 |
| --- a/internal/calls/standing.go |
| +++ b/internal/calls/standing.go |
| @@ -4,6 +4,8 @@ import ( |
| "context" |
| "fmt" |
| "strings" |
| + |
| + "amadan.net/oficina/home/roster" |
| ) |
| func normalizeAddress(address string) string { |
| @@ -37,6 +39,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 |
| } |
| @@ -87,6 +96,9 @@ func (a *app) isMember(p Person) bool { |
| } |
| func (a *app) standingFor(ctx context.Context, p Person, m Meeting) (Standing, error) { |
| + if a.team != nil { |
| + return a.teamStandingFor(ctx, p, m) |
| + } |
| if p.Anonymous && m.RequireSignin { |
| return StandingNone, nil |
| } |
| @@ -102,3 +114,35 @@ func (a *app) standingFor(ctx context.Context, p Person, m Meeting) (Standing, e |
| } |
| return StandingNone, nil |
| } |
| + |
| +// teamStandingFor is standingFor in team mode. The meeting stands on its |
| +// host first (team_host.go): a host who has left ends it, and nobody has |
| +// standing toward an ended meeting; a host who cannot be decided now is |
| +// errTeamUnavailable for everyone. Then the person's own: Member is a |
| +// member, Unknown is errTeamUnavailable (whether they need a grant cannot |
| +// be told), and a non-member stands on an unexpired grant, as always. |
| +func (a *app) teamStandingFor(ctx context.Context, p Person, m Meeting) (Standing, error) { |
| + switch _, st := a.meetingStands(ctx, m); st { |
| + case roster.NotMember: |
| + return StandingNone, nil |
| + case roster.Unknown: |
| + return StandingNone, errTeamUnavailable |
| + } |
| + if p.Anonymous && m.RequireSignin { |
| + return StandingNone, nil |
| + } |
| + switch a.memberState(ctx, p) { |
| + case roster.Member: |
| + return StandingMember, nil |
| + case roster.Unknown: |
| + return StandingNone, errTeamUnavailable |
| + } |
| + g, ok, err := a.store.grantFor(ctx, m.ID, p.ID) |
| + if err != nil { |
| + return StandingNone, err |
| + } |
| + if ok && g.ExpiresAt.After(a.store.now()) { |
| + return StandingGuest, nil |
| + } |
| + return StandingNone, nil |
| +} |
diff --git a/internal/calls/store.go b/internal/calls/store.go| index f2d3d0e..8eab01f 100644 |
| --- a/internal/calls/store.go |
| +++ b/internal/calls/store.go |
| @@ -47,6 +47,10 @@ type store struct { |
| sealer *seal.Sealer |
| clk *clock |
| logger *slog.Logger |
| + // team is whether team mode is on: every person's write then runs |
| + // inside the standing guard (team_guard.go). False, every write is |
| + // what it always was. |
| + team bool |
| } |
| // now is the app's clock, the one a test can move. |
| @@ -132,24 +136,26 @@ func (s *store) insertMeeting(ctx context.Context, title string, auto bool, zone |
| } |
| var m Meeting |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - for attempt := 0; ; attempt++ { |
| - sqid, err := newSqid() |
| - if err != nil { |
| - return err |
| - } |
| - m = Meeting{RequireSignin: defaults.RequireSignin, WaitingRoom: defaults.WaitingRoom, AutoTitle: auto, TitleZone: zone, Sqid: sqid, TitleSealed: sealed, StartsAt: startsAt, CreatedBy: actor, CreatedAt: s.now().UTC()} |
| - res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&m) |
| - if res.Error != nil { |
| - return res.Error |
| + return s.guard(ctx, func() error { |
| + for attempt := 0; ; attempt++ { |
| + sqid, err := newSqid() |
| + if err != nil { |
| + return err |
| + } |
| + m = Meeting{RequireSignin: defaults.RequireSignin, WaitingRoom: defaults.WaitingRoom, AutoTitle: auto, TitleZone: zone, Sqid: sqid, TitleSealed: sealed, StartsAt: startsAt, CreatedBy: actor, CreatedAt: s.now().UTC()} |
| + res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&m) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 1 { |
| + break |
| + } |
| + if attempt+1 >= maxSqidAttempts { |
| + return errors.New("calls: could not mint a unique sqid") |
| + } |
| } |
| - if res.RowsAffected == 1 { |
| - break |
| - } |
| - if attempt+1 >= maxSqidAttempts { |
| - return errors.New("calls: could not mint a unique sqid") |
| - } |
| - } |
| - return tx.Create(&MeetingLink{MeetingID: m.ID, TokenHash: hash, TokenSealed: linkSealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| + return tx.Create(&MeetingLink{MeetingID: m.ID, TokenHash: hash, TokenSealed: linkSealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| + }) |
| }) |
| if err != nil { |
| return Meeting{}, "", err |
| @@ -307,17 +313,19 @@ func (s *store) replaceLink(ctx context.Context, meetingID int64, actor string) |
| } |
| now := s.now().UTC() |
| err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var m Meeting |
| - if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return errMeetingEnded |
| + return s.guard(ctx, func() error { |
| + var m Meeting |
| + if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return errMeetingEnded |
| + } |
| + return err |
| } |
| - return err |
| - } |
| - if err := tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error; err != nil { |
| - return err |
| - } |
| - return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: now}).Error |
| + if err := tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error; err != nil { |
| + return err |
| + } |
| + return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: now}).Error |
| + }) |
| }) |
| if err != nil { |
| return "", err |
| @@ -331,36 +339,43 @@ func (s *store) replaceLink(ctx context.Context, meetingID int64, actor string) |
| func (s *store) shareLink(ctx context.Context, meetingID int64, actor string) (string, error) { |
| var token string |
| err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var m Meeting |
| - if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return errMeetingEnded |
| + return s.guard(ctx, func() error { |
| + var m Meeting |
| + if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return errMeetingEnded |
| + } |
| + return err |
| } |
| - return err |
| - } |
| - var link MeetingLink |
| - err := tx.Where("meeting_id = ? AND revoked_at IS NULL AND token_sealed IS NOT NULL", meetingID).Order("id DESC").Take(&link).Error |
| - if err == nil { |
| - token, err = s.sealer.OpenString(seal.PurposeMeetingLink, link.TokenSealed) |
| - if err != nil || token == "" || hashLinkToken(token) != link.TokenHash { |
| - return errors.New("calls: cannot open invitation") |
| + var link MeetingLink |
| + err := tx.Where("meeting_id = ? AND revoked_at IS NULL AND token_sealed IS NOT NULL", meetingID).Order("id DESC").Take(&link).Error |
| + if err == nil { |
| + token, err = s.sealer.OpenString(seal.PurposeMeetingLink, link.TokenSealed) |
| + if err != nil || token == "" || hashLinkToken(token) != link.TokenHash { |
| + return errors.New("calls: cannot open invitation") |
| + } |
| + return nil |
| } |
| - return nil |
| - } |
| - if !errors.Is(err, gorm.ErrRecordNotFound) { |
| - return err |
| - } |
| - var hash string |
| - token, hash, err = newLinkToken() |
| - if err != nil { |
| - return err |
| - } |
| - sealed, err := s.sealer.SealString(seal.PurposeMeetingLink, token) |
| - if err != nil { |
| - return err |
| - } |
| - return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + var hash string |
| + token, hash, err = newLinkToken() |
| + if err != nil { |
| + return err |
| + } |
| + sealed, err := s.sealer.SealString(seal.PurposeMeetingLink, token) |
| + if err != nil { |
| + return err |
| + } |
| + return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| + }) |
| }) |
| + if err != nil { |
| + // A token opened before a refusal at commit is not handed out: |
| + // the guard said this person may not have it. |
| + token = "" |
| + } |
| return token, err |
| } |
| @@ -375,16 +390,19 @@ func (s *store) endMeeting(ctx context.Context, meetingID int64, actor string) ( |
| now := s.now().UTC() |
| ended := false |
| err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - res := tx.Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", meetingID). |
| - Select("ended_at", "ended_by").Updates(map[string]any{"ended_at": now, "ended_by": actor}) |
| - if res.Error != nil { |
| - return res.Error |
| - } |
| - if res.RowsAffected == 0 { |
| - return nil |
| - } |
| - ended = true |
| - return tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error |
| + return s.guard(ctx, func() error { |
| + ended = false |
| + res := tx.Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", meetingID). |
| + Select("ended_at", "ended_by").Updates(map[string]any{"ended_at": now, "ended_by": actor}) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return nil |
| + } |
| + ended = true |
| + return tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error |
| + }) |
| }) |
| if err != nil { |
| return false, err |
| @@ -436,17 +454,23 @@ func (s *store) mintGrant(ctx context.Context, m Meeting, personID int64) (Guest |
| func (s *store) mintGrantViaLink(ctx context.Context, linkID, personID int64) (GuestGrant, bool, error) { |
| var g GuestGrant |
| live := false |
| + // In team mode the grant stands on the meeting's host, whose Access |
| + // the caller carries on ctx (team_host.go): a link admits nobody new |
| + // once its host has left the team. |
| err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| - _, m, ok, err := ts.liveLinkByID(ctx, linkID) |
| - if err != nil || !ok { |
| - return err |
| - } |
| - if g, err = ts.mintGrant(ctx, m, personID); err != nil { |
| - return err |
| - } |
| - live = true |
| - return nil |
| + return s.guard(ctx, func() error { |
| + live = false |
| + ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| + _, m, ok, err := ts.liveLinkByID(ctx, linkID) |
| + if err != nil || !ok { |
| + return err |
| + } |
| + if g, err = ts.mintGrant(ctx, m, personID); err != nil { |
| + return err |
| + } |
| + live = true |
| + return nil |
| + }) |
| }) |
| if err != nil { |
| return GuestGrant{}, false, err |
| @@ -520,26 +544,38 @@ func (s *store) deletePending(ctx context.Context, address string) error { |
| func (s *store) consumePending(ctx context.Context, p Person, pend PendingJoin, member bool) (string, error) { |
| dest := "" |
| err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| - current, ok, err := ts.latestPending(ctx, p.Email) |
| - if err != nil || !ok || current.ID != pend.ID { |
| - return err |
| - } |
| - if err := ts.deletePending(ctx, p.Email); err != nil { |
| - return err |
| - } |
| - _, m, live, err := ts.liveLinkByID(ctx, current.LinkID) |
| - if err != nil || !live { |
| - return err |
| - } |
| - if !member { |
| - if _, err := ts.mintGrant(ctx, m, p.ID); err != nil { |
| + consume := func() error { |
| + dest = "" |
| + ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| + current, ok, err := ts.latestPending(ctx, p.Email) |
| + if err != nil || !ok || current.ID != pend.ID { |
| return err |
| } |
| + if err := ts.deletePending(ctx, p.Email); err != nil { |
| + return err |
| + } |
| + _, m, live, err := ts.liveLinkByID(ctx, current.LinkID) |
| + if err != nil || !live { |
| + return err |
| + } |
| + if !member { |
| + if _, err := ts.mintGrant(ctx, m, p.ID); err != nil { |
| + return err |
| + } |
| + } |
| + dest = "/m/" + m.Sqid + "/join" |
| + return nil |
| + } |
| + if member { |
| + return consume() |
| } |
| - dest = "/m/" + m.Sqid + "/join" |
| - return nil |
| + // A guest's grant stands on the meeting's host, whose Access the |
| + // caller carries on ctx in team mode (team_host.go). |
| + return s.guard(ctx, consume) |
| }) |
| + if err != nil { |
| + dest = "" |
| + } |
| return dest, err |
| } |
| @@ -664,13 +700,49 @@ func (s *store) meetingDefaults(ctx context.Context) (MeetingDefaults, error) { |
| return d, err |
| } |
| func (s *store) saveMeetingDefaults(ctx context.Context, signin, waiting bool) error { |
| - return s.g.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}}, DoUpdates: clause.AssignmentColumns([]string{"require_signin", "waiting_room"})}).Create(&MeetingDefaults{ID: 1, RequireSignin: signin, WaitingRoom: waiting}).Error |
| + return s.guarded(ctx, func(g *gorm.DB) error { |
| + return g.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}}, DoUpdates: clause.AssignmentColumns([]string{"require_signin", "waiting_room"})}).Create(&MeetingDefaults{ID: 1, RequireSignin: signin, WaitingRoom: waiting}).Error |
| + }) |
| } |
| // Meetings are team-owned, as are the other meeting mutations in this store. |
| func (s *store) saveMeetingSettings(ctx context.Context, id int64, signin, waiting bool) error { |
| - return s.g.WithContext(ctx).Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", id).Select("RequireSignin", "WaitingRoom").Updates(map[string]any{"RequireSignin": signin, "WaitingRoom": waiting}).Error |
| + return s.guarded(ctx, func(g *gorm.DB) error { |
| + return g.Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", id).Select("RequireSignin", "WaitingRoom").Updates(map[string]any{"RequireSignin": signin, "WaitingRoom": waiting}).Error |
| + }) |
| } |
| + |
| +// guestWithGrant is team mode's named guest: the anonymous person and |
| +// their grant through the link, in one transaction inside the standing |
| +// guard (the meeting host's, which the caller carries on ctx). False, with |
| +// nothing written, when the link is no longer live. |
| +func (s *store) guestWithGrant(ctx context.Context, name string, linkID int64) (Person, bool, error) { |
| + var p Person |
| + live := false |
| + err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + return s.guard(ctx, func() error { |
| + live = false |
| + ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| + _, m, ok, err := ts.liveLinkByID(ctx, linkID) |
| + if err != nil || !ok { |
| + return err |
| + } |
| + if p, err = ts.createGuest(ctx, name); err != nil { |
| + return err |
| + } |
| + if _, err = ts.mintGrant(ctx, m, p.ID); err != nil { |
| + return err |
| + } |
| + live = true |
| + return nil |
| + }) |
| + }) |
| + if err != nil || !live { |
| + return Person{}, false, err |
| + } |
| + return p, true, nil |
| +} |
| + |
| func (s *store) createGuest(ctx context.Context, name string) (Person, error) { |
| p := Person{Email: "guest:" + nativeRandom(), Name: name, Anonymous: true, CreatedAt: s.now().UTC()} |
| err := s.g.WithContext(ctx).Create(&p).Error |
| @@ -685,12 +757,14 @@ func (s *store) createGuest(ctx context.Context, name string) (Person, error) { |
| // which is what lets a token that has gone quiet be swept later. |
| func (s *store) saveDeviceToken(ctx context.Context, personID int64, token, platform string) error { |
| now := s.now().UTC() |
| - return s.g.WithContext(ctx).Clauses(clause.OnConflict{ |
| - Columns: []clause.Column{{Name: "token"}}, |
| - DoUpdates: clause.AssignmentColumns([]string{"person_id", "platform", "last_seen"}), |
| - }).Create(&DeviceToken{ |
| - PersonID: personID, Token: token, Platform: platform, CreatedAt: now, LastSeen: now, |
| - }).Error |
| + return s.guarded(ctx, func(g *gorm.DB) error { |
| + return g.Clauses(clause.OnConflict{ |
| + Columns: []clause.Column{{Name: "token"}}, |
| + DoUpdates: clause.AssignmentColumns([]string{"person_id", "platform", "last_seen"}), |
| + }).Create(&DeviceToken{ |
| + PersonID: personID, Token: token, Platform: platform, CreatedAt: now, LastSeen: now, |
| + }).Error |
| + }) |
| } |
| // deviceTokensFor answers every device a set of people can be reached |
diff --git a/internal/calls/stream.go b/internal/calls/stream.go| index 9f02474..b2e98f1 100644 |
| --- a/internal/calls/stream.go |
| +++ b/internal/calls/stream.go |
| @@ -12,6 +12,7 @@ import ( |
| "github.com/go-chi/chi/v5" |
| + "amadan.net/oficina/home/roster" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/oficina/calls/internal/calls/hub" |
| @@ -161,6 +162,9 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| var sub *hub.Sub |
| var peer hub.PeerID |
| var first []hub.Message |
| + // meeting is the row this stream stands on, for team mode's |
| + // per-delivery decision (team_stream.go). |
| + var meeting Meeting |
| if resume := hub.PeerID(r.URL.Query().Get("peer")); resume != "" { |
| // A resume is authorized by the participation, not by standing |
| @@ -173,6 +177,16 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| streamJSON(w, http.StatusInternalServerError, nil) |
| return |
| } |
| + if a.team != nil && found && m.EndedAt == nil { |
| + // A call stands on its host (team_host.go). One who has left |
| + // has ended it just now, which the tombstone below answers |
| + // 410 ended; one who cannot be decided now leaves the |
| + // participation to resume and be held (team_stream.go). |
| + if _, st := a.meetingStands(r.Context(), m); st == roster.NotMember { |
| + m.EndedAt = &time.Time{} |
| + } |
| + } |
| + meeting = m |
| if !found || m.EndedAt != nil { |
| // The hub answers first when it holds a tombstone, so a peer |
| // that was in the room when it ended is told why (410 ended) |
| @@ -243,10 +257,23 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if !found || m.EndedAt != nil { |
| + if a.requestPartial(r) { |
| + // Team mode, standing Unknown: not "gone", which the |
| + // browser would take as the end (team_answers.go). |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| streamJSON(w, http.StatusNotFound, map[string]any{"boot": a.hub.Boot()}) |
| return |
| } |
| + meeting = m |
| st, err := a.standingFor(r.Context(), person, m) |
| + if a.team != nil && isTeamUnavailable(err) { |
| + // Nothing is allocated for an entry that cannot be decided |
| + // now; the browser's ladder asks again. |
| + teamUnavailableJSON(w) |
| + return |
| + } |
| if err != nil { |
| a.logger.Error("calls: stream: standing", "err", err) |
| streamJSON(w, http.StatusInternalServerError, nil) |
| @@ -295,6 +322,10 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| // stream displaced by a second one does not detach its replacement — |
| // which starts the thirty-second resume window (§4.5). |
| defer a.hub.Detach(sqid, peer, sub) |
| + if a.team != nil { |
| + a.serveTeamStream(w, r, sub, first, meeting, person, sqid, session, peer) |
| + return |
| + } |
| a.serveStream(w, r, sub, first) |
| } |
diff --git a/internal/calls/team_access.go b/internal/calls/team_access.go| new file mode 100644 |
| index 0000000..8b9dc16 |
| --- /dev/null |
| +++ b/internal/calls/team_access.go |
| @@ -0,0 +1,311 @@ |
| +package calls |
| + |
| +// Team mode's per-request standing. With a.team nil nothing here runs: |
| +// requirePerson, the route gates, the hub's standing and every store |
| +// write are what they have always been. |
| +// |
| +// Standing itself is home/teammode's Access. Identity is resolved from |
| +// the actual session — a guest's own session, a local address (and its |
| +// account link, if it has one), or a Home subject (an account link or a |
| +// Home-only person) — and the roster is asked about the Home subject, if |
| +// there is one. The answer is one of three: |
| +// |
| +// - Member: the team. Every meeting, every member page, and entry to |
| +// every call, as an allowlisted address has outside team mode. The |
| +// roster's role is never consulted: Calls has no owner-only power. |
| +// - NotMember: for somebody the roster knows (a Home subject), removal. |
| +// They are signed out and told so, existing sessions included, which |
| +// is removal within the lease (a member never holds a guest grant, so |
| +// a guest session would reach nothing). For somebody it does not — |
| +// an anonymous guest, a local account with no Oficina link — it is |
| +// what a non-member always was here: a guest, standing on the grants |
| +// the team's links gave them. |
| +// - Unknown: the roster could not be read within its lease. The meeting |
| +// list is partial (empty: without standing a member reaches nothing) |
| +// with a notice; everything else that needs standing is a retryable |
| +// 503, never a 404 that would claim the meeting is gone. |
| +// |
| +// A Member decision carries a lease. Access.State checks it every time it |
| +// is asked; a write checks it again inside its own transaction, before |
| +// and after (team_guard.go); the list asks again after it is built; a |
| +// call's stream re-decides before each delivery and at the lease's end |
| +// (team_stream.go). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/calls/internal/calls/hub" |
| + "amadan.net/oficina/calls/internal/calls/teamstate" |
| +) |
| + |
| +// errTeamUnavailable is team standing that cannot be decided now: the |
| +// roster within its lease, or the storage behind a session's identity. It |
| +// is teammode's ErrUnavailable, so the guard's refusals and the gates' |
| +// read the same, and the hub's ErrStandingUnknown, so the hub holds a |
| +// resuming stream rather than refusing it (hub.Resume). |
| +var errTeamUnavailable = errors.Join(teammode.ErrUnavailable, hub.ErrStandingUnknown) |
| + |
| +// teamReq is who one request's session speaks for in team mode, and |
| +// their standing. Never stored beyond the request. |
| +type teamReq struct { |
| + person Person |
| + // subject is the Home subject the roster knows them by, "" for an |
| + // anonymous guest or a local account with no Oficina link. |
| + subject string |
| + // method is the session's sign-in method. |
| + method string |
| + access *teammode.Access |
| +} |
| + |
| +// removed is a definite NotMember for somebody the roster knows: a |
| +// member taken off the team, who is signed out. |
| +func (t *teamReq) removed() bool { |
| + return t.subject != "" && t.access.State() == roster.NotMember |
| +} |
| + |
| +type teamReqKey struct{} |
| + |
| +// withTeamReq carries t, and its Access for the store's guard, on ctx. |
| +func withTeamReq(ctx context.Context, t *teamReq) context.Context { |
| + return context.WithValue(teammode.WithAccess(ctx, t.access), teamReqKey{}, t) |
| +} |
| + |
| +func teamReqFrom(ctx context.Context) (*teamReq, bool) { |
| + t, ok := ctx.Value(teamReqKey{}).(*teamReq) |
| + return t, ok && t != nil |
| +} |
| + |
| +// teamSubjectFor is the Home subject a session's person is known by: a |
| +// Home session's own subject, a local account's link, or "" for a guest |
| +// and for a local account with no link. errTeamUnavailable is storage |
| +// that cannot be read now. |
| +func (a *app) teamSubjectFor(ctx context.Context, s sessions.Session, p Person) (string, error) { |
| + switch { |
| + case p.Anonymous || s.Method == "guest": |
| + return "", nil |
| + case s.Method == connect.HomeMethod: |
| + return s.Subject, nil |
| + } |
| + return a.homeSubjectOf(ctx, p.ID) |
| +} |
| + |
| +// homeSubjectOf is the Home subject the roster knows a person 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 |
| +} |
| + |
| +// teamReqFor resolves a session to its person and asks the roster about |
| +// them, once. errHomeIdentity (and errHomeRemoved) are personForSession's: |
| +// a session that speaks for nobody here. errTeamUnavailable is storage. |
| +func (a *app) teamReqFor(ctx context.Context, s sessions.Session) (*teamReq, error) { |
| + p, err := a.personForSession(ctx, s) |
| + if err != nil { |
| + if !errors.Is(err, errHomeIdentity) { |
| + return nil, errTeamUnavailable |
| + } |
| + return nil, err |
| + } |
| + subject, err := a.teamSubjectFor(ctx, s, p) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &teamReq{person: p, subject: subject, method: s.Method, access: a.team.Access(ctx, subject)}, nil |
| +} |
| + |
| +// teamRequirePerson is requirePerson in team mode: who the session is, |
| +// and the roster's answer, asked once and carried on the request. |
| +// |
| +// A definite NotMember for a Home subject is signed out and told so |
| +// (endRemovedSession), existing sessions included: that is removal within |
| +// the lease. A guest, and a local account with no link, are let through |
| +// as the non-members they are. A session that speaks for nobody is the |
| +// 404 (or, for a refused Home link, the sign-out) it has always been. |
| +// Storage that cannot be read is a 503, never a sign-out. Unknown ends |
| +// nothing. |
| +func (a *app) teamRequirePerson(w http.ResponseWriter, r *http.Request, s sessions.Session, next http.Handler) { |
| + t, err := a.teamReqFor(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errHomeRemoved): |
| + a.endRemovedSession(w, r) |
| + return |
| + case errors.Is(err, errHomeIdentity): |
| + a.notFound(w, r) |
| + return |
| + case err != nil: |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + if t.removed() { |
| + a.endRemovedSession(w, r) |
| + return |
| + } |
| + ctx := context.WithValue(withTeamReq(r.Context(), t), personCtxKey{}, t.person) |
| + next.ServeHTTP(w, r.WithContext(ctx)) |
| +} |
| + |
| +// memberState is p's member standing. Outside team mode it is the |
| +// allowlist's, Member or NotMember, exactly isMember. In team mode it is |
| +// the roster's: for the request's own person the Access requirePerson |
| +// carried (latched); for anyone else asked now (standingOf). |
| +func (a *app) memberState(ctx context.Context, p Person) roster.State { |
| + if a.team == nil { |
| + if a.isMember(p) { |
| + return roster.Member |
| + } |
| + return roster.NotMember |
| + } |
| + if p.Anonymous { |
| + return roster.NotMember |
| + } |
| + if t, ok := teamReqFrom(ctx); ok && t.person.ID == p.ID { |
| + return t.access.State() |
| + } |
| + return a.standingOf(ctx, p.ID).State() |
| +} |
| + |
| +// memberNow is memberState == Member: the one question the pages ask. |
| +func (a *app) memberNow(ctx context.Context, p Person) bool { |
| + return a.memberState(ctx, p) == roster.Member |
| +} |
| + |
| +// standingOf builds the roster's answer about somebody other than the |
| +// request's own person — a meeting's host, an agent's operator, a |
| +// knock's push recipient, a participation the hub re-derives — so what it |
| +// says about them is what their own requests would be told. A person the |
| +// roster cannot be asked about (no link, no Home-only row) is NotMember; |
| +// one whose subject cannot be read now is Unknown (a nil Access). |
| +func (a *app) standingOf(ctx context.Context, person int64) *teammode.Access { |
| + subject, err := a.homeSubjectOf(ctx, person) |
| + if err != nil { |
| + return nil |
| + } |
| + return a.team.Access(ctx, subject) |
| +} |
| + |
| +// requireTeamMember is requireMember in team mode: Member, or a retryable |
| +// 503 for Unknown. A non-member is the 404 the gate always answered — an |
| +// unlinked local account the local door admits is sent to link instead |
| +// (requireLinkable), which is the only way it can gain standing. |
| +func (a *app) requireTeamMember(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| + t, ok := teamReqFrom(r.Context()) |
| + if !ok { |
| + // requirePerson puts the request on every route behind this |
| + // gate; a route that reaches here without it is a wiring bug, and |
| + // the closed answer is the one that cannot leak. |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + switch t.access.State() { |
| + case roster.Member: |
| + next.ServeHTTP(w, r) |
| + case roster.Unknown: |
| + a.teamUnavailable(w, r) |
| + default: |
| + if a.linkable(t) && (r.Method == http.MethodGet || r.Method == http.MethodHead) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, "/account/home", http.StatusSeeOther) |
| + return |
| + } |
| + a.notFound(w, r) |
| + } |
| +} |
| + |
| +// linkable is a local session the allowlist admits, not yet linked to an |
| +// Oficina account: in team mode the allowlist is the local door and |
| +// nothing more, and linking is how such an account comes to stand on the |
| +// roster. |
| +func (a *app) linkable(t *teamReq) bool { |
| + return a.home != nil && t.subject == "" && !t.person.Anonymous && |
| + (t.method == "magiclink" || t.method == "keymail") && a.allowNow().allows(t.person.Email) |
| +} |
| + |
| +// requireLinkable gates /account/home in team mode: the local door's |
| +// admitted, unlinked accounts, and nobody else (a linked account and a |
| +// Home session already are the connection). Outside team mode the link |
| +// routes stay behind requireMember. |
| +func (a *app) requireLinkable(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + t, ok := teamReqFrom(r.Context()) |
| + if !ok || !a.linkable(t) { |
| + a.notFound(w, r) |
| + return |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
| + |
| +// teamSignin is GET /signin in team mode: it asks the question |
| +// requirePerson asks before connect's Signin may shortcut a signed-in |
| +// person to where they were headed. One the roster says is off the team |
| +// is signed out and told so; storage that cannot be read is a 503, never |
| +// a sign-out. Unknown ends nothing. Identity is looked up without the |
| +// first-sign-in write (lookupPerson), as /signin always has. It reports |
| +// whether it answered. |
| +func (a *app) teamSignin(w http.ResponseWriter, r *http.Request) bool { |
| + id, ok := a.auth.SessionFrom(r) |
| + if !ok { |
| + return false |
| + } |
| + s := sessions.Session{Subject: id.Address, Method: string(id.Method), AuthTime: id.AuthTime, At: id.At} |
| + p, err := a.lookupPerson(r, s) |
| + switch { |
| + case errors.Is(err, errHomeRemoved): |
| + a.endRemovedSession(w, r) |
| + return true |
| + case errors.Is(err, errHomeIdentity), errors.Is(err, gorm.ErrRecordNotFound): |
| + // Nobody here yet, or nobody at all: the form, as before. |
| + return false |
| + case err != nil: |
| + a.teamUnavailable(w, r) |
| + return true |
| + } |
| + subject, err := a.teamSubjectFor(r.Context(), s, p) |
| + if err != nil { |
| + a.teamUnavailable(w, r) |
| + return true |
| + } |
| + if subject != "" && a.team.Access(r.Context(), subject).State() == roster.NotMember { |
| + a.endRemovedSession(w, r) |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// homeOnlyLabel is how a Home-only person, who has no address, is named |
| +// where an address or a name would be: "Oficina account" and the last |
| +// four characters of the person ref ("Oficina account …k7qz"), as Home's |
| +// Team page shows a ref. It is the persons row's name. |
| +func homeOnlyLabel(subject string) string { |
| + const label = "Oficina account" |
| + if len(subject) <= 4 { |
| + return label |
| + } |
| + return label + " …" + subject[len(subject)-4:] |
| +} |
| + |
| +// shown is how a person is named where an address would be: their |
| +// address, or for a Home-only person, who has none, their label. Outside |
| +// team mode no persons row holds a Home-only placeholder, so it is |
| +// exactly Email. |
| +func (p Person) shown() string { |
| + if teamstate.Addressless(p.Email) { |
| + return p.Name |
| + } |
| + return p.Email |
| +} |
diff --git a/internal/calls/team_answers.go b/internal/calls/team_answers.go| new file mode 100644 |
| index 0000000..f225a5a |
| --- /dev/null |
| +++ b/internal/calls/team_answers.go |
| @@ -0,0 +1,94 @@ |
| +package calls |
| + |
| +// Team mode's answers: the retryable 503 for Unknown standing, in each of |
| +// the shapes Calls answers in, and the partial list's notice. None of it |
| +// is reached outside team mode. |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// retryAfter is the roster's own retry interval, in whole seconds, as |
| +// every team-mode 503 says it. |
| +var retryAfter = strconv.Itoa(int(roster.RetryAfter / time.Second)) |
| + |
| +// unavailableHeaders are every team-mode 503's: never cached, and when to |
| +// ask again. |
| +func unavailableHeaders(w http.ResponseWriter) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", retryAfter) |
| +} |
| + |
| +// teamUnavailable is the retryable answer for Unknown standing to a page |
| +// or a form: the 503 page (with Try again for a GET) for a request that |
| +// asked for a page, plain text for anything else. A 404 would tell a |
| +// member their meeting is gone because Home was slow. |
| +func (a *app) teamUnavailable(w http.ResponseWriter, r *http.Request) { |
| + unavailableHeaders(w) |
| + a.errorPage(w, r, http.StatusServiceUnavailable, kindTeam, "") |
| +} |
| + |
| +// teamUnavailableJSON is the same answer to a script — the room's stream, |
| +// signal and ICE fetches, the native app — in their JSON shape. room.js |
| +// and callscore retry a 5xx with backoff; the body names nothing. |
| +func teamUnavailableJSON(w http.ResponseWriter) { |
| + unavailableHeaders(w) |
| + streamJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "unavailable"}) |
| +} |
| + |
| +// teamUnavailableAPI is the drive surface's. |
| +func teamUnavailableAPI(w http.ResponseWriter) { |
| + unavailableHeaders(w) |
| + apiJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "unavailable"}) |
| +} |
| + |
| +// isTeamUnavailable reports whether err is standing that cannot be |
| +// decided now (errTeamUnavailable, or the guard's ErrUnavailable). |
| +// Outside team mode no error is ever one. |
| +func isTeamUnavailable(err error) bool { return errors.Is(err, teammode.ErrUnavailable) } |
| + |
| +// requestPartial reports whether this request's own standing is Unknown |
| +// now, which is the partial-list rule (Paul, 2026-10-28, Home |
| +// implementation/teammode-package.md §4): the list asks it after it is |
| +// built, of the same Access it was built with — State latches, so a lease |
| +// that lapsed while listing marks the list partial. Without standing a |
| +// member reaches no meeting at all (Calls has no per-person shares of a |
| +// meeting: a guest's grant is for one call, and a guest has no list), so |
| +// a partial list is always empty, and the notice is what keeps it from |
| +// reading as "no meetings". NotMember is never partial: it never reaches |
| +// the list. Always false outside team mode. |
| +func (a *app) requestPartial(r *http.Request) bool { |
| + t, ok := teamReqFrom(r.Context()) |
| + return a.team != nil && ok && t.access.Partial() |
| +} |
| + |
| +// The partial notice (Paul, 2026-10-28): what the meeting list says when |
| +// the roster could not be read within its lease. |
| +const ( |
| + partialTitle = "We couldn’t check your team access" |
| + partialBody = "Your team’s meetings can’t be shown until it’s checked, so this list is not complete. Try again in a moment." |
| +) |
| + |
| +// guardRefused answers a write the guard refused, and reports whether it |
| +// did: standing lapsed between the route's gate and the commit, the same |
| +// retryable 503 as Unknown anywhere else, and the 404 for a definite "no" |
| +// (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 |
| +} |
diff --git a/internal/calls/team_call_test.go b/internal/calls/team_call_test.go| new file mode 100644 |
| index 0000000..20cc5cd |
| --- /dev/null |
| +++ b/internal/calls/team_call_test.go |
| @@ -0,0 +1,849 @@ |
| +package calls |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calls/internal/calls/hub" |
| +) |
| + |
| +// sseEvent is one event on a call stream; a heartbeat comment is |
| +// typ ":". |
| +type sseEvent struct { |
| + typ string |
| + data map[string]any |
| +} |
| + |
| +// callStream is an open GET /m/{sqid}/stream, read on a goroutine. |
| +type callStream struct { |
| + t *testing.T |
| + events chan sseEvent |
| + closed chan struct{} |
| + cancel context.CancelFunc |
| + peer string |
| +} |
| + |
| +// newStreamServer is a real server for f's handler, closed after every |
| +// stream the test opens has been cancelled (cleanups run last first, and |
| +// Close waits for open requests). |
| +func newStreamServer(t *testing.T, f *teamFixture) *httptest.Server { |
| + srv := httptest.NewServer(f.handler) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +// openStream opens a fresh stream for the jar's session against a real |
| +// server (an event stream needs one), waits for its hello and returns it. |
| +func (f *teamFixture) openStream(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream { |
| + f.t.Helper() |
| + s, status := f.tryStream(srv, jar, "/m/"+sqid+"/stream") |
| + if status != http.StatusOK { |
| + f.t.Fatalf("stream = %d", status) |
| + } |
| + hello := s.next("hello") |
| + s.peer, _ = hello.data["peer"].(string) |
| + return s |
| +} |
| + |
| +// tryStream opens path and returns the stream and the status. |
| +func (f *teamFixture) tryStream(srv *httptest.Server, jar map[string]*http.Cookie, path string) (*callStream, int) { |
| + f.t.Helper() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+path, nil) |
| + req.Header.Set("Accept", "text/event-stream") |
| + // The instance's own host, as the edge passes it on. |
| + req.Host = strings.TrimPrefix(homeTestOrigin, "https://") |
| + for _, c := range jar { |
| + req.AddCookie(c) |
| + } |
| + resp, err := srv.Client().Do(req) |
| + if err != nil { |
| + cancel() |
| + f.t.Fatal(err) |
| + } |
| + s := &callStream{t: f.t, events: make(chan sseEvent, 256), closed: make(chan struct{}), cancel: cancel} |
| + f.t.Cleanup(cancel) |
| + if resp.StatusCode != http.StatusOK { |
| + resp.Body.Close() |
| + cancel() |
| + return s, resp.StatusCode |
| + } |
| + go func() { |
| + defer close(s.closed) |
| + defer resp.Body.Close() |
| + r := bufio.NewReader(resp.Body) |
| + var typ string |
| + for { |
| + line, err := r.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + line = strings.TrimRight(line, "\n") |
| + switch { |
| + case strings.HasPrefix(line, ":"): |
| + s.events <- sseEvent{typ: ":"} |
| + case strings.HasPrefix(line, "event: "): |
| + typ = strings.TrimPrefix(line, "event: ") |
| + case strings.HasPrefix(line, "data: "): |
| + var data map[string]any |
| + _ = json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &data) |
| + s.events <- sseEvent{typ: typ, data: data} |
| + } |
| + } |
| + }() |
| + return s, http.StatusOK |
| +} |
| + |
| +// next waits for the next event of type typ, skipping heartbeats and |
| +// anything else, and fails after a few seconds. |
| +func (s *callStream) next(typ string) sseEvent { |
| + s.t.Helper() |
| + deadline := time.After(5 * time.Second) |
| + for { |
| + select { |
| + case e := <-s.events: |
| + if e.typ == typ { |
| + return e |
| + } |
| + case <-s.closed: |
| + // Whatever was read before the close is still owed. |
| + for { |
| + select { |
| + case e := <-s.events: |
| + if e.typ == typ { |
| + return e |
| + } |
| + continue |
| + default: |
| + } |
| + break |
| + } |
| + s.t.Fatalf("the stream closed waiting for %q", typ) |
| + case <-deadline: |
| + s.t.Fatalf("no %q within 5 s", typ) |
| + } |
| + } |
| +} |
| + |
| +// drain reads whatever the stream has already been sent, until it has |
| +// been quiet (heartbeats aside) for a moment. |
| +func (s *callStream) drain() { |
| + quiet := time.NewTimer(100 * time.Millisecond) |
| + defer quiet.Stop() |
| + for { |
| + select { |
| + case e := <-s.events: |
| + if e.typ != ":" { |
| + quiet.Reset(100 * time.Millisecond) |
| + } |
| + case <-quiet.C: |
| + return |
| + } |
| + } |
| +} |
| + |
| +// quiet fails if anything but heartbeats arrives for d, or the stream |
| +// closes, and reports how many heartbeats did. |
| +func (s *callStream) quiet(d time.Duration) int { |
| + s.t.Helper() |
| + beats := 0 |
| + deadline := time.After(d) |
| + for { |
| + select { |
| + case e := <-s.events: |
| + if e.typ != ":" { |
| + s.t.Fatalf("a held stream delivered %q %v", e.typ, e.data) |
| + } |
| + beats++ |
| + case <-s.closed: |
| + s.t.Fatal("a held stream closed") |
| + case <-deadline: |
| + return beats |
| + } |
| + } |
| +} |
| + |
| +// signal posts one message as jar's session. |
| +func (f *teamFixture) signal(jar map[string]*http.Cookie, sqid string, body map[string]any) *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + raw, _ := json.Marshal(body) |
| + saved := f.cookies |
| + f.cookies = jar |
| + defer func() { f.cookies = saved }() |
| + return f.doWith("POST", "/m/"+sqid+"/signal", string(raw), http.Header{"Content-Type": {"application/json"}}) |
| +} |
| + |
| +// join opens a stream and joins: the participation admitted, as a member |
| +// (or a guest in a meeting with no waiting room) is. |
| +func (f *teamFixture) join(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream { |
| + f.t.Helper() |
| + s := f.openStream(srv, jar, sqid) |
| + if w := f.signal(jar, sqid, map[string]any{"peer": s.peer, "type": "join"}); w.Code != http.StatusOK { |
| + f.t.Fatalf("join = %d %s", w.Code, w.Body.String()) |
| + } |
| + s.next("roster") |
| + return s |
| +} |
| + |
| +// guestJar joins a meeting's link as a named guest and returns their jar. |
| +func (f *teamFixture) guestJar(token, name string) map[string]*http.Cookie { |
| + f.t.Helper() |
| + saved := f.cookies |
| + f.cookies = map[string]*http.Cookie{} |
| + defer func() { f.cookies = saved }() |
| + if w := f.post("/j/"+token+"/guest", "name="+name); w.Code != http.StatusSeeOther { |
| + f.t.Fatalf("guest join = %d %s", w.Code, w.Body.String()) |
| + } |
| + return f.jar() |
| +} |
| + |
| +// fastStreams makes the streams re-decide and beat in milliseconds. |
| +func fastStreams(t *testing.T, f *teamFixture) { |
| + f.app.heartbeat.Store(int64(20 * time.Millisecond)) |
| + holdRetry, recheck := teamStreamHoldRetry, teamStreamRecheckMax |
| + teamStreamHoldRetry, teamStreamRecheckMax = 20*time.Millisecond, 40*time.Millisecond |
| + t.Cleanup(func() { teamStreamHoldRetry, teamStreamRecheckMax = holdRetry, recheck }) |
| +} |
| + |
| +// A meeting stands on its host. When the roster takes the host off the |
| +// team, the call in progress ends for everyone in it (members and guests: |
| +// lost{ended}), the meeting is ended and its links revoked, its links |
| +// 404 for everyone new, and no grant is minted through them. |
| +func TestTeamHostRemovalEndsTheCallAndItsLinks(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + host := teamSubject('h') |
| + f.member(host, "member") |
| + sqid, token := f.meeting("Host's call") |
| + alice := f.jar() |
| + f.member(teamSubject('b'), "member") |
| + bob := f.jar() |
| + gina := f.guestJar(token, "Gina") |
| + grants := f.count("guest_grants") |
| + aliceS := f.join(srv, alice, sqid) |
| + bobS := f.join(srv, bob, sqid) |
| + ginaS := f.join(srv, gina, sqid) |
| + _ = aliceS |
| + |
| + f.removed(host) |
| + for name, s := range map[string]*callStream{"bob": bobS, "gina": ginaS} { |
| + lost := s.next("lost") |
| + if lost.data["reason"] != "ended" { |
| + t.Fatalf("%s's stream: lost %v, want ended", name, lost.data) |
| + } |
| + } |
| + m := f.meetingRow(sqid) |
| + if m.EndedAt == nil || m.EndedBy != hostRemovedActor { |
| + t.Fatalf("the meeting was not ended for its host: %+v", m) |
| + } |
| + if n := f.app.hub.AdmittedCount(sqid); n != 0 { |
| + t.Fatalf("the hub still holds %d admitted in the ended call", n) |
| + } |
| + var live int |
| + f.app.db.Writer().QueryRow("SELECT count(*) FROM meeting_links WHERE meeting_id=? AND revoked_at IS NULL", m.ID).Scan(&live) |
| + if live != 0 { |
| + t.Fatalf("%d links still live", live) |
| + } |
| + f.cookies = map[string]*http.Cookie{} |
| + if w := f.get("/j/" + token); w.Code != http.StatusNotFound { |
| + t.Fatalf("a removed host's link = %d", w.Code) |
| + } |
| + if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a removed host's link, as a named guest = %d", w.Code) |
| + } |
| + if f.count("guest_grants") != grants { |
| + t.Fatal("a grant was minted through a removed host's link") |
| + } |
| + f.cookies = bob |
| + if w := f.page("/m/" + sqid + "/join"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a member opening the removed host's meeting = %d", w.Code) |
| + } |
| + if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") { |
| + t.Fatalf("the list does not show the meeting ended:\n%s", body) |
| + } |
| +} |
| + |
| +// Before anybody touches it, a removed host's meeting is settled where it |
| +// is listed: the list shows it ended, never as one that will refuse every |
| +// entry. And it is not revived by re-adding the host. |
| +func TestTeamListSettlesARemovedHostsMeetings(t *testing.T) { |
| + f := newTeamFixture(t) |
| + host := teamSubject('o') |
| + f.member(host, "member") |
| + sqid, _ := f.meeting("Orphaned") |
| + f.member(teamSubject('m'), "member") |
| + bob := f.jar() |
| + f.removed(host) |
| + f.cookies = bob |
| + if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") { |
| + t.Fatalf("the list still offers a removed host's meeting:\n%s", body) |
| + } |
| + f.dir.Set(host, "member") |
| + f.refreshed() |
| + if f.meetingRow(sqid).EndedAt == nil { |
| + t.Fatal("re-adding the host revived the meeting") |
| + } |
| + // A meeting whose host stands is untouched by the same listing. |
| + f.cookies = bob |
| + other, _ := f.meeting("Standing") |
| + f.page("/") |
| + if f.meetingRow(other).EndedAt != nil { |
| + t.Fatal("listing ended a meeting whose host stands") |
| + } |
| +} |
| + |
| +// An agent's meeting stands on the agent's operator. |
| +func TestTeamAnAgentsMeetingStandsOnItsOperator(t *testing.T) { |
| + f := newTeamFixture(t) |
| + // Two other people first, so the operator's person id is not the |
| + // agent's id. |
| + f.member(teamSubject('2'), "member") |
| + f.member(teamSubject('3'), "member") |
| + op := teamSubject('p') |
| + f.member(op, "member") |
| + bearer := f.agentToken("maker") |
| + w := f.api("POST", "/api/v1/meetings", bearer, `{"title":"By an agent"}`) |
| + if w.Code != http.StatusCreated { |
| + t.Fatalf("api create = %d", w.Code) |
| + } |
| + var out struct { |
| + Meeting struct{ Sqid string } |
| + Link string |
| + } |
| + json.Unmarshal(w.Body.Bytes(), &out) |
| + token := out.Link[strings.LastIndex(out.Link, "/")+1:] |
| + f.member(teamSubject('q'), "member") |
| + f.removed(op) |
| + f.cookies = map[string]*http.Cookie{} |
| + if w := f.get("/j/" + token); w.Code != http.StatusNotFound { |
| + t.Fatalf("a removed operator's agent's link = %d", w.Code) |
| + } |
| + if m := f.meetingRow(out.Meeting.Sqid); m.EndedAt == nil { |
| + t.Fatal("a removed operator's agent's meeting was not ended") |
| + } |
| +} |
| + |
| +// With the host's standing Unknown, nothing new enters — following the |
| +// link, joining by name, a fresh stream, an ICE fetch, a signal: each a |
| +// retryable 503 — and nothing is ended. The call in progress is held: |
| +// its streams stay open, carry heartbeats and deliver nothing. When the |
| +// roster is back, the held streams deliver again. |
| +func TestTeamHostUnknownRefusesEntriesAndHoldsTheCall(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, token := f.meeting("Held") |
| + alice := f.jar() |
| + f.member(teamSubject('b'), "member") |
| + bob := f.jar() |
| + gina := f.guestJar(token, "Gina") |
| + aliceS := f.join(srv, alice, sqid) |
| + bobS := f.join(srv, bob, sqid) |
| + ginaS := f.join(srv, gina, sqid) |
| + f.member(teamSubject('c'), "member") |
| + carol := f.jar() |
| + for _, s := range []*callStream{aliceS, bobS, ginaS} { |
| + s.drain() |
| + } |
| + |
| + // A visitor who followed the link before the roster went away. |
| + f.cookies = map[string]*http.Cookie{} |
| + f.page("/j/" + token) |
| + visitor := f.jar() |
| + f.expired() |
| + f.cookies = visitor |
| + // The sign-in form under that cookie: a retryable 503 — not "check |
| + // your email" with no mail behind it — and no pending row, no mail. |
| + retryable(t, "signing in through the link", f.post("/signin", "address=outsider%40example.test")) |
| + if n := f.count("pending_joins"); n != 0 { |
| + t.Fatalf("a link on an undecidable host wrote %d pending joins", n) |
| + } |
| + if body := f.mailBody(); body != "" { |
| + t.Fatalf("a link on an undecidable host mailed:\n%s", body) |
| + } |
| + f.cookies = map[string]*http.Cookie{} |
| + retryable(t, "following the link", f.page("/j/"+token)) |
| + retryable(t, "joining by name", f.post("/j/"+token+"/guest", "name=Late")) |
| + if _, status := f.tryStream(srv, carol, "/m/"+sqid+"/stream"); status != http.StatusServiceUnavailable { |
| + t.Fatalf("a fresh stream under Unknown = %d", status) |
| + } |
| + f.cookies = bob |
| + retryable(t, "ICE for a member", f.get("/m/"+sqid+"/ice?peer="+bobS.peer)) |
| + f.cookies = gina |
| + retryable(t, "ICE for a guest", f.get("/m/"+sqid+"/ice?peer="+ginaS.peer)) |
| + retryable(t, "a member's chat", f.signal(bob, sqid, map[string]any{"peer": bobS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}})) |
| + retryable(t, "a guest's chat", f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}})) |
| + // Leaving is always allowed. |
| + for _, s := range []*callStream{aliceS, bobS, ginaS} { |
| + if beats := s.quiet(200 * time.Millisecond); beats == 0 { |
| + t.Fatal("a held stream carried no heartbeat") |
| + } |
| + } |
| + f.app.hub.Tick(context.Background()) |
| + if f.meetingRow(sqid).EndedAt != nil { |
| + t.Fatal("Unknown ended the meeting") |
| + } |
| + // A stream that drops while held (its TTL, the network) resumes into |
| + // a held stream: its probe says it may, the resume attaches and says |
| + // hello, and nothing else is delivered — not even the roster a resume |
| + // owes — until standing is known again. |
| + bobS.cancel() |
| + time.Sleep(50 * time.Millisecond) |
| + f.cookies = bob |
| + if w := f.get("/m/" + sqid + "/stream?probe=1&peer=" + bobS.peer); w.Code != http.StatusNoContent { |
| + t.Fatalf("the resume probe under Unknown = %d %s", w.Code, w.Body.String()) |
| + } |
| + resumed, status := f.tryStream(srv, bob, "/m/"+sqid+"/stream?peer="+bobS.peer+"&last=%7B%7D") |
| + if status != http.StatusOK { |
| + t.Fatalf("a resume under Unknown = %d", status) |
| + } |
| + resumed.next("hello") |
| + resumed.quiet(150 * time.Millisecond) |
| + |
| + f.refreshed() |
| + if r := resumed.next("roster"); r.data["roster"] == nil { |
| + t.Fatalf("the resume's roster after recovery: %v", r.data) |
| + } |
| + bobS = resumed |
| + if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "back"}}); w.Code != http.StatusOK { |
| + t.Fatalf("a guest's chat after recovery = %d %s", w.Code, w.Body.String()) |
| + } |
| + for name, s := range map[string]*callStream{"alice": aliceS, "bob": bobS} { |
| + if chat := s.next("chat"); chat.data["payload"].(map[string]any)["text"] != "back" { |
| + t.Fatalf("%s got %v", name, chat.data) |
| + } |
| + } |
| + if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "leave"}); w.Code != http.StatusOK { |
| + t.Fatalf("leave = %d", w.Code) |
| + } |
| +} |
| + |
| +// A held stream delivers nothing published while it is held — here, a |
| +// chat a guest's request put on the hub after its own gate, as the lease |
| +// ran out — and delivers it, in order, once a Member answer says it may. |
| +func TestTeamHeldStreamDeliversNothingUntilStandingReturns(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, token := f.meeting("Held delivery") |
| + alice := f.jar() |
| + gina := f.guestJar(token, "Gina") |
| + aliceS := f.join(srv, alice, sqid) |
| + ginaS := f.join(srv, gina, sqid) |
| + aliceS.drain() |
| + |
| + f.expired() |
| + ginaSession := "" |
| + for _, c := range gina { |
| + if c.Name == f.app.auth.SessionCookie() { |
| + ginaSession = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value) |
| + } |
| + } |
| + for _, text := range []string{"one", "two"} { |
| + payload, _ := json.Marshal(map[string]string{"text": text}) |
| + if err := f.app.hub.Fanout(context.Background(), sqid, ginaSession, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload}); err != nil { |
| + t.Fatalf("fan out while held: %v", err) |
| + } |
| + } |
| + aliceS.quiet(150 * time.Millisecond) |
| + f.refreshed() |
| + for _, want := range []string{"one", "two"} { |
| + if chat := aliceS.next("chat"); chat.data["payload"].(map[string]any)["text"] != want { |
| + t.Fatalf("caught up out of order: %v", chat.data) |
| + } |
| + } |
| +} |
| + |
| +// sessionSubject is the session subject a jar's session carries. |
| +func sessionSubject(t *testing.T, f *teamFixture, jar map[string]*http.Cookie) string { |
| + t.Helper() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range jar { |
| + r.AddCookie(c) |
| + } |
| + id, ok := f.app.auth.SessionFrom(r) |
| + if !ok { |
| + t.Fatal("no session in the jar") |
| + } |
| + return id.Address |
| +} |
| + |
| +// A member the roster removes is ended within the lease, live session |
| +// included: their stream is told lost{standing}, the room is told they |
| +// have gone, and their next request is signed out. The host and the call |
| +// carry on. |
| +func TestTeamRemovalEndsAMembersLiveSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, _ := f.meeting("Ongoing") |
| + alice := f.jar() |
| + bobSubject := teamSubject('b') |
| + f.member(bobSubject, "member") |
| + f.signInHome(bobSubject) |
| + bob := f.jar() |
| + aliceS := f.join(srv, alice, sqid) |
| + bobS := f.join(srv, bob, sqid) |
| + aliceS.next("peer") |
| + |
| + f.removed(bobSubject) |
| + if lost := bobS.next("lost"); lost.data["reason"] != "standing" { |
| + t.Fatalf("the removed member's stream: %v", lost.data) |
| + } |
| + if gone := aliceS.next("gone"); gone.data["from"] != bobS.peer { |
| + t.Fatalf("the room was told %v", gone.data) |
| + } |
| + f.cookies = bob |
| + signedOutRemoved(t, "the removed member's ICE fetch", f.get("/m/"+sqid+"/ice?peer="+bobS.peer)) |
| + if f.meetingRow(sqid).EndedAt != nil { |
| + t.Fatal("a member's removal ended the host's meeting") |
| + } |
| +} |
| + |
| +// The stream-order lesson (oficina/slides #33, oficina/sheets #54): swept |
| +// across the lease's end, with a roster clock that ticks on every reading, |
| +// a decision is never "delivers, with nothing to renew" — every delivering |
| +// answer carries a timer of at least a second — and a lease that ran out |
| +// after the decision never stands for a delivery. |
| +func TestTeamStreamDecisionNeverDeliversWithoutALease(t *testing.T) { |
| + sawDeliver, sawHold := false, false |
| + for k := 1; k <= 30; k++ { |
| + f := newTeamFixture(t) |
| + srv := newStreamServer(t, f) |
| + subject := teamSubject('h') |
| + p := f.member(subject, "member") |
| + sqid, _ := f.meeting("Swept") |
| + s := f.join(srv, f.jar(), sqid) |
| + m := f.meetingRow(sqid) |
| + session := "" |
| + for _, c := range f.cookies { |
| + if c.Name == f.app.auth.SessionCookie() { |
| + session = hubSessionKey(f.app.hubSalt, subject, c.Value) |
| + } |
| + } |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + d := f.app.teamStreamDecide(freshStanding(context.Background()), m, p, sqid, session, hub.PeerID(s.peer)) |
| + switch d.verdict { |
| + case streamDelivers: |
| + sawDeliver = true |
| + if d.renew < time.Second || len(d.leases) == 0 { |
| + t.Fatalf("k=%d: delivers with renew %v on %d leases", k, d.renew, len(d.leases)) |
| + } |
| + case streamHolds: |
| + sawHold = true |
| + default: |
| + t.Fatalf("k=%d: Unknown ended the stream", k) |
| + } |
| + f.clock.SetTick(0) |
| + f.clock.Step(roster.MaximumAge) |
| + if d.stands() { |
| + t.Fatalf("k=%d: a lapsed lease still stands for a delivery", k) |
| + } |
| + s.cancel() |
| + } |
| + if !sawDeliver || !sawHold { |
| + t.Fatalf("the sweep did not cross the lease's end: deliver %v hold %v", sawDeliver, sawHold) |
| + } |
| +} |
| + |
| +// A knock's push goes only to people the roster says are Members when it |
| +// is sent: never to a removed member, never under Unknown. |
| +func TestTeamKnockPushGoesOnlyToCurrentMembers(t *testing.T) { |
| + f := newTeamFixture(t) |
| + push := &recordingPusher{} |
| + f.app.push = push |
| + alice := teamSubject('a') |
| + f.member(alice, "member") |
| + if w := f.json("/native/devices", `{"token":"aa01","platform":"ios"}`); w.Code != http.StatusNoContent { |
| + t.Fatalf("alice's device = %d", w.Code) |
| + } |
| + bob := teamSubject('b') |
| + f.member(bob, "member") |
| + if w := f.json("/native/devices", `{"token":"bb02","platform":"macos"}`); w.Code != http.StatusNoContent { |
| + t.Fatalf("bob's device = %d", w.Code) |
| + } |
| + f.removed(bob) |
| + f.app.knocked("room", nil, "Gina") |
| + if got := push.all(); len(got) != 1 || !strings.HasPrefix(got[0], "aa01|") { |
| + t.Fatalf("pushed %v, want alice's device only", got) |
| + } |
| + f.expired() |
| + f.app.knocked("room", nil, "Gina") |
| + if got := push.all(); len(got) != 1 { |
| + t.Fatalf("pushed under Unknown: %v", got) |
| + } |
| + // No push key: nothing breaks, nothing is sent. |
| + f.app.push = nil |
| + f.refreshed() |
| + f.app.knocked("room", nil, "Gina") |
| +} |
| + |
| +// The drive surface stands on the agent's operator, asked on every |
| +// request: removed, the one not-found body; Unknown, a retryable 503; |
| +// back on the team, it works again. |
| +func TestTeamAgentStandsOnItsOperator(t *testing.T) { |
| + f := newTeamFixture(t) |
| + op := teamSubject('o') |
| + f.member(op, "member") |
| + bearer := f.agentToken("bot") |
| + if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK { |
| + t.Fatalf("member's agent = %d", w.Code) |
| + } |
| + f.member(teamSubject('q'), "member") |
| + sqid, _ := f.meeting("Somebody's") |
| + // And one already over, which no host check would refuse: only the |
| + // gate's own answer for the operator stands between it and a 200. |
| + over, _ := f.meeting("Over") |
| + if w := f.post("/meetings/"+over+"/end", ""); w.Code != http.StatusSeeOther { |
| + t.Fatalf("end = %d", w.Code) |
| + } |
| + f.expired() |
| + if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("operator Unknown = %d", w.Code) |
| + } |
| + // An item, too: a meeting another member made. |
| + for _, item := range []string{sqid, over} { |
| + if w := f.api("GET", "/api/v1/meetings/"+item, bearer, ""); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("an item under an Unknown operator = %d %s", w.Code, w.Body.String()) |
| + } |
| + } |
| + f.removed(op) |
| + if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "not-found") { |
| + t.Fatalf("operator removed = %d %s", w.Code, w.Body.String()) |
| + } |
| + f.dir.Set(op, "member") |
| + f.refreshed() |
| + if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK { |
| + t.Fatalf("operator re-added = %d", w.Code) |
| + } |
| +} |
| + |
| +// standingOf for somebody the roster cannot be asked about is NotMember; |
| +// for storage that cannot be read, Unknown. |
| +func TestTeamStandingOfSomebodyElse(t *testing.T) { |
| + f := newTeamFixture(t) |
| + p := f.member(teamSubject('s'), "member") |
| + if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Member { |
| + t.Fatalf("a member = %v", st) |
| + } |
| + if st := f.app.standingOf(context.Background(), 999).State(); st != roster.NotMember { |
| + t.Fatalf("nobody = %v", st) |
| + } |
| + f.app.db.Writer().Exec("ALTER TABLE calls_team_home_persons RENAME TO unreadable") |
| + if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Unknown { |
| + t.Fatalf("unreadable = %v", st) |
| + } |
| + var acc *teammode.Access |
| + if acc.State() != roster.Unknown { |
| + t.Fatal("a nil Access is not Unknown") |
| + } |
| +} |
| + |
| +// Before anybody has touched it, a removed host's link is already dead: |
| +// to a visitor following it (who is shown no title), to a sign-in it |
| +// would carry (no pending join is written, so no mail is owed), and the |
| +// meeting is ended by the first of them. |
| +func TestTeamARemovedHostsLinkIsDeadBeforeAnyoneTouchesIt(t *testing.T) { |
| + f := newTeamFixture(t) |
| + host := teamSubject('k') |
| + f.member(host, "member") |
| + sqid, token := f.meeting("Secret title") |
| + // A visitor followed the link while the host stood: the join cookie |
| + // the sign-in form reads. |
| + f.cookies = map[string]*http.Cookie{} |
| + if w := f.page("/j/" + token); w.Code != http.StatusOK { |
| + t.Fatalf("the link while the host stands = %d", w.Code) |
| + } |
| + visitor := f.jar() |
| + f.removed(host) |
| + f.cookies = visitor |
| + if w := f.post("/signin", "address=outsider%40example.test"); w.Code != http.StatusSeeOther { |
| + t.Fatalf("sign-in = %d", w.Code) |
| + } |
| + if n := f.count("pending_joins"); n != 0 { |
| + t.Fatalf("a removed host's link wrote %d pending joins", n) |
| + } |
| + f.cookies = map[string]*http.Cookie{} |
| + persons := f.count("persons") |
| + if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a removed host's link, joining by name = %d", w.Code) |
| + } |
| + if f.count("persons") != persons || f.count("guest_grants") != 0 { |
| + t.Fatal("a removed host's link made a guest") |
| + } |
| + w := f.page("/j/" + token) |
| + if w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), "Secret title") { |
| + t.Fatalf("a removed host's link = %d", w.Code) |
| + } |
| + if f.meetingRow(sqid).EndedAt == nil { |
| + t.Fatal("following a removed host's link did not end the meeting") |
| + } |
| +} |
| + |
| +// The quiet case (spec §2.4's tick): with nobody's stream re-deciding, |
| +// the hub's own pass ends a removed host's call, and a member opening |
| +// another of that host's meetings, untouched until now, finds it ended. |
| +func TestTeamTheTickEndsAQuietCallWhoseHostLeft(t *testing.T) { |
| + f := newTeamFixture(t) |
| + srv := newStreamServer(t, f) |
| + host := teamSubject('t') |
| + f.member(host, "member") |
| + sqid, token := f.meeting("Quiet") |
| + other, _ := f.meeting("Untouched") |
| + alice := f.jar() |
| + f.member(teamSubject('u'), "member") |
| + bob := f.jar() |
| + gina := f.guestJar(token, "Gina") |
| + f.join(srv, alice, sqid) |
| + bobS := f.join(srv, bob, sqid) |
| + ginaS := f.join(srv, gina, sqid) |
| + f.removed(host) |
| + f.app.hub.Tick(context.Background()) |
| + for _, s := range []*callStream{bobS, ginaS} { |
| + if lost := s.next("lost"); lost.data["reason"] != "ended" { |
| + t.Fatalf("after the tick: %v", lost.data) |
| + } |
| + } |
| + f.cookies = bob |
| + if w := f.page("/m/" + other + "/join"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a removed host's untouched meeting = %d", w.Code) |
| + } |
| + if f.meetingRow(other).EndedAt == nil { |
| + t.Fatal("opening it did not end it") |
| + } |
| +} |
| + |
| +// Swept across the lease's end with a roster clock that ticks on every |
| +// reading — so that a host asked a moment later can still stand while the |
| +// request's own standing has run out — every answer is either what a |
| +// member gets or a retryable 503: never "not found", never a 500, and |
| +// never a grant for a member who needs none. |
| +func TestTeamAnswersAcrossTheLeaseEdgeAreWholeOrRetryable(t *testing.T) { |
| + retries := 0 |
| + for k := 1; k <= 30; k++ { |
| + f := newTeamFixture(t) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, token := f.meeting("Edge") |
| + host := f.jar() |
| + s := f.join(srv, host, sqid) |
| + s.drain() |
| + f.member(teamSubject('m'), "member") |
| + member := f.jar() |
| + link, _, _, _ := f.app.store.liveLink(context.Background(), token) |
| + edge := func() { |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + } |
| + check := func(what string, w *httptest.ResponseRecorder, ok ...int) { |
| + t.Helper() |
| + for _, c := range ok { |
| + if w.Code == c { |
| + return |
| + } |
| + } |
| + if w.Code == http.StatusServiceUnavailable { |
| + retryable(t, what, w) |
| + retries++ |
| + return |
| + } |
| + t.Fatalf("k=%d %s = %d %s", k, what, w.Code, w.Body.String()) |
| + } |
| + f.cookies = member |
| + edge() |
| + check("the holding screen", f.page("/m/"+sqid+"/join"), http.StatusOK) |
| + f.clock.SetTick(0) |
| + edge() |
| + check("a member follows the link", f.page("/j/"+token), http.StatusSeeOther) |
| + f.clock.SetTick(0) |
| + f.app.store.writePending(context.Background(), f.personFor(teamSubject('m')).Email, link) |
| + edge() |
| + check("a member's pending join", f.page("/continue"), http.StatusSeeOther) |
| + f.clock.SetTick(0) |
| + edge() |
| + check("a chat", f.signal(host, sqid, map[string]any{"peer": s.peer, "type": "chat", "payload": map[string]any{"text": "x"}}), http.StatusOK) |
| + f.clock.SetTick(0) |
| + if n := f.count("guest_grants"); n != 0 { |
| + t.Fatalf("k=%d: a member was given %d grants", k, n) |
| + } |
| + s.cancel() |
| + } |
| + if retries == 0 { |
| + t.Fatal("the sweep never reached the lease's end") |
| + } |
| +} |
| + |
| +// A held stream keeps what arrives, in order, but no more than a |
| +// subscriber's buffer: past it the stream ends lost{buffer}, and the |
| +// browser resumes. |
| +func TestTeamHeldStreamEndsPastTheBuffer(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, token := f.meeting("Overflow") |
| + alice := f.jar() |
| + gina := f.guestJar(token, "Gina") |
| + aliceS := f.join(srv, alice, sqid) |
| + ginaS := f.join(srv, gina, sqid) |
| + aliceS.drain() |
| + f.expired() |
| + session := "" |
| + for _, c := range gina { |
| + if c.Name == f.app.auth.SessionCookie() { |
| + session = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value) |
| + } |
| + } |
| + payload, _ := json.Marshal(map[string]string{"text": "x"}) |
| + for range teamStreamHeld + 2 { |
| + f.app.hub.Fanout(context.Background(), sqid, session, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload}) |
| + // Slowly enough that the stream reads each one off the hub, so |
| + // it is the held stream's own bound that is reached, not the |
| + // hub's buffer for a subscriber that is not reading. |
| + time.Sleep(2 * time.Millisecond) |
| + } |
| + if lost := aliceS.next("lost"); lost.data["reason"] != "buffer" { |
| + t.Fatalf("an overflowing held stream: %v", lost.data) |
| + } |
| +} |
| + |
| +// What ends a stream is said at once even while it is held: a second tab |
| +// resuming the same participation replaces the held one, which is told so |
| +// and closes, rather than holding the news until standing returns. |
| +func TestTeamHeldStreamIsToldItWasReplaced(t *testing.T) { |
| + f := newTeamFixture(t) |
| + fastStreams(t, f) |
| + srv := newStreamServer(t, f) |
| + f.member(teamSubject('h'), "member") |
| + sqid, _ := f.meeting("Replaced") |
| + alice := f.jar() |
| + first := f.join(srv, alice, sqid) |
| + first.drain() |
| + f.expired() |
| + second, status := f.tryStream(srv, alice, "/m/"+sqid+"/stream?peer="+first.peer+"&last=%7B%7D") |
| + if status != http.StatusOK { |
| + t.Fatalf("the second tab's resume = %d", status) |
| + } |
| + second.next("hello") |
| + if lost := first.next("lost"); lost.data["reason"] != "replaced" { |
| + t.Fatalf("the held stream was told %v", lost.data) |
| + } |
| +} |
diff --git a/internal/calls/team_config.go b/internal/calls/team_config.go| new file mode 100644 |
| index 0000000..f7b80cd |
| --- /dev/null |
| +++ b/internal/calls/team_config.go |
| @@ -0,0 +1,129 @@ |
| +package calls |
| + |
| +// Team mode: Home's roster decides standing (Home implementation/ |
| +// team-members.md Part B §7; implementation/teammode-package.md §7.4). |
| +// Configuration, the marker, the roster runtime and the probe are |
| +// home/teammode's: CALLS_TEAM_ID, _DIRECTORY_ORIGIN, _PROVISIONING_BASE64, |
| +// _OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN, all or none, and only beside |
| +// CALLS_HOME_*. Without them nothing in the team_*.go files runs and |
| +// Calls is the allowlist app it has always been. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/calls/internal/calls/teamstate" |
| +) |
| + |
| +// homeNamespace is Calls' Home storage namespace: connect's link and |
| +// handoff sealing, and in team mode the roster evidence's. |
| +const homeNamespace = "oficina/calls" |
| + |
| +// teamState is the activation marker and the roster evidence, in |
| +// calls_team_required and calls_team_roster_evidence (migration set |
| +// calls_team, teammode's own SQL). The marker is read before anything |
| +// migrates (teamBootSchema). |
| +var teamState = teammode.MustState("calls") |
| + |
| +// teamIssuerTables are the tables holding Home identities in an issuer |
| +// column: connect's links and Calls' Home-only persons. teammode.Open |
| +// refuses activation while any row names another issuer. |
| +var teamIssuerTables = []string{"home_identity_links", "calls_team_home_persons"} |
| + |
| +// homeSchema is what wireHome applies beside Calls' own schema: the |
| +// handoff and link tables connect needs. |
| +func homeSchema() *migrate.Set { |
| + return migrate.Merge(migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| +} |
| + |
| +// teamBoot is base plus Home's tables plus team state: teammode's marker |
| +// set, then Calls' Home-only persons (whose triggers name persons 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, homeSchema(), teamState.Schema(), teamstate.Schema) |
| +} |
| + |
| +// teamSettings verifies team configuration for this instance: nil, nil |
| +// with team mode off; otherwise a verified record or ErrConfig. 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 build 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, teammode.ErrConfig |
| + } |
| + return teammode.Verify(cfg, &teammode.Home{Issuer: home.Issuer, ConsumerID: home.ConsumerID}, "calls", origin) |
| +} |
| + |
| +// teamBootSchema is the schema build 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 |
| +// CALLS_ALLOWED_ADDRESSES. Off, and never activated, it is base: one |
| +// sqlite_master read, and boot is otherwise unchanged. |
| +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 persons 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 wired, |
| +// 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() error { |
| + settings := a.cfg.team |
| + if settings == nil { |
| + return nil |
| + } |
| + if a.home == nil || a.cfg.home == nil { |
| + return teammode.ErrConfig |
| + } |
| + sealer, err := seal.New(a.cfg.home.DEK, homeNamespace) |
| + if err != nil { |
| + return teammode.ErrConfig |
| + } |
| + 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} |
| + a.store.team = true |
| + return nil |
| +} |
| + |
| +// 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/calls/team_config_test.go b/internal/calls/team_config_test.go| new file mode 100644 |
| index 0000000..7e3750a |
| --- /dev/null |
| +++ b/internal/calls/team_config_test.go |
| @@ -0,0 +1,265 @@ |
| +package calls |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +// tableExists reports whether path's database has table, read without the |
| +// app. |
| +func tableExists(t *testing.T, path, table string) bool { |
| + t.Helper() |
| + d := openTeamDB(t, path) |
| + var n int |
| + if err := d.Writer().QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", table).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n == 1 |
| +} |
| + |
| +// markerFor reports whether path holds an activation marker. |
| +func markerFor(t *testing.T, path string) bool { |
| + t.Helper() |
| + d := openTeamDB(t, path) |
| + _, activated, err := teamState.Required(context.Background(), d.Writer()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return activated |
| +} |
| + |
| +// bootAt builds the app over path with cfg, returning the error. |
| +func bootAt(t *testing.T, path string, cfg Config) error { |
| + t.Helper() |
| + d := openTeamDB(t, path) |
| + _, _, err := buildForTest(t, d, cfg) |
| + return err |
| +} |
| + |
| +func TestTeamEnvNamesAreTheFive(t *testing.T) { |
| + want := [5]string{"CALLS_TEAM_ID", "CALLS_TEAM_DIRECTORY_ORIGIN", "CALLS_TEAM_PROVISIONING_BASE64", "CALLS_TEAM_OPERATOR_KEYS_BASE64", "CALLS_TEAM_ROSTER_TOKEN"} |
| + if got := teammode.EnvNames("CALLS"); got != want { |
| + t.Fatalf("CALLS team variables %v", got) |
| + } |
| + if teammode.ConfigFromLookup("CALLS", func(string) string { return "" }) != nil { |
| + t.Fatal("no team variables read as team mode") |
| + } |
| +} |
| + |
| +// Every binding the provisioning record names is pinned: one signed for |
| +// another issuer, consumer, app, origin, team or directory refuses boot |
| +// before anything migrates, and writes no marker. |
| +func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, mutate := range map[string]func(*roster.Bindings){ |
| + "issuer": func(b *roster.Bindings) { b.Issuer = "https://id.elsewhere.test" }, |
| + "consumer": func(b *roster.Bindings) { b.Consumer = "someone-else" }, |
| + "app": func(b *roster.Bindings) { b.App = "calendar" }, |
| + "origin": func(b *roster.Bindings) { b.Audience = "https://calls.elsewhere.test" }, |
| + "team": func(b *roster.Bindings) { b.Team = "TeamB" }, |
| + "directory": func(b *roster.Bindings) { b.Directory = "https://home.elsewhere.test" }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + b := teamTestBindings() |
| + mutate(&b) |
| + cfg, _, _ := teamConfigFor(t, b, key) |
| + if name == "team" || name == "directory" { |
| + // The record names the team and directory; the |
| + // instance's own configuration must name the same ones. |
| + good, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + good.Team.ProvisioningBase64 = cfg.Team.ProvisioningBase64 |
| + good.Team.OperatorKeysBase64 = cfg.Team.OperatorKeysBase64 |
| + cfg = good |
| + } |
| + path := filepath.Join(t.TempDir(), "calls.db") |
| + if err := bootAt(t, path, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a record signed for another %s: %v", name, err) |
| + } |
| + if tableExists(t, path, "persons") || markerFor(t, path) { |
| + t.Fatalf("a refused %s migrated or wrote the marker", name) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTeamEnvIsAllOrNoneAndNeedsHome(t *testing.T) { |
| + key, _ := assertioncrypto.Generate() |
| + for _, name := range teammode.EnvNames("CALLS") { |
| + env := map[string]string{} |
| + for _, n := range teammode.EnvNames("CALLS") { |
| + env[n] = "x" |
| + } |
| + delete(env, name) |
| + c := teammode.ConfigFromLookup("CALLS", func(k string) string { return env[k] }) |
| + if c == nil { |
| + t.Fatalf("four of five (%s missing) read as team mode off", name) |
| + } |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + cfg.Team = c |
| + path := filepath.Join(t.TempDir(), "calls.db") |
| + if err := bootAt(t, path, cfg); err == nil { |
| + t.Fatalf("four of five (%s missing) booted", name) |
| + } |
| + if tableExists(t, path, "persons") { |
| + t.Fatalf("four of five (%s missing) migrated", name) |
| + } |
| + } |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + cfg.Home = nil |
| + if err := bootAt(t, filepath.Join(t.TempDir(), "calls.db"), cfg); err == nil { |
| + t.Fatal("team mode booted without Home") |
| + } |
| +} |
| + |
| +func TestTeamTheAllowlistBecomesOptionalAndAdmitsOnlyLocally(t *testing.T) { |
| + team := &teammode.Config{TeamID: "TeamA"} |
| + for _, env := range []string{"production", EnvDevelopment} { |
| + list, err := resolveAllowlist(Config{Env: env, Team: team}) |
| + if err != nil { |
| + t.Fatalf("%s team mode with no allowlist: %v", env, err) |
| + } |
| + // Never the development default that admits everyone. |
| + if list.addrs == nil || list.allows("anyone@example.test") { |
| + t.Fatalf("an empty %s team allowlist admits somebody locally", env) |
| + } |
| + list, err = resolveAllowlist(Config{Env: env, Team: team, AllowedAddresses: []string{"alice@example.test"}}) |
| + if err != nil || !list.allows("alice@example.test") || list.allows("bob@example.test") { |
| + t.Fatalf("a %s team allowlist is not the local door: %v", env, err) |
| + } |
| + } |
| + if _, err := resolveAllowlist(Config{Env: "production"}); err == nil { |
| + t.Fatal("production without team mode accepted no allowlist") |
| + } |
| + // Alta's shape: no allowlist at all, in production. It boots, and |
| + // the local door admits nobody. |
| + key, _ := assertioncrypto.Generate() |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + cfg.AllowedAddresses = nil |
| + _, a, err := buildForTest(t, openTeamDB(t, filepath.Join(t.TempDir(), "calls.db")), cfg) |
| + if err != nil { |
| + t.Fatalf("team mode with no allowlist: %v", err) |
| + } |
| + if a.authorize("anyone@example.test") { |
| + t.Fatal("an empty team allowlist admits an address at the local door") |
| + } |
| +} |
| + |
| +// Once activated, a database refuses to boot without team configuration |
| +// or with another binding, before anything migrates; the marker's |
| +// triggers refuse a rewrite. |
| +func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| + f := newTeamFixture(t) |
| + if !markerFor(t, f.dbPath) { |
| + t.Fatal("team mode wrote no marker") |
| + } |
| + off := f.cfg |
| + off.Team = nil |
| + if err := bootAt(t, f.dbPath, off); err == nil { |
| + t.Fatal("an activated database booted without team mode") |
| + } |
| + key, _ := assertioncrypto.Generate() |
| + b := teamTestBindings() |
| + b.Team = "TeamB" |
| + other, _, _ := teamConfigFor(t, b, key) |
| + other.Team.TeamID = "TeamB" |
| + if err := bootAt(t, f.dbPath, other); err == nil { |
| + t.Fatal("an activated database booted with another team's binding") |
| + } |
| + if err := bootAt(t, f.dbPath, f.cfg); err != nil { |
| + t.Fatalf("the same binding refused: %v", err) |
| + } |
| + for _, stmt := range []string{"UPDATE calls_team_required SET fingerprint='x'", "DELETE FROM calls_team_required"} { |
| + if _, err := f.app.db.Writer().Exec(stmt); err == nil { |
| + t.Fatalf("%s: allowed", stmt) |
| + } |
| + } |
| +} |
| + |
| +// The census: a Home identity from another issuer in either table refuses |
| +// activation, and no marker is written. The tables are named here, not |
| +// read from teamIssuerTables: a list that lost a table would otherwise |
| +// lose its test with it. |
| +func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| + for _, table := range []string{"home_identity_links", "calls_team_home_persons"} { |
| + t.Run(table, func(t *testing.T) { |
| + key, _ := assertioncrypto.Generate() |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) |
| + // A database migrated in team mode's shape but not yet |
| + // activated, holding one row from another issuer. |
| + path := filepath.Join(t.TempDir(), "calls.db") |
| + d := openTeamDB(t, path) |
| + if _, err := migrate.Apply(context.Background(), d, teamBoot(BootSchema)); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := d.Writer() |
| + res, err := w.Exec("INSERT INTO persons(email,name,created_at,anonymous) VALUES('home-only:00','n',0,0)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + person, _ := res.LastInsertId() |
| + if _, err := w.Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.elsewhere.test',?,?)", teamSubject('q'), person); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := buildForTest(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a foreign issuer in %s: %v", table, err) |
| + } |
| + if markerFor(t, path) { |
| + t.Fatalf("a refused census in %s wrote the marker", table) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// GET /api/team: {"team_mode":false} off; on, only {team_mode, consumer, |
| +// roster} with the roster's three states, no-store, whoever asks. |
| +func TestTeamProbeSaysOnlyItsState(t *testing.T) { |
| + probe := func(h http.Handler) (map[string]any, *httptest.ResponseRecorder) { |
| + w := httptest.NewRecorder() |
| + h.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", w.Body.String()) |
| + } |
| + if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("probe = %d %q", w.Code, w.Header().Get("Cache-Control")) |
| + } |
| + return body, w |
| + } |
| + off := newHomeRouterFixture(t) |
| + if body, w := probe(off.handler); len(body) != 1 || body["team_mode"] != false { |
| + t.Fatalf("team mode off: %s", w.Body.String()) |
| + } |
| + f := newTeamFixture(t) |
| + f.dir.SetDown(true) |
| + if body, _ := probe(f.handler); body["roster"] != "unknown" { |
| + t.Fatalf("before any roster: %v", body) |
| + } |
| + f.refreshed() |
| + body, w := probe(f.handler) |
| + if len(body) != 3 || body["team_mode"] != true || body["consumer"] != teamTestConsumer || body["roster"] != "ok" { |
| + t.Fatalf("roster held: %s", w.Body.String()) |
| + } |
| + for _, leak := range []string{"TeamA", homeTestIssuer, "pr_", "@"} { |
| + if strings.Contains(w.Body.String(), leak) { |
| + t.Fatalf("the probe says %q: %s", leak, w.Body.String()) |
| + } |
| + } |
| + f.expired() |
| + if body, _ := probe(f.handler); body["roster"] != "stale" { |
| + t.Fatalf("aged out: %v", body) |
| + } |
| +} |
diff --git a/internal/calls/team_fixture_test.go b/internal/calls/team_fixture_test.go| new file mode 100644 |
| index 0000000..819c4c4 |
| --- /dev/null |
| +++ b/internal/calls/team_fixture_test.go |
| @@ -0,0 +1,290 @@ |
| +package calls |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "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/sessions" |
| +) |
| + |
| +// Team mode's fixture: Home configured exactly as homeRouterFixture does |
| +// (same issuer, origin, consumer and assertion key, so its local and |
| +// exchange helpers drive this app too), 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 teamTestConsumer = "calls-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 |
| +// homeRouterFixture configures them, the test directory and team, Calls, |
| +// and the test origin. |
| +func teamTestBindings() roster.Bindings { |
| + b := teammodetest.Bindings("calls", teamTestConsumer, homeTestOrigin) |
| + b.Issuer = homeTestIssuer |
| + return b |
| +} |
| + |
| +type teamFixture struct { |
| + *homeRouterFixture |
| + t *testing.T |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| + cfg Config |
| + d *db.DB |
| + dbPath string |
| +} |
| + |
| +// teamConfigFor is a team-mode Config on bindings b: Home as |
| +// homeRouterFixture has it, the record signed for b, and the test |
| +// directory and clock. allowed is CALLS_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() |
| + cfg := Config{Origin: homeTestOrigin, InstanceKey: "test-only-instance", DEK: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)), |
| + AllowedAddresses: allowed, Mailer: &homeTestMail{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| + Home: &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: homeKeysBase64(key), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}, |
| + Team: tcfg, teamTransport: dir, teamClock: clock} |
| + return cfg, dir, clock |
| +} |
| + |
| +func openTeamDB(t *testing.T, path string) *db.DB { |
| + t.Helper() |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + return d |
| +} |
| + |
| +// newTeamFixture is a team-mode Calls with alice@example.test (or |
| +// allowed) admitted to the local door. |
| +func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { |
| + t.Helper() |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(allowed) == 0 { |
| + allowed = []string{"alice@example.test"} |
| + } |
| + dbPath := filepath.Join(t.TempDir(), "calls.db") |
| + d := openTeamDB(t, dbPath) |
| + cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, allowed...) |
| + mux, a, err := buildForTest(t, d, cfg) |
| + if err != nil { |
| + t.Fatalf("build in team mode: %v", err) |
| + } |
| + hf := &homeRouterFixture{app: a, handler: mux, key: key, mail: cfg.Mailer.(*homeTestMail), cookies: map[string]*http.Cookie{}} |
| + return &teamFixture{homeRouterFixture: hf, t: t, dir: dir, clock: clock, cfg: cfg, d: d, dbPath: dbPath} |
| +} |
| + |
| +func (f *teamFixture) get(path string) *httptest.ResponseRecorder { return f.do("GET", path, "") } |
| +func (f *teamFixture) post(path, body string) *httptest.ResponseRecorder { |
| + return f.do("POST", path, body) |
| +} |
| + |
| +// page is a GET that asks for a page, as a browser navigation does. |
| +func (f *teamFixture) page(path string) *httptest.ResponseRecorder { |
| + return f.doWith("GET", path, "", http.Header{"Accept": {"text/html"}}) |
| +} |
| + |
| +// json is a POST with a JSON body, as the native app and the share |
| +// button send. |
| +func (f *teamFixture) json(path, body string) *httptest.ResponseRecorder { |
| + return f.doWith("POST", path, body, http.Header{"Content-Type": {"application/json"}}) |
| +} |
| + |
| +// signInHome runs a full Home exchange for subject from an empty jar and |
| +// returns the finish response. |
| +func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + f.cookies = map[string]*http.Cookie{} |
| + start := homeRedirect(f.t, f.do("GET", "/signin", "")) |
| + return f.exchange(f.t, start, subject) |
| +} |
| + |
| +// member puts subject on the roster with role, refreshes, and signs them |
| +// in with Home from an empty jar, failing unless they reach the meeting |
| +// list; it returns their person. |
| +func (f *teamFixture) member(subject, role string) Person { |
| + f.t.Helper() |
| + f.dir.Set(subject, role) |
| + f.refreshed() |
| + finish := f.signInHome(subject) |
| + if finish.Code != http.StatusSeeOther { |
| + f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) |
| + } |
| + if w := f.get("/"); w.Code != http.StatusOK { |
| + f.t.Fatalf("meeting list of %s = %d %s", subject, w.Code, w.Header().Get("Location")) |
| + } |
| + return f.personFor(subject) |
| +} |
| + |
| +// jar is the cookie jar now, to switch between people. |
| +func (f *teamFixture) jar() map[string]*http.Cookie { |
| + out := make(map[string]*http.Cookie, len(f.cookies)) |
| + for k, v := range f.cookies { |
| + out[k] = v |
| + } |
| + return out |
| +} |
| + |
| +// personFor is the person a Home subject signs in as. |
| +func (f *teamFixture) personFor(subject string) Person { |
| + f.t.Helper() |
| + ref, err := f.app.home.bridge.Resolve(context.Background(), subject) |
| + if err != nil { |
| + f.t.Fatalf("resolve %s: %v", subject, err) |
| + } |
| + p, ok, err := f.app.store.personByID(context.Background(), ref.ID) |
| + if err != nil || !ok { |
| + f.t.Fatalf("person %d: %v %v", ref.ID, ok, err) |
| + } |
| + return p |
| +} |
| + |
| +// 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.dir.SetDown(false) |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + // A refresh a request started while the directory was down may still |
| + // be in flight, and Refresh joins it: past it, ask again. |
| + var err error |
| + for range 5 { |
| + if err = f.app.team.Refresh(context.Background()); err == nil { |
| + return |
| + } |
| + f.clock.Step(roster.RetryAfter + time.Second) |
| + } |
| + 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) |
| +} |
| + |
| +// removed takes subject off the roster and refreshes: NotMember. |
| +func (f *teamFixture) removed(subject string) { |
| + f.t.Helper() |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| +} |
| + |
| +// withAccess is ctx carrying subject's standing now, for store calls a |
| +// test makes directly as that person. |
| +func (f *teamFixture) withAccess(subject string) context.Context { |
| + return teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) |
| +} |
| + |
| +// localSession puts a local (magic link) session for address in the jar, |
| +// as a sign-in the local door admitted would. |
| +func (f *teamFixture) localSession(address string) { |
| + f.t.Helper() |
| + w := httptest.NewRecorder() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.cookies = map[string]*http.Cookie{} |
| + for _, c := range w.Result().Cookies() { |
| + f.cookies[c.Name] = c |
| + } |
| +} |
| + |
| +var ( |
| + reTeamToken = regexp.MustCompile(`/j/([A-Za-z0-9_-]{43})`) |
| + reTeamSqid = regexp.MustCompile(`/m/([23456789a-z]{10})/join`) |
| +) |
| + |
| +// meeting makes a meeting as whoever is signed in and returns its sqid |
| +// and its link's token. |
| +func (f *teamFixture) meeting(title string) (sqid, token string) { |
| + f.t.Helper() |
| + w := f.post("/meetings", "title="+strings.ReplaceAll(title, " ", "+")) |
| + if w.Code != http.StatusOK { |
| + f.t.Fatalf("create %q = %d %s", title, w.Code, w.Body.String()) |
| + } |
| + tok, sq := reTeamToken.FindStringSubmatch(w.Body.String()), reTeamSqid.FindStringSubmatch(w.Body.String()) |
| + if tok == nil || sq == nil { |
| + f.t.Fatalf("no link on the link page:\n%s", w.Body.String()) |
| + } |
| + return sq[1], tok[1] |
| +} |
| + |
| +// meetingRow reads a meeting back. |
| +func (f *teamFixture) meetingRow(sqid string) Meeting { |
| + f.t.Helper() |
| + m, ok, err := f.app.store.meetingBySqid(context.Background(), sqid) |
| + if err != nil || !ok { |
| + f.t.Fatalf("meeting %s: %v %v", sqid, ok, err) |
| + } |
| + return m |
| +} |
| + |
| +// count is a table's row count. |
| +func (f *teamFixture) count(table string) int { |
| + f.t.Helper() |
| + var n int |
| + if err := f.app.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// retryable fails unless w is the team-mode retryable 503. |
| +func retryable(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| + t.Fatalf("%s = %d (Retry-After %q, Cache-Control %q), want a retryable no-store 503: %s", what, w.Code, w.Header().Get("Retry-After"), w.Header().Get("Cache-Control"), w.Body.String()) |
| + } |
| +} |
| + |
| +// signedOutRemoved fails unless w ended the session and said why. |
| +func signedOutRemoved(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + switch w.Code { |
| + case http.StatusSeeOther: |
| + if !strings.Contains(w.Header().Get("Location"), "err=removed") { |
| + t.Fatalf("%s: redirected to %q, want the removed notice", what, w.Header().Get("Location")) |
| + } |
| + case http.StatusForbidden: |
| + default: |
| + t.Fatalf("%s = %d, want the removed member signed out", what, w.Code) |
| + } |
| + ended := false |
| + for _, c := range w.Result().Cookies() { |
| + if c.MaxAge < 0 { |
| + ended = true |
| + } |
| + } |
| + if !ended { |
| + t.Fatalf("%s: the session cookie was not cleared", what) |
| + } |
| +} |
diff --git a/internal/calls/team_guard.go b/internal/calls/team_guard.go| new file mode 100644 |
| index 0000000..753643b |
| --- /dev/null |
| +++ b/internal/calls/team_guard.go |
| @@ -0,0 +1,74 @@ |
| +package calls |
| + |
| +// Team mode's write guard: the standing a write was admitted on, checked |
| +// again inside the transaction that commits it, before and after |
| +// (teammode.Guard; Home implementation/teammode-package.md §3, invariant |
| +// 13). The route's gate (team_access.go) decides whether a 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 context carries, whose lease check |
| +// never waits, so it is safe under the one-connection SQLite writer. |
| +// |
| +// Whose standing a write rests on is the caller's to put on the context: |
| +// |
| +// - a member's own write (a meeting, a link, an ending, settings, an |
| +// agent token, a device): the request's Access, put there by |
| +// requirePerson; |
| +// - an agent's write: its operator's, put there by requireAgent; |
| +// - a guest's grant, minted by following a link: the meeting HOST's |
| +// (team_host.go), because a link stands on its host. |
| +// |
| +// Writes nobody's standing makes — a meeting ended because its host left |
| +// the team, sign-in bookkeeping, identity rows — are systemWrite or never |
| +// reach the guard. Outside team mode store.team is false and every helper |
| +// here is the write path exactly as it was. |
| + |
| +import ( |
| + "context" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// 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 |
| + |
| +type systemWriteKey struct{} |
| + |
| +// systemWrite marks ctx as carrying a write that nobody's standing makes: |
| +// the instance ending a meeting whose host the roster says has left. |
| +func systemWrite(ctx context.Context) context.Context { |
| + return context.WithValue(ctx, systemWriteKey{}, true) |
| +} |
| + |
| +func isSystemWrite(ctx context.Context) bool { |
| + v, _ := ctx.Value(systemWriteKey{}).(bool) |
| + return v |
| +} |
| + |
| +// guard runs write under the standing ctx carries. Call it INSIDE the |
| +// write's transaction, with write using that transaction. Outside team |
| +// mode, and for a systemWrite, it is write alone. A context with no |
| +// Access reads as Unknown (teammode.Standing), so a write that lost its |
| +// standing on the way here is refused. |
| +func (s *store) guard(ctx context.Context, write func() error) error { |
| + if !s.team || isSystemWrite(ctx) { |
| + return write() |
| + } |
| + return teamGuard(ctx, teammode.RequireMember, write) |
| +} |
| + |
| +// guarded runs write against the store's database exactly as it always |
| +// has outside team mode (and for a systemWrite), and in team mode in one |
| +// transaction, inside guard, against that transaction (never the outer |
| +// handle: the writer pool has one connection). |
| +func (s *store) guarded(ctx context.Context, write func(db *gorm.DB) error) error { |
| + if !s.team || isSystemWrite(ctx) { |
| + return write(s.g.WithContext(ctx)) |
| + } |
| + return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + return s.guard(ctx, func() error { return write(tx) }) |
| + }) |
| +} |
diff --git a/internal/calls/team_guard_test.go b/internal/calls/team_guard_test.go| new file mode 100644 |
| index 0000000..eec211b |
| --- /dev/null |
| +++ b/internal/calls/team_guard_test.go |
| @@ -0,0 +1,300 @@ |
| +package calls |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// teamSnapshot is every table a write can touch, row by row, so "nothing |
| +// it wrote survived" is read back rather than assumed. Sealed columns |
| +// carry a fresh nonce on every write, and the rest carry ids, times or |
| +// flags, so any write shows. |
| +func teamSnapshot(t *testing.T, f *teamFixture) string { |
| + t.Helper() |
| + var b strings.Builder |
| + for _, table := range []string{"meetings", "meeting_links", "guest_grants", "pending_joins", "agents", "meeting_defaults", "device_tokens", "persons", "calls_team_home_persons"} { |
| + rows, err := f.app.db.Writer().Query("SELECT * FROM " + table + " ORDER BY rowid") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, _ := rows.Columns() |
| + for rows.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + if err := rows.Scan(ptrs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + fmt.Fprintf(&b, "%s %v\n", table, vals) |
| + } |
| + rows.Close() |
| + } |
| + return b.String() |
| +} |
| + |
| +// lapsingGuard is teammode.Guard with the lease running out between the |
| +// write and its commit: authorize, write, the directory goes away and the |
| +// clock passes the lease, authorize again. |
| +func (f *teamFixture) lapsingGuard(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + if err := authorize(teammode.Standing(ctx)); err != nil { |
| + return err |
| + } |
| + if err := write(); err != nil { |
| + return err |
| + } |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return authorize(teammode.Standing(ctx)) |
| +} |
| + |
| +// teamWriteWorld is a team instance with something for every write route |
| +// to act on: Alice, a member (not an owner), with her meetings and an |
| +// agent; Carol, a guest with a local account and no Oficina link; and the |
| +// links, the legacy link and the pending join the guest routes follow. |
| +type teamWriteWorld struct { |
| + f *teamFixture |
| + alice, carol map[string]*http.Cookie |
| + share, replace, end, settings string |
| + apiReplace, apiEnd string |
| + followToken, namedToken, pendToken string |
| + pendLink int64 |
| + bearer string |
| + agentID int64 |
| +} |
| + |
| +func newTeamWriteWorld(t *testing.T) *teamWriteWorld { |
| + f := newTeamFixture(t) |
| + w := &teamWriteWorld{f: f} |
| + f.member(teamSubject('a'), "member") |
| + w.share, _ = f.meeting("Share me") |
| + // A link from before invitations were sealed: sharing must mint one. |
| + if _, err := f.app.db.Writer().Exec("UPDATE meeting_links SET token_sealed=NULL WHERE meeting_id=(SELECT id FROM meetings WHERE sqid=?)", w.share); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.replace, _ = f.meeting("Replace me") |
| + w.end, _ = f.meeting("End me") |
| + w.settings, _ = f.meeting("Set me") |
| + w.apiReplace, _ = f.meeting("API replace") |
| + w.apiEnd, _ = f.meeting("API end") |
| + _, w.followToken = f.meeting("Follow me") |
| + _, w.namedToken = f.meeting("Name me") |
| + _, w.pendToken = f.meeting("Pend me") |
| + w.bearer = f.agentToken("worker") |
| + f.agentToken("revokee") |
| + if err := f.app.db.Writer().QueryRow("SELECT id FROM agents WHERE name='revokee'").Scan(&w.agentID); err != nil { |
| + t.Fatal(err) |
| + } |
| + link, _, live, err := f.app.store.liveLink(context.Background(), w.pendToken) |
| + if err != nil || !live { |
| + t.Fatal("pending link", err) |
| + } |
| + w.pendLink = link.ID |
| + w.alice = f.jar() |
| + // Carol: a local account, no link, so a guest; her persons row is made |
| + // by her first page, as anybody's is. |
| + f.localSession("carol@example.test") |
| + f.get("/welcome") |
| + w.carol = f.jar() |
| + f.cookies = w.alice |
| + return w |
| +} |
| + |
| +// writeRoute is one write, and how to make it. |
| +type writeRoute struct { |
| + name string |
| + do func() *httptest.ResponseRecorder |
| +} |
| + |
| +// routes is every write a person makes (or, for the three guest routes, |
| +// a guest makes on the host's standing). Add yours. |
| +func (w *teamWriteWorld) routes() []writeRoute { |
| + f := w.f |
| + as := func(jar map[string]*http.Cookie, do func() *httptest.ResponseRecorder) func() *httptest.ResponseRecorder { |
| + return func() *httptest.ResponseRecorder { |
| + saved := f.cookies |
| + f.cookies = jar |
| + defer func() { f.cookies = saved }() |
| + return do() |
| + } |
| + } |
| + alice := func(do func() *httptest.ResponseRecorder) func() *httptest.ResponseRecorder { return as(w.alice, do) } |
| + return []writeRoute{ |
| + {"create", alice(func() *httptest.ResponseRecorder { return f.post("/meetings", "title=New") })}, |
| + {"start a call", alice(func() *httptest.ResponseRecorder { return f.post("/meetings/start", "zone=UTC") })}, |
| + {"native start", alice(func() *httptest.ResponseRecorder { return f.json("/native/meetings/start", `{"zone":"UTC"}`) })}, |
| + {"native device", alice(func() *httptest.ResponseRecorder { |
| + return f.json("/native/devices", `{"token":"aabbccdd","platform":"ios"}`) |
| + })}, |
| + {"share", alice(func() *httptest.ResponseRecorder { return f.post("/m/"+w.share+"/share", "") })}, |
| + {"replace the link", alice(func() *httptest.ResponseRecorder { return f.post("/meetings/"+w.replace+"/links", "") })}, |
| + {"team defaults", alice(func() *httptest.ResponseRecorder { return f.post("/settings/defaults", "require_signin=on") })}, |
| + {"meeting settings", alice(func() *httptest.ResponseRecorder { |
| + return f.post("/meetings/"+w.settings+"/settings", "waiting_room=on") |
| + })}, |
| + {"mint agent", alice(func() *httptest.ResponseRecorder { return f.post("/settings/agents", "name=another") })}, |
| + {"revoke agent", alice(func() *httptest.ResponseRecorder { |
| + return f.post("/settings/agents/"+strconv.FormatInt(w.agentID, 10)+"/revoke", "") |
| + })}, |
| + {"api create", func() *httptest.ResponseRecorder { |
| + return f.api("POST", "/api/v1/meetings", w.bearer, `{"title":"By agent"}`) |
| + }}, |
| + {"api replace", func() *httptest.ResponseRecorder { |
| + return f.api("POST", "/api/v1/meetings/"+w.apiReplace+"/links", w.bearer, "") |
| + }}, |
| + {"api end", func() *httptest.ResponseRecorder { |
| + return f.api("POST", "/api/v1/meetings/"+w.apiEnd+"/end", w.bearer, "") |
| + }}, |
| + {"guest follows a link", as(w.carol, func() *httptest.ResponseRecorder { return f.get("/j/" + w.followToken) })}, |
| + {"named guest joins", as(map[string]*http.Cookie{}, func() *httptest.ResponseRecorder { |
| + return f.post("/j/"+w.namedToken+"/guest", "name=Dana") |
| + })}, |
| + {"pending join continues", as(w.carol, func() *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + link, _, _, err := f.app.store.liveLinkByID(context.Background(), w.pendLink) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := f.app.store.writePending(context.Background(), "carol@example.test", link); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return f.get("/continue") |
| + })}, |
| + // Last: it ends a meeting the routes above do not use, but ending |
| + // is the one write that also tells the hub. |
| + {"end", alice(func() *httptest.ResponseRecorder { return f.post("/meetings/"+w.end+"/end", "") })}, |
| + } |
| +} |
| + |
| +// Every write route, with the lease running out between its write and its |
| +// commit, answers a retryable 503 and leaves the database exactly as it |
| +// was, read back row by row. Then the same routes under the real guard, |
| +// as a member (not an owner) and as a guest on the member's meetings, |
| +// each change the database. |
| +func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| + w := newTeamWriteWorld(t) |
| + f := w.f |
| + defer func() { teamGuard = teammode.Guard }() |
| + for _, route := range w.routes() { |
| + f.refreshed() |
| + // The pending route writes its row before the request; that row |
| + // is the request's to consume, so the snapshot is taken after. |
| + var before string |
| + got := func() *httptest.ResponseRecorder { |
| + if route.name == "pending join continues" { |
| + link, _, _, _ := f.app.store.liveLinkByID(context.Background(), w.pendLink) |
| + f.app.store.writePending(context.Background(), "carol@example.test", link) |
| + before = teamSnapshot(t, f) |
| + teamGuard = f.lapsingGuard |
| + defer func() { teamGuard = teammode.Guard }() |
| + saved := f.cookies |
| + f.cookies = w.carol |
| + defer func() { f.cookies = saved }() |
| + return f.get("/continue") |
| + } |
| + before = teamSnapshot(t, f) |
| + teamGuard = f.lapsingGuard |
| + defer func() { teamGuard = teammode.Guard }() |
| + return route.do() |
| + }() |
| + retryable(t, route.name+" through a lapse", got) |
| + if after := teamSnapshot(t, f); after != before { |
| + t.Fatalf("%s: a write refused at commit left something behind:\nbefore\n%s\nafter\n%s", route.name, before, after) |
| + } |
| + } |
| + if _, err := f.app.db.Writer().Exec("DELETE FROM pending_joins"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, route := range w.routes() { |
| + f.refreshed() |
| + before := teamSnapshot(t, f) |
| + got := route.do() |
| + if got.Code >= 400 { |
| + t.Fatalf("%s as a member = %d %s", route.name, got.Code, got.Body.String()) |
| + } |
| + if teamSnapshot(t, f) == before { |
| + t.Fatalf("%s as a member changed nothing", route.name) |
| + } |
| + } |
| +} |
| + |
| +// The guard itself, independent of the test seam: a write with no |
| +// standing is refused before it runs, a write under Unknown is refused, |
| +// and a write whose own body lapses the lease rolls back (the after-check). |
| +// Outside team mode there is no guard at all. |
| +func TestTeamGuardRefusesWithoutStanding(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('g') |
| + f.member(subject, "member") |
| + count := func() int { return f.count("meeting_defaults") } |
| + write := func(db *gorm.DB) error { |
| + return db.Exec("INSERT OR REPLACE INTO meeting_defaults(id, require_signin, waiting_room) VALUES(1, 1, 1)").Error |
| + } |
| + ran := false |
| + if err := f.app.store.guarded(context.Background(), func(db *gorm.DB) error { ran = true; return write(db) }); !errors.Is(err, teammode.ErrUnavailable) || ran || count() != 0 { |
| + t.Fatalf("a write with no standing = %v (ran %v, %d rows)", err, ran, count()) |
| + } |
| + f.expired() |
| + if err := f.app.store.guarded(f.withAccess(subject), write); !errors.Is(err, teammode.ErrUnavailable) || count() != 0 { |
| + t.Fatalf("a write under Unknown = %v", err) |
| + } |
| + f.refreshed() |
| + ctx := f.withAccess(subject) |
| + err := f.app.store.guarded(ctx, func(db *gorm.DB) error { |
| + if err := write(db); err != nil { |
| + return err |
| + } |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return nil |
| + }) |
| + if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 { |
| + t.Fatalf("a write whose own body lapsed = %v, %d rows", err, count()) |
| + } |
| + // guard (inside a caller's transaction) the same way. |
| + f.refreshed() |
| + ctx = f.withAccess(subject) |
| + err = f.app.db.G.Transaction(func(tx *gorm.DB) error { |
| + return f.app.store.guard(ctx, func() error { |
| + if err := write(tx); err != nil { |
| + return err |
| + } |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + return nil |
| + }) |
| + }) |
| + if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 { |
| + t.Fatalf("a guard whose own write lapsed = %v, %d rows", err, count()) |
| + } |
| + // A removed member's write is refused as NotMember. |
| + f.refreshed() |
| + f.removed(subject) |
| + if err := f.app.store.guarded(f.withAccess(subject), write); !errors.Is(err, teammode.ErrNotMember) || count() != 0 { |
| + t.Fatalf("a removed member's write = %v", err) |
| + } |
| + // A system write is never guarded; team mode off has no guard. |
| + if err := f.app.store.guarded(systemWrite(context.Background()), write); err != nil || count() != 1 { |
| + t.Fatalf("a system write = %v", err) |
| + } |
| + off := newHomeRouterFixture(t) |
| + if off.app.store.team { |
| + t.Fatal("team mode off has a guard") |
| + } |
| + if err := off.app.store.guarded(context.Background(), write); err != nil { |
| + t.Fatalf("team mode off guarded a write: %v", err) |
| + } |
| +} |
diff --git a/internal/calls/team_home_only.go b/internal/calls/team_home_only.go| new file mode 100644 |
| index 0000000..7d9800d |
| --- /dev/null |
| +++ b/internal/calls/team_home_only.go |
| @@ -0,0 +1,76 @@ |
| +package calls |
| + |
| +// Home sign-in for a roster member with no account here: connect's two |
| +// team-mode hooks over Calls' persons 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 wireHome gives |
| +// connect these, and connect's own completion does the rest (its cookie |
| +// checks, the same-person rule, the link flow). |
| +// |
| +// The person Unlinked creates is identity, never standing: every request |
| +// after this one asks the roster again (team_access.go). |
| +// |
| +// A Home-only person has NO address, here or in Home. Their persons row's |
| +// email column holds a random "home-only:" placeholder, because the |
| +// column is NOT NULL and UNIQUE and migrations are additive-only; nothing |
| +// mails it or shows it (Person.shown), and their name — what a call's |
| +// roster shows the others — is "Oficina account …xxxx". Calls mails |
| +// nobody but a person signing in by link, so the only thing this costs |
| +// them is local sign-in: they sign in through Oficina. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calls/internal/calls/teamstate" |
| +) |
| + |
| +// teamHomeOnly is connect's HomeOnly: the addressless person 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.HomePerson(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 person: an |
| +// addressless person for a subject the roster says is a Member now, with |
| +// the lease on that answer still valid (Runtime.AdmitUnlinked). A |
| +// stranger is connect's "unknown"; an undecidable roster is a 503. |
| +func (a *app) teamUnlinked(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + if a.team == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if err := a.team.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + id, _, err := teamstate.EnsureHomePerson(ctx, d, issuer, subject, homeOnlyLabel(subject)) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + // Linked to a local account in the meantime: that person |
| + // signs in as that account, not as a new one. |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
diff --git a/internal/calls/team_host.go b/internal/calls/team_host.go| new file mode 100644 |
| index 0000000..73f7d92 |
| --- /dev/null |
| +++ b/internal/calls/team_host.go |
| @@ -0,0 +1,173 @@ |
| +package calls |
| + |
| +// Team mode: a meeting stands on its HOST — the member who made it, or, |
| +// for a meeting an agent made, the agent's operator — as a booking page |
| +// in Calendar stands on its host and a presentation in Slides on its |
| +// presenter (oficina/calendar #35, oficina/slides #33). Calls' meetings |
| +// are the team's to run (any member lists, shares, replaces and ends |
| +// them), but what lets an outsider in is the meeting's link, and a link |
| +// is an invitation somebody on the team gave out. When that somebody |
| +// leaves, what they gave out stops working: |
| +// |
| +// - Member: as before. |
| +// - NotMember: the meeting is over. The instance ends it (a system |
| +// write: ended_at, every link revoked) and tells every open stream |
| +// "ended", exactly as a member's End would. Its links 404 like any |
| +// ended meeting's, nobody new is let in, and the call in progress |
| +// ends — guests, and the members still in it, who can start another |
| +// in one click. Re-adding the host does not revive it. |
| +// (Flagged for Paul: the alternative keeps the meeting for members |
| +// and ends only the guests.) |
| +// - Unknown: nothing is ended. Every new entry — following a link, |
| +// joining, an ICE fetch, a signal — is a retryable 503, and a call in |
| +// progress is held (team_stream.go): its streams stay open and |
| +// deliver nothing until the host's standing is known again. |
| +// |
| +// Nothing here runs outside team mode. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calls/internal/calls/hub" |
| +) |
| + |
| +// hostRemovedActor is the ended_by of a meeting the instance ended because |
| +// its host left the team: nobody's actor, and never a person's. |
| +const hostRemovedActor = "system:host-removed" |
| + |
| +// hostOf is the person a meeting stands on: its creator, or the operator |
| +// of the agent that created it. ok is false for a creator Calls cannot |
| +// resolve to a person, which stands on nobody (NotMember). |
| +func (a *app) hostOf(ctx context.Context, m Meeting) (id int64, ok bool, err error) { |
| + kind, rest, found := strings.Cut(m.CreatedBy, ":") |
| + if !found { |
| + return 0, false, nil |
| + } |
| + n, perr := strconv.ParseInt(rest, 10, 64) |
| + if perr != nil { |
| + return 0, false, nil |
| + } |
| + switch kind { |
| + case "person": |
| + return n, true, nil |
| + case "agent": |
| + _, op, found, err := a.store.agentAnyByID(ctx, n) |
| + if err != nil { |
| + return 0, false, err |
| + } |
| + return op.ID, found, nil |
| + } |
| + return 0, false, nil |
| +} |
| + |
| +// hostAccess is the roster's answer about m's host now: a fresh Access, |
| +// never the request's own (a host is somebody else's standing even when |
| +// they are the one asking). nil, which reads Unknown, when the host |
| +// cannot be read now. |
| +func (a *app) hostAccess(ctx context.Context, m Meeting) *teammode.Access { |
| + id, ok, err := a.hostOf(ctx, m) |
| + if err != nil { |
| + return nil |
| + } |
| + if !ok { |
| + return a.team.Access(ctx, "") |
| + } |
| + return a.standingOf(ctx, id) |
| +} |
| + |
| +// meetingStands decides m on its host's standing and returns the host's |
| +// Access for whatever the caller writes on it (a guest's grant). On a |
| +// definite NotMember it ends the meeting before it answers, so whatever |
| +// the caller does next finds it ended. Outside team mode it is Member, |
| +// with no Access. |
| +func (a *app) meetingStands(ctx context.Context, m Meeting) (*teammode.Access, roster.State) { |
| + if a.team == nil { |
| + return nil, roster.Member |
| + } |
| + acc := a.hostAccess(ctx, m) |
| + st := acc.State() |
| + if st == roster.NotMember { |
| + a.endForHost(ctx, m) |
| + } |
| + return acc, st |
| +} |
| + |
| +// endForHost ends a meeting whose host the roster says has left the team: |
| +// the row first, then the hub, so every stream is told "ended" and every |
| +// later entry reads ended_at. A write nobody's standing makes. An ending |
| +// that fails is logged and left for the next request, the tick or a |
| +// member to retry; the hub is told regardless, because a host who is |
| +// definitely gone must not keep the call running for want of a write. |
| +func (a *app) endForHost(ctx context.Context, m Meeting) { |
| + if m.EndedAt == nil { |
| + if _, err := a.store.endMeeting(systemWrite(ctx), m.ID, hostRemovedActor); err != nil { |
| + a.logger.Error("calls: end a meeting whose host left the team", "meeting_id", m.ID, "err", err) |
| + } |
| + } |
| + a.hub.End(m.Sqid) |
| +} |
| + |
| +// settleHosts ends every listed meeting whose host the roster says has |
| +// left the team, so the list shows it ended rather than offering a |
| +// meeting that will refuse every entry. Unknown leaves a meeting as it |
| +// is. It answers the views as they now stand. |
| +func (a *app) settleHosts(ctx context.Context, views []meetingView) []meetingView { |
| + if a.team == nil { |
| + return views |
| + } |
| + // One answer per host, not per meeting: a list is mostly a few |
| + // people's meetings. |
| + hosts := map[string]roster.State{} |
| + for i, v := range views { |
| + if v.EndedAt != nil { |
| + continue |
| + } |
| + st, asked := hosts[v.CreatedBy] |
| + if !asked { |
| + st = a.hostAccess(ctx, v.Meeting).State() |
| + hosts[v.CreatedBy] = st |
| + } |
| + if st != roster.NotMember { |
| + continue |
| + } |
| + a.endForHost(ctx, v.Meeting) |
| + if fresh, ok, err := a.store.meetingBySqid(ctx, v.Sqid); err == nil && ok { |
| + views[i].Meeting = fresh |
| + views[i].LinkPresent = false |
| + } |
| + } |
| + return views |
| +} |
| + |
| +// teamRoomStands is the signal endpoint's host check: true when the |
| +// call's host stands and the message may go to the hub. A meeting that is |
| +// missing or ended is the hub's to answer (it holds the tombstone); a host |
| +// who has left has just ended it, and the sender is told what an ended |
| +// room's peer is told; one who cannot be decided now is a retryable 503. |
| +func (a *app) teamRoomStands(w http.ResponseWriter, r *http.Request, sqid string, peer hub.PeerID, typ string) bool { |
| + m, found, err := a.store.meetingBySqid(r.Context(), sqid) |
| + if err != nil { |
| + a.logger.Error("calls: signal refused", "room", sqid, "peer", string(peer), "type", safeSignalType(typ), "outcome", "internal", "err", err) |
| + streamJSON(w, http.StatusInternalServerError, nil) |
| + return false |
| + } |
| + if !found || m.EndedAt != nil { |
| + return true |
| + } |
| + switch _, st := a.meetingStands(r.Context(), m); st { |
| + case roster.NotMember: |
| + a.refuseSignal(w, sqid, peer, typ, http.StatusNotFound, "binding", a.notFoundBody()) |
| + return false |
| + case roster.Unknown: |
| + a.logRefusal(sqid, peer, typ, "standing-unknown") |
| + teamUnavailableJSON(w) |
| + return false |
| + } |
| + return true |
| +} |
diff --git a/internal/calls/team_identity_test.go b/internal/calls/team_identity_test.go| new file mode 100644 |
| index 0000000..04f2a88 |
| --- /dev/null |
| +++ b/internal/calls/team_identity_test.go |
| @@ -0,0 +1,276 @@ |
| +package calls |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/calls/internal/calls/teamstate" |
| +) |
| + |
| +// A roster member with no account here signs in through Home and gets an |
| +// addressless person: the placeholder in the email column, the label as |
| +// their name, and neither the placeholder nor an address on any page. |
| +func TestTeamHomeOnlyMemberSignsInWithNoAddress(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('a') |
| + p := f.member(subject, "member") |
| + if !teamstate.Addressless(p.Email) || strings.Contains(p.Email, "@") || p.Anonymous { |
| + t.Fatalf("Home-only person %+v", p) |
| + } |
| + if p.Name != homeOnlyLabel(subject) || !strings.HasSuffix(p.Name, subject[len(subject)-4:]) { |
| + t.Fatalf("Home-only name %q", p.Name) |
| + } |
| + for _, path := range []string{"/", "/settings", "/welcome"} { |
| + body := f.page(path).Body.String() |
| + if strings.Contains(body, p.Email) || strings.Contains(body, teamstate.PlaceholderPrefix) { |
| + t.Fatalf("%s shows the placeholder:\n%s", path, body) |
| + } |
| + } |
| + if body := f.page("/").Body.String(); !strings.Contains(body, p.Name) { |
| + t.Fatalf("the account menu does not name the Home-only member:\n%s", body) |
| + } |
| + sqid, _ := f.meeting("Standup") |
| + if w := f.page("/m/" + sqid + "/join"); w.Code != http.StatusOK || strings.Contains(w.Body.String(), teamstate.PlaceholderPrefix) { |
| + t.Fatalf("holding screen = %d", w.Code) |
| + } |
| + // Signing in again finds the same person; nothing new is allocated. |
| + before := f.count("persons") |
| + f.signInHome(subject) |
| + if f.count("persons") != before || f.personFor(subject).ID != p.ID { |
| + t.Fatal("a second sign-in allocated another person") |
| + } |
| +} |
| + |
| +// Only a current Member is allocated a person: a stranger is connect's |
| +// unknown (403), an undecidable roster a 503, and neither leaves a row. |
| +func TestTeamOnlyACurrentMemberIsAllocated(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.refreshed() |
| + if w := f.signInHome(teamSubject('s')); w.Code != http.StatusForbidden { |
| + t.Fatalf("a stranger's sign-in = %d, want 403", w.Code) |
| + } |
| + f.dir.Set(teamSubject('u'), "member") |
| + f.expired() |
| + if w := f.signInHome(teamSubject('u')); w.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("a member's sign-in with the roster unknown = %d, want 503", w.Code) |
| + } |
| + if n := f.count("persons"); n != 0 { |
| + t.Fatalf("%d persons allocated", n) |
| + } |
| + if n := f.count("calls_team_home_persons"); n != 0 { |
| + t.Fatalf("%d Home-only rows allocated", n) |
| + } |
| +} |
| + |
| +// A known arrival over somebody else's live session is refused and that |
| +// session survives; nothing new is allocated. |
| +func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('b'), "member") |
| + bob := f.jar() |
| + f.member(teamSubject('c'), "member") |
| + f.cookies = bob |
| + before := f.count("persons") |
| + w := f.exchange(t, "/auth/start", teamSubject('c')) |
| + if w.Code < 400 { |
| + t.Fatalf("an arrival over another live session = %d, want a refusal", w.Code) |
| + } |
| + if f.count("persons") != before { |
| + t.Fatal("allocated a person") |
| + } |
| + if g := f.get("/"); g.Code != http.StatusOK { |
| + t.Fatalf("the session it arrived over did not survive: %d", g.Code) |
| + } |
| +} |
| + |
| +// Removal reaches an existing session within the lease: every page and |
| +// write signs them out with the reason, /signin does too, and signing in |
| +// again allocates nothing and is refused. Re-added, they are back. |
| +func TestTeamRemovalSignsOutAnExistingSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('r') |
| + f.member(subject, "member") |
| + sqid, _ := f.meeting("Planning") |
| + // Four live sessions (four devices), each to be tried once: a |
| + // sign-out ends the session it was asked of. |
| + var jars []map[string]*http.Cookie |
| + for range 4 { |
| + f.signInHome(subject) |
| + jars = append(jars, f.jar()) |
| + } |
| + f.removed(subject) |
| + for i, probe := range []struct { |
| + what string |
| + do func() *httptest.ResponseRecorder |
| + }{ |
| + {"GET /", func() *httptest.ResponseRecorder { return f.get("/") }}, |
| + {"POST /meetings", func() *httptest.ResponseRecorder { return f.post("/meetings", "title=After") }}, |
| + {"the holding screen", func() *httptest.ResponseRecorder { return f.get("/m/" + sqid + "/join") }}, |
| + {"GET /signin", func() *httptest.ResponseRecorder { return f.get("/signin") }}, |
| + } { |
| + f.cookies = jars[i] |
| + signedOutRemoved(t, probe.what, probe.do()) |
| + } |
| + before := f.count("persons") |
| + if w := f.signInHome(subject); w.Code != http.StatusSeeOther { |
| + t.Fatalf("a removed member's sign-in = %d", w.Code) |
| + } |
| + if w := f.get("/"); w.Code != http.StatusSeeOther || !strings.Contains(w.Header().Get("Location"), "err=removed") { |
| + t.Fatalf("a removed member signed in again: %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + if f.count("persons") != before { |
| + t.Fatal("re-sign-in allocated a person") |
| + } |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.signInHome(subject) |
| + if w := f.get("/"); w.Code != http.StatusOK { |
| + t.Fatalf("re-added member = %d", w.Code) |
| + } |
| +} |
| + |
| +// A local account linked to an Oficina account stands on the roster, on |
| +// or off the allowlist: off the team it is signed out even though the |
| +// local door admits it, and on the team it is a member with no place on |
| +// the list. An unlinked local account is a guest: no member pages. |
| +func TestTeamLinkedAccountStandsOnTheRoster(t *testing.T) { |
| + f := newTeamFixture(t, "alice@example.test") |
| + subject := teamSubject('l') |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.local(t) |
| + // Unlinked: a guest, sent to link from a member page, which the |
| + // account menu offers. |
| + if w := f.get("/settings"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/account/home" { |
| + t.Fatalf("an unlinked local account on a member page = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + if w := f.get("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/welcome" { |
| + t.Fatalf("an unlinked local account's list = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + if body := f.page("/welcome").Body.String(); !strings.Contains(body, "/account/home") { |
| + t.Fatal("the account menu does not offer to connect the account") |
| + } |
| + if w := f.get("/account/home"); w.Code != http.StatusOK { |
| + t.Fatalf("link page = %d", w.Code) |
| + } |
| + start := homeRedirect(t, f.post("/account/home", "")) |
| + if got := homeRedirect(t, f.exchange(t, start, subject)); got != "/account/home/confirm" { |
| + t.Fatalf("link exchange landed on %s", got) |
| + } |
| + homeRedirect(t, f.post("/account/home/confirm", "")) |
| + if w := f.get("/"); w.Code != http.StatusOK { |
| + t.Fatalf("linked member's list = %d", w.Code) |
| + } |
| + // A local account the local door does not admit (a guest who signed |
| + // in through a meeting link) may not link: linking is the door's. |
| + jar := f.jar() |
| + f.localSession("guest@example.test") |
| + if w := f.get("/account/home"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a guest's local account on the link page = %d", w.Code) |
| + } |
| + if w := f.get("/settings"); w.Code != http.StatusNotFound { |
| + t.Fatalf("a guest's local account on a member page = %d", w.Code) |
| + } |
| + f.cookies = jar |
| + // Off the allowlist is not off the team, signed in either way. |
| + f.app.allow.Store(&allowlist{addrs: map[string]struct{}{}}) |
| + if w := f.get("/settings"); w.Code != http.StatusOK { |
| + t.Fatalf("a linked member off the allowlist = %d", w.Code) |
| + } |
| + local := f.jar() |
| + if w := f.signInHome(subject); w.Code != http.StatusSeeOther { |
| + t.Fatalf("a linked member's Home sign-in off the allowlist = %d", w.Code) |
| + } |
| + if w := f.get("/settings"); w.Code != http.StatusOK { |
| + t.Fatalf("a linked member's Home session off the allowlist = %d", w.Code) |
| + } |
| + f.cookies = local |
| + // Off the team is off, whatever the allowlist says. |
| + f.app.allow.Store(nil) |
| + f.removed(subject) |
| + signedOutRemoved(t, "linked local account off the team", f.get("/")) |
| +} |
| + |
| +// Storage that cannot be read resolving identity is a 503, never a |
| +// sign-out: the session survives it. |
| +func TestTeamIdentityStorageFailureIsNotASignOut(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('d'), "member") |
| + if _, err := f.app.db.Writer().Exec("ALTER TABLE calls_team_home_persons RENAME TO unavailable_home_persons"); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := f.get("/") |
| + retryable(t, "the list with identity storage down", w) |
| + for _, c := range w.Result().Cookies() { |
| + if c.MaxAge < 0 { |
| + t.Fatal("storage failure ended the session") |
| + } |
| + } |
| + if _, err := f.app.db.Writer().Exec("ALTER TABLE unavailable_home_persons RENAME TO calls_team_home_persons"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := f.get("/"); w.Code != http.StatusOK { |
| + t.Fatalf("recovered = %d", w.Code) |
| + } |
| +} |
| + |
| +// The Home-only rows hold: addressless, never updated, never deleted |
| +// (foreign keys off too), disjoint from account links both ways. |
| +func TestTeamHomeOnlyRowsKeepTheirShape(t *testing.T) { |
| + f := newTeamFixture(t) |
| + p := f.member(teamSubject('h'), "member") |
| + db := f.app.db.Writer() |
| + for name, stmt := range map[string]string{ |
| + "give an address": "UPDATE persons SET email='h@example.test' WHERE id=?", |
| + "delete the person": "DELETE FROM persons WHERE id=?", |
| + "move the row": "UPDATE calls_team_home_persons SET person_id=person_id WHERE person_id=?", |
| + "delete the row": "DELETE FROM calls_team_home_persons WHERE person_id=?", |
| + "link it": "INSERT INTO home_identity_links(issuer,subject,person_id,created_at) VALUES('" + homeTestIssuer + "','other',?,0)", |
| + } { |
| + if _, err := db.Exec(stmt, p.ID); err == nil { |
| + t.Fatalf("%s: allowed", name) |
| + } |
| + } |
| + if _, err := db.Exec("PRAGMA foreign_keys=OFF"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec("DELETE FROM persons WHERE id=?", p.ID); err == nil { |
| + t.Fatal("deleted a Home-only person with foreign keys off") |
| + } |
| + db.Exec("PRAGMA foreign_keys=ON") |
| + // An address can never be a Home-only person, and a linked subject |
| + // never becomes one. |
| + if _, err := db.Exec("INSERT INTO persons(email,name,created_at,anonymous) VALUES('x@example.test','x',0,0)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + var id int64 |
| + db.QueryRow("SELECT id FROM persons WHERE email='x@example.test'").Scan(&id) |
| + if _, err := db.Exec("INSERT INTO calls_team_home_persons(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('x'), id); err == nil { |
| + t.Fatal("an addressed person became Home-only") |
| + } |
| + if _, _, err := teamstate.EnsureHomePerson(context.Background(), db, homeTestIssuer, "a@b", "n"); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("an address as a subject = %v", err) |
| + } |
| + if _, _, err := teamstate.EnsureHomePerson(context.Background(), db, homeTestIssuer, teamSubject('y'), "x@y"); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("an address as a name = %v", err) |
| + } |
| +} |
| + |
| +// A removed member who follows one of the team's links is signed out like |
| +// anywhere else, not turned into a guest with a grant. |
| +func TestTeamARemovedMemberFollowingALinkIsSignedOut(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('h'), "member") |
| + _, token := f.meeting("Still running") |
| + subject := teamSubject('r') |
| + f.member(subject, "member") |
| + f.removed(subject) |
| + signedOutRemoved(t, "following a link", f.get("/j/"+token)) |
| + if n := f.count("guest_grants"); n != 0 { |
| + t.Fatalf("a removed member was given %d grants", n) |
| + } |
| +} |
diff --git a/internal/calls/team_lease_test.go b/internal/calls/team_lease_test.go| new file mode 100644 |
| index 0000000..4209de7 |
| --- /dev/null |
| +++ b/internal/calls/team_lease_test.go |
| @@ -0,0 +1,287 @@ |
| +package calls |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// A held decision ends at the lease under a failing refresh, existing |
| +// sessions included: at 59 s the list is whole and the meeting opens; at |
| +// 61 s the list is the partial notice with nothing in it, every item page |
| +// and form is a retryable 503 (a missing meeting too: not "not found"), |
| +// and the member is still signed in. |
| +func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('l'), "member") |
| + sqid, _ := f.meeting("Quarterly review") |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Second) |
| + if w := f.page("/"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Quarterly review") || strings.Contains(w.Body.String(), "data-partial") { |
| + t.Fatalf("59 s list = %d, want the whole list", w.Code) |
| + } |
| + if w := f.page("/m/" + sqid + "/join"); w.Code != http.StatusOK { |
| + t.Fatalf("59 s holding screen = %d", w.Code) |
| + } |
| + f.clock.Step(2 * time.Second) |
| + w := f.page("/") |
| + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "Quarterly review") || !strings.Contains(w.Body.String(), "data-partial") { |
| + t.Fatalf("61 s list = %d, want partial and without the meeting:\n%s", w.Code, w.Body.String()) |
| + } |
| + for _, path := range []string{ |
| + "/m/" + sqid + "/join", "/m/" + sqid, "/m/" + sqid + "/info", "/m/" + sqid + "/app", |
| + "/meetings/" + sqid + "/settings", "/meetings/" + sqid + "/end", "/meetings/" + sqid + "/links/replace", |
| + "/settings", "/m/2222222222/join", "/meetings/2222222222/settings", |
| + } { |
| + retryable(t, "61 s "+path, f.page(path)) |
| + } |
| + for path, body := range map[string]string{ |
| + "/meetings": "title=Later", "/meetings/start": "", "/m/" + sqid + "/share": "", |
| + "/meetings/" + sqid + "/links": "", "/meetings/" + sqid + "/end": "", "/settings/defaults": "", |
| + "/meetings/" + sqid + "/settings": "", "/settings/agents": "name=bot", |
| + } { |
| + retryable(t, "61 s POST "+path, f.post(path, body)) |
| + } |
| + retryable(t, "61 s stream for a missing meeting", f.doWith("GET", "/m/2222222222/stream", "", http.Header{"Accept": {"text/event-stream"}})) |
| + retryable(t, "61 s native start", f.json("/native/meetings/start", "{}")) |
| + retryable(t, "61 s native device", f.json("/native/devices", `{"token":"aabb","platform":"ios"}`)) |
| + if f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + t.Fatal("Unknown signed the member out") |
| + } |
| + // /signin under Unknown is the ordinary shortcut, never a sign-out. |
| + if w := f.get("/signin"); w.Code != http.StatusSeeOther || f.cookies[f.app.home.sessions.CookieName()] == nil { |
| + t.Fatalf("/signin under Unknown = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + // The meeting was never ended by a roster that could not be read. |
| + if f.meetingRow(sqid).EndedAt != nil { |
| + t.Fatal("Unknown ended the meeting") |
| + } |
| +} |
| + |
| +// Paul's ruling, condition 2 of 4 on #98 and #53's ask 3: under Unknown |
| +// the list says partial even when there is nothing in it, and withholds |
| +// the empty state, which would read as "no meetings". |
| +func TestTeamEmptyPartialListSaysPartialNotEmpty(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('e'), "member") |
| + if w := f.page("/"); !strings.Contains(w.Body.String(), "No meetings yet") { |
| + t.Fatal("the empty state is not where this test expects it") |
| + } |
| + f.expired() |
| + w := f.page("/") |
| + body := w.Body.String() |
| + if w.Code != http.StatusOK || !strings.Contains(body, "data-partial") || !strings.Contains(body, partialTitle) || strings.Contains(body, "No meetings yet") || strings.Contains(body, "rst-empty") { |
| + t.Fatalf("empty partial list = %d:\n%s", w.Code, body) |
| + } |
| + // A guest is never partial: they never reach the list. |
| + f.cookies = map[string]*http.Cookie{} |
| + if w := f.page("/"); strings.Contains(w.Body.String(), "data-partial") { |
| + t.Fatal("a signed-out visitor sees the partial notice") |
| + } |
| +} |
| + |
| +// The list asks again after it is built, of the same Access: swept across |
| +// the lease's end with a clock that ticks on every reading, the list is |
| +// always either whole or the partial notice with nothing in it — never a |
| +// short list without the notice. The drive surface's JSON list, which |
| +// cannot carry the notice, is whole or a retryable 503. |
| +func TestTeamListIsWholeOrPartialAcrossTheLeaseEdge(t *testing.T) { |
| + sawWhole, sawPartial := false, false |
| + apiWhole, api503 := false, false |
| + for k := 1; k <= 40; k++ { |
| + f := newTeamFixture(t) |
| + // Meetings of several hosts, so the list asks the roster about |
| + // each of them between building and asking again: the window a |
| + // lapse can fall in. |
| + for i, c := range []byte("vxyz") { |
| + f.member(teamSubject(c), "member") |
| + f.meeting("Other " + string("0123"[i])) |
| + } |
| + f.member(teamSubject('w'), "member") |
| + f.meeting("Alpha") |
| + f.meeting("Beta") |
| + token := f.agentToken("lister") |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + w := f.page("/") |
| + body := w.Body.String() |
| + whole := strings.Contains(body, "Alpha") && strings.Contains(body, "Beta") && !strings.Contains(body, "data-partial") |
| + partial := !strings.Contains(body, "Alpha") && !strings.Contains(body, "Beta") && strings.Contains(body, "data-partial") |
| + switch { |
| + case w.Code == http.StatusOK && whole: |
| + sawWhole = true |
| + case w.Code == http.StatusOK && partial: |
| + sawPartial = true |
| + default: |
| + t.Fatalf("k=%d: the list is neither whole nor partial (%d):\n%s", k, w.Code, body) |
| + } |
| + f.clock.SetTick(0) |
| + // The JSON list from where the page started, in its own request. |
| + f.clock.Step(-time.Duration(0)) |
| + a := apiAt(f, token, k) |
| + switch { |
| + case a.Code == http.StatusOK && strings.Contains(a.Body.String(), "Alpha") && strings.Contains(a.Body.String(), "Beta"): |
| + apiWhole = true |
| + case a.Code == http.StatusServiceUnavailable && a.Header().Get("Retry-After") != "": |
| + api503 = true |
| + default: |
| + t.Fatalf("k=%d: the API list = %d %s", k, a.Code, a.Body.String()) |
| + } |
| + } |
| + if !sawWhole || !sawPartial || !apiWhole || !api503 { |
| + t.Fatalf("the sweep did not cross the lease's end: whole %v partial %v api whole %v api 503 %v", sawWhole, sawPartial, apiWhole, api503) |
| + } |
| +} |
| + |
| +// agentToken mints an agent for whoever is signed in, through the page, |
| +// and returns its bearer. |
| +func (f *teamFixture) agentToken(name string) string { |
| + f.t.Helper() |
| + w := f.post("/settings/agents", "name="+name) |
| + if w.Code != http.StatusOK { |
| + f.t.Fatalf("mint agent = %d %s", w.Code, w.Body.String()) |
| + } |
| + i := strings.Index(w.Body.String(), "mt_") |
| + if i < 0 { |
| + f.t.Fatal("no token on the page") |
| + } |
| + end := i |
| + for end < len(w.Body.String()) && strings.IndexByte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-", w.Body.String()[end]) >= 0 { |
| + end++ |
| + } |
| + return w.Body.String()[i:end] |
| +} |
| + |
| +// api is one drive-surface request with bearer. |
| +func (f *teamFixture) api(method, path, bearer, body string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body)) |
| + r.Header.Set("Authorization", "Bearer "+bearer) |
| + if body != "" { |
| + r.Header.Set("Content-Type", "application/json") |
| + } |
| + w := httptest.NewRecorder() |
| + f.handler.ServeHTTP(w, r.WithContext(context.Background())) |
| + return w |
| +} |
| + |
| +// The list asks again after it is built, and a list built on standing that |
| +// has run out since is withheld, not shown beside the notice. Swept one |
| +// reading at a time across the lease's end, with the request's own Access |
| +// made just before the page is drawn, so the readings between building and |
| +// asking again (the hosts the list settles) can straddle the end. |
| +func TestTeamListBuiltThenLapsedIsWithheld(t *testing.T) { |
| + sawWhole, sawPartial := false, false |
| + for k := 1; k <= 12; k++ { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('a') |
| + p := f.member(subject, "member") |
| + f.meeting("Alpha") |
| + gamma, _ := f.meeting("Gamma") |
| + if w := f.post("/meetings/"+gamma+"/end", ""); w.Code != http.StatusSeeOther { |
| + t.Fatalf("end = %d", w.Code) |
| + } |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + // The refresh this request would start has just been tried, so |
| + // none is in flight to contend with the readings. |
| + f.app.team.Refresh(context.Background()) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + ctx := context.Background() |
| + tr := &teamReq{person: p, subject: subject, method: "home", access: f.app.team.Access(ctx, subject)} |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + r.Header.Set("Accept", "text/html") |
| + r = r.WithContext(context.WithValue(withTeamReq(ctx, tr), personCtxKey{}, p)) |
| + w := httptest.NewRecorder() |
| + f.app.renderIndex(w, r, "", "") |
| + // Alpha is upcoming and Gamma ended: the list's two sections. |
| + listed := strings.Contains(w.Body.String(), "Alpha") || strings.Contains(w.Body.String(), "Gamma") |
| + partial := strings.Contains(w.Body.String(), "data-partial") |
| + switch { |
| + case listed && partial: |
| + t.Fatalf("k=%d: a list built before the lease ran out is shown beside the partial notice", k) |
| + case listed: |
| + sawWhole = true |
| + case partial: |
| + sawPartial = true |
| + } |
| + } |
| + if !sawWhole || !sawPartial { |
| + t.Fatalf("the sweep did not cross the lease's end: whole %v partial %v", sawWhole, sawPartial) |
| + } |
| +} |
| + |
| +// apiAt is the drive surface's list from k ms before the lease's end, a |
| +// reading at a time. |
| +func apiAt(f *teamFixture, token string, k int) *httptest.ResponseRecorder { |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + defer f.clock.SetTick(0) |
| + return f.api("GET", "/api/v1/meetings", token, "") |
| +} |
| + |
| +// The drive surface's list asks again after it is built, of the same |
| +// Access its gate put on the request: swept a reading at a time across |
| +// the lease's end from just before the handler runs, it is whole or a |
| +// retryable 503, and both happen. |
| +func TestTeamAPIListAsksAgainAfterBuilding(t *testing.T) { |
| + sawWhole, saw503 := false, false |
| + for k := 1; k <= 12; k++ { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('a') |
| + p := f.member(subject, "member") |
| + f.meeting("Alpha") |
| + f.refreshed() |
| + f.dir.SetDown(true) |
| + f.app.team.Refresh(context.Background()) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) |
| + f.clock.SetTick(time.Millisecond) |
| + ctx := teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/api/v1/meetings", nil) |
| + r = r.WithContext(withAgent(ctx, Agent{ID: 1}, p)) |
| + if acc, _ := teammode.FromContext(r.Context()); acc.State() != roster.Member { |
| + continue // the gate would have refused it |
| + } |
| + w := httptest.NewRecorder() |
| + f.app.apiListMeetings(w, r) |
| + switch { |
| + case w.Code == http.StatusOK && strings.Contains(w.Body.String(), "Alpha"): |
| + sawWhole = true |
| + case w.Code == http.StatusServiceUnavailable && w.Header().Get("Retry-After") != "": |
| + saw503 = true |
| + default: |
| + t.Fatalf("k=%d: %d %s", k, w.Code, w.Body.String()) |
| + } |
| + } |
| + if !sawWhole || !saw503 { |
| + t.Fatalf("the sweep did not cross the lease's end: whole %v 503 %v", sawWhole, saw503) |
| + } |
| +} |
| + |
| +// Settling the list never ends a meeting on a host the roster cannot |
| +// decide: only a definite NotMember does. |
| +func TestTeamSettlingLeavesAnUnknownHostsMeeting(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('h'), "member") |
| + sqid, _ := f.meeting("Undecided") |
| + views, err := f.app.store.listMeetings(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.expired() |
| + f.app.settleHosts(context.Background(), views) |
| + if f.meetingRow(sqid).EndedAt != nil { |
| + t.Fatal("an Unknown host's meeting was ended") |
| + } |
| +} |
diff --git a/internal/calls/team_links.go b/internal/calls/team_links.go| new file mode 100644 |
| index 0000000..cad4198 |
| --- /dev/null |
| +++ b/internal/calls/team_links.go |
| @@ -0,0 +1,167 @@ |
| +package calls |
| + |
| +// Team mode's invitations: following a meeting link, joining as a named |
| +// guest, and the pending join a link's sign-in carries to /continue. A |
| +// link stands on its meeting's host (team_host.go), and a guest's grant is |
| +// written on the host's standing (team_guard.go). Nothing here runs |
| +// outside team mode. |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// teamLinkHost decides a followed link on its meeting's host: the host's |
| +// Access when they stand, or the answer already written — the 404 every |
| +// dead link gets when they have left (meetingStands has ended the |
| +// meeting), a retryable 503 when it cannot be decided now. |
| +func (a *app) teamLinkHost(w http.ResponseWriter, r *http.Request, m Meeting) (*teammode.Access, bool) { |
| + host, st := a.meetingStands(r.Context(), m) |
| + switch st { |
| + case roster.Member: |
| + return host, true |
| + case roster.NotMember: |
| + a.ErrorPage(w, r, http.StatusNotFound, "") |
| + default: |
| + a.teamUnavailable(w, r) |
| + } |
| + return nil, false |
| +} |
| + |
| +// teamJoinCookieStands is the sign-in form's host check (POST /signin), |
| +// made before the address is read: a join cookie whose link's host |
| +// cannot be decided now is a retryable 503, as following the link itself |
| +// is (nothing is written, nothing is mailed), rather than "check your |
| +// email" with no mail behind it. A host who has left ends the meeting |
| +// here (meetingStands), so the cookie's link is dead and mayRequestLink |
| +// answers as it always has for a dead link. The work does not depend on |
| +// the address, and the holding page already gives the same person the |
| +// same 503, so it is no membership oracle. It reports whether the form |
| +// may go on. |
| +func (a *app) teamJoinCookieStands(w http.ResponseWriter, r *http.Request) bool { |
| + ck, ok := a.readJoinCookie(r) |
| + if !ok { |
| + return true |
| + } |
| + _, m, live, err := a.store.liveLinkByHash(r.Context(), ck.TokenHash) |
| + if err != nil || !live { |
| + // Read failures and dead links are mayRequestLink's to answer, |
| + // as before. |
| + return true |
| + } |
| + if _, st := a.meetingStands(r.Context(), m); st == roster.Unknown { |
| + a.teamUnavailable(w, r) |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// teamFollowSignedIn is followLink's signed-in half in team mode. A member |
| +// goes to the holding screen; somebody the roster has taken off the team |
| +// is signed out and told so, exactly as on any other page; anyone else — |
| +// a guest, a local account with no Oficina link — is given a grant on the |
| +// host's standing, as a non-member always was. |
| +func (a *app) teamFollowSignedIn(w http.ResponseWriter, r *http.Request, s sessions.Session, link MeetingLink, m Meeting, host *teammode.Access) { |
| + t, err := a.teamReqFor(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errHomeRemoved): |
| + a.endRemovedSession(w, r) |
| + return |
| + case errors.Is(err, errHomeIdentity): |
| + a.ErrorPage(w, r, http.StatusNotFound, "") |
| + return |
| + case err != nil: |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + if t.removed() { |
| + a.endRemovedSession(w, r) |
| + return |
| + } |
| + if t.person.Anonymous && m.RequireSignin { |
| + a.setJoinCookie(w, link.TokenHash) |
| + http.Redirect(w, r, signinPath, http.StatusSeeOther) |
| + return |
| + } |
| + switch t.access.State() { |
| + case roster.Member: |
| + http.Redirect(w, r, "/m/"+m.Sqid+"/join", http.StatusSeeOther) |
| + return |
| + case roster.Unknown: |
| + // Whether this is a member (who needs no grant) or a guest |
| + // (who does) cannot be told now. |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + _, live, err := a.store.mintGrantViaLink(teammode.WithAccess(r.Context(), host), link.ID, t.person.ID) |
| + switch { |
| + case isTeamUnavailable(err): |
| + a.teamUnavailable(w, r) |
| + return |
| + case err != nil: |
| + a.logger.Error("calls: mint grant", "err", err) |
| + a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| + return |
| + case !live: |
| + a.ErrorPage(w, r, http.StatusNotFound, "") |
| + return |
| + } |
| + http.Redirect(w, r, "/m/"+m.Sqid+"/join", http.StatusSeeOther) |
| +} |
| + |
| +// teamContinuePending is /continue's pending branch in team mode: the |
| +// person's own standing and the meeting host's are both decided before |
| +// anything is consumed, so an undecidable roster leaves the pending row |
| +// for a retry (it lives fifteen minutes) rather than spending it. A host |
| +// who has left the team has ended the meeting, and consumePending then |
| +// finds its link dead and falls through as it always did. It answers |
| +// handled with no destination when it has written the 503 itself. |
| +func (a *app) teamContinuePending(w http.ResponseWriter, r *http.Request, p Person, pend PendingJoin) (string, bool) { |
| + ctx := r.Context() |
| + _, m, live, err := a.store.liveLinkByID(ctx, pend.LinkID) |
| + if err != nil { |
| + a.logger.Error("calls: pending link", "err", err) |
| + return "", false |
| + } |
| + // mint: the link is live and its host stands, so a non-member is |
| + // given a grant on the host's standing. Otherwise the pending rows |
| + // are consumed as bookkeeping and nothing is minted, as for a dead |
| + // link before. |
| + var host *teammode.Access |
| + mint := false |
| + if live { |
| + var st roster.State |
| + host, st = a.meetingStands(ctx, m) |
| + switch st { |
| + case roster.Unknown: |
| + a.teamUnavailable(w, r) |
| + return "", true |
| + case roster.Member: |
| + mint = true |
| + } |
| + } |
| + member := true |
| + if mint { |
| + switch a.memberState(ctx, p) { |
| + case roster.Unknown: |
| + a.teamUnavailable(w, r) |
| + return "", true |
| + case roster.NotMember: |
| + member = false |
| + } |
| + } |
| + dest, err := a.store.consumePending(teammode.WithAccess(ctx, host), p, pend, member) |
| + if isTeamUnavailable(err) { |
| + a.teamUnavailable(w, r) |
| + return "", true |
| + } |
| + if err != nil { |
| + a.logger.Error("calls: consume pending", "err", err) |
| + return "", false |
| + } |
| + return dest, dest != "" |
| +} |
diff --git a/internal/calls/team_push.go b/internal/calls/team_push.go| new file mode 100644 |
| index 0000000..3915773 |
| --- /dev/null |
| +++ b/internal/calls/team_push.go |
| @@ -0,0 +1,35 @@ |
| +package calls |
| + |
| +// Team mode's knock push: who is told, when somebody is at the door of a |
| +// call they are not in. A knock is a member's to answer, and in team mode |
| +// a member is whoever the roster says is one at the moment the push goes: |
| +// a person taken off the team gets nothing (their device rows stay, and a |
| +// re-added member is reached again), and a person whose standing cannot |
| +// be decided now gets nothing either — a push is said once and never |
| +// retried (knocked), so the conservative answer is silence. With no push |
| +// key configured nothing here runs at all: knocked returns first. |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/home/roster" |
| + |
| + "amadan.net/oficina/calls/internal/calls/teamstate" |
| +) |
| + |
| +// teamMemberPersonIDs is every person the roster says is a Member now, |
| +// each asked separately (standingOf, a fresh Access per person), never |
| +// the request's or anybody else's. |
| +func (a *app) teamMemberPersonIDs(ctx context.Context) ([]int64, error) { |
| + people, err := teamstate.Subjects(ctx, a.team.db, a.team.issuer()) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ids := make([]int64, 0, len(people)) |
| + for _, ps := range people { |
| + if a.team.Access(ctx, ps.Subject).State() == roster.Member { |
| + ids = append(ids, ps.PersonID) |
| + } |
| + } |
| + return ids, nil |
| +} |
diff --git a/internal/calls/team_stream.go b/internal/calls/team_stream.go| new file mode 100644 |
| index 0000000..6f7e55a |
| --- /dev/null |
| +++ b/internal/calls/team_stream.go |
| @@ -0,0 +1,276 @@ |
| +package calls |
| + |
| +// Team mode's call stream (GET /m/{sqid}/stream): the signalling channel |
| +// a participation's browser listens on, re-decided on standing before |
| +// every delivery and at the end of every lease (Home teammode-package.md |
| +// §5, "the stream hook"; §7.4: "the signaling socket closed at |
| +// Access.Remaining() unless renewed"). |
| +// |
| +// What a participation stands on: the meeting's host, always (a call |
| +// stands on its host, team_host.go), and for a member-kind participation |
| +// the member's own standing as well. A guest's own standing is not asked: |
| +// once admitted a guest stands on the participation (ruling 14), and the |
| +// participation on the host. |
| +// |
| +// Three answers, as Slides' streams (oficina/slides #33): |
| +// |
| +// - Member: deliver, and re-decide at the lease's end (never later than |
| +// the shortest Remaining, never sooner than a second). Before every |
| +// delivery the decision's leases are checked again (Access.State, |
| +// which never waits); one that has run out is re-decided first. |
| +// - Unknown: hold. The connection stays open and carries nothing but |
| +// heartbeat comments; the standing is asked again every |
| +// teamStreamHoldRetry. What arrives meanwhile is kept, in order, and |
| +// delivered only once a Member answer says it may be — or, past what |
| +// the hub's own buffer would keep, the stream ends with lost{buffer} |
| +// and the browser resumes, which replays from the ring on standing it |
| +// must have again. A Home blip does not drop the call: the media, |
| +// which never passes through Calls, carries on, and so does the |
| +// browser's stream, which receives its hello and so does not count |
| +// the round as a stall. |
| +// - NotMember: the end. A host who has left ends the meeting (lost |
| +// {ended}); a member who has left is ended by the hub, in its words |
| +// (lost{standing}), and the others are told "gone" and close their |
| +// connections to them. |
| +// |
| +// The terminal events the hub raises (lost, ended) are delivered whatever |
| +// the answer: they carry no call's content, only that this stream is |
| +// over and why. |
| +// |
| +// What this cannot do, said plainly: Calls signals; it does not carry |
| +// media. A connection already established peer to peer, or through the |
| +// platform relay on credentials /ice minted (valid for up to three |
| +// hours), is not Calls' to cut. Ending a participation tells every other |
| +// browser to close its connection to it, which is what stops the media |
| +// in practice; a modified client that ignored "gone" could keep a |
| +// connection to a colluding peer until its relay credentials expire. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/calls/internal/calls/hub" |
| +) |
| + |
| +var ( |
| + // teamStreamHoldRetry is how often a held stream asks again: the |
| + // roster's own retry interval. A variable only so a test can shorten |
| + // it. |
| + teamStreamHoldRetry = roster.RetryAfter |
| + // teamStreamRecheckMax caps how long a delivering stream goes before |
| + // it re-decides. A lease is never longer than roster.MaximumAge, so |
| + // in production this changes nothing; a test shortens it so a lease |
| + // measured on a stepped roster clock is re-decided in real time. |
| + teamStreamRecheckMax = roster.MaximumAge |
| +) |
| + |
| +// teamStreamHeld bounds what a held stream keeps: the hub's own buffer |
| +// for one subscriber. Past it the stream ends as an overflowing |
| +// subscriber does (lost{buffer}), and the browser resumes. |
| +const teamStreamHeld = 64 |
| + |
| +// streamVerdict is one decision's answer. |
| +type streamVerdict int |
| + |
| +const ( |
| + streamHolds streamVerdict = iota |
| + streamDelivers |
| + streamEnds |
| +) |
| + |
| +// streamDecision is a participation's standing, decided once: what to do, |
| +// when to decide again, the leases a delivery rests on, and the event |
| +// that ends the stream. |
| +type streamDecision struct { |
| + verdict streamVerdict |
| + renew time.Duration |
| + leases []*teammode.Access |
| + end hub.Message |
| +} |
| + |
| +// stands reports whether every lease the decision delivers on still |
| +// holds. It never waits (Access.State's TryLock), and a lease that has |
| +// run out latches, so the stream re-decides before it delivers. |
| +func (d streamDecision) stands() bool { |
| + if d.verdict != streamDelivers { |
| + return false |
| + } |
| + for _, acc := range d.leases { |
| + if acc.State() != roster.Member { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// freshStanding masks the request's own Access, latched when the stream |
| +// opened, so that whatever is asked about this person on the stream's |
| +// behalf — by the hub's re-derivation included — is asked of the roster |
| +// now (memberState falls through to standingOf). A long-lived stream |
| +// that kept reading its door-time Access could never renew. |
| +func freshStanding(ctx context.Context) context.Context { |
| + return context.WithValue(ctx, teamReqKey{}, (*teamReq)(nil)) |
| +} |
| + |
| +// teamStreamDecide decides one participation's stream now, on fresh |
| +// Accesses. Standing is read before anything else, and a Member answer |
| +// always carries a timer (the Slides and Sheets stream-order lesson, |
| +// oficina/slides #33 and oficina/sheets #54): a lease that runs out |
| +// after it is read gives a one-second timer, never "delivers, nothing to |
| +// renew". |
| +func (a *app) teamStreamDecide(ctx context.Context, m Meeting, person Person, sqid, session string, peer hub.PeerID) streamDecision { |
| + host := a.hostAccess(ctx, m) |
| + switch host.State() { |
| + case roster.NotMember: |
| + a.endForHost(ctx, m) |
| + return streamDecision{verdict: streamEnds, end: hub.Message{Type: hub.TypeLost, Reason: hub.ReasonEnded}} |
| + case roster.Unknown: |
| + return streamDecision{verdict: streamHolds} |
| + } |
| + leases := []*teammode.Access{host} |
| + id, kind, live := a.hub.LiveKindForSession(sqid, session) |
| + if !live || id != peer { |
| + // The participation has ended (removed, replaced, left): the hub |
| + // has put its terminal event on this stream's subscriber, which |
| + // is delivered whatever the answer. Until it is read, nothing |
| + // else is. |
| + return streamDecision{verdict: streamHolds} |
| + } |
| + if kind == hub.KindMember { |
| + own := a.standingOf(ctx, person.ID) |
| + switch own.State() { |
| + case roster.Unknown: |
| + return streamDecision{verdict: streamHolds} |
| + case roster.NotMember: |
| + ended, err := a.hub.Recheck(ctx, sqid, session, peer) |
| + if err == nil && ended { |
| + return streamDecision{verdict: streamEnds, end: hub.Message{Type: hub.TypeLost, Reason: hub.ReasonStanding}} |
| + } |
| + // Unknown by the time the hub asked, or re-derived as a |
| + // guest still holding a grant (§2.4): asked again shortly, |
| + // as what it now is. |
| + return streamDecision{verdict: streamHolds} |
| + } |
| + leases = append(leases, own) |
| + } |
| + left := roster.MaximumAge |
| + for _, acc := range leases { |
| + left = min(left, acc.Remaining()) |
| + } |
| + renew := min(left, teamStreamRecheckMax) |
| + if left < time.Second { |
| + // Member when read, run out since: ask again in a second. |
| + renew = time.Second |
| + } |
| + return streamDecision{verdict: streamDelivers, renew: renew, leases: leases} |
| +} |
| + |
| +// serveTeamStream is serveStream in team mode: the same wire, the same |
| +// heartbeat, TTL and shutdown, with every delivery decided on standing |
| +// (above). first is what the stream owes before the subscriber's events: |
| +// the hello is written at once — it names only this browser's own peer |
| +// and the process — and the rest (a resume's roster and replay) waits on |
| +// a Member answer like everything else. |
| +func (a *app) serveTeamStream(w http.ResponseWriter, r *http.Request, sub *hub.Sub, first []hub.Message, m Meeting, person Person, sqid, session string, peer hub.PeerID) { |
| + ctx := freshStanding(r.Context()) |
| + rc := http.NewResponseController(w) |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("X-Accel-Buffering", "no") |
| + w.WriteHeader(http.StatusOK) |
| + if err := rc.Flush(); err != nil { |
| + return |
| + } |
| + if len(first) > 0 && first[0].Type == hub.TypeHello { |
| + if !writeEvent(w, rc, first[0]) { |
| + return |
| + } |
| + first = first[1:] |
| + } |
| + held := append([]hub.Message(nil), first...) |
| + |
| + heartbeat := time.NewTicker(a.heartbeatEvery()) |
| + defer heartbeat.Stop() |
| + ttl := time.NewTimer(a.streamLifeFor(r)) |
| + defer ttl.Stop() |
| + // again fires when this decision is due to be asked again: at its |
| + // lease's end while delivering, after teamStreamHoldRetry while held. |
| + // It is set when a decision is made and at no other time, so a |
| + // heartbeat or a delivery never postpones it. |
| + again := time.NewTimer(time.Hour) |
| + defer again.Stop() |
| + var d streamDecision |
| + decide := func() { |
| + d = a.teamStreamDecide(ctx, m, person, sqid, session, peer) |
| + wait := teamStreamHoldRetry |
| + if d.verdict == streamDelivers { |
| + wait = d.renew |
| + } |
| + // Go 1.23 timers: Reset drops any expiry not yet received. |
| + again.Reset(wait) |
| + } |
| + decide() |
| + |
| + for { |
| + // Deliver what is owed, one stand-check per event. |
| + for d.verdict == streamDelivers && len(held) > 0 { |
| + if !d.stands() { |
| + decide() |
| + continue |
| + } |
| + msg := held[0] |
| + held = held[1:] |
| + if !writeEvent(w, rc, msg) { |
| + return |
| + } |
| + } |
| + if d.verdict == streamEnds { |
| + writeEvent(w, rc, d.end) |
| + return |
| + } |
| + select { |
| + case <-r.Context().Done(): |
| + return |
| + case <-a.done: |
| + return |
| + case <-ttl.C: |
| + return |
| + case <-heartbeat.C: |
| + if !writeRaw(w, rc, ": hb\n\n") { |
| + return |
| + } |
| + case <-again.C: |
| + decide() |
| + case msg, ok := <-sub.C(): |
| + if !ok { |
| + return |
| + } |
| + if msg.Type == hub.TypeLost || msg.Type == hub.TypeEnded { |
| + // Terminal for this stream, and no call's content: said |
| + // whatever the standing (§4.5's reasons). |
| + writeEvent(w, rc, msg) |
| + return |
| + } |
| + if len(held) == 0 && d.stands() { |
| + if !writeEvent(w, rc, msg) { |
| + return |
| + } |
| + continue |
| + } |
| + held = append(held, msg) |
| + if len(held) > teamStreamHeld { |
| + writeEvent(w, rc, hub.Message{Type: hub.TypeLost, Reason: hub.ReasonBuffer}) |
| + return |
| + } |
| + if d.verdict == streamDelivers { |
| + // A lease ran out between decisions: decide before |
| + // anything more is delivered. |
| + decide() |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/calls/teamstate/migrations/0001_home_persons.sql b/internal/calls/teamstate/migrations/0001_home_persons.sql| new file mode 100644 |
| index 0000000..c56041e |
| --- /dev/null |
| +++ b/internal/calls/teamstate/migrations/0001_home_persons.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE calls_team_home_persons ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + person_id INTEGER NOT NULL UNIQUE REFERENCES persons(id), |
| + PRIMARY KEY(issuer,subject) |
| +); |
| +CREATE TRIGGER calls_team_home_person_addressless BEFORE INSERT ON calls_team_home_persons WHEN NOT EXISTS(SELECT 1 FROM persons WHERE id=NEW.person_id AND substr(email,1,10)='home-only:' AND instr(email,'@')=0 AND anonymous=0) BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_home_person_unlinked BEFORE INSERT ON calls_team_home_persons WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_home_persons_keep_update BEFORE UPDATE ON calls_team_home_persons BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_home_persons_keep_delete BEFORE DELETE ON calls_team_home_persons BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_link_not_home_only BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM calls_team_home_persons WHERE (issuer=NEW.issuer AND subject=NEW.subject) OR person_id=NEW.person_id) BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_home_person_keeps_no_address BEFORE UPDATE OF email ON persons WHEN EXISTS(SELECT 1 FROM calls_team_home_persons WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
| +CREATE TRIGGER calls_team_home_person_keep_row BEFORE DELETE ON persons WHEN EXISTS(SELECT 1 FROM calls_team_home_persons WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'calls team: refused'); END; |
diff --git a/internal/calls/teamstate/store.go b/internal/calls/teamstate/store.go| new file mode 100644 |
| index 0000000..c1481e1 |
| --- /dev/null |
| +++ b/internal/calls/teamstate/store.go |
| @@ -0,0 +1,203 @@ |
| +// 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 ("calls", set calls_team), merged beside this |
| +// package's own set (calls_team_home). Calls' people are its persons |
| +// table, whose email column is NOT NULL and UNIQUE, so a Home-only |
| +// person is a persons row whose email is a random "home-only:" |
| +// placeholder that holds no address — no "@", never mailed, never shown |
| +// — 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" |
| + "crypto/rand" |
| + "database/sql" |
| + "embed" |
| + "encoding/hex" |
| + "errors" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema is the Home-only persons table and its triggers. They name |
| +// persons and home_identity_links, so it is merged after Calls' own |
| +// schema and linkstore's (team_config.go's teamBoot). |
| +var Schema = migrate.MustFromFS(migrations, "calls_team_home") |
| + |
| +var ( |
| + // ErrRefused is a definite "no": no such person, or a subject that |
| + // cannot be one. |
| + ErrRefused = errors.New("calls team: refused") |
| + // ErrUnavailable is "cannot read it now". |
| + ErrUnavailable = errors.New("calls team: unavailable") |
| +) |
| + |
| +// PlaceholderPrefix starts every Home-only person's email column. The |
| +// triggers check it, and Addressless recognises it: nothing that sends |
| +// mail or shows an address may use such a value. |
| +const PlaceholderPrefix = "home-only:" |
| + |
| +// Addressless reports whether a persons.email value is a Home-only |
| +// placeholder rather than an address. An anonymous guest's "guest:" value |
| +// is not one: it is never a Home identity. |
| +func Addressless(email string) bool { |
| + return strings.HasPrefix(email, PlaceholderPrefix) |
| +} |
| + |
| +// HomePerson reads the person a Home-only identity was given. It never |
| +// creates one: ErrRefused means there is none. |
| +func HomePerson(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 person_id FROM calls_team_home_persons 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 person 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, person int64) (string, error) { |
| + var subject string |
| + e := db.QueryRowContext(ctx, `SELECT subject FROM calls_team_home_persons WHERE issuer=? AND person_id=? |
| + UNION ALL SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=? LIMIT 1`, issuer, person, issuer, person).Scan(&subject) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", ErrRefused |
| + } |
| + if e != nil { |
| + return "", ErrUnavailable |
| + } |
| + return subject, nil |
| +} |
| + |
| +// PersonSubject is one person the roster can be asked about. |
| +type PersonSubject struct { |
| + PersonID int64 |
| + Subject string |
| +} |
| + |
| +// Subjects is every person on this instance with a Home subject — a |
| +// Home-only row or an account link — for asking the roster about people |
| +// who are not making the request (a knock's push recipients). It says |
| +// who could be on the team, never who is. |
| +func Subjects(ctx context.Context, db *sql.DB, issuer string) ([]PersonSubject, error) { |
| + rows, e := db.QueryContext(ctx, `SELECT person_id, subject FROM calls_team_home_persons WHERE issuer=? |
| + UNION ALL SELECT person_id, subject FROM home_identity_links WHERE issuer=?`, issuer, issuer) |
| + if e != nil { |
| + return nil, ErrUnavailable |
| + } |
| + defer rows.Close() |
| + var out []PersonSubject |
| + for rows.Next() { |
| + var ps PersonSubject |
| + if rows.Scan(&ps.PersonID, &ps.Subject) != nil { |
| + return nil, ErrUnavailable |
| + } |
| + out = append(out, ps) |
| + } |
| + if rows.Err() != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return out, nil |
| +} |
| + |
| +// EnsureHomePerson gives a Home subject an addressless person, 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. |
| +// |
| +// name is the display name the person goes by in a call's roster, which |
| +// for a Home-only person is a label built from the subject, never an |
| +// address. |
| +func EnsureHomePerson(ctx context.Context, db *sql.DB, issuer, subject, name string) (id int64, created bool, err error) { |
| + if !Opaque(subject) || issuer == "" || strings.Contains(name, "@") { |
| + 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 person_id FROM calls_team_home_persons 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 |
| + } |
| + placeholder, e := newPlaceholder() |
| + if e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + res, e := tx.ExecContext(ctx, `INSERT INTO persons(email,name,created_at,anonymous) VALUES(?,?,?,0)`, placeholder, name, 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 calls_team_home_persons(issuer,subject,person_id) VALUES(?,?,?)", issuer, subject, id); e != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + if tx.Commit() != nil { |
| + return 0, false, ErrUnavailable |
| + } |
| + return id, true, nil |
| +} |
| + |
| +// newPlaceholder is the persons.email a Home-only person holds: the |
| +// prefix and sixteen random bytes, unique (the column is) and never an |
| +// address (no "@"). |
| +func newPlaceholder() (string, error) { |
| + b := make([]byte, 16) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + return PlaceholderPrefix + hex.EncodeToString(b), 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/calls/templates/index.html b/internal/calls/templates/index.html| index ec405a8..5817848 100644 |
| --- a/internal/calls/templates/index.html |
| +++ b/internal/calls/templates/index.html |
| @@ -13,7 +13,8 @@ |
| </section> |
| <section> |
| <h2>Upcoming</h2> |
| -{{if .Upcoming}} |
| +{{if .Partial}}<div data-partial>{{template "callout" dict "Title" .PartialTitle "Body" .PartialBody "Tone" "warning"}}</div> |
| +{{else if .Upcoming}} |
| <div rst-list class="calls-meetings"> |
| {{range .Upcoming}} |
| <div rst-row> |