diff --git a/changelog.d/added-15966-public-safe-activity-view.md b/changelog.d/added-15966-public-safe-activity-view.md new file mode 100644 index 0000000000..e35f83891a --- /dev/null +++ b/changelog.d/added-15966-public-safe-activity-view.md @@ -0,0 +1 @@ +- The hub serves an anonymous **public-safe Fleet activity view** at `/activity/public`, backed by `GET /api/hub/activity/public` ([#15966](https://github.com/hivecommons/hive/issues/15966), part of [#15861](https://github.com/hivecommons/hive/issues/15861)). It is the source of the `twitch.tv/hivecommonsfleet` broadcast, and `src/deploy/stream/fleet` now points `DASHBOARD_PATH` at it. The view shows only public-repository items and events from hives the registry lists as public on github.com. It leaves out private or unknown-visibility rows, totals and drop counts that can include private items, hive owners and every per-user grant. It never reads a session or token, so a signed-in viewer's own Fleet access cannot leak onto a public stream. The signed-in `/activity` page is unchanged, and no broadcast is activated. diff --git a/src/deploy/stream/fleet/configmap.yaml b/src/deploy/stream/fleet/configmap.yaml index 26d12bc6c7..9675296f29 100644 --- a/src/deploy/stream/fleet/configmap.yaml +++ b/src/deploy/stream/fleet/configmap.yaml @@ -6,7 +6,8 @@ metadata: data: # Fail-closed switches (see ../public-safe-gate.sh). Only the owner flips # STREAM_ENABLED to "true" and sets PUBLIC_SAFE_POLICY_ACK to the policy - # version, after provisioning the stream key and the public-safe hub view. + # version, after provisioning the stream key and checking the public-safe + # hub view in a private browser window. STREAM_PROFILE: "public-safe" STREAM_ENABLED: "false" PUBLIC_SAFE_POLICY_ACK: "" @@ -14,9 +15,10 @@ data: # credential exists in this namespace and the auth proxy refuses one, so the # stream shows only what the hub serves to the public. DASHBOARD_URL: "https://hive.hivecommons.dev" - # The separately authorized public-safe hub view (#15966). The placeholder - # makes the gate refuse to start until the owner sets the real path. - DASHBOARD_PATH: "CHANGE-ME-public-safe-hub-view" + # The hub's anonymous public-safe Fleet activity view (#15966): public + # repositories of registry-public hives only, never per-user visibility. + # ?kiosk=1 hides the page chrome for the unattended stream. + DASHBOARD_PATH: "/activity/public?kiosk=1" TWITCH_INGEST: "rtmp://live.twitch.tv/app" VIDEO_SIZE: "1920x1080" FPS: "30" diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 00f8fd4bb2..701de79c8f 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -36,6 +36,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1773` | | `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1774` | | `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` | +| `GET` | `/activity/public` | Public | Public-safe Fleet activity page ([#15966](https://github.com/hivecommons/hive/issues/15966)): the same data-free shell as `/activity`, served without a session; on this path the page polls `/api/hub/activity/public` with `credentials: 'omit'`. Source of the `twitch.tv/hivecommonsfleet` broadcast. Same CSP and cache headers as `/activity`. See [Hub Fleet activity page](../hub-fleet-activity.md#public-safe-view) | `pkg/hub/activity_public.go` | | `GET` | `/activity/assets/{name}` | Public | The shared tracker assets the Fleet activity page loads, byte-identical: the row asset (`pkg/webassets/trackerrow`, [#16062](https://github.com/hivecommons/hive/issues/16062)) and the `am.*` URL-view and display-playlist helpers (`pkg/webassets/trackerview`, [#16064](https://github.com/hivecommons/hive/issues/16064)); only names in `trackerrow.Files` or `trackerview.Files`, else `404`. `Cache-Control: no-cache` + content `ETag` | `pkg/hub/activity_page.go` | | `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1708` | | `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1709` | @@ -49,6 +50,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | | `GET` | `/api/hub/activity` | Signed-in user | Read-only hub-wide activity view ([#15951](https://github.com/hivecommons/hive/issues/15951), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)) merged from each spoke's heartbeat `activity` digest, held in hub memory only. Authorization is per user and per hive before aggregation: hub admins see every registered hive; everyone else only hives they own or hold an unexpired grant for; anonymous → `401`. Returns `hives[]` (`hive_id`, `name`, `status` `ok`/`stale`/`not_reporting`/`missing`, `reporting`, `stale` once the block is older than two heartbeats, `last_heartbeat`, `received_at`, `generated_at`, `totals` — `items`, `by_stage`, `by_modifier`, counting private and truncated items too — `truncated` and `events_dropped`), `items[]` (`hive_id`, `repo`, `n`, `kind`, `title`, `author_kind`, `stage`, `stage_n`, `since`, `mods`, `private`) ordered needs-human/needs-decision, stalled, furthest stage, oldest, a response-level `truncated` (cap 2000), and `events[]` ([#15964](https://github.com/hivecommons/hive/issues/15964): `hive_id`, `received_at`, `seq`, `type` `opened`/`stage`/`merged`, `repo`, `n`, `kind`, `title`, `from`, `stage`, `at`, `private`), oldest first, from a fleet-wide in-memory ring of at most 1,000 events, none held longer than 24 hours (ageing out is not counted in `events_dropped`; when full, the oldest event of the hive holding the most events is dropped, counted in that hive's `events_dropped`, so one hive cannot evict the others' events). Events are filtered per user and per hive exactly like items, before aggregation, so an event for a hive the viewer cannot see is never delivered; `mod`/`author_kind` filters keep only events whose item is still on the hive's board. A spoke block carries at most 200 events; drops are disclosed per hive as `events_dropped`. New events change the `ETag`. Each digest carries at most 100 items by default and never more than the 250-item hub ceiling; private-repository items appear only when the spoke opts in. Filters: `hive`, `repo`, `stage`, `mod`, `author_kind`, `q` (title substring or `#`), each ≤ 200 characters (else `400`). `ETag` + `If-None-Match` → `304`; `Cache-Control: private, no-cache`, `Vary: Cookie, Authorization`. No actions | `pkg/hub/activity.go` | +| `GET` | `/api/hub/activity/public` | Public | Public-safe activity view ([#15966](https://github.com/hivecommons/hive/issues/15966)): the `/api/hub/activity` shape for anyone, never reading a cookie, token or `Authorization` header (credentials do not change the response). Only hives the registry lists as public on github.com, and only items and events not marked `private`; `totals`, per-hive `truncated` and `events_dropped`, hive owners and per-user grants are omitted. Same filters (`400` on an invalid one); `ETag` + `If-None-Match` → `304`; `Cache-Control: no-cache` | `pkg/hub/activity_public.go` | | `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1731` | | `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1741` | | `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1742` | diff --git a/src/docs/hub-fleet-activity.md b/src/docs/hub-fleet-activity.md index ea8724cce1..a69a65a920 100644 --- a/src/docs/hub-fleet-activity.md +++ b/src/docs/hub-fleet-activity.md @@ -128,12 +128,35 @@ The playlist follows the spoke's rules: The spoke-only wall options `density=tv` and `shift=1` are ignored here. +## Public-safe view + +`https:///activity/public` is the same board served to anyone, without a +session ([#15966](https://github.com/hivecommons/hive/issues/15966)). It is the +source of the `twitch.tv/hivecommonsfleet` broadcast +([Streaming the Activity Monitor](streaming-the-activity-monitor.md#the-hivecommonsfleet-broadcast)). +On that path the page polls `GET /api/hub/activity/public` with +`credentials: 'omit'`, and the endpoint never reads a cookie, token or +`Authorization` header, so a signed-in browser or an admin gets the same rows +as an anonymous visitor. + +The view is filtered on the hub before it is built: + +- Only hives the registry lists as **public** (the flag the public registry + and leaderboard use) on public github.com. A hive with no public flag, or + on a GitHub Enterprise host, is left out. +- Only items and events the spoke marked public. A spoke marks a repository + private unless it knows it is public, so unknown visibility is left out. +- No `totals`, digest `truncated` or `events_dropped`, since those can count + private items, and no hive owner. +- No per-user grants: your own access never widens it. + ## What the page does not do - It has no action menus. The hub is visibility-only: act on an item on GitHub, or from the hive's own tracker. -- It is not a broadcast source. Display mode only changes how the signed-in - page looks; the page still needs a hub session and shows only your hives. +- `/activity` is not a broadcast source. Display mode only changes how the + signed-in page looks; the page still needs a hub session and shows only + your hives. Broadcast only the [public-safe view](#public-safe-view). ## Security @@ -146,7 +169,8 @@ The spoke-only wall options `density=tv` and `shift=1` are ignored here. - The page, its script and the shared row-presentation and view assets are revalidated on every load (`Cache-Control: no-cache` with a content ETag), so a hub upgrade is picked up on the next visit. -- `/activity` is marked `noindex` and is disallowed in `robots.txt`. +- `/activity` (including `/activity/public`) is marked `noindex` and is + disallowed in `robots.txt`. ## For operators diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index 91b58780a2..8436b4c041 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -292,13 +292,37 @@ It reuses the same `hive-stream` image. Its ConfigMap sets holds the `CHANGE-ME` placeholder; and `TWITCH_STREAM_KEY` is installed (a local dry run with `STREAM_OUTPUT=null` or an absolute local `*.flv` path needs no key; a URL such as `rtmp://…/x.flv` or any other raw - `STREAM_OUTPUT` is refused). Shipped defaults fail every one of - these, and the Deployment is at `replicas: 0` on top. + `STREAM_OUTPUT` is refused). Shipped defaults fail the enable, + acknowledgement and stream-key checks, and the Deployment is at + `replicas: 0` on top. - **The auth proxy runs anonymous.** It refuses to start with a token, strips any `Authorization` or `Cookie` header the browser sends and drops `Set-Cookie` from responses, so no session can form. The kiosk sees exactly what an anonymous visitor of the hub sees, and nothing else. +### The public-safe hub view + +The source is the hub's anonymous public-safe Fleet activity view, +`/activity/public?kiosk=1` (`DASHBOARD_PATH` in `fleet/configmap.yaml`). It is +a separate route from the signed-in `/activity` page and polls its own +endpoint, `GET /api/hub/activity/public`, which needs no login and ignores any +cookie or token it is sent. The hub filters the data before it builds the +view, so private rows never reach the page: + +- **Shown:** open issues and pull requests in public repositories of hives the + registry lists as public on github.com — number, title, stage, modifiers, + author kind — plus their public stage hops, opens and merges, each hive's + name and report freshness. +- **Omitted:** private-repository items and events (and items whose + visibility the spoke does not know), hives not listed as public or on a + GitHub Enterprise host, per-hive totals, truncation and dropped-event counts + (they can count private items), hive owners, and any per-user access grant. + +A hub test (`TestActivityPublic_OmitsPrivateRowsByConstruction`) checks that a +private row is absent from this view whether the request is anonymous or +carries an admin's session. See also +[Hub Fleet activity page](hub-fleet-activity.md#public-safe-view). + ### Dashboard authentication does not protect Twitch output A Twitch stream is public. Anything painted in the kiosk is visible to anyone, @@ -333,15 +357,14 @@ acknowledgement cannot cover new content. ### Enabling it (owner only) Nothing below is done by this repository or by the hive; it is the owner's -decision on #15861. Status as of this change: the channel is provisioned; the -stream key is **not** installed and the public-safe hub view does **not** yet -exist (it follows the Fleet activity page, -[#15965](https://github.com/hivecommons/hive/issues/15965)). - -1. **Source.** Confirm a hub route renders the public-safe view anonymously - and meets the policy above, then set `DASHBOARD_PATH` in - `fleet/configmap.yaml` (e.g. with `?kiosk=1`). Open it in a private - browser window first: what you see there is what Twitch will show. +decision on #15861. Status as of this change: the channel is provisioned and +the [public-safe hub view](#the-public-safe-hub-view) exists; the stream key +is **not** installed and the broadcast is **not** enabled. + +1. **Source.** `DASHBOARD_PATH` already points at + `/activity/public?kiosk=1`. Open `https://hive.hivecommons.dev/activity/public` + in a private browser window and confirm it meets the policy above: what + you see there is what Twitch will show. 2. **Stream key.** In the `hivecommonsfleet` Creator Dashboard, copy the Primary Stream key and install it without echoing it or writing it to a file, a commit or an issue comment: diff --git a/src/pkg/hub/activity.go b/src/pkg/hub/activity.go index f6116bbaa9..9d4f11e7c1 100644 --- a/src/pkg/hub/activity.go +++ b/src/pkg/hub/activity.go @@ -163,6 +163,9 @@ type activityHive struct { Owner string LastHeartbeat string Missing bool + // Public is set only for a registry-public hive on public GitHub; only + // the public-safe view (activity_public.go) reads it. + Public bool } // visibleActivityHives returns the hives username may see, applying the @@ -359,16 +362,7 @@ func (s *HubServer) handleHubActivity(w http.ResponseWriter, r *http.Request) { return } now := time.Now().UTC() - s.mu.RLock() - registry := make([]activityHive, 0, len(s.registry.Hives)) - for _, h := range s.registry.Hives { - name := h.ProjectName - if name == "" { - name = h.Name - } - registry = append(registry, activityHive{ID: h.ID, Name: name, Owner: h.Owner, LastHeartbeat: h.LastHeartbeat}) - } - s.mu.RUnlock() + registry := s.activityRegistry() hives := visibleActivityHives(username, loadSaaSUser(username), registry, now) ids := make([]string, len(hives)) @@ -398,6 +392,24 @@ func (s *HubServer) handleHubActivity(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(body) } +// activityRegistry copies the registry slice the activity views need. +func (s *HubServer) activityRegistry() []activityHive { + s.mu.RLock() + defer s.mu.RUnlock() + registry := make([]activityHive, 0, len(s.registry.Hives)) + for _, h := range s.registry.Hives { + name := h.ProjectName + if name == "" { + name = h.Name + } + registry = append(registry, activityHive{ + ID: h.ID, Name: name, Owner: h.Owner, LastHeartbeat: h.LastHeartbeat, + Public: h.IsPublic && sameGitHubHost(h.GitHubHost, publicGitHubHost), + }) + } + return registry +} + // activityETagMatches is the RFC 9110 weak comparison of If-None-Match. func activityETagMatches(header, etag string) bool { want := strings.TrimPrefix(etag, "W/") diff --git a/src/pkg/hub/activity_page.go b/src/pkg/hub/activity_page.go index 5617935ef2..769041d5ae 100644 --- a/src/pkg/hub/activity_page.go +++ b/src/pkg/hub/activity_page.go @@ -106,8 +106,11 @@ func (s *HubServer) handleActivityAsset(w http.ResponseWriter, r *http.Request) _, _ = w.Write(body) } -// registerActivityPageRoutes mounts the page and its row asset. +// registerActivityPageRoutes mounts the page and its row asset, plus the +// anonymous public-safe view and its endpoint (activity_public.go, #15966). func (s *HubServer) registerActivityPageRoutes() { s.mux.HandleFunc("GET "+activityPagePath, s.handleActivityPage) + s.mux.HandleFunc("GET "+activityPublicPagePath, s.handleActivityPublicPage) + s.mux.HandleFunc("GET "+activityPublicPath, s.handleHubActivityPublic) s.mux.HandleFunc("GET "+activityAssetPrefix+"{name}", s.handleActivityAsset) } diff --git a/src/pkg/hub/activity_public.go b/src/pkg/hub/activity_public.go new file mode 100644 index 0000000000..8d89d1fcba --- /dev/null +++ b/src/pkg/hub/activity_public.go @@ -0,0 +1,124 @@ +package hub + +import ( + "encoding/json" + "net/http" + "time" + + "github.com/hivecommons/hive/pkg/dashboard/webstatic" + "github.com/hivecommons/hive/pkg/hubactivity" +) + +// Public-safe Fleet activity view (#15966, part of RFC #15861 by @hanthor). +// +// The hivecommonsfleet Twitch broadcast renders this view and nothing else. +// A stream is public, so dashboard authentication cannot protect it and a +// viewer's per-user Fleet visibility must never decide what it shows. This +// view is therefore anonymous by construction: it reads no session, cookie +// or Authorization header, and the same request returns the same rows for +// everyone. It keeps only: +// +// - hives the registry lists as public (the flag the public registry and +// leaderboard already honour) that target public github.com; +// - items and events the spoke marked public. The spoke marks every repo +// private unless it is known public, so unknown visibility is omitted. +// +// It drops every count that can include private items (totals, digest +// truncation, dropped events) and the hive owner. Filtering happens on the +// copied store data BEFORE the view is built, so a private row never enters +// the response or its ETag. + +const ( + activityPublicPagePath = "/activity/public" + activityPublicPath = "/api/hub/activity/public" +) + +// publicActivityHives returns the registry hives the public-safe view may +// show. It takes no viewer: no per-user grant can widen it. +func publicActivityHives(registry []activityHive) []activityHive { + var out []activityHive + for _, h := range registry { + if h.Public && !h.Missing { + out = append(out, activityHive{ID: h.ID, Name: h.Name, LastHeartbeat: h.LastHeartbeat, Public: true}) + } + } + return out +} + +// publicSafeActivityBlocks keeps only public items and drops the counts +// that include private or capped items. +func publicSafeActivityBlocks(blocks map[string]storedActivity) map[string]storedActivity { + out := make(map[string]storedActivity, len(blocks)) + for id, b := range blocks { + var items []hubactivity.Item + for _, it := range b.digest.Items { + if !it.Private { + items = append(items, it) + } + } + out[id] = storedActivity{ + digest: hubactivity.Digest{GeneratedAt: b.digest.GeneratedAt, Items: items}, + receivedAt: b.receivedAt, + } + } + return out +} + +// publicSafeActivityEvents keeps only public events; per-hive dropped +// counts are omitted because they may count private events. +func publicSafeActivityEvents(snap activityEventsSnapshot) activityEventsSnapshot { + out := activityEventsSnapshot{dropped: map[string]int{}} + for _, e := range snap.events { + if !e.event.Private { + out.events = append(out.events, e) + } + } + return out +} + +// buildPublicActivityView is the whole public-safe view: registry-public +// hives, public rows only, no viewer input beyond the query filters. +func (s *HubServer) buildPublicActivityView(f activityFilter, now time.Time) ActivityView { + hives := publicActivityHives(s.activityRegistry()) + ids := make([]string, len(hives)) + for i, h := range hives { + ids[i] = h.ID + } + blocks := publicSafeActivityBlocks(s.activity.snapshot(ids)) + view := buildActivityView(hives, blocks, f, now) + addActivityEvents(&view, hives, blocks, publicSafeActivityEvents(s.activity.eventsSnapshot(ids)), f) + return view +} + +// handleHubActivityPublic serves GET /api/hub/activity/public. It is not +// behind requireAuth and never reads the request's credentials, so a token +// or session presented with it changes nothing. +func (s *HubServer) handleHubActivityPublic(w http.ResponseWriter, r *http.Request) { + f, err := parseActivityFilter(r.URL.Query()) + if err != nil { + writeJSONError(w, http.StatusBadRequest, err.Error()) + return + } + body, err := json.Marshal(s.buildPublicActivityView(f, time.Now().UTC())) + if err != nil { + s.logger.Error("hub public activity: encode view", "error", err) + writeJSONError(w, http.StatusInternalServerError, "internal error") + return + } + etag := webstatic.ETagFor(body) + h := w.Header() + h.Set("Content-Type", "application/json") + h.Set("Cache-Control", "no-cache") + h.Set("ETag", etag) + if activityETagMatches(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return + } + _, _ = w.Write(body) +} + +// handleActivityPublicPage serves the Fleet activity shell anonymously. The +// shell carries no data; on this path activity.js polls activityPublicPath. +func (s *HubServer) handleActivityPublicPage(w http.ResponseWriter, r *http.Request) { + s.serveActivityShell(w, r) +} diff --git a/src/pkg/hub/activity_public_test.go b/src/pkg/hub/activity_public_test.go new file mode 100644 index 0000000000..fa3303f5e0 --- /dev/null +++ b/src/pkg/hub/activity_public_test.go @@ -0,0 +1,213 @@ +package hub + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/hubactivity" +) + +// Public-safe Fleet activity view (#15966, part of RFC #15861). + +func setActivityHiveVisibility(t *testing.T, s *HubServer, hiveID string, public bool, host string) { + t.Helper() + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.registry.Hives { + if s.registry.Hives[i].ID == hiveID { + s.registry.Hives[i].IsPublic = public + s.registry.Hives[i].GitHubHost = host + return + } + } + t.Fatalf("hive %s is not in the registry", hiveID) +} + +// getPublicActivity requests the public-safe endpoint, optionally with the +// credentials a signed-in admin would send. +func getPublicActivity(t *testing.T, s *HubServer, user, ifNoneMatch string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, activityPublicPath, nil) + if user != "" { + req.AddCookie(testAuthCookie(user)) + req.Header.Set("Authorization", "Bearer "+testHubSecret) + } + if ifNoneMatch != "" { + req.Header.Set("If-None-Match", ifNoneMatch) + } + rec := httptest.NewRecorder() + s.handleHubActivityPublic(rec, req) + return rec +} + +// mixedVisibilityDigest carries a public and a private item, plus one public +// and one private event, as a spoke that opted in to share private items +// sends them. +func mixedVisibilityDigest() *hubactivity.Digest { + d := hubactivity.Build([]hubactivity.Item{ + {Repo: "o/pub", Number: 1, Kind: "pr", Title: "public change", Stage: "ci_review", StageNumber: 70}, + {Repo: "o/secret", Number: 2, Kind: "pr", Title: "secret change", Stage: "ci_review", StageNumber: 70, Private: true}, + }, hubactivity.BuildOptions{SharePrivate: true, Now: activityT0}) + pub := activityEv(1, hubactivity.EventOpened, "o/pub", 1) + priv := activityEv(2, hubactivity.EventOpened, "o/secret", 2) + priv.Title = "secret change" + priv.Private = true + d.Events = []hubactivity.Event{pub, priv} + d.EventsDropped = 3 + return &d +} + +// Acceptance (#15966): the public-safe view omits private rows by +// construction — private-repository items and events, hives not listed as +// public, hives on a non-public GitHub, and every count that may include +// private items — whoever asks and whatever credentials they present. +func TestActivityPublic_OmitsPrivateRowsByConstruction(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + mkUser(t, "root") + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-pub", mixedVisibilityDigest()) + postActivityHeartbeat(t, s, "hive-priv", activityDigest("o/privhive", 3)) + postActivityHeartbeat(t, s, "hive-ghe", activityDigest("o/ghe", 4)) + postActivityHeartbeat(t, s, "hive-unset", activityDigest("o/unset", 5)) + setActivityHiveVisibility(t, s, "hive-pub", true, "") + setActivityHiveVisibility(t, s, "hive-priv", false, "") + setActivityHiveVisibility(t, s, "hive-ghe", true, "github.example.com") + + // The signed-in admin view still sees everything (unchanged behaviour). + full := decodeActivity(t, getActivity(t, s, "root", "", "")) + if got := activityHiveIDs(full); len(got) != 4 { + t.Fatalf("admin /api/hub/activity rows from %v, want all four hives", got) + } + + anon := getPublicActivity(t, s, "", "") + if anon.Code != http.StatusOK { + t.Fatalf("anonymous public view status %d body=%s", anon.Code, anon.Body.String()) + } + authed := getPublicActivity(t, s, "root", "") + if authed.Body.String() != anon.Body.String() { + t.Fatalf("credentials must not change the public-safe view:\nanonymous: %s\nadmin: %s", anon.Body.String(), authed.Body.String()) + } + body := anon.Body.String() + for _, leak := range []string{"o/secret", "secret change", "hive-priv", "o/privhive", "hive-ghe", "o/ghe", "hive-unset", "o/unset", `"private"`, `"totals"`, `"truncated"`, `"events_dropped"`, "root"} { + if strings.Contains(body, leak) { + t.Errorf("public-safe view leaks %q: %s", leak, body) + } + } + + v := decodeActivity(t, anon) + if len(v.Hives) != 1 || v.Hives[0].HiveID != "hive-pub" { + t.Fatalf("public hives = %+v, want only hive-pub", v.Hives) + } + if len(v.Items) != 1 || v.Items[0].Repo != "o/pub" || v.Items[0].Number != 1 { + t.Fatalf("public items = %+v, want only o/pub#1", v.Items) + } + if len(v.Events) != 1 || v.Events[0].Repo != "o/pub" { + t.Fatalf("public events = %+v, want only the o/pub event", v.Events) + } + + h := anon.Header() + if h.Get("Content-Type") != "application/json" || h.Get("Cache-Control") != "no-cache" || h.Get("ETag") == "" { + t.Fatalf("headers = %v, want JSON + no-cache + ETag", h) + } + if again := getPublicActivity(t, s, "", h.Get("ETag")); again.Code != http.StatusNotModified { + t.Fatalf("revalidation status %d, want 304", again.Code) + } +} + +// A spoke that sends no private items still has every public row rendered. +func TestActivityPublic_PublicRowsRender(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1, 2)) + setActivityHiveVisibility(t, s, "hive-a", true, "github.com") + v := decodeActivity(t, getPublicActivity(t, s, "", "")) + if len(v.Items) != 2 || len(v.Hives) != 1 || v.Hives[0].Status != activityStatusOK { + t.Fatalf("public view = %+v, want hive-a ok with both items", v) + } + if v.Hives[0].Totals != nil { + t.Fatalf("public view must omit totals, got %+v", v.Hives[0].Totals) + } + if rec := getPublicActivity(t, s, "", ""); rec.Code != http.StatusOK { + t.Fatalf("status %d", rec.Code) + } + req := httptest.NewRequest(http.MethodGet, activityPublicPath+"?repo="+strings.Repeat("x", maxActivityFilterRunes+1), nil) + rec := httptest.NewRecorder() + s.handleHubActivityPublic(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("oversized filter status %d, want 400", rec.Code) + } +} + +// The public page and endpoint are anonymous through the real mux, while +// the signed-in page and endpoint keep requiring a session. +func TestActivityPublic_RoutesAnonymouslyThroughTheHubMux(t *testing.T) { + t.Setenv("HUB_DATA_DIR", t.TempDir()) + srv := newHubServerForTest(t, withHubIdentity("test", "v5")) + serve := func(path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + srv.mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec + } + page := serve(activityPublicPagePath + "?kiosk=1") + if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), `id="activity-board"`) { + t.Fatalf("GET %s anonymous = %d, want the page shell", activityPublicPagePath, page.Code) + } + if page.Header().Get("Content-Security-Policy") != activityPageCSP { + t.Errorf("public page CSP = %q, want the Fleet activity CSP", page.Header().Get("Content-Security-Policy")) + } + api := serve(activityPublicPath) + if api.Code != http.StatusOK { + t.Fatalf("GET %s anonymous = %d, want 200", activityPublicPath, api.Code) + } + var v ActivityView + if err := json.Unmarshal(api.Body.Bytes(), &v); err != nil { + t.Fatal(err) + } + if rec := serve(activityPagePath); rec.Code != http.StatusTemporaryRedirect { + t.Errorf("GET /activity anonymous = %d, want redirect to login", rec.Code) + } + if rec := serve(activityPath); rec.Code != http.StatusUnauthorized { + t.Errorf("GET %s anonymous = %d, want 401", activityPath, rec.Code) + } + if !hubNoIndexPath(activityPublicPagePath) || !hubNoIndexPath(activityPublicPath) { + t.Errorf("the public-safe view is a stream source, not a search result: it must be noindex") + } +} + +// On the public path the page polls only the public endpoint, without +// credentials; on /activity it keeps polling the signed-in endpoint. +func TestActivityPublic_PagePollsThePublicEndpointWithoutCredentials(t *testing.T) { + js := readActivityScript(t) + for _, want := range []string{"'" + activityPublicPagePath + "'", "'" + activityPublicPath + "'", "'omit'"} { + if !strings.Contains(js, want) { + t.Fatalf("activity.js missing %q", want) + } + } + src := strings.Join(append([]string{js}, + "result = {", + " pub: activityApiFor('/activity/public'),", + " pubSlash: activityApiFor('/activity/public/'),", + " full: activityApiFor('/activity'),", + " other: activityApiFor('/activity/publicx'),", + " pubCreds: activityFetchOptions({}, true).credentials,", + " fullCreds: activityFetchOptions({}, false).credentials,", + "};", + ), "\n") + var got struct{ Pub, PubSlash, Full, Other, PubCreds, FullCreds string } + runEvidenceJS(t, src, &got) + if got.Pub != activityPublicPath || got.PubSlash != activityPublicPath { + t.Errorf("public page polls %q / %q, want %s", got.Pub, got.PubSlash, activityPublicPath) + } + if got.Full != activityPath || got.Other != activityPath { + t.Errorf("signed-in page polls %q / %q, want %s", got.Full, got.Other, activityPath) + } + if got.PubCreds != "omit" || got.FullCreds != "same-origin" { + t.Errorf("credentials public=%q signed-in=%q, want omit / same-origin", got.PubCreds, got.FullCreds) + } +} diff --git a/src/pkg/hub/static/activity.js b/src/pkg/hub/static/activity.js index 20f34a6c86..abc66be80e 100644 --- a/src/pkg/hub/static/activity.js +++ b/src/pkg/hub/static/activity.js @@ -41,6 +41,11 @@ const ACTIVITY_STAGE_DETOURS = [ const ACTIVITY_COLUMN_LABELS = { 0: 'Open', 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 50: 'CI / Review', 80: 'Merge gate', 110: 'Merged' }; const ACTIVITY_API = '/api/hub/activity'; +// The anonymous public-safe view (#15966) serves this same page at +// ACTIVITY_PUBLIC_PAGE and polls only its own endpoint, without credentials, +// so it can never show the signed-in view's rows. +const ACTIVITY_PUBLIC_PAGE = '/activity/public'; +const ACTIVITY_PUBLIC_API = '/api/hub/activity/public'; const ACTIVITY_POLL_MS = 15000; // Display mode (#16064): #15860 Part A reused unchanged. `am.*` URL state and @@ -470,8 +475,16 @@ function activityClock(t) { return new Date(t).toLocaleTimeString(); } -function activityFetchOptions(headers) { - const opts = { headers: headers, credentials: 'same-origin', cache: 'no-store' }; +function activityIsPublicPage(pathname) { + return String(pathname || '').replace(/\/+$/, '') === ACTIVITY_PUBLIC_PAGE; +} + +function activityApiFor(pathname) { + return activityIsPublicPage(pathname) ? ACTIVITY_PUBLIC_API : ACTIVITY_API; +} + +function activityFetchOptions(headers, isPublic) { + const opts = { headers: headers, credentials: isPublic ? 'omit' : 'same-origin', cache: 'no-store' }; if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') { opts.signal = AbortSignal.timeout(ACTIVITY_FETCH_TIMEOUT_MS); } @@ -488,14 +501,15 @@ async function activityPoll() { try { const headers = {}; if (activityState.etag) headers['If-None-Match'] = activityState.etag; + const isPublic = activityIsPublicPage(window.location.pathname); let res; try { - res = await fetch(ACTIVITY_API, activityFetchOptions(headers)); + res = await fetch(activityApiFor(window.location.pathname), activityFetchOptions(headers, isPublic)); } catch (e) { activitySetStatus('Hub unreachable — retrying every 15 s', true); return; } - if (res.status === 401) { + if (res.status === 401 && !isPublic) { window.location.assign('/login'); return; } @@ -589,6 +603,10 @@ function activityBoot() { const urlView = activityUrlView(window.location.href); activityState.filter = urlView.filter; activityState.group = urlView.group; + if (activityIsPublicPage(window.location.pathname)) { + const sub = document.querySelector('.activity-sub'); + if (sub) sub.textContent = 'Public view: open issues and pull requests in public repositories of hives listed as public. Private repositories and per-user access are never shown.'; + } const toggle = document.getElementById('activity-group'); toggle.checked = activityState.group === 'hive'; // The toggle is am.group: the address bar stays a link to this view