diff --git a/changelog.d/added-18596-companion-token.md b/changelog.d/added-18596-companion-token.md new file mode 100644 index 0000000000..63949af5b4 --- /dev/null +++ b/changelog.d/added-18596-companion-token.md @@ -0,0 +1 @@ +- Meetings: per-user desktop companion tokens (`/companion/token`), admitted only on the companion meeting routes at the user's live role; hosted hubs pass `/api/companion/info` and `/api/companion/meetings/*` through to the hive (#18596). diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index d281c7eccf..dae36edc46 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -27,7 +27,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1792` | | `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1793` | | `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1794` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:559` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:560` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:561` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:562` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:560` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:561` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:562` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:563` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 886c542b78..03646e6549 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -101,11 +101,11 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:215` | | `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:524` | | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:525` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:553` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:554` | -| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:556` | -| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:565` | -| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:566` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:554` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:555` | +| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:557` | +| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:566` | +| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:567` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 065ec666a1..b2f5938537 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -25,7 +25,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:551`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:552`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | | `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_acmm_eval.go` | | `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:346` | diff --git a/src/docs/meetings.md b/src/docs/meetings.md index 9b45535169..f7eb9eaeb8 100644 --- a/src/docs/meetings.md +++ b/src/docs/meetings.md @@ -155,6 +155,7 @@ The desktop companion ([hivecommons/quorum-companion](https://github.com/hivecom - **Consent.** Before every capture the companion shows the companion consent notice (`GET /api/companion/info`, versioned) and the person confirms the participants were told and agreed. Zoom does not tell the other participants, so that confirmation is the consent gate. The meeting records who confirmed it, when, and the notice version (`companion` on the meeting record). The companion keeps a "Betty is listening" indicator on while it captures and offers the notice on the clipboard to paste into the meeting chat. - **Who can use it.** Owner or read-write users. A companion meeting can be used only by the person who started it (owners can use any). Read-only users cannot stream. +- **Signing in.** Each owner or read-write user opens `/companion/token` on their hive and creates a companion token (shown once; only its SHA-256 is stored, one per user, **Replace** or **Revoke** any time). The companion sends it as `X-Hive-Companion-Token`. It works only on the `/api/companion/info` and `/api/companion/meetings` routes, acts as that user at their current role (a user removed or downgraded below read-write stops working at once), and never in `Authorization`. On hosted hives the hub lets those routes through to the hive, which does the check; the token page stays behind the hub sign-in. - **Audio.** Two channels of raw 16 kHz mono s16le PCM: `call` (the meeting app's audio, everyone else) and `mic` (the person). Quorum cuts each at silences and transcribes it with the shared transcription service (`meetings.transcribe_url` is required); `mic` segments are attributed to the person, `call` segments to "Call". - **Betty's replies** go to the companion window (and the meeting panel) instead of a meeting chat: the consent notice first, then answers. Betty cannot speak in a companion meeting yet. Saying "betty leave" ends the meeting, as does stopping the capture. - **After the meeting** it is an ordinary meeting: notes, research and the Inbox hand-off are unchanged. diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index deb209505e..2a8e098401 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -540,6 +540,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.registerInboxRecordingRoutes() s.registerMeetingsRoutes() s.registerCompanionRoutes() + s.registerCompanionTokenRoutes() s.registerMeetingsScheduleRoutes() s.registerMeetingsPersonaRoutes() s.registerMeetingsModelRoutes() diff --git a/src/pkg/dashboard/companion_token.go b/src/pkg/dashboard/companion_token.go new file mode 100644 index 0000000000..a48ce84dfa --- /dev/null +++ b/src/pkg/dashboard/companion_token.go @@ -0,0 +1,284 @@ +package dashboard + +import ( + "encoding/json" + "errors" + "fmt" + "html/template" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Desktop companion tokens (hivecommons/hive#18596). +// +// The companion app (hivecommons/quorum-companion) has no browser session, so +// each owner or read-write user mints one companion token for themselves on +// the /companion/token page. The token: +// +// - travels in companionTokenHeader (never Authorization, so a hosted hive's +// hub auth-check never treats it as a GitHub token); +// - is admitted by authenticate only on the companion meeting routes +// (companionTokenAdmits), never on the token page or any other route; +// - acts as the user who minted it at their LIVE role (liveAllowlistRole, +// the rule sessions use), so a revoked or downgraded user stops working at +// once, and a role below read-write is refused; +// - is stored only as its SHA-256, one per user; minting again replaces it, +// revoking deletes it. The plaintext is shown once. +const ( + companionTokenHeader = "X-Hive-Companion-Token" + companionTokenPrefix = "hct_" + companionTokenBytes = 32 + // companionTokenTouchInterval throttles last-used bookkeeping. + companionTokenTouchInterval = 10 * time.Minute + companionTokenPagePath = "/companion/token" +) + +// companionTokenPath is a package var so tests can point it at a temp dir. +var companionTokenPath = "/data/companion-tokens.json" + +var companionTokenMu sync.Mutex + +type companionTokenRecord struct { + Hash string `json:"hash"` + Role string `json:"role"` + CreatedAt string `json:"createdAt"` + LastUsedAt string `json:"lastUsedAt,omitempty"` +} + +type companionTokenFile struct { + Tokens map[string]companionTokenRecord `json:"tokens"` +} + +func loadCompanionTokens() (companionTokenFile, error) { + out := companionTokenFile{Tokens: map[string]companionTokenRecord{}} + data, err := os.ReadFile(companionTokenPath) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return out, nil + } + return out, err + } + if err := json.Unmarshal(data, &out); err != nil { + return out, fmt.Errorf("parse companion tokens: %w", err) + } + if out.Tokens == nil { + out.Tokens = map[string]companionTokenRecord{} + } + return out, nil +} + +func saveCompanionTokens(f companionTokenFile) error { + if err := os.MkdirAll(filepath.Dir(companionTokenPath), 0o700); err != nil { + return err + } + data, err := json.Marshal(f) + if err != nil { + return err + } + tmp := companionTokenPath + ".tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + return err + } + return os.Rename(tmp, companionTokenPath) +} + +// mintCompanionToken replaces user's token and returns the new plaintext. +func mintCompanionToken(user, role string, now time.Time) (string, error) { + token := companionTokenPrefix + randomHex(companionTokenBytes) + companionTokenMu.Lock() + defer companionTokenMu.Unlock() + f, err := loadCompanionTokens() + if err != nil { + return "", err + } + f.Tokens[user] = companionTokenRecord{Hash: sha256Hex(token), Role: role, CreatedAt: now.UTC().Format(time.RFC3339)} + if err := saveCompanionTokens(f); err != nil { + return "", err + } + return token, nil +} + +// revokeCompanionToken deletes user's token; it reports whether one existed. +func revokeCompanionToken(user string) (bool, error) { + companionTokenMu.Lock() + defer companionTokenMu.Unlock() + f, err := loadCompanionTokens() + if err != nil { + return false, err + } + if _, ok := f.Tokens[user]; !ok { + return false, nil + } + delete(f.Tokens, user) + return true, saveCompanionTokens(f) +} + +// companionTokenStatus is user's token record, if any. +func companionTokenStatus(user string) (companionTokenRecord, bool) { + f, err := loadCompanionTokens() + if err != nil { + return companionTokenRecord{}, false + } + rec, ok := f.Tokens[user] + return rec, ok +} + +// companionTokenOwner returns the user and minted role of a valid token. +// Fails closed on any read or parse error. +func companionTokenOwner(token string, now time.Time) (user, role string, ok bool) { + token = strings.TrimSpace(token) + if !strings.HasPrefix(token, companionTokenPrefix) || len(token) <= len(companionTokenPrefix) { + return "", "", false + } + hash := sha256Hex(token) + companionTokenMu.Lock() + defer companionTokenMu.Unlock() + f, err := loadCompanionTokens() + if err != nil { + return "", "", false + } + for u, rec := range f.Tokens { + if !secureCompare(hash, rec.Hash) { + continue + } + if last, err := time.Parse(time.RFC3339, rec.LastUsedAt); err != nil || now.Sub(last) >= companionTokenTouchInterval { + rec.LastUsedAt = now.UTC().Format(time.RFC3339) + f.Tokens[u] = rec + _ = saveCompanionTokens(f) + } + return u, rec.Role, true + } + return "", "", false +} + +// companionTokenAdmits lists the only paths a companion token may reach. +func companionTokenAdmits(path string) bool { + return path == "/api/companion/info" || path == "/api/companion/meetings" || + strings.HasPrefix(path, "/api/companion/meetings/") +} + +// companionTokenAuthenticates is authenticate's hook: on a companion route +// with a valid token it injects the minting user's identity at their live +// role and reports true. A user whose live role is below read-write (or who +// was revoked) is not authenticated. +func (s *Server) companionTokenAuthenticates(r *http.Request) bool { + if !companionTokenAdmits(r.URL.Path) { + return false + } + user, minted, ok := companionTokenOwner(r.Header.Get(companionTokenHeader), time.Now()) + if !ok { + return false + } + role, ok := s.liveAllowlistRole(user, minted) + if !ok || !config.RoleAtLeast(role, config.RoleReadWrite) { + return false + } + r.Header.Set("X-Hive-User", user) + r.Header.Set("X-Hive-Role", role) + if isOwnerRole(role) { + r.Header.Set(ownerRoleVerifiedHeader, "true") + } + return true +} + +func (s *Server) registerCompanionTokenRoutes() { + s.mux.HandleFunc("GET "+companionTokenPagePath, s.handleCompanionTokenPage) + s.mux.HandleFunc("POST "+companionTokenPagePath, s.handleCompanionTokenMint) + s.mux.HandleFunc("POST "+companionTokenPagePath+"/revoke", s.handleCompanionTokenRevoke) +} + +var companionTokenPage = template.Must(template.New("companion-token").Parse(` + +Companion token + +

Desktop companion token

+

The Quorum Companion app lets Betty listen to a call through your own meeting app, after you confirm the participants were told. It signs in to this hive with a companion token: it works only for companion meetings, acts as you ({{.User}}), and stops working if your access is removed.

+{{if .Token}}

Your new token (shown once; paste it into the companion's Settings with this hive's URL):

+
{{.Token}}
+

Hive URL: {{.HiveURL}}

{{end}} +{{if .Revoked}}

Your companion token was revoked. Companions using it stop working now.

{{end}} +{{if .Has}}

You have a token, created {{.CreatedAt}}{{if .LastUsedAt}}, last used {{.LastUsedAt}}{{end}}.

{{else if not .Token}}

You have no companion token.

{{end}} +
+{{if .Has}}
{{end}} +`)) + +type companionTokenView struct { + User, Token, HiveURL, CreatedAt, LastUsedAt string + Has, Revoked bool +} + +func (s *Server) renderCompanionTokenPage(w http.ResponseWriter, r *http.Request, v companionTokenView) { + v.User = requestUser(r) + if rec, ok := companionTokenStatus(v.User); ok { + v.Has, v.CreatedAt, v.LastUsedAt = true, rec.CreatedAt, rec.LastUsedAt + } + if v.HiveURL == "" { + v.HiveURL = widgetHiveURL(r, "") + } + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + if err := companionTokenPage.Execute(w, v); err != nil { + s.logger.Warn("companion token page", "error", err) + } +} + +// companionTokenForm admits owner or read-write and refuses cross-site posts. +func companionTokenForm(w http.ResponseWriter, r *http.Request) bool { + if !requireInboxPlaybackRole(w, r) { + return false + } + if r.Method == http.MethodPost && r.Header.Get("Sec-Fetch-Site") == "cross-site" { + jsonError(w, "cross-site request refused", http.StatusForbidden) + return false + } + return true +} + +func (s *Server) handleCompanionTokenPage(w http.ResponseWriter, r *http.Request) { + if !companionTokenForm(w, r) { + return + } + s.renderCompanionTokenPage(w, r, companionTokenView{}) +} + +func (s *Server) handleCompanionTokenMint(w http.ResponseWriter, r *http.Request) { + if !companionTokenForm(w, r) { + return + } + token, err := mintCompanionToken(requestUser(r), r.Header.Get("X-Hive-Role"), time.Now()) + if err != nil { + s.logger.Warn("companion token: persist failed", "error", err) + jsonError(w, "could not store the companion token", http.StatusInternalServerError) + return + } + s.auditFromRequest(r, "companion_token_mint", "", "") + s.renderCompanionTokenPage(w, r, companionTokenView{Token: token}) +} + +func (s *Server) handleCompanionTokenRevoke(w http.ResponseWriter, r *http.Request) { + if !companionTokenForm(w, r) { + return + } + removed, err := revokeCompanionToken(requestUser(r)) + if err != nil { + jsonError(w, "could not revoke the companion token", http.StatusInternalServerError) + return + } + if removed { + s.auditFromRequest(r, "companion_token_revoke", "", "") + } + s.renderCompanionTokenPage(w, r, companionTokenView{Revoked: removed}) +} diff --git a/src/pkg/dashboard/companion_token_test.go b/src/pkg/dashboard/companion_token_test.go new file mode 100644 index 0000000000..ce48a61f76 --- /dev/null +++ b/src/pkg/dashboard/companion_token_test.go @@ -0,0 +1,224 @@ +package dashboard + +import ( + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" +) + +func serverWithCompanionTokens(t *testing.T) (*Server, *Dependencies) { + t.Helper() + old := companionTokenPath + companionTokenPath = filepath.Join(t.TempDir(), "companion-tokens.json") + t.Cleanup(func() { companionTokenPath = old }) + logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})) + s := NewServerWithAuth(0, "dashboard-secret", logger) + deps := testDeps(t) + s.RegisterAPI(deps) + s.SetMeetingsService(&fakeCompanionService{}) + return s, deps +} + +var companionTokenRE = regexp.MustCompile(`hct_[0-9a-f]+`) + +func companionTokenPagePost(t *testing.T, s *Server, path, user, role string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, nil) + req.Header.Set("X-Hive-User", user) + req.Header.Set("X-Hive-Role", role) + s.mux.ServeHTTP(rec, req) + return rec +} + +func mintCompanionTokenAs(t *testing.T, s *Server, user string) string { + t.Helper() + rec := companionTokenPagePost(t, s, companionTokenPagePath, user, "read-write") + if rec.Code != http.StatusOK { + t.Fatalf("mint = %d %s", rec.Code, rec.Body.String()) + } + token := companionTokenRE.FindString(rec.Body.String()) + if token == "" { + t.Fatalf("no token on the page: %s", rec.Body.String()) + } + return token +} + +func TestCompanionTokenPageMintsShowsAndRevokes(t *testing.T) { + s, _ := serverWithCompanionTokens(t) + get := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, companionTokenPagePath, nil) + req.Header.Set("X-Hive-User", "ana") + req.Header.Set("X-Hive-Role", "read-write") + s.mux.ServeHTTP(get, req) + if get.Code != http.StatusOK || !strings.Contains(get.Body.String(), "no companion token") { + t.Fatalf("page = %d %s", get.Code, get.Body.String()) + } + + token := mintCompanionTokenAs(t, s, "ana") + if !strings.HasPrefix(token, companionTokenPrefix) { + t.Fatalf("token = %q", token) + } + raw, err := os.ReadFile(companionTokenPath) + if err != nil || strings.Contains(string(raw), token) || !strings.Contains(string(raw), sha256Hex(token)) { + t.Fatalf("stored = %s (%v)", raw, err) + } + if info, err := os.Stat(companionTokenPath); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("token file mode = %v (%v)", info, err) + } + again := httptest.NewRecorder() + s.mux.ServeHTTP(again, req) + if body := again.Body.String(); strings.Contains(body, token) || !strings.Contains(body, "You have a token") { + t.Fatalf("page after mint shows the token again or no status: %s", body) + } + + if rec := companionTokenPagePost(t, s, companionTokenPagePath+"/revoke", "ana", "read-write"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "was revoked") { + t.Fatalf("revoke = %d %s", rec.Code, rec.Body.String()) + } + if _, ok := companionTokenStatus("ana"); ok { + t.Fatal("token still stored after revoke") + } + if rec := companionTokenPagePost(t, s, companionTokenPagePath+"/revoke", "ana", "read-write"); rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "was revoked") { + t.Fatalf("second revoke = %d", rec.Code) + } + + if rec := companionTokenPagePost(t, s, companionTokenPagePath, "rita", "read"); rec.Code != http.StatusForbidden { + t.Fatalf("read role mint = %d", rec.Code) + } + cross := httptest.NewRecorder() + creq := httptest.NewRequest(http.MethodPost, companionTokenPagePath, nil) + creq.Header.Set("X-Hive-User", "ana") + creq.Header.Set("X-Hive-Role", "read-write") + creq.Header.Set("Sec-Fetch-Site", "cross-site") + s.mux.ServeHTTP(cross, creq) + if cross.Code != http.StatusForbidden { + t.Fatalf("cross-site mint = %d", cross.Code) + } +} + +func TestCompanionTokenReachesOnlyTheCompanionRoutes(t *testing.T) { + s, _ := serverWithCompanionTokens(t) + token := mintCompanionTokenAs(t, s, "ana") + h := s.Handler() + do := func(method, path string, header string) int { + rec := httptest.NewRecorder() + req := httptest.NewRequest(method, path, strings.NewReader("{}")) + if header == "authorization" { + req.Header.Set("Authorization", "Bearer "+token) + } else if header != "" { + req.Header.Set(companionTokenHeader, header) + } + h.ServeHTTP(rec, req) + return rec.Code + } + if code := do(http.MethodGet, "/api/companion/info", token); code != http.StatusOK { + t.Fatalf("info with token = %d", code) + } + if code := do(http.MethodPost, "/api/companion/meetings/mtg-c1/end", token); code != http.StatusOK { + t.Fatalf("end with token = %d", code) + } + for _, tc := range []struct{ method, path string }{ + {http.MethodGet, companionTokenPagePath}, + {http.MethodPost, companionTokenPagePath}, + {http.MethodGet, "/api/meetings"}, + {http.MethodGet, "/api/status"}, + {http.MethodPost, "/api/pause"}, + {http.MethodGet, "/api/companion/meetingsx"}, + } { + if code := do(tc.method, tc.path, token); code != http.StatusUnauthorized { + t.Errorf("%s %s with companion token = %d, want 401", tc.method, tc.path, code) + } + } + if code := do(http.MethodGet, "/api/companion/info", "authorization"); code != http.StatusUnauthorized { + t.Errorf("token in Authorization = %d, want 401", code) + } + for _, bad := range []string{"hct_nope", "hwt_" + strings.TrimPrefix(token, companionTokenPrefix), "hct_"} { + if code := do(http.MethodGet, "/api/companion/info", bad); code != http.StatusUnauthorized { + t.Errorf("token %q = %d, want 401", bad, code) + } + } + if _, err := revokeCompanionToken("ana"); err != nil { + t.Fatal(err) + } + if code := do(http.MethodGet, "/api/companion/info", token); code != http.StatusUnauthorized { + t.Errorf("revoked token = %d, want 401", code) + } +} + +func TestCompanionTokenActsAtTheLiveRole(t *testing.T) { + s, deps := serverWithCompanionTokens(t) + token := mintCompanionTokenAs(t, s, "ana") + req := func() *http.Request { + r := httptest.NewRequest(http.MethodGet, "/api/companion/info", nil) + r.Header.Set(companionTokenHeader, token) + return r + } + r := req() + if !s.companionTokenAuthenticates(r) || r.Header.Get("X-Hive-User") != "ana" || r.Header.Get("X-Hive-Role") != "read-write" { + t.Fatalf("identity = %q %q", r.Header.Get("X-Hive-User"), r.Header.Get("X-Hive-Role")) + } + deps.Config.Dashboard.AuthorizedUsers = []string{"octo", "ana:owner"} + r = req() + if !s.companionTokenAuthenticates(r) || r.Header.Get("X-Hive-Role") != "owner" || r.Header.Get(ownerRoleVerifiedHeader) != "true" { + t.Fatalf("upgraded identity = %q verified=%q", r.Header.Get("X-Hive-Role"), r.Header.Get(ownerRoleVerifiedHeader)) + } + deps.Config.Dashboard.AuthorizedUsers = []string{"octo", "ana:read"} + if s.companionTokenAuthenticates(req()) { + t.Fatal("a user downgraded to read must not stream") + } + deps.Config.Dashboard.AuthorizedUsers = []string{"octo"} + deps.Config.Dashboard.HubProxied = false + if s.companionTokenAuthenticates(req()) { + t.Fatal("a user removed from a direct-route allowlist must not stream") + } +} + +func TestCompanionTokenStoreEdges(t *testing.T) { + old := companionTokenPath + companionTokenPath = filepath.Join(t.TempDir(), "sub", "companion-tokens.json") + t.Cleanup(func() { companionTokenPath = old }) + if _, _, ok := companionTokenOwner("hct_missing", time.Now()); ok { + t.Fatal("no file must not authenticate") + } + tok, err := mintCompanionToken("ana", "read-write", time.Now().Add(-time.Hour)) + if err != nil { + t.Fatal(err) + } + if u, role, ok := companionTokenOwner(tok, time.Now()); !ok || u != "ana" || role != "read-write" { + t.Fatalf("owner = %q %q %v", u, role, ok) + } + if rec, _ := companionTokenStatus("ana"); rec.LastUsedAt == "" { + t.Fatal("last use not recorded") + } + if err := os.WriteFile(companionTokenPath, []byte("not json"), 0o600); err != nil { + t.Fatal(err) + } + if _, _, ok := companionTokenOwner(tok, time.Now()); ok { + t.Fatal("a corrupt store must fail closed") + } + if _, err := mintCompanionToken("ana", "read-write", time.Now()); err == nil { + t.Fatal("minting over a corrupt store should fail") + } + if _, err := revokeCompanionToken("ana"); err == nil { + t.Fatal("revoking from a corrupt store should fail") + } + if _, ok := companionTokenStatus("ana"); ok { + t.Fatal("corrupt store has no status") + } + if err := os.WriteFile(companionTokenPath, []byte(`{}`), 0o600); err != nil { + t.Fatal(err) + } + if f, err := loadCompanionTokens(); err != nil || f.Tokens == nil { + t.Fatalf("empty store = %+v %v", f, err) + } + if !companionTokenAdmits("/api/companion/meetings") || companionTokenAdmits("/api/companion/token") { + t.Fatal("admitted paths") + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index ce809a0e67..d191a72cd2 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -2407,6 +2407,13 @@ func (s *Server) authenticate(next http.Handler) http.Handler { widgetTokenIdentity(r) } + // Desktop companion token (#18596): admits ONLY the companion meeting + // routes, as the minting user at their live role (read-write or + // owner). It never reaches the token page or any other route. + if !trusted && s.companionTokenAuthenticates(r) { + trusted = true + } + if !trusted && r.URL.Path == "/api/knowledge/export" { profile, reason := authenticateContributorToken(registrationTokenFromAuthorization(r), s.contributorTokenPolicy()) if profile == nil && reason == contributorTokenExpired { diff --git a/src/pkg/hub/companion_public_path_test.go b/src/pkg/hub/companion_public_path_test.go new file mode 100644 index 0000000000..158ff36afb --- /dev/null +++ b/src/pkg/hub/companion_public_path_test.go @@ -0,0 +1,23 @@ +package hub + +import "testing" + +// The desktop companion's routes bypass the hub gate (the spoke checks the +// companion token); the token page stays behind it (#18596). +func TestCompanionRoutesBypassTheHubGateButNotTheTokenPage(t *testing.T) { + for _, uri := range []string{ + "/api/companion/info", + "/api/companion/meetings", + "/api/companion/meetings/mtg-1/audio?channel=mic&seq=0", + "/api/companion/meetings/mtg-1/replies?after=3", + } { + if !isSaaSPublicPath(uri) { + t.Errorf("%s should reach the spoke", uri) + } + } + for _, uri := range []string{"/companion/token", "/companion/token/revoke", "/api/companion/token", "/api/companion/meetingsx", "/api/meetings"} { + if isSaaSPublicPath(uri) { + t.Errorf("%s must stay behind the hub gate", uri) + } + } +} diff --git a/src/pkg/hub/saas_auth.go b/src/pkg/hub/saas_auth.go index e709a242bc..915f6ecdde 100644 --- a/src/pkg/hub/saas_auth.go +++ b/src/pkg/hub/saas_auth.go @@ -879,6 +879,9 @@ var publicExactPaths = map[string]struct{}{ ssoHandoffPath: {}, "/tokens.css": {}, spokeWidgetSummaryPath: {}, + // The desktop companion's settings route (#18596); see + // spokeCompanionMeetingsPath. + spokeCompanionInfoPath: {}, spokeWebhookRelayPath: {}, // The hive-mx mail relay targets (#18395, mail_relay.go). Like the // webhook receiver, each spoke handler fails closed without a valid @@ -890,7 +893,7 @@ var publicExactPaths = map[string]struct{}{ wire.SpokeFilesChunkPath: {}, } -var publicTreePaths = []string{"/api/contribute", "/api/leaderboard", "/contribute", "/leaderboard", "/snapshot"} +var publicTreePaths = []string{"/api/contribute", "/api/leaderboard", "/contribute", "/leaderboard", "/snapshot", spokeCompanionMeetingsPath} var publicStaticAssetPrefixes = []string{"/static/infra/", "/static/integrations/"} @@ -960,6 +963,20 @@ const knowledgeExportPath = "/api/knowledge/export" // 401. const spokeWidgetSummaryPath = "/api/widget/summary" +// spokeCompanionInfoPath and spokeCompanionMeetingsPath are the spoke's +// desktop companion routes (#18596). The companion app has no browser +// session, so the hub's nginx auth_request gate must wave them through, +// exactly like spokeWidgetSummaryPath. This does NOT open them to anonymous +// callers: the spoke admits these paths only with a hub session, the shared +// token, or a per-user companion token (X-Hive-Companion-Token, never +// Authorization, so the hub never forwards it to GitHub) whose user still +// has read-write or owner access; anything else is a 401. The token page +// (/companion/token) stays behind the hub gate. +const ( + spokeCompanionInfoPath = "/api/companion/info" + spokeCompanionMeetingsPath = "/api/companion/meetings" +) + // spokeWebhookRelayPath is the spoke's GitHub App webhook receiver, the path // the hub POSTs every relayed delivery to (relayWebhookToSpoke in webhook.go, // #11177 / #13165). The relay carries no hub session, so without this entry