From d4136841c7d99a8aa13a5dc362d7e9cc9b4d340f Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 17 Nov 2026 13:06:58 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20Dashboard/API:=20set=20review.p?= =?UTF-8?q?erspectives=5Fsource=20and=20agent=20sandbox=20image/block=20wi?= =?UTF-8?q?thout=20editing=20config=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #18797 Signed-off-by: Andy Anderson --- ...rspectives-source-and-sandbox-dashboard.md | 1 + src/docs/agent-configuration.md | 4 + src/docs/review-swarm.md | 6 +- src/docs/sandbox-isolation.md | 10 + .../config/save_perspectives_sandbox_test.go | 62 ++++++ .../dashboard/agent_sandbox_warnings.test.js | 12 +- src/pkg/dashboard/api_agent_config.go | 43 +++- src/pkg/dashboard/api_agent_sandbox_fields.go | 197 ++++++++++++++++++ .../api_agent_sandbox_fields_test.go | 163 +++++++++++++++ src/pkg/dashboard/api_agent_sandbox_toggle.go | 2 +- src/pkg/dashboard/api_config_review.go | 87 +++++++- src/pkg/dashboard/api_governor_security.go | 20 +- .../dashboard/api_perspectives_source_test.go | 141 +++++++++++++ .../dashboard/config_sandbox_source.test.js | 91 ++++++++ .../static-src/css/config-dialog.css | 4 + .../dashboard/static-src/js/agent-cards.js | 12 +- .../dashboard/static-src/js/config-agent.js | 3 +- .../static-src/js/config-features.js | 6 +- .../static-src/js/config-sandbox-source.js | 161 ++++++++++++++ .../static-src/js/config-watchdog-security.js | 3 +- src/pkg/dashboard/static-src/manifest.txt | 1 + src/pkg/dashboard/static/index.html | 189 ++++++++++++++++- 22 files changed, 1189 insertions(+), 29 deletions(-) create mode 100644 changelog.d/added-18797-perspectives-source-and-sandbox-dashboard.md create mode 100644 src/pkg/config/save_perspectives_sandbox_test.go create mode 100644 src/pkg/dashboard/api_agent_sandbox_fields.go create mode 100644 src/pkg/dashboard/api_agent_sandbox_fields_test.go create mode 100644 src/pkg/dashboard/api_perspectives_source_test.go create mode 100644 src/pkg/dashboard/config_sandbox_source.test.js create mode 100644 src/pkg/dashboard/static-src/js/config-sandbox-source.js diff --git a/changelog.d/added-18797-perspectives-source-and-sandbox-dashboard.md b/changelog.d/added-18797-perspectives-source-and-sandbox-dashboard.md new file mode 100644 index 0000000000..370edd4240 --- /dev/null +++ b/changelog.d/added-18797-perspectives-source-and-sandbox-dashboard.md @@ -0,0 +1 @@ +- **Dashboard and API: link review perspectives to a repo file and set up an agent sandbox without editing config files (#18797).** Review Gate has owner, repo, path and ref fields with the resolver status and an Unlink button; `PUT /api/config/review` accepts `perspectives_source` (set, and `null` to clear), gated like `definition_source` by `GitHubPromptAllowed` with an error that points to Settings, Security, Prompt sources, and re-resolves the set in the same request, so no restart is needed. The 409 for inline perspective edits now names Unlink. An agent's General tab gains editable sandbox image, runtime and Job fields and a "Copy sandbox settings from..." action (Secret names only, never values); `PUT /api/config/agent//general` takes `sandboxImage`, `sandboxRuntime`, `sandboxJob` and `sandboxCopyFrom`; Settings, Security gains `agent_sandbox.job.env_from_secrets`. Saving an enabled sandbox with no image anywhere is refused with `sandbox.image` named, and the "no sandbox image" warning links to the controls that fix it. diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 9b030fe5a8..2648df2559 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -408,6 +408,10 @@ is refused at the tier the non-conversational half requires. For prompt file resolution and the complete built-in `${VAR}` reference, see [Policy and prompt templates](../policies/README.md). +### Sandbox settings (`agents..sandbox`) + +An agent's `sandbox` block (image, runtime, Job fields) is editable from its General tab under "Sandbox settings: image, runtime and Job", and through `PUT /api/config/agent//general` with `sandboxImage`, `sandboxRuntime`, `sandboxJob` and `sandboxCopyFrom` (hivecommons/hive#18797). A blank value inherits the hive-wide `agent_sandbox` default, which is set under Settings, Security. "Copy sandbox settings from..." copies another agent's complete block, Secret names included and never values. Enabling a sandbox that resolves no image is refused with the field named. The full set of controls and keys is in [sandbox-isolation.md](sandbox-isolation.md#setting-up-a-sandbox-from-the-dashboard). + ### Declarative extensions Three optional blocks replace hardcoded behavior with declarations: diff --git a/src/docs/review-swarm.md b/src/docs/review-swarm.md index c579e8a7ad..37013386de 100644 --- a/src/docs/review-swarm.md +++ b/src/docs/review-swarm.md @@ -59,8 +59,10 @@ perspectives: - **The source wins; inline is the fallback.** While the source resolves, its set replaces inline `review.perspectives` and `review.perspective_prompts` everywhere the effective set is read (`ReviewConfig.EffectivePerspectives`). Inline values stay in the config and apply whenever nothing resolves. - **Fallback order.** A fetch that has no GitHub client or fails, and a document that is malformed, each keep the last-known-good document for that source. With none cached, the inline set applies, and if that is empty too, the built-ins. A source whose repo is not on the allowlist is ignored outright (logged, nothing fetched or cached) and the inline set applies. A malformed document keeps the last-known-good set and records a warning rather than quietly dropping to the five built-ins. Only a document that parsed cleanly is remembered, so the cache never holds a corrupt set. A fetch is bounded to 8 seconds. - **When it resolves.** Resolution happens at startup, before the first relay install, and again on every config reload. Each time the relay's perspective set is reinstalled, so a verdict naming a removed perspective is refused and an added one is accepted without a restart. Heads waiting on a removed perspective settle rather than stay stuck (#14905). A dashboard edit of the review config keeps the linked set. -- **Same trust gate as `definition_source`.** The source repo must be on the seed-only `variables.security.github_prompt_allowlist`; see [agent-configuration.md](agent-configuration.md#the-trust-boundary-allowlisted-repos-are-seed-only). -- **Dashboard.** Governor → Features → Review Gate → Perspectives shows the linked set (not the inline fallback), a "Linked to owner/repo/path@ref" line, and the resolver's status and any warning. The perspective checkboxes and focus text are read-only and "Add perspective" is hidden, and `PUT /api/config/review` answers 409 for `perspectives` / `perspective_prompts` edits that the next resolve would replace. `combined_perspectives`, `plan_match` and `max_perspectives_per_pr` stay editable. +- **Same trust gate as `definition_source`.** The source repo must be allowed by `GitHubPromptAllowed`: on the seed `variables.security.github_prompt_allowlist`, or approved by an owner under Settings, Security, Prompt sources; see [agent-configuration.md](agent-configuration.md#the-trust-boundary-allowlisted-repos-are-seed-only). +- **Dashboard.** Governor → Features → Review Gate → Perspectives has a "Link perspectives to a repo file" section with `owner`, `repo`, `path` and `ref` fields, so the source never needs a hand edit of the config files (hivecommons/hive#18797). While a source is set the section shows the resolver's status (`github:owner/repo@ref`, `github-cache:owner/repo`, or "not resolved yet") and any warning, plus an **Unlink** button. The perspectives below it show the linked set (not the inline fallback) with a "Linked to owner/repo/path@ref" line; the checkboxes and focus text are read-only and "Add perspective" is hidden. Blank all four fields and save to unlink too. If the linked repo is not approved the section says so and points to Settings, Security, Prompt sources. `combined_perspectives`, `plan_match` and `max_perspectives_per_pr` stay editable. +- **API.** `PUT /api/config/review` accepts `perspectives_source` as `{"owner": "...", "repo": "...", "path": "...", "ref": "..."}` to set it, and `null` (or an object missing `owner`, `repo` or `path`) to clear it. The repo must pass the same gate as `definition_source` (the seed allowlist or an owner approval, see below); otherwise the request is refused with 400 and a message that names the repo and points to Settings, Security, Prompt sources. A successful save re-resolves the source in the same request, so the new set is in effect without a restart, and unlinking drops the linked set at once. `GET /api/config/review` returns `perspectives_source`, `perspectives_linked`, `perspectives_source_status`, `perspectives_source_warning` and `perspectives_source_approved`. While a source is set, `PUT /api/config/review` answers 409 for `perspectives` / `perspective_prompts` edits that the next resolve would replace; the message names the Unlink button. Send `perspectives_source: null` together with the inline edit to unlink and edit in one request. +- **Both config files.** The save writes the same marshalled config to `/data/hive.yaml.runtime` and `/data/hive.yaml.dashboard` through the one `Config.Save` path, so a dashboard or API change to the source is never half-applied. Do not hand-edit either file for this setting. ### Combined perspectives: recommended, opt-in diff --git a/src/docs/sandbox-isolation.md b/src/docs/sandbox-isolation.md index 05776ca992..3b7dba15c8 100644 --- a/src/docs/sandbox-isolation.md +++ b/src/docs/sandbox-isolation.md @@ -193,6 +193,16 @@ A target in another repository is ignored, because the workspace clones the prim **Refusals fail the kick and push nothing.** A closed PR, a fork PR, a PR another agent opened, a PR no hive agent opened, a head that moved since checkout, an unreadable PR or a failed scan all fail the kick with a reason that names the PR. The run record carries the reason, and the audit log gets a `sandbox_target_pr_refused` line with `repo=`, `number=`, `source=` and `reason=`, or the broker's usual `sandbox_broker_rejected`. If the refusal comes after the run, the commits stay in the workspace, and the run record notes them as withheld. +## Setting up a sandbox from the dashboard + +Nothing about a sandbox needs a hand edit of the config files (hivecommons/hive#18797). Everything below saves through the normal config API, which writes both `/data/hive.yaml.runtime` and `/data/hive.yaml.dashboard`. + +- **Hive-wide defaults.** Settings, Security, "Advanced sandbox: default image and Job settings" edits `agent_sandbox.image`, `runtime`, the Job defaults (workspace claim and mount, service account, scheduler name, TTL) and `agent_sandbox.job.env_from_secrets`. The section opens by itself when the sandbox is on and no image is set. API: `PUT /api/config/governor/security` with `agentSandboxImage`, `agentSandboxRuntime`, `agentSandboxJobWorkspaceClaim`, `agentSandboxJobEnvFromSecrets` and the other `agentSandbox*` keys. +- **One agent.** The agent's General tab has "Sandbox settings: image, runtime and Job" with its own `sandbox.image`, `sandbox.runtime` and Job fields. A blank field inherits the hive default, shown as the placeholder. API: `PUT /api/config/agent//general` with `sandboxImage`, `sandboxRuntime` and `sandboxJob` (`workspaceClaim`, `workspaceClaimMount`, `serviceAccount`, `schedulerName`, `ttlSeconds`, `envFromSecrets`). Node selector, tolerations, resources and volumes have no field; they travel with the copy action below and survive an edit. +- **Copy from another agent.** "Copy sandbox settings from..." lists the agents whose block is complete (an image and a usable runtime, plus a workspace claim for `runtime: job`) and copies the block, turning the sandbox on. API: `PUT /api/config/agent//general` with `{"sandboxCopyFrom": ""}`. The copy is deep. The source's `publish.verify` commands are not copied (they are written for the source's repository); the receiving agent keeps its own. +- **Secrets are names only.** `env_from_secrets` holds Kubernetes Secret names. The API refuses anything that is not a valid name (a `KEY=value` pair, for one), so a value can never be written to the config file through these controls. +- **Refused without an image.** Turning the sandbox on, or saving an enabled sandbox, when no image resolves from the agent or `agent_sandbox.image` is refused with 400 and a message naming `sandbox.image` and `agent_sandbox.image`. The "no sandbox image" warning on the agent card and in the General tab links to the agent's Sandbox settings and to the default image controls. + ## Running sandboxed kicks as Kubernetes Jobs `sandbox.runtime: job` runs an agent's sandboxed kicks as a Kubernetes `Job` in the hive's own namespace instead of a rootless Podman container on the hive pod's node ([#6311](https://github.com/hivecommons/hive/issues/6311)). It exists for work that must run in a **different runtime than the hive image** - a different base OS, a heavyweight toolchain, or on **accelerator hardware** reached through a device plugin - while hive stays the orchestrator. diff --git a/src/pkg/config/save_perspectives_sandbox_test.go b/src/pkg/config/save_perspectives_sandbox_test.go new file mode 100644 index 0000000000..e44e7edf70 --- /dev/null +++ b/src/pkg/config/save_perspectives_sandbox_test.go @@ -0,0 +1,62 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// hivecommons/hive#18797: review.perspectives_source and the agent sandbox +// block are set from the dashboard, so one save must leave /data/hive.yaml.runtime +// and /data/hive.yaml.dashboard carrying the same values. A hand edit of one +// file was reverted or resurrected by the other. +func TestSaveKeepsRuntimeAndDashboardOverlayConsistentForLinkedSettings(t *testing.T) { + dir := t.TempDir() + origOverlay, origRuntime := DashboardOverlayFile, RuntimeConfigFile + DashboardOverlayFile = filepath.Join(dir, "hive.yaml.dashboard") + RuntimeConfigFile = filepath.Join(dir, "hive.yaml.runtime") + t.Cleanup(func() { DashboardOverlayFile, RuntimeConfigFile = origOverlay, origRuntime }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + on := true + cfg := &Config{ + SourcePath: filepath.Join(dir, "hive.yaml"), + Project: ProjectConfig{Org: "testorg"}, + AgentRuntimeConfig: AgentRuntimeConfig{ + Agents: map[string]AgentConfig{"reviewer": {Role: "reviewer", Sandbox: &AgentSandboxOverride{ + Enabled: &on, Image: "registry.example/sbx:1", Runtime: SandboxRuntimeJob, + Job: &SandboxJobConfig{WorkspaceClaim: "hive-data", EnvFromSecrets: []string{"gh-token"}}, + }}}, + AgentSandbox: AgentSandboxConfig{Image: "registry.example/default:1"}, + }, + } + cfg.Review.PerspectivesSource = &DefinitionSourceConfig{Owner: "acme", Repo: "rules", Path: ".hive/p.yaml", Ref: "main"} + if err := cfg.Save(); err != nil { + t.Fatalf("Save: %v", err) + } + + for _, p := range []string{RuntimeConfigFile, DashboardOverlayFile} { + data, err := os.ReadFile(p) + if err != nil { + t.Fatalf("%s not written: %v", p, err) + } + for _, want := range []string{"perspectives_source:", "repo: rules", "registry.example/sbx:1", "registry.example/default:1", "gh-token", "workspace_claim: hive-data"} { + if !strings.Contains(string(data), want) { + t.Errorf("%s is missing %q", p, want) + } + } + } + + // Clearing the source clears it from both files in the same save. + cfg.Review.PerspectivesSource = nil + if err := cfg.Save(); err != nil { + t.Fatalf("Save after unlink: %v", err) + } + for _, p := range []string{RuntimeConfigFile, DashboardOverlayFile} { + data, _ := os.ReadFile(p) + if strings.Contains(string(data), "perspectives_source") { + t.Errorf("%s still carries perspectives_source after an unlink", p) + } + } +} diff --git a/src/pkg/dashboard/agent_sandbox_warnings.test.js b/src/pkg/dashboard/agent_sandbox_warnings.test.js index 4c5b8dc18d..c161d1b31f 100644 --- a/src/pkg/dashboard/agent_sandbox_warnings.test.js +++ b/src/pkg/dashboard/agent_sandbox_warnings.test.js @@ -8,7 +8,9 @@ const src = fs.readFileSync(path.join(__dirname, 'static-src', 'js', 'agent-card const m = src.match(/function agentSandboxWarningsHtml\(a\) \{[\s\S]*?\n \}\n/); assert.ok(m, 'agentSandboxWarningsHtml not found'); const esc = s => String(s).replace(/&/g, '&').replace(/ { const html = agentSandboxWarningsHtml({ sandbox_warnings: ['operator missing', 'no '] }); @@ -27,3 +29,11 @@ test('shipped index.html carries the card hook', () => { const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); assert.ok(html.includes('${agentSandboxWarningsHtml(a)}')); }); + +test('the no-sandbox-image warning links to the agent and the default controls (#18797)', () => { + const html = agentSandboxWarningsHtml({ name: 'reviewer', sandbox_warnings: ['no sandbox image: neither the agent\'s sandbox.image nor agent_sandbox.image is set'] }); + assert.ok(html.includes('data-agent="reviewer"')); + assert.ok(html.includes('data-config-type="agent" data-tab="General"')); + assert.ok(html.includes('data-config-type="governor" data-tab="Security"')); + assert.ok(!agentSandboxWarningsHtml({ name: 'x', sandbox_warnings: ['operator missing'] }).includes('data-action')); +}); diff --git a/src/pkg/dashboard/api_agent_config.go b/src/pkg/dashboard/api_agent_config.go index 3db1f074d1..961dff46c5 100644 --- a/src/pkg/dashboard/api_agent_config.go +++ b/src/pkg/dashboard/api_agent_config.go @@ -192,6 +192,7 @@ func (s *Server) handleAgentConfigGet(w http.ResponseWriter, r *http.Request) { // complete block, and which other agents a block can be copied from. "sandboxDefaultsProblem": agentCfg.SandboxBlockProblem(s.deps.Config.AgentSandbox), "sandboxCopySources": s.sandboxCopySources(name), + "sandboxFields": agentSandboxFieldsView(agentCfg, s.deps.Config.AgentSandbox), "replicas": agentCfg.Replicas, }, "cadences": cadences, @@ -658,14 +659,40 @@ func (s *Server) handleAgentConfigGeneral(w http.ResponseWriter, r *http.Request agentCfg.Aliases = a } } - if v, ok := body["sandboxEnabled"]; ok { - if b, ok := v.(bool); ok { - block, err := s.sandboxBlockForToggle(name, agentCfg, b, sandboxCopyFromBody(body)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - agentCfg.Sandbox = block + // Sandbox block edits (#18525, #18797). Field edits land first unless a + // copy_from is named, so "enable + set the image" in one save sees the + // image; with a copy the copied block is written first and the edits go + // on top of it. A bare sandboxCopyFrom (no sandboxEnabled) copies and + // enables, the dialog's "Copy sandbox settings from" action. + copyFrom := sandboxCopyFromBody(body) + if copyFrom == "" { + if err := applySandboxEdits(&agentCfg, body); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + } + enable, hasToggle := body["sandboxEnabled"].(bool) + if !hasToggle && copyFrom != "" { + enable, hasToggle = true, true + } + if hasToggle { + block, err := s.sandboxBlockForToggle(name, agentCfg, enable, copyFrom) + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + agentCfg.Sandbox = block + } + if copyFrom != "" { + if err := applySandboxEdits(&agentCfg, body); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + } + if sandboxEditsPresent(body) { + if err := sandboxEnabledProblem(name, agentCfg, s.deps.Config.AgentSandbox); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return } } if v, ok := body["sandboxSubstrate"]; ok { diff --git a/src/pkg/dashboard/api_agent_sandbox_fields.go b/src/pkg/dashboard/api_agent_sandbox_fields.go new file mode 100644 index 0000000000..14bddd712e --- /dev/null +++ b/src/pkg/dashboard/api_agent_sandbox_fields.go @@ -0,0 +1,197 @@ +package dashboard + +import ( + "fmt" + "reflect" + "regexp" + "strings" + + "github.com/hivecommons/hive/pkg/config" +) + +// Editable sandbox fields on an agent's General tab (hivecommons/hive#18797). +// Before this the image, runtime and Job fields of an agent's sandbox block +// were config-file-only; the dashboard could only flip enabled. The keys are +// camelCase like the rest of the General section: +// +// sandboxImage string the agent's own sandbox.image ("" inherits agent_sandbox.image) +// sandboxRuntime string the agent's own sandbox.runtime ("" inherits agent_sandbox.runtime) +// sandboxJob object workspaceClaim, workspaceClaimMount, serviceAccount, +// schedulerName, ttlSeconds, envFromSecrets (secret NAMES only) +// sandboxCopyFrom string copy another agent's complete block (see CopiedSandboxBlock) +// +// Node selector, tolerations, resources and volumes are carried by the copy +// action and preserved by an edit, but have no field here. + +// sandboxJobBodyKey is the General-tab body key carrying the Job fields. +const sandboxJobBodyKey = "sandboxJob" + +// sandboxEditKeys are the body keys that change an agent's sandbox block. +var sandboxEditKeys = []string{"sandboxImage", "sandboxRuntime", sandboxJobBodyKey} + +// secretNameRE is a Kubernetes object name (DNS-1123 subdomain). env_from_secrets +// holds names only, so anything else, a KEY=value pair most of all, is refused. +var secretNameRE = regexp.MustCompile(`^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$`) + +// maxSecretNameLen is the Kubernetes object-name length limit. +const maxSecretNameLen = 253 + +// sandboxEditsPresent reports whether body edits the agent's sandbox block. +func sandboxEditsPresent(body map[string]interface{}) bool { + for _, k := range sandboxEditKeys { + if _, ok := body[k]; ok { + return true + } + } + return false +} + +// agentSandboxFieldsView is what the General tab shows for the sandbox block: +// the agent's OWN values (blank means inherited) and what each resolves to. +func agentSandboxFieldsView(a config.AgentConfig, global config.AgentSandboxConfig) map[string]interface{} { + var own config.AgentSandboxOverride + if a.Sandbox != nil { + own = *a.Sandbox + } + job := config.SandboxJobConfig{} + if own.Job != nil { + job = *own.Job + } + return map[string]interface{}{ + "sandboxImage": own.Image, + "sandboxRuntime": own.Runtime, + "sandboxImageEffective": a.SandboxImage(global), + "sandboxRuntimeEffective": a.SandboxRuntime(global), + "sandboxJob": map[string]interface{}{ + "workspaceClaim": job.WorkspaceClaim, + "workspaceClaimMount": job.WorkspaceClaimMount, + "serviceAccount": job.ServiceAccount, + "schedulerName": job.SchedulerName, + "ttlSeconds": job.TTLSeconds, + "envFromSecrets": nonNilStrings(job.EnvFromSecrets), + }, + } +} + +// applySandboxEdits applies the sandboxImage, sandboxRuntime and sandboxJob +// body keys to agentCfg. Every value is validated before agentCfg changes, so +// a refusal leaves the agent untouched. An absent key is left as it is. +func applySandboxEdits(agentCfg *config.AgentConfig, body map[string]interface{}) error { + if !sandboxEditsPresent(body) { + return nil + } + next := &config.AgentSandboxOverride{} + if agentCfg.Sandbox != nil { + cp := *agentCfg.Sandbox + next = &cp + } + if v, ok := body["sandboxImage"]; ok { + img, _ := v.(string) + img = sanitizeString(img) + if strings.ContainsAny(img, " \t\r\n") { + return fmt.Errorf("sandbox.image must not contain whitespace") + } + next.Image = img + } + if v, ok := body["sandboxRuntime"]; ok { + rt, _ := v.(string) + rt = strings.TrimSpace(rt) + if rt != "" && !config.ValidSandboxRuntimes[rt] { + return fmt.Errorf("sandbox.runtime %q is not one hive has (%s, %s, %s or %s)", rt, + config.SandboxRuntimePodman, config.SandboxRuntimeJob, config.SandboxRuntimeOpenShell, config.SandboxRuntimeSubstrate) + } + next.Runtime = rt + } + if v, ok := body[sandboxJobBodyKey]; ok { + m, isObj := v.(map[string]interface{}) + if !isObj && v != nil { + return fmt.Errorf("sandboxJob must be an object") + } + job := config.SandboxJobConfig{} + if next.Job != nil { + job = *next.Job + } + if err := applySandboxJobFields(&job, m); err != nil { + return err + } + if reflect.DeepEqual(job, config.SandboxJobConfig{}) { + next.Job = nil + } else { + next.Job = &job + } + } + agentCfg.Sandbox = next + return nil +} + +// applySandboxJobFields applies the editable Job keys present in m to job. +func applySandboxJobFields(job *config.SandboxJobConfig, m map[string]interface{}) error { + for _, f := range []struct { + key string + dst *string + }{ + {"workspaceClaim", &job.WorkspaceClaim}, + {"workspaceClaimMount", &job.WorkspaceClaimMount}, + {"serviceAccount", &job.ServiceAccount}, + {"schedulerName", &job.SchedulerName}, + } { + if v, ok := m[f.key]; ok { + s, _ := v.(string) + *f.dst = sanitizeString(s) + } + } + if v, ok := m["ttlSeconds"]; ok { + n, isNum := v.(float64) + if !isNum || n < 0 || n != float64(int(n)) { + return fmt.Errorf("sandbox.job.ttl_seconds must be a whole number >= 0") + } + job.TTLSeconds = int(n) + } + if v, ok := m["envFromSecrets"]; ok { + names, err := secretNamesFromBody(v) + if err != nil { + return err + } + job.EnvFromSecrets = names + } + return nil +} + +// secretNamesFromBody validates a list of Kubernetes Secret names. The block +// references secrets by name; a value pasted here would be written to the +// config file, so anything that is not a name is refused. +func secretNamesFromBody(v interface{}) ([]string, error) { + if v == nil { + return nil, nil + } + arr, ok := v.([]interface{}) + if !ok { + return nil, fmt.Errorf("sandbox.job.env_from_secrets must be a list of secret names") + } + var out []string + for _, item := range arr { + s, _ := item.(string) + s = strings.TrimSpace(s) + if s == "" { + continue + } + if len(s) > maxSecretNameLen || !secretNameRE.MatchString(s) { + return nil, fmt.Errorf("sandbox.job.env_from_secrets takes Secret names, not values: %q is not a valid name", s) + } + out = append(out, s) + } + return out, nil +} + +// sandboxEnabledProblem refuses an enabled block that cannot run, naming the +// field: the same check the toggle makes, applied after field edits so +// clearing an image cannot leave an enabled agent with none. +func sandboxEnabledProblem(name string, a config.AgentConfig, global config.AgentSandboxConfig) error { + if a.Sandbox == nil || a.Sandbox.Enabled == nil || !*a.Sandbox.Enabled { + return nil + } + if problem := a.SandboxBlockProblem(global); problem != "" { + return fmt.Errorf("cannot save %s with its sandbox enabled: %s. Set sandbox.image on the agent, or the agent_sandbox default image in Settings, Security", name, problem) + } + return nil +} diff --git a/src/pkg/dashboard/api_agent_sandbox_fields_test.go b/src/pkg/dashboard/api_agent_sandbox_fields_test.go new file mode 100644 index 0000000000..362f4c10bb --- /dev/null +++ b/src/pkg/dashboard/api_agent_sandbox_fields_test.go @@ -0,0 +1,163 @@ +package dashboard + +import ( + "net/http" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// hivecommons/hive#18797: an agent's sandbox image, runtime and Job fields are +// editable through the General section, and a block can be copied without the +// toggle. + +func completeBlock() *config.AgentSandboxOverride { + return &config.AgentSandboxOverride{ + Image: "spyre-img", Runtime: "job", + Job: &config.SandboxJobConfig{WorkspaceClaim: "hive-data", ServiceAccount: "sbx", EnvFromSecrets: []string{"gh-token"}, TTLSeconds: 300}, + } +} + +func TestSandboxFieldsEditable(t *testing.T) { + s, deps := apiServer(t) + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{ + "sandboxImage": "registry.example/sbx:2", "sandboxRuntime": "job", + "sandboxJob": map[string]any{"workspaceClaim": "hive-data", "serviceAccount": "sbx", "ttlSeconds": 600, "envFromSecrets": []string{"gh-token", " llm-key "}}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("PUT = %d: %s", rec.Code, rec.Body.String()) + } + got := deps.Config.Agents["scanner"].Sandbox + if got == nil || got.Image != "registry.example/sbx:2" || got.Runtime != "job" || got.Job == nil || + got.Job.WorkspaceClaim != "hive-data" || got.Job.ServiceAccount != "sbx" || got.Job.TTLSeconds != 600 || + strings.Join(got.Job.EnvFromSecrets, ",") != "gh-token,llm-key" { + t.Fatalf("fields not stored: %#v", got) + } + if got.Enabled != nil && *got.Enabled { + t.Fatal("editing fields must not enable the sandbox") + } + view := decodeJSON(t, doGet(s, "/api/config/agent/scanner")) + fields, _ := view["general"].(map[string]any)["sandboxFields"].(map[string]any) + if fields["sandboxImage"] != "registry.example/sbx:2" || fields["sandboxRuntimeEffective"] != "job" { + t.Fatalf("GET sandboxFields = %v", fields) + } + // Blank values clear back to inherit, and an empty Job is dropped. + rec = doPut(s, "/api/config/agent/scanner/general", map[string]any{ + "sandboxImage": "", "sandboxRuntime": "", + "sandboxJob": map[string]any{"workspaceClaim": "", "serviceAccount": "", "ttlSeconds": 0, "envFromSecrets": []string{}}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("clear PUT = %d: %s", rec.Code, rec.Body.String()) + } + got = deps.Config.Agents["scanner"].Sandbox + if got.Image != "" || got.Runtime != "" || got.Job != nil { + t.Fatalf("not cleared: %#v", got) + } +} + +func TestSandboxFieldValidation(t *testing.T) { + s, deps := apiServer(t) + for name, body := range map[string]map[string]any{ + "runtime": {"sandboxRuntime": "docker"}, + "image ws": {"sandboxImage": "a b"}, + "ttl": {"sandboxJob": map[string]any{"ttlSeconds": -1}}, + "secret val": {"sandboxJob": map[string]any{"envFromSecrets": []string{"TOKEN=abc123"}}}, + "job shape": {"sandboxJob": "x"}, + } { + rec := doPut(s, "/api/config/agent/scanner/general", body) + if rec.Code != http.StatusBadRequest { + t.Errorf("%s: PUT = %d, want 400: %s", name, rec.Code, rec.Body.String()) + } + } + if deps.Config.Agents["scanner"].Sandbox != nil { + t.Fatalf("a refused edit wrote a block: %#v", deps.Config.Agents["scanner"].Sandbox) + } +} + +func TestSandboxEnabledWithoutImageRefusedNamingField(t *testing.T) { + s, deps := apiServer(t) + on := true + sc := deps.Config.Agents["scanner"] + sc.Sandbox = &config.AgentSandboxOverride{Enabled: &on, Image: "img", Runtime: "podman"} + deps.Config.Agents["scanner"] = sc + // Clearing the only image of an enabled sandbox is refused. + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"sandboxImage": ""}) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "sandbox.image") { + t.Fatalf("PUT = %d %s, want 400 naming sandbox.image", rec.Code, rec.Body.String()) + } + if deps.Config.Agents["scanner"].Sandbox.Image != "img" { + t.Fatal("refused edit changed the image") + } + // Enabling and supplying the image in one save works. + deps.Config.Agents["fresh"] = config.AgentConfig{Backend: "claude"} + rec = doPut(s, "/api/config/agent/fresh/general", map[string]any{"sandboxEnabled": true, "sandboxImage": "img2"}) + if rec.Code != http.StatusOK { + t.Fatalf("enable + image = %d: %s", rec.Code, rec.Body.String()) + } + if b := deps.Config.Agents["fresh"].Sandbox; b == nil || b.Image != "img2" || b.Enabled == nil || !*b.Enabled { + t.Fatalf("block = %#v", b) + } +} + +func TestSandboxCopyWithoutToggleClearsWarning(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Agents["deps"] = config.AgentConfig{Backend: "claude", Sandbox: completeBlock()} + before := decodeJSON(t, doGet(s, "/api/config/agent/scanner"))["general"].(map[string]any) + if p, _ := before["sandboxDefaultsProblem"].(string); !strings.Contains(p, "no sandbox image") { + t.Fatalf("precondition: sandboxDefaultsProblem = %v", before["sandboxDefaultsProblem"]) + } + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"sandboxCopyFrom": "deps"}) + if rec.Code != http.StatusOK { + t.Fatalf("copy PUT = %d: %s", rec.Code, rec.Body.String()) + } + got := deps.Config.Agents["scanner"].Sandbox + if got == nil || got.Image != "spyre-img" || got.Runtime != "job" || got.Job == nil || got.Job.ServiceAccount != "sbx" || + strings.Join(got.Job.EnvFromSecrets, ",") != "gh-token" || got.Enabled == nil || !*got.Enabled { + t.Fatalf("block not copied and enabled: %#v", got) + } + // The copy is deep: editing the receiver must not touch the source. + got.Job.EnvFromSecrets[0] = "changed" + if deps.Config.Agents["deps"].Sandbox.Job.EnvFromSecrets[0] != "gh-token" { + t.Fatal("copy aliases the source's secret list") + } + after := decodeJSON(t, doGet(s, "/api/config/agent/scanner"))["general"].(map[string]any) + if p, _ := after["sandboxDefaultsProblem"].(string); p != "" { + t.Fatalf("warning not cleared: %q", p) + } +} + +func TestSandboxCopySourcesOnlyListCompleteBlocks(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Agents["deps"] = config.AgentConfig{Backend: "claude", Sandbox: completeBlock()} + deps.Config.Agents["noimage"] = config.AgentConfig{Backend: "claude", Sandbox: &config.AgentSandboxOverride{Runtime: "podman"}} + deps.Config.Agents["nojobclaim"] = config.AgentConfig{Backend: "claude", Sandbox: &config.AgentSandboxOverride{Image: "i", Runtime: "job"}} + general := decodeJSON(t, doGet(s, "/api/config/agent/scanner"))["general"].(map[string]any) + sources, _ := general["sandboxCopySources"].([]any) + if len(sources) != 1 || sources[0] != "deps" { + t.Fatalf("sandboxCopySources = %v, want [deps]", sources) + } +} + +func TestSecuritySectionSetsDefaultSandboxImageAndJobSecrets(t *testing.T) { + s, deps := apiServer(t) + rec := doPut(s, "/api/config/governor/security", map[string]any{ + "agentSandboxImage": "registry.example/default:1", "agentSandboxRuntime": "job", + "agentSandboxJobWorkspaceClaim": "hive-data", "agentSandboxJobEnvFromSecrets": []string{"gh-token"}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("PUT = %d: %s", rec.Code, rec.Body.String()) + } + g := deps.Config.AgentSandbox + if g.Image != "registry.example/default:1" || g.Job == nil || strings.Join(g.Job.EnvFromSecrets, ",") != "gh-token" { + t.Fatalf("default not stored: %#v", g) + } + // With the default set, an agent's toggle no longer needs a copy source. + if rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"sandboxEnabled": true}); rec.Code != http.StatusOK { + t.Fatalf("toggle after default = %d: %s", rec.Code, rec.Body.String()) + } + rec = doPut(s, "/api/config/governor/security", map[string]any{"agentSandboxJobEnvFromSecrets": []string{"KEY=value"}}) + if rec.Code != http.StatusBadRequest { + t.Fatalf("secret value accepted: %d %s", rec.Code, rec.Body.String()) + } +} diff --git a/src/pkg/dashboard/api_agent_sandbox_toggle.go b/src/pkg/dashboard/api_agent_sandbox_toggle.go index 30e5491bce..718713b73a 100644 --- a/src/pkg/dashboard/api_agent_sandbox_toggle.go +++ b/src/pkg/dashboard/api_agent_sandbox_toggle.go @@ -89,7 +89,7 @@ func (s *Server) sandboxBlockForToggle(name string, agentCfg config.AgentConfig, return config.CopiedSandboxBlock(&src, global, keep), nil } if problem := agentCfg.SandboxBlockProblem(global); problem != "" { - msg := fmt.Sprintf("cannot run %s in a sandbox: %s. Set the agent_sandbox defaults (Governor → Security), or pass copy_from naming an agent with a complete sandbox block", name, problem) + msg := fmt.Sprintf("cannot run %s in a sandbox: %s. Set the default sandbox image in Settings, Security, or set sandbox.image on this agent, or pass copy_from naming an agent with a complete sandbox block", name, problem) if sources := s.sandboxCopySources(name); len(sources) > 0 { msg += " (candidates: " + strings.Join(sources, ", ") + ")" } else { diff --git a/src/pkg/dashboard/api_config_review.go b/src/pkg/dashboard/api_config_review.go index 3a4306da90..0484bc6a70 100644 --- a/src/pkg/dashboard/api_config_review.go +++ b/src/pkg/dashboard/api_config_review.go @@ -1,6 +1,8 @@ package dashboard import ( + "encoding/json" + "fmt" "net/http" "net/url" "sort" @@ -52,6 +54,11 @@ type reviewSection struct { PerspectivesSourceWarning string `json:"perspectives_source_warning,omitempty"` // PerspectivesSourceURL is the GitHub blob URL of the linked document. PerspectivesSourceURL string `json:"perspectives_source_url,omitempty"` + // PerspectivesSourceApproved reports whether the linked repo passes + // GitHubPromptAllowed (seed allowlist or owner approval). False while + // linked means the resolver will refuse to fetch it, so the dialog says so + // and points at Settings, Security, Prompt sources (#18797). + PerspectivesSourceApproved bool `json:"perspectives_source_approved"` } // perspectivesSourceStatusUnresolved marks a set source with no resolved set. @@ -113,6 +120,7 @@ func reviewSectionResponse(cfg *config.Config) reviewSection { if src := rc.PerspectivesSource; src.IsSet() { out.PerspectivesLinked = true out.PerspectivesSourceURL = perspectivesSourceURL(*src) + out.PerspectivesSourceApproved = cfg != nil && cfg.GitHubPromptAllowed(src.Slug()) out.PerspectivesSourceStatus = perspectivesSourceStatusUnresolved if lp := rc.LinkedPerspectives; lp != nil { if lp.Source != "" { @@ -214,7 +222,11 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { // perspective is only valid once its prompt exists, so validating one // without the other would reject a correct pair sent in two requests. // The dialog always sends both when it sends either. - Perspectives *[]string `json:"perspectives"` + Perspectives *[]string `json:"perspectives"` + // PerspectivesSource links the perspective set to a repo file + // (hivecommons/hive#18797). A JSON object sets it, null (or an object + // missing owner, repo or path) clears it, an absent key leaves it. + PerspectivesSource json.RawMessage `json:"perspectives_source"` PerspectivePrompts *map[string]string `json:"perspective_prompts"` CombinedPerspectives *bool `json:"combined_perspectives"` // ReviseRepos / ReviseVerdictsBefore drive the reviewer's revisit @@ -275,14 +287,26 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { return } + // perspectives_source is parsed and gated before anything is mutated. + newSource, sourceChange, srcErr := s.parsePerspectivesSourceBody(body.PerspectivesSource) + if srcErr != nil { + jsonError(w, srcErr.msg, srcErr.status) + return + } + linkedAfter := s.deps.Config.Review.PerspectivesSource.IsSet() + if sourceChange { + linkedAfter = newSource.IsSet() + } + // A linked perspective set is owned by its repo file: an inline edit // would be saved and then silently replaced by the next reload, so it is // refused before anything is mutated. The operator-owned review knobs // (combined_perspectives, plan_match, max_perspectives_per_pr) stay - // editable (hivecommons/hive#17989). - if src := s.deps.Config.Review.PerspectivesSource; src.IsSet() && (body.Perspectives != nil || body.PerspectivePrompts != nil) { + // editable (hivecommons/hive#17989). Unlinking in the same request lifts + // the refusal. + if src := s.deps.Config.Review.PerspectivesSource; linkedAfter && src.IsSet() && (body.Perspectives != nil || body.PerspectivePrompts != nil) { jsonError(w, "review perspectives are linked to "+perspectivesSourceLabel(*src)+ - "; change them in that file, or remove review.perspectives_source to edit them here", http.StatusConflict) + "; change them in that file, or use Unlink in Review Gate (or send perspectives_source: null) to edit them here", http.StatusConflict) return } @@ -520,6 +544,12 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { cfg.Review.PerspectivePrompts = cleaned } } + if sourceChange { + cfg.Review.PerspectivesSource = newSource + if newSource == nil { + cfg.Review.LinkedPerspectives = nil + } + } if body.CombinedPerspectives != nil { cfg.Review.CombinedPerspectives = *body.CombinedPerspectives } @@ -702,3 +732,52 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { s.refreshAndPersist() okResponse(w, map[string]string{"status": "updated"}) } + +// perspectivesSourceError is a refusal from parsePerspectivesSourceBody. +type perspectivesSourceError struct { + msg string + status int +} + +// promptSourcesSettingsPath is where an owner approves a repo as a prompt +// and definition source. +const promptSourcesSettingsPath = "Settings, Security, Prompt sources" + +// parsePerspectivesSourceBody validates the perspectives_source request value +// like an agent's definition_source: an object missing owner, repo or path +// counts as unset (a clear), and a set source must name a repo that +// GitHubPromptAllowed accepts (seed allowlist or owner approval). changed is +// false when the key was absent. The returned source is nil for a clear. +func (s *Server) parsePerspectivesSourceBody(raw json.RawMessage) (src *config.DefinitionSourceConfig, changed bool, perr *perspectivesSourceError) { + if len(raw) == 0 { + return nil, false, nil + } + var in struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + Path string `json:"path"` + Ref string `json:"ref"` + } + if string(raw) == "null" { + return nil, true, nil + } + if err := json.Unmarshal(raw, &in); err != nil { + return nil, false, &perspectivesSourceError{"perspectives_source must be an object with owner, repo, path and optional ref, or null to unlink", http.StatusBadRequest} + } + ds := &config.DefinitionSourceConfig{ + Type: "github", + Owner: sanitizeString(in.Owner), + Repo: sanitizeString(in.Repo), + Path: strings.TrimLeft(sanitizeString(in.Path), "/"), + Ref: sanitizeString(in.Ref), + } + if !ds.IsSet() { + return nil, true, nil + } + if !s.deps.Config.GitHubPromptAllowed(ds.Slug()) { + return nil, false, &perspectivesSourceError{fmt.Sprintf( + "perspectives_source: repo %q is not approved as a prompt source. An owner can approve it under %s, or add it to github_prompt_allowlist on the config volume", + ds.Slug(), promptSourcesSettingsPath), http.StatusBadRequest} + } + return ds, true, nil +} diff --git a/src/pkg/dashboard/api_governor_security.go b/src/pkg/dashboard/api_governor_security.go index 99889a117c..bb48eac5de 100644 --- a/src/pkg/dashboard/api_governor_security.go +++ b/src/pkg/dashboard/api_governor_security.go @@ -56,6 +56,7 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) SandboxJobTTLSeconds *int `json:"agentSandboxJobTtlSeconds"` SandboxJobWorkspaceClaim *string `json:"agentSandboxJobWorkspaceClaim"` SandboxJobClaimMount *string `json:"agentSandboxJobWorkspaceClaimMount"` + SandboxJobEnvFromSecrets *[]string `json:"agentSandboxJobEnvFromSecrets"` SandboxSubstrate *config.SandboxSubstrateConfig `json:"agentSandboxSubstrate"` // Sentinel (suspicious-activity alerts) is pointer-typed per field // so an absent key means "unchanged" — a save that only toggled a @@ -222,6 +223,19 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) } cfg.AgentSandbox.Runtime = v } + var envFromSecrets []string + if body.SandboxJobEnvFromSecrets != nil { + raw := make([]interface{}, 0, len(*body.SandboxJobEnvFromSecrets)) + for _, n := range *body.SandboxJobEnvFromSecrets { + raw = append(raw, n) + } + names, err := secretNamesFromBody(raw) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + envFromSecrets = names + } if body.SandboxTimeoutS != nil && *body.SandboxTimeoutS < 0 || body.SandboxJobTTLSeconds != nil && *body.SandboxJobTTLSeconds < 0 { http.Error(w, "sandbox timeouts must be >= 0", http.StatusBadRequest) return @@ -245,7 +259,7 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) cfg.AgentSandbox.TimeoutS = *body.SandboxTimeoutS } if body.SandboxJobServiceAccount != nil || body.SandboxJobSchedulerName != nil || body.SandboxJobTTLSeconds != nil || - body.SandboxJobWorkspaceClaim != nil || body.SandboxJobClaimMount != nil { + body.SandboxJobWorkspaceClaim != nil || body.SandboxJobClaimMount != nil || body.SandboxJobEnvFromSecrets != nil { if cfg.AgentSandbox.Job == nil { cfg.AgentSandbox.Job = &config.SandboxJobConfig{} } @@ -265,6 +279,9 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) if body.SandboxJobTTLSeconds != nil { job.TTLSeconds = *body.SandboxJobTTLSeconds } + if body.SandboxJobEnvFromSecrets != nil { + job.EnvFromSecrets = envFromSecrets + } } if body.SandboxSubstrate != nil { sub, err := sanitizeSubstrateConfig(*body.SandboxSubstrate) @@ -372,6 +389,7 @@ func securitySectionResponse(cfg *config.Config) map[string]interface{} { "agentSandboxJobTtlSeconds": sandboxJobOrEmpty(cfg).TTLSeconds, "agentSandboxJobWorkspaceClaim": sandboxJobOrEmpty(cfg).WorkspaceClaim, "agentSandboxJobWorkspaceClaimMount": sandboxJobOrEmpty(cfg).WorkspaceClaimMount, + "agentSandboxJobEnvFromSecrets": nonNilStrings(sandboxJobOrEmpty(cfg).EnvFromSecrets), "agentSandboxSubstrate": substrateOrEmpty(cfg.AgentSandbox.Substrate), "sandboxedAgents": sandboxed, "totalAgents": len(cfg.Agents), diff --git a/src/pkg/dashboard/api_perspectives_source_test.go b/src/pkg/dashboard/api_perspectives_source_test.go new file mode 100644 index 0000000000..78ef821cbc --- /dev/null +++ b/src/pkg/dashboard/api_perspectives_source_test.go @@ -0,0 +1,141 @@ +package dashboard + +import ( + "context" + "net/http" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/perspsrc" +) + +// hivecommons/hive#18797: review.perspectives_source is settable and clearable +// through PUT /api/config/review, gated like definition_source. + +const perspectivesDoc = `kind: ReviewPerspectives +perspectives: + - name: security + - name: api-compat + focus: "public API breakage" +` + +type docFetcher struct{ calls int } + +func (f *docFetcher) GetFileContentRef(_ context.Context, _, _, _, _ string) (string, error) { + f.calls++ + return perspectivesDoc, nil +} + +func approveSeedRepo(cfg *config.Config, slug string) { + cfg.Variables.Security.AllowGitHubPrompt = true + cfg.Variables.Security.GitHubPromptAllowlist = []string{slug} +} + +func TestReviewConfigPutSetsAndClearsPerspectivesSource(t *testing.T) { + s := covApiServer(t) + cfg := s.deps.Config + approveSeedRepo(cfg, "acme/rules") + fetcher := &docFetcher{} + resolver := perspsrc.NewResolver(fetcher, cfg.GitHubPromptAllowed, nil) + applied := 0 + // Mirrors the hive's ReviewConfigApplied hook: re-resolve on every save. + s.deps.ReviewConfigApplied = func(config.ReviewConfig) { + applied++ + perspsrc.ApplyToConfig(context.Background(), cfg, resolver, nil) + } + + rec := doPut(s, "/api/config/review", map[string]any{"perspectives_source": map[string]any{ + "owner": "acme", "repo": "rules", "path": "/.hive/p.yaml", "ref": "main", + }}) + if rec.Code != http.StatusOK { + t.Fatalf("set: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + src := cfg.Review.PerspectivesSource + if src == nil || src.Owner != "acme" || src.Repo != "rules" || src.Path != ".hive/p.yaml" || src.Ref != "main" { + t.Fatalf("source not stored (leading slash trimmed): %+v", src) + } + // No restart: the linked set resolved inside the PUT. + if applied != 1 || fetcher.calls != 1 || cfg.Review.LinkedPerspectives == nil { + t.Fatalf("not re-resolved after save: applied=%d fetches=%d linked=%v", applied, fetcher.calls, cfg.Review.LinkedPerspectives) + } + got := decodeJSON(t, doGetNoRole(s, "/api/config/review")) + if got["perspectives_linked"] != true || got["perspectives_source_approved"] != true { + t.Fatalf("GET after set: %v", got) + } + if names, _ := got["perspectives"].([]any); len(names) != 2 || names[1] != "api-compat" { + t.Fatalf("GET perspectives = %v, want the linked set", got["perspectives"]) + } + if !strings.HasPrefix(got["perspectives_source_status"].(string), "github:acme/rules") { + t.Fatalf("status = %v", got["perspectives_source_status"]) + } + + // Inline edits are refused while linked, and the message names Unlink. + rec = doPut(s, "/api/config/review", map[string]any{"perspectives": []string{"security"}}) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "Unlink") { + t.Fatalf("expected 409 pointing at Unlink, got %d: %s", rec.Code, rec.Body.String()) + } + + // null clears the source and the runtime-only linked set with it. + rec = doPut(s, "/api/config/review", map[string]any{"perspectives_source": nil}) + if rec.Code != http.StatusOK { + t.Fatalf("clear: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + if cfg.Review.PerspectivesSource != nil || cfg.Review.LinkedPerspectives != nil { + t.Fatalf("not cleared: %+v", cfg.Review) + } + if rec := doPut(s, "/api/config/review", map[string]any{"perspectives": []string{"security"}}); rec.Code != http.StatusOK { + t.Fatalf("inline edit after unlink: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } +} + +func TestReviewConfigPutPerspectivesSourceUnapprovedRepoIsActionable(t *testing.T) { + s := covApiServer(t) + rec := doPut(s, "/api/config/review", map[string]any{"perspectives_source": map[string]any{ + "owner": "evil", "repo": "rules", "path": "p.yaml", + }}) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String()) + } + for _, want := range []string{"evil/rules", "not approved", "Settings, Security, Prompt sources"} { + if !strings.Contains(rec.Body.String(), want) { + t.Errorf("error %q does not mention %q", rec.Body.String(), want) + } + } + if s.deps.Config.Review.PerspectivesSource != nil { + t.Fatalf("refused PUT stored a source: %+v", s.deps.Config.Review.PerspectivesSource) + } +} + +func TestReviewConfigPutPerspectivesSourceValidation(t *testing.T) { + s := covApiServer(t) + cfg := s.deps.Config + approveSeedRepo(cfg, "acme/rules") + cfg.Review.PerspectivesSource = &config.DefinitionSourceConfig{Owner: "acme", Repo: "rules", Path: "p.yaml"} + + // A source missing owner, repo or path counts as unset, as for definition_source. + rec := doPut(s, "/api/config/review", map[string]any{"perspectives_source": map[string]any{"owner": "acme", "repo": "rules"}}) + if rec.Code != http.StatusOK || cfg.Review.PerspectivesSource != nil { + t.Fatalf("partial source should clear: %d %s %+v", rec.Code, rec.Body.String(), cfg.Review.PerspectivesSource) + } + // A non-object is a 400 and changes nothing. + cfg.Review.PerspectivesSource = &config.DefinitionSourceConfig{Owner: "acme", Repo: "rules", Path: "p.yaml"} + rec = doPut(s, "/api/config/review", map[string]any{"perspectives_source": "acme/rules"}) + if rec.Code != http.StatusBadRequest || cfg.Review.PerspectivesSource == nil { + t.Fatalf("string source: %d %s", rec.Code, rec.Body.String()) + } + // Unlinking and editing inline in one request is allowed. + rec = doPut(s, "/api/config/review", map[string]any{"perspectives_source": nil, "perspectives": []string{"security"}}) + if rec.Code != http.StatusOK || cfg.Review.PerspectivesSource != nil || len(cfg.Review.Perspectives) != 1 { + t.Fatalf("unlink + edit: %d %s", rec.Code, rec.Body.String()) + } +} + +func TestReviewConfigGetFlagsUnapprovedLinkedRepo(t *testing.T) { + s := covApiServer(t) + s.deps.Config.Review.PerspectivesSource = &config.DefinitionSourceConfig{Owner: "acme", Repo: "rules", Path: "p.yaml"} + got := decodeJSON(t, doGetNoRole(s, "/api/config/review")) + if got["perspectives_linked"] != true || got["perspectives_source_approved"] != false { + t.Fatalf("GET = %v, want linked and not approved", got) + } +} diff --git a/src/pkg/dashboard/config_sandbox_source.test.js b/src/pkg/dashboard/config_sandbox_source.test.js new file mode 100644 index 0000000000..88dfc58980 --- /dev/null +++ b/src/pkg/dashboard/config_sandbox_source.test.js @@ -0,0 +1,91 @@ +// Review Gate perspectives_source controls and agent Sandbox settings (#18797). +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const src = fs.readFileSync(path.join(__dirname, 'static-src', 'js', 'config-sandbox-source.js'), 'utf8'); +const esc = s => String(s).replace(/&/g, '&').replace(/ `${k}`; +const names = ['reviewPerspectivesSourceHtml', 'agentSandboxSettingsHtml', 'markDirtySandboxJob', 'markDirtyPerspectivesSource']; + +function load(extra) { + const state = { dirty: {} }; + const markDirty = (section, key, value) => { (state.dirty[section] = state.dirty[section] || {})[key] = value; }; + const inputs = (extra && extra.inputs) || {}; + const document = { getElementById: id => (id in inputs ? { value: inputs[id] } : null) }; + const body = src + '\nreturn {' + names.join(',') + '};'; + const api = new Function('esc', 'yamlHint', 'markDirty', '_configState', 'document', body)(esc, yamlHint, markDirty, { dirty: state.dirty }, document); + return { api, state, markDirty }; +} + +test('unlinked Review Gate shows four fields and no Unlink button', () => { + const { api } = load(); + const html = api.reviewPerspectivesSourceHtml({}, true); + for (const f of ['owner', 'repo', 'path', 'ref']) assert.ok(html.includes(`id="rv-psrc-${f}"`), f); + assert.ok(!html.includes('unlinkReviewPerspectivesSource')); +}); + +test('linked Review Gate shows resolver status, Unlink, and the Prompt sources link when unapproved', () => { + const { api } = load(); + const linked = { perspectives_linked: true, perspectives_source: { owner: 'acme', repo: 'rules', path: 'p.yaml' }, perspectives_source_status: 'github:acme/rules@main', perspectives_source_approved: true }; + let html = api.reviewPerspectivesSourceHtml(linked, true); + assert.ok(html.includes('data-action="unlinkReviewPerspectivesSource"')); + assert.ok(html.includes('github:acme/rules@main')); + assert.ok(!html.includes('not approved')); + html = api.reviewPerspectivesSourceHtml(Object.assign({}, linked, { perspectives_source_approved: false, perspectives_source_status: 'unresolved' }), true); + assert.ok(html.includes('not approved as a prompt source')); + assert.ok(html.includes('Settings, Security, Prompt sources')); + assert.ok(html.includes('data-tab="Security"')); +}); + +test('non-owners get disabled fields and no Unlink', () => { + const { api } = load(); + const html = api.reviewPerspectivesSourceHtml({ perspectives_linked: true, perspectives_source: { owner: 'a', repo: 'b', path: 'c' } }, false); + assert.ok(html.includes(' disabled')); + assert.ok(!html.includes('unlinkReviewPerspectivesSource')); +}); + +test('editing the fields stages an object, blanking all stages null', () => { + let t = load({ inputs: { 'rv-psrc-owner': 'acme', 'rv-psrc-repo': 'rules', 'rv-psrc-path': 'p.yaml', 'rv-psrc-ref': '' } }); + t.api.markDirtyPerspectivesSource(); + assert.deepStrictEqual(t.state.dirty.review.perspectives_source, { owner: 'acme', repo: 'rules', path: 'p.yaml', ref: '' }); + t = load({ inputs: { 'rv-psrc-owner': '', 'rv-psrc-repo': '', 'rv-psrc-path': '', 'rv-psrc-ref': '' } }); + t.api.markDirtyPerspectivesSource(); + assert.strictEqual(t.state.dirty.review.perspectives_source, null); +}); + +test('agent Sandbox settings: fields, warning with links, copy action', () => { + const { api } = load(); + const g = { + sandboxDefaultsProblem: "no sandbox image: neither the agent's sandbox.image nor agent_sandbox.image is set", + sandboxCopySources: ['deps'], + sandboxFields: { sandboxImage: '', sandboxRuntime: '', sandboxRuntimeEffective: 'podman', sandboxImageEffective: '', sandboxJob: { envFromSecrets: ['gh-token'] } }, + }; + const html = api.agentSandboxSettingsHtml(g); + assert.ok(html.includes('id="cfg-agent-sandbox-image"')); + assert.ok(html.includes('id="cfg-agent-sandbox-runtime"')); + assert.ok(html.includes('id="cfg-agent-sandbox-job-workspaceClaim"')); + assert.ok(html.includes('Copy sandbox settings from...')); + assert.ok(html.includes('data-action="copySandboxSettingsFrom"')); + assert.ok(html.includes('')); + assert.ok(html.includes('no sandbox image')); + assert.ok(html.includes('data-config-type="governor" data-tab="Security"')); + assert.ok(html.includes('gh-token')); + // No copy picker when no agent has a complete block. + assert.ok(!api.agentSandboxSettingsHtml({ sandboxCopySources: [], sandboxFields: {} }).includes('copySandboxSettingsFrom')); +}); + +test('Job edits stage as one sandboxJob object with typed values', () => { + const t = load(); + t.api.markDirtySandboxJob('ttlSeconds', '600'); + t.api.markDirtySandboxJob('envFromSecrets', 'a\n b \n'); + t.api.markDirtySandboxJob('serviceAccount', 'sbx'); + assert.deepStrictEqual(t.state.dirty.general.sandboxJob, { ttlSeconds: 600, envFromSecrets: ['a', 'b'], serviceAccount: 'sbx' }); +}); + +test('shipped index.html carries the controls', () => { + const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); + assert.ok(html.includes('${reviewPerspectivesSourceHtml(rv, rvCanEdit)}') || html.includes('reviewPerspectivesSourceHtml(rv, rvCanEdit)')); + assert.ok(html.includes('${agentSandboxSettingsHtml(g)}')); +}); diff --git a/src/pkg/dashboard/static-src/css/config-dialog.css b/src/pkg/dashboard/static-src/css/config-dialog.css index 60aba9b23a..eb993ad05f 100644 --- a/src/pkg/dashboard/static-src/css/config-dialog.css +++ b/src/pkg/dashboard/static-src/css/config-dialog.css @@ -279,6 +279,10 @@ .rv-perspectives-linked { margin: var(--sp-0) var(--sp-0) var(--sp-3); padding: var(--sp-4) var(--sp-5); background: var(--surface); border: 1px solid var(--border); border-radius: var(--r); font-size: var(--fs-sm); } .rv-perspectives-linked-status, .rv-perspectives-linked-warning { margin-top: var(--sp-2); color: var(--muted); } .rv-perspectives-linked-warning { color: var(--yellow); } + .rv-psrc-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); gap: var(--sp-3) var(--sp-5); } + .rv-psrc-actions { margin-top: var(--sp-3); } + .cfg-inline-row { display: flex; gap: var(--sp-3); align-items: center; flex-wrap: wrap; } + .cfg-inline-row select { flex: 1 1 12rem; min-width: 0; } .am-trusted-authors-repos { min-height: 72px; } .am-bot-empty { color: var(--muted); margin: var(--sp-1) 0; } .am-bot-add { display: flex; gap: var(--sp-3); margin-top: var(--sp-4); align-items: center; } diff --git a/src/pkg/dashboard/static-src/js/agent-cards.js b/src/pkg/dashboard/static-src/js/agent-cards.js index f72670ee33..af8d30e9f1 100644 --- a/src/pkg/dashboard/static-src/js/agent-cards.js +++ b/src/pkg/dashboard/static-src/js/agent-cards.js @@ -789,7 +789,17 @@ substrate), computed at boot/reload and carried as sandbox_warnings. */ function agentSandboxWarningsHtml(a) { const ws = a && Array.isArray(a.sandbox_warnings) ? a.sandbox_warnings : []; - return ws.map(w => `
⚠ ${esc(w)}
`).join(''); + return ws.map(w => `
⚠ ${esc(w)}${sandboxImageFixLinksHtml(w, a)}
`).join(''); + } + /* The "no sandbox image" warning is fixed in two places (#18797): this + agent's Sandbox settings, or the hive-wide default under Settings, + Security. Link both instead of describing a manual step. */ + const NO_SANDBOX_IMAGE_WARNING = 'no sandbox image'; + function sandboxImageFixLinksHtml(w, a) { + if (String(w || '').indexOf(NO_SANDBOX_IMAGE_WARNING) === -1) return ''; + const agent = esc((a && a.name) || ''); + return ` Set this agent's image` + + ` Set the default image`; } function agentSandboxRun(a) { return (a && a.sandboxed && a.sandboxRun && a.sandboxRun.health) ? a.sandboxRun : null; diff --git a/src/pkg/dashboard/static-src/js/config-agent.js b/src/pkg/dashboard/static-src/js/config-agent.js index c811e0ef1f..e5fcedd740 100644 --- a/src/pkg/dashboard/static-src/js/config-agent.js +++ b/src/pkg/dashboard/static-src/js/config-agent.js @@ -124,6 +124,7 @@ Run in sandbox ${settingHelpMark('sandbox-isolation', '', 'Run in sandbox', `Opt this agent into the credential-free sandbox runner. Requires the hive-wide sandbox gate in Governor → Security to be enabled. Turning it on writes a complete sandbox block: the agent_sandbox defaults, or a copy of another sandboxed agent's block (its publish.verify commands excluded).`)}${g.sandboxEffective ? ' ' + statusBadgeHTML('ready', 'sandboxed', '', 'done') : ''} ${sandboxSourcePickerHTML(g)} + ${agentSandboxSettingsHtml(g)}
Substrate sandbox overrides ${substrateSandboxFields('general', g.sandboxSubstrate)}
@@ -1467,7 +1468,7 @@ let inner; if (!defaultsOk && sources.length === 0) { inner = ''; + + esc(g.sandboxDefaultsProblem) + '. No agent has a complete sandbox block to copy either: set the default image in Settings, Security first, or set this agent's image under Sandbox settings.'; } else { const opts = (defaultsOk ? '' : '') + sources.map(n => '').join(''); diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 4f7e6b60d5..d93b47e5d7 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -235,10 +235,9 @@ const rvSrcStatus = rv.perspectives_source_status || ''; const rvSrcURL = /^https:\/\/github\.com\//.test(rv.perspectives_source_url || '') ? rv.perspectives_source_url : ''; const rvLinkedBanner = !rvLinked ? '' : `
-
Linked to ${rvSrcURL ? `${esc(rvSrcLabel)} ↗` : `${esc(rvSrcLabel)}`} ${yamlHint('review.perspectives_source')} — read-only here; change the perspectives in that file, or remove the link from hive.yaml to edit them inline.
-
${rvSrcStatus === 'unresolved' ? 'Not resolved yet (repo unreachable, not allowlisted, or invalid) — the inline perspectives below are in effect.' : `Status: ${esc(rvSrcStatus)}`}
- ${rv.perspectives_source_warning ? `
⚠ ${esc(rv.perspectives_source_warning)}
` : ''} +
Linked to ${rvSrcURL ? `${esc(rvSrcLabel)} ↗` : `${esc(rvSrcLabel)}`} ${yamlHint('review.perspectives_source')} — the perspectives below are read-only. Change them in that file, or use Unlink under "Link perspectives to a repo file" to edit them here.
`; + const rvSourceControls = reviewPerspectivesSourceHtml(rv, rvCanEdit); const rvLockAttr = rvLinked ? ' disabled' : ''; const rvPerspectiveRow = (name, defaultFocus) => { const custom = rvPrompts[name] || ''; @@ -500,6 +499,7 @@

Which questions the reviewer asks of every PR, and what each one looks for. Edit the text to tell this hive's reviewer what matters in your repos — e.g. name the conventions doc for style. Blank means the built-in. Unchecking a perspective stops it running and stops its verdicts being accepted.

+ ${rvSourceControls} ${rvLinkedBanner} ${rvBuiltin.map(b => rvPerspectiveRow(b.name, b.focus)).join('')} ${rvCustomNames.map(n => rvPerspectiveRow(n, '')).join('')} diff --git a/src/pkg/dashboard/static-src/js/config-sandbox-source.js b/src/pkg/dashboard/static-src/js/config-sandbox-source.js new file mode 100644 index 0000000000..3671e670a2 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/config-sandbox-source.js @@ -0,0 +1,161 @@ + // ── Review Gate: linked perspectives + agent sandbox settings (#18797) ── + // Both used to be hand edits of the config files on the PVC. The Review + // Gate fields save through PUT /api/config/review (perspectives_source); + // the agent Sandbox fields through the agent General section. + + const PERSPECTIVES_SOURCE_FIELDS = ['owner', 'repo', 'path', 'ref']; + const SANDBOX_RUNTIME_CHOICES = ['podman', 'job', 'openshell', 'substrate']; + + function reviewSourceFieldHtml(field, label, value, placeholder, canEdit) { + return `
` + + `
`; + } + + /* The link controls and the resolver status. Shown whether or not a source + is set: an unlinked hive links here, a linked one relinks or unlinks. */ + function reviewPerspectivesSourceHtml(rv, canEdit) { + rv = rv || {}; + const src = rv.perspectives_source || {}; + const linked = rv.perspectives_linked === true; + const status = rv.perspectives_source_status || ''; + const warning = rv.perspectives_source_warning || ''; + const approved = rv.perspectives_source_approved !== false; + const securityLink = 'Settings, Security, Prompt sources'; + let statusHtml = ''; + if (linked && status === 'unresolved') { + statusHtml = '
Not resolved yet. The repo may be unreachable, the file invalid, or the repo not approved. The inline perspectives below are in effect.
'; + } else if (linked) { + statusHtml = `
Resolved from ${esc(status)}
`; + } + const approvalHtml = linked && !approved + ? `` + : ''; + const warningHtml = warning ? `
⚠ ${esc(warning)}
` : ''; + const unlink = linked && canEdit + ? '' + : ''; + return `
+ Link perspectives to a repo file ${yamlHint('review.perspectives_source')} +

Read the perspective names and focus text from a file in a GitHub repo, so a merged change there applies without editing this hive. The repo must be approved under ${securityLink}.

+
+ ${reviewSourceFieldHtml('owner', 'Owner', src.owner, 'org or user', canEdit)} + ${reviewSourceFieldHtml('repo', 'Repo', src.repo, 'repo name', canEdit)} + ${reviewSourceFieldHtml('path', 'Path', src.path, '.hive/perspectives.yaml', canEdit)} + ${reviewSourceFieldHtml('ref', 'Ref (optional)', src.ref, 'branch, tag or SHA; default branch if blank', canEdit)} +
+
${unlink}
+ ${statusHtml}${approvalHtml}${warningHtml} +
`; + } + + /* Reads the four inputs. Blank owner, repo or path clears the link on + save, matching the server, where a partial source counts as unset. */ + function markDirtyPerspectivesSource() { + const val = {}; + PERSPECTIVES_SOURCE_FIELDS.forEach(f => { + const el = document.getElementById('rv-psrc-' + f); + val[f] = el ? el.value.trim() : ''; + }); + const empty = PERSPECTIVES_SOURCE_FIELDS.every(f => !val[f]); + markDirty('review', 'perspectives_source', empty ? null : val); + } + + /* Unlink saves at once, not on the dialog's Save: it is the action the + 409 message sends the operator to, and it must work with the inline + perspective edits still unsaved. */ + async function unlinkReviewPerspectivesSource() { + try { + const res = await fetch('/api/config/review', { + method: 'PUT', headers: _inceptionAuthHeaders(), body: JSON.stringify({ perspectives_source: null }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const fresh = await fetch('/api/config/review'); + if (fresh.ok) _configState.data.review = await fresh.json(); + if (_configState.dirty.review) delete _configState.dirty.review.perspectives_source; + showToast('Perspectives unlinked. They are editable here now.', 'success'); + renderConfigTab('Features'); + } catch (err) { + showToast('Failed to unlink perspectives: ' + err.message, 'error'); + } + } + + // ── Agent sandbox settings ────────────────────────────────────────── + + function sandboxFieldHtml(label, id, value, placeholder, onchange) { + return `
` + + `
`; + } + + function sandboxJobFieldHtml(label, key, value, placeholder) { + return sandboxFieldHtml(label, 'cfg-agent-sandbox-job-' + key, value, placeholder, + `data-change-action="markDirtySandboxJob" data-arg0="${key}" data-arg-types="s,v"`); + } + + /* Image, runtime and Job fields of this agent's own sandbox block. A blank + field inherits the hive default (Settings, Security), shown as the + placeholder; the warning names the field and links to the controls. */ + function agentSandboxSettingsHtml(g) { + g = g || {}; + const f = g.sandboxFields || {}; + const job = f.sandboxJob || {}; + const sources = Array.isArray(g.sandboxCopySources) ? g.sandboxCopySources : []; + const problem = g.sandboxDefaultsProblem || ''; + const defaultLink = 'Set the default image in Settings, Security'; + const problemHtml = problem + ? `` + : ''; + const runtimeOpts = [''] + .concat(SANDBOX_RUNTIME_CHOICES.map(r => ``)).join(''); + const copyHtml = sources.length + ? `
+
+
+
Copies the image, runtime and Job settings, including Secret names. No secret values are stored in a sandbox block. This agent's publish checks are kept. Turns the sandbox on for this agent.
` + : ''; + return `
+ Sandbox settings: image, runtime and Job + ${problemHtml} + ${copyHtml} + ${sandboxFieldHtml('Image ' + yamlHint('sandbox.image'), 'cfg-agent-sandbox-image', f.sandboxImage, f.sandboxImageEffective ? 'inherits ' + f.sandboxImageEffective : 'container image', 'data-change-action="markDirty" data-arg0="general" data-arg1="sandboxImage" data-arg-types="s,s,v"')} +
+
+ ${sandboxJobFieldHtml('Job workspace claim ' + yamlHint('sandbox.job.workspace_claim'), 'workspaceClaim', job.workspaceClaim, 'PersistentVolumeClaim name (runtime job)')} + ${sandboxJobFieldHtml('Job workspace claim mount', 'workspaceClaimMount', job.workspaceClaimMount, 'mount path')} + ${sandboxJobFieldHtml('Job service account', 'serviceAccount', job.serviceAccount, 'service account name')} + ${sandboxJobFieldHtml('Job scheduler name', 'schedulerName', job.schedulerName, 'cluster default')} + ${sandboxJobFieldHtml('Job TTL (seconds)', 'ttlSeconds', job.ttlSeconds || '', '0 uses the default')} +
+ +
Secret names only. Never paste a value.
+
`; + } + + function markDirtySandboxJob(key, value) { + let v = value; + if (key === 'ttlSeconds') v = value === '' || value == null ? 0 : Number(value); + if (key === 'envFromSecrets') v = String(value || '').split('\n').map(s => s.trim()).filter(Boolean); + const prev = (_configState.dirty.general || {}).sandboxJob || {}; + markDirty('general', 'sandboxJob', Object.assign({}, prev, { [key]: v })); + } + + /* Copies the chosen agent's complete block into this agent at once, then + reloads the dialog so the fields and the warning show the result. */ + async function copySandboxSettingsFrom() { + const sel = document.getElementById('cfg-agent-sandbox-copy'); + const agent = _configState.agent; + if (!sel || !sel.value || !agent) return; + try { + const res = await fetch('/api/config/agent/' + encodeURIComponent(agent) + '/general', { + method: 'PUT', headers: _inceptionAuthHeaders(), body: JSON.stringify({ sandboxCopyFrom: sel.value }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + await loadConfigData('agent', agent); + if (_configState.dirty.general) { + ['sandboxImage', 'sandboxRuntime', 'sandboxJob', 'sandboxCopyFrom', 'sandboxEnabled'].forEach(k => { delete _configState.dirty.general[k]; }); + } + showToast('Sandbox settings copied from ' + sel.value, 'success'); + renderConfigTab('General'); + } catch (err) { + showToast('Failed to copy sandbox settings: ' + err.message, 'error'); + } + } diff --git a/src/pkg/dashboard/static-src/js/config-watchdog-security.js b/src/pkg/dashboard/static-src/js/config-watchdog-security.js index f542d0e2f4..244ba01d26 100644 --- a/src/pkg/dashboard/static-src/js/config-watchdog-security.js +++ b/src/pkg/dashboard/static-src/js/config-watchdog-security.js @@ -978,7 +978,7 @@

Per-agent opt-in lives on each agent's General tab. Current effective posture: ${Number(sec.sandboxedAgents || 0)}/${Number(sec.totalAgents || 0)} agents sandboxed.

${isolationWarning} -
Advanced sandbox +
Advanced sandbox: default image and Job settings
@@ -988,6 +988,7 @@
+
Substrate sandbox diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 01a3625203..899353908a 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -178,6 +178,7 @@ js/config-workflows-ingest-sources.js js/config-workflows-marketplace.js js/config-watchdog-security.js js/config-features.js +js/config-sandbox-source.js js/integration-execution-settings.js js/config-event-triggers.js js/config-sentinel.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 16c30b01fe..ecb4ea388d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -4844,6 +4844,10 @@ .rv-perspectives-linked { margin: var(--sp-0) var(--sp-0) var(--sp-3); padding: var(--sp-4) var(--sp-5); background: var(--surface); border: 1px solid var(--border); border-radius: var(--r); font-size: var(--fs-sm); } .rv-perspectives-linked-status, .rv-perspectives-linked-warning { margin-top: var(--sp-2); color: var(--muted); } .rv-perspectives-linked-warning { color: var(--yellow); } + .rv-psrc-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); gap: var(--sp-3) var(--sp-5); } + .rv-psrc-actions { margin-top: var(--sp-3); } + .cfg-inline-row { display: flex; gap: var(--sp-3); align-items: center; flex-wrap: wrap; } + .cfg-inline-row select { flex: 1 1 12rem; min-width: 0; } .am-trusted-authors-repos { min-height: 72px; } .am-bot-empty { color: var(--muted); margin: var(--sp-1) 0; } .am-bot-add { display: flex; gap: var(--sp-3); margin-top: var(--sp-4); align-items: center; } @@ -32279,7 +32283,17 @@

All labels

substrate), computed at boot/reload and carried as sandbox_warnings. */ function agentSandboxWarningsHtml(a) { const ws = a && Array.isArray(a.sandbox_warnings) ? a.sandbox_warnings : []; - return ws.map(w => `
⚠ ${esc(w)}
`).join(''); + return ws.map(w => `
⚠ ${esc(w)}${sandboxImageFixLinksHtml(w, a)}
`).join(''); + } + /* The "no sandbox image" warning is fixed in two places (#18797): this + agent's Sandbox settings, or the hive-wide default under Settings, + Security. Link both instead of describing a manual step. */ + const NO_SANDBOX_IMAGE_WARNING = 'no sandbox image'; + function sandboxImageFixLinksHtml(w, a) { + if (String(w || '').indexOf(NO_SANDBOX_IMAGE_WARNING) === -1) return ''; + const agent = esc((a && a.name) || ''); + return ` Set this agent's image` + + ` Set the default image`; } function agentSandboxRun(a) { return (a && a.sandboxed && a.sandboxRun && a.sandboxRun.health) ? a.sandboxRun : null; @@ -68166,6 +68180,7 @@

Hub settings

Run in sandbox ${settingHelpMark('sandbox-isolation', '', 'Run in sandbox', `Opt this agent into the credential-free sandbox runner. Requires the hive-wide sandbox gate in Governor → Security to be enabled. Turning it on writes a complete sandbox block: the agent_sandbox defaults, or a copy of another sandboxed agent's block (its publish.verify commands excluded).`)}${g.sandboxEffective ? ' ' + statusBadgeHTML('ready', 'sandboxed', '', 'done') : ''} ${sandboxSourcePickerHTML(g)} + ${agentSandboxSettingsHtml(g)}
Substrate sandbox overrides ${substrateSandboxFields('general', g.sandboxSubstrate)}
@@ -69509,7 +69524,7 @@

Hub settings

let inner; if (!defaultsOk && sources.length === 0) { inner = ''; + + esc(g.sandboxDefaultsProblem) + '. No agent has a complete sandbox block to copy either: set the default image in Settings, Security first, or set this agent's image under Sandbox settings.'; } else { const opts = (defaultsOk ? '' : '') + sources.map(n => '').join(''); @@ -76207,7 +76222,7 @@

Escalation Breaker

Per-agent opt-in lives on each agent's General tab. Current effective posture: ${Number(sec.sandboxedAgents || 0)}/${Number(sec.totalAgents || 0)} agents sandboxed.

${isolationWarning} -
Advanced sandbox +
Advanced sandbox: default image and Job settings
@@ -76217,6 +76232,7 @@

Escalation Breaker

+
Substrate sandbox @@ -76936,10 +76952,9 @@

${esc(s.title)}

const rvSrcStatus = rv.perspectives_source_status || ''; const rvSrcURL = /^https:\/\/github\.com\//.test(rv.perspectives_source_url || '') ? rv.perspectives_source_url : ''; const rvLinkedBanner = !rvLinked ? '' : `
-
Linked to ${rvSrcURL ? `${esc(rvSrcLabel)} ↗` : `${esc(rvSrcLabel)}`} ${yamlHint('review.perspectives_source')} — read-only here; change the perspectives in that file, or remove the link from hive.yaml to edit them inline.
-
${rvSrcStatus === 'unresolved' ? 'Not resolved yet (repo unreachable, not allowlisted, or invalid) — the inline perspectives below are in effect.' : `Status: ${esc(rvSrcStatus)}`}
- ${rv.perspectives_source_warning ? `
⚠ ${esc(rv.perspectives_source_warning)}
` : ''} +
Linked to ${rvSrcURL ? `${esc(rvSrcLabel)} ↗` : `${esc(rvSrcLabel)}`} ${yamlHint('review.perspectives_source')} — the perspectives below are read-only. Change them in that file, or use Unlink under "Link perspectives to a repo file" to edit them here.
`; + const rvSourceControls = reviewPerspectivesSourceHtml(rv, rvCanEdit); const rvLockAttr = rvLinked ? ' disabled' : ''; const rvPerspectiveRow = (name, defaultFocus) => { const custom = rvPrompts[name] || ''; @@ -77201,6 +77216,7 @@

${esc(s.title)}

Which questions the reviewer asks of every PR, and what each one looks for. Edit the text to tell this hive's reviewer what matters in your repos — e.g. name the conventions doc for style. Blank means the built-in. Unchecking a perspective stops it running and stops its verdicts being accepted.

+ ${rvSourceControls} ${rvLinkedBanner} ${rvBuiltin.map(b => rvPerspectiveRow(b.name, b.focus)).join('')} ${rvCustomNames.map(n => rvPerspectiveRow(n, '')).join('')} @@ -78003,6 +78019,167 @@

${esc(s.title)}

`)}`; } + // ── Review Gate: linked perspectives + agent sandbox settings (#18797) ── + // Both used to be hand edits of the config files on the PVC. The Review + // Gate fields save through PUT /api/config/review (perspectives_source); + // the agent Sandbox fields through the agent General section. + + const PERSPECTIVES_SOURCE_FIELDS = ['owner', 'repo', 'path', 'ref']; + const SANDBOX_RUNTIME_CHOICES = ['podman', 'job', 'openshell', 'substrate']; + + function reviewSourceFieldHtml(field, label, value, placeholder, canEdit) { + return `
` + + `
`; + } + + /* The link controls and the resolver status. Shown whether or not a source + is set: an unlinked hive links here, a linked one relinks or unlinks. */ + function reviewPerspectivesSourceHtml(rv, canEdit) { + rv = rv || {}; + const src = rv.perspectives_source || {}; + const linked = rv.perspectives_linked === true; + const status = rv.perspectives_source_status || ''; + const warning = rv.perspectives_source_warning || ''; + const approved = rv.perspectives_source_approved !== false; + const securityLink = 'Settings, Security, Prompt sources'; + let statusHtml = ''; + if (linked && status === 'unresolved') { + statusHtml = '
Not resolved yet. The repo may be unreachable, the file invalid, or the repo not approved. The inline perspectives below are in effect.
'; + } else if (linked) { + statusHtml = `
Resolved from ${esc(status)}
`; + } + const approvalHtml = linked && !approved + ? `` + : ''; + const warningHtml = warning ? `
⚠ ${esc(warning)}
` : ''; + const unlink = linked && canEdit + ? '' + : ''; + return `
+ Link perspectives to a repo file ${yamlHint('review.perspectives_source')} +

Read the perspective names and focus text from a file in a GitHub repo, so a merged change there applies without editing this hive. The repo must be approved under ${securityLink}.

+
+ ${reviewSourceFieldHtml('owner', 'Owner', src.owner, 'org or user', canEdit)} + ${reviewSourceFieldHtml('repo', 'Repo', src.repo, 'repo name', canEdit)} + ${reviewSourceFieldHtml('path', 'Path', src.path, '.hive/perspectives.yaml', canEdit)} + ${reviewSourceFieldHtml('ref', 'Ref (optional)', src.ref, 'branch, tag or SHA; default branch if blank', canEdit)} +
+
${unlink}
+ ${statusHtml}${approvalHtml}${warningHtml} +
`; + } + + /* Reads the four inputs. Blank owner, repo or path clears the link on + save, matching the server, where a partial source counts as unset. */ + function markDirtyPerspectivesSource() { + const val = {}; + PERSPECTIVES_SOURCE_FIELDS.forEach(f => { + const el = document.getElementById('rv-psrc-' + f); + val[f] = el ? el.value.trim() : ''; + }); + const empty = PERSPECTIVES_SOURCE_FIELDS.every(f => !val[f]); + markDirty('review', 'perspectives_source', empty ? null : val); + } + + /* Unlink saves at once, not on the dialog's Save: it is the action the + 409 message sends the operator to, and it must work with the inline + perspective edits still unsaved. */ + async function unlinkReviewPerspectivesSource() { + try { + const res = await fetch('/api/config/review', { + method: 'PUT', headers: _inceptionAuthHeaders(), body: JSON.stringify({ perspectives_source: null }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const fresh = await fetch('/api/config/review'); + if (fresh.ok) _configState.data.review = await fresh.json(); + if (_configState.dirty.review) delete _configState.dirty.review.perspectives_source; + showToast('Perspectives unlinked. They are editable here now.', 'success'); + renderConfigTab('Features'); + } catch (err) { + showToast('Failed to unlink perspectives: ' + err.message, 'error'); + } + } + + // ── Agent sandbox settings ────────────────────────────────────────── + + function sandboxFieldHtml(label, id, value, placeholder, onchange) { + return `
` + + `
`; + } + + function sandboxJobFieldHtml(label, key, value, placeholder) { + return sandboxFieldHtml(label, 'cfg-agent-sandbox-job-' + key, value, placeholder, + `data-change-action="markDirtySandboxJob" data-arg0="${key}" data-arg-types="s,v"`); + } + + /* Image, runtime and Job fields of this agent's own sandbox block. A blank + field inherits the hive default (Settings, Security), shown as the + placeholder; the warning names the field and links to the controls. */ + function agentSandboxSettingsHtml(g) { + g = g || {}; + const f = g.sandboxFields || {}; + const job = f.sandboxJob || {}; + const sources = Array.isArray(g.sandboxCopySources) ? g.sandboxCopySources : []; + const problem = g.sandboxDefaultsProblem || ''; + const defaultLink = 'Set the default image in Settings, Security'; + const problemHtml = problem + ? `` + : ''; + const runtimeOpts = [''] + .concat(SANDBOX_RUNTIME_CHOICES.map(r => ``)).join(''); + const copyHtml = sources.length + ? `
+
+
+
Copies the image, runtime and Job settings, including Secret names. No secret values are stored in a sandbox block. This agent's publish checks are kept. Turns the sandbox on for this agent.
` + : ''; + return `
+ Sandbox settings: image, runtime and Job + ${problemHtml} + ${copyHtml} + ${sandboxFieldHtml('Image ' + yamlHint('sandbox.image'), 'cfg-agent-sandbox-image', f.sandboxImage, f.sandboxImageEffective ? 'inherits ' + f.sandboxImageEffective : 'container image', 'data-change-action="markDirty" data-arg0="general" data-arg1="sandboxImage" data-arg-types="s,s,v"')} +
+
+ ${sandboxJobFieldHtml('Job workspace claim ' + yamlHint('sandbox.job.workspace_claim'), 'workspaceClaim', job.workspaceClaim, 'PersistentVolumeClaim name (runtime job)')} + ${sandboxJobFieldHtml('Job workspace claim mount', 'workspaceClaimMount', job.workspaceClaimMount, 'mount path')} + ${sandboxJobFieldHtml('Job service account', 'serviceAccount', job.serviceAccount, 'service account name')} + ${sandboxJobFieldHtml('Job scheduler name', 'schedulerName', job.schedulerName, 'cluster default')} + ${sandboxJobFieldHtml('Job TTL (seconds)', 'ttlSeconds', job.ttlSeconds || '', '0 uses the default')} +
+ +
Secret names only. Never paste a value.
+
`; + } + + function markDirtySandboxJob(key, value) { + let v = value; + if (key === 'ttlSeconds') v = value === '' || value == null ? 0 : Number(value); + if (key === 'envFromSecrets') v = String(value || '').split('\n').map(s => s.trim()).filter(Boolean); + const prev = (_configState.dirty.general || {}).sandboxJob || {}; + markDirty('general', 'sandboxJob', Object.assign({}, prev, { [key]: v })); + } + + /* Copies the chosen agent's complete block into this agent at once, then + reloads the dialog so the fields and the warning show the result. */ + async function copySandboxSettingsFrom() { + const sel = document.getElementById('cfg-agent-sandbox-copy'); + const agent = _configState.agent; + if (!sel || !sel.value || !agent) return; + try { + const res = await fetch('/api/config/agent/' + encodeURIComponent(agent) + '/general', { + method: 'PUT', headers: _inceptionAuthHeaders(), body: JSON.stringify({ sandboxCopyFrom: sel.value }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + await loadConfigData('agent', agent); + if (_configState.dirty.general) { + ['sandboxImage', 'sandboxRuntime', 'sandboxJob', 'sandboxCopyFrom', 'sandboxEnabled'].forEach(k => { delete _configState.dirty.general[k]; }); + } + showToast('Sandbox settings copied from ' + sel.value, 'success'); + renderConfigTab('General'); + } catch (err) { + showToast('Failed to copy sandbox settings: ' + err.message, 'error'); + } + } async function prepareIntegrationExecutionIdentity() { const target = document.getElementById('integration-execution-identity'); if (!target) return; From 2c61920c495ca5f547a5a1928520def1582d0c5b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 17 Nov 2026 13:14:10 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=90=9B=20Fix=20unescaped=20apostrophe?= =?UTF-8?q?=20in=20sandbox=20picker=20hint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/static-src/js/config-agent.js | 2 +- src/pkg/dashboard/static/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pkg/dashboard/static-src/js/config-agent.js b/src/pkg/dashboard/static-src/js/config-agent.js index e5fcedd740..be397610ff 100644 --- a/src/pkg/dashboard/static-src/js/config-agent.js +++ b/src/pkg/dashboard/static-src/js/config-agent.js @@ -1468,7 +1468,7 @@ let inner; if (!defaultsOk && sources.length === 0) { inner = ''; + + esc(g.sandboxDefaultsProblem) + '. No agent has a complete sandbox block to copy either: set the default image in Settings, Security first, or set the image under Sandbox settings below.'; } else { const opts = (defaultsOk ? '' : '') + sources.map(n => '').join(''); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index ecb4ea388d..4b88259b06 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -69524,7 +69524,7 @@

Hub settings

let inner; if (!defaultsOk && sources.length === 0) { inner = ''; + + esc(g.sandboxDefaultsProblem) + '. No agent has a complete sandbox block to copy either: set the default image in Settings, Security first, or set the image under Sandbox settings below.'; } else { const opts = (defaultsOk ? '' : '') + sources.map(n => '').join(''); From 4c6d4e61a070f53d844806ef959a8cad0cdb86db Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 17 Nov 2026 13:44:01 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=90=9B=20Drop=20settings-parity=20all?= =?UTF-8?q?owlist=20entry=20now=20covered=20by=20the=20Settings=20UI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/settings_parity_allowlist.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 6df5f45cc6..4d422b515d 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -1,7 +1,6 @@ # Current Settings dialog parity gaps. # Every entry must have a Settings control before it is removed. # TODO #11854 -agent_sandbox.job.env_from_secrets[] # TODO #11854 agent_sandbox.job.node_selector. # TODO #11854 agent_sandbox.job.relay_image # TODO #11854 agent_sandbox.job.relay_run_as_user # TODO #11854