From 3ca85d6f18714bf67310a7eccb0877ac2acb0c67 Mon Sep 17 00:00:00 2001 From: Danathar Date: Tue, 10 Nov 2026 09:45:47 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feat(settings):=20set=20per-rep?= =?UTF-8?q?ository=20Sentinel=20paths=20and=20workflow=20fence=20scope=20f?= =?UTF-8?q?rom=20the=20dashboard=20and=20admin=20MCP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #17547 added project.repo_policies[].sentinel_sensitive_paths and workflow_fence_scope, but they could only be set by editing hive.yaml, which a hub-managed hive cannot do. This adds the write surface: - PUT/PATCH /api/config/auto-merge takes contributor_lane.workflow_fence_scope_repos ({owner/repo: "all" | "human_merge_paths" | null}) and PUT /api/config/governor/security takes sentinel.repoSensitivePaths ({owner/repo: [globs] | null}). Per repository: null clears, an absent repository is untouched, the hive-wide value and the policy's other fields never change. Owner only, validated before anything changes (watched repo, the loader's rules plus malformed globs), audited per repository. Requests without the keys behave as before. - Settings gets a per-repository table in Auto Merge and in Security → Suspicious Activity, with help marks; static/index.html regenerated by the manifest concatenation. - auto_merge.update and sentinel.settings take the two keys, send only the changed repositories, name what loosens per repository, remind that a repository without human_merge_paths keeps the full fence, fingerprint what the disclosure read, and refuse a hive whose GET does not report the write as settable. - RepoPolicy.MarshalYAML keeps an explicit empty sentinel_sensitive_paths, which omitempty dropped, so a saved "flag no path" no longer comes back as the hive-wide list after a reload. Refs #17547 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- .../added-repo-policy-overrides-write.md | 1 + src/docs/admin-mcp.md | 35 ++- src/docs/api-reference.md | 4 +- src/docs/api-reference/configuration.md | 4 +- src/docs/design/admin-mcp.md | 7 +- src/docs/hive-merge.md | 15 +- src/docs/operator-reference/README.md | 4 +- .../sweeps-and-operations.md | 2 +- .../adminmcp/tools_automerge_fence_repos.go | 222 +++++++++++++++ src/pkg/adminmcp/tools_automerge_ops.go | 30 +- src/pkg/adminmcp/tools_config_surface_ops.go | 41 ++- .../tools_repo_policy_overrides_write_test.go | 260 ++++++++++++++++++ .../tools_sentinel_repo_paths_write.go | 194 +++++++++++++ .../repo_policy_sentinel_fence_write.go | 210 ++++++++++++++ .../repo_policy_sentinel_fence_write_test.go | 173 ++++++++++++ src/pkg/dashboard/api_config_automerge.go | 81 +++++- src/pkg/dashboard/api_governor_security.go | 74 ++++- .../api_repo_policy_overrides_write_test.go | 227 +++++++++++++++ .../static-src/js/config-features.js | 22 +- .../dashboard/static-src/js/config-helpers.js | 33 ++- .../static-src/js/config-watchdog-security.js | 23 +- src/pkg/dashboard/static/index.html | 78 +++++- 22 files changed, 1701 insertions(+), 39 deletions(-) create mode 100644 changelog.d/added-repo-policy-overrides-write.md create mode 100644 src/pkg/adminmcp/tools_automerge_fence_repos.go create mode 100644 src/pkg/adminmcp/tools_repo_policy_overrides_write_test.go create mode 100644 src/pkg/adminmcp/tools_sentinel_repo_paths_write.go create mode 100644 src/pkg/config/repo_policy_sentinel_fence_write.go create mode 100644 src/pkg/config/repo_policy_sentinel_fence_write_test.go create mode 100644 src/pkg/dashboard/api_repo_policy_overrides_write_test.go diff --git a/changelog.d/added-repo-policy-overrides-write.md b/changelog.d/added-repo-policy-overrides-write.md new file mode 100644 index 0000000000..6931f6eead --- /dev/null +++ b/changelog.d/added-repo-policy-overrides-write.md @@ -0,0 +1 @@ +- **An owner can set, change and clear one repository's Sentinel sensitive-path list and workflow fence scope without editing hive.yaml** (refs #17547). Settings → Features → Auto Merge → **Workflow fence scope per repository** and Settings → Security → Suspicious Activity → **Sensitive files per repository** list every watched repository with its value; choosing the hive-wide value clears the override. The same writes go through `PUT /api/config/auto-merge` (`contributor_lane.workflow_fence_scope_repos`) and `PUT /api/config/governor/security` (`sentinel.repoSensitivePaths`), owner only, as `{owner/repo: value}` maps where `null` clears, and through the admin MCP `auto_merge.update` and `sentinel.settings` operations, whose previews name what loosens in each repository ("workflow edits outside human-merge paths in org/a merge without an owner Approve", "Sentinel stops flagging Justfile in org/a"), remind that a repository with no `human_merge_paths` entry keeps the full fence, and refuse a stale confirm. A write changes only the repositories it names, never the hive-wide value or a policy's other fields, is validated as hive.yaml is (plus malformed globs), and is recorded in the audit log per repository. Requests without the new keys behave as before. An explicit empty per-repository Sentinel list (`[]`, flag no path) now also survives a save; before, the next save wrote it out as unset, so it came back as the hive-wide list. See [hive-merge.md](src/docs/hive-merge.md#contributor-lane-auto-merge). diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index eaaed09cb8..c0ae2fe6d4 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -754,10 +754,16 @@ other role. - `sentinel.settings` changes Sentinel's `sensitive_paths`, `disabled_behaviors`, `exempt_logins` and `trusted_authors_block`. A repository with its own list - (`project.repo_policies[].sentinel_sensitive_paths`, set in hive.yaml) - keeps it: the preview names those repositories and the hive-wide globs - their lists leave out, and does not change them. A per-repository list - added or changed after the preview refuses the confirm. + (`project.repo_policies[].sentinel_sensitive_paths`) keeps it when + `sensitive_paths` changes: the preview names those repositories and the + hive-wide globs their lists leave out. A per-repository list added or + changed after the preview refuses the confirm. +- `sentinel.settings` also sets one repository's own list, with + `repo_sensitive_paths`: `{"owner/repo": [every glob for it]}`. `[]` flags + no path there, and `null` removes the repository's list so it uses the + hive-wide list again. Only the repositories you name change; the + hive-wide list does not. A blank or malformed glob, or a repository that + is not in `project.repos`, is refused. Each list takes a change, not a new list: `{"add": [...], "remove": [...]}`, or `{"clear": true}` to empty it first. For example, to turn reporter trust on @@ -784,7 +790,9 @@ The preview says plainly when a change lets more through: a triage label. - **Fewer pull requests flagged by Sentinel:** sensitive paths removed, a behavior disabled, an exempt login added, or `trusted_authors_block` turned - off. The preview names the pull requests that would no longer be held. + off. The preview names the pull requests that would no longer be held. For + a repository's own list it names the globs per repository, for example + `Sentinel stops flagging Justfile, **/requirements*.txt in org/a`. On a hive managed by a hub, the issue filter preview also says the change may be overwritten. If the hub's record for the hive carries an issue filter, the @@ -809,6 +817,14 @@ only. "trusted_authors": [...]}`; `null` removes it. An enabled exception needs `human_merge_paths` for the repository, set already or in the same change. An unknown field is refused. +- **One repository's workflow fence scope:** + `{"contributor_lane": {"workflow_fence_scope_repos": {"org/a": "human_merge_paths"}}}` + gives `org/a` its own scope (`project.repo_policies[].workflow_fence_scope`, + `all` or `human_merge_paths`); `null` removes it so the repository uses the + hive-wide `workflow_fence_scope` again. The endpoint takes this map per + repository, so the preview sends only the repositories that change; the + hive-wide scope is never changed. A hive too old to take it says so, and + the preview is refused. - **Entries you do not name are kept.** The endpoint replaces each list and map it is sent, so the preview reads the current settings and sends the merged whole value. It shows every change before and after. @@ -822,7 +838,14 @@ only. a pin-only exception on, or giving it more paths, kinds or trusted authors, is widening too, and the preview names what merges as a result, for example "pin bumps (action-sha) to .github/workflows/*.yml in org/a by renovate[bot] - will merge without a hand merge". Removing any of those is not. + will merge without a hand merge". Removing any of those is not. A + repository whose fence scope becomes `human_merge_paths` (its own, or the + hive-wide one after its own is removed) is named: "workflow edits outside + human-merge paths in org/a merge without an owner Approve". The preview + also reminds that a repository with no `human_merge_paths` entry keeps the + full fence, and names the repositories in the change that have none. The + hive-wide scope and the human-merge paths it read are part of the stale + check. - It never merges a pull request. `decisions.delegate_settings` changes the "Let hive decide" settings diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 63fde579bc..9471d1a958 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -216,7 +216,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:269` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | | `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:281` | @@ -227,7 +227,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `PUT` | `/api/config/decisions/delegate` | Owner only | Change `decisions.delegate`: `enabled`, `repos` (the full override map when sent; an entry with `enabled: null` is dropped; a new key must be in `project.repos`), `llm.enabled`, `llm.model` (a model name; a key-like value is refused) and `effect_timeout`. Unknown fields and invalid values are 400 with nothing changed. Saved, audited as `config_decisions_delegate` with the actor and each change before and after, and applied without a restart. Starts no decision and merges nothing | `pkg/dashboard/api_config_decisions_delegate.go` | | `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:294` | | `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:295` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:296` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:296` | | `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:298` | | `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:299` | | `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:314` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 0f0ce7fbd8..a622178d46 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -102,7 +102,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:269` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | @@ -114,7 +114,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/decisions/delegate` | Owner only | Change `decisions.delegate`: `enabled`, `repos` (the full override map when sent; an entry with `enabled: null` is dropped; a new key must be in `project.repos`), `llm.enabled`, `llm.model` (a model name; a key-like value is refused) and `effect_timeout`. Unknown fields and invalid values are 400 with nothing changed. Saved, audited as `config_decisions_delegate` with the actor and each change before and after, and applied without a restart. Starts no decision and merges nothing | `pkg/dashboard/api_config_decisions_delegate.go` | | `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:294` | | `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:295` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:296` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:296` | | `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:298` | | `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:299` | | `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:314` | diff --git a/src/docs/design/admin-mcp.md b/src/docs/design/admin-mcp.md index 0ace0f0865..d9eeba7d4a 100644 --- a/src/docs/design/admin-mcp.md +++ b/src/docs/design/admin-mcp.md @@ -537,7 +537,7 @@ start-up script, its process launch, PIDs, signal handling and exit codes are un | plan propose | `POST /api/plan/from-issue` | **deliberately not owner** — ioscan + ACMM L5 floor | | plan approve / reject | `POST /api/plan/{epicID}/approve`, `.../reject` | `requireOwnerRole` | | feature settings | `PUT /api/config/governor/features` | `requireOwnerRole`; pointer fields, nil means unchanged | -| merge settings | `PATCH /api/config/auto-merge` | `requireOwnerRole` on the read and the write; every list and map is a full replace | +| merge settings | `PATCH /api/config/auto-merge` | `requireOwnerRole` on the read and the write; every list and map is a full replace, except `contributor_lane.workflow_fence_scope_repos`, which is per repository (`null` clears) | | Let hive decide settings | `PUT /api/config/decisions/delegate` | `requireOwnerRole` on the read and the write; `repos` is a full replace, the op sends the merged map | | repository pause / resume | `POST /api/repos/pause`, `/api/repos/resume` | `requireRepoPausePermission` → `canToggleRepoHold` | | item hold | `POST /api/repos/{owner}/{repo}/items/{number}/hold` | `canToggleRepoHold` | @@ -634,7 +634,10 @@ Phase 5 registers the fleet-level write operations under that contract: it read, so a change made between preview and confirm refuses the confirm (`ErrConfirmationStale`) instead of being overwritten. A change that admits more issues without triage, or that makes Sentinel flag fewer pull requests, is disclosed as widening, and the Sentinel - disclosure names the pull requests that would no longer be held. + disclosure names the pull requests that would no longer be held. `sentinel.settings` also + takes `repo_sensitive_paths`, one repository's own list, which the endpoint takes per + repository (`sentinel.repoSensitivePaths`, `null` clears), so the op sends only the + repositories that change. - `auto_merge.update` wraps `PATCH /api/config/auto-merge`, the endpoint behind the dashboard's merge settings. That endpoint replaces every list and map it is sent whole (`squash_only`, `require_current_base`, `human_merge_paths`, the native merge queue's repos and bases, the diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 1122628414..b4bb55f8fa 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -1127,8 +1127,19 @@ A PR merges through this tier only when all of the following hold: repository that has its own. A repository with `human_merge_paths` scope but no `human_merge_paths` entry still keeps the full fence. An invalid value stops the config from loading, and the running hive ignores one - that gets through and uses the hive-wide value. The overrides are set in - hive.yaml; Settings and `settings_read` list them. + that gets through and uses the hive-wide value. + + An owner can set, change and clear either override without editing + hive.yaml. In Settings, use **Workflow fence scope per repository** + (Features → Auto Merge) and **Sensitive files per repository** + (Security → Suspicious Activity); choosing the hive-wide value clears the + override. The same writes go through `PUT /api/config/auto-merge` + (`contributor_lane.workflow_fence_scope_repos`) and + `PUT /api/config/governor/security` (`sentinel.repoSensitivePaths`), or + the admin MCP `auto_merge.update` and `sentinel.settings` operations, + whose previews name what each change loosens in each repository. Each + write changes only the repositories it names, never the hive-wide value, + and is recorded in the audit log. `settings_read` lists the overrides. ```yaml project: diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index ded5ae9837..4aa706afd7 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -273,8 +273,8 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `project.repo_policies[].release_version_source` | Unset (version-file check disabled). | Optional repository-relative text file, for example `VERSION`, read at the proposed release target. Its trimmed value must match the proposed tag; a single leading `v` is ignored on either value. Invalid paths, unreadable content, and mismatches refuse the release while leaving the issue parked. Only used with `release_on_approve: true`. | | `project.repo_policies[].companion_repos` | Unset (no companions). | List of sibling repositories (`name` in the project org, or `org/name`) that this repo's tooling expects checked out beside it under the agent workspace root — for example a docs/website repo a spec tool registers at `///…`. Contributor task prompts and resident-agent kicks carry a shallow-clone plan for each companion at `//` (`$HIVE_WORKSPACE_DIR` for contributor agents, `$HOME/workspace` for resident agents), and agents are told that a tool reporting one of those paths missing means *clone it*, never park the issue. Self-references and malformed entries are dropped. See [running-at-level-6.md](../running-at-level-6.md#needless-parks). | | `project.repo_policies[].max_open_held_prs` | Unset (no cap) for every repo. | Per-repo cap on open hive PRs still waiting on a human ([#13645](https://github.com/hivecommons/hive/issues/13645)). `0` means the default of `12`; a positive number is the cap. At the cap `hive-open-pr` refuses new PRs in that repo and PR-opening agents are told "repo at capacity: review or close existing PRs first". Needs GitHub App auth: under a PAT the cap cannot be enforced and the governor warns once ([#13739](https://github.com/hivecommons/hive/issues/13739)). See [Open held PR cap](v6-controls.md#open-held-pr-cap-max_open_held_prs). | -| `project.repo_policies[].sentinel_sensitive_paths` | Unset: inherits `sentinel.sensitive_paths`. | This repository's own Sentinel sensitive-path list. It replaces the hive-wide list for this repository's pull requests only, so it can be stricter or looser, and a later change to `sentinel.sensitive_paths` does not reach it. An explicit empty list (`[]`) matches nothing, as the hive-wide key does. A blank pattern is rejected when the config loads. Set in hive.yaml; Settings → Security → Suspicious Activity and the admin MCP `sentinel.settings` preview name every repository with its own list. See [Suspicious-activity alerts](sweeps-and-operations.md#suspicious-activity-alerts-sentinel). | -| `project.repo_policies[].workflow_fence_scope` | Unset: inherits `auto_merge.contributor_lane.workflow_fence_scope`. | This repository's own contributor-lane workflow fence scope, `all` or `human_merge_paths`. It can be stricter or looser than the hive-wide value, and a later change to the hive-wide value does not reach it. `human_merge_paths` still keeps the full fence when the repository has no `auto_merge.human_merge_paths` entry. Any other value is rejected when the config loads. Set in hive.yaml; Settings → Features → Auto Merge lists the overrides under **Workflow fence scope**, and `settings_read` section `auto_merge` returns them as `contributor_lane.workflow_fence_scope_repos`. See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | +| `project.repo_policies[].sentinel_sensitive_paths` | Unset: inherits `sentinel.sensitive_paths`. | This repository's own Sentinel sensitive-path list. It replaces the hive-wide list for this repository's pull requests only, so it can be stricter or looser, and a later change to `sentinel.sensitive_paths` does not reach it. An explicit empty list (`[]`) matches nothing, as the hive-wide key does. A blank pattern is rejected when the config loads. Set it in hive.yaml, in Settings → Security → Suspicious Activity → **Sensitive files per repository**, through `PUT /api/config/governor/security` (`sentinel.repoSensitivePaths`, owner only, audited), or with the admin MCP `sentinel.settings` `repo_sensitive_paths`; a blank or malformed glob is refused there, and clearing it returns the repository to the hive-wide list. Settings and the `sentinel.settings` preview name every repository with its own list. See [Suspicious-activity alerts](sweeps-and-operations.md#suspicious-activity-alerts-sentinel). | +| `project.repo_policies[].workflow_fence_scope` | Unset: inherits `auto_merge.contributor_lane.workflow_fence_scope`. | This repository's own contributor-lane workflow fence scope, `all` or `human_merge_paths`. It can be stricter or looser than the hive-wide value, and a later change to the hive-wide value does not reach it. `human_merge_paths` still keeps the full fence when the repository has no `auto_merge.human_merge_paths` entry. Any other value is rejected when the config loads. Set it in hive.yaml, in Settings → Features → Auto Merge → **Workflow fence scope per repository**, through `PUT /api/config/auto-merge` (`contributor_lane.workflow_fence_scope_repos`, owner only, audited), or with the admin MCP `auto_merge.update`; clearing it returns the repository to the hive-wide scope. `settings_read` section `auto_merge` returns the overrides as `contributor_lane.workflow_fence_scope_repos`. See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | | `project.label_driven_approval_labels` | `["triage/accepted"]` | Labels whose trusted addition approves an issue on every label-driven repo without its own list. Ignored by repos without `label_driven: true`. Dashboard: Settings → Repos → "Default approval labels". | | `project.label_driven_trust_org_members` | `true` | Whether a public member of the repo's owning org who applies an approval label is trusted (Prow's own rule). Dashboard: Settings → Repos → "trust public org members". | | `project.label_driven_trusted_bots` | `["kubestellar-prow[bot]"]` | Bot logins whose label additions count as a trusted triager (Prow command bots relaying `/triage accepted`). `github-actions[bot]` is not in the default because it is the shared identity of every workflow in the repo, including ones triggered by untrusted events; operators whose Prow emulation runs as `github-actions[bot]` must add it explicitly per deployment. Dashboard: Settings → Repos → "Trusted bots". | diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index aad55daa6d..ddab7b16c1 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -821,7 +821,7 @@ push re-arms it. | `sentinel.label` | `sentinel-alert` | Label added to untrusted flagged PRs (created red if missing). Neutral on purpose: it means "look closely", not "malicious". This configured label is also added to Hive's hold/exclude set and blocks Hive approval plus every auto-merge lane until a human removes it. | | `sentinel.trusted_authors_block` | `false` | When `false`, trusted author findings are notice-only: comment, audit/dashboard record, no label, no approval/merge block. Set `true` to add the blocking label for trusted authors too. A PR the hive opens to supersede an adopted contributor PR (body line `Supersedes #N (…; original commits by @login preserved).`) is judged by the adopted PR's author, not by the App: its code is that author's, so an untrusted author's flagged head gets the label on the App's PR too. A maintainer who removed the label from the adopted PR at the same head is not asked again; any later head is judged afresh. | | `sentinel.sensitive_paths` | shipped defaults (`sentinel.DefaultSensitivePaths`) | Glob list (same syntax as `intent.guardrail_path_patterns`; `**` crosses directories) that **replaces** the defaults when set. Defaults cover OWNERS/CODEOWNERS/MAINTAINERS, SECURITY.md, GOVERNANCE.md, `.github/workflows/**`, actions, dependabot, codeql, rulesets, CI config, Makefile/Justfile, pre-commit hooks, `policies/**`, `hive.yaml*`, `gh-wrapper*`, proxy rules, Dockerfiles, `install.sh`, dependency manifests and lockfiles, release workflows, `.env*`/key material, `deploy/**`, Terraform, Helm/k8s manifests. | -| `project.repo_policies[].sentinel_sensitive_paths` | unset = `sentinel.sensitive_paths` | One repository's own sensitive-path list. It replaces the hive-wide list for that repository's pull requests only, stricter or looser, and a change to `sentinel.sensitive_paths` does not reach it. `[]` matches nothing. Set in hive.yaml. Like any Sentinel setting, it applies to heads Sentinel evaluates after the change. | +| `project.repo_policies[].sentinel_sensitive_paths` | unset = `sentinel.sensitive_paths` | One repository's own sensitive-path list. It replaces the hive-wide list for that repository's pull requests only, stricter or looser, and a change to `sentinel.sensitive_paths` does not reach it. `[]` matches nothing. Set in hive.yaml, in Settings → Security (**Sensitive files per repository**) or with the admin MCP `sentinel.settings` `repo_sensitive_paths`; clearing it returns the repository to the hive-wide list. Like any Sentinel setting, it applies to heads Sentinel evaluates after the change. | | `sentinel.disabled_behaviors` | empty | Rule names from the table above to switch off. Unknown names are rejected. | | `sentinel.exempt_logins` | empty | GitHub logins never flagged (e.g. a release bot). Use sparingly. | | `sentinel.repos` | empty = all watched repos | Optional `owner/repo` allow-list. | diff --git a/src/pkg/adminmcp/tools_automerge_fence_repos.go b/src/pkg/adminmcp/tools_automerge_fence_repos.go new file mode 100644 index 0000000000..f1e47160b2 --- /dev/null +++ b/src/pkg/adminmcp/tools_automerge_fence_repos.go @@ -0,0 +1,222 @@ +package adminmcp + +import ( + "fmt" + "strings" + + "github.com/hivecommons/hive/pkg/config" +) + +// auto_merge.update's contributor_lane.workflow_fence_scope_repos: one +// repository's own workflow fence scope (project.repo_policies[]. +// workflow_fence_scope). Unlike the other merge settings, the endpoint takes +// it per repository ({"owner/repo": "all" | "human_merge_paths" | null}) and +// leaves repositories it is not sent alone, so the op sends only the +// repositories that change. The hive reports the overrides as a list under +// the same name; the preview reads that list as a repository → scope map. + +const ( + amFenceReposKey = "contributor_lane.workflow_fence_scope_repos" + amFenceSettableKey = "contributor_lane.workflow_fence_scope_repos_settable" + amFenceHiveWideKey = "contributor_lane.workflow_fence_scope" + amFenceHumanPathsKey = "human_merge_paths" +) + +func amFenceReposSchema() map[string]any { + scope := map[string]any{"type": "string", "enum": config.ContributorLaneWorkflowFenceScopes} + return map[string]any{"type": "object", "description": "owner/repo to that repository's own workflow fence scope: all fences every workflow / action edit, human_merge_paths only edits to files in its human_merge_paths. null removes the repository's override so it uses the hive-wide contributor_lane.workflow_fence_scope again. Repositories you do not name keep theirs; the hive-wide value is not changed.", "additionalProperties": map[string]any{"anyOf": []any{scope, map[string]any{"type": "null"}}}} +} + +// amFenceRepoOverrides reads the overrides as the hive reported them, a list +// of {repo, workflow_fence_scope}, or as a map this file built. +func amFenceRepoOverrides(v any) map[string]string { + out := map[string]string{} + switch x := v.(type) { + case map[string]string: + for repo, scope := range x { + out[repo] = scope + } + case []any: + for _, item := range x { + m, _ := item.(map[string]any) + repo, _ := m["repo"].(string) + scope, _ := m["workflow_fence_scope"].(string) + if strings.TrimSpace(repo) != "" && scope != "" { + out[repo] = scope + } + } + } + return out +} + +func amFenceRepoKey(m map[string]string, repo string) (string, bool) { + for k := range m { + if strings.EqualFold(k, repo) { + return k, true + } + } + return "", false +} + +// amFenceReposApply sets or clears the named repositories' scopes on top of +// before and returns every override after the change. +func amFenceReposApply(before, raw any, projectRepos []string) (map[string]string, error) { + change, ok := raw.(map[string]any) + if !ok || len(change) == 0 { + return nil, fmt.Errorf("%s takes {\"owner/repo\": \"all\" | \"human_merge_paths\" | null}", amFenceReposKey) + } + out := amFenceRepoOverrides(before) + touched := map[string]bool{} + for _, key := range SortKeys(change) { + repo := qualifyProjectRepo(strings.TrimSpace(key), projectRepos) + watched := false + for _, full := range projectRepos { + if strings.EqualFold(full, repo) { + repo, watched = full, true + } + } + if !watched { + return nil, fmt.Errorf("%s: %q is not a repository in project.repos", amFenceReposKey, key) + } + if touched[strings.ToLower(repo)] { + return nil, fmt.Errorf("%s names %s twice", amFenceReposKey, repo) + } + touched[strings.ToLower(repo)] = true + existing, has := amFenceRepoKey(out, repo) + if change[key] == nil { + if !has { + return nil, fmt.Errorf("%s: %s has no override to remove; it already uses the hive-wide scope", amFenceReposKey, repo) + } + delete(out, existing) + continue + } + s, _ := change[key].(string) + s = strings.ToLower(strings.TrimSpace(s)) + if s != config.ContributorLaneWorkflowFenceScopeAll && s != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + return nil, fmt.Errorf("%s[%s] must be one of %s, or null to use the hive-wide scope", amFenceReposKey, repo, strings.Join(config.ContributorLaneWorkflowFenceScopes, ", ")) + } + if has { + repo = existing + } + out[repo] = s + } + return out, nil +} + +// amFenceReposPatch is the body the endpoint takes: only the repositories +// whose override changes, null for one that goes back to the hive-wide scope. +func amFenceReposPatch(before, after map[string]string) map[string]any { + patch := map[string]any{} + for repo, scope := range after { + if b, ok := before[repo]; !ok || b != scope { + patch[repo] = scope + } + } + for repo := range before { + if _, ok := after[repo]; !ok { + patch[repo] = nil + } + } + return patch +} + +func amFenceScopeLabel(m map[string]string, repo, hiveWide string) string { + if s, ok := m[repo]; ok { + return s + } + return "hive-wide (" + hiveWide + ")" +} + +func amFenceEffective(m map[string]string, repo, hiveWide string) string { + if s, ok := m[repo]; ok { + return s + } + return hiveWide +} + +// amFenceReposRows is one preview row per repository whose override changes. +func amFenceReposRows(c amPlanned, hiveWide string) []amRow { + before := amFenceRepoOverrides(c.before) + after := amFenceRepoOverrides(c.after) + var rows []amRow + for _, repo := range SortKeys(amFenceReposPatch(before, after)) { + rows = append(rows, amRow{field: c.field.key + "[" + repo + "]", before: amFenceScopeLabel(before, repo, hiveWide), after: amFenceScopeLabel(after, repo, hiveWide)}) + } + return rows +} + +// amFenceReposFinish completes a plan that changes per-repository fence +// scopes: it refuses a hive that cannot take them, names what loosens, adds +// the fail-closed reminder, and adds the hive-wide scope and human-merge paths +// the disclosure was built from to the confirm's fingerprint. A plan without +// that change is returned untouched. +func amFenceReposFinish(plan *amPlan, current map[string]any, beforeValues map[string]any) error { + idx := -1 + for i := range plan.changes { + if plan.changes[i].field.kind == amFenceScopeRepos { + idx = i + } + } + if idx < 0 { + return nil + } + if settable, _ := lookupSetting(current, amFenceSettableKey); settable != true { + return fmt.Errorf("this hive reports %s but cannot set it through the merge settings endpoint (it runs an older build); upgrade it, or set project.repo_policies[].workflow_fence_scope in hive.yaml", amFenceReposKey) + } + hiveWide, _ := lookupSetting(current, amFenceHiveWideKey) + hiveWideScope, _ := hiveWide.(string) + if hiveWideScope == "" { + hiveWideScope = config.ContributorLaneWorkflowFenceScopeAll + } + paths := repoPathsValue(current[amFenceHumanPathsKey]) + if sent, ok := plan.body[amFenceHumanPathsKey]; ok { + paths = repoPathsValue(sent) + } + hasPaths := func(repo string) bool { + for k, patterns := range paths { + if strings.EqualFold(k, repo) && len(patterns) > 0 { + return true + } + } + return false + } + c := &plan.changes[idx] + c.fenceHiveWide = hiveWideScope + before := amFenceRepoOverrides(c.before) + after := amFenceRepoOverrides(c.after) + var named, noPaths []string + for _, repo := range SortKeys(amFenceReposPatch(before, after)) { + named = append(named, repo) + if !hasPaths(repo) { + noPaths = append(noPaths, repo) + } + was, now := amFenceEffective(before, repo, hiveWideScope), amFenceEffective(after, repo, hiveWideScope) + if was == config.ContributorLaneWorkflowFenceScopeHumanMergePaths || now != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + continue + } + note := c.field.key + "[" + repo + "] " + amFenceScopeLabel(before, repo, hiveWideScope) + " → " + amFenceScopeLabel(after, repo, hiveWideScope) + ": workflow edits outside human-merge paths in " + repo + " merge without an owner Approve" + if !hasPaths(repo) { + note += " (" + repo + " has no human_merge_paths entry yet, so it keeps the full fence until one is set)" + } + c.notes = append(c.notes, note) + } + reminder := "A repository whose scope is human_merge_paths but which has no human_merge_paths entry keeps the full fence: every workflow edit there still waits for an owner Approve." + if len(noPaths) > 0 { + reminder += " Of the repositories named here, " + strings.Join(noPaths, ", ") + " " + amFenceHasHave(len(noPaths)) + " no human_merge_paths entry." + } else { + reminder += " Every repository named here has a human_merge_paths entry." + } + plan.effects = append(plan.effects, + "Sets project.repo_policies[].workflow_fence_scope for "+strings.Join(named, ", ")+" only. The hive-wide workflow_fence_scope ("+hiveWideScope+") and every other repository keep their values; a repository set back to null uses the hive-wide scope again.", + reminder) + beforeValues[amFenceHiveWideKey] = hiveWideScope + beforeValues[amFenceHumanPathsKey] = current[amFenceHumanPathsKey] + return nil +} + +func amFenceHasHave(n int) string { + if n == 1 { + return "has" + } + return "have" +} diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go index 63444a6925..00386813b9 100644 --- a/src/pkg/adminmcp/tools_automerge_ops.go +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -54,6 +54,7 @@ const ( amList amRepoPaths amPinOnly + amFenceScopeRepos // per-repository map, sent as a patch (tools_automerge_fence_repos.go) ) // amEntry is how a list's entries are compared. @@ -136,11 +137,14 @@ var autoMergeFields = []amField{ {key: "contributor_lane.auto_promotion_scope", kind: amEnum, enum: config.ContributorLaneAutoPromotionScopes, widen: amWidenScope, why: "merges in every repository count toward automatic promotion"}, {key: "contributor_lane.approve_held_runs_for_registry_trusted", kind: amBool, widen: amWidenOn, why: "the hive approves held workflow runs for registry-trusted authors"}, {key: "contributor_lane.owner_approval_releases_workflow_fence", kind: amBool, widen: amWidenOn, why: "an owner's approval lets the lane merge workflow-file changes"}, + // Widening is named in amFenceReposFinish, which also needs the hive-wide + // scope and the human-merge paths. + {key: amFenceReposKey, kind: amFenceScopeRepos}, } func (autoMergeUpdateOp) Name() string { return WriteOpAutoMergeUpdate } func (autoMergeUpdateOp) Description() string { - return "Change merge settings (auto_merge) through PATCH /api/config/auto-merge, the endpoint the dashboard's merge controls use. Owner only. Pass only what changes, shaped like the endpoint's body. A list takes {\"add\": [...], \"remove\": [...]}; human_merge_paths takes {\"owner/repo\": [every pattern for that repository]}, with null or [] removing that repository. human_merge_pin_only takes {\"owner/repo\": {\"enabled\": true, \"paths\": [...], \"kinds\": [...], \"trusted_authors\": [...]}}, the whole exception for that repository, with null removing it; the repository needs human_merge_paths. The preview reads the current settings and sends each changed list or map whole, keeping every entry you did not name, shows each change before and after, and says which changes let the hive merge more on its own. write_confirm refuses if any of those settings changed after the preview. This operation never merges a pull request." + return "Change merge settings (auto_merge) through PATCH /api/config/auto-merge, the endpoint the dashboard's merge controls use. Owner only. Pass only what changes, shaped like the endpoint's body. A list takes {\"add\": [...], \"remove\": [...]}; human_merge_paths takes {\"owner/repo\": [every pattern for that repository]}, with null or [] removing that repository. human_merge_pin_only takes {\"owner/repo\": {\"enabled\": true, \"paths\": [...], \"kinds\": [...], \"trusted_authors\": [...]}}, the whole exception for that repository, with null removing it; the repository needs human_merge_paths. contributor_lane.workflow_fence_scope_repos takes {\"owner/repo\": \"all\" | \"human_merge_paths\"}, one repository's own workflow fence scope, with null returning it to the hive-wide scope; only the named repositories change. The preview reads the current settings and sends each changed list or map whole, keeping every entry you did not name, shows each change before and after, and says which changes let the hive merge more on its own. write_confirm refuses if any of those settings changed after the preview. This operation never merges a pull request." } func (autoMergeUpdateOp) InputSchema() map[string]any { @@ -175,6 +179,8 @@ func (f *amField) schema() map[string]any { return map[string]any{"type": "string", "description": "A duration such as 3m or 1h30m."} case amEnum: return map[string]any{"type": "string", "enum": f.enum} + case amFenceScopeRepos: + return amFenceReposSchema() case amRepoPaths: return map[string]any{"type": "object", "description": "owner/repo to every glob pattern that repository should hold; null or [] removes the repository. Repositories you do not name are kept.", "additionalProperties": map[string]any{"anyOf": []any{list, map[string]any{"type": "null"}}}} case amPinOnly: @@ -242,6 +248,7 @@ func (autoMergeUpdateOp) PreviewWithProvider(ctx context.Context, args map[strin "This changes which pull requests the merge sweeps may merge from now on. It merges nothing itself.", "write_confirm reads these settings again and refuses if any of them changed after this preview.", } + effects = append(effects, plan.effects...) if len(plan.unchanged) > 0 { effects = append(effects, "Already as requested, so not sent: "+strings.Join(plan.unchanged, ", ")+".") } @@ -282,6 +289,9 @@ type amPlanned struct { before any after any notes []string + // fenceHiveWide is the hive-wide workflow_fence_scope, which a + // per-repository fence scope row names when the repository has none. + fenceHiveWide string } type amPlan struct { @@ -289,6 +299,7 @@ type amPlan struct { unchanged []string body map[string]any fingerprint string + effects []string // extra preview effects a change adds } type amRow struct { @@ -300,6 +311,9 @@ type amRow struct { // per repository that changes, so a preview names repositories as values // rather than as keys. func (c amPlanned) rows() []amRow { + if c.field.kind == amFenceScopeRepos { + return amFenceReposRows(c, c.fenceHiveWide) + } if c.field.kind == amPinOnly { before := autoMergePinOnlyValue(c.before) after, _ := c.after.(map[string]autoMergePinOnlyEntry) @@ -402,6 +416,9 @@ func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Prov if !ok { return amPlan{}, fmt.Errorf("this hive's merge settings do not report %s, so the change cannot be previewed against its current value; the hive may run an older build", f.key) } + if f.kind == amFenceScopeRepos { + before = amFenceRepoOverrides(before) + } after, err := f.apply(before, a.raw, projectRepos) if err != nil { return amPlan{}, err @@ -410,7 +427,11 @@ func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Prov plan.unchanged = append(plan.unchanged, f.key) continue } - setSetting(plan.body, f.key, after) + send := after + if f.kind == amFenceScopeRepos { + send = amFenceReposPatch(amFenceRepoOverrides(before), amFenceRepoOverrides(after)) + } + setSetting(plan.body, f.key, send) beforeValues[f.key] = before plan.changes = append(plan.changes, amPlanned{field: f, before: before, after: after, notes: f.widening(before, after, projectRepos)}) } @@ -420,6 +441,9 @@ func planAutoMergeUpdate(ctx context.Context, args map[string]any, provider Prov if err := autoMergeCheckPinOnlyGuarded(plan, current); err != nil { return amPlan{}, err } + if err := amFenceReposFinish(&plan, current, beforeValues); err != nil { + return amPlan{}, err + } plan.fingerprint = settingsFingerprint(beforeValues) return plan, nil } @@ -519,6 +543,8 @@ func (f *amField) apply(before, raw any, projectRepos []string) (any, error) { return applyRepoPaths(before, raw, projectRepos) case amPinOnly: return autoMergeApplyPinOnly(before, raw, projectRepos) + case amFenceScopeRepos: + return amFenceReposApply(before, raw, projectRepos) default: return f.applyList(before, raw, projectRepos) } diff --git a/src/pkg/adminmcp/tools_config_surface_ops.go b/src/pkg/adminmcp/tools_config_surface_ops.go index 29986f3087..f6d8488e76 100644 --- a/src/pkg/adminmcp/tools_config_surface_ops.go +++ b/src/pkg/adminmcp/tools_config_surface_ops.go @@ -849,6 +849,10 @@ type sentinelState struct { RepoOverrides []sentinelRepoPathsOverride `json:"repo_sensitive_paths"` label string defaultPaths []string + // repoPathsSettable is whether the hive takes repoSensitivePaths on the + // security PUT; projectRepos are its watched owner/repo names. + repoPathsSettable bool + projectRepos []string } // sentinelRepoPathsOverride is one repository's own Sentinel sensitive-path @@ -930,6 +934,8 @@ func readSentinelState(ctx context.Context, provider Provider) (sentinelState, e } } st.RepoOverrides = readSentinelRepoOverrides(sc["repoSensitivePaths"]) + st.repoPathsSettable, _ = boolField(sc, "repoSensitivePathsSettable") + st.projectRepos = stringListValueLoose(m["repos"]) st.label, _ = sc["label"].(string) if strings.TrimSpace(st.label) == "" { st.label = config.DefaultSentinelLabel @@ -951,7 +957,7 @@ func sentinelBehaviorDescriptions() (map[string]string, []string) { func (sentinelSettingsOp) Name() string { return WriteOpSentinelSettings } func (sentinelSettingsOp) Description() string { - return "Change Sentinel's sensitive_paths, disabled_behaviors, exempt_logins and trusted_authors_block through PUT /api/config/governor/security, the endpoint Settings → Security saves through. Each list takes {add, remove, clear}: the preview reads the current lists, shows each before → after and sends the merged list, and write_confirm is refused if the settings changed since the preview. A change that flags fewer pull requests is disclosed as widening and names which pull requests would no longer be held. A repository with its own list (project.repo_policies[].sentinel_sensitive_paths, set in hive.yaml) keeps it: the preview names those repositories and what their lists leave out, and this operation does not change them. Owner only: the endpoint refuses any other role. It removes no label from any pull request." + return "Change Sentinel's sensitive_paths, disabled_behaviors, exempt_logins and trusted_authors_block through PUT /api/config/governor/security, the endpoint Settings → Security saves through. Each list takes {add, remove, clear}: the preview reads the current lists, shows each before → after and sends the merged list, and write_confirm is refused if the settings changed since the preview. A change that flags fewer pull requests is disclosed as widening and names which pull requests would no longer be held. A repository with its own list (project.repo_policies[].sentinel_sensitive_paths) keeps it when sensitive_paths changes: the preview names those repositories and what their lists leave out. repo_sensitive_paths sets or clears one repository's own list: {\"owner/repo\": [every glob for it]}, [] to flag nothing by path there, or null to use the hive-wide list again; only the named repositories change, and a list that flags fewer paths in a repository is disclosed as widening. Owner only: the endpoint refuses any other role. It removes no label from any pull request." } func (sentinelSettingsOp) InputSchema() map[string]any { _, names := sentinelBehaviorDescriptions() @@ -960,6 +966,7 @@ func (sentinelSettingsOp) InputSchema() map[string]any { "disabled_behaviors": listChangeSchema("Sentinel rules switched off (add disables a rule, remove turns it back on). Known rules: " + strings.Join(names, ", ") + "."), "exempt_logins": listChangeSchema("Pull request authors Sentinel never flags (exact login, case-insensitive)."), "trusted_authors_block": map[string]any{"type": "boolean", "description": "Whether a finding on a trusted author's pull request (the Hive App, configured trusted bots, authorized owners) gets the blocking label; off posts an informational notice only."}, + "repo_sensitive_paths": sentinelRepoPathsSchema(), }, "additionalProperties": false} } @@ -983,12 +990,14 @@ type sentinelRequest struct { paths, behaviors, exempt listChange hasPaths, hasBehaviors, hasExempt bool block *bool + // repoPaths are the per-repository lists to set (nil value: clear). + repoPaths map[string]*[]string } func parseSentinelArgs(args map[string]any) (sentinelRequest, error) { const where = "sentinel.settings" var req sentinelRequest - if err := rejectUnknownKeys(args, where, "sensitive_paths", "disabled_behaviors", "exempt_logins", "trusted_authors_block"); err != nil { + if err := rejectUnknownKeys(args, where, "sensitive_paths", "disabled_behaviors", "exempt_logins", "trusted_authors_block", "repo_sensitive_paths"); err != nil { return req, err } var err error @@ -1008,8 +1017,11 @@ func parseSentinelArgs(args map[string]any) (sentinelRequest, error) { } req.block = &b } - if !req.hasPaths && !req.hasBehaviors && !req.hasExempt && req.block == nil { - return req, fmt.Errorf("give at least one of sensitive_paths, disabled_behaviors, exempt_logins or trusted_authors_block") + if req.repoPaths, err = parseSentinelRepoPathsArg(args, where); err != nil { + return req, err + } + if !req.hasPaths && !req.hasBehaviors && !req.hasExempt && req.block == nil && req.repoPaths == nil { + return req, fmt.Errorf("give at least one of sensitive_paths, disabled_behaviors, exempt_logins, trusted_authors_block or repo_sensitive_paths") } if req.hasBehaviors { descriptions, names := sentinelBehaviorDescriptions() @@ -1049,6 +1061,14 @@ func (sentinelSettingsOp) PreviewWithProvider(ctx context.Context, args map[stri var changes []settingChange var notes []string + if req.repoPaths != nil { + repoChanges, repoNotes, err := applySentinelRepoPaths(&after, before, req.repoPaths, sentinelBody) + if err != nil { + return WritePreview{}, err + } + changes = append(changes, repoChanges...) + notes = append(notes, repoNotes...) + } if hasPaths { list, err := paths.apply("sensitive_paths", before.SensitivePaths, foldExact) if err != nil { @@ -1066,8 +1086,8 @@ func (sentinelSettingsOp) PreviewWithProvider(ctx context.Context, args map[stri } else if before.SensitivePathsDefault { notes = append(notes, "sensitive_paths was following the shipped defaults; it is now saved as this explicit list, so globs a later Hive release adds to the defaults will not apply to this hive.") } - if len(before.RepoOverrides) > 0 { - notes = append(notes, "Not changed by this write: "+listLabel(sentinelOverrideRepos(before.RepoOverrides))+" use their own sensitive-path list (hive.yaml repo_policies[].sentinel_sensitive_paths), so the hive-wide sensitive_paths does not apply to them.") + if len(after.RepoOverrides) > 0 { + notes = append(notes, "Not changed by this write: "+listLabel(sentinelOverrideRepos(after.RepoOverrides))+" use their own sensitive-path list (hive.yaml repo_policies[].sentinel_sensitive_paths), so the hive-wide sensitive_paths does not apply to them.") } after.SensitivePaths = effective if !sameList(before.SensitivePaths, effective, foldExact) || before.SensitivePathsDefault != after.SensitivePathsDefault { @@ -1140,9 +1160,12 @@ func sentinelDisclosure(before, after sentinelState, descriptions map[string]str var fewer, more []string pathsAdded, pathsRemoved := listDiff(before.SensitivePaths, after.SensitivePaths, foldExact) where := "" - if len(before.RepoOverrides) > 0 { - where = " (except in " + listLabel(sentinelOverrideRepos(before.RepoOverrides)) + ", which keep their own list)" + if len(after.RepoOverrides) > 0 { + where = " (except in " + listLabel(sentinelOverrideRepos(after.RepoOverrides)) + ", which keep their own list)" } + repoFewer, repoMore := sentinelRepoPathsDisclosure(before, after) + fewer = append(fewer, repoFewer...) + more = append(more, repoMore...) if len(pathsRemoved) > 0 { fewer = append(fewer, "a pull request"+where+" whose only sensitive-path match is "+listLabel(pathsRemoved)+" is no longer flagged by the sensitive_path rule (other rules still look at it)") } @@ -1173,7 +1196,7 @@ func sentinelDisclosure(before, after sentinelState, descriptions map[string]str if len(more) > 0 { moreNote = " Also: " + strings.Join(more, "; ") + "." } - moreNote += sentinelRepoOverrideStanding(before.RepoOverrides, after.SensitivePaths) + moreNote += sentinelRepoOverrideStanding(sentinelRepoOverridesUntouched(before, after), after.SensitivePaths) if len(fewer) > 0 { return "Widening: fewer pull requests flagged by Sentinel, which narrows its protection. " + capitalize(strings.Join(fewer, "; ")) + ". The " + before.label + " label holds a pull request from Hive approval and every auto-merge lane until a maintainer removes it, so these pull requests would no longer be held for a maintainer." + moreNote } diff --git a/src/pkg/adminmcp/tools_repo_policy_overrides_write_test.go b/src/pkg/adminmcp/tools_repo_policy_overrides_write_test.go new file mode 100644 index 0000000000..04a585330c --- /dev/null +++ b/src/pkg/adminmcp/tools_repo_policy_overrides_write_test.go @@ -0,0 +1,260 @@ +package adminmcp + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" +) + +// fenceReposFixture is GET /api/config/auto-merge for a hive whose +// hive-wide fence scope is all, with org/b overriding it and only org/a and +// org/b holding human-merge paths. +func fenceReposFixture() map[string]any { + f := autoMergeFixture() + cl := f["contributor_lane"].(map[string]any) + cl["workflow_fence_scope"] = "all" + cl["workflow_fence_scope_repos"] = []any{map[string]any{"repo": "org/b", "workflow_fence_scope": "human_merge_paths"}} + cl["workflow_fence_scope_repos_settable"] = true + return f +} + +func fenceReposArgs(repos map[string]any) map[string]any { + return map[string]any{"contributor_lane": map[string]any{"workflow_fence_scope_repos": repos}} +} + +// Setting a repository's own scope sends only that repository, names what +// loosens in it, and says which named repositories keep the full fence for +// want of human-merge paths. On v6 tip auto_merge.update refuses the field as +// unsupported. +func TestAutoMergeUpdateSetsRepoFenceScopeAndNamesWidening(t *testing.T) { + p := &autoMergeProvider{settings: fenceReposFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, fenceReposArgs(map[string]any{"a": "human_merge_paths", "org/c": "Human_Merge_Paths"})) + + want := `{"contributor_lane":{"workflow_fence_scope_repos":{"org/a":"human_merge_paths","org/c":"human_merge_paths"}}}` + if got := compactJSON(preview.Request.Body); got != want { + t.Fatalf("body = %s, want %s", got, want) + } + if !strings.HasPrefix(preview.WideningDisclosure, "Widening:") || + !strings.Contains(preview.WideningDisclosure, "workflow edits outside human-merge paths in org/a merge without an owner Approve") || + !strings.Contains(preview.WideningDisclosure, "workflow edits outside human-merge paths in org/c merge without an owner Approve (org/c has no human_merge_paths entry yet, so it keeps the full fence until one is set)") { + t.Fatalf("disclosure = %q", preview.WideningDisclosure) + } + effects := strings.Join(preview.Effects, "\n") + for _, want := range []string{ + "no human_merge_paths entry keeps the full fence", + "Of the repositories named here, org/c has no human_merge_paths entry.", + "The hive-wide workflow_fence_scope (all) and every other repository keep their values", + } { + if !strings.Contains(effects, want) { + t.Fatalf("effects missing %q:\n%s", want, effects) + } + } + if got := compactJSON(preview.Details["changes"]); !strings.Contains(got, `{"after":"human_merge_paths","before":"hive-wide (all)","field":"contributor_lane.workflow_fence_scope_repos[org/a]"}`) { + t.Fatalf("changes = %s", got) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != want { + t.Fatalf("executed %+v", p.requests) + } +} + +// null returns a repository to the hive-wide scope. That narrows when the +// hive-wide scope is all, and widens when it is human_merge_paths. +func TestAutoMergeUpdateClearsRepoFenceScope(t *testing.T) { + p := &autoMergeProvider{settings: fenceReposFixture()} + preview, _ := autoMergePreview(t, autoMergeHandler(p), fenceReposArgs(map[string]any{"org/b": nil})) + if got := compactJSON(preview.Request.Body); got != `{"contributor_lane":{"workflow_fence_scope_repos":{"org/b":null}}}` { + t.Fatalf("body = %s", got) + } + if !strings.HasPrefix(preview.WideningDisclosure, "No widening") { + t.Fatalf("org/b human_merge_paths → hive-wide all is not widening: %q", preview.WideningDisclosure) + } + + f := fenceReposFixture() + cl := f["contributor_lane"].(map[string]any) + cl["workflow_fence_scope"] = "human_merge_paths" + cl["workflow_fence_scope_repos"] = []any{map[string]any{"repo": "org/b", "workflow_fence_scope": "all"}} + preview, _ = autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: f}), fenceReposArgs(map[string]any{"org/b": nil})) + if !strings.Contains(preview.WideningDisclosure, "contributor_lane.workflow_fence_scope_repos[org/b] all → hive-wide (human_merge_paths): workflow edits outside human-merge paths in org/b merge without an owner Approve") { + t.Fatalf("disclosure = %q", preview.WideningDisclosure) + } +} + +func TestAutoMergeUpdateRepoFenceScopeRefusals(t *testing.T) { + for name, tc := range map[string]struct { + settings map[string]any + repos map[string]any + want string + }{ + "unknown scope": {fenceReposFixture(), map[string]any{"org/a": "release_only"}, "must be one of all, human_merge_paths"}, + "unwatched": {fenceReposFixture(), map[string]any{"org/z": "all"}, "is not a repository in project.repos"}, + "clear what is not": {fenceReposFixture(), map[string]any{"org/c": nil}, "has no override to remove"}, + "already so": {fenceReposFixture(), map[string]any{"org/b": "human_merge_paths"}, "nothing would change"}, + "older hive": {func() map[string]any { + f := fenceReposFixture() + delete(f["contributor_lane"].(map[string]any), "workflow_fence_scope_repos_settable") + return f + }(), map[string]any{"org/a": "all"}, "older build"}, + } { + p := &autoMergeProvider{settings: tc.settings} + _, err := autoMergeHandler(p).PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": fenceReposArgs(tc.repos)}) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("%s: err = %v, want %q", name, err, tc.want) + } + } +} + +// The overrides, the hive-wide scope and the human-merge paths the preview +// was built from are all part of its basis: a change to any refuses the +// confirm. +func TestAutoMergeUpdateRepoFenceScopeStalePreview(t *testing.T) { + for name, mutate := range map[string]func(map[string]any){ + "override added": func(s map[string]any) { s["contributor_lane"].(map[string]any)["workflow_fence_scope_repos"] = []any{} }, + "hive-wide changed": func(s map[string]any) { + s["contributor_lane"].(map[string]any)["workflow_fence_scope"] = "human_merge_paths" + }, + "paths changed": func(s map[string]any) { s["human_merge_paths"] = map[string][]string{"org/a": {"CODEOWNERS"}} }, + } { + p := &autoMergeProvider{settings: fenceReposFixture()} + h := autoMergeHandler(p) + _, id := autoMergePreview(t, h, fenceReposArgs(map[string]any{"org/a": "human_merge_paths"})) + mutate(p.settings) + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("%s: confirm err = %v, want ErrConfirmationStale", name, err) + } + if len(p.requests) != 0 { + t.Fatalf("%s: a stale confirm wrote %+v", name, p.requests) + } + } +} + +func TestAutoMergeUpdateRepoFenceScopeRefusesNonOwner(t *testing.T) { + ownerOnly := fmt.Errorf("%w: Hive API returned HTTP 403: owner access required", ErrForbidden) + p := &autoMergeProvider{settings: fenceReposFixture(), readErr: ownerOnly} + _, err := autoMergeHandler(p).PreviewWrite(context.Background(), map[string]any{"operation": WriteOpAutoMergeUpdate, "args": fenceReposArgs(map[string]any{"org/a": "human_merge_paths"})}) + if err == nil || !errors.Is(err, ErrForbidden) { + t.Fatalf("non-owner preview err = %v", err) + } + if len(p.requests) != 0 { + t.Fatalf("wrote without owner access: %+v", p.requests) + } +} + +// ---- sentinel.settings repo_sensitive_paths --------------------------------- + +func sentinelRepoPathsGovernor() map[string]any { + g := surfaceGovernorWithRepoOverrides() + g["repos"] = []string{"acme/api", "acme/website", "acme/docs"} + g["security"].(map[string]any)["sentinel"].(map[string]any)["repoSensitivePathsSettable"] = true + return g +} + +// A per-repository list sends only that repository and names, per repository, +// what Sentinel stops flagging there. On v6 tip sentinel.settings refuses +// repo_sensitive_paths as an unsupported field. +func TestSentinelSettingsSetsRepoSensitivePathsAndNamesWidening(t *testing.T) { + provider := &surfaceProvider{governor: sentinelRepoPathsGovernor()} + h := surfaceHandler(provider) + p, id := capPreview(t, h, WriteOpSentinelSettings, map[string]any{"repo_sensitive_paths": map[string]any{ + "docs": []any{"OWNERS"}, "acme/website": []any{}, + }}) + want := `{"sentinel":{"repoSensitivePaths":{"acme/docs":["OWNERS"],"acme/website":[]}}}` + if got := compactJSON(p.Request.Body); got != want { + t.Fatalf("body = %s, want %s", got, want) + } + for _, want := range []string{ + "Sentinel stops flagging .github/workflows/**, **/.github/workflows/**, hive.yaml in acme/docs", + "Sentinel stops flagging OWNERS in acme/website (its own list is empty, so the sensitive_path rule flags no path there)", + } { + if !strings.HasPrefix(p.WideningDisclosure, "Widening:") || !strings.Contains(p.WideningDisclosure, want) { + t.Fatalf("disclosure missing %q: %q", want, p.WideningDisclosure) + } + } + // acme/api is untouched and still named as already in force where it + // leaves something out; it covers the hive-wide list, so it is not. + if strings.Contains(p.WideningDisclosure, "acme/api") { + t.Fatalf("an untouched repository was named: %q", p.WideningDisclosure) + } + if !strings.Contains(strings.Join(p.Effects, "\n"), "Sets project.repo_policies[].sentinel_sensitive_paths for acme/docs, acme/website only.") { + t.Fatalf("effects = %v", p.Effects) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(provider.requests) != 1 || compactJSON(provider.requests[0].Body) != want { + t.Fatalf("executed %+v", provider.requests) + } +} + +// null clears a repository's list: it goes back to the hive-wide list, which +// flags more there, so it is not widening. +func TestSentinelSettingsClearsRepoSensitivePaths(t *testing.T) { + p, _ := capPreview(t, surfaceHandler(&surfaceProvider{governor: sentinelRepoPathsGovernor()}), WriteOpSentinelSettings, map[string]any{"repo_sensitive_paths": map[string]any{"acme/website": nil}}) + if got := compactJSON(p.Request.Body); got != `{"sentinel":{"repoSensitivePaths":{"acme/website":null}}}` { + t.Fatalf("body = %s", got) + } + if !strings.HasPrefix(p.WideningDisclosure, "No widening") || !strings.Contains(p.WideningDisclosure, "Sentinel flags .github/workflows/**, **/.github/workflows/**, hive.yaml in acme/website") { + t.Fatalf("disclosure = %q", p.WideningDisclosure) + } +} + +func TestSentinelSettingsRepoSensitivePathsRefusals(t *testing.T) { + older := sentinelRepoPathsGovernor() + delete(older["security"].(map[string]any)["sentinel"].(map[string]any), "repoSensitivePathsSettable") + for name, tc := range map[string]struct { + governor map[string]any + repos map[string]any + want string + }{ + "blank pattern": {sentinelRepoPathsGovernor(), map[string]any{"acme/docs": []any{"OWNERS", " "}}, "empty entry"}, + "malformed glob": {sentinelRepoPathsGovernor(), map[string]any{"acme/docs": []any{"[x"}}, "not a valid glob"}, + "unwatched": {sentinelRepoPathsGovernor(), map[string]any{"acme/zzz": []any{"OWNERS"}}, "is not a repository in project.repos"}, + "clear what is not": {sentinelRepoPathsGovernor(), map[string]any{"acme/docs": nil}, "has no list of its own to remove"}, + "already so": {sentinelRepoPathsGovernor(), map[string]any{"acme/website": []any{"OWNERS"}}, "changes nothing"}, + "older hive": {older, map[string]any{"acme/docs": []any{"OWNERS"}}, "older build"}, + } { + h := surfaceHandler(&surfaceProvider{governor: tc.governor}) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpSentinelSettings, "args": map[string]any{"repo_sensitive_paths": tc.repos}}) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("%s: err = %v, want %q", name, err, tc.want) + } + } +} + +// Another repository's list changing after the preview refuses the confirm. +func TestSentinelSettingsRepoSensitivePathsStalePreview(t *testing.T) { + provider := &surfaceProvider{governor: sentinelRepoPathsGovernor()} + h := surfaceHandler(provider) + _, id := capPreview(t, h, WriteOpSentinelSettings, map[string]any{"repo_sensitive_paths": map[string]any{"acme/docs": []any{"OWNERS"}}}) + sn := provider.governor["security"].(map[string]any)["sentinel"].(map[string]any) + sn["repoSensitivePaths"] = sn["repoSensitivePaths"].([]any)[:1] + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("confirm err = %v, want ErrConfirmationStale", err) + } + if len(provider.requests) != 0 { + t.Fatalf("a stale confirm wrote %+v", provider.requests) + } +} + +type repoOverrideDeniedProvider struct{ *surfaceProvider } + +func (p repoOverrideDeniedProvider) Read(context.Context, string, map[string]any) (any, error) { + return nil, fmt.Errorf("%w: Hive API returned HTTP 403: owner access required", ErrForbidden) +} + +func TestSentinelSettingsRepoSensitivePathsRefusesNonOwner(t *testing.T) { + inner := &surfaceProvider{governor: sentinelRepoPathsGovernor()} + h := NewHandler(repoOverrideDeniedProvider{inner}, WithWritesEnabled(true), WithPendingStore(NewMemoryPendingStore()), WithHiveID("hive-a")) + _, err := h.PreviewWrite(context.Background(), map[string]any{"operation": WriteOpSentinelSettings, "args": map[string]any{"repo_sensitive_paths": map[string]any{"acme/docs": []any{}}}}) + if err == nil { + t.Fatal("a caller who cannot read the settings got a preview") + } + if len(inner.requests) != 0 { + t.Fatalf("wrote without owner access: %+v", inner.requests) + } +} diff --git a/src/pkg/adminmcp/tools_sentinel_repo_paths_write.go b/src/pkg/adminmcp/tools_sentinel_repo_paths_write.go new file mode 100644 index 0000000000..ff06fa04c0 --- /dev/null +++ b/src/pkg/adminmcp/tools_sentinel_repo_paths_write.go @@ -0,0 +1,194 @@ +package adminmcp + +import ( + "fmt" + "maps" + "slices" + "strings" + + "github.com/hivecommons/hive/pkg/config" +) + +// sentinel.settings' repo_sensitive_paths: one repository's own Sentinel +// sensitive-path list (project.repo_policies[].sentinel_sensitive_paths). The +// security endpoint takes it per repository under +// sentinel.repoSensitivePaths ({"owner/repo": [globs] | null}) and leaves +// repositories it is not sent alone, so the op sends only the repositories +// that change. The preview's fingerprint already covers every repository's +// list (sentinelState.RepoOverrides), so a list changed after the preview +// refuses the confirm. + +func sentinelRepoPathsSchema() map[string]any { + list := map[string]any{"type": "array", "items": stringSchema()} + return map[string]any{"type": "object", "description": "owner/repo to every glob that repository's own sensitive-path list should hold; it replaces the hive-wide sensitive_paths for that repository's pull requests. [] flags nothing by path there; null removes the repository's list so it uses the hive-wide list again. Repositories you do not name keep theirs; the hive-wide list is not changed.", "additionalProperties": map[string]any{"anyOf": []any{list, map[string]any{"type": "null"}}}} +} + +// parseSentinelRepoPathsArg reads repo_sensitive_paths: nil when absent, a +// nil value for a repository to clear. +func parseSentinelRepoPathsArg(args map[string]any, where string) (map[string]*[]string, error) { + m, err := objectArg(args, "repo_sensitive_paths", where) + if err != nil || m == nil { + return nil, err + } + name := where + ".repo_sensitive_paths" + if len(m) == 0 { + return nil, fmt.Errorf("%s names no repository", name) + } + out := make(map[string]*[]string, len(m)) + for _, repo := range SortKeys(m) { + if strings.TrimSpace(repo) == "" { + return nil, fmt.Errorf("%s has an empty repository name", name) + } + if m[repo] == nil { + out[repo] = nil + continue + } + field := name + "[" + repo + "]" + list, err := namedStringList(m[repo], field) + if err != nil { + return nil, err + } + paths, err := config.NormalizeRepoSentinelSensitivePaths(field, list) + if err != nil { + return nil, err + } + out[repo] = &paths + } + return out, nil +} + +func sentinelRepoOverrideIndex(list []sentinelRepoPathsOverride, repo string) int { + for i, o := range list { + if strings.EqualFold(o.Repo, repo) { + return i + } + } + return -1 +} + +// applySentinelRepoPaths sets or clears the named repositories' lists on +// after, adds the per-repository patch to body, and returns the preview rows +// and notes. +func applySentinelRepoPaths(after *sentinelState, before sentinelState, req map[string]*[]string, body map[string]any) ([]settingChange, []string, error) { + const field = "sentinel.repo_sensitive_paths" + if !before.repoPathsSettable { + return nil, nil, fmt.Errorf("this hive cannot set %s through Settings → Security (it runs an older build); upgrade it, or set project.repo_policies[].sentinel_sensitive_paths in hive.yaml", field) + } + next := append([]sentinelRepoPathsOverride(nil), before.RepoOverrides...) + patch := map[string]any{} + var changes []settingChange + var named []string + touched := map[string]bool{} + for _, key := range slices.Sorted(maps.Keys(req)) { + repo := qualifyProjectRepo(strings.TrimSpace(key), before.projectRepos) + watched := false + for _, full := range before.projectRepos { + if strings.EqualFold(full, repo) { + repo, watched = full, true + } + } + if !watched { + return nil, nil, fmt.Errorf("%s: %q is not a repository in project.repos", field, key) + } + if touched[strings.ToLower(repo)] { + return nil, nil, fmt.Errorf("%s names %s twice", field, repo) + } + touched[strings.ToLower(repo)] = true + idx := sentinelRepoOverrideIndex(next, repo) + row := field + "[" + repo + "]" + if req[key] == nil { + if idx < 0 { + return nil, nil, fmt.Errorf("%s: %s has no list of its own to remove; it already uses the hive-wide list", field, repo) + } + changes = append(changes, settingChange{Field: row, Before: next[idx].SensitivePaths, After: "hive-wide"}) + next = append(next[:idx:idx], next[idx+1:]...) + patch[repo] = nil + named = append(named, repo) + continue + } + paths := *req[key] + if idx >= 0 { + if sameList(next[idx].SensitivePaths, paths, foldExact) { + continue + } + changes = append(changes, settingChange{Field: row, Before: next[idx].SensitivePaths, After: paths}) + next[idx] = sentinelRepoPathsOverride{Repo: next[idx].Repo, SensitivePaths: paths} + } else { + changes = append(changes, settingChange{Field: row, Before: "hive-wide", After: paths}) + next = append(next, sentinelRepoPathsOverride{Repo: repo, SensitivePaths: paths}) + } + patch[repo] = paths + named = append(named, repo) + } + if len(patch) == 0 { + return nil, nil, nil + } + body["repoSensitivePaths"] = patch + after.RepoOverrides = next + slices.Sort(named) + return changes, []string{"Sets project.repo_policies[].sentinel_sensitive_paths for " + strings.Join(named, ", ") + " only. The hive-wide sensitive_paths and every other repository keep their lists; a repository set to null uses the hive-wide list again, and an empty list flags no path there."}, nil +} + +// sentinelRepoPathsDisclosure compares, for each repository whose own list +// the write sets or clears, the globs Sentinel checks there before and after: +// a glob dropped is a widening ("Sentinel stops flagging … in owner/repo"). +// A write that changes no repository's list returns nothing. +func sentinelRepoPathsDisclosure(before, after sentinelState) (fewer, more []string) { + for _, repo := range sentinelRepoOverridesChanged(before, after) { + effBefore, effAfter := before.SensitivePaths, after.SensitivePaths + if i := sentinelRepoOverrideIndex(before.RepoOverrides, repo); i >= 0 { + effBefore = before.RepoOverrides[i].SensitivePaths + } + ownEmpty := false + if i := sentinelRepoOverrideIndex(after.RepoOverrides, repo); i >= 0 { + effAfter = after.RepoOverrides[i].SensitivePaths + ownEmpty = len(effAfter) == 0 + } + added, removed := listDiff(effBefore, effAfter, foldExact) + if len(removed) > 0 { + line := "Sentinel stops flagging " + listLabel(removed) + " in " + repo + if ownEmpty { + line += " (its own list is empty, so the sensitive_path rule flags no path there)" + } + fewer = append(fewer, line) + } + if len(added) > 0 { + more = append(more, "Sentinel flags "+listLabel(added)+" in "+repo) + } + } + return fewer, more +} + +// sentinelRepoOverridesChanged names the repositories whose own list differs +// between before and after (set, changed or cleared). +func sentinelRepoOverridesChanged(before, after sentinelState) []string { + var out []string + for _, o := range after.RepoOverrides { + i := sentinelRepoOverrideIndex(before.RepoOverrides, o.Repo) + if i < 0 || !sameList(before.RepoOverrides[i].SensitivePaths, o.SensitivePaths, foldExact) { + out = append(out, o.Repo) + } + } + for _, o := range before.RepoOverrides { + if sentinelRepoOverrideIndex(after.RepoOverrides, o.Repo) < 0 { + out = append(out, o.Repo) + } + } + return out +} + +// sentinelRepoOverridesUntouched is after's per-repository lists less the ones +// this write sets or changes: the lists already in force that it leaves alone. +func sentinelRepoOverridesUntouched(before, after sentinelState) []sentinelRepoPathsOverride { + changed := map[string]bool{} + for _, repo := range sentinelRepoOverridesChanged(before, after) { + changed[strings.ToLower(repo)] = true + } + var out []sentinelRepoPathsOverride + for _, o := range after.RepoOverrides { + if !changed[strings.ToLower(o.Repo)] { + out = append(out, o) + } + } + return out +} diff --git a/src/pkg/config/repo_policy_sentinel_fence_write.go b/src/pkg/config/repo_policy_sentinel_fence_write.go new file mode 100644 index 0000000000..fd381194a0 --- /dev/null +++ b/src/pkg/config/repo_policy_sentinel_fence_write.go @@ -0,0 +1,210 @@ +package config + +import ( + "fmt" + "path/filepath" + "sort" + "strings" + + "gopkg.in/yaml.v3" +) + +// Writes for the per-repository Sentinel sensitive-path list and workflow +// fence scope (repo_policy_sentinel_fence.go). The dashboard's merge and +// Security settings and the admin MCP auto_merge.update and sentinel.settings +// operations set them through these, so an owner can change one repository's +// override without a hand edit of hive.yaml. +// +// Both setters edit one repository at a time and nothing else: they never +// touch the hive-wide sentinel.sensitive_paths or +// auto_merge.contributor_lane.workflow_fence_scope, nor any other field of +// the repository's policy entry. A nil value clears the repository's +// override, so it reads the hive-wide value again. An invalid value refuses +// the whole batch before anything changes. Persistence is the caller's job. + +// RepoOverrideHiveWide is how a change line names "no override": the +// repository reads the hive-wide value. +const RepoOverrideHiveWide = "hive-wide" + +// NormalizeRepoSentinelSensitivePaths trims each pattern, drops exact +// duplicates and checks the result: a blank pattern is refused (as +// ValidateRepoSentinelSensitivePaths does when hive.yaml loads) and so is a +// malformed glob, which would otherwise never match. An empty list stays a +// non-nil empty list: it flags nothing by path. +func NormalizeRepoSentinelSensitivePaths(field string, paths []string) ([]string, error) { + out := make([]string, 0, len(paths)) + seen := map[string]bool{} + for _, p := range paths { + p = strings.TrimSpace(p) + if p == "" { + return nil, ValidateRepoSentinelSensitivePaths(field, []string{p}) + } + if _, err := filepath.Match(filepath.ToSlash(p), ""); err != nil { + return nil, fmt.Errorf("%s: sentinel_sensitive_paths: %q is not a valid glob", field, p) + } + if !seen[p] { + seen[p] = true + out = append(out, p) + } + } + return out, nil +} + +// SetRepoWorkflowFenceScopes records or clears per-repository +// workflow_fence_scope overrides in memory. A value ("all" or +// "human_merge_paths", any case) sets the override; nil clears it. It returns +// one "owner/repo: before → after" line per repository it changed, sorted. +func (c *Config) SetRepoWorkflowFenceScopes(values map[string]*string) ([]string, error) { + if c == nil { + return nil, fmt.Errorf("no config loaded") + } + next := make(map[string]string, len(values)) + for _, repo := range sortedRepoOverrideKeys(values) { + scope := "" + if v := values[repo]; v != nil { + normalized, ok := repoPolicyFenceScopeValue(*v) + if !ok { + return nil, fmt.Errorf("workflow_fence_scope for %s: %q is not one of %s", repo, *v, strings.Join(ContributorLaneWorkflowFenceScopes, ", ")) + } + scope = normalized + } + next[repo] = scope + } + repoPauseMu.Lock() + defer repoPauseMu.Unlock() + var changes []string + for _, repo := range sortedRepoOverrideKeys(values) { + scope := next[repo] + before := RepoOverrideHiveWide + if c.editRepoSentinelFencePolicyLocked(repo, func(rp *RepoPolicy) bool { + if cur, ok := repoPolicyFenceScopeValue(rp.WorkflowFenceScope); ok { + before = cur + } + if rp.WorkflowFenceScope == scope { + return false + } + rp.WorkflowFenceScope = scope + return true + }) { + after := scope + if after == "" { + after = RepoOverrideHiveWide + } + changes = append(changes, QualifyRepo(c.Project.Org, repo)+": "+before+" → "+after) + } + } + return changes, nil +} + +// SetRepoSentinelSensitivePaths records or clears per-repository +// sentinel_sensitive_paths overrides in memory. A list (normalized by +// NormalizeRepoSentinelSensitivePaths) replaces the repository's own list, +// and an empty list flags nothing by path there; nil clears the override. It +// returns one "owner/repo: before → after" line per repository it changed, +// sorted. +func (c *Config) SetRepoSentinelSensitivePaths(values map[string]*[]string) ([]string, error) { + if c == nil { + return nil, fmt.Errorf("no config loaded") + } + next := make(map[string][]string, len(values)) + for _, repo := range sortedRepoOverrideKeys(values) { + if v := values[repo]; v != nil { + paths, err := NormalizeRepoSentinelSensitivePaths("repo "+repo, *v) + if err != nil { + return nil, err + } + next[repo] = paths + } + } + repoPauseMu.Lock() + defer repoPauseMu.Unlock() + var changes []string + for _, repo := range sortedRepoOverrideKeys(values) { + paths := next[repo] + before := RepoOverrideHiveWide + if c.editRepoSentinelFencePolicyLocked(repo, func(rp *RepoPolicy) bool { + if rp.SentinelSensitivePaths != nil { + before = repoOverridePathsLabel(rp.SentinelSensitivePaths) + } + if (rp.SentinelSensitivePaths == nil) == (paths == nil) && strings.Join(rp.SentinelSensitivePaths, "\n") == strings.Join(paths, "\n") { + return false + } + rp.SentinelSensitivePaths = paths + return true + }) { + after := RepoOverrideHiveWide + if paths != nil { + after = repoOverridePathsLabel(paths) + } + changes = append(changes, QualifyRepo(c.Project.Org, repo)+": "+before+" → "+after) + } + } + return changes, nil +} + +func repoOverridePathsLabel(paths []string) string { + return "[" + strings.Join(paths, ", ") + "]" +} + +func sortedRepoOverrideKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// editRepoSentinelFencePolicyLocked applies edit to repo's policy entry, +// adding one when the repository has none, and reports whether edit changed +// anything. An entry the edit leaves with no override is removed, unless it +// still carries forge settings (repoPolicyHasNoOverrides does not count +// those). Callers hold repoPauseMu. +func (c *Config) editRepoSentinelFencePolicyLocked(repo string, edit func(*RepoPolicy) bool) bool { + name, _ := NormalizeRepoForOrg(c.Project.Org, strings.TrimSpace(repo)) + key := repoPauseKey(c.Project.Org, name) + if key == "" { + return false + } + for i := range c.Project.RepoPolicies { + if repoPauseKey(c.Project.Org, c.Project.RepoPolicies[i].Repo) != key { + continue + } + if !edit(&c.Project.RepoPolicies[i]) { + return false + } + rp := c.Project.RepoPolicies[i] + if repoPolicyHasNoOverrides(rp) && rp.Forge == "" && rp.ForgeURL == "" { + c.Project.RepoPolicies = append(c.Project.RepoPolicies[:i:i], c.Project.RepoPolicies[i+1:]...) + } + return true + } + rp := RepoPolicy{Repo: name} + if !edit(&rp) || repoPolicyHasNoOverrides(rp) { + return false + } + c.Project.RepoPolicies = append(c.Project.RepoPolicies, rp) + return true +} + +// MarshalYAML keeps an explicit empty sentinel_sensitive_paths. The field is +// omitempty, which drops an empty list exactly as it drops nil, so without +// this a saved "flag nothing by path" override came back as unset (the +// hive-wide list) on the next load. Every other policy marshals unchanged. +func (rp RepoPolicy) MarshalYAML() (interface{}, error) { + type plain RepoPolicy + if rp.SentinelSensitivePaths == nil || len(rp.SentinelSensitivePaths) > 0 { + return plain(rp), nil + } + var node yaml.Node + if err := node.Encode(plain(rp)); err != nil { + return nil, err + } + if node.Kind != yaml.MappingNode { + return plain(rp), nil + } + node.Content = append(node.Content, + &yaml.Node{Kind: yaml.ScalarNode, Value: "sentinel_sensitive_paths"}, + &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Style: yaml.FlowStyle}) + return &node, nil +} diff --git a/src/pkg/config/repo_policy_sentinel_fence_write_test.go b/src/pkg/config/repo_policy_sentinel_fence_write_test.go new file mode 100644 index 0000000000..eaa74fcb22 --- /dev/null +++ b/src/pkg/config/repo_policy_sentinel_fence_write_test.go @@ -0,0 +1,173 @@ +package config + +import ( + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func repoOverrideWriteConfig(t *testing.T) *Config { + t.Helper() + return loadRepoPolicySentinelFenceYAML(t, ` +project: + org: acme + repos: [a, b, c, d] + repo_policies: + - repo: a + auto_merge: false + merge_strategy: hive-serialized + - repo: d + forge_url: https://git.example.com +sentinel: + sensitive_paths: ["OWNERS", "Justfile"] +auto_merge: + contributor_lane: + workflow_fence_scope: all +`) +} + +func repoOverrideStrPtr(s string) *string { return &s } + +// An owner sets and clears one repository's workflow fence scope; the other +// fields of its policy entry, other repositories and the hive-wide value stay +// as they were. On v6 tip there is no setter, so this does not compile. +func TestSetRepoWorkflowFenceScopesSetsAndClearsOneRepository(t *testing.T) { + cfg := repoOverrideWriteConfig(t) + changes, err := cfg.SetRepoWorkflowFenceScopes(map[string]*string{"a": repoOverrideStrPtr("Human_Merge_Paths"), "acme/b": repoOverrideStrPtr("all")}) + if err != nil { + t.Fatalf("set: %v", err) + } + if got := strings.Join(changes, "; "); got != "acme/a: hive-wide → human_merge_paths; acme/b: hive-wide → all" { + t.Fatalf("changes = %q", got) + } + if scope, override := cfg.RepoWorkflowFenceScope("a"); scope != ContributorLaneWorkflowFenceScopeHumanMergePaths || !override { + t.Fatalf("a = %q, %v; want its own human_merge_paths", scope, override) + } + rp, _ := cfg.RepoPolicyFor("a") + if rp.AutoMerge == nil || *rp.AutoMerge || rp.MergeStrategy != MergeStrategyHiveSerialized { + t.Fatalf("setting the scope changed a's other fields: %+v", rp) + } + if scope, override := cfg.RepoWorkflowFenceScope("c"); scope != ContributorLaneWorkflowFenceScopeAll || override { + t.Fatalf("c = %q, %v; want the hive-wide all", scope, override) + } + if cfg.AutoMerge.ContributorLane.WorkflowFenceScope != ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("hive-wide scope changed to %q", cfg.AutoMerge.ContributorLane.WorkflowFenceScope) + } + + // Clearing returns a to the hive-wide value and keeps its entry, which + // still holds other overrides; clearing b prunes its now-empty entry. + if _, err := cfg.SetRepoWorkflowFenceScopes(map[string]*string{"acme/a": nil, "b": nil}); err != nil { + t.Fatalf("clear: %v", err) + } + if _, override := cfg.RepoWorkflowFenceScope("a"); override { + t.Fatal("a still has an override after clearing") + } + if rp, ok := cfg.RepoPolicyFor("a"); !ok || rp.MergeStrategy != MergeStrategyHiveSerialized { + t.Fatalf("clearing a's scope dropped its entry: %+v, %v", rp, ok) + } + if _, ok := cfg.RepoPolicyFor("b"); ok { + t.Fatal("b's entry held only the scope and should be pruned") + } + // Clearing what is not set is no change. + if changes, err := cfg.SetRepoWorkflowFenceScopes(map[string]*string{"c": nil}); err != nil || len(changes) != 0 { + t.Fatalf("clearing an unset scope = %v, %v; want no change", changes, err) + } + + // An invalid value refuses the batch before anything changes. + before := append([]RepoPolicy(nil), cfg.Project.RepoPolicies...) + if _, err := cfg.SetRepoWorkflowFenceScopes(map[string]*string{"c": repoOverrideStrPtr("all"), "a": repoOverrideStrPtr("release_only")}); err == nil { + t.Fatal("an unknown scope was accepted") + } + if len(cfg.Project.RepoPolicies) != len(before) { + t.Fatalf("a refused batch changed the policies: %+v", cfg.Project.RepoPolicies) + } + if _, override := cfg.RepoWorkflowFenceScope("c"); override { + t.Fatal("a refused batch still set c") + } +} + +// An owner sets, empties and clears one repository's Sentinel list. On v6 tip +// there is no setter, so this does not compile. +func TestSetRepoSentinelSensitivePathsSetsAndClearsOneRepository(t *testing.T) { + cfg := repoOverrideWriteConfig(t) + own := []string{" OWNERS ", "OWNERS", ".github/workflows/**"} + none := []string{} + if _, err := cfg.SetRepoSentinelSensitivePaths(map[string]*[]string{"a": &own, "c": &none}); err != nil { + t.Fatalf("set: %v", err) + } + if got, override := cfg.RepoSentinelSensitivePaths("a"); !override || strings.Join(got, ",") != "OWNERS,.github/workflows/**" { + t.Fatalf("a = %v, %v; want its own trimmed, de-duplicated list", got, override) + } + if got, override := cfg.RepoSentinelSensitivePaths("c"); !override || got == nil || len(got) != 0 { + t.Fatalf("c = %#v, %v; want an explicit empty list that flags nothing", got, override) + } + if got, override := cfg.RepoSentinelSensitivePaths("b"); override || strings.Join(got, ",") != "OWNERS,Justfile" { + t.Fatalf("b = %v, %v; want the hive-wide list", got, override) + } + if strings.Join(cfg.Sentinel.SensitivePaths, ",") != "OWNERS,Justfile" { + t.Fatalf("hive-wide list changed: %v", cfg.Sentinel.SensitivePaths) + } + if rp, _ := cfg.RepoPolicyFor("a"); rp.AutoMerge == nil || rp.MergeStrategy != MergeStrategyHiveSerialized { + t.Fatalf("setting the list changed a's other fields: %+v", rp) + } + + // Blank and malformed patterns are refused, and nothing changes. + for _, bad := range [][]string{{"OWNERS", " "}, {"[unclosed"}} { + list := bad + if _, err := cfg.SetRepoSentinelSensitivePaths(map[string]*[]string{"b": &list}); err == nil { + t.Fatalf("pattern list %q was accepted", bad) + } + if _, override := cfg.RepoSentinelSensitivePaths("b"); override { + t.Fatalf("refused list %q still set b", bad) + } + } + + // d's entry carries only forge settings; adding and then clearing a list + // must leave those in place. + if _, err := cfg.SetRepoSentinelSensitivePaths(map[string]*[]string{"d": &own}); err != nil { + t.Fatal(err) + } + if _, err := cfg.SetRepoSentinelSensitivePaths(map[string]*[]string{"a": nil, "c": nil, "d": nil}); err != nil { + t.Fatalf("clear: %v", err) + } + if rp, ok := cfg.RepoPolicyFor("d"); !ok || rp.ForgeURL != "https://git.example.com" || rp.SentinelSensitivePaths != nil { + t.Fatalf("clearing d's list lost its forge_url: %+v, %v", rp, ok) + } + if _, ok := cfg.RepoPolicyFor("c"); ok { + t.Fatal("c's entry held only the list and should be pruned") + } + if _, override := cfg.RepoSentinelSensitivePaths("a"); override { + t.Fatal("a still has its own list after clearing") + } +} + +// An explicit empty list must survive a save and reload: omitempty dropped it, +// so on v6 tip a saved "flag nothing by path" came back as the hive-wide list. +func TestRepoPolicyEmptySentinelPathsSurviveYAMLRoundTrip(t *testing.T) { + in := []RepoPolicy{ + {Repo: "a", SentinelSensitivePaths: []string{}, WorkflowFenceScope: "human_merge_paths"}, + {Repo: "b", AutoMerge: new(bool)}, + {Repo: "c", SentinelSensitivePaths: []string{"OWNERS"}}, + } + data, err := yaml.Marshal(in) + if err != nil { + t.Fatal(err) + } + var out []RepoPolicy + if err := yaml.Unmarshal(data, &out); err != nil { + t.Fatalf("unmarshal %s: %v", data, err) + } + if len(out) != 3 { + t.Fatalf("round trip = %+v", out) + } + if out[0].SentinelSensitivePaths == nil || len(out[0].SentinelSensitivePaths) != 0 || out[0].WorkflowFenceScope != "human_merge_paths" { + t.Fatalf("a after round trip = %+v; want an explicit empty list and its scope\n%s", out[0], data) + } + if out[1].SentinelSensitivePaths != nil || strings.Count(string(data), "sentinel_sensitive_paths") != 2 { + t.Fatalf("an unset list must stay unset:\n%s", data) + } + if strings.Join(out[2].SentinelSensitivePaths, ",") != "OWNERS" { + t.Fatalf("c after round trip = %+v", out[2]) + } +} diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 49a661c8f5..74c96440b7 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -196,6 +196,12 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { ApproveHeldRunsForRegistryTrusted *bool `json:"approve_held_runs_for_registry_trusted"` OwnerApprovalReleasesWorkflowFence *bool `json:"owner_approval_releases_workflow_fence"` WorkflowFenceScope *string `json:"workflow_fence_scope"` + // WorkflowFenceScopeRepos sets or clears single repositories' + // project.repo_policies[].workflow_fence_scope: "all" or + // "human_merge_paths" sets it, null clears it so the repository + // reads workflow_fence_scope again. Repositories it does not name + // keep their override; the hive-wide value is never changed here. + WorkflowFenceScopeRepos map[string]*string `json:"workflow_fence_scope_repos"` } `json:"contributor_lane"` } if err := decodeBody(r, &body); err != nil { @@ -295,6 +301,7 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { var contributorLaneTiers []string var contributorLaneScope string var contributorLaneWorkflowFenceScope string + var fenceScopeRepos map[string]*string if body.ContributorLane != nil { if body.ContributorLane.SoakMinutes != nil && *body.ContributorLane.SoakMinutes < 0 { jsonError(w, "contributor_lane.soak_minutes must be 0 (default 30) or greater", http.StatusBadRequest) @@ -339,11 +346,32 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } contributorLaneWorkflowFenceScope = scope.EffectiveWorkflowFenceScope() } + if body.ContributorLane.WorkflowFenceScopeRepos != nil { + repos, msg := s.repoOverrideFenceScopeRepos(body.ContributorLane.WorkflowFenceScopeRepos) + if msg != "" { + jsonError(w, msg, http.StatusBadRequest) + return + } + fenceScopeRepos = repos + } } // --- apply --- cfg := s.deps.Config previousAutoMerge := cfg.AutoMerge + // Per-repository fence scopes go first: they are the only write here that + // can still be refused, and a refusal must leave every setting untouched. + var fenceScopeChanges []string + var previousRepoPolicies []config.RepoPolicy + if fenceScopeRepos != nil { + previousRepoPolicies = append([]config.RepoPolicy(nil), cfg.Project.RepoPolicies...) + changes, err := cfg.SetRepoWorkflowFenceScopes(fenceScopeRepos) + if err != nil { + jsonError(w, "contributor_lane.workflow_fence_scope_repos: "+err.Error(), http.StatusBadRequest) + return + } + fenceScopeChanges = changes + } if body.MergeTrain != nil { if body.MergeTrain.Enabled != nil { v := *body.MergeTrain.Enabled @@ -469,15 +497,24 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { s.logger.Error("failed to persist config after auto-merge update", "error", err) // A pin-only exception lets PRs past a human-merge hold, so one that // cannot be saved is not left running until the next restart drops it. - if body.NativeMergeQueue != nil || body.MergeTrain != nil || body.HumanMergePinOnly != nil { + // A per-repository fence scope can let workflow edits past the fence, + // so it is rolled back the same way. + if body.NativeMergeQueue != nil || body.MergeTrain != nil || body.HumanMergePinOnly != nil || len(fenceScopeChanges) > 0 { cfg.AutoMerge = previousAutoMerge + if len(fenceScopeChanges) > 0 { + cfg.Project.RepoPolicies = previousRepoPolicies + } syncAutoMergePolicyToGitHubClient(cfg, s.deps.GHClient) jsonError(w, "failed to persist auto-merge settings", http.StatusInternalServerError) return } } - s.auditFromRequest(r, "config_auto_merge", auditDetail("section", "auto_merge"), "") + auditKV := []string{"section", "auto_merge"} + if len(fenceScopeChanges) > 0 { + auditKV = append(auditKV, "workflow_fence_scope_repos", strings.Join(fenceScopeChanges, "; ")) + } + s.auditFromRequest(r, "config_auto_merge", auditDetail(auditKV...), "") s.refreshAndPersist() jsonResponse(w, s.autoMergeSectionResponseWithBots(cfg)) } @@ -612,6 +649,10 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "workflow_fence_scope": cl.EffectiveWorkflowFenceScope(), "workflow_fence_scopes": config.ContributorLaneWorkflowFenceScopes, "workflow_fence_scope_repos": contributorLaneFenceScopeRepos, + + // This build takes workflow_fence_scope_repos on PUT/PATCH; the + // admin MCP refuses to send it to a hive that does not say so. + "workflow_fence_scope_repos_settable": true, }, } } @@ -757,6 +798,42 @@ func (s *Server) autoMergeWatchedRepo(key, repo string) (full, msg string) { return full, "" } +// repoOverrideFenceScopeRepos validates +// contributor_lane.workflow_fence_scope_repos: every key a repository in +// project.repos (stored as owner/repo, named once), every value "all", +// "human_merge_paths" (any case, the rule hive.yaml loads under) or null to +// clear. A non-empty msg is the 400 to return. +func (s *Server) repoOverrideFenceScopeRepos(in map[string]*string) (map[string]*string, string) { + const key = "contributor_lane.workflow_fence_scope_repos" + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + out := make(map[string]*string, len(in)) + seen := map[string]bool{} + for _, k := range keys { + full, msg := s.autoMergeWatchedRepo(key, strings.TrimSpace(k)) + if msg != "" { + return nil, msg + } + if seen[strings.ToLower(full)] { + return nil, key + ": " + full + " is named twice" + } + seen[strings.ToLower(full)] = true + v := in[k] + if v != nil { + if strings.TrimSpace(*v) == "" || config.ValidateRepoWorkflowFenceScope(key+": "+full, *v) != nil { + return nil, key + ": " + full + " must be one of " + strings.Join(config.ContributorLaneWorkflowFenceScopes, ", ") + ", or null to use the hive-wide workflow_fence_scope" + } + scope := strings.ToLower(strings.TrimSpace(*v)) + v = &scope + } + out[full] = v + } + return out, "" +} + // autoMergeHumanMergePaths validates auto_merge.human_merge_paths sent by the // dashboard: keys follow autoMergeWatchedRepoList, patterns must be valid // globs (the syntax intent.PathMatchesAny uses), and a repo left with no diff --git a/src/pkg/dashboard/api_governor_security.go b/src/pkg/dashboard/api_governor_security.go index 346ae221a1..36200d4ef6 100644 --- a/src/pkg/dashboard/api_governor_security.go +++ b/src/pkg/dashboard/api_governor_security.go @@ -3,6 +3,7 @@ package dashboard import ( "net/http" "os" + "sort" "strings" "github.com/hivecommons/hive/pkg/config" @@ -72,6 +73,13 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) TrustedAuthorsBlock *bool `json:"trustedAuthorsBlock"` Repos *[]string `json:"repos"` MaxActions *int `json:"maxActions"` + // RepoSensitivePaths sets or clears single repositories' + // project.repo_policies[].sentinel_sensitive_paths: a list + // replaces that repository's own list ([] flags nothing by + // path there), null clears it so the repository reads + // sensitivePaths again. Repositories it does not name keep their + // list; the hive-wide list is never changed here. + RepoSensitivePaths map[string]*[]string `json:"repoSensitivePaths"` } `json:"sentinel"` } if err := decodeBody(r, &body); err != nil { @@ -79,6 +87,7 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) return } var nextSentinel *config.SentinelConfig + var repoSensitivePaths map[string]*[]string if body.Sentinel != nil { sc := s.deps.Config.Sentinel if body.Sentinel.Enabled != nil { @@ -121,6 +130,14 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) return } nextSentinel = &sc + if body.Sentinel.RepoSensitivePaths != nil { + paths, msg := s.repoOverrideSensitivePaths(body.Sentinel.RepoSensitivePaths) + if msg != "" { + jsonError(w, msg, http.StatusBadRequest) + return + } + repoSensitivePaths = paths + } } if body.IoscanFailMode != nil && !validIoscanFailMode(*body.IoscanFailMode) { jsonError(w, "ioscan fail_mode must be open or closed", http.StatusBadRequest) @@ -163,6 +180,18 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) } cfg := s.deps.Config + // Per-repository Sentinel lists go first: they are the only write here + // that can still be refused, and a refusal must leave every setting as + // it was. + var repoSensitivePathChanges []string + if repoSensitivePaths != nil { + changes, err := cfg.SetRepoSentinelSensitivePaths(repoSensitivePaths) + if err != nil { + jsonError(w, "sentinel.repoSensitivePaths: "+err.Error(), http.StatusBadRequest) + return + } + repoSensitivePathChanges = changes + } if body.IoscanEnabled != nil { v := *body.IoscanEnabled cfg.Ioscan.Enabled = &v @@ -308,11 +337,50 @@ func (s *Server) handleGovernorSecurity(w http.ResponseWriter, r *http.Request) if ioscanChanged && s.deps.IoscanConfigApplied != nil { s.deps.IoscanConfigApplied() } - s.auditFromRequest(r, "config_governor_security", auditDetail("section", "security"), "") + auditKV := []string{"section", "security"} + if len(repoSensitivePathChanges) > 0 { + auditKV = append(auditKV, "sentinel_repo_sensitive_paths", strings.Join(repoSensitivePathChanges, "; ")) + } + s.auditFromRequest(r, "config_governor_security", auditDetail(auditKV...), "") s.refreshAndPersist() okResponse(w, map[string]string{"status": "updated"}) } +// repoOverrideSensitivePaths validates sentinel.repoSensitivePaths: every key +// a repository in project.repos (stored as owner/repo, named once), every +// value null (clear) or a list of non-blank, well-formed globs. A non-empty +// msg is the 400 to return. +func (s *Server) repoOverrideSensitivePaths(in map[string]*[]string) (map[string]*[]string, string) { + const key = "sentinel.repoSensitivePaths" + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + out := make(map[string]*[]string, len(in)) + seen := map[string]bool{} + for _, k := range keys { + full, msg := s.autoMergeWatchedRepo(key, strings.TrimSpace(k)) + if msg != "" { + return nil, msg + } + if seen[strings.ToLower(full)] { + return nil, key + ": " + full + " is named twice" + } + seen[strings.ToLower(full)] = true + v := in[k] + if v != nil { + paths, err := config.NormalizeRepoSentinelSensitivePaths(key+": "+full, *v) + if err != nil { + return nil, err.Error() + } + v = &paths + } + out[full] = v + } + return out, "" +} + // validIoscanFailMode accepts open, closed, or empty (follow the default). func validIoscanFailMode(raw string) bool { switch strings.ToLower(strings.TrimSpace(raw)) { @@ -463,6 +531,10 @@ func sentinelSectionResponse(sc config.SentinelConfig, overrides []config.RepoSe "trustedAuthorsBlock": sc.TrustedAuthorsBlock, "repos": nonNilStrings(sc.Repos), "maxActions": sc.MaxActionsOrDefault(), + + // This build takes sentinel.repoSensitivePaths on PUT; the admin MCP + // refuses to send it to a hive that does not say so. + "repoSensitivePathsSettable": true, } } diff --git a/src/pkg/dashboard/api_repo_policy_overrides_write_test.go b/src/pkg/dashboard/api_repo_policy_overrides_write_test.go new file mode 100644 index 0000000000..8a1b00744b --- /dev/null +++ b/src/pkg/dashboard/api_repo_policy_overrides_write_test.go @@ -0,0 +1,227 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +func repoOverrideWriteServer(t *testing.T) (*Server, *Dependencies) { + t.Helper() + s, deps := apiServer(t) + deps.Config.Project.Repos = []string{"repo1", "repo2", "repo3"} + off := false + deps.Config.Project.RepoPolicies = []config.RepoPolicy{{Repo: "repo1", AutoMerge: &off}} + return s, deps +} + +func doPutAsRole(s *Server, path, role string, body any) *httptest.ResponseRecorder { + var b bytes.Buffer + _ = json.NewEncoder(&b).Encode(body) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, path, &b) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-Role", role) + s.mux.ServeHTTP(rec, req) + return rec +} + +func repoOverrideAuditDetails(s *Server, prefix string) string { + var out []string + for _, e := range s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), prefix) { + out = append(out, e.Detail) + } + return strings.Join(out, "\n") +} + +// PUT /api/config/auto-merge sets and clears one repository's workflow fence +// scope under contributor_lane.workflow_fence_scope_repos. Other repositories, +// the entry's other fields and the hive-wide scope are untouched. On v6 tip +// the key is ignored, so repo1 never gets its own scope. +func TestAutoMergePutSetsAndClearsRepoWorkflowFenceScope(t *testing.T) { + s, deps := repoOverrideWriteServer(t) + rec := doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"workflow_fence_scope_repos": map[string]any{ + "repo1": "human_merge_paths", "myorg/repo2": "ALL", + }}}) + if rec.Code != http.StatusOK { + t.Fatalf("PUT: %d %s", rec.Code, rec.Body.String()) + } + cfg := deps.Config + if scope, override := cfg.RepoWorkflowFenceScope("repo1"); !override || scope != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("repo1 = %q, %v; want its own human_merge_paths", scope, override) + } + if scope, override := cfg.RepoWorkflowFenceScope("repo2"); !override || scope != config.ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("repo2 = %q, %v; want its own all", scope, override) + } + if _, override := cfg.RepoWorkflowFenceScope("repo3"); override { + t.Fatal("repo3 was not named and must keep the hive-wide scope") + } + if got := cfg.AutoMerge.ContributorLane.EffectiveWorkflowFenceScope(); got != config.ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("hive-wide scope = %q; the per-repository key must not change it", got) + } + if rp, _ := cfg.RepoPolicyFor("repo1"); rp.AutoMerge == nil || *rp.AutoMerge { + t.Fatalf("repo1's auto_merge override was lost: %+v", rp) + } + cl := decodeJSON(t, rec)["contributor_lane"].(map[string]any) + if cl["workflow_fence_scope_repos_settable"] != true { + t.Fatalf("response does not say the per-repository scope is settable: %v", cl) + } + if repos, _ := cl["workflow_fence_scope_repos"].([]any); len(repos) != 2 { + t.Fatalf("response overrides = %#v, want two", cl["workflow_fence_scope_repos"]) + } + if got := repoOverrideAuditDetails(s, "config_auto_merge"); !strings.Contains(got, "workflow_fence_scope_repos=myorg/repo1: hive-wide → human_merge_paths; myorg/repo2: hive-wide → all") { + t.Fatalf("audit detail = %q", got) + } + + // null clears: repo1 keeps its entry (auto_merge), repo2's entry goes. + rec = doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"workflow_fence_scope_repos": map[string]any{"repo1": nil, "repo2": nil}}}) + if rec.Code != http.StatusOK { + t.Fatalf("clear PUT: %d %s", rec.Code, rec.Body.String()) + } + if _, override := cfg.RepoWorkflowFenceScope("repo1"); override { + t.Fatal("repo1 still has its own scope after null") + } + if rp, ok := cfg.RepoPolicyFor("repo1"); !ok || rp.AutoMerge == nil { + t.Fatalf("clearing repo1's scope dropped its entry: %+v, %v", rp, ok) + } + if _, ok := cfg.RepoPolicyFor("repo2"); ok { + t.Fatal("repo2's entry held only the scope and should be gone") + } +} + +// An invalid scope, an unwatched repository or a non-owner is refused, and +// nothing changes. On v6 tip the key is ignored, so every request gets 200. +func TestAutoMergePutRepoWorkflowFenceScopeRefusals(t *testing.T) { + s, deps := repoOverrideWriteServer(t) + before := append([]config.RepoPolicy(nil), deps.Config.Project.RepoPolicies...) + for name, body := range map[string]map[string]any{ + "unknown scope": {"repo1": "release_only"}, + "empty scope": {"repo1": ""}, + "unwatched": {"other/elsewhere": "all"}, + "named twice": {"repo2": "all", "myorg/REPO2": "all"}, + } { + rec := doPut(s, "/api/config/auto-merge", map[string]any{ + "max_merges": 9, + "contributor_lane": map[string]any{"workflow_fence_scope_repos": body}, + }) + if rec.Code != http.StatusBadRequest { + t.Fatalf("%s: got %d, want 400", name, rec.Code) + } + } + if !reflect.DeepEqual(deps.Config.Project.RepoPolicies, before) || deps.Config.AutoMerge.MaxMerges == 9 { + t.Fatalf("a refused request changed settings: %+v, max_merges %d", deps.Config.Project.RepoPolicies, deps.Config.AutoMerge.MaxMerges) + } + rec := doPutAsRole(s, "/api/config/auto-merge", "read-write", map[string]any{"contributor_lane": map[string]any{"workflow_fence_scope_repos": map[string]any{"repo1": "human_merge_paths"}}}) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-owner: got %d, want 403", rec.Code) + } + if _, override := deps.Config.RepoWorkflowFenceScope("repo1"); override { + t.Fatal("a non-owner set repo1's scope") + } +} + +// PUT /api/config/governor/security sets, empties and clears one repository's +// Sentinel list under sentinel.repoSensitivePaths, and never touches the +// hive-wide list. On v6 tip the key is ignored. +func TestGovernorSecurityPutSetsAndClearsRepoSensitivePaths(t *testing.T) { + s, deps := repoOverrideWriteServer(t) + deps.Config.Sentinel.SensitivePaths = []string{"OWNERS", "Justfile", "**/requirements*.txt"} + rec := doPut(s, "/api/config/governor/security", map[string]any{"sentinel": map[string]any{"repoSensitivePaths": map[string]any{ + "repo1": []string{"OWNERS", " .github/workflows/** "}, "repo2": []string{}, + }}}) + if rec.Code != http.StatusOK { + t.Fatalf("PUT: %d %s", rec.Code, rec.Body.String()) + } + cfg := deps.Config + if got, override := cfg.RepoSentinelSensitivePaths("repo1"); !override || strings.Join(got, ",") != "OWNERS,.github/workflows/**" { + t.Fatalf("repo1 = %v, %v", got, override) + } + if got, override := cfg.RepoSentinelSensitivePaths("repo2"); !override || got == nil || len(got) != 0 { + t.Fatalf("repo2 = %#v, %v; want an explicit empty list", got, override) + } + if got, override := cfg.RepoSentinelSensitivePaths("repo3"); override || len(got) != 3 { + t.Fatalf("repo3 = %v, %v; want the hive-wide list", got, override) + } + if strings.Join(cfg.Sentinel.SensitivePaths, ",") != "OWNERS,Justfile,**/requirements*.txt" { + t.Fatalf("hive-wide list changed: %v", cfg.Sentinel.SensitivePaths) + } + if rp, _ := cfg.RepoPolicyFor("repo1"); rp.AutoMerge == nil || *rp.AutoMerge { + t.Fatalf("repo1's auto_merge override was lost: %+v", rp) + } + sn := decodeJSON(t, doGet(s, "/api/config/governor"))["security"].(map[string]any)["sentinel"].(map[string]any) + if sn["repoSensitivePathsSettable"] != true { + t.Fatalf("GET does not say the per-repository list is settable: %v", sn) + } + if got := repoOverrideAuditDetails(s, "config_governor_security"); !strings.Contains(got, "sentinel_repo_sensitive_paths=myorg/repo1: hive-wide → [OWNERS, .github/workflows/**]; myorg/repo2: hive-wide → []") { + t.Fatalf("audit detail = %q", got) + } + + rec = doPut(s, "/api/config/governor/security", map[string]any{"sentinel": map[string]any{"repoSensitivePaths": map[string]any{"repo1": nil, "repo2": nil}}}) + if rec.Code != http.StatusOK { + t.Fatalf("clear PUT: %d %s", rec.Code, rec.Body.String()) + } + if _, override := cfg.RepoSentinelSensitivePaths("repo1"); override { + t.Fatal("repo1 still has its own list after null") + } + if rp, ok := cfg.RepoPolicyFor("repo1"); !ok || rp.AutoMerge == nil { + t.Fatalf("clearing repo1's list dropped its entry: %+v, %v", rp, ok) + } + if _, ok := cfg.RepoPolicyFor("repo2"); ok { + t.Fatal("repo2's entry held only the list and should be gone") + } +} + +func TestGovernorSecurityPutRepoSensitivePathsRefusals(t *testing.T) { + s, deps := repoOverrideWriteServer(t) + before := append([]config.RepoPolicy(nil), deps.Config.Project.RepoPolicies...) + for name, paths := range map[string]map[string]any{ + "blank pattern": {"repo1": []string{"OWNERS", " "}}, + "malformed glob": {"repo1": []string{"[unclosed"}}, + "unwatched": {"other/elsewhere": []string{"OWNERS"}}, + "not a string list": {"repo1": "OWNERS"}, + } { + rec := doPut(s, "/api/config/governor/security", map[string]any{"intentEnforce": true, "sentinel": map[string]any{"repoSensitivePaths": paths}}) + if rec.Code != http.StatusBadRequest { + t.Fatalf("%s: got %d, want 400", name, rec.Code) + } + } + if !reflect.DeepEqual(deps.Config.Project.RepoPolicies, before) || deps.Config.Intent.Enforce { + t.Fatalf("a refused request changed settings: %+v, intent.enforce %v", deps.Config.Project.RepoPolicies, deps.Config.Intent.Enforce) + } + rec := doPutAsRole(s, "/api/config/governor/security", "read-write", map[string]any{"sentinel": map[string]any{"repoSensitivePaths": map[string]any{"repo1": []string{}}}}) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-owner: got %d, want 403", rec.Code) + } + if _, override := deps.Config.RepoSentinelSensitivePaths("repo1"); override { + t.Fatal("a non-owner set repo1's list") + } +} + +// A request without the new keys behaves as before: no repo policy changes +// and the audit detail is the plain section entry. +func TestRepoOverrideKeysAbsentLeavesRepoPoliciesAlone(t *testing.T) { + s, deps := repoOverrideWriteServer(t) + deps.Config.Project.RepoPolicies = append(deps.Config.Project.RepoPolicies, config.RepoPolicy{Repo: "repo2", WorkflowFenceScope: "human_merge_paths", SentinelSensitivePaths: []string{}}) + before := append([]config.RepoPolicy(nil), deps.Config.Project.RepoPolicies...) + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"soak_minutes": 45, "workflow_fence_scope": "human_merge_paths"}}); rec.Code != http.StatusOK { + t.Fatalf("auto-merge PUT: %d %s", rec.Code, rec.Body.String()) + } + if rec := doPut(s, "/api/config/governor/security", map[string]any{"sentinel": map[string]any{"sensitivePaths": []string{"CODEOWNERS"}}}); rec.Code != http.StatusOK { + t.Fatalf("security PUT: %d %s", rec.Code, rec.Body.String()) + } + if !reflect.DeepEqual(deps.Config.Project.RepoPolicies, before) { + t.Fatalf("repo policies changed: %+v", deps.Config.Project.RepoPolicies) + } + for prefix, want := range map[string]string{"config_auto_merge": "section=auto_merge", "config_governor_security": "section=security"} { + if got := repoOverrideAuditDetails(s, prefix); got != want { + t.Fatalf("%s audit detail = %q, want %q", prefix, got, want) + } + } +} diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 3812682bdd..44df563666 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -427,6 +427,21 @@ const key = Object.keys(amHumanMergePaths).find(k => k.toLowerCase() === String(repo).toLowerCase()); return key && Array.isArray(amHumanMergePaths[key]) ? amHumanMergePaths[key] : []; }; + // project.repo_policies[].workflow_fence_scope: one row per watched + // repository; '' is "use the hive-wide scope". A staged choice wins + // over the saved one so a re-render keeps it. + const amFenceRepoStaged = ((((_configState.dirty || {})['auto-merge'] || {}).contributor_lane || {}).workflow_fence_scope_repos) || {}; + const amFenceRepoScope = (repo) => { + const staged = Object.keys(amFenceRepoStaged).find(k => k.toLowerCase() === String(repo).toLowerCase()); + if (staged !== undefined) return amFenceRepoStaged[staged] || ''; + const o = amContributorLaneFenceScopeRepos.find(x => String(x.repo).toLowerCase() === String(repo).toLowerCase()); + return o ? String(o.workflow_fence_scope || '') : ''; + }; + const amFenceRepoRows = amProjectRepos.map(r => { + const cur = amFenceRepoScope(r); + const choices = [['', `hive-wide (${amContributorLaneFenceScope})`]].concat(amContributorLaneFenceScopes.map(v => [v, v])); + return `${esc(r)}${amHumanMergePathsFor(r).length ? 'yes' : 'none, so it keeps the full fence'}`; + }).join(''); // auto_merge.human_merge_pin_only: one row per repository that has // human-merge paths or already holds an exception (it only ever lifts a // human-merge-path hold, so elsewhere it would never apply). @@ -676,7 +691,12 @@

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

-

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it. Overrides are set in hive.yaml.

+

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.

+ +
+ + ${amProjectRepos.length ? `${amFenceRepoRows}
RepositoryScopeHuman-merge paths
` : '

No repositories in project.repos yet.

'} +

Hive-wide scope: ${esc(amContributorLaneFenceScope)}. A repository set to human_merge_paths lets workflow edits outside its Human-merge paths merge without an owner Approve.

diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index 34c011b28d..ba9abf7dba 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -159,6 +159,24 @@ markSentinelDirty('sensitivePaths', []); renderConfigTab('Security'); } + /* Security → Sentinel → Sensitive files per repository. Stages one + repository's project.repo_policies[].sentinel_sensitive_paths under + sentinel.repoSensitivePaths: hive-wide sends null (clears it), "flag + no paths" sends [], own list sends the box's globs. It does not touch + sentinelState(), whose repoSensitivePaths is the saved list. */ + function markSentinelRepoPathsRow(el) { + const row = el && el.closest ? el.closest('.sn-repo-paths-row') : null; + if (!row || !row.dataset.repo) return; + const mode = row.querySelector('.sn-repo-paths-mode'); + const list = row.querySelector('.sn-repo-paths-list'); + const m = mode ? mode.value : 'hive'; + if (list) list.disabled = m !== 'own'; + const lines = list ? String(list.value || '').split('\n').map(l => l.trim()).filter(Boolean) : []; + if (!_configState.dirty.security) _configState.dirty.security = {}; + const bag = _configState.dirty.security.sentinel || {}; + bag.repoSensitivePaths = Object.assign({}, bag.repoSensitivePaths || {}, { [row.dataset.repo]: m === 'hive' ? null : (m === 'none' ? [] : lines) }); + _configState.dirty.security.sentinel = bag; + } function markSentinelPathsFromText(text) { const lines = String(text || '').split('\n').map(l => l.trim()).filter(Boolean); /* An emptied box restores defaults rather than disabling the rule. */ @@ -464,7 +482,8 @@ const scope = document.getElementById('am-contributor-lane-auto-promotion-scope'); const fenceScope = document.getElementById('am-contributor-lane-workflow-fence-scope'); const soakMinutes = soak ? parseInt(soak.value, 10) : 30; - markDirty('auto-merge', 'contributor_lane', { + const staged = ((_configState.dirty || {})['auto-merge'] || {}).contributor_lane || {}; + markDirty('auto-merge', 'contributor_lane', Object.assign({ enabled: !!(enabled && enabled.classList.contains('on')), soak_minutes: Number.isFinite(soakMinutes) && soakMinutes >= 0 ? soakMinutes : 30, require_reviewer_verdict: !!(verdict && verdict.classList.contains('on')), @@ -476,7 +495,17 @@ exclude_labels: labels ? labels.value.split(',').map(s => s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], require_tiers: tiers ? tiers.value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean) : [] - }); + }, staged.workflow_fence_scope_repos ? { workflow_fence_scope_repos: staged.workflow_fence_scope_repos } : {})); + } + + // Settings → Features → Auto-merge → Workflow fence scope per repository. + // Stages one repository's project.repo_policies[].workflow_fence_scope + // inside contributor_lane: a scope sets it, '' (hive-wide) sends null, + // which clears it. Only repositories changed here are sent. + function markDirtyFenceScopeRepo(repo, value) { + const staged = ((_configState.dirty || {})['auto-merge'] || {}).contributor_lane || {}; + const repos = Object.assign({}, staged.workflow_fence_scope_repos || {}, { [repo]: value ? value : null }); + markDirty('auto-merge', 'contributor_lane', Object.assign({}, staged, { workflow_fence_scope_repos: repos })); } function markDirtyPerspectives() { 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 495fb8103e..24e73ff727 100644 --- a/src/pkg/dashboard/static-src/js/config-watchdog-security.js +++ b/src/pkg/dashboard/static-src/js/config-watchdog-security.js @@ -984,6 +984,23 @@ const snPaths = Array.isArray(sn.sensitivePaths) ? sn.sensitivePaths : []; const snRepoPaths = Array.isArray(sn.repoSensitivePaths) ? sn.repoSensitivePaths : []; const snRepoPathsText = snRepoPaths.length ? snRepoPaths.map(o => `${esc(o.repo)}: ${(Array.isArray(o.sensitivePaths) && o.sensitivePaths.length) ? o.sensitivePaths.map(p => `${esc(p)}`).join(' ') : 'no globs (matches nothing)'}`).join('; ') : 'none'; + /* project.repo_policies[].sentinel_sensitive_paths: one row per watched + repository. null is "use the hive-wide list", [] flags no path. A + staged choice wins over the saved one so a re-render keeps it. */ + const snRepoStaged = (((_configState.dirty || {}).security || {}).sentinel || {}).repoSensitivePaths || {}; + const snWatchedRepos = Array.isArray((_configState.data || {}).repos) ? (_configState.data || {}).repos : []; + const snRepoOwn = (repo) => { + const staged = Object.keys(snRepoStaged).find(k => k.toLowerCase() === String(repo).toLowerCase()); + if (staged !== undefined) return snRepoStaged[staged]; + const o = snRepoPaths.find(x => String(x.repo).toLowerCase() === String(repo).toLowerCase()); + return o ? (Array.isArray(o.sensitivePaths) ? o.sensitivePaths : []) : null; + }; + const snRepoRows = snWatchedRepos.map(r => { + const own = snRepoOwn(r); + const mode = own === null ? 'hive' : (own.length ? 'own' : 'none'); + const modes = [['hive', 'hive-wide list'], ['own', 'own list'], ['none', 'flag no paths']]; + return `${esc(r)}`; + }).join(''); const snBehaviors = (sn.behaviors || []).map(b => `
@@ -1005,7 +1022,11 @@
-

Per-repository lists ${yamlHint('project.repo_policies[].sentinel_sensitive_paths[]')}: ${snRepoPathsText}. A listed repository uses its own list instead of this one. Per-repository lists are set in hive.yaml.

+

Per-repository lists ${yamlHint('project.repo_policies[].sentinel_sensitive_paths[]')}: ${snRepoPathsText}. A listed repository uses its own list instead of this one.

+
+
+ + ${snWatchedRepos.length ? `${snRepoRows}
RepositoryUsesGlobs
` : '

No repositories in project.repos yet.

'}
diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 166590a0dd..b4820db724 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -66092,6 +66092,23 @@

Escalation Breaker

const snPaths = Array.isArray(sn.sensitivePaths) ? sn.sensitivePaths : []; const snRepoPaths = Array.isArray(sn.repoSensitivePaths) ? sn.repoSensitivePaths : []; const snRepoPathsText = snRepoPaths.length ? snRepoPaths.map(o => `${esc(o.repo)}: ${(Array.isArray(o.sensitivePaths) && o.sensitivePaths.length) ? o.sensitivePaths.map(p => `${esc(p)}`).join(' ') : 'no globs (matches nothing)'}`).join('; ') : 'none'; + /* project.repo_policies[].sentinel_sensitive_paths: one row per watched + repository. null is "use the hive-wide list", [] flags no path. A + staged choice wins over the saved one so a re-render keeps it. */ + const snRepoStaged = (((_configState.dirty || {}).security || {}).sentinel || {}).repoSensitivePaths || {}; + const snWatchedRepos = Array.isArray((_configState.data || {}).repos) ? (_configState.data || {}).repos : []; + const snRepoOwn = (repo) => { + const staged = Object.keys(snRepoStaged).find(k => k.toLowerCase() === String(repo).toLowerCase()); + if (staged !== undefined) return snRepoStaged[staged]; + const o = snRepoPaths.find(x => String(x.repo).toLowerCase() === String(repo).toLowerCase()); + return o ? (Array.isArray(o.sensitivePaths) ? o.sensitivePaths : []) : null; + }; + const snRepoRows = snWatchedRepos.map(r => { + const own = snRepoOwn(r); + const mode = own === null ? 'hive' : (own.length ? 'own' : 'none'); + const modes = [['hive', 'hive-wide list'], ['own', 'own list'], ['none', 'flag no paths']]; + return `${esc(r)}`; + }).join(''); const snBehaviors = (sn.behaviors || []).map(b => `
@@ -66113,7 +66130,11 @@

Escalation Breaker

-

Per-repository lists ${yamlHint('project.repo_policies[].sentinel_sensitive_paths[]')}: ${snRepoPathsText}. A listed repository uses its own list instead of this one. Per-repository lists are set in hive.yaml.

+

Per-repository lists ${yamlHint('project.repo_policies[].sentinel_sensitive_paths[]')}: ${snRepoPathsText}. A listed repository uses its own list instead of this one.

+
+
+ + ${snWatchedRepos.length ? `${snRepoRows}
RepositoryUsesGlobs
` : '

No repositories in project.repos yet.

'}
@@ -66882,6 +66903,21 @@

${esc(s.title)}

const key = Object.keys(amHumanMergePaths).find(k => k.toLowerCase() === String(repo).toLowerCase()); return key && Array.isArray(amHumanMergePaths[key]) ? amHumanMergePaths[key] : []; }; + // project.repo_policies[].workflow_fence_scope: one row per watched + // repository; '' is "use the hive-wide scope". A staged choice wins + // over the saved one so a re-render keeps it. + const amFenceRepoStaged = ((((_configState.dirty || {})['auto-merge'] || {}).contributor_lane || {}).workflow_fence_scope_repos) || {}; + const amFenceRepoScope = (repo) => { + const staged = Object.keys(amFenceRepoStaged).find(k => k.toLowerCase() === String(repo).toLowerCase()); + if (staged !== undefined) return amFenceRepoStaged[staged] || ''; + const o = amContributorLaneFenceScopeRepos.find(x => String(x.repo).toLowerCase() === String(repo).toLowerCase()); + return o ? String(o.workflow_fence_scope || '') : ''; + }; + const amFenceRepoRows = amProjectRepos.map(r => { + const cur = amFenceRepoScope(r); + const choices = [['', `hive-wide (${amContributorLaneFenceScope})`]].concat(amContributorLaneFenceScopes.map(v => [v, v])); + return `${esc(r)}${amHumanMergePathsFor(r).length ? 'yes' : 'none, so it keeps the full fence'}`; + }).join(''); // auto_merge.human_merge_pin_only: one row per repository that has // human-merge paths or already holds an exception (it only ever lifts a // human-merge-path hold, so elsewhere it would never apply). @@ -67131,7 +67167,12 @@

${esc(s.title)}

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

-

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it. Overrides are set in hive.yaml.

+

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.

+
+
+ + ${amProjectRepos.length ? `${amFenceRepoRows}
RepositoryScopeHuman-merge paths
` : '

No repositories in project.repos yet.

'} +

Hive-wide scope: ${esc(amContributorLaneFenceScope)}. A repository set to human_merge_paths lets workflow edits outside its Human-merge paths merge without an owner Approve.

@@ -70033,6 +70074,24 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

l.trim()).filter(Boolean) : []; + if (!_configState.dirty.security) _configState.dirty.security = {}; + const bag = _configState.dirty.security.sentinel || {}; + bag.repoSensitivePaths = Object.assign({}, bag.repoSensitivePaths || {}, { [row.dataset.repo]: m === 'hive' ? null : (m === 'none' ? [] : lines) }); + _configState.dirty.security.sentinel = bag; + } function markSentinelPathsFromText(text) { const lines = String(text || '').split('\n').map(l => l.trim()).filter(Boolean); /* An emptied box restores defaults rather than disabling the rule. */ @@ -70338,7 +70397,8 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

= 0 ? soakMinutes : 30, require_reviewer_verdict: !!(verdict && verdict.classList.contains('on')), @@ -70350,7 +70410,17 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], require_tiers: tiers ? tiers.value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean) : [] - }); + }, staged.workflow_fence_scope_repos ? { workflow_fence_scope_repos: staged.workflow_fence_scope_repos } : {})); + } + + // Settings → Features → Auto-merge → Workflow fence scope per repository. + // Stages one repository's project.repo_policies[].workflow_fence_scope + // inside contributor_lane: a scope sets it, '' (hive-wide) sends null, + // which clears it. Only repositories changed here are sent. + function markDirtyFenceScopeRepo(repo, value) { + const staged = ((_configState.dirty || {})['auto-merge'] || {}).contributor_lane || {}; + const repos = Object.assign({}, staged.workflow_fence_scope_repos || {}, { [repo]: value ? value : null }); + markDirty('auto-merge', 'contributor_lane', Object.assign({}, staged, { workflow_fence_scope_repos: repos })); } function markDirtyPerspectives() { From 0e227fecfc1f1261a1a7c4bcc4310464022065f1 Mon Sep 17 00:00:00 2001 From: Danathar Date: Tue, 10 Nov 2026 09:54:59 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20fix(dashboard):=20one=20cont?= =?UTF-8?q?rol=20carries=20the=20per-repo=20fence=20scope=20key,=20so=20se?= =?UTF-8?q?ttings=20search=20resolves=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The read-only overrides note from #17547 and the new per-repository table both carried yamlHint('project.repo_policies[].workflow_fence_scope'), so TestSettingsSearchIndexResolvesToControls found two innermost rows. The note keeps its text; the table row keeps the key. static/index.html edited identically (manifest concatenation cmp-identical). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/pkg/dashboard/static-src/js/config-features.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-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 44df563666..d6e215c567 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -691,7 +691,7 @@

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

-

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.

+

Per-repository overrides: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.

diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index b4820db724..43e061302c 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -67167,7 +67167,7 @@

${esc(s.title)}

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

-

Per-repository overrides ${yamlHint('project.repo_policies[].workflow_fence_scope')}: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.

+

Per-repository overrides: ${amContributorLaneFenceScopeReposText}. A listed repository uses its own scope; this setting does not apply to it.