diff --git a/docs-site/src/content/docs/reference/experiments.md b/docs-site/src/content/docs/reference/experiments.md index f2389173c17..89daff45bdf 100644 --- a/docs-site/src/content/docs/reference/experiments.md +++ b/docs-site/src/content/docs/reference/experiments.md @@ -60,7 +60,7 @@ An agent can see which experiments are on with `scion whoami --full`, which read - **`hub.system_one` (System One message guardrails, server layer, alpha, off by default).** Enables Hub-scoped System One provider instance administration and probing (`GET`/`POST /api/v1/admin/system-one/instances`, `GET`/`DELETE /api/v1/admin/system-one/instances/{name}`, and `POST /api/v1/admin/system-one/instances/{name}/probe`, backed by `scion admin system-one instance create|list|delete|probe`) as well as per-project instance allowlist management (`GET`/`PUT /api/v1/projects/{id}/system-one/instances` and `PUT`/`DELETE /api/v1/projects/{id}/system-one/instances/{name}`, backed by `scion project system-one list|add|remove|set`, gated by `project.manage_system_one_instances` and empty by default on every hub). Runtime and probe evaluations are bounded by `server.hub.system_one.max_eval_time` (`SCION_SERVER_HUB_SYSTEMONE_MAXEVALTIME`, default `3s`, maximum `30s`), per-replica project concurrency cap `server.hub.system_one.max_in_flight_per_project` (default `4`; per-project isolation prevents single-project monopolization only when the instance's `limits.maxInFlight` has headroom above this cap), and admission wait ceiling `server.hub.system_one.admission_wait` (default `100ms`). Instance `limits.maxInFlight` and `limits.ratePerSec` are also enforced per Hub replica, so a Hub deployment with N replicas permits approximately N× of each configured limit. Outbound provider calls enforce HTTPS and refuse loopback, RFC 1918, link-local, cloud metadata, and unspecified IP addresses at connect time (`allowPrivateNetwork: true` is refused). While it is off, all System One admin and project allowlist routes answer `404` and stored provider instances and allowlists are kept. - **`hub.triggers` (Triggers and webhook endpoints, server layer, alpha, off by default).** Enables project-scoped event triggers, signed (`scion_v1`) webhook endpoints, and the durable event inbox and drainer (`POST /api/v1/hooks/{id}`, `GET`/`POST`/`DELETE /api/v1/projects/{id}/webhook-endpoints`, `GET`/`POST`/`PATCH`/`DELETE /api/v1/projects/{id}/triggers` with `/pause`, `/resume`, and `/history`, and `GET /api/v1/projects/{id}/trigger-events`, backed by [`scion trigger`](/scion/reference/cli/#scion-trigger)). `POST /webhook-endpoints` mints a one-time HMAC signing secret stored as a hub-scoped internal secret (never returned again or exposed through the generic secrets API) and accepts an optional `defaultTrigger` (`agentId`/`agentName`/`toSelf`, `message`, `interrupt`, `wake`) to create the endpoint and default `webhook.received` trigger in one transaction. Triggers fire through the shared fire core under the authoring principal's recorded authority and are processed asynchronously via the `trigger.event` durable queue with hourly abandoned-fire reaping and 7-day history retention. While `hub.triggers` is on, `GET /api/v1/admin/scheduler` reports `durableQueues`, `GET /api/v1/admin/health/summary` includes the caller-scoped `triggers` section (failing triggers and hub-paused triggers with `paused_by_reason`), and `GET /metrics` (plus OTel `scion.hub.durablequeue.*` and `scion.hub.trigger.*` series) exposes queue, ingress, fire, and reaper counters. Stage 1 note: `subject.mode` currently accepts `"new"` only (`"skip"` returns `400` until subject-skip support lands), and ordered CEL `match.rules` and `subject.expr` are evaluated at dispatch time under a shared per-event rule budget. While `hub.triggers` is off, all trigger, webhook, event, and ingress routes answer `404`, the `trigger.event` drainer does not claim items, and the admin, health-summary, and metrics trigger sections are omitted. See [API Reference — Projects](/scion/reference/api/#projects-apiv1projects) and [Glossary — Triggers](/scion/glossary/#triggers). - **`hub.github_triggers` (GitHub App events as triggers, server and web layers, alpha, off by default).** Enables GitHub App webhook trigger readiness reporting (`triggers` on `GET /api/v1/github-app`, computed from the Hub's cached `GET /app` identity and permissions metadata refreshed at startup, during health checks, via `POST /api/v1/github-app/sync-permissions`, and on `installation.new_permissions_accepted`) and Hub-admin primary-project repository routing (`GET /api/v1/github-app/repo-routing` and `PUT`/`DELETE /api/v1/github-app/repo-routing/{owner}/{repo}`, audited as `hub.github_app.repo_routing.update`; `404` while the experiment is off), preparing for GitHub pull request, issue, review, and `@ /command` trigger ingress, presets, and `github.comment` actions (requires `hub.triggers`). While it is off, `GET /api/v1/github-app` omits `triggers`, the repository-routing routes answer `404`, and stored `trigger_routing` entries on installations are kept. See [Authentication — Permissions and Events for GitHub Triggers](/scion/hosted/single-node/auth/#permissions-and-events-for-github-triggers). -- **`hub.message_policies` (Project message policies, server layer, alpha, off by default).** Enables project-scoped CEL and optional System One (`system_one_rule`, requiring `hub.system_one` and a project-allowlisted instance) message policies on the enforced outbound agent surfaces `agent_to_user`, `agent_to_conversation`, `agent_dm`, and `mention_delivery` (including prompt cards on `agent_to_user` and `agent_to_conversation`), served at `GET`/`POST /api/v1/projects/{id}/message-policies`, `POST /api/v1/projects/{id}/message-policies/test`, `GET /api/v1/projects/{id}/message-policies/decisions`, `GET`/`PATCH`/`DELETE /api/v1/projects/{id}/message-policies/{policyId}`, `POST /api/v1/projects/{id}/message-policies/{policyId}/test`, and `GET /api/v1/projects/{id}/message-policies/{policyId}/decisions` (backed by `scion message-policy create|update|list|get|delete|test|decisions`; in agent mode only `list` and `get` are available). New policies default to `shadow` mode and require an explicit `on_failed` outcome (`admit` or `reject`), plus `on_uncertain` when `system_one_rule` is set. For CEL-only policies, messages longer than 16 KiB fail with `body_truncated`, handled by `on_failed`; policies with a `system_one_rule` pass the full body to System One, where `on_oversize` (`reject` → `input_too_large`, or `truncate`) applies. Failures such as `cost_limit`, `timeout`, `budget_exhausted` and `body_truncated` can be triggered by message content (`admit` lets such messages through). `PATCH` edits a policy, bumps its revision, and invalidates cached compiled rules. `POST .../test` stores nothing and never echoes the sample body, but when `system_one_rule` is set without synthetic judgments it executes a live System One provider call (sending selected fields, potentially incurring provider cost, with no automatic replay or retry; requires `project.secret_read` for project-scoped secrets; rate-limited to 30/min per caller per project per replica, while CEL-only and synthetic tests are not rate-limited). Enforced violations return `422 message_policy_rejected` before attachment ingestion, persistence or delivery, and content-free decision rows are trimmed at 7 days and 100,000 rows per project. On `agent_to_user` and `agent_to_conversation`, the user-visible decision text (question, choice labels and descriptions, Other), the secret-request description and requested variable name, and the command-request script, description and displayed workdir are appended to `message.body` for policy evaluation; mention facts use only the intro, and secret values, URLs and IDs are excluded. Uncovered agent paths — `group_post`, `group_set`, `mention_fanout`, and `broadcast` (reported in `coverage.uncovered_agent_paths`) — as well as scheduled deliveries, user-originated sends, and inbound external bridges are not evaluated. While it is off, the message policy routes answer `404`, the outbound gate evaluates nothing, and stored policies and decision records are kept. +- **`hub.message_policies` (Project message policies, server and web layers, alpha, off by default).** Enables project-scoped CEL and optional System One (`system_one_rule`, requiring `hub.system_one` and a project-allowlisted instance) message policies on the enforced outbound agent surfaces `agent_to_user`, `agent_to_conversation`, `agent_dm`, and `mention_delivery` (including prompt cards on `agent_to_user` and `agent_to_conversation`), served at `GET`/`POST /api/v1/projects/{id}/message-policies`, `POST /api/v1/projects/{id}/message-policies/test`, `GET /api/v1/projects/{id}/message-policies/decisions`, `GET`/`PATCH`/`DELETE /api/v1/projects/{id}/message-policies/{policyId}`, `POST /api/v1/projects/{id}/message-policies/{policyId}/test`, and `GET /api/v1/projects/{id}/message-policies/{policyId}/decisions` (backed by `scion message-policy create|update|list|get|delete|test|decisions`; in agent mode only `list` and `get` are available). New policies default to `shadow` mode and require an explicit `on_failed` outcome (`admit` or `reject`), plus `on_uncertain` when `system_one_rule` is set. For CEL-only policies, messages longer than 16 KiB fail with `body_truncated`, handled by `on_failed`; policies with a `system_one_rule` pass the full body to System One, where `on_oversize` (`reject` → `input_too_large`, or `truncate`) applies. Failures such as `cost_limit`, `timeout`, `budget_exhausted` and `body_truncated` can be triggered by message content (`admit` lets such messages through). `PATCH` edits a policy, bumps its revision, and invalidates cached compiled rules. `POST .../test` stores nothing and never echoes the sample body, but when `system_one_rule` is set without synthetic judgments it executes a live System One provider call (sending selected fields, potentially incurring provider cost, with no automatic replay or retry; requires `project.secret_read` for project-scoped secrets; rate-limited to 30/min per caller per project per replica, while CEL-only and synthetic tests are not rate-limited). Enforced violations return `422 message_policy_rejected` before attachment ingestion, persistence or delivery, and content-free decision rows are trimmed at 7 days and 100,000 rows per project. On `agent_to_user` and `agent_to_conversation`, the user-visible decision text (question, choice labels and descriptions, Other), the secret-request description and requested variable name, and the command-request script, description and displayed workdir are appended to `message.body` for policy evaluation; mention facts use only the intro, and secret values, URLs and IDs are excluded. Uncovered agent paths — `group_post`, `group_set`, `mention_fanout`, and `broadcast` (reported in `coverage.uncovered_agent_paths`) — as well as scheduled deliveries, user-originated sends, and inbound external bridges are not evaluated. While it is off, the message policy routes answer `404`, the outbound gate evaluates nothing, and stored policies and decision records are kept. - **`hub.effective_permissions` (Effective permissions viewer, server and web layers, alpha, off by default).** Enables the read-only admin effective permissions endpoint (`GET`/`HEAD /api/v1/admin/effective-permissions?principalType=user&principalId=[&projectId=]`, gated on `role_binding.read` at hub scope; `404` while the experiment is off) and the **Effective permissions** tab inside the admin **Users → Roles** dialog. Resolves a user's effective permissions server-side through the same authorization kernel as `Decide`, listing every contributing role binding (direct or via group) and any role-granted permissions removed by active access constraints (with constraint names revealed only to callers holding `access_constraint.read`). While it is off, the route answers `404` and the Roles dialog renders the roles content without tabs. - **`hub.exec_containers` (Execution containers, server and web layers, alpha, off by default).** Enables execution containers (agents started with the reserved built-in `shell` harness-config; creating one while the experiment is off answers `400 experiment_disabled`) and per-user default execution container registration at `GET`/`PUT`/`DELETE /api/v1/users/me/exec-container` (backed by `scion exec-container show|set|clear`, human-mode only and not enabled on Windows in v1). All three routes require an interactive session or dev credential (`403` with `INTERACTIVE_STATE` for user access tokens, and `403 forbidden` for agent identities). `PUT` accepts `{"agentId": ""}`, validates that the target is a non-deleted execution container the caller can attach to, returns a uniform `422 exec_container_ineligible` body for every ineligible target (no existence oracle), and records a `user.exec_container.set` mutation audit event (`DELETE` records `user.exec_container.clear` when a registration existed). `GET` re-evaluates eligibility on every read (failing closed to `unavailable` with no agent metadata when ineligible or when authorization is indeterminate), maps live state to `ready`, `starting`, `stopped`, `suspended`, or `unavailable`, and reports `homePersistent` on the `agent` object when the Runtime Broker has recorded whether `$HOME` survives container restarts (injected into execution containers via the reserved `SCION_HOME_PERSISTENT` environment variable and recorded in `runtime_state`; non-persistent runtimes are allowed with a warning). While `hub.exec_containers` is off, `GET` and `PUT` answer `404`, `DELETE` stays available and returns `204`, stored registrations are kept (resolving as `unconfigured` until re-enabled), and security protections on existing execution containers (human-only attach/exec/schedules, message delivery refusal, user-scope-only env/secrets plus reserved `SCION_*` control variables, and the reserved `shell` name) remain enforced. Execution containers receive no project GitHub App token or project default GCP identity, so private-repo clones require a user-scope `GITHUB_TOKEN`; execution containers created before this change keep their previously inherited identity (recreate them to apply it), and on Kubernetes the forced `block` mode requires Workload Identity node pools. See [Glossary — Execution container](/scion/glossary/#execution-container). - **`hub.command_requests` (Approved command execution, server and web layers, alpha, off by default).** Lets agents propose commands (`scion message --command-request`) for a single named human approver (DM recipient, or `--approver` naming a human participant in a conversation/thread) to approve (`POST /api/v1/command-requests/{id}/approve`, `scion command request approve`) or dismiss (`POST /api/v1/command-requests/{id}/dismiss`, `scion command request dismiss`, reason ≤ 500 characters) and run at most once in that human's execution container over Conduit. Agents can list (`GET /api/v1/agent/command-requests`, `scion command request list`) and withdraw (`POST /api/v1/agent/command-requests/withdraw`, `scion command request withdraw `) their own requests, up to a cap of 10 pending requests per agent (`429 command_request_limit`). Pending requests expire after 24 hours and are withdrawn (`withdrawn_by: system`) when the requesting agent is deleted (leaving approved requests and `command_runs` untouched). Requires `hub.exec_containers` and `hub.conduit`. When Conduit is served, the Hub includes `hub.command_requests` in `SCION_HUB_EXPERIMENTS` at agent launch, and shell execution containers register the `exec-start` and `exec-status` control routes from it (LLM agents never gain exec routes from this flag). While `hub.command_requests` is off, command-request routes answer `404` and new command-run dispatches are refused; in-flight runs and the command-run sweeper (lease expiry, request expiry, 7-day raw-output purge, and up to 1-hour outcome-delivery retry) continue running. **Output retention and rollout:** the command-run sweeper purges stored raw command outputs (`exec_run_outputs` rows with `owner_kind=action_run`) after 7 days; when an approver opts in to sharing output, the redacted ≤ 4 KiB tail is delivered to the asking agent and follows message retention rather than the 7-day raw-output purge. Upgrade runtime brokers before enabling output sharing, as older brokers log message content on delivery. See [Approved Commands](/scion/hosted/user/approved-commands/). diff --git a/pkg/experiments/registry.go b/pkg/experiments/registry.go index 7bc2a5fbae5..e1528b33f3d 100644 --- a/pkg/experiments/registry.go +++ b/pkg/experiments/registry.go @@ -633,11 +633,12 @@ const Triggers = "hub.triggers" // MessagePolicies gates project-scoped message admission policies // (ptone/scion#8047): /api/v1/projects/{id}/message-policies[/{policyId}[/test|/decisions]], -// scion message-policy create|list|get|delete|test|decisions, and the H2 -// outbound agent message gate (agent->user DMs, agent conversation posts and -// choice prompts; shadow and enforce modes). While it is off, the message -// policy routes answer 404, the outbound gate evaluates and records nothing, -// and stored policies and decision records are kept. +// scion message-policy create|update|list|get|delete|test|decisions, and the outbound +// agent message gate (agent_to_user, agent_to_conversation, agent_dm, +// mention_delivery; shadow and enforce modes). Server layer: while it is off, +// the message policy routes answer 404, the outbound gate evaluates and records +// nothing, and stored policies and decision records are kept. Web layer: +// exposes the flag for UI presentation. const MessagePolicies = "hub.message_policies" // EffectivePermissions gates the admin effective-permissions viewer @@ -1432,9 +1433,9 @@ var compiled = []Experiment{ { Name: MessagePolicies, Title: "Project message policies", - Description: "Enables project-scoped CEL message policies on outbound agent messages to users, conversations and choice prompts (/api/v1/projects/{id}/message-policies[/{policyId}[/test|/decisions]] and scion message-policy create|list|get|delete|test|decisions), with shadow and enforce modes and content-free decision records. Agent-to-agent DMs, group-set fan-out and mention deliveries are not covered yet and are reported in coverage.uncovered_agent_paths. While off, the routes answer 404, the gate evaluates nothing and stored policies and decisions are kept.", + Description: "Enables project-scoped message policies on outbound agent messages to users, conversations, choice prompts, agent-to-agent DMs, and mention deliveries (agent_to_user, agent_to_conversation, agent_dm, mention_delivery) (/api/v1/projects/{id}/message-policies[/{policyId}[/test|/decisions]] and scion message-policy), with shadow and enforce modes and content-free decision records. Uncovered agent paths (group_post, group_set, mention_fanout, broadcast) are reported in coverage.uncovered_agent_paths. Server layer: while off, the routes answer 404, the gate evaluates nothing and stored policies and decisions are kept. Web layer: exposes the flag for UI presentation.", Default: false, - Layers: []Layer{LayerServer}, + Layers: []Layer{LayerServer, LayerWeb}, Stage: StageAlpha, Issue: "ptone/scion#8047", Owner: "system-one", diff --git a/pkg/experiments/registry_test.go b/pkg/experiments/registry_test.go index 23a994cbe4c..47ec7fa9a48 100644 --- a/pkg/experiments/registry_test.go +++ b/pkg/experiments/registry_test.go @@ -947,7 +947,7 @@ func TestTriggersExperimentRegistered(t *testing.T) { } // TestMessagePoliciesExperimentRegistered pins hub.message_policies -// (ptone/scion#8047): server-layer only and ships off by default. +// (ptone/scion#8047): server+web layers and ships off by default. func TestMessagePoliciesExperimentRegistered(t *testing.T) { e, ok := Default().Lookup(MessagePolicies) if !ok { @@ -959,8 +959,8 @@ func TestMessagePoliciesExperimentRegistered(t *testing.T) { if e.Default { t.Fatal("hub.message_policies must default to off") } - if !e.HasLayer(LayerServer) || e.HasLayer(LayerWeb) { - t.Fatalf("must be a server-layer (only) experiment, got %v", e.Layers) + if !e.HasLayer(LayerServer) || !e.HasLayer(LayerWeb) { + t.Fatalf("must have both LayerServer and LayerWeb, got %v", e.Layers) } if e.Issue != "ptone/scion#8047" || e.Stage != StageAlpha || e.Owner != "system-one" { t.Fatalf("unexpected registration: %+v", e) diff --git a/pkg/hub/capabilities_test.go b/pkg/hub/capabilities_test.go index aff3181a6e0..e7d498b3463 100644 --- a/pkg/hub/capabilities_test.go +++ b/pkg/hub/capabilities_test.go @@ -957,3 +957,123 @@ func TestResourceBuilders(t *testing.T) { assert.Equal(t, Resource{}, gcpServiceAccountResource(nil)) }) } + +// TestProjectCapabilities_MessagePolicyAndSystemOneActions pins the exact +// project _capabilities.actions names and built-in role mapping relied on by +// the message-policy and System One project UI (A5). +func TestProjectCapabilities_MessagePolicyAndSystemOneActions(t *testing.T) { + const ( + actionManagePolicies = "manage_message_policies" + actionReadPolicies = "read_message_policies" + actionManageS1 = "manage_system_one_instances" + ) + + // Pin the exact action names on ResourceActions["project"]. + assert.Contains(t, ResourceActions["project"], Action(actionManagePolicies)) + assert.Contains(t, ResourceActions["project"], Action(actionReadPolicies)) + assert.Contains(t, ResourceActions["project"], Action(actionManageS1)) + + srv, s := testServer(t) + ctx := context.Background() + + project := &store.Project{ + ID: tid("mp-cap-project"), + Name: "MP Cap Project", + Slug: "mp-cap-project", + } + require.NoError(t, s.CreateProject(ctx, project)) + + type roleCase struct { + name string + userID string + email string + systemRole string + projectRole string + wantActions []string + forbidAction []string + } + + cases := []roleCase{ + { + name: "project-owner", + userID: tid("mp-cap-owner"), + email: "mp-cap-owner@example.com", + projectRole: store.ProjectRoleOwner, + wantActions: []string{actionManagePolicies, actionReadPolicies, actionManageS1}, + }, + { + name: "project-admin", + userID: tid("mp-cap-admin"), + email: "mp-cap-admin@example.com", + projectRole: store.ProjectRoleAdmin, + wantActions: []string{actionManagePolicies, actionReadPolicies, actionManageS1}, + }, + { + name: "hub-admin", + userID: tid("mp-cap-hubadmin"), + email: "mp-cap-hubadmin@example.com", + systemRole: store.SystemRoleHubAdmin, + wantActions: []string{actionManagePolicies, actionReadPolicies, actionManageS1}, + }, + { + name: "project-member", + userID: tid("mp-cap-member"), + email: "mp-cap-member@example.com", + projectRole: store.ProjectRoleMember, + wantActions: []string{actionReadPolicies}, + forbidAction: []string{actionManagePolicies, actionManageS1}, + }, + { + name: "project-viewer", + userID: tid("mp-cap-viewer"), + email: "mp-cap-viewer@example.com", + projectRole: store.ProjectRoleViewer, + wantActions: []string{actionReadPolicies}, + forbidAction: []string{actionManagePolicies, actionManageS1}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if tc.systemRole != "" { + createTestUserWithRole(t, s, tc.userID, tc.email, store.UserRoleAdmin, tc.systemRole) + } else { + require.NoError(t, s.CreateUser(ctx, &store.User{ + ID: tc.userID, + Email: tc.email, + DisplayName: tc.name, + Role: store.UserRoleMember, + Status: "active", + })) + projectOpsGrant(t, s, tc.userID, project.ID, tc.projectRole) + } + + userRole := store.UserRoleMember + if tc.systemRole != "" { + userRole = store.UserRoleAdmin + } + ident := NewAuthenticatedUser(tc.userID, tc.email, tc.name, userRole, "session") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/projects/"+project.ID, nil). + WithContext(contextWithIdentity(ctx, ident)) + srv.getProject(rec, req, project.ID) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + var resp struct { + Capabilities *Capabilities `json:"_capabilities"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + require.NotNil(t, resp.Capabilities, "GET /api/v1/projects/{id} must populate _capabilities") + + for _, want := range tc.wantActions { + assert.Contains(t, resp.Capabilities.Actions, want, + "%s must receive %q in project _capabilities.actions", tc.name, want) + } + for _, forbid := range tc.forbidAction { + assert.NotContains(t, resp.Capabilities.Actions, forbid, + "%s must not receive %q in project _capabilities.actions", tc.name, forbid) + } + }) + } +} diff --git a/pkg/hub/experiments_test.go b/pkg/hub/experiments_test.go index fe1177c868f..8a5f460d819 100644 --- a/pkg/hub/experiments_test.go +++ b/pkg/hub/experiments_test.go @@ -213,6 +213,30 @@ func TestResolvedExperiments_IncludesProjectVisitors(t *testing.T) { } } +// TestResolvedExperiments_IncludesMessagePolicies: the browser reads +// GET /api/v1/experiments to gate the project Message Policies UI, so +// hub.message_policies must appear in the resolved web-layer map with its +// effective value (off by default, true when overridden on). +func TestResolvedExperiments_IncludesMessagePolicies(t *testing.T) { + srv := &Server{} + got := srv.resolvedExperiments() + if v, ok := got[experiments.MessagePolicies]; !ok || v { + t.Errorf("resolvedExperiments()[%q] = %v (present=%v), want false and present", experiments.MessagePolicies, v, ok) + } + + fakeStore := newFakeHubSettingStore() + fakeStore.seed("experiments", json.RawMessage(`{"overrides":{"hub.message_policies":true}}`)) + ops := NewOperationalSettings(fakeStore, emptyKoanf(), emptyKoanf()) + if _, err := ops.Refresh(context.Background()); err != nil { + t.Fatalf("Refresh: %v", err) + } + on := &Server{} + on.SetOperationalSettings(ops) + if v, ok := on.resolvedExperiments()[experiments.MessagePolicies]; !ok || !v { + t.Errorf("with the override on: resolvedExperiments()[%q] = %v (present=%v), want true", experiments.MessagePolicies, v, ok) + } +} + // --- requireExperiment --- func TestRequireExperiment_OffReturns404(t *testing.T) { diff --git a/web/e2e-perf/budgets/fixture-schema.json b/web/e2e-perf/budgets/fixture-schema.json index e47a9ee445f..670cafab80a 100644 --- a/web/e2e-perf/budgets/fixture-schema.json +++ b/web/e2e-perf/budgets/fixture-schema.json @@ -59,6 +59,7 @@ "experiments.hub.flat_runtime_brokers:boolean", "experiments.hub.github_triggers:boolean", "experiments.hub.k8s_workload_identity_setup:boolean", + "experiments.hub.message_policies:boolean", "experiments.hub.system_one:boolean", "experiments.hub.triggers:boolean", "experiments.hub.user_delete_force_cascade:boolean", diff --git a/web/e2e-perf/budgets/fixture.mjs b/web/e2e-perf/budgets/fixture.mjs index b36653b9b19..1cf2b011953 100644 --- a/web/e2e-perf/budgets/fixture.mjs +++ b/web/e2e-perf/budgets/fixture.mjs @@ -202,6 +202,7 @@ export function buildFixture() { 'hub.flat_runtime_brokers': true, 'hub.github_triggers': false, 'hub.k8s_workload_identity_setup': false, + 'hub.message_policies': false, 'hub.system_one': false, 'hub.triggers': false, 'hub.user_delete_force_cascade': true, diff --git a/web/src/utils/feature-flags.test.ts b/web/src/utils/feature-flags.test.ts index 1d3ed17343f..1fdc738692e 100644 --- a/web/src/utils/feature-flags.test.ts +++ b/web/src/utils/feature-flags.test.ts @@ -533,3 +533,17 @@ describe('idleSuspendEnabled (lifecycle.idle_suspend)', () => { expect(idleSuspendEnabled()).toBe(false); }); }); + +describe('messagePoliciesEnabled (hub.message_policies)', () => { + it('defaults to false and follows server/explicit flags', async () => { + const { MESSAGE_POLICIES_FLAG, messagePoliciesEnabled } = await import('./feature-flags.js'); + expect(MESSAGE_POLICIES_FLAG).toBe('hub.message_policies'); + expect(messagePoliciesEnabled()).toBe(false); + + setServerFlags({ 'hub.message_policies': true }); + expect(messagePoliciesEnabled()).toBe(true); + + setFeatureFlag('hub.message_policies', false); + expect(messagePoliciesEnabled()).toBe(false); + }); +}); diff --git a/web/src/utils/feature-flags.ts b/web/src/utils/feature-flags.ts index 0b3fd02eec0..7f0ee43fa62 100644 --- a/web/src/utils/feature-flags.ts +++ b/web/src/utils/feature-flags.ts @@ -363,6 +363,20 @@ export function systemOneEnabled(): boolean { return isFeatureEnabled(SYSTEM_ONE_FLAG); } +/** + * Project message policies (hub.message_policies, ptone/scion#8047): + * exposes the message-policies experiment flag for UI presentation. + * Presentation only: the hub enforces the experiment (404 when off) and + * permissions on every /api/v1/projects/{id}/message-policies* route. + * Default OFF. + */ +export const MESSAGE_POLICIES_FLAG = 'hub.message_policies'; + +/** Whether project message policies UI surfaces are enabled in this session. */ +export function messagePoliciesEnabled(): boolean { + return isFeatureEnabled(MESSAGE_POLICIES_FLAG); +} + /** * Effective permissions viewer (hub.effective_permissions, ptone/scion#8439): * shows the two-tab Roles dialog (Effective roles + Effective permissions) on