diff --git a/changelog.d/added-19160-hub-customer-consent.md b/changelog.d/added-19160-hub-customer-consent.md new file mode 100644 index 0000000000..8778a05cf0 --- /dev/null +++ b/changelog.d/added-19160-hub-customer-consent.md @@ -0,0 +1 @@ +- Hub operators can enable a profile-sharing page where people enter their own profile details and grant or withdraw consent per hive and field. Scale Controls shows the effective setting. Off by default; no profile data is sent to hives in this phase ([#19160](https://github.com/hivecommons/hive/issues/19160)). diff --git a/src/docs/api-reference/hub-saas.md b/src/docs/api-reference/hub-saas.md index bfeadafa03..3e39ebb680 100644 --- a/src/docs/api-reference/hub-saas.md +++ b/src/docs/api-reference/hub-saas.md @@ -5,109 +5,109 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/saas/my-hives` | Hub auth | My Hives. Each row carries `quadrant` and the payload carries `fleet_quadrant` ([#12458](https://github.com/hivecommons/hive/issues/12458)): `axes[]` of `{axis, score, scored, reason?, delta, nudge?, criteria[], measured, unmeasured, summary?, n?}` where each `criteria[]` entry is `{name, label, measured, value, display?, score, weight, how, good, reason?, n?}`; every criterion maps to 0–100 on a fixed named curve, an axis is the weighted mean of its *measured* criteria only (an unmeasured criterion is listed with `reason` and excluded, never scored 0), `composite` averages the scored axes, and `fleet_quadrant` is the per-axis **median** across hives in view (`aggregate: "median"`, `n` hives) with each criterion's median value. `delta` is the hive minus the fleet median. Shape is additive over the earlier `axes[]{axis,score,scored,reason,delta,nudge}`/`composite`/`scored_axes` payload. See [Fleet quadrant](../fleet-health.md#fleet-quadrant) | `pkg/hub/saas.go:371`, `pkg/hub/quadrant.go` | -| `GET` | `/api/hub/widget` | Hub auth | iPhone fleet widget ([#12148](https://github.com/hivecommons/hive/issues/12148)): every hive the caller can see (hub admins: all; others: hives they own or hold a role on; pool placeholders excluded), sorted by `act_issues + act_prs` descending. Per hive `id`, `project`, `url`, `online`, `acmm_level`, `issues`, `prs` (all open, from the heartbeat; 0 from spokes that do not report them), `act_issues`, `act_prs`, `agents_running`, `agents_total`, `last_heartbeat`; `totals` (`hives`, `online`, `need_you`, the same counts summed) and `history` (fleet `act_issues`/`act_prs` per 15-minute bucket, `t` in Unix seconds, at most 48 points). See [iOS widget](../ios-widget.md#fleet-widget-hub-mode) | `pkg/hub/saas.go:372` | -| `GET` | `/api/saas/usage` | Hub auth | Usage | `pkg/hub/saas.go:381` | -| `POST` | `/api/saas/hives` | Hub auth | Create Hive | `pkg/hub/saas.go:394` | -| `GET` | `/api/saas/hives/{id}/status` | Hub auth | Hive Status | `pkg/hub/saas.go:395` | +| `GET` | `/api/saas/my-hives` | Hub auth | My Hives. Each row carries `quadrant` and the payload carries `fleet_quadrant` ([#12458](https://github.com/hivecommons/hive/issues/12458)): `axes[]` of `{axis, score, scored, reason?, delta, nudge?, criteria[], measured, unmeasured, summary?, n?}` where each `criteria[]` entry is `{name, label, measured, value, display?, score, weight, how, good, reason?, n?}`; every criterion maps to 0–100 on a fixed named curve, an axis is the weighted mean of its *measured* criteria only (an unmeasured criterion is listed with `reason` and excluded, never scored 0), `composite` averages the scored axes, and `fleet_quadrant` is the per-axis **median** across hives in view (`aggregate: "median"`, `n` hives) with each criterion's median value. `delta` is the hive minus the fleet median. Shape is additive over the earlier `axes[]{axis,score,scored,reason,delta,nudge}`/`composite`/`scored_axes` payload. See [Fleet quadrant](../fleet-health.md#fleet-quadrant) | `pkg/hub/saas.go:363`, `pkg/hub/quadrant.go` | +| `GET` | `/api/hub/widget` | Hub auth | iPhone fleet widget ([#12148](https://github.com/hivecommons/hive/issues/12148)): every hive the caller can see (hub admins: all; others: hives they own or hold a role on; pool placeholders excluded), sorted by `act_issues + act_prs` descending. Per hive `id`, `project`, `url`, `online`, `acmm_level`, `issues`, `prs` (all open, from the heartbeat; 0 from spokes that do not report them), `act_issues`, `act_prs`, `agents_running`, `agents_total`, `last_heartbeat`; `totals` (`hives`, `online`, `need_you`, the same counts summed) and `history` (fleet `act_issues`/`act_prs` per 15-minute bucket, `t` in Unix seconds, at most 48 points). See [iOS widget](../ios-widget.md#fleet-widget-hub-mode) | `pkg/hub/saas.go:364` | +| `GET` | `/api/saas/usage` | Hub auth | Usage | `pkg/hub/saas.go:373` | +| `POST` | `/api/saas/hives` | Hub auth | Create Hive | `pkg/hub/saas.go:383` | +| `GET` | `/api/saas/hives/{id}/status` | Hub auth | Hive Status | `pkg/hub/saas.go:384` | | `POST` | `/api/saas/hives/{id}/pin-digest` | Hub auth (owner or admin) | Pin Digest - hold the spoke at an immutable image digest (`{"digest":"sha256:..."}` or `{"sha":""}`, optional `reason`) | `pkg/hub/digest_pin.go` | | `POST` | `/api/saas/hives/{id}/unpin-digest` | Hub auth (owner or admin) | Unpin Digest - lift the pin and return to the tracked channel or branch tag | `pkg/hub/digest_pin.go` | | `GET` | `/api/saas/hives/{id}/digest-pin` | Hub auth (owner or admin) | Digest Pin - the pin with provenance and whether the spoke reports running it | `pkg/hub/digest_pin.go` | -| `GET` | `/api/saas/hives/{id}/open` | Hub handler-specific | Open Hive | `pkg/hub/saas.go:400` | -| `DELETE` | `/api/saas/hives/{id}` | Hub auth (owner or admin) | Delete Hive | `pkg/hub/saas.go:401` | -| `POST` | `/api/saas/hives/{id}/upgrade` | Hub auth | Upgrade Hive - arms heartbeat delivery (`200 {"status":"upgrading"}`); a spoke already at its reachable target is a no-op `200 {"status":"current","current","target","channel","message"}`, not an error | `pkg/hub/saas.go:402` | -| `POST` | `/api/saas/hives/{id}/switch-branch` | Hub auth | Switch Branch | `pkg/hub/saas.go:403` | -| `PUT` | `/api/saas/hives/{id}/visibility` | Hub auth | Toggle Visibility | `pkg/hub/saas.go:410` | -| `PUT` | `/api/saas/hives/{id}/auto-upgrade` | Hub auth | Toggle Auto Upgrade | `pkg/hub/saas.go:411` | -| `PUT` | `/api/saas/hives/{id}/name` | Hub auth | Rename Hive | `pkg/hub/saas.go:415` | -| `POST` | `/api/saas/hives/{id}/forge` | Hub auth | Switch Forge | `pkg/hub/saas.go:420` | -| `POST` | `/api/saas/hives/{id}/reset-app` | Hub auth | Reset App | `pkg/hub/saas.go:421` | -| `POST` | `/api/saas/hives/{id}/restart-spoke` | Hub auth | Restart Spoke | `pkg/hub/saas.go:426` | -| `POST` | `/api/saas/hives/{id}/breaker` | Hub auth | Pause / Resume Hive (fleet breaker) | `pkg/hub/saas.go:429` | -| `GET` | `/api/saas/hive-config/{hiveID}` | Hub auth | Proxy Hive Config | `pkg/hub/saas.go:430` | -| `GET` | `/api/saas/latest-sha` | Hub handler-specific | Latest SHA | `pkg/hub/saas.go:431` | -| `GET` | `/api/hub/release/stable-promotion` | Public | Stable Promotion State | `pkg/hub/saas.go:433` | -| `POST` | `/api/saas/hub/upgrade` | Hub handler-specific | Hub Self Upgrade | `pkg/hub/saas.go:434` | -| `PUT` | `/api/saas/hub/auto-upgrade` | Hub handler-specific | Hub Auto Upgrade | `pkg/hub/saas.go:435` | -| `PUT` | `/api/hub/release/stable-promotion` | Hub admin | Stable Promotion Toggle (audit-logged) | `pkg/hub/saas.go:436` | -| `GET` | `/api/saas/auth-check` | Hub handler-specific | Saa SAuth Check | `pkg/hub/saas.go:441` | -| `POST` | `/api/saas/user-token` | Hub auth | User Token | `pkg/hub/saas.go:452` | -| `GET` | `/api/saas/hives/{id}/access` | Hub auth | Access List | `pkg/hub/saas.go:453` | -| `GET` | `/api/saas/grantable-users` | Hub auth | Grantable Users | `pkg/hub/saas.go:454` | -| `POST` | `/api/saas/hives/{id}/access` | Hub auth | Access Add | `pkg/hub/saas.go:455` | -| `DELETE` | `/api/saas/hives/{id}/access/{username}` | Hub auth | Access Remove | `pkg/hub/saas.go:456` | -| `POST` | `/api/saas/hives/{id}/request-access` | Hub auth | Request Access | `pkg/hub/saas.go:457` | -| `GET` | `/api/saas/hives/{id}/requests` | Hub auth | Get Requests | `pkg/hub/saas.go:458` | -| `GET` | `/api/saas/hives/{id}/timeline` | Hub auth | Hive Timeline | `pkg/hub/saas.go:459` | -| `POST` | `/api/saas/hives/{id}/requests/{username}/approve` | Hub auth | Approve Request | `pkg/hub/saas.go:461` | -| `POST` | `/api/saas/hives/{id}/requests/{username}/deny` | Hub auth | Deny Request | `pkg/hub/saas.go:462` | -| `PUT` | `/api/saas/hives/{id}/approve-access/{username}` | Hub auth | Approve Access | `pkg/hub/saas.go:463` | -| `DELETE` | `/api/saas/hives/{id}/deny-access/{username}` | Hub auth | Deny Access | `pkg/hub/saas.go:464` | -| `GET` | `/api/saas/access-status` | Hub handler-specific | Access Status | `pkg/hub/saas.go:465` | -| `POST` | `/api/saas/request-provision` | Hub auth | Request Provision | `pkg/hub/saas.go:473` | -| `PUT` | `/api/saas/approve-provision/{username}` | Hub handler-specific | Approve Provision | `pkg/hub/saas.go:474` | -| `DELETE` | `/api/saas/deny-provision/{username}` | Hub handler-specific | Deny Provision | `pkg/hub/saas.go:475` | -| `GET` | `/api/saas/admin/available-placeholders` | Hub handler-specific | Available Placeholders | `pkg/hub/saas.go:476` | -| `GET` | `/api/saas/admin/users` | Hub handler-specific | Admin Users | `pkg/hub/saas.go:479` | +| `GET` | `/api/saas/hives/{id}/open` | Hub handler-specific | Open Hive | `pkg/hub/saas.go:389` | +| `DELETE` | `/api/saas/hives/{id}` | Hub auth (owner or admin) | Delete Hive | `pkg/hub/saas.go:390` | +| `POST` | `/api/saas/hives/{id}/upgrade` | Hub auth | Upgrade Hive - arms heartbeat delivery (`200 {"status":"upgrading"}`); a spoke already at its reachable target is a no-op `200 {"status":"current","current","target","channel","message"}`, not an error | `pkg/hub/saas.go:391` | +| `POST` | `/api/saas/hives/{id}/switch-branch` | Hub auth | Switch Branch | `pkg/hub/saas.go:392` | +| `PUT` | `/api/saas/hives/{id}/visibility` | Hub auth | Toggle Visibility | `pkg/hub/saas.go:399` | +| `PUT` | `/api/saas/hives/{id}/auto-upgrade` | Hub auth | Toggle Auto Upgrade | `pkg/hub/saas.go:400` | +| `PUT` | `/api/saas/hives/{id}/name` | Hub auth | Rename Hive | `pkg/hub/saas.go:404` | +| `POST` | `/api/saas/hives/{id}/forge` | Hub auth | Switch Forge | `pkg/hub/saas.go:409` | +| `POST` | `/api/saas/hives/{id}/reset-app` | Hub auth | Reset App | `pkg/hub/saas.go:410` | +| `POST` | `/api/saas/hives/{id}/restart-spoke` | Hub auth | Restart Spoke | `pkg/hub/saas.go:415` | +| `POST` | `/api/saas/hives/{id}/breaker` | Hub auth | Pause / Resume Hive (fleet breaker) | `pkg/hub/saas.go:418` | +| `GET` | `/api/saas/hive-config/{hiveID}` | Hub auth | Proxy Hive Config | `pkg/hub/saas.go:419` | +| `GET` | `/api/saas/latest-sha` | Hub handler-specific | Latest SHA | `pkg/hub/saas.go:420` | +| `GET` | `/api/hub/release/stable-promotion` | Public | Stable Promotion State | `pkg/hub/saas.go:422` | +| `POST` | `/api/saas/hub/upgrade` | Hub handler-specific | Hub Self Upgrade | `pkg/hub/saas.go:423` | +| `PUT` | `/api/saas/hub/auto-upgrade` | Hub handler-specific | Hub Auto Upgrade | `pkg/hub/saas.go:424` | +| `PUT` | `/api/hub/release/stable-promotion` | Hub admin | Stable Promotion Toggle (audit-logged) | `pkg/hub/saas.go:425` | +| `GET` | `/api/saas/auth-check` | Hub handler-specific | Saa SAuth Check | `pkg/hub/saas.go:430` | +| `POST` | `/api/saas/user-token` | Hub auth | User Token | `pkg/hub/saas.go:441` | +| `GET` | `/api/saas/hives/{id}/access` | Hub auth | Access List | `pkg/hub/saas.go:442` | +| `GET` | `/api/saas/grantable-users` | Hub auth | Grantable Users | `pkg/hub/saas.go:443` | +| `POST` | `/api/saas/hives/{id}/access` | Hub auth | Access Add | `pkg/hub/saas.go:444` | +| `DELETE` | `/api/saas/hives/{id}/access/{username}` | Hub auth | Access Remove | `pkg/hub/saas.go:445` | +| `POST` | `/api/saas/hives/{id}/request-access` | Hub auth | Request Access | `pkg/hub/saas.go:446` | +| `GET` | `/api/saas/hives/{id}/requests` | Hub auth | Get Requests | `pkg/hub/saas.go:447` | +| `GET` | `/api/saas/hives/{id}/timeline` | Hub auth | Hive Timeline | `pkg/hub/saas.go:448` | +| `POST` | `/api/saas/hives/{id}/requests/{username}/approve` | Hub auth | Approve Request | `pkg/hub/saas.go:450` | +| `POST` | `/api/saas/hives/{id}/requests/{username}/deny` | Hub auth | Deny Request | `pkg/hub/saas.go:451` | +| `PUT` | `/api/saas/hives/{id}/approve-access/{username}` | Hub auth | Approve Access | `pkg/hub/saas.go:452` | +| `DELETE` | `/api/saas/hives/{id}/deny-access/{username}` | Hub auth | Deny Access | `pkg/hub/saas.go:453` | +| `GET` | `/api/saas/access-status` | Hub handler-specific | Access Status | `pkg/hub/saas.go:454` | +| `POST` | `/api/saas/request-provision` | Hub auth | Request Provision | `pkg/hub/saas.go:462` | +| `PUT` | `/api/saas/approve-provision/{username}` | Hub handler-specific | Approve Provision | `pkg/hub/saas.go:463` | +| `DELETE` | `/api/saas/deny-provision/{username}` | Hub handler-specific | Deny Provision | `pkg/hub/saas.go:464` | +| `GET` | `/api/saas/admin/available-placeholders` | Hub handler-specific | Available Placeholders | `pkg/hub/saas.go:465` | +| `GET` | `/api/saas/admin/users` | Hub handler-specific | Admin Users | `pkg/hub/saas.go:468` | `GET /api/saas/admin/users` includes cached `affiliation`, `affiliation_source`, `profile_bio`, `profile_location`, `public_activity`, `top_repo`, and `top_repo_url` fields for the Hub Admin — Users **AFFILIATION** column. The cache identifies who a signup appears affiliated with from public GitHub/GHE footprint only, ranked as profile company, contributed-to repo owner/org (excluding the personal namespace), public org membership, then top-repo owner/independent fallback; bio/location are supporting tooltip context, and `public_activity` buckets recent public events as `quiet`, `active`, or `prolific`. Provider API refreshes are asynchronous and daily, so the table never blocks on GitHub/GHE and never requires Hive activity. -| `PUT` | `/api/saas/admin/users/{username}` | Hub handler-specific | Admin Update User | `pkg/hub/saas.go:502` | -| `DELETE` | `/api/saas/admin/users/{username}` | Hub handler-specific | Admin Delete User | `pkg/hub/saas.go:503` | -| `POST` | `/api/saas/admin/impersonate/exit` | Hub handler-specific | Impersonate Exit | `pkg/hub/saas.go:509` | -| `POST` | `/api/saas/admin/impersonate/{username}` | Hub handler-specific | Impersonate Start | `pkg/hub/saas.go:510` | -| `GET` | `/api/saas/impersonation-status` | Hub auth | Impersonation Status | `pkg/hub/saas.go:511` | -| `POST` | `/api/saas/hives/{id}/assign` | Hub auth | Assign Hive | `pkg/hub/saas.go:512` | -| `POST` | `/api/saas/hives/{id}/reset-assignment` | Hub handler-specific | Reset Assignment | `pkg/hub/saas.go:516` | -| `GET` | `/api/saas/cluster-health` | Hub handler-specific | Cluster Health | `pkg/hub/saas.go:517` | -| `POST` | `/api/saas/admin/alert-ack` | Hub handler-specific | Alert Ack | `pkg/hub/saas.go:530` | -| `GET` | `/api/saas/admin/cluster-app-keys` | Hub handler-specific | Get Cluster App Keys | `pkg/hub/saas.go:534` | -| `PUT` | `/api/saas/admin/cluster-app-keys/{clusterID}` | Hub handler-specific | Put Cluster App Key | `pkg/hub/saas.go:535` | -| `POST` | `/api/saas/admin/hub-banner` | Hub handler-specific | Send Hub Banner | `pkg/hub/saas.go:536` | -| `DELETE` | `/api/saas/admin/hub-banner` | Hub handler-specific | Clear Hub Banner | `pkg/hub/saas.go:537` | -| `GET` | `/api/saas/admin/hub-banner` | Hub handler-specific | Get Hub Banner | `pkg/hub/saas.go:538` | -| `POST` | `/api/saas/slack/user/{username}` | Hub auth | Slack Message User | `pkg/hub/saas.go:545` | -| `POST` | `/api/saas/hives/{id}/slack` | Hub auth | Slack Message Hive Owner | `pkg/hub/saas.go:546` | -| `POST` | `/api/saas/admin/slack/broadcast` | Hub handler-specific | Slack Broadcast | `pkg/hub/saas.go:547` | -| `POST` | `/api/saas/admin/journey-snooze` | Hub handler-specific | Journey Snooze | `pkg/hub/saas.go:548` | -| `GET` | `/api/saas/admin/journey-status` | Hub handler-specific | Journey Status | `pkg/hub/saas.go:549` | -| `GET` | `/api/saas/me/country` | Hub auth | My Country Get | `pkg/hub/saas.go:391` | -| `PUT` | `/api/saas/me/country` | Hub auth | My Country Set (write blocked while impersonating) | `pkg/hub/saas.go:392` | -| `POST` | `/api/saas/lite/enroll` | Hub auth | Hive Lite Enroll | `pkg/hub/saas.go:393` | -| `PUT` | `/api/saas/hives/{id}/secondary-app` | Hub auth | Assign Secondary GitHub App | `pkg/hub/saas.go:425` | -| `POST` | `/api/saas/hives/{id}/agents/{agent}/restarts/reset` | Hub auth | Reset Agent Restart Counter | `pkg/hub/saas.go:416` | -| `GET` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch State | `pkg/hub/saas.go:439` | -| `POST` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch Toggle (audit-logged) | `pkg/hub/saas.go:440` | -| `GET` | `/api/saas/whoami` | Hub handler-specific | Session Identity (stable key + profile) | `pkg/hub/saas.go:447` | -| `GET` | `/api/saas/dibs/repos` | Hub handler-specific | Dibs Repo/Owner List (public, short shared cache) | `pkg/hub/saas.go:451` | -| `GET` | `/api/saas/hives/{id}/access-log` | Hub auth | Permission-Change Audit Log | `pkg/hub/saas.go:460` | -| `GET` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Get | `pkg/hub/saas.go:477` | -| `POST` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Set | `pkg/hub/saas.go:478` | -| `GET` | `/api/saas/admin/user-countries` | Hub admin | User Country Rollup | `pkg/hub/saas.go:487` | -| `GET` | `/api/saas/admin/auth-rollout` | Hub admin | Auth Rollout Readiness Summary | `pkg/hub/saas.go:492` | -| `GET` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Get | `pkg/hub/saas.go:493` | -| `PUT` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Update + hot reload | `pkg/hub/saas.go:494` | -| `GET` | `/api/saas/admin/key-generations` | Hub admin | Token-Crypto Key Generations | `pkg/hub/saas.go:500` | -| `POST` | `/api/saas/admin/rotate-master-key` | Hub admin | Rotate Token Master Key (double-call refused) | `pkg/hub/saas.go:501` | -| `GET` | `/api/saas/admin/advisory-diagnostics` | Hub admin | Fleet Advisory/App-State Diagnostics | `pkg/hub/saas.go:527` | +| `PUT` | `/api/saas/admin/users/{username}` | Hub handler-specific | Admin Update User | `pkg/hub/saas.go:491` | +| `DELETE` | `/api/saas/admin/users/{username}` | Hub handler-specific | Admin Delete User | `pkg/hub/saas.go:492` | +| `POST` | `/api/saas/admin/impersonate/exit` | Hub handler-specific | Impersonate Exit | `pkg/hub/saas.go:498` | +| `POST` | `/api/saas/admin/impersonate/{username}` | Hub handler-specific | Impersonate Start | `pkg/hub/saas.go:499` | +| `GET` | `/api/saas/impersonation-status` | Hub auth | Impersonation Status | `pkg/hub/saas.go:500` | +| `POST` | `/api/saas/hives/{id}/assign` | Hub auth | Assign Hive | `pkg/hub/saas.go:501` | +| `POST` | `/api/saas/hives/{id}/reset-assignment` | Hub handler-specific | Reset Assignment | `pkg/hub/saas.go:505` | +| `GET` | `/api/saas/cluster-health` | Hub handler-specific | Cluster Health | `pkg/hub/saas.go:506` | +| `POST` | `/api/saas/admin/alert-ack` | Hub handler-specific | Alert Ack | `pkg/hub/saas.go:519` | +| `GET` | `/api/saas/admin/cluster-app-keys` | Hub handler-specific | Get Cluster App Keys | `pkg/hub/saas.go:523` | +| `PUT` | `/api/saas/admin/cluster-app-keys/{clusterID}` | Hub handler-specific | Put Cluster App Key | `pkg/hub/saas.go:524` | +| `POST` | `/api/saas/admin/hub-banner` | Hub handler-specific | Send Hub Banner | `pkg/hub/saas.go:525` | +| `DELETE` | `/api/saas/admin/hub-banner` | Hub handler-specific | Clear Hub Banner | `pkg/hub/saas.go:526` | +| `GET` | `/api/saas/admin/hub-banner` | Hub handler-specific | Get Hub Banner | `pkg/hub/saas.go:527` | +| `POST` | `/api/saas/slack/user/{username}` | Hub auth | Slack Message User | `pkg/hub/saas.go:534` | +| `POST` | `/api/saas/hives/{id}/slack` | Hub auth | Slack Message Hive Owner | `pkg/hub/saas.go:535` | +| `POST` | `/api/saas/admin/slack/broadcast` | Hub handler-specific | Slack Broadcast | `pkg/hub/saas.go:536` | +| `POST` | `/api/saas/admin/journey-snooze` | Hub handler-specific | Journey Snooze | `pkg/hub/saas.go:537` | +| `GET` | `/api/saas/admin/journey-status` | Hub handler-specific | Journey Status | `pkg/hub/saas.go:538` | +| `GET` | `/api/saas/me/country` | Hub auth | My Country Get | `pkg/hub/saas.go:380` | +| `PUT` | `/api/saas/me/country` | Hub auth | My Country Set (write blocked while impersonating) | `pkg/hub/saas.go:381` | +| `POST` | `/api/saas/lite/enroll` | Hub auth | Hive Lite Enroll | `pkg/hub/saas.go:382` | +| `PUT` | `/api/saas/hives/{id}/secondary-app` | Hub auth | Assign Secondary GitHub App | `pkg/hub/saas.go:414` | +| `POST` | `/api/saas/hives/{id}/agents/{agent}/restarts/reset` | Hub auth | Reset Agent Restart Counter | `pkg/hub/saas.go:405` | +| `GET` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch State | `pkg/hub/saas.go:428` | +| `POST` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch Toggle (audit-logged) | `pkg/hub/saas.go:429` | +| `GET` | `/api/saas/whoami` | Hub handler-specific | Session Identity (stable key + profile) | `pkg/hub/saas.go:436` | +| `GET` | `/api/saas/dibs/repos` | Hub handler-specific | Dibs Repo/Owner List (public, short shared cache) | `pkg/hub/saas.go:440` | +| `GET` | `/api/saas/hives/{id}/access-log` | Hub auth | Permission-Change Audit Log | `pkg/hub/saas.go:449` | +| `GET` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Get | `pkg/hub/saas.go:466` | +| `POST` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Set | `pkg/hub/saas.go:467` | +| `GET` | `/api/saas/admin/user-countries` | Hub admin | User Country Rollup | `pkg/hub/saas.go:476` | +| `GET` | `/api/saas/admin/auth-rollout` | Hub admin | Auth Rollout Readiness Summary | `pkg/hub/saas.go:481` | +| `GET` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Get | `pkg/hub/saas.go:482` | +| `PUT` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Update + hot reload | `pkg/hub/saas.go:483` | +| `GET` | `/api/saas/admin/key-generations` | Hub admin | Token-Crypto Key Generations | `pkg/hub/saas.go:489` | +| `POST` | `/api/saas/admin/rotate-master-key` | Hub admin | Rotate Token Master Key (double-call refused) | `pkg/hub/saas.go:490` | +| `GET` | `/api/saas/admin/advisory-diagnostics` | Hub admin | Fleet Advisory/App-State Diagnostics | `pkg/hub/saas.go:516` | | `POST` | `/api/saas/hives/bulk` | Hub auth | Bulk Hive Action | `pkg/hub/saas_bulk.go:89` | | `GET` | `/api/saas/build-contains` | Hub auth | Does each hive's running build contain a PR or commit ([#18915](https://github.com/hivecommons/hive/issues/18915)): `?q=` returns `{query:{kind,pr?,commit?}, commit?, reason?, hives:[{id,name?,commit?,channel?,contains,reason?}]}` for the hives the caller can see in My Hives. `contains` is `yes`, `no` or `unknown`, computed from the hive's already-reported commit and repository ancestry: `yes` when the PR's merge commit (or the SHA) is the running commit or an ancestor, `no` when ancestry resolved and it is not (an unmerged PR is `no`), `unknown` (with `reason`) when the commit cannot be resolved or the lookup failed. Never a guess. `400` when `q` is neither a PR number nor a SHA. See [Build visibility](../release-channels.md) | `pkg/hub/build_contains.go:225` | -| `GET` | `/api/saas/me/country` | Hub auth | My Country Get | `pkg/hub/saas.go:391` | -| `PUT` | `/api/saas/me/country` | Hub auth | My Country Set (write blocked while impersonating) | `pkg/hub/saas.go:392` | -| `POST` | `/api/saas/lite/enroll` | Hub auth | Hive Lite Enroll | `pkg/hub/saas.go:393` | -| `PUT` | `/api/saas/hives/{id}/secondary-app` | Hub auth | Assign Secondary GitHub App | `pkg/hub/saas.go:425` | -| `POST` | `/api/saas/hives/{id}/agents/{agent}/restarts/reset` | Hub auth | Reset Agent Restart Counter | `pkg/hub/saas.go:416` | -| `GET` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch State | `pkg/hub/saas.go:439` | -| `POST` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch Toggle (audit-logged) | `pkg/hub/saas.go:440` | -| `GET` | `/api/saas/whoami` | Hub handler-specific | Session Identity (stable key + profile) | `pkg/hub/saas.go:447` | -| `GET` | `/api/saas/dibs/repos` | Hub handler-specific | Dibs Repo/Owner List (public, short shared cache) | `pkg/hub/saas.go:451` | -| `GET` | `/api/saas/hives/{id}/access-log` | Hub auth | Permission-Change Audit Log | `pkg/hub/saas.go:460` | -| `GET` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Get | `pkg/hub/saas.go:477` | -| `POST` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Set | `pkg/hub/saas.go:478` | -| `GET` | `/api/saas/admin/user-countries` | Hub admin | User Country Rollup | `pkg/hub/saas.go:487` | -| `GET` | `/api/saas/admin/auth-rollout` | Hub admin | Auth Rollout Readiness Summary | `pkg/hub/saas.go:492` | -| `GET` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Get | `pkg/hub/saas.go:493` | -| `PUT` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Update + hot reload | `pkg/hub/saas.go:494` | -| `GET` | `/api/saas/admin/key-generations` | Hub admin | Token-Crypto Key Generations | `pkg/hub/saas.go:500` | -| `POST` | `/api/saas/admin/rotate-master-key` | Hub admin | Rotate Token Master Key (double-call refused) | `pkg/hub/saas.go:501` | -| `GET` | `/api/saas/admin/advisory-diagnostics` | Hub admin | Fleet Advisory/App-State Diagnostics | `pkg/hub/saas.go:527` | +| `GET` | `/api/saas/me/country` | Hub auth | My Country Get | `pkg/hub/saas.go:380` | +| `PUT` | `/api/saas/me/country` | Hub auth | My Country Set (write blocked while impersonating) | `pkg/hub/saas.go:381` | +| `POST` | `/api/saas/lite/enroll` | Hub auth | Hive Lite Enroll | `pkg/hub/saas.go:382` | +| `PUT` | `/api/saas/hives/{id}/secondary-app` | Hub auth | Assign Secondary GitHub App | `pkg/hub/saas.go:414` | +| `POST` | `/api/saas/hives/{id}/agents/{agent}/restarts/reset` | Hub auth | Reset Agent Restart Counter | `pkg/hub/saas.go:405` | +| `GET` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch State | `pkg/hub/saas.go:428` | +| `POST` | `/api/saas/upgrade-pause` | Hub admin | Upgrade Kill-Switch Toggle (audit-logged) | `pkg/hub/saas.go:429` | +| `GET` | `/api/saas/whoami` | Hub handler-specific | Session Identity (stable key + profile) | `pkg/hub/saas.go:436` | +| `GET` | `/api/saas/dibs/repos` | Hub handler-specific | Dibs Repo/Owner List (public, short shared cache) | `pkg/hub/saas.go:440` | +| `GET` | `/api/saas/hives/{id}/access-log` | Hub auth | Permission-Change Audit Log | `pkg/hub/saas.go:449` | +| `GET` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Get | `pkg/hub/saas.go:466` | +| `POST` | `/api/saas/admin/scale-settings` | Hub admin | Placeholder Pool Scale Settings Set | `pkg/hub/saas.go:467` | +| `GET` | `/api/saas/admin/user-countries` | Hub admin | User Country Rollup | `pkg/hub/saas.go:476` | +| `GET` | `/api/saas/admin/auth-rollout` | Hub admin | Auth Rollout Readiness Summary | `pkg/hub/saas.go:481` | +| `GET` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Get | `pkg/hub/saas.go:482` | +| `PUT` | `/api/saas/admin/notifications` | Hub admin | Hub Notifications Update + hot reload | `pkg/hub/saas.go:483` | +| `GET` | `/api/saas/admin/key-generations` | Hub admin | Token-Crypto Key Generations | `pkg/hub/saas.go:489` | +| `POST` | `/api/saas/admin/rotate-master-key` | Hub admin | Rotate Token Master Key (double-call refused) | `pkg/hub/saas.go:490` | +| `GET` | `/api/saas/admin/advisory-diagnostics` | Hub admin | Fleet Advisory/App-State Diagnostics | `pkg/hub/saas.go:516` | diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 1e143399da..a3223de629 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -28,13 +28,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Hub auth | Hub Open Router Models | `pkg/hub/openrouter.go:28` | | `GET` | `/api/openrouter/credit` | Hub auth | Hub Open Router Credit | `pkg/hub/openrouter.go:29` | | `GET` | `/openrouter/callback` | Hub handler-specific | Hub Open Router Callback | `pkg/hub/openrouter.go:30` | -| `GET` | `/dashboard` | Hub handler-specific | Dashboard | `pkg/hub/saas.go:369` | -| `GET` | `/access-denied` | Hub handler-specific | Access Denied | `pkg/hub/saas.go:370` | -| `GET` | `/api/hub/clusters` | Hub auth | List Clusters | `pkg/hub/saas.go:531` | -| `GET` | `/api/hub/image-pulls` | Hub auth | Per-Release Image Pull Series | `pkg/hub/saas.go:377` | +| `GET` | `/dashboard` | Hub handler-specific | Dashboard | `pkg/hub/saas.go:361` | +| `GET` | `/access-denied` | Hub handler-specific | Access Denied | `pkg/hub/saas.go:362` | +| `GET` | `/api/hub/clusters` | Hub auth | List Clusters | `pkg/hub/saas.go:520` | +| `GET` | `/api/hub/image-pulls` | Hub auth | Per-Release Image Pull Series | `pkg/hub/saas.go:369` | | `POST` | `/api/benchmarks/ingest` | Per-hive heartbeat bearer | Spoke push target for anonymized [benchmark records](../benchmarks.md): body `{hive_id, records[]}`; the hub recomputes the hive hash from the authenticated id, rejects records whose `source.hive_id` differs (`401` bad bearer, `403` unregistered hive, `400` malformed), merges accepted records by id into `/data/benchmarks//.json` and returns `202 {accepted, rejected, files}` | `pkg/hub/benchmarks.go` | | `GET` | `/api/hub/benchmarks` | Public | Benchmark publisher status: `last_ingest_at`, `last_publish_at`, `last_publish_files`, `last_error`, `pending_files`, `hive_count`, `record_count` and per-hive-hash `hives{}` counts; the hub commits pending month files hourly to `hivecommons/benchmarks` (`HIVE_BENCHMARKS_REPO`) via its App identity | `pkg/hub/benchmarks.go` | -| `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:522` | +| `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:511` | | `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1829` | | `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1830` | | `GET` | `/activity` | Signed-in user | Fleet activity page ([#16063](https://github.com/hivecommons/hive/issues/16063)): read-only, data-free shell that polls `/api/hub/activity` every 15 s with `If-None-Match`. No session → `307` to `/login`; blocked user → `403`. Own Content-Security-Policy (scripts and styles from `'self'` only, `script-src-attr`/`style-src-attr` `'none'`), `Cache-Control: no-cache` + content `ETag`. See [Hub Fleet activity page](../hub-fleet-activity.md) | `pkg/hub/activity_page.go` | diff --git a/src/docs/env-vars.md b/src/docs/env-vars.md index 1a3def9f04..e28acd1b66 100644 --- a/src/docs/env-vars.md +++ b/src/docs/env-vars.md @@ -93,6 +93,7 @@ behavior. [Maintenance limitations](#keeping-this-reference-current) still apply | `HIVE_HUB_LEGACY_COOKIE_DOMAIN` | No | none | Optional transition-only hub SSO cookie domain to expire alongside the active cookie domain while accepting any carried `hive_hub_user` cookie value during a host migration. Writes still target the domain derived from `HIVE_HUB_PUBLIC_URL`; unset disables the extra legacy-domain cleanup. | | `HIVE_HUB_SECRET` | Required for spokes registered to a protected hub; optional for a standalone hub with `/data/saas/hub-secret.key` | `/data/saas/hub-secret.key` on the hub when present; no fallback for spoke heartbeat auth | Bearer secret for spoke heartbeats and hub/spoke SaaS APIs. Self-hosted (`byo-`) hives registered through self-service never receive it: they hold only their own `HIVE_HEARTBEAT_KEY`, and the hub never tries `HIVE_HUB_SECRET` or anything derived from it for a `byo-` ID. | | `HIVE_HUB_SELFSERVICE_REGISTRATION` | No | off | Enables the self-service registration API (`/api/hub/selfservice/*`) that lets a signed-in user register a hive they run themselves under the reserved `byo---` ID namespace, after proving `permissions.admin` on every listed repo with their own GitHub token ([#18060](https://github.com/hivecommons/hive/issues/18060)). Accepts `1/true/yes/on`. When off, every route but `GET /api/hub/selfservice/status` answers `404` and the status reports `enabled: false`. Read per request; no restart needed. | +| `HIVE_HUB_CUSTOMERS_SHARE_ENABLED` | No | off | Enables the hub's signed-in profile-sharing page and API for per-person, per-hive consent. Accepts `1/true/yes/on`. This phase sends no profile data to hives. See [Customer profile sharing](hub-deployment.md#customer-profile-sharing). | | `HIVE_HUB_MAIL_TOKEN` | Only on a hub that routes mail from `hive-mx` | none | Bearer token `hive-mx` presents on `GET /api/mail/hosts` and `POST /api/mail/inbound` ([#18395](https://github.com/hivecommons/hive/issues/18395)); the same value as the `hive-mx` Secret. Unset: both endpoints answer `404`. Read per request. Secret. | | `HIVE_HUB_MAIL_MAX_BODY_BYTES` | No | `50331648` | Largest delivery `POST /api/mail/inbound` accepts from a `hive-mx` that sends routing headers (48 MiB, this route only; [#18564](https://github.com/hivecommons/hive/issues/18564)). Without routing headers the cap stays 8 MiB. | | `HIVE_HUB_MAIL_CHUNK_BYTES` | No | `786432` | Piece size when the hub relays a large mail-in delivery to the spoke (768 KiB, under the 1 MiB ingress default); clamped to 64 KiB to 8 MiB. | diff --git a/src/docs/hub-deployment.md b/src/docs/hub-deployment.md index e58264fd5e..434ef38f74 100644 --- a/src/docs/hub-deployment.md +++ b/src/docs/hub-deployment.md @@ -88,6 +88,20 @@ env: Without `HIVE_HUB_SECRET`, a protected hub returns `401 unauthorized`, the spoke logs `hub heartbeat rejected status=401`, and the hub shows the hive offline. This matches the gotcha in `manual-provisioning.md`. +### Customer profile sharing + +`HIVE_HUB_CUSTOMERS_SHARE_ENABLED` is off by default. Set it to `1`, `true`, +`yes`, or `on` in the hub environment to enable **Profile sharing** in Fleet +and on hive cards where the signed-in person holds a grant. The hub dashboard's +operator settings show the effective state. With the switch off, the page and +its API return `404`; stored choices are not deleted. + +People can enter or clear their real name, organization, and country, then +confirm or withdraw their own selections separately for each hive. Legacy, +administrator-entered, and inferred values are not eligible for sharing. A +material disclosure change requires reconfirmation. This phase records consent +on the hub only and does not send any profile fields to hives. + ### Reserved `byo-` hive IDs (credential fence) Hive IDs that start with `byo-` are reserved for hives that their owners run and register themselves ([#18060](https://github.com/hivecommons/hive/issues/18060)). A hub lists such a hive as directory metadata only, so its heartbeat response never carries hub-held credentials or management actions, whatever key the spoke authenticated with. The hub withholds these fields: the GitHub App config (including cluster, secondary and webhook relay keys), the pending gateway, the claimed project config, the cluster ID, the authorized-user list, visibility, upgrade and branch-switch instructions, the upgrade announcement and policy, spoke restarts, agent-restart resets, fleet-breaker instructions, and self-experiment flags. Display-only data such as admin banners still flows. When the fence withholds a field, the hub logs `heartbeat: credential fence withheld fields from self-service hive` with the field names, never the values. Do not give an operator-provisioned hive a `byo-` ID. diff --git a/src/pkg/hub/assets/dashboard.html b/src/pkg/hub/assets/dashboard.html index 18b17a27c8..3c85fef141 100644 --- a/src/pkg/hub/assets/dashboard.html +++ b/src/pkg/hub/assets/dashboard.html @@ -187,6 +187,10 @@ .cluster-health-message.info { color: var(--muted); background: var(--surface); border: 1px solid var(--border); } .cluster-health-message.warn { color: var(--amber); background: var(--surface); border: 1px solid var(--amber); } + .customers-share-setting { padding: var(--sp-5); margin-bottom: var(--sp-6); border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); font-size: var(--fs-base); } + .customers-share-setting h3 { font-size: var(--fs-base); margin-bottom: var(--sp-2); } + .customers-share-setting p:last-child { font-size: var(--fs-sm); color: var(--muted); margin-top: var(--sp-2); } + /* ── Hive search + facets ── The facet panel is a CLICK-TOGGLED left tray, collapsed by default so the dashboard is uncluttered until the operator asks for filters. Collapsed it @@ -835,6 +839,7 @@

My Hives

Hive instances you own or have access to

+

👋 New to Hive? Read the Getting Started Guide before diving in.

📊 See how models perform across the fleet — merge rate, CI first-try and estimated cost per PR, from real hive output. Open the benchmarks ↗

@@ -1086,6 +1091,11 @@

+
+

Customers profile sharing

+

In force: Unknown · Default: Off

+

Set HIVE_HUB_CUSTOMERS_SHARE_ENABLED on the hub to enable the personal profile and consent page. The environment is authoritative; this setting cannot be changed here. No profile details are sent to hives in this release.

+
Per-cluster limits
@@ -4717,6 +4727,7 @@

Profile sharing'); if (_isAdmin && h.provStatus === 'available' && !h.assigning) menuItems.push('
Assign / Claim
'); /* Reset assignment: escape hatch for a placeholder wedged at assigned && !claim_delivered (assignedUnclaimed) — its spoke never @@ -11660,6 +11680,8 @@

+ + + + + Profile sharing — Hive Hub + + + + + + + +
+

Profile sharing

+

Manage your own Hub details and choose what may be shared with each hive’s Customers area.

+ + +
+

Your details

+

Each field is saved separately. A value you didn’t enter yourself isn’t eligible for sharing unless you type and save it here. Clearing a value leaves that field empty; it does not change your selections for any hive.

+

Loading your details…

+
+
+ +
+

Hives

+
+

What you’re agreeing to

+

No profile details are sent to any hive in this release. You can record your choices now for future syncs.

+

For each hive you choose, only the fields you select may be shared: your real name, organization, or country. Only non-empty values you entered about yourself are eligible. That hive’s owner and anyone with Customers access there can view and export the shared values. When a future sync matches you to a confirmed customer in that hive, the Hub learns about that customer relationship.

+

This feature never sends notes, Slack IDs, email, affiliation, provider-supplied profile details, or anything an administrator entered or the Hub inferred. Information already visible to hive owners through existing access lists is unaffected by these choices.

+

Withdrawal stops sharing immediately on the Hub. Once syncing is available, the hive removes the imported values at its next sync. Withdrawal cannot undo what someone already saw, copied, or exported.

+

Boxes always start unchecked; any previous selection is shown separately. Confirming replaces the entire selection for that hive. Leave nothing selected and use Withdraw consent to remove the entire selection.

+
+

Loading your hives…

+ +
+
+
+ © Copyright Hive Commons Series of LF Projects, LLC
+ For website terms of use, trademark policy and other project policies please see https://lfprojects.org/policies/. +
+ + + + + diff --git a/src/pkg/hub/background_pollers.go b/src/pkg/hub/background_pollers.go index 0822db2313..21f45783c7 100644 --- a/src/pkg/hub/background_pollers.go +++ b/src/pkg/hub/background_pollers.go @@ -56,6 +56,7 @@ func (s *HubServer) StartBackgroundPollers(ctx context.Context) <-chan struct{} // Self-service (byo-) registrations past HIVE_HUB_SELFSERVICE_EXPIRY with // no accepted heartbeat are revoked and dropped from the registry (#18146). start(s.startSelfServiceExpirySweep) + start(s.startCustomerConsentSweep) s.githubActivityMu.Lock() s.githubActivityCtx = ctx feed := s.githubActivityFeed diff --git a/src/pkg/hub/customer_consent.go b/src/pkg/hub/customer_consent.go new file mode 100644 index 0000000000..345fccb21b --- /dev/null +++ b/src/pkg/hub/customer_consent.go @@ -0,0 +1,227 @@ +package hub + +import ( + "encoding/json" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +const ( + customersShareEnv = "HIVE_HUB_CUSTOMERS_SHARE_ENABLED" + // Bump for a material disclosure change. The page submits the version it + // displayed, not a version fetched after the person read the disclosure. + customerConsentTextVersion = "1" + maxCustomerConsentBody = 4096 +) + +func customersShareEnabled() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv(customersShareEnv))) { + case "1", "true", "yes", "on": + return true + } + return false +} + +func (s *HubServer) customerShareSession(r *http.Request) string { + for _, value := range hubSessionCookieValues(r) { + if id, ok := s.verifyHubUserCookie(value); ok && loadSaaSUser(id) != nil { + return id + } + } + return "" +} + +func (s *HubServer) requireCustomerSharing(next http.HandlerFunc) http.HandlerFunc { + auth := s.requireAuth(next) + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if !customersShareEnabled() { + http.NotFound(w, r) + return + } + // requireAuth also accepts API bearer tokens. These routes must use + // the person's signed browser session, with no bearer fallback. + if r.Header.Get("Authorization") != "" { + writeJSONError(w, http.StatusUnauthorized, "hub session required") + return + } + if s.customerShareSession(r) == "" { + if r.URL.Path == "/profile-share" { + http.Redirect(w, r, "/login?redirect="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) + return + } + writeJSONError(w, http.StatusUnauthorized, "hub session required") + return + } + if _, err := r.Cookie(impersonateCookieName); err == nil { + if _, _, impersonating := s.resolveIdentity(r); impersonating { + writeJSONError(w, http.StatusForbidden, "exit impersonation to use profile sharing") + return + } + } + auth(w, r) + } +} + +func (s *HubServer) registerCustomerSharingRoutes() { + s.mux.HandleFunc("GET /profile-share", s.requireCustomerSharing(s.handleProfileSharePage)) + s.mux.HandleFunc("GET /api/saas/me/profile-share", s.requireCustomerSharing(s.handleMyProfileShare)) + s.mux.HandleFunc("PUT /api/saas/me/profile-share", s.requireCustomerSharing(s.handleMyProfileShare)) + s.mux.HandleFunc("GET /api/saas/me/profile-share/consents", s.requireCustomerSharing(s.handleListCustomerConsents)) + s.mux.HandleFunc("POST /api/saas/me/profile-share/consents/{id}", s.requireCustomerSharing(s.handleChangeCustomerConsent)) + s.mux.HandleFunc("DELETE /api/saas/me/profile-share/consents/{id}", s.requireCustomerSharing(s.handleChangeCustomerConsent)) +} + +type customerConsentHive struct { + HiveID string `json:"hive_id"` + Name string `json:"name"` + Consent *customerConsent `json:"consent,omitempty"` +} + +func (s *HubServer) customerConsentHiveName(id string) string { + if h := s.registryEntryCopy(id); h != nil { + if h.ProjectName != "" { + return h.ProjectName + } + if h.Name != "" { + return h.Name + } + } + return id +} + +func (s *HubServer) handleListCustomerConsents(w http.ResponseWriter, r *http.Request) { + customerConsentMu.Lock() + defer customerConsentMu.Unlock() + user := loadSaaSUser(s.customerShareSession(r)) + if user == nil || user.Blocked { + writeJSONError(w, http.StatusForbidden, "account unavailable") + return + } + path, err := customerConsentPath(user) + if err != nil { + s.customerConsentError(w, err) + return + } + records, err := readCustomerConsents(path) + if err != nil { + s.customerConsentError(w, err) + return + } + now := time.Now() + hives := make([]customerConsentHive, 0, len(user.Hives)) + for id, role := range user.Hives { + if id == "" || role == "" { + continue + } + hive := customerConsentHive{HiveID: id, Name: s.customerConsentHiveName(id)} + if c, ok := records[id]; ok && !c.discardable(now) { + hive.Consent = &c + } + hives = append(hives, hive) + } + sort.Slice(hives, func(i, j int) bool { return hives[i].HiveID < hives[j].HiveID }) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(struct { + TextVersion string `json:"text_version"` + Hives []customerConsentHive `json:"hives"` + }{customerConsentTextVersion, hives}) +} + +func (s *HubServer) handleChangeCustomerConsent(w http.ResponseWriter, r *http.Request) { + hiveID := r.PathValue("id") + var body struct { + TextVersion string `json:"text_version"` + Fields customerConsentFields `json:"fields"` + } + withdrawing := r.Method == http.MethodDelete + if !withdrawing { + d := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxCustomerConsentBody)) + d.DisallowUnknownFields() + if d.Decode(&body) != nil || d.Decode(new(json.RawMessage)) != io.EOF { + writeJSONError(w, http.StatusBadRequest, "invalid consent JSON") + return + } + if body.TextVersion != customerConsentTextVersion { + writeJSONError(w, http.StatusConflict, "disclosure version changed; reload and confirm again") + return + } + if body.Fields == (customerConsentFields{}) { + writeJSONError(w, http.StatusBadRequest, "select at least one field or withdraw consent") + return + } + } + + customerConsentMu.Lock() + defer customerConsentMu.Unlock() + user := loadSaaSUser(s.customerShareSession(r)) + if user == nil || user.Blocked { + writeJSONError(w, http.StatusForbidden, "account unavailable") + return + } + // loadSaaSUser already drops expired grants. A hub admin's fleet view or + // public visibility is not a grant. Withdrawal remains safe after loss + // of access: it can only remove the session person's existing consent. + if !withdrawing && user.Hives[hiveID] == "" { + writeJSONError(w, http.StatusForbidden, "you do not hold a grant on this hive") + return + } + path, err := customerConsentPath(user) + if err != nil { + s.customerConsentError(w, err) + return + } + records, err := readCustomerConsents(path) + if err != nil { + s.customerConsentError(w, err) + return + } + + now := time.Now().UTC() + consent, exists := records[hiveID] + action := "grant" + auditFields := body.Fields + if withdrawing { + if !exists || consent.WithdrawnAt != nil { + w.WriteHeader(http.StatusNoContent) + return + } + action, auditFields = "withdrawal", consent.Fields + consent.Fields = customerConsentFields{} + consent.UpdatedAt, consent.WithdrawnAt = now, &now + if consent.discardable(now) { + delete(records, hiveID) + } else { + records[hiveID] = consent + } + } else { + if !exists || consent.discardable(now) { + consent = customerConsent{ + Person: strings.TrimSuffix(filepath.Base(path), ".json"), + HiveID: hiveID, GrantedAt: now, + } + } else if consent.WithdrawnAt == nil { + action = "change" + } + consent.Fields, consent.TextVersion = body.Fields, body.TextVersion + consent.UpdatedAt, consent.WithdrawnAt = now, nil + records[hiveID] = consent + } + if err := saveCustomerConsents(path, records); err != nil { + s.customerConsentError(w, err) + return + } + s.logger.Info("audit: customer consent "+action, "person", consent.Person, "hive", hiveID, "fields", auditFields.names()) + w.WriteHeader(http.StatusNoContent) +} + +func (s *HubServer) customerConsentError(w http.ResponseWriter, err error) { + s.logger.Warn("customer consent store failed", "error", err) + writeJSONError(w, http.StatusInternalServerError, "could not access consent records") +} diff --git a/src/pkg/hub/customer_consent_store.go b/src/pkg/hub/customer_consent_store.go new file mode 100644 index 0000000000..3a82357c2e --- /dev/null +++ b/src/pkg/hub/customer_consent_store.go @@ -0,0 +1,178 @@ +package hub + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +const ( + customerConsentRetention = 90 * 24 * time.Hour + customerConsentSweepInterval = 24 * time.Hour +) + +// Serialize consent mutations with each other and with user deletion. This is +// a per-person document: a change for one hive must not drop another hive's +// record, and a concurrent consent write must not recreate a deleted account's +// records. The hub has a single writer process for its SaaS files. +var customerConsentMu sync.Mutex + +type customerConsentFields struct { + RealName bool `json:"real_name"` + Organization bool `json:"organization"` + Country bool `json:"country"` +} + +func (f customerConsentFields) names() []string { + var names []string + if f.RealName { + names = append(names, "real_name") + } + if f.Organization { + names = append(names, "organization") + } + if f.Country { + names = append(names, "country") + } + return names +} + +type customerConsent struct { + Person string `json:"person"` + HiveID string `json:"hive_id"` + Fields customerConsentFields `json:"fields"` + TextVersion string `json:"text_version"` + GrantedAt time.Time `json:"granted_at"` + UpdatedAt time.Time `json:"updated_at"` + WithdrawnAt *time.Time `json:"withdrawn_at,omitempty"` + // Only the delivery path (phase 2) may stamp these times. + FirstDeliveredAt *time.Time `json:"first_delivered_at,omitempty"` + LastDeliveredAt *time.Time `json:"last_delivered_at,omitempty"` +} + +func (c customerConsent) discardable(now time.Time) bool { + return c.WithdrawnAt != nil && (c.FirstDeliveredAt == nil && c.LastDeliveredAt == nil || + !now.Before(c.WithdrawnAt.Add(customerConsentRetention))) +} + +func customerConsentDir() string { + return filepath.Join(filepath.Dir(saasUsersDir), "consents") +} + +func customerConsentPath(u *SaaSUser) (string, error) { + userPath, err := saveSaaSUserPath(u) + if err != nil { + return "", err + } + return filepath.Join(customerConsentDir(), filepath.Base(userPath)), nil +} + +func readCustomerConsents(path string) (map[string]customerConsent, error) { + records := make(map[string]customerConsent) + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return records, nil + } + if err != nil { + return nil, err + } + if err := json.Unmarshal(data, &records); err != nil { + return nil, err + } + if records == nil { + return nil, errors.New("invalid null consent document") + } + return records, nil +} + +func removeCustomerConsents(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func saveCustomerConsents(path string, records map[string]customerConsent) error { + if len(records) == 0 { + return removeCustomerConsents(path) + } + data, err := json.MarshalIndent(records, "", " ") + if err != nil { + return err + } + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".consent-*") // mode 0600 + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + _, writeErr := tmp.Write(data) + closeErr := tmp.Close() + if err := errors.Join(writeErr, closeErr); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} + +func pruneCustomerConsents(path string, now time.Time) error { + customerConsentMu.Lock() + defer customerConsentMu.Unlock() + records, err := readCustomerConsents(path) + if err != nil { + return err + } + before := len(records) + for id, consent := range records { + if consent.discardable(now) { + delete(records, id) + } + } + if before == len(records) { + return nil + } + return saveCustomerConsents(path, records) +} + +// Retention still applies when the sharing switch is turned off. +func (s *HubServer) startCustomerConsentSweep(ctx context.Context) { + sweep := func(now time.Time) { + dir := customerConsentDir() + entries, err := os.ReadDir(dir) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + s.logger.Warn("customer consent sweep: list failed", "error", err) + } + return + } + for _, entry := range entries { + if ctx.Err() != nil { + return + } + if !entry.Type().IsRegular() || !strings.HasSuffix(entry.Name(), ".json") { + continue + } + if err := pruneCustomerConsents(filepath.Join(dir, entry.Name()), now); err != nil { + s.logger.Warn("customer consent sweep: prune failed", "error", err) + } + } + } + sweep(time.Now()) + ticker := time.NewTicker(customerConsentSweepInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case now := <-ticker.C: + sweep(now) + } + } +} diff --git a/src/pkg/hub/customer_consent_test.go b/src/pkg/hub/customer_consent_test.go new file mode 100644 index 0000000000..c83c14b98f --- /dev/null +++ b/src/pkg/hub/customer_consent_test.go @@ -0,0 +1,160 @@ +package hub + +import ( + "bytes" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +const consentTestAPI = "/api/saas/me/profile-share/consents" + +func TestCustomerConsentRoutes(t *testing.T) { + defer helperSetupTempDirs(t)() + t.Setenv(customersShareEnv, "") + t.Setenv("HIVE_HUB_PUBLIC_URL", "https://hub.example.com") + s := newHandlerHub() + s.mux = http.NewServeMux() + s.registerCustomerSharingRoutes() + s.mux.HandleFunc("DELETE /admin/{username}", s.requireAdmin(s.handleAdminDeleteUser)) + var logs bytes.Buffer + s.logger = slog.New(slog.NewTextHandler(&logs, nil)) + mkUser(t, hubAdminUsername) + mkUser(t, "bob") + alice := &SaaSUser{ + GitHubUsername: "alice", FullName: "Alice Private", + Hives: map[string]string{"one": "viewer", "two": "viewer", "expired": "viewer"}, + HiveExpiry: map[string]string{"expired": "2020-01-01T00:00:00Z"}, + } + if err := saveSaaSUser(alice); err != nil { + t.Fatal(err) + } + request := func(method, path, body, login, origin string, impersonate bool) *httptest.ResponseRecorder { + t.Helper() + r := reqWithUser(method, path, body, login) + if login == "" { + r.Header.Del("Cookie") + } + if origin != "" { + r.Header.Set("Origin", origin) + } + if impersonate { + r.AddCookie(&http.Cookie{Name: impersonateCookieName, Value: mintImpersonateCookieValueForGeneration(s.currentGenerations(), login, "alice", time.Now())}) + } + w := httptest.NewRecorder() + s.mux.ServeHTTP(w, r) + return w + } + const hubOrigin = "https://hub.example.com" + expect := func(w *httptest.ResponseRecorder, want int) { + t.Helper() + if w.Code != want { + t.Fatalf("status %d, want %d: %s", w.Code, want, w.Body) + } + } + for _, path := range []string{"/profile-share", "/api/saas/me/profile-share", consentTestAPI} { + expect(request("GET", path, "", "alice", "", false), 404) + } + t.Setenv(customersShareEnv, "true") + expect(request("GET", "/profile-share", "", "", "", false), 303) + expect(request("GET", consentTestAPI, "", "", "", false), 401) + expect(request("GET", consentTestAPI, "", hubAdminUsername, "", true), 403) + page := request("GET", "/profile-share", "", "alice", "", false) + expect(page, 200) + if !strings.Contains(page.Body.String(), `data-text-version="`+customerConsentTextVersion+`"`) || page.Header().Get("Cache-Control") != "no-store" { + t.Fatal("page did not bind the displayed disclosure version or disable caching") + } + + grant := `{"text_version":"` + customerConsentTextVersion + `","fields":{"real_name":true}}` + post := func(hive, body, login string, status int) { + t.Helper() + expect(request("POST", consentTestAPI+"/"+hive, body, login, hubOrigin, false), status) + } + post("one", strings.Replace(grant, `"fields"`, `"person":"bob","fields"`, 1), "alice", 400) + post("one", strings.Replace(grant, customerConsentTextVersion, "old", 1), "alice", 409) + post("one", strings.Replace(grant, "true", "false", 1), "alice", 400) + post("one", grant, "bob", 403) + post("one", grant, hubAdminUsername, 403) + post("expired", grant, "alice", 403) + expect(request("POST", consentTestAPI+"/one", grant, "alice", "https://other.example.com", false), 403) + expect(request("POST", consentTestAPI+"/one", grant, hubAdminUsername, hubOrigin, true), 403) + post("one", grant, "alice", 204) + post("two", grant, "alice", 204) + post("one", strings.Replace(grant, "real_name", "country", 1), "alice", 204) + + path, err := customerConsentPath(alice) + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if mode := info.Mode().Perm(); mode != 0o600 { + t.Fatalf("consent permissions = %o", mode) + } + read := func(login string) []customerConsentHive { + t.Helper() + w := request("GET", consentTestAPI, "", login, "", false) + expect(w, 200) + var body struct{ Hives []customerConsentHive } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + return body.Hives + } + if rows := read("bob"); len(rows) != 0 { + t.Fatalf("another session saw consent rows: %+v", rows) + } + if rows := read("alice"); len(rows) != 2 || rows[0].Consent == nil || rows[1].Consent == nil || + rows[0].Consent.Fields != (customerConsentFields{Country: true}) || rows[0].Consent.Person != "alice" || + rows[1].Consent.Fields != (customerConsentFields{RealName: true}) { + t.Fatalf("expected independent replacement and expired grant filtering, got %+v", rows) + } + expect(request("DELETE", consentTestAPI+"/one", "", "alice", hubOrigin, false), 204) + if rows := read("alice"); len(rows) != 2 || rows[0].Consent != nil || rows[1].Consent == nil { + t.Fatalf("withdrawal must delete only the undelivered hive record: %+v", rows) + } + if audit := logs.String(); strings.Count(audit, "audit: customer consent") != 4 || strings.Contains(audit, "Alice Private") { + t.Fatalf("unexpected consent audit: %s", audit) + } + t.Setenv(customersShareEnv, "off") + expect(request("DELETE", "/admin/alice", "", hubAdminUsername, hubOrigin, false), 200) + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) || loadSaaSUser("alice") != nil { + t.Fatalf("user deletion must remove profile and all consents even when sharing is off: %v", err) + } +} + +func TestCustomerConsentRetention(t *testing.T) { + defer helperSetupTempDirs(t)() + now := time.Now().UTC() + old := now.Add(-customerConsentRetention) + path, err := customerConsentPath(&SaaSUser{GitHubUsername: "alice"}) + if err != nil { + t.Fatal(err) + } + if err := saveCustomerConsents(path, map[string]customerConsent{ + "undelivered": {WithdrawnAt: &now}, + "expired": {WithdrawnAt: &old, FirstDeliveredAt: &old}, + "retained": {WithdrawnAt: &now, FirstDeliveredAt: &old}, + "active": {FirstDeliveredAt: &old}, + }); err != nil { + t.Fatal(err) + } + if err := pruneCustomerConsents(path, now); err != nil { + t.Fatal(err) + } + records, err := readCustomerConsents(path) + if err != nil { + t.Fatal(err) + } + if len(records) != 2 || records["active"].FirstDeliveredAt == nil || records["retained"].WithdrawnAt == nil { + t.Fatalf("unexpected retention result: %+v", records) + } +} diff --git a/src/pkg/hub/profile_share.go b/src/pkg/hub/profile_share.go new file mode 100644 index 0000000000..cecfb36261 --- /dev/null +++ b/src/pkg/hub/profile_share.go @@ -0,0 +1,133 @@ +package hub + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" +) + +// customerProfileMu serializes profile edits, provision approvals, and user +// deletion across their read-modify-save operations. Never take the consent +// lock while holding this lock; deletion takes the consent lock first. +var customerProfileMu sync.Mutex + +type profileShareField struct { + Value string `json:"value"` + Source string `json:"source"` +} + +type profileShareResponse struct { + RealName profileShareField `json:"real_name"` + Organization profileShareField `json:"organization"` + Country profileShareField `json:"country"` +} + +type profileSharePatch struct { + name, organization, country *string +} + +// Decode exact, non-repeating field names so neither null nor an ambiguous +// duplicate can be mistaken for an explicit choice. Empty strings are clears. +func decodeProfileSharePatch(w http.ResponseWriter, r *http.Request) (profileSharePatch, error) { + var patch profileSharePatch + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUpdateUserBodyBytes)) + if token, err := dec.Token(); err != nil || token != json.Delim('{') { + return patch, errors.New("profile update must be a JSON object") + } + for dec.More() { + token, err := dec.Token() + if err != nil { + return patch, errors.New("invalid JSON profile field") + } + var field **string + switch token { + case "real_name": + field = &patch.name + case "organization": + field = &patch.organization + case "country": + field = &patch.country + default: + return patch, errors.New("profile update allows only real_name, organization, and country") + } + if *field != nil { + return patch, fmt.Errorf("%s must not be repeated", token) + } + if err := dec.Decode(field); err != nil || *field == nil { + return patch, fmt.Errorf("%s must be a string (send \"\" to clear it)", token) + } + } + if token, err := dec.Token(); err != nil || token != json.Delim('}') { + return patch, errors.New("invalid JSON profile update") + } + if _, err := dec.Token(); err != io.EOF { + return patch, errors.New("profile update must contain exactly one JSON object") + } + if patch.country != nil { + raw := strings.TrimSpace(*patch.country) + *patch.country = normalizeCountryCode(raw) + if raw != "" && *patch.country == "" { + return patch, errors.New("country must be an ISO 3166-1 alpha-2 code (two letters), or \"\" to clear it") + } + } + return patch, nil +} + +// handleMyProfileShare is registered behind the session-only sharing gate. +func (s *HubServer) handleMyProfileShare(w http.ResponseWriter, r *http.Request) { + username := s.customerShareSession(r) + if username == "" { + writeJSONError(w, http.StatusUnauthorized, "not authenticated") + return + } + + var patch profileSharePatch + if r.Method == http.MethodPut { + var err error + patch, err = decodeProfileSharePatch(w, r) + if err != nil { + writeJSONError(w, http.StatusBadRequest, err.Error()) + return + } + customerProfileMu.Lock() + defer customerProfileMu.Unlock() + } + user := loadSaaSUser(username) + if user == nil { + writeJSONError(w, http.StatusUnauthorized, "unknown user — please log in again") + return + } + if user.Blocked { + writeJSONError(w, http.StatusForbidden, "account blocked") + return + } + if patch.name != nil { + user.FullName = truncateRunes(strings.TrimSpace(*patch.name), maxContactNameLen) + user.FullNameSource = countrySourceUser + } + if patch.organization != nil { + user.Company = truncateRunes(strings.TrimSpace(*patch.organization), maxContactCompanyLen) + user.CompanySource = countrySourceUser + } + if patch.country != nil { + setUserCountry(user, *patch.country, countrySourceUser) + } + if patch != (profileSharePatch{}) { + if err := saveSaaSUser(user); err != nil { + s.logger.Warn("profile share: save failed", "user", username, "error", err) + writeJSONError(w, http.StatusInternalServerError, "could not save profile") + return + } + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(profileShareResponse{ + RealName: profileShareField{Value: user.FullName, Source: user.FullNameSource}, + Organization: profileShareField{Value: user.Company, Source: user.CompanySource}, + Country: profileShareField{Value: normalizeCountryCode(user.Country), Source: effectiveCountrySource(user)}, + }) +} diff --git a/src/pkg/hub/profile_share_page.go b/src/pkg/hub/profile_share_page.go new file mode 100644 index 0000000000..d6fc80d8dd --- /dev/null +++ b/src/pkg/hub/profile_share_page.go @@ -0,0 +1,19 @@ +package hub + +import ( + _ "embed" + "io" + "net/http" + "strings" +) + +//go:embed assets/profile-share.html +var profileSharePageTemplate string + +var profileSharePageHTML = strings.Replace(profileSharePageTemplate, "{{CONSENT_TEXT_VERSION}}", customerConsentTextVersion, 1) + +func (s *HubServer) handleProfileSharePage(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'") + _, _ = io.WriteString(w, profileSharePageHTML) +} diff --git a/src/pkg/hub/profile_share_test.go b/src/pkg/hub/profile_share_test.go new file mode 100644 index 0000000000..b6b90cfa5a --- /dev/null +++ b/src/pkg/hub/profile_share_test.go @@ -0,0 +1,156 @@ +package hub + +import ( + "bytes" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func requestMyProfileShare(s *HubServer, method, user, body string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + s.handleMyProfileShare(rec, reqWithUser(method, "/api/saas/me/profile-share", body, user)) + return rec +} + +func TestMyProfileShareProvenance(t *testing.T) { + s := adminAssignHub(t) + u := &SaaSUser{GitHubUsername: "ada", Hives: map[string]string{}, FullName: "Legacy", Country: "FR", DisplayName: "Provider Name", Affiliation: "Public affiliation"} + if err := saveSaaSUser(u); err != nil { + t.Fatal(err) + } + assertProfile := func(method, request, want string) { + t.Helper() + rec := requestMyProfileShare(s, method, "ada", request) + if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != want { + t.Fatalf("%s %s returned %d %s; want 200 %s", method, request, rec.Code, rec.Body.String(), want) + } + } + assertProfile(http.MethodGet, "", `{"real_name":{"value":"Legacy","source":""},"organization":{"value":"","source":""},"country":{"value":"FR","source":"inferred"}}`) + + if rec := adminPut(s, "ada", `{"full_name":" Admin Name ","company":" Admin Org "}`, hubAdminUsername); rec.Code != http.StatusOK { + t.Fatalf("admin update returned %d %s", rec.Code, rec.Body.String()) + } + assertProfile(http.MethodGet, "", `{"real_name":{"value":"Admin Name","source":"admin"},"organization":{"value":"Admin Org","source":"admin"},"country":{"value":"FR","source":"inferred"}}`) + assertProfile(http.MethodPut, `{"real_name":" Ada ","country":" gb "}`, `{"real_name":{"value":"Ada","source":"user"},"organization":{"value":"Admin Org","source":"admin"},"country":{"value":"GB","source":"user"}}`) + const cleared = `{"real_name":{"value":"","source":"user"},"organization":{"value":"","source":"user"},"country":{"value":"","source":"user"}}` + assertProfile(http.MethodPut, `{"real_name":" ","organization":"","country":""}`, cleared) + if rec := adminPut(s, "ada", `{"full_name":"Replaced","company":"Replaced","country":"US","saas_quota":7}`, hubAdminUsername); rec.Code != http.StatusOK { + t.Fatalf("admin update returned %d %s", rec.Code, rec.Body.String()) + } + assertProfile(http.MethodGet, "", cleared) + u = loadSaaSUser("ada") + if u.SaaSQuota != 7 || !u.CountrySetByUser || u.DisplayName != "Provider Name" || u.Affiliation != "Public affiliation" { + t.Fatalf("unexpected saved record: %+v", u) + } +} + +func TestMyProfileShareValidationAndCaps(t *testing.T) { + s := countryTestHub(t) + mkUser(t, "ada") + for _, body := range []string{ + `null`, `[]`, `{`, `{} {}`, `{"real_name":null}`, `{"organization":123}`, `{"country":"USA","real_name":"Ada"}`, + `{"owner":"someone","real_name":"Ada"}`, `{"person":"someone"}`, `{"Real_Name":"Ada"}`, + `{"real_name":"Ada","real_name":"Other"}`, + `{"organization":"` + strings.Repeat("x", maxUpdateUserBodyBytes) + `"}`, + } { + rec := requestMyProfileShare(s, http.MethodPut, "ada", body) + var reply struct { + Error string `json:"error"` + } + if rec.Code != http.StatusBadRequest || json.Unmarshal(rec.Body.Bytes(), &reply) != nil || reply.Error == "" { + t.Fatalf("invalid profile update returned %d %s; want a JSON 400 error", rec.Code, rec.Body.String()) + } + } + u := loadSaaSUser("ada") + if u.FullNameSource != "" || u.CompanySource != "" || u.CountrySource != "" { + t.Fatalf("invalid update changed profile: %+v", u) + } + name := strings.Repeat("é", maxContactNameLen) + org := strings.Repeat("語", maxContactCompanyLen) + body, err := json.Marshal(map[string]string{"real_name": " " + name + "X ", "organization": " " + org + "X "}) + if err != nil { + t.Fatal(err) + } + if rec := requestMyProfileShare(s, http.MethodPut, "ada", string(body)); rec.Code != http.StatusOK { + t.Fatalf("profile update returned %d %s", rec.Code, rec.Body.String()) + } + u = loadSaaSUser("ada") + if u.FullName != name || u.Company != org || u.FullNameSource != countrySourceUser || u.CompanySource != countrySourceUser { + t.Fatalf("profile fields not capped and attributed correctly: %+v", u) + } +} + +func TestProfileShareLegacyFileRoundTrip(t *testing.T) { + s := countryTestHub(t) + const legacy = `{"github_username":"ada","created_at":"2020-01-01T00:00:00Z","last_login":"2020-01-02T00:00:00Z","hives":{},"saas_quota":1,"blocked":false,"full_name":"Ada","slack_id":"U123","notes":"private","company":"Legacy Org","country":"GB","country_set_by_user":true,"login_count":1}` + var raw bytes.Buffer + if err := json.Indent(&raw, []byte(legacy), "", " "); err != nil { + t.Fatal(err) + } + path := filepath.Join(saasUsersDir, "ada.json") + if err := os.MkdirAll(saasUsersDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + u := loadSaaSUser("ada") + if u == nil || u.FullNameSource != "" || u.CompanySource != "" || u.CountrySource != "" { + t.Fatalf("legacy sources backfilled: %+v", u) + } + if err := saveSaaSUser(u); err != nil { + t.Fatal(err) + } + stored, err := os.ReadFile(path) + if err != nil || !bytes.Equal(stored, raw.Bytes()) { + t.Fatalf("legacy file changed: %v\ngot %s\nwant %s", err, stored, raw.Bytes()) + } + const want = `{"real_name":{"value":"Ada","source":""},"organization":{"value":"Legacy Org","source":""},"country":{"value":"GB","source":"user"}}` + if rec := requestMyProfileShare(s, http.MethodGet, "ada", ""); rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != want { + t.Fatalf("legacy profile returned %d %s; want 200 %s", rec.Code, rec.Body.String(), want) + } +} + +func TestProfileShareProvisionApproval(t *testing.T) { + t.Cleanup(helperSetupTempDirs(t)) + mkUser(t, hubAdminUsername) + mkUser(t, "ada") + s := &HubServer{logger: slog.Default(), hubSecret: testHubSecret, saveCh: make(chan struct{}, 1), clusters: map[string]ClusterConfig{"hive-oke": *dynamicCluster()}} + if err := saveProvisionRequest(&ProvisionRequest{ + Username: "ada", Org: "repo-owner", Repos: "repo", PrimaryRepo: "repo", ACMMLevel: 2, AuthMethod: "public", + Status: provisionStatusPending, FullName: " Ada Lovelace ", Country: "gb", + }); err != nil { + t.Fatal(err) + } + if err := saveSaaSHive(&SaaSHive{ID: "ph1", Owner: hubAdminUsername, Status: statusAvailable, ClusterID: "hive-oke"}); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + s.handleApproveProvision(rec, setPathValue(reqWithUser(http.MethodPost, "/approve-prov", "", hubAdminUsername), "username", "ada")) + if rec.Code != http.StatusOK { + t.Fatalf("approval returned %d %s", rec.Code, rec.Body.String()) + } + u := loadSaaSUser("ada") + if u == nil || u.FullName != "Ada Lovelace" || u.FullNameSource != countrySourceUser || u.Country != "GB" || u.CountrySource != countrySourceUser || u.Company != "" || u.CompanySource != "" { + t.Fatalf("approval did not attribute only the supplied contact fields: %+v", u) + } +} + +func TestProfileShareApprovalPreservesExplicitClears(t *testing.T) { + u := &SaaSUser{FullNameSource: countrySourceUser, CountrySource: countrySourceUser, CountrySetByUser: true} + applyRequestContactToUser(u, &ProvisionRequest{FullName: "Earlier", Country: "GB"}) + if u.FullName != "" || u.Country != "" || u.FullNameSource != countrySourceUser || u.CountrySource != countrySourceUser { + t.Fatalf("approval overwrote a user clear: %+v", u) + } + u = &SaaSUser{} + applyRequestContactToUser(u, &ProvisionRequest{FullName: " "}) + if u.FullNameSource != "" { + t.Fatalf("approval attributed blank request name: %+v", u) + } +} diff --git a/src/pkg/hub/saas.go b/src/pkg/hub/saas.go index c75236d0cf..44baa88388 100644 --- a/src/pkg/hub/saas.go +++ b/src/pkg/hub/saas.go @@ -182,32 +182,24 @@ type SaaSUser struct { // DisplayName is the PROVIDER-ASSERTED human name from the OIDC name claim // (or userinfo), refreshed on every completed login. Distinct from FullName, - // which is ADMIN-entered CRM text and must never be clobbered by a login. + // which is contact text that must never be clobbered by a login. // Display only — the identity key stays provider:sub. omitempty so existing // records round-trip byte-identical until the user's next login enriches // them (backfill-by-login, no migration). DisplayName string `json:"display_name,omitempty"` - // Contact/CRM fields. Admin-maintained free text used to reach a hub user - // outside GitHub (and to remember what was said last time). All three are - // omitempty so the thousands of existing user records already on the PVC - // stay byte-identical until an admin actually fills one in — a record - // without them round-trips through load/save unchanged. - // - // These are operator-entered free text rendered into the dashboard, so - // every render path must escape them and every write path must cap them - // (see maxContactNameLen / maxContactSlackIDLen / maxContactNotesLen). + // Contact/CRM fields are free text, never asserted by a login. Renderers + // must escape them, and writers must cap them (maxContact*Len). FullName string `json:"full_name,omitempty"` SlackID string `json:"slack_id,omitempty"` Notes string `json:"notes,omitempty"` - // Company is ADMIN-entered CRM free text — the user's company/organization. - // Like FullName/SlackID/Notes it is operator-maintained (never asserted by a - // login) and is deliberately NOT collected in the hive request/provision - // form; the operator fills it in manually from the admin Users table. Same - // escaping + length-cap discipline as the other contact fields - // (maxContactCompanyLen); omitempty so existing records round-trip - // byte-identical until an admin sets it. + // Company is the user's company or organization, not the repository owner + // selected in the hive request form. Company string `json:"company,omitempty"` + // Provenance records who supplied each value, including explicit clears: + // "admin" or "user". Legacy contact values have no source; do not backfill. + FullNameSource string `json:"full_name_source,omitempty"` + CompanySource string `json:"company_source,omitempty"` // Country is an OPTIONAL ISO 3166-1 alpha-2 code (uppercase, e.g. "GB"), // rendered as a small flag beside the user's avatar. Two sources, in @@ -270,7 +262,7 @@ type SaaSUser struct { // opened to fix. // // Precedence, strongest first: user > admin > inferred > unset. See - // countryProvenanceRank and mayOverwriteCountry in user_country.go, which + // profileProvenanceRank and mayOverwriteCountry in user_country.go, which // are the single arbiters — no caller compares these strings by hand. // // BACKWARD COMPATIBILITY. Records written before this field exists carry @@ -379,12 +371,9 @@ func (s *HubServer) registerSaaSRoutes() { // non-admin legitimately sees their OWN hives' usage; the handler scopes // fleet-wide data to admins itself. s.mux.HandleFunc("GET /api/saas/usage", s.requireAuth(s.handleUsage)) - // Self-service country: the ONE field a non-admin may write on their own - // user record. requireAuth, not requireAdmin — that is the entire point, - // since every other SaaSUser write is admin-gated and the wizard is a - // one-time surface. The handler resolves the acting user from the SESSION - // and the body carries no identity, so this cannot reach anyone else's - // record. See handleMyCountry in user_country.go. + // Self-service country for the acting session user. The body carries no + // identity, so it cannot select another user's record. See handleMyCountry + // in user_country.go. // // PUT with a JSON body rather than a code in the path: country is personal // data and a URL would put it in access logs, Referer headers and history. @@ -548,6 +537,7 @@ func (s *HubServer) registerSaaSRoutes() { s.mux.HandleFunc("POST /api/saas/admin/journey-snooze", s.requireAdmin(s.handleJourneySnooze)) s.mux.HandleFunc("GET /api/saas/admin/journey-status", s.requireAdmin(s.handleJourneyStatus)) s.registerBuildContainsRoutes() + s.registerCustomerSharingRoutes() } func pendingAgentRestartResetsForHeartbeat(hiveID string) []string { diff --git a/src/pkg/hub/saas_hives_api.go b/src/pkg/hub/saas_hives_api.go index db8f298764..6cfe261bad 100644 --- a/src/pkg/hub/saas_hives_api.go +++ b/src/pkg/hub/saas_hives_api.go @@ -590,6 +590,18 @@ func serverTimingHeader(metrics ...serverTimingMetric) string { func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values) ([]byte, error) { user := ensureSaaSUser(username) + shareEnabled := customersShareEnabled() + var shareHiveIDs []string + if shareEnabled { + // Capture actual grants before the fleet's owner normalization can + // add missing grants. Admin visibility alone is not a personal grant. + for id, role := range user.Hives { + if role != "" { + shareHiveIDs = append(shareHiveIDs, id) + } + } + sort.Strings(shareHiveIDs) + } s.mu.Lock() offlineEvents := s.markStaleHives() @@ -777,6 +789,7 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values } isAdmin := isHubAdmin(username) + var ownerRepairs []string for _, h := range allHives { if role, ok := user.Hives[h.ID]; ok { // A stale/demoted stored role must not hide owner-gated UI (the @@ -786,7 +799,7 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values // OWN hives (#4081). if role != "owner" && canonicalEqual(h.Owner, username) { role = "owner" - user.Hives[h.ID] = "owner" // heal the demoted stored role + ownerRepairs = append(ownerRepairs, h.ID) } if isAdmin && role != "owner" { role = "owner" @@ -800,7 +813,7 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values entry := MyHiveEntry{RegistryEntry: h, Role: "owner", AutoUpgrade: autoUpgradeMap[h.ID], AutoUpgradeMode: autoUpgradeModeMap[h.ID]} enrichFromSaaSMeta(&entry) result = append(result, entry) - user.Hives[h.ID] = "owner" + ownerRepairs = append(ownerRepairs, h.ID) continue } if isAdmin { @@ -826,7 +839,7 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values // role (#4081). if role != "owner" && canonicalEqual(sh.Owner, username) { role = "owner" - user.Hives[hiveID] = "owner" + ownerRepairs = append(ownerRepairs, hiveID) } entry := MyHiveEntry{ RegistryEntry: RegistryEntry{ @@ -852,7 +865,9 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values for _, sh := range listSaaSHives() { if (canonicalEqual(sh.Owner, username) || isAdmin) && !seen[sh.ID] { - user.Hives[sh.ID] = "owner" + if canonicalEqual(sh.Owner, username) { + ownerRepairs = append(ownerRepairs, sh.ID) + } entry := MyHiveEntry{ RegistryEntry: RegistryEntry{ ID: sh.ID, @@ -874,10 +889,19 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values } } - if len(user.Hives) > 0 { - if err := saveSaaSUser(user); err != nil { - s.logger.Warn("handleMyHives: save failed", "user", username, "error", err) + if len(ownerRepairs) > 0 { + // Fleet refreshes independently of profile edits. Persist only the + // repaired grants against a fresh record, not the old profile snapshot. + customerProfileMu.Lock() + if current := loadSaaSUser(username); current != nil { + for _, id := range ownerRepairs { + current.Hives[id] = roleOwner + } + if err := saveSaaSUser(current); err != nil { + s.logger.Warn("handleMyHives: owner repair failed", "user", username, "error", err) + } } + customerProfileMu.Unlock() } // Read the user roster ONCE for the access hover rather than per row — @@ -1286,6 +1310,12 @@ func (s *HubServer) buildMyHivesResponse(username string, queryValues url.Values // the existence of a hive they have no access to. "alerts": s.fleetAlerts(result, alertFleet), } + if shareEnabled { + resp["customersShareEnabled"] = true + if len(shareHiveIDs) > 0 { + resp["profileShareHiveIDs"] = shareHiveIDs + } + } myReq := loadProvisionRequest(username) if myReq != nil { diff --git a/src/pkg/hub/saas_provisioning.go b/src/pkg/hub/saas_provisioning.go index ae46e7d3a7..0617641dbd 100644 --- a/src/pkg/hub/saas_provisioning.go +++ b/src/pkg/hub/saas_provisioning.go @@ -271,9 +271,9 @@ func enrichProvisionRequests(requests []ProvisionRequest) []ProvisionRequest { // messaging shipped with no user having a slack_id, settable only by hand one // user at a time; approval is the natural point of capture. // -// It only ever FILLS A BLANK. An admin who has already curated these fields (or -// a user who corrected them later) outranks whatever was typed into a request -// form, and a re-approval must not silently revert that. +// It fills blank name and Slack fields without undoing an explicit name clear. +// A wizard country can replace an admin assignment or inference, but not a +// user choice already on the record: approval may lag behind a profile edit. // // Nil-safe on both sides: it runs on the approval path beside other work that // can legitimately leave either side absent, and must not panic there. @@ -281,22 +281,18 @@ func applyRequestContactToUser(user *SaaSUser, pr *ProvisionRequest) { if user == nil || pr == nil { return } - if user.FullName == "" && pr.FullName != "" { - user.FullName = truncateRunes(strings.TrimSpace(pr.FullName), maxContactNameLen) + if name := strings.TrimSpace(pr.FullName); name != "" && user.FullName == "" && + profileProvenanceRank(user.FullNameSource) < profileProvenanceRank(countrySourceUser) { + user.FullName = truncateRunes(name, maxContactNameLen) + user.FullNameSource = countrySourceUser } if user.SlackID == "" && pr.SlackID != "" { user.SlackID = truncateRunes(strings.TrimSpace(pr.SlackID), maxContactSlackIDLen) } - // The explicit pick outranks anything Accept-Language inferred at login, so - // unlike the two fields above this one overwrites a value already on the - // record — but only when the request actually carries a choice. Re-normalize - // rather than trusting the stored request: it may predate the validation. - if code := normalizeCountryCode(pr.Country); code != "" { - // The wizard pick is a deliberate statement BY THE USER, so it carries - // the same provenance the self-service endpoint stamps. Without this, - // an approval would leave the record looking "inferred", and the - // priority rule would hold only by the accident of the value being - // non-empty. + // A request's repository owner (Org) is not the requester's company. + // Re-normalize the country rather than trusting older stored requests. + if code := normalizeCountryCode(pr.Country); code != "" && + profileProvenanceRank(effectiveCountrySource(user)) < profileProvenanceRank(countrySourceUser) { setUserCountry(user, code, countrySourceUser) } } @@ -792,6 +788,7 @@ func (s *HubServer) handleApproveProvision(w http.ResponseWriter, r *http.Reques // Manage Access — only the admin who provisioned the placeholder did — and // on a heartbeat-only cluster (the heartbeat-only cluster) that stale list is what gets // delivered to the spoke. + customerProfileMu.Lock() user := loadSaaSUser(targetUsername) if user == nil { user = ensureSaaSUser(targetUsername) @@ -805,6 +802,7 @@ func (s *HubServer) handleApproveProvision(w http.ResponseWriter, r *http.Reques if err := saveSaaSUser(user); err != nil { s.logger.Warn("assigned placeholder but failed to grant owner access", "user", targetUsername, "hive", hiveID, "error", err) } + customerProfileMu.Unlock() // Mark the request fulfilled, recording who approved it and which hive the // requester actually received — that pairing is the whole point of the diff --git a/src/pkg/hub/saas_users_admin.go b/src/pkg/hub/saas_users_admin.go index c63260a0dc..9b79f668d6 100644 --- a/src/pkg/hub/saas_users_admin.go +++ b/src/pkg/hub/saas_users_admin.go @@ -500,11 +500,6 @@ func (s *HubServer) handleImpersonationStatus(w http.ResponseWriter, r *http.Req // Registered behind requireAdmin; this handler does no auth of its own. func (s *HubServer) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request) { username := r.PathValue("username") - u := loadSaaSUser(username) - if u == nil { - writeJSONError(w, http.StatusNotFound, "user not found") - return - } // Free-text fields land on a PVC, so bound the body before decoding it. r.Body = http.MaxBytesReader(w, r.Body, maxUpdateUserBodyBytes) var body struct { @@ -529,6 +524,13 @@ func (s *HubServer) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request writeJSONError(w, http.StatusForbidden, "root hub admins can only be changed by root hub admins") return } + customerProfileMu.Lock() + defer customerProfileMu.Unlock() + u := loadSaaSUser(username) + if u == nil { + writeJSONError(w, http.StatusNotFound, "user not found") + return + } // Whether the country branch below actually APPLIED, which is not the same // as the key being present: a stronger user-chosen value declines the edit. // Tracked so the audit line records what changed rather than what was asked. @@ -541,8 +543,10 @@ func (s *HubServer) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request } // Trim before capping so trailing whitespace does not eat the budget, and // so clearing a field to spaces stores "" (and drops out via omitempty). - if body.FullName != nil { + nameEdited := body.FullName != nil && mayOverwriteProfileSource(u.FullNameSource, countrySourceAdmin) + if nameEdited { u.FullName = truncateRunes(strings.TrimSpace(*body.FullName), maxContactNameLen) + u.FullNameSource = countrySourceAdmin } if body.SlackID != nil { u.SlackID = truncateRunes(strings.TrimSpace(*body.SlackID), maxContactSlackIDLen) @@ -550,8 +554,10 @@ func (s *HubServer) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request if body.Notes != nil { u.Notes = truncateRunes(strings.TrimSpace(*body.Notes), maxContactNotesLen) } - if body.Company != nil { + companyEdited := body.Company != nil && mayOverwriteProfileSource(u.CompanySource, countrySourceAdmin) + if companyEdited { u.Company = truncateRunes(strings.TrimSpace(*body.Company), maxContactCompanyLen) + u.CompanySource = countrySourceAdmin } if body.Country != nil { raw := strings.TrimSpace(*body.Country) @@ -611,7 +617,7 @@ func (s *HubServer) handleAdminUpdateUser(w http.ResponseWriter, r *http.Request // Logged only when the write actually applied, so the line never claims a // change that mayOverwriteCountry declined. attrs := []any{"target", username, "quota", u.SaaSQuota, "blocked", u.Blocked, - "contactEdited", body.FullName != nil || body.SlackID != nil || body.Notes != nil || body.Company != nil} + "contactEdited", nameEdited || body.SlackID != nil || body.Notes != nil || companyEdited} if countryEdited { attrs = append(attrs, "countryAssigned", u.Country, "countrySource", u.CountrySource) } @@ -635,6 +641,10 @@ func (s *HubServer) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request writeJSONError(w, http.StatusBadRequest, "invalid username") return } + customerConsentMu.Lock() + defer customerConsentMu.Unlock() + customerProfileMu.Lock() + defer customerProfileMu.Unlock() u := loadSaaSUser(username) if u == nil { writeJSONError(w, http.StatusNotFound, "user not found") @@ -651,12 +661,26 @@ func (s *HubServer) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request len(ownedHives), strings.Join(ownedHives, ", "))) return } - path := filepath.Join(saasUsersDir, username+".json") - if err := os.Remove(path); err != nil && !os.IsNotExist(err) { - s.logger.Warn("admin delete user: remove failed", "target", username, "error", err) - writeJSONError(w, http.StatusInternalServerError, "failed to delete user record") + // Remove consents first. If storage fails, leave the user in place so a + // subsequent deletion can retry; never report deletion with consents left. + consentPath, err := customerConsentPath(u) + if err == nil { + err = removeCustomerConsents(consentPath) + } + if err != nil { + s.logger.Warn("admin delete user: consent removal failed", "target", username, "error", err) + writeJSONError(w, http.StatusInternalServerError, "failed to delete user's consent records") return } + // Delete both canonical and legacy representations; otherwise a leftover + // fallback would become the live account as soon as the first file is gone. + for _, path := range saaSUserFilePaths(username) { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + s.logger.Warn("admin delete user: remove failed", "target", username, "error", err) + writeJSONError(w, http.StatusInternalServerError, "failed to delete user record") + return + } + } s.logger.Info("audit: admin deleted user", "target", username, "by", s.getAuthUser(r)) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]string{"status": "deleted"}) diff --git a/src/pkg/hub/scale_settings.go b/src/pkg/hub/scale_settings.go index d5864d8478..ecd8bc398c 100644 --- a/src/pkg/hub/scale_settings.go +++ b/src/pkg/hub/scale_settings.go @@ -187,6 +187,7 @@ func (s *HubServer) handleGetScaleSettings(w http.ResponseWriter, r *http.Reques // Reported in seconds to match the input's unit, so the card shows // the same number the operator typed. 0 = debouncing disabled. "upgrade_debounce_seconds": int(autoUpgradeDebounceInterval() / time.Second), + "customers_share_enabled": customersShareEnabled(), }, Clusters: rows, Defaults: map[string]int{ diff --git a/src/pkg/hub/static/my-hives.html b/src/pkg/hub/static/my-hives.html index 42b6fb4ae0..009d4f4840 100644 --- a/src/pkg/hub/static/my-hives.html +++ b/src/pkg/hub/static/my-hives.html @@ -215,6 +215,8 @@ /* Header summary + controls. */ .summary { font-size: 13px; } .allclear { color: var(--status-ok); font-weight: 600; } + .profile-share-link { color: var(--brand); text-decoration: underline; } + .spoke .profile-share-link { margin-left: var(--sp-3); white-space: nowrap; font-size: var(--fs-sm); } .controls { margin-left: auto; display: flex; gap: 14px; font-size: var(--fs-sm); color: var(--text-muted); } .controls label { cursor: pointer; user-select: none; } @media (max-width: 900px) { @@ -266,6 +268,7 @@

Fleet health

+ a hive is a problem when it has no recent output for its ACMM level (L2 advisory · L3–L5 authored writes: issues/PRs created, comments, reviews · L6 merged) with work still queued, or a precondition is broken (agents cannot work / GitHub App auth / budget exhausted / repo Issues tab disabled). Absence of output a level does not produce is never a fault. The ⎘ attach chip copies the kubectl+tmux command to jump into the hive's spoke pod for root-causing. @@ -931,17 +934,21 @@

Fleet health

var tr = document.createElement("tr"); tr.className = "spoke health-" + health + (open ? " open" : ""); + var profileLink = personalProfileLinksAllowed && profileShareHiveIDs.has(h.id) + ? 'Profile sharing' + : ""; tr.innerHTML = '

' + - '' + + '' + '' + '' + '' + '' + ''; tb.appendChild(tr); - var link = tr.querySelector(".hive-link"); - if (link) link.addEventListener("click", function (e) { e.stopPropagation(); }); + tr.querySelectorAll(".hive-link, .profile-share-link").forEach(function (link) { + link.addEventListener("click", function (e) { e.stopPropagation(); }); + }); // The remediation "open" link must navigate, not toggle the row expand. var remLink = tr.querySelector(".rem-link"); if (remLink) remLink.addEventListener("click", function (e) { e.stopPropagation(); }); @@ -1045,6 +1052,12 @@

Fleet health

} var lastHives = []; +var personalProfileLinksAllowed = false; +var profileShareEnabled = false; +var profileShareHiveIDs = new Set(); +function updateProfileShareLink() { + document.getElementById("profile-share-link").hidden = !personalProfileLinksAllowed || !profileShareEnabled; +} function load() { fetch("/api/saas/my-hives", { credentials: "same-origin", headers: { "Accept": "application/json" } }) .then(function (r) { @@ -1055,7 +1068,13 @@

Fleet health

if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); }) - .then(function (d) { lastHives = d.hives || []; renderHives(lastHives); }) + .then(function (d) { + lastHives = d.hives || []; + profileShareEnabled = d.customersShareEnabled === true; + profileShareHiveIDs = new Set(profileShareEnabled ? (d.profileShareHiveIDs || []) : []); + updateProfileShareLink(); + renderHives(lastHives); + }) .catch(function (e) { if (e && e.message === "redirecting to login") return; var c = document.getElementById("statusCell"); @@ -1107,6 +1126,9 @@

Fleet health

.then(function (r) { return r.json(); }) .then(function (d) { if (!d || !d.authenticated) return; + personalProfileLinksAllowed = !d.impersonating; + updateProfileShareLink(); + if (personalProfileLinksAllowed && profileShareHiveIDs.size) renderHives(lastHives); var wrap = document.getElementById("nav-avatar-wrap"); var img = document.getElementById("nav-avatar"); if (!wrap || !img) return; diff --git a/src/pkg/hub/static/profile-share.css b/src/pkg/hub/static/profile-share.css new file mode 100644 index 0000000000..8a6d2c0901 --- /dev/null +++ b/src/pkg/hub/static/profile-share.css @@ -0,0 +1,62 @@ +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { + margin: 0; + min-width: 320px; + background: var(--surface-1); + color: var(--text); + font: var(--fs-base)/1.55 var(--font-ui); +} +a { color: var(--brand); } +.site-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--sp-5); + padding: var(--sp-5) clamp(1rem, 4vw, 4.5rem); + border-bottom: 1px solid var(--line); + background: var(--surface); +} +.brand { font-size: var(--fs-lg); font-weight: 800; text-decoration: none; } +.site-header nav { display: flex; gap: var(--sp-5); } +main { width: min(100%, 64rem); margin: auto; padding: var(--sp-8) var(--sp-6); } +h1, h2, h3 { margin: 0 0 var(--sp-3); line-height: 1.2; } +p { margin: 0 0 var(--sp-4); } +section { margin-top: var(--sp-8); } +.muted { color: var(--text-muted); } +.profile-fields, .consent-hives { display: grid; gap: var(--sp-5); } +.profile-fields { grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); } +.panel { + border: 1px solid var(--line); + border-radius: var(--r); + background: var(--surface); + padding: var(--sp-6); + overflow-wrap: anywhere; +} +.disclosure, .consent { max-width: 52rem; } +.disclosure p:last-child, .status:last-child { margin-bottom: 0; } +.status { margin-top: var(--sp-4); } +.status:empty { display: none; } +.status[data-error] { color: var(--status-error); } +.current { margin-bottom: var(--sp-1); font-weight: 600; white-space: pre-wrap; } +fieldset { margin: 0; padding: 0; border: 0; min-width: 0; } +.detail label span { display: block; } +.detail input { + display: block; + width: 100%; + margin-top: var(--sp-2); + padding: var(--sp-3); + border: 1px solid var(--line); + border-radius: var(--r); + background: var(--surface-1); + color: var(--text); + font: inherit; +} +.choices, .actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-5); } +.choices { margin-top: var(--sp-2); } +.choices label { display: inline-flex; align-items: center; gap: var(--sp-2); cursor: pointer; } +.choices input { accent-color: var(--brand); } +.actions { margin-top: var(--sp-4); } +:focus-visible { outline: 2px solid var(--brand); outline-offset: 3px; } +footer { border-top: 1px solid var(--line); padding: var(--sp-6); text-align: center; font-size: var(--fs-sm); } diff --git a/src/pkg/hub/static/profile-share.js b/src/pkg/hub/static/profile-share.js new file mode 100644 index 0000000000..869db0bc01 --- /dev/null +++ b/src/pkg/hub/static/profile-share.js @@ -0,0 +1,212 @@ +"use strict"; + +const profileURL = "/api/saas/me/profile-share"; +const consentsURL = profileURL + "/consents"; +const fields = [ + { key: "real_name", label: "Real name" }, + { key: "organization", label: "Organization" }, + { key: "country", label: "Country" }, +]; +const textVersion = document.body.dataset.textVersion; +const profileList = document.getElementById("profile-fields"); +const hiveList = document.getElementById("consent-hives"); +const profileStatus = document.getElementById("profile-status"); +const consentsStatus = document.getElementById("consents-status"); +let versionMatches = false; + +function showStatus(node, message, error = false) { + node.toggleAttribute("data-error", error); + node.textContent = message; +} + +async function request(url, method = "GET", body) { + const headers = { Accept: "application/json" }; + if (body !== undefined) headers["Content-Type"] = "application/json"; + const response = await fetch(url, { + method, headers, credentials: "same-origin", cache: "no-store", + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => null); + throw new Error(data?.error || `Request failed (HTTP ${response.status})`); + } + return response.status === 204 ? null : response.json(); +} + +function renderProfileField(field, saved) { + const form = document.getElementById("profile-field-template").content.firstElementChild.cloneNode(true); + const input = form.querySelector("input"); + const clear = form.querySelector(".clear"); + const controls = form.querySelector("fieldset"); + const status = form.querySelector(".status"); + form.dataset.field = field.key; + form.querySelector("h3").textContent = field.label; + form.querySelector("label span").textContent = "Enter your " + field.label.toLowerCase(); + if (field.key === "country") { + input.placeholder = "Two-letter code, e.g. US"; + input.setAttribute("aria-label", "Enter your two-letter country code"); + } + + function showValue({ value, source }) { + form.querySelector(".current").textContent = value || "Not set"; + let provenance = ""; + if (value) { + switch (source) { + case "user": provenance = "You entered this."; break; + case "admin": provenance = "An administrator entered this."; break; + case "inferred": provenance = "Guessed from your browser."; break; + default: provenance = "Source not recorded."; + } + if (source !== "user") provenance += " Not eligible for sharing until you enter it yourself."; + } + form.querySelector(".source").textContent = provenance; + clear.disabled = !value; + } + + async function save(value) { + const focused = document.activeElement; + controls.disabled = true; + showStatus(status, "Saving…"); + try { + const profile = await request(profileURL, "PUT", { [field.key]: value }); + showValue(profile[field.key]); + input.value = ""; + showStatus(status, value ? `${field.label} saved.` : `${field.label} cleared.`); + } catch (error) { + showStatus(status, `Could not save: ${error.message}`, true); + } finally { + controls.disabled = false; + if (document.activeElement === document.body) (focused === clear && clear.disabled ? input : focused).focus(); + } + } + + form.addEventListener("submit", event => { + event.preventDefault(); + const value = input.value.trim(); + if (value) save(value); + else showStatus(status, "Enter a value to save or use Clear saved value.", true); + }); + clear.addEventListener("click", () => save("")); + showValue(saved); + return form; +} + +async function loadProfile() { + try { + const profile = await request(profileURL); + profileList.replaceChildren(...fields.map(field => renderProfileField(field, profile[field.key]))); + showStatus(profileStatus, ""); + } catch (error) { + showStatus(profileStatus, `Could not load your details: ${error.message}. Reload to try again.`, true); + } +} + +function setConsentBusy(busy) { + hiveList.querySelectorAll("fieldset, button[type=submit]").forEach(node => { + node.disabled = busy || !versionMatches; + }); + hiveList.querySelectorAll(".withdraw").forEach(node => { node.disabled = busy; }); +} + +function scrollToHive(id) { + const form = Array.from(hiveList.children).find(node => node.dataset.hiveId === id); + if (!form) return false; + form.querySelector("h3").focus(); + return true; +} + +function renderConsentHive(hive) { + const form = document.getElementById("consent-hive-template").content.firstElementChild.cloneNode(true); + const name = hive.name || hive.hive_id; + const consent = hive.consent; + const status = form.querySelector(".status"); + const choices = form.querySelector(".choices"); + const withdraw = form.querySelector(".withdraw"); + const recorded = consent && !consent.withdrawn_at; + form.dataset.hiveId = hive.hive_id; + form.querySelector("h3").textContent = name; + form.setAttribute("aria-label", `Profile sharing for ${name}`); + withdraw.hidden = !recorded; + let selection = "No consent recorded."; + if (consent?.withdrawn_at) selection = "Consent withdrawn."; + else if (recorded) { + const labels = fields.filter(field => consent.fields[field.key]).map(field => field.label).join(", "); + const suspended = !versionMatches || consent.text_version !== textVersion; + selection = suspended + ? `Suspended — reconfirm under the current disclosure. Previous selection: ${labels}.` + : `Recorded selection: ${labels}.`; + } + form.querySelector(".saved-selection").textContent = selection; + + for (const field of fields) { + const label = document.createElement("label"); + const input = document.createElement("input"); + input.type = "checkbox"; + input.name = field.key; + label.append(input, document.createTextNode(field.label)); + choices.append(label); + } + + async function updateConsent(method, body) { + const focused = document.activeElement; + setConsentBusy(true); + showStatus(status, method === "POST" ? "Saving…" : "Withdrawing…"); + try { + await request(consentsURL + "/" + encodeURIComponent(hive.hive_id), method, body); + } catch (error) { + showStatus(status, `Could not ${method === "POST" ? "save consent" : "withdraw consent"}: ${error.message}`, true); + setConsentBusy(false); + if (document.activeElement === document.body) focused.focus(); + return; + } + const done = method === "POST" ? `Selection saved for ${name}.` : `Consent withdrawn for ${name}.`; + form.reset(); + showStatus(status, ""); + try { + renderConsentList(await request(consentsURL), done); + if (document.activeElement === document.body) scrollToHive(hive.hive_id); + } catch (error) { + showStatus(consentsStatus, `${done} Could not refresh the hive list: ${error.message}. Reload before making more changes.`, true); + } + } + + form.addEventListener("submit", event => { + event.preventDefault(); + if (!versionMatches) return; + const selected = Object.fromEntries(Array.from(choices.querySelectorAll("input"), input => [input.name, input.checked])); + if (!Object.values(selected).some(Boolean)) { + showStatus(status, "Select at least one field to confirm. To remove a previous selection, use Withdraw consent.", true); + return; + } + updateConsent("POST", { text_version: textVersion, fields: selected }); + }); + withdraw.addEventListener("click", () => updateConsent("DELETE")); + return form; +} + +function renderConsentList(data, message = "") { + versionMatches = data.text_version === textVersion; + const hives = data.hives || []; + hiveList.replaceChildren(...hives.map(renderConsentHive)); + setConsentBusy(false); + if (!versionMatches) { + showStatus(consentsStatus, `${message ? message + " " : ""}The disclosure has changed. Reload the page to review it before confirming a selection.`, true); + } else { + showStatus(consentsStatus, message || (hives.length ? "" : "You don’t have a current access grant for any hive.")); + } +} + +async function loadConsents() { + try { + renderConsentList(await request(consentsURL)); + const target = new URLSearchParams(location.search).get("hive"); + if (target && !scrollToHive(target) && versionMatches) { + showStatus(consentsStatus, "That hive isn’t in your current access grants.", true); + } + } catch (error) { + showStatus(consentsStatus, `Could not load your hives: ${error.message}. Reload to try again.`, true); + } +} + +loadProfile(); +loadConsents(); diff --git a/src/pkg/hub/user_country.go b/src/pkg/hub/user_country.go index 634aa3d8f8..432a26d747 100644 --- a/src/pkg/hub/user_country.go +++ b/src/pkg/hub/user_country.go @@ -40,12 +40,12 @@ const ( countrySourceUser = "user" ) -// countryProvenanceRank maps a source to its strength. Higher wins. +// profileProvenanceRank maps a source to its strength. Higher wins. // // Ranks rather than a chain of if-statements at each call site, so "user beats // admin beats inference" is asserted in exactly one place and a future source // slots in by picking a number instead of by auditing every comparison. -func countryProvenanceRank(source string) int { +func profileProvenanceRank(source string) int { switch source { case countrySourceUser: return 3 @@ -99,7 +99,11 @@ func effectiveCountrySource(user *SaaSUser) string { // stronger existing claim blocks the write — which is the whole precedence rule // (user > admin > inferred > unset) in one line. func mayOverwriteCountry(user *SaaSUser, source string) bool { - return countryProvenanceRank(source) >= countryProvenanceRank(effectiveCountrySource(user)) + return mayOverwriteProfileSource(effectiveCountrySource(user), source) +} + +func mayOverwriteProfileSource(current, incoming string) bool { + return profileProvenanceRank(incoming) >= profileProvenanceRank(current) } // setUserCountry is the ONE place a country and its provenance are written @@ -315,13 +319,12 @@ func (s *HubServer) handleMyCountry(w http.ResponseWriter, r *http.Request) { writeJSONError(w, http.StatusUnauthorized, "not authenticated") return } - user := loadSaaSUser(username) - if user == nil { - writeJSONError(w, http.StatusUnauthorized, "unknown user — please log in again") - return - } - if r.Method == http.MethodGet { + user := loadSaaSUser(username) + if user == nil { + writeJSONError(w, http.StatusUnauthorized, "unknown user — please log in again") + return + } writeMyCountry(w, user) return } @@ -352,6 +355,14 @@ func (s *HubServer) handleMyCountry(w http.ResponseWriter, r *http.Request) { } } + customerProfileMu.Lock() + defer customerProfileMu.Unlock() + user := loadSaaSUser(username) + if user == nil { + writeJSONError(w, http.StatusUnauthorized, "unknown user — please log in again") + return + } + // Both a pick and a clear are deliberate, so BOTH stamp countrySourceUser // (and, through setUserCountry, the legacy CountrySetByUser). Stamping it on // the clear is the load-bearing half: it is what stops the next login's
ClusterHivesPool avail▶' + hiveNameHTML(h) + hiveAccessAvatars(h) + (health === "parked" ? 'parked' : "") + whyChipHTML(h, health) + rosterMismatchChipHTML(h) + attachChipHTML(h) + remediationHTML(h, health) + '' + hiveNameHTML(h) + hiveAccessAvatars(h) + (health === "parked" ? 'parked' : "") + whyChipHTML(h, health) + rosterMismatchChipHTML(h) + attachChipHTML(h) + remediationHTML(h, health) + profileLink + '' + acmmBadge(h.acmmLevel) + '' + modeBadge(h.governorMode) + '' + versionHTML(h) + '' + rollupHTML(h.fleetRollup) + '' + outputHTML(h) + '
' + budgetHealthHTML(h.budgetHealth) + '
' + githubAppHealthHTML(h.githubAppHealth, h) + '