diff --git a/changelog.d/added-repo-policy-sentinel-fence-overrides.md b/changelog.d/added-repo-policy-sentinel-fence-overrides.md new file mode 100644 index 0000000000..216c7bda6c --- /dev/null +++ b/changelog.d/added-repo-policy-sentinel-fence-overrides.md @@ -0,0 +1 @@ +- **Sentinel's sensitive-path list and the contributor lane's workflow fence scope can be set per repository.** Two opt-in hive.yaml keys under `project.repo_policies`, `sentinel_sensitive_paths` and `workflow_fence_scope`, replace `sentinel.sensitive_paths` and `auto_merge.contributor_lane.workflow_fence_scope` for one repository, so an operator can loosen (or tighten) them where the maintainers agreed without changing repositories that belong to someone else. A repository without the key behaves exactly as before, and a later change to the hive-wide value does not reach a repository that has its own. An explicit empty sensitive-path list matches nothing, as the hive-wide key does; `human_merge_paths` scope still keeps the full fence for a repository with no `human_merge_paths` entry. An invalid override stops the config from loading, and the running hive treats one that gets through as unset. Settings → Security → Suspicious Activity and Settings → Features → Auto Merge list the overrides (read-only), `settings_read` returns them, and the admin MCP `sentinel.settings` preview names every repository with its own list, what that list leaves out, and refuses a stale confirm if an override changed. See [hive-merge.md](src/docs/hive-merge.md#contributor-lane-auto-merge). diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index 5df2e7e7df..b90713e512 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -1396,6 +1396,19 @@ func sentinelSweepOptions(cfg *config.Config, ghClient *github.Client, dashSrv * } dashSrv.AuditLogRecord("system", action, detail, "", event.Repo, event.Number) }, + // Per-repo sensitive paths (project.repo_policies[].sentinel_sensitive_paths). + SensitivePathsForRepo: sentinelRepoSensitivePathsFunc(cfg), + } +} + +// sentinelRepoSensitivePathsFunc resolves Sentinel's sensitive-path globs for +// one "owner/repo": its project.repo_policies[].sentinel_sensitive_paths +// override, else the hive-wide sentinel.sensitive_paths (or the shipped +// defaults). +func sentinelRepoSensitivePathsFunc(cfg *config.Config) func(repo string) []string { + return func(repo string) []string { + paths, _ := cfg.RepoSentinelSensitivePaths(repo) + return paths } } diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index cb31320e61..a2d1549178 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -114,10 +114,21 @@ func contributorLanePolicyFunc(cfg *config.Config) func() automerge.ContributorL ApproveHeldRunsForRegistryTrusted: p.EffectiveApproveHeldRunsForRegistryTrusted(), OwnerApprovalReleasesWorkflowFence: p.EffectiveOwnerApprovalReleasesWorkflowFence(), WorkflowFenceScope: p.EffectiveWorkflowFenceScope(), + WorkflowFenceScopeForRepo: repoWorkflowFenceScopeFunc(cfg), } } } +// repoWorkflowFenceScopeFunc resolves the contributor lane's workflow fence +// scope for one "owner/repo": its project.repo_policies[].workflow_fence_scope +// override, else the hive-wide auto_merge.contributor_lane.workflow_fence_scope. +func repoWorkflowFenceScopeFunc(cfg *config.Config) func(repo string) string { + return func(repo string) string { + scope, _ := cfg.RepoWorkflowFenceScope(repo) + return scope + } +} + // stageLabelPolicyFunc reads governor.labels.stage live so a config reload // turns the stage reconciler on/off and re-times dwell without a restart. func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy { diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index 93bc9c1fed..eaaed09cb8 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -752,7 +752,12 @@ other role. `needs_decision`, `needs_spec`), and `reporter_trust` (`enabled`, `trusted_associations`, `trusted_logins`, `untrusted_require_labels`). - `sentinel.settings` changes Sentinel's `sensitive_paths`, - `disabled_behaviors`, `exempt_logins` and `trusted_authors_block`. + `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. 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 diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 4767856175..9b72fe174b 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -1116,6 +1116,30 @@ A PR merges through this tier only when all of the following hold: content rules (permission widening, secret exposure, CI-gate weakening, remote code execution) still read every workflow patch (see [Suspicious-activity alerts](operator-reference/sweeps-and-operations.md#suspicious-activity-alerts-sentinel)). + + Both keys can be set for one repository instead of the whole hive, for + example when some repositories belong to maintainers who have not agreed + to the looser setting. Under `project.repo_policies`, + `workflow_fence_scope` replaces the hive-wide scope and + `sentinel_sensitive_paths` replaces the hive-wide Sentinel list, for that + repository only. Either can be stricter or looser than the hive-wide + value, and a later change to the hive-wide value does not reach a + 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. + + ```yaml + project: + repo_policies: + - repo: website + workflow_fence_scope: human_merge_paths + sentinel_sensitive_paths: # replaces sentinel.sensitive_paths for this repository + - OWNERS + - CODEOWNERS + - .github/workflows/release*.yml + ``` - The diff does not delete a test file or remove 25+ test lines while deleting at least 3× what it adds (`contributor-lane:tests-removed`). - Required CI is green on the current head, using the same merge-CI gate as diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 9d92dca7f9..ded5ae9837 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -273,6 +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.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". | @@ -557,7 +559,7 @@ advanced into the merge path. | `auto_merge.contributor_tier.auto_promote_after_merged` | `5` | Clean merged PRs (no revert, no sentinel label, not undone by a later merged revert) after which the contributor lane treats an author as `trusted` without an operator grant, unless the registry marks them `revoked`. Negative disables the ratchet. | | `auto_merge.contributor_lane.approve_held_runs_for_registry_trusted` | `true` | When the registry path admitted the PR author and the lane stops at `required-check-missing:` (or at `ci-unverified` with every `pull_request` run on the head held), approve the head's `action_required` workflow runs once per hive process (`POST /repos/{owner}/{repo}/actions/runs/{id}/approve`; only fork `pull_request` runs and Actions-bot runs, the ones GitHub accepts; a 403 is not retried until the head changes or the App gains Actions write), post one `hive:contributor-held-runs-approved` audit comment and log `contributor-lane approved held runs`. Never acts for claim-marker, auto-promoted or association admissions, sentinel/exclude-labelled PRs, or diffs touching `.github/workflows/**`. Needs the App's **Actions: Read and write** permission. See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | | `auto_merge.contributor_lane.owner_approval_releases_workflow_fence` | `true` | A hive owner / trusted merger's explicit approval on the **current** head — a GitHub `APPROVED` review on that commit, or a `/hive decision approve` (typed on the PR by the merger, or from the dashboard) bound to it — releases the contributor lane's `contributor-lane:workflow-path` fence (never for a head that also removes tests, which stays `contributor-lane:tests-removed`), so the lane merges a PR editing `.github/workflows/**` / `.github/actions/**` itself once CI, soak and the other gates are clear. The same approval answers a `requires_human` reviewer verdict on that head (a typed one is recorded as the decision, logging `typed approval recorded as the answer to the reviewer's requires_human question`); `/hive approve` answers the verdict but never releases the fence, so on the owner's own PR, where GitHub refuses the self-review, `/hive decision approve` is the one command for both ([Danathar/zfs-aurora-complex#254](https://github.com/Danathar/zfs-aurora-complex/pull/254)). Logs `workflow-path fence released by owner approval`, leaves one `hive:workflow-approval` audit comment per head, which says whether the verdict is answered; approval on an older head does not count, except across the hive's own base refresh: when only GitHub-verified App merges of the base branch (at most five) separate the approved head from the current one and the PR's three-dot diff is unchanged, the approval carries over and the lane logs `workflow-path fence approval carried over hive base refresh`. Any contributor push re-arms the fence. An unmarked approval binds to the PR `updated_at` pinned on the hive's first sweep of the head, not to the push, so one typed between the push and that sweep is judged stale and must be typed again ([#14754](https://github.com/hivecommons/hive/issues/14754)). Needs the App's **Workflows: Read and write**; without it the merge is refused, the PR is marked `hive:unauthorized` (`merge-workflow-path`) and parks at 090 for a person's click. `false` keeps every workflow-path PR a person's merge ([#14664](https://github.com/hivecommons/hive/issues/14664)). See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | -| `auto_merge.contributor_lane.workflow_fence_scope` | `all` | Which CI workflow / action edits trip the `contributor-lane:workflow-path` fence. `all` fences every edit under `.github/workflows/**` or `.github/actions/**`. `human_merge_paths` fences only a workflow / action file that also matches the repository's `auto_merge.human_merge_paths` (the human-merge hold's matcher), so routine workflow edits go through review, CI and soak without an owner's approval. Fails closed: a repository with no `human_merge_paths` entry keeps the full fence, a renamed workflow / action file always trips it, and a head GitHub refused to merge for want of the App's **Workflows: Read and write** is marked `hive:unauthorized` (`merge-workflow-path`) and stays fenced. The tests-removed fence, Sentinel, the human-merge hold, the held-run approval guard (never for any workflow edit) and adoption's refusal to publish workflow edits upstream are unchanged. Sentinel's default `sensitive_path` list still labels such PRs `sentinel-alert`. Any other value is rejected on save and read as `all`. Owner-only through `PUT /api/config/auto-merge`; Settings → Features → Auto Merge → Contributor-lane auto-merge → **Workflow fence scope**. See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | +| `auto_merge.contributor_lane.workflow_fence_scope` | `all` | Which CI workflow / action edits trip the `contributor-lane:workflow-path` fence. `all` fences every edit under `.github/workflows/**` or `.github/actions/**`. `human_merge_paths` fences only a workflow / action file that also matches the repository's `auto_merge.human_merge_paths` (the human-merge hold's matcher), so routine workflow edits go through review, CI and soak without an owner's approval. Fails closed: a repository with no `human_merge_paths` entry keeps the full fence, a renamed workflow / action file always trips it, and a head GitHub refused to merge for want of the App's **Workflows: Read and write** is marked `hive:unauthorized` (`merge-workflow-path`) and stays fenced. The tests-removed fence, Sentinel, the human-merge hold, the held-run approval guard (never for any workflow edit) and adoption's refusal to publish workflow edits upstream are unchanged. Sentinel's default `sensitive_path` list still labels such PRs `sentinel-alert`. Any other value is rejected on save and read as `all`. Owner-only through `PUT /api/config/auto-merge`; Settings → Features → Auto Merge → Contributor-lane auto-merge → **Workflow fence scope**. A repository can set its own value with `project.repo_policies[].workflow_fence_scope`. See [hive-merge.md](../hive-merge.md#contributor-lane-auto-merge). | | `auto_merge.contributor_lane.repos` | empty = all watched repos | Optional repo allow-list for the contributor-lane tier (bare name or `owner/repo`). | | `auto_merge.contributor_lane.exclude_labels` | `hold`, `do-not-merge`, `needs-human`, `blocked`, `needs-rebase` | Labels that keep a PR out of contributor-lane auto-merge (`do-not-merge/*` always excluded). | diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 02c8661a61..2dc9cf15d7 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -774,6 +774,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. | | `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_config_surface_ops.go b/src/pkg/adminmcp/tools_config_surface_ops.go index d748d707c0..29986f3087 100644 --- a/src/pkg/adminmcp/tools_config_surface_ops.go +++ b/src/pkg/adminmcp/tools_config_surface_ops.go @@ -842,8 +842,46 @@ type sentinelState struct { DisabledBehaviors []string `json:"disabled_behaviors"` ExemptLogins []string `json:"exempt_logins"` TrustedAuthorsBlock bool `json:"trusted_authors_block"` - label string - defaultPaths []string + // RepoOverrides are the repositories whose own list + // (repo_policies[].sentinel_sensitive_paths) replaces sensitive_paths. A + // change to sensitive_paths does not reach them, and an override added, + // changed or removed after the preview refuses the confirm. + RepoOverrides []sentinelRepoPathsOverride `json:"repo_sensitive_paths"` + label string + defaultPaths []string +} + +// sentinelRepoPathsOverride is one repository's own Sentinel sensitive-path +// list, as Settings → Security reports it. +type sentinelRepoPathsOverride struct { + Repo string `json:"repo"` + SensitivePaths []string `json:"sensitive_paths"` +} + +// readSentinelRepoOverrides parses security.sentinel.repoSensitivePaths. A +// hive older than per-repo overrides sends none, which reads as no override. +func readSentinelRepoOverrides(raw any) []sentinelRepoPathsOverride { + items, _ := raw.([]any) + var out []sentinelRepoPathsOverride + for _, item := range items { + m, _ := item.(map[string]any) + repo, _ := m["repo"].(string) + paths, ok := stringsField(m, "sensitivePaths") + if strings.TrimSpace(repo) == "" || !ok { + continue + } + out = append(out, sentinelRepoPathsOverride{Repo: repo, SensitivePaths: paths}) + } + return out +} + +// sentinelOverrideRepos names the repositories with their own list. +func sentinelOverrideRepos(overrides []sentinelRepoPathsOverride) []string { + out := make([]string, 0, len(overrides)) + for _, o := range overrides { + out = append(out, o.Repo) + } + return out } func readSentinelState(ctx context.Context, provider Provider) (sentinelState, error) { @@ -891,6 +929,7 @@ func readSentinelState(ctx context.Context, provider Provider) (sentinelState, e st.DisabledBehaviors = append(st.DisabledBehaviors, name) } } + st.RepoOverrides = readSentinelRepoOverrides(sc["repoSensitivePaths"]) st.label, _ = sc["label"].(string) if strings.TrimSpace(st.label) == "" { st.label = config.DefaultSentinelLabel @@ -912,7 +951,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. 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, 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." } func (sentinelSettingsOp) InputSchema() map[string]any { _, names := sentinelBehaviorDescriptions() @@ -1027,6 +1066,9 @@ 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.") + } after.SensitivePaths = effective if !sameList(before.SensitivePaths, effective, foldExact) || before.SensitivePathsDefault != after.SensitivePathsDefault { changes = append(changes, settingChange{Field: "sentinel.sensitive_paths", Before: before.SensitivePaths, After: effective}) @@ -1097,11 +1139,15 @@ func (sentinelSettingsOp) PreviewWithProvider(ctx context.Context, args map[stri func sentinelDisclosure(before, after sentinelState, descriptions map[string]string) string { 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(pathsRemoved) > 0 { - fewer = append(fewer, "a pull request whose only sensitive-path match is "+listLabel(pathsRemoved)+" is no longer flagged by the sensitive_path rule (other rules still look at it)") + 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)") } if len(pathsAdded) > 0 { - more = append(more, "pull requests touching "+listLabel(pathsAdded)+" are flagged by the sensitive_path rule") + more = append(more, "pull requests"+where+" touching "+listLabel(pathsAdded)+" are flagged by the sensitive_path rule") } disabled, enabled := listDiff(before.DisabledBehaviors, after.DisabledBehaviors, foldCase) for _, name := range disabled { @@ -1127,8 +1173,26 @@ func sentinelDisclosure(before, after sentinelState, descriptions map[string]str if len(more) > 0 { moreNote = " Also: " + strings.Join(more, "; ") + "." } + moreNote += sentinelRepoOverrideStanding(before.RepoOverrides, 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 } return "No widening: Sentinel flags every pull request it flags today." + moreNote } + +// sentinelRepoOverrideStanding names, for each repository with its own +// sensitive-path list, the hive-wide globs that list leaves out: a widening +// already in force there, which this write does not change. +func sentinelRepoOverrideStanding(overrides []sentinelRepoPathsOverride, hiveWide []string) string { + var parts []string + for _, o := range overrides { + _, leftOut := listDiff(hiveWide, o.SensitivePaths, foldExact) + if len(leftOut) > 0 { + parts = append(parts, o.Repo+" does not flag "+listLabel(leftOut)) + } + } + if len(parts) == 0 { + return "" + } + return " Already in force and not changed by this write (per-repository lists): " + strings.Join(parts, "; ") + "." +} diff --git a/src/pkg/adminmcp/tools_sentinel_repo_overrides_test.go b/src/pkg/adminmcp/tools_sentinel_repo_overrides_test.go new file mode 100644 index 0000000000..45d7f50f37 --- /dev/null +++ b/src/pkg/adminmcp/tools_sentinel_repo_overrides_test.go @@ -0,0 +1,58 @@ +package adminmcp + +import ( + "context" + "errors" + "strings" + "testing" +) + +func surfaceGovernorWithRepoOverrides() map[string]any { + g := surfaceGovernor() + g["security"].(map[string]any)["sentinel"].(map[string]any)["repoSensitivePaths"] = []any{ + map[string]any{"repo": "acme/api", "sensitivePaths": []any{"OWNERS", ".github/workflows/**", "**/.github/workflows/**", "hive.yaml"}}, + map[string]any{"repo": "acme/website", "sensitivePaths": []any{"OWNERS"}}, + } + return g +} + +// A hive-wide sentinel.settings change names the repositories that keep their +// own list, both in the effects and in the widening disclosure, and what a +// looser per-repository list already leaves out. On v6 tip the preview never +// reads the per-repository lists, so none of the repositories is named. +func TestSentinelSettingsOpNamesReposWithTheirOwnList(t *testing.T) { + p, _ := capPreview(t, surfaceHandler(&surfaceProvider{governor: surfaceGovernorWithRepoOverrides()}), WriteOpSentinelSettings, map[string]any{ + "sensitive_paths": map[string]any{"remove": []any{"hive.yaml"}}, + }) + if !strings.HasPrefix(p.WideningDisclosure, "Widening:") { + t.Fatalf("disclosure = %q", p.WideningDisclosure) + } + if !strings.Contains(p.WideningDisclosure, "except in acme/api, acme/website, which keep their own list") { + t.Fatalf("widening disclosure does not name the repositories the change skips: %q", p.WideningDisclosure) + } + if !strings.Contains(p.WideningDisclosure, "acme/website does not flag .github/workflows/**, **/.github/workflows/**") { + t.Fatalf("widening disclosure does not name what acme/website's own list leaves out: %q", p.WideningDisclosure) + } + if strings.Contains(p.WideningDisclosure, "acme/api does not flag") { + t.Fatalf("acme/api's list covers the new hive-wide list and must not be named as leaving anything out: %q", p.WideningDisclosure) + } + if !strings.Contains(strings.Join(p.Effects, "\n"), "Not changed by this write: acme/api, acme/website") { + t.Fatalf("effects do not name the repositories with their own list: %v", p.Effects) + } +} + +// The per-repository lists are part of the preview's basis: one added after +// the preview refuses the confirm. +func TestSentinelSettingsOpRepoOverrideChangeMakesPreviewStale(t *testing.T) { + provider := &surfaceProvider{governor: surfaceGovernorWithRepoOverrides()} + h := surfaceHandler(provider) + _, id := capPreview(t, h, WriteOpSentinelSettings, map[string]any{"exempt_logins": map[string]any{"add": []any{"renovate[bot]"}}}) + sn := provider.governor["security"].(map[string]any)["sentinel"].(map[string]any) + sn["repoSensitivePaths"] = append(sn["repoSensitivePaths"].([]any), map[string]any{"repo": "acme/new", "sensitivePaths": []any{}}) + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); !errors.Is(err, ErrConfirmationStale) { + t.Fatalf("stale confirm err = %v, want ErrConfirmationStale", err) + } + if len(provider.requests) != 0 { + t.Fatalf("a stale confirm wrote %+v", provider.requests) + } +} diff --git a/src/pkg/adminmcp/tools_settings.go b/src/pkg/adminmcp/tools_settings.go index e3cbc3608a..1146f2f7f7 100644 --- a/src/pkg/adminmcp/tools_settings.go +++ b/src/pkg/adminmcp/tools_settings.go @@ -36,7 +36,7 @@ var settingsSections = []SettingsSection{ {"dashboard", "/api/config/dashboard", "Dashboard settings."}, {"channels", "/api/config/channels", "Channels: email, push, Slack, Matrix, Microsoft Teams and Telegram targets, GitHub mentions and Actions identity (secret values are never returned; secrets are named by environment variable)."}, {"escalation", "/api/config/escalation", "Escalation settings."}, - {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths, human_merge_pin_only)."}, + {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths, human_merge_pin_only) and which repositories override the contributor lane's workflow_fence_scope (contributor_lane.workflow_fence_scope_repos)."}, {"review", "/api/config/review", "Review settings: reviewers, perspectives, review bots and gates."}, {"convergence", "/api/config/convergence", "Convergence settings."}, {"sla", "/api/config/sla", "SLA settings."}, diff --git a/src/pkg/config/repo_policy.go b/src/pkg/config/repo_policy.go index ca020b3038..ab70209a1b 100644 --- a/src/pkg/config/repo_policy.go +++ b/src/pkg/config/repo_policy.go @@ -61,6 +61,17 @@ type RepoPolicy struct { // gitlab.gitlab_url / gitea.gitea_url / github's base URL for the repo's // forge kind. Read it through Config.ForgeURLForRepo. ForgeURL string `yaml:"forge_url,omitempty" json:"forge_url,omitempty"` + // SentinelSensitivePaths overrides sentinel.sensitive_paths for this + // repo: the globs whose change raises Sentinel's sensitive_path finding + // on this repo's pull requests. nil (unset) inherits the hive-wide list; + // an explicit empty list matches nothing, as the hive-wide key does. + // Read it through Config.RepoSentinelSensitivePaths. + SentinelSensitivePaths []string `yaml:"sentinel_sensitive_paths,omitempty" json:"sentinel_sensitive_paths,omitempty"` + // WorkflowFenceScope overrides + // auto_merge.contributor_lane.workflow_fence_scope for this repo: "all" + // or "human_merge_paths". Empty inherits the hive-wide value. Read it + // through Config.RepoWorkflowFenceScope. + WorkflowFenceScope string `yaml:"workflow_fence_scope,omitempty" json:"workflow_fence_scope,omitempty"` } // Per-repo merge strategies (hivecommons/hive#10886). The strategy decides how @@ -414,7 +425,7 @@ func (c *Config) SetSelfAuthorizationHoldForRepoAndSave(repo string, enabled *bo } func repoPolicyHasNoOverrides(rp RepoPolicy) bool { - return rp.SelfAuthorizationHold == nil && rp.ReporterTrustHold == nil && rp.AutoMerge == nil && rp.ACMMLevel == nil && !rp.ACMMPinned && rp.ACMMLastAutomatic == nil && !rp.LabelDriven && !rp.ReleaseOnApprove && rp.ReleaseVersionSource == "" && rp.MergeStrategy == "" && rp.MergeFrontTimeout == "" && rp.RedMainThreshold == "" && rp.MaxOpenHeldPRs == nil && len(rp.LabelDrivenApprovalLabels) == 0 && len(rp.LabelDrivenSupersedeParkActors) == 0 && len(rp.CompanionRepos) == 0 + return rp.SelfAuthorizationHold == nil && rp.ReporterTrustHold == nil && rp.AutoMerge == nil && rp.ACMMLevel == nil && !rp.ACMMPinned && rp.ACMMLastAutomatic == nil && !rp.LabelDriven && !rp.ReleaseOnApprove && rp.ReleaseVersionSource == "" && rp.MergeStrategy == "" && rp.MergeFrontTimeout == "" && rp.RedMainThreshold == "" && rp.MaxOpenHeldPRs == nil && len(rp.LabelDrivenApprovalLabels) == 0 && len(rp.LabelDrivenSupersedeParkActors) == 0 && len(rp.CompanionRepos) == 0 && rp.SentinelSensitivePaths == nil && strings.TrimSpace(rp.WorkflowFenceScope) == "" } // ValidateRepoMergeStrategy accepts "" (unset, meaning direct), "direct" and diff --git a/src/pkg/config/repo_policy_sentinel_fence.go b/src/pkg/config/repo_policy_sentinel_fence.go new file mode 100644 index 0000000000..117d5758ed --- /dev/null +++ b/src/pkg/config/repo_policy_sentinel_fence.go @@ -0,0 +1,147 @@ +package config + +import ( + "fmt" + "strings" +) + +// Per-repository overrides of two hive-wide merge-safety keys: +// +// - repo_policies[].sentinel_sensitive_paths overrides +// sentinel.sensitive_paths for one repository's pull requests. +// - repo_policies[].workflow_fence_scope overrides +// auto_merge.contributor_lane.workflow_fence_scope for one repository. +// +// Both are opt-in: a repository without the key reads the hive-wide value, +// so a config that never sets them behaves exactly as before. An override +// may be stricter or looser than the hive-wide value, and a later change +// to the hive-wide value does not touch a repository that overrides it. +// +// Fail closed: Validate rejects an invalid override, so a config carrying +// one does not load or reload. If one reaches the running config anyway, +// the resolvers ignore it and use the hive-wide value. + +// RepoSentinelSensitivePaths returns the Sentinel sensitive-path globs for +// repo and whether they come from its repo_policies override. Without a +// valid override it returns the hive-wide list (sentinel.sensitive_paths, +// or the shipped defaults when that is unset). An explicit empty override +// is returned as a non-nil empty list, which matches nothing. +func (c *Config) RepoSentinelSensitivePaths(repo string) ([]string, bool) { + if c == nil { + return SentinelConfig{}.EffectiveSensitivePaths(), false + } + if rp, ok := c.RepoPolicyFor(repo); ok && rp.SentinelSensitivePaths != nil && + ValidateRepoSentinelSensitivePaths("", rp.SentinelSensitivePaths) == nil { + return append([]string{}, rp.SentinelSensitivePaths...), true + } + return c.Sentinel.EffectiveSensitivePaths(), false +} + +// RepoWorkflowFenceScope returns the contributor lane's workflow fence scope +// for repo ("all" or "human_merge_paths") and whether it comes from its +// repo_policies override. Without a valid override it returns the hive-wide +// auto_merge.contributor_lane.workflow_fence_scope. +func (c *Config) RepoWorkflowFenceScope(repo string) (string, bool) { + if c == nil { + return ContributorLaneWorkflowFenceScopeAll, false + } + if rp, ok := c.RepoPolicyFor(repo); ok { + if scope, valid := repoPolicyFenceScopeValue(rp.WorkflowFenceScope); valid { + return scope, true + } + } + return c.AutoMerge.ContributorLane.EffectiveWorkflowFenceScope(), false +} + +// repoPolicyFenceScopeValue normalizes a repo_policies[].workflow_fence_scope +// value. ok is false for an unset or unknown value. +func repoPolicyFenceScopeValue(raw string) (string, bool) { + switch strings.ToLower(strings.TrimSpace(raw)) { + case ContributorLaneWorkflowFenceScopeAll: + return ContributorLaneWorkflowFenceScopeAll, true + case ContributorLaneWorkflowFenceScopeHumanMergePaths: + return ContributorLaneWorkflowFenceScopeHumanMergePaths, true + } + return "", false +} + +// ValidateRepoSentinelSensitivePaths rejects blank patterns in a +// repo_policies[].sentinel_sensitive_paths override, as ValidateSentinel +// does for the hive-wide list. nil (unset) and an empty list are valid. +func ValidateRepoSentinelSensitivePaths(field string, paths []string) error { + for _, p := range paths { + if strings.TrimSpace(p) == "" { + return fmt.Errorf("%s: sentinel_sensitive_paths must not contain blank patterns", field) + } + } + return nil +} + +// ValidateRepoWorkflowFenceScope accepts "" (unset), "all" and +// "human_merge_paths" (any case). +func ValidateRepoWorkflowFenceScope(field, value string) error { + if strings.TrimSpace(value) == "" { + return nil + } + if _, ok := repoPolicyFenceScopeValue(value); !ok { + return fmt.Errorf("%s: invalid workflow_fence_scope %q (allowed: %s)", field, value, strings.Join(ContributorLaneWorkflowFenceScopes, ", ")) + } + return nil +} + +// RepoSensitivePathsOverride is one repository's Sentinel sensitive-path +// override, as the dashboard and admin MCP show it. +type RepoSensitivePathsOverride struct { + Repo string + Paths []string +} + +// RepoWorkflowFenceScopeOverride is one repository's workflow fence scope +// override, as the dashboard and admin MCP show it. +type RepoWorkflowFenceScopeOverride struct { + Repo string + Scope string +} + +// SentinelSensitivePathsRepoOverrides lists the repositories whose valid +// repo_policies override replaces sentinel.sensitive_paths, in config +// order, with org-qualified names. +func (c *Config) SentinelSensitivePathsRepoOverrides() []RepoSensitivePathsOverride { + var out []RepoSensitivePathsOverride + for _, rp := range c.repoPoliciesSnapshot() { + if rp.SentinelSensitivePaths == nil || ValidateRepoSentinelSensitivePaths("", rp.SentinelSensitivePaths) != nil { + continue + } + out = append(out, RepoSensitivePathsOverride{Repo: c.repoPolicyDisplayName(rp.Repo), Paths: append([]string{}, rp.SentinelSensitivePaths...)}) + } + return out +} + +// WorkflowFenceScopeRepoOverrides lists the repositories whose valid +// repo_policies override replaces +// auto_merge.contributor_lane.workflow_fence_scope, in config order, with +// org-qualified names. +func (c *Config) WorkflowFenceScopeRepoOverrides() []RepoWorkflowFenceScopeOverride { + var out []RepoWorkflowFenceScopeOverride + for _, rp := range c.repoPoliciesSnapshot() { + scope, ok := repoPolicyFenceScopeValue(rp.WorkflowFenceScope) + if !ok { + continue + } + out = append(out, RepoWorkflowFenceScopeOverride{Repo: c.repoPolicyDisplayName(rp.Repo), Scope: scope}) + } + return out +} + +func (c *Config) repoPoliciesSnapshot() []RepoPolicy { + if c == nil { + return nil + } + repoPauseMu.RLock() + defer repoPauseMu.RUnlock() + return append([]RepoPolicy(nil), c.Project.RepoPolicies...) +} + +func (c *Config) repoPolicyDisplayName(repo string) string { + return QualifyRepo(c.Project.Org, repo) +} diff --git a/src/pkg/config/repo_policy_sentinel_fence_test.go b/src/pkg/config/repo_policy_sentinel_fence_test.go new file mode 100644 index 0000000000..200e6546c5 --- /dev/null +++ b/src/pkg/config/repo_policy_sentinel_fence_test.go @@ -0,0 +1,178 @@ +package config + +import ( + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func loadRepoPolicySentinelFenceYAML(t *testing.T, raw string) *Config { + t.Helper() + var cfg Config + if err := yaml.Unmarshal([]byte(raw), &cfg); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return &cfg +} + +// repo_policies[].sentinel_sensitive_paths replaces sentinel.sensitive_paths +// for that repository only. On v6 tip there is no such key or resolver. +func TestRepoSentinelSensitivePathsResolvesPerRepo(t *testing.T) { + cfg := loadRepoPolicySentinelFenceYAML(t, ` +project: + org: acme + repos: [a, b, c, d] + repo_policies: + - repo: a + sentinel_sensitive_paths: ["OWNERS", ".github/workflows/**"] + - repo: acme/b + sentinel_sensitive_paths: [] + - repo: d + sentinel_sensitive_paths: ["OWNERS", " "] +sentinel: + sensitive_paths: ["OWNERS", "Justfile", "**/requirements*.txt"] +`) + for _, tc := range []struct { + repo string + want string + override bool + }{ + {repo: "a", want: "OWNERS,.github/workflows/**", override: true}, + {repo: "acme/a", want: "OWNERS,.github/workflows/**", override: true}, + {repo: "b", want: "", override: true}, + {repo: "c", want: "OWNERS,Justfile,**/requirements*.txt"}, + // A blank pattern makes the override invalid: the hive-wide list applies. + {repo: "d", want: "OWNERS,Justfile,**/requirements*.txt"}, + } { + got, override := cfg.RepoSentinelSensitivePaths(tc.repo) + if strings.Join(got, ",") != tc.want || override != tc.override { + t.Errorf("RepoSentinelSensitivePaths(%q) = %v, %v; want %q, %v", tc.repo, got, override, tc.want, tc.override) + } + } + // An explicit empty override must stay non-nil: Sentinel reads nil as + // the shipped defaults and an empty list as "match nothing". + if got, _ := cfg.RepoSentinelSensitivePaths("b"); got == nil { + t.Error("an explicit empty override resolved to nil, which Sentinel reads as the shipped defaults") + } + + // A hive-wide change does not touch a repository that overrides it. + cfg.Sentinel.SensitivePaths = []string{"CODEOWNERS"} + if got, _ := cfg.RepoSentinelSensitivePaths("a"); strings.Join(got, ",") != "OWNERS,.github/workflows/**" { + t.Errorf("hive-wide change reached overridden repo a: %v", got) + } + if got, _ := cfg.RepoSentinelSensitivePaths("c"); strings.Join(got, ",") != "CODEOWNERS" { + t.Errorf("hive-wide change did not reach repo c: %v", got) + } + // Unset hive-wide list: a repository without an override gets the defaults. + cfg.Sentinel.SensitivePaths = nil + if got, override := cfg.RepoSentinelSensitivePaths("c"); override || strings.Join(got, ",") != strings.Join(DefaultSentinelSensitivePaths(), ",") { + t.Errorf("repo c with no hive-wide list = %v, %v; want the shipped defaults", got, override) + } + + overrides := cfg.SentinelSensitivePathsRepoOverrides() + var names []string + for _, o := range overrides { + names = append(names, o.Repo) + } + if strings.Join(names, ",") != "acme/a,acme/b" { + t.Errorf("SentinelSensitivePathsRepoOverrides repos = %v, want acme/a,acme/b (the invalid d is not an override)", names) + } + + var nilCfg *Config + if got, override := nilCfg.RepoSentinelSensitivePaths("a"); override || len(got) == 0 { + t.Errorf("nil config = %v, %v; want the shipped defaults", got, override) + } +} + +// repo_policies[].workflow_fence_scope replaces +// auto_merge.contributor_lane.workflow_fence_scope for that repository only, +// whether stricter or looser. On v6 tip there is no such key or resolver. +func TestRepoWorkflowFenceScopeResolvesPerRepo(t *testing.T) { + cfg := loadRepoPolicySentinelFenceYAML(t, ` +project: + org: acme + repos: [a, b, c, d] + repo_policies: + - repo: a + workflow_fence_scope: human_merge_paths + - repo: acme/b + workflow_fence_scope: " ALL " + - repo: d + workflow_fence_scope: release_only +auto_merge: + contributor_lane: + workflow_fence_scope: all +`) + check := func(repo, want string, override bool) { + t.Helper() + got, o := cfg.RepoWorkflowFenceScope(repo) + if got != want || o != override { + t.Errorf("RepoWorkflowFenceScope(%q) = %q, %v; want %q, %v", repo, got, o, want, override) + } + } + check("a", ContributorLaneWorkflowFenceScopeHumanMergePaths, true) + check("acme/a", ContributorLaneWorkflowFenceScopeHumanMergePaths, true) + check("b", ContributorLaneWorkflowFenceScopeAll, true) + check("c", ContributorLaneWorkflowFenceScopeAll, false) + // An unknown override is ignored: the hive-wide value applies. + check("d", ContributorLaneWorkflowFenceScopeAll, false) + + // Loosening the hive-wide value does not loosen b, which pins "all". + cfg.AutoMerge.ContributorLane.WorkflowFenceScope = ContributorLaneWorkflowFenceScopeHumanMergePaths + check("b", ContributorLaneWorkflowFenceScopeAll, true) + check("c", ContributorLaneWorkflowFenceScopeHumanMergePaths, false) + check("d", ContributorLaneWorkflowFenceScopeHumanMergePaths, false) + + overrides := cfg.WorkflowFenceScopeRepoOverrides() + var got []string + for _, o := range overrides { + got = append(got, o.Repo+"="+o.Scope) + } + if strings.Join(got, ",") != "acme/a=human_merge_paths,acme/b=all" { + t.Errorf("WorkflowFenceScopeRepoOverrides = %v", got) + } + + var nilCfg *Config + if scope, override := nilCfg.RepoWorkflowFenceScope("a"); scope != ContributorLaneWorkflowFenceScopeAll || override { + t.Errorf("nil config = %q, %v; want all, false", scope, override) + } +} + +func TestValidateRepoSentinelFenceOverrides(t *testing.T) { + field := `project.repo_policies: repo "a"` + for _, ok := range [][]string{nil, {}, {"OWNERS", "**/go.mod"}} { + if err := ValidateRepoSentinelSensitivePaths(field, ok); err != nil { + t.Errorf("ValidateRepoSentinelSensitivePaths(%q) = %v, want nil", ok, err) + } + } + if err := ValidateRepoSentinelSensitivePaths(field, []string{"OWNERS", " "}); err == nil || !strings.Contains(err.Error(), `repo "a"`) { + t.Errorf("blank pattern = %v, want an error naming the repo", err) + } + for _, ok := range []string{"", " ", "all", "human_merge_paths", "Human_Merge_Paths"} { + if err := ValidateRepoWorkflowFenceScope(field, ok); err != nil { + t.Errorf("ValidateRepoWorkflowFenceScope(%q) = %v, want nil", ok, err) + } + } + if err := ValidateRepoWorkflowFenceScope(field, "release_only"); err == nil || !strings.Contains(err.Error(), "invalid workflow_fence_scope") || !strings.Contains(err.Error(), `repo "a"`) { + t.Errorf("unknown scope = %v, want an error naming the field and repo", err) + } +} + +// A policy holding only one of the new overrides must not be pruned when +// another override on it is cleared, or the override is silently dropped on +// save. +func TestRepoPolicySentinelFenceOverridesCountAsOverrides(t *testing.T) { + if repoPolicyHasNoOverrides(RepoPolicy{Repo: "a", SentinelSensitivePaths: []string{"OWNERS"}}) { + t.Error("a repo policy with only sentinel_sensitive_paths must count as an override") + } + if repoPolicyHasNoOverrides(RepoPolicy{Repo: "a", SentinelSensitivePaths: []string{}}) { + t.Error("an explicit empty sentinel_sensitive_paths must count as an override") + } + if repoPolicyHasNoOverrides(RepoPolicy{Repo: "a", WorkflowFenceScope: ContributorLaneWorkflowFenceScopeHumanMergePaths}) { + t.Error("a repo policy with only workflow_fence_scope must count as an override") + } + if !repoPolicyHasNoOverrides(RepoPolicy{Repo: "a"}) { + t.Error("an empty repo policy must count as no override") + } +} diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index b31d32f6f2..fa158adb68 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -110,6 +110,12 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := ValidateMaxOpenHeldPRs(fmt.Sprintf("project.repo_policies: repo %q", rp.Repo), rp.MaxOpenHeldPRs); err != nil { return err } + if err := ValidateRepoSentinelSensitivePaths(fmt.Sprintf("project.repo_policies: repo %q", rp.Repo), rp.SentinelSensitivePaths); err != nil { + return err + } + if err := ValidateRepoWorkflowFenceScope(fmt.Sprintf("project.repo_policies: repo %q", rp.Repo), rp.WorkflowFenceScope); err != nil { + return err + } } if err := ValidateMergeFrontTimeout("project", c.Project.MergeFrontTimeout); err != nil { return err diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 5a9da70eec..49a661c8f5 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -551,6 +551,13 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { if contributorLaneLabels == nil { contributorLaneLabels = append([]string{}, config.DefaultContributorLaneExcludeLabels...) } + // Repositories whose repo_policies override replaces workflow_fence_scope; + // the hive-wide value (and a change to it) does not apply to them. + fenceOverrides := cfg.WorkflowFenceScopeRepoOverrides() + contributorLaneFenceScopeRepos := make([]map[string]interface{}, 0, len(fenceOverrides)) + for _, o := range fenceOverrides { + contributorLaneFenceScopeRepos = append(contributorLaneFenceScopeRepos, map[string]interface{}{"repo": o.Repo, "workflow_fence_scope": o.Scope}) + } return map[string]interface{}{ "self_authored": selfAuthored, "self_authored_set": am.SelfAuthored != nil, @@ -604,6 +611,7 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "owner_approval_releases_workflow_fence": cl.EffectiveOwnerApprovalReleasesWorkflowFence(), "workflow_fence_scope": cl.EffectiveWorkflowFenceScope(), "workflow_fence_scopes": config.ContributorLaneWorkflowFenceScopes, + "workflow_fence_scope_repos": contributorLaneFenceScopeRepos, }, } } diff --git a/src/pkg/dashboard/api_governor_security.go b/src/pkg/dashboard/api_governor_security.go index a9af31ec78..346ae221a1 100644 --- a/src/pkg/dashboard/api_governor_security.go +++ b/src/pkg/dashboard/api_governor_security.go @@ -423,14 +423,21 @@ func securitySectionResponse(cfg *config.Config) map[string]interface{} { "sandboxedAgents": sandboxed, "totalAgents": len(cfg.Agents), "sandboxWarnings": sandboxWarnings, - "sentinel": sentinelSectionResponse(cfg.Sentinel), + "sentinel": sentinelSectionResponse(cfg.Sentinel, cfg.SentinelSensitivePathsRepoOverrides()), } } // sentinelSectionResponse renders the suspicious-activity block. It sends // the EFFECTIVE sensitive-path list plus whether that list is the shipped // default, so the UI can show the defaults pre-filled and offer a reset. -func sentinelSectionResponse(sc config.SentinelConfig) map[string]interface{} { +// repoSensitivePaths lists the repositories whose repo_policies override +// replaces that list; the hive-wide list (and a change to it) does not apply +// to them. +func sentinelSectionResponse(sc config.SentinelConfig, overrides []config.RepoSensitivePathsOverride) map[string]interface{} { + repoPaths := make([]map[string]interface{}, 0, len(overrides)) + for _, o := range overrides { + repoPaths = append(repoPaths, map[string]interface{}{"repo": o.Repo, "sensitivePaths": nonNilStrings(o.Paths)}) + } rules := config.SentinelBehaviors() behaviors := make([]map[string]interface{}, 0, len(rules)) disabled := map[string]bool{} @@ -450,6 +457,7 @@ func sentinelSectionResponse(sc config.SentinelConfig) map[string]interface{} { "sensitivePaths": sc.EffectiveSensitivePaths(), "sensitivePathsDefault": sc.SensitivePaths == nil, "defaultSensitivePaths": config.DefaultSentinelSensitivePaths(), + "repoSensitivePaths": repoPaths, "behaviors": behaviors, "exemptLogins": nonNilStrings(sc.ExemptLogins), "trustedAuthorsBlock": sc.TrustedAuthorsBlock, diff --git a/src/pkg/dashboard/api_repo_policy_sentinel_fence_test.go b/src/pkg/dashboard/api_repo_policy_sentinel_fence_test.go new file mode 100644 index 0000000000..284a249dd7 --- /dev/null +++ b/src/pkg/dashboard/api_repo_policy_sentinel_fence_test.go @@ -0,0 +1,60 @@ +package dashboard + +import ( + "net/http" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// Settings shows which repositories override the hive-wide Sentinel list and +// workflow fence scope, and a hive-wide save leaves those overrides alone. On +// v6 tip neither response carries the override lists. +func TestRepoPolicySentinelFenceOverridesShownInSettings(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Project.RepoPolicies = []config.RepoPolicy{ + {Repo: "repo1", SentinelSensitivePaths: []string{"OWNERS"}, WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths}, + {Repo: "myorg/repo2", SentinelSensitivePaths: []string{}}, + } + + sn := decodeJSON(t, doGet(s, "/api/config/governor"))["security"].(map[string]any)["sentinel"].(map[string]any) + repoPaths, ok := sn["repoSensitivePaths"].([]any) + if !ok || len(repoPaths) != 2 { + t.Fatalf("repoSensitivePaths = %#v, want two overrides", sn["repoSensitivePaths"]) + } + first := repoPaths[0].(map[string]any) + if first["repo"] != "myorg/repo1" || len(first["sensitivePaths"].([]any)) != 1 { + t.Fatalf("first override = %#v", first) + } + second := repoPaths[1].(map[string]any) + if second["repo"] != "myorg/repo2" || second["sensitivePaths"] == nil || len(second["sensitivePaths"].([]any)) != 0 { + t.Fatalf("explicit empty override must show as an empty list: %#v", second) + } + + rec := doOwnerGet(s, "/api/config/auto-merge") + if rec.Code != http.StatusOK { + t.Fatalf("GET auto-merge: %d", rec.Code) + } + cl := decodeJSON(t, rec)["contributor_lane"].(map[string]any) + if cl["workflow_fence_scope"] != config.ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("hive-wide workflow_fence_scope = %v, want all", cl["workflow_fence_scope"]) + } + fence, ok := cl["workflow_fence_scope_repos"].([]any) + if !ok || len(fence) != 1 { + t.Fatalf("workflow_fence_scope_repos = %#v, want one override", cl["workflow_fence_scope_repos"]) + } + if o := fence[0].(map[string]any); o["repo"] != "myorg/repo1" || o["workflow_fence_scope"] != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("fence override = %#v", o) + } + + // A hive-wide Sentinel save does not touch a repository's own list. + if rec := doPut(s, "/api/config/governor/security", map[string]any{"sentinel": map[string]any{"sensitivePaths": []string{"CODEOWNERS"}}}); rec.Code != http.StatusOK { + t.Fatalf("PUT security: %d %s", rec.Code, rec.Body.String()) + } + if got, override := deps.Config.RepoSentinelSensitivePaths("repo1"); !override || len(got) != 1 || got[0] != "OWNERS" { + t.Fatalf("repo1 after hive-wide save = %v, %v; want its own [OWNERS]", got, override) + } + if got, override := deps.Config.RepoSentinelSensitivePaths("repo3"); override || len(got) != 1 || got[0] != "CODEOWNERS" { + t.Fatalf("repo3 after hive-wide save = %v, %v; want the hive-wide [CODEOWNERS]", got, override) + } +} diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 1c2d0db68d..3812682bdd 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -405,6 +405,8 @@ const amContributorLaneFenceScopes = Array.isArray(amContributorLane.workflow_fence_scopes) && amContributorLane.workflow_fence_scopes.length ? amContributorLane.workflow_fence_scopes : ['all','human_merge_paths']; const amContributorLaneFenceScopeLabel = { all: "all — every workflow / action file edit", human_merge_paths: "human_merge_paths — only workflow / action files listed in Human-merge paths" }; const amContributorLaneFenceScopeOptions = amContributorLaneFenceScopes.map(v => ``).join(''); + const amContributorLaneFenceScopeRepos = Array.isArray(amContributorLane.workflow_fence_scope_repos) ? amContributorLane.workflow_fence_scope_repos : []; + const amContributorLaneFenceScopeReposText = amContributorLaneFenceScopeRepos.length ? amContributorLaneFenceScopeRepos.map(o => `${esc(o.repo)}: ${esc(o.workflow_fence_scope)}`).join(', ') : 'none'; const amContributorLaneRepoSet = new Set((Array.isArray(amContributorLane.repos) ? amContributorLane.repos : []).map(r => String(r).toLowerCase())); const amContributorLaneRepoOptions = watchedRepos.map(r => ``).join(''); // Per-repo merge policy lists offer project.repos as owner/repo (the form @@ -674,6 +676,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. Overrides are set in hive.yaml.

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 1c8e4e1c36..495fb8103e 100644 --- a/src/pkg/dashboard/static-src/js/config-watchdog-security.js +++ b/src/pkg/dashboard/static-src/js/config-watchdog-security.js @@ -982,6 +982,8 @@ get the blocking alert label; trusted authors default to notice-only. */ const sn = sec.sentinel || {}; 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'; const snBehaviors = (sn.behaviors || []).map(b => `
@@ -1003,6 +1005,7 @@
+

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.

diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 2d3da69ee4..166590a0dd 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -66090,6 +66090,8 @@

Escalation Breaker

get the blocking alert label; trusted authors default to notice-only. */ const sn = sec.sentinel || {}; 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'; const snBehaviors = (sn.behaviors || []).map(b => `
@@ -66111,6 +66113,7 @@

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.

@@ -66857,6 +66860,8 @@

${esc(s.title)}

const amContributorLaneFenceScopes = Array.isArray(amContributorLane.workflow_fence_scopes) && amContributorLane.workflow_fence_scopes.length ? amContributorLane.workflow_fence_scopes : ['all','human_merge_paths']; const amContributorLaneFenceScopeLabel = { all: "all — every workflow / action file edit", human_merge_paths: "human_merge_paths — only workflow / action files listed in Human-merge paths" }; const amContributorLaneFenceScopeOptions = amContributorLaneFenceScopes.map(v => ``).join(''); + const amContributorLaneFenceScopeRepos = Array.isArray(amContributorLane.workflow_fence_scope_repos) ? amContributorLane.workflow_fence_scope_repos : []; + const amContributorLaneFenceScopeReposText = amContributorLaneFenceScopeRepos.length ? amContributorLaneFenceScopeRepos.map(o => `${esc(o.repo)}: ${esc(o.workflow_fence_scope)}`).join(', ') : 'none'; const amContributorLaneRepoSet = new Set((Array.isArray(amContributorLane.repos) ? amContributorLane.repos : []).map(r => String(r).toLowerCase())); const amContributorLaneRepoOptions = watchedRepos.map(r => ``).join(''); // Per-repo merge policy lists offer project.repos as owner/repo (the form @@ -67126,6 +67131,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. Overrides are set in hive.yaml.

diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 5e098c4a01..0016d0075f 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -235,6 +235,11 @@ type ContributorLanePolicy struct { // repository's auto_merge.human_merge_paths; anything else (the default, // "all") fences every such edit. See automerge_workflow_fence_scope.go. WorkflowFenceScope string + // WorkflowFenceScopeForRepo, when set, resolves the scope for one + // "owner/repo", applying project.repo_policies[].workflow_fence_scope + // over WorkflowFenceScope. nil means every repository uses + // WorkflowFenceScope. + WorkflowFenceScopeForRepo func(repo string) string } // Contributor-lane auto-promotion scopes; mirrors diff --git a/src/pkg/github/automerge/automerge_workflow_fence_scope.go b/src/pkg/github/automerge/automerge_workflow_fence_scope.go index 8cdb19b2ea..bb28eb9061 100644 --- a/src/pkg/github/automerge/automerge_workflow_fence_scope.go +++ b/src/pkg/github/automerge/automerge_workflow_fence_scope.go @@ -29,6 +29,11 @@ package automerge // The tests-removed fence, Sentinel, the human-merge hold and the pin-only // exception are untouched. // +// A repository can override the hive-wide scope with +// project.repo_policies[].workflow_fence_scope; the policy's +// WorkflowFenceScopeForRepo resolves it per pull request, so every reader +// below sees the PR's own repository's scope. +// // Every merge-side reader (the lane, the stage engine's explanations via // headDiffFence, the merge asks via headManualMergeRule, `/hive approve`) // goes through contributorLaneMergeFence, so they cannot disagree. @@ -44,10 +49,16 @@ import ( ) // workflowFenceScopedToHumanMergePaths reports whether the policy limits the -// workflow-path fence to human_merge_paths. Anything but that exact value -// (any case) is the full fence. -func (p ContributorLanePolicy) workflowFenceScopedToHumanMergePaths() bool { - return strings.EqualFold(strings.TrimSpace(p.WorkflowFenceScope), config.ContributorLaneWorkflowFenceScopeHumanMergePaths) +// workflow-path fence to human_merge_paths for repo ("owner/repo"): the +// repository's project.repo_policies[].workflow_fence_scope when +// WorkflowFenceScopeForRepo resolves one, else WorkflowFenceScope. Anything +// but that exact value (any case) is the full fence. +func (p ContributorLanePolicy) workflowFenceScopedToHumanMergePaths(repo string) bool { + scope := p.WorkflowFenceScope + if p.WorkflowFenceScopeForRepo != nil { + scope = p.WorkflowFenceScopeForRepo(repo) + } + return strings.EqualFold(strings.TrimSpace(scope), config.ContributorLaneWorkflowFenceScopeHumanMergePaths) } // contributorLaneWorkflowFiles returns the changed files that are CI @@ -76,7 +87,7 @@ func contributorLaneTouchesWorkflowFiles(files []intent.ChangedFile) bool { // head's merge for want of `workflows: write`, or when a workflow / action // file matches the repository's human_merge_paths. func (c *Engine) workflowFenceCovers(policy ContributorLanePolicy, owner, repo string, number int, headSHA string, files []intent.ChangedFile) bool { - if !policy.workflowFenceScopedToHumanMergePaths() { + if !policy.workflowFenceScopedToHumanMergePaths(owner + "/" + repo) { return true } patterns := c.currentHumanMergePaths(owner + "/" + repo) @@ -113,7 +124,7 @@ func (c *Engine) contributorLaneMergeFence(policy ContributorLanePolicy, owner, // re-read when the scope, the repository's human_merge_paths or the // head's workflows-permission refusal changes. func (c *Engine) workflowFenceScopeKey(policy ContributorLanePolicy, owner, repo string, number int, headSHA string) string { - if !policy.workflowFenceScopedToHumanMergePaths() { + if !policy.workflowFenceScopedToHumanMergePaths(owner + "/" + repo) { return config.ContributorLaneWorkflowFenceScopeAll } key := config.ContributorLaneWorkflowFenceScopeHumanMergePaths + "\x00" + strings.Join(c.currentHumanMergePaths(owner+"/"+repo), "\x00") diff --git a/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go b/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go index 8df2931f38..42080c0a23 100644 --- a/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go +++ b/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go @@ -342,3 +342,83 @@ func TestPRApproveReplyWorkflowFenceScope(t *testing.T) { }) } } + +// project.repo_policies[].workflow_fence_scope overrides the hive-wide +// scope for one repository, either way, and a repository without an override +// keeps the hive-wide value. The lane resolves it through the same config +// resolver the hive wires in (config.RepoWorkflowFenceScope). On v6 tip the +// policy has no per-repo resolver, so the "override loosens" case stops at +// workflow-path and the "override tightens" case merges. +func TestContributorLaneWorkflowFenceScopeRepoOverride(t *testing.T) { + lintEdit := []map[string]any{{"filename": ".github/workflows/lint.yml", "status": "modified", "additions": 2, "deletions": 1}} + for _, tc := range []struct { + name string + hiveWide string + policies []config.RepoPolicy + paths func(string) []string + wantReason string + wantMerges int + }{ + { + name: "override loosens: hive-wide all, widget human_merge_paths", + hiveWide: config.ContributorLaneWorkflowFenceScopeAll, + policies: []config.RepoPolicy{{Repo: "widget", WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths}}, + paths: humanPathsFor("acme/widget", testReleaseWorkflow), + wantMerges: 1, + }, + { + name: "override tightens: hive-wide human_merge_paths, widget all", + hiveWide: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + policies: []config.RepoPolicy{{Repo: "acme/widget", WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeAll}}, + paths: humanPathsFor("acme/widget", testReleaseWorkflow), + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "another repo's override leaves widget on the hive-wide scope", + hiveWide: config.ContributorLaneWorkflowFenceScopeAll, + policies: []config.RepoPolicy{{Repo: "other", WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths}}, + paths: humanPathsFor("acme/widget", testReleaseWorkflow), + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "unknown override falls back to the hive-wide scope", + hiveWide: config.ContributorLaneWorkflowFenceScopeAll, + policies: []config.RepoPolicy{{Repo: "widget", WorkflowFenceScope: "release_only"}}, + paths: humanPathsFor("acme/widget", testReleaseWorkflow), + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "override to human_merge_paths keeps the full fence without human_merge_paths", + hiveWide: config.ContributorLaneWorkflowFenceScopeAll, + policies: []config.RepoPolicy{{Repo: "widget", WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths}}, + paths: humanPathsFor("acme/other", testReleaseWorkflow), + wantReason: contributorLaneReasonWorkflowPath, + }, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{} + cfg.Project.Org = "acme" + cfg.Project.RepoPolicies = tc.policies + cfg.AutoMerge.ContributorLane.WorkflowFenceScope = tc.hiveWide + fx := validContributorFixture() + fx.files = lintEdit + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.WorkflowFenceScope = cfg.AutoMerge.ContributorLane.EffectiveWorkflowFenceScope() + policy.WorkflowFenceScopeForRepo = func(repo string) string { + scope, _ := cfg.RepoWorkflowFenceScope(repo) + return scope + } + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock), HumanMergePaths: tc.paths}) + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatal(err) + } + if reason != tc.wantReason || fx.merges != tc.wantMerges { + t.Fatalf("reason=%q merges=%d, want %q/%d (comments=%v)", reason, fx.merges, tc.wantReason, tc.wantMerges, fx.allComments) + } + }) + } +} diff --git a/src/pkg/github/sentinel_sweep.go b/src/pkg/github/sentinel_sweep.go index e80cd80b1b..246a04bb2c 100644 --- a/src/pkg/github/sentinel_sweep.go +++ b/src/pkg/github/sentinel_sweep.go @@ -58,6 +58,12 @@ type SentinelSweepOptions struct { LabelColor string LabelDescription string Evaluator sentinel.Config + // SensitivePathsForRepo, when set, returns the sensitive-path globs for + // one "owner/repo" (project.repo_policies[].sentinel_sensitive_paths over + // sentinel.sensitive_paths); its result replaces Evaluator.SensitivePaths + // for that repository's pull requests. nil means every repository uses + // Evaluator.SensitivePaths. + SensitivePathsForRepo func(repo string) []string // TrustedAuthor classifies authors with the same predicate used by the // auto-merge exception lanes: the Hive App, trusted bots and owner-tier // authorized users. nil means no author is trusted. @@ -81,6 +87,17 @@ type SentinelSweepOptions struct { PatchObserver func(SentinelPatchObservation) } +// sentinelEvaluatorForRepo is the evaluator config for one "owner/repo": +// Evaluator with SensitivePaths taken from SensitivePathsForRepo when that is +// set. A non-nil empty result is kept as-is, so it matches nothing. +func (opts SentinelSweepOptions) sentinelEvaluatorForRepo(repo string) sentinel.Config { + cfg := opts.Evaluator + if opts.SensitivePathsForRepo != nil { + cfg.SensitivePaths = opts.SensitivePathsForRepo(repo) + } + return cfg +} + // SentinelPatchObservation is what PatchObserver sees: the pushed head's // patch files exactly as the sentinel fetched them. HiveIdentified is true // only when the hive can name its own accounts and the author is one of them. @@ -674,7 +691,7 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if opts.PatchObserver != nil { c.observeSentinelPatch(ctx, owner, repo, pr, files, opts.PatchObserver) } - findings := sentinel.Evaluate(sentinel.PR{Author: author, Title: pr.GetTitle(), Files: files}, opts.Evaluator) + findings := sentinel.Evaluate(sentinel.PR{Author: author, Title: pr.GetTitle(), Files: files}, opts.sentinelEvaluatorForRepo(owner+"/"+repo)) if len(findings) == 0 { return SentinelSweepEvent{}, false, nil } diff --git a/src/pkg/github/sentinel_sweep_repo_paths_test.go b/src/pkg/github/sentinel_sweep_repo_paths_test.go new file mode 100644 index 0000000000..682f6a32f4 --- /dev/null +++ b/src/pkg/github/sentinel_sweep_repo_paths_test.go @@ -0,0 +1,90 @@ +package github + +import ( + "context" + "testing" + + "github.com/hivecommons/hive/pkg/sentinel" +) + +// SensitivePathsForRepo replaces the hive-wide sensitive-path list for one +// repository's pull requests (project.repo_policies[].sentinel_sensitive_paths), +// tighter or looser, and an explicit empty list matches nothing. On v6 tip the +// option does not exist and the scan always uses Evaluator.SensitivePaths, so +// the "override drops requirements" and "explicit empty" cases are flagged and +// the "override adds requirements" case is not. +func TestSweepSentinelPerRepoSensitivePaths(t *testing.T) { + for _, tc := range []struct { + name string + hiveWide []string + perRepo func(string) []string + flagged bool + }{ + {name: "no override uses the hive-wide defaults", flagged: true}, + { + name: "override drops requirements for this repo", + perRepo: func(string) []string { return []string{"OWNERS"} }, + }, + { + name: "explicit empty override matches nothing", + perRepo: func(string) []string { return []string{} }, + }, + { + name: "override adds requirements the hive-wide list leaves out", + hiveWide: []string{"OWNERS"}, + perRepo: func(string) []string { return []string{"OWNERS", "**/requirements*.txt"} }, + flagged: true, + }, + { + name: "another repo's override leaves this repo on the hive-wide list", + hiveWide: []string{"OWNERS"}, + perRepo: func(repo string) []string { + if repo == "o/other" { + return []string{"**/requirements*.txt"} + } + return []string{"OWNERS"} + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + f := &sentinelFixture{ + prs: []map[string]any{sentinelPR(5, "mallory", "req111")}, + files: map[int][]map[string]any{5: {{ + "filename": "requirements.txt", "status": "modified", "additions": 1, "deletions": 1, + "patch": "@@ -1 +1 @@\n-requests==2.31.0\n+requests==2.32.3\n", + }}}, + } + srv := newSentinelServer(t, f) + defer srv.Close() + c := newTestClient(t, srv, "o", []string{"o/r"}) + opts := defaultSentinelOpts(nil) + opts.Evaluator.SensitivePaths = tc.hiveWide + var asked []string + if tc.perRepo != nil { + opts.SensitivePathsForRepo = func(repo string) []string { + asked = append(asked, repo) + return tc.perRepo(repo) + } + } + res, err := c.SweepSentinel(context.Background(), opts) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if tc.perRepo != nil && (len(asked) != 1 || asked[0] != "o/r") { + t.Fatalf("SensitivePathsForRepo asked for %v, want [o/r]", asked) + } + if !tc.flagged { + if len(res.Flagged) != 0 || len(f.labels[5]) != 0 { + t.Fatalf("want no finding: res=%+v labels=%v comments=%v", res, f.labels, f.comments) + } + return + } + if len(res.Flagged) != 1 { + t.Fatalf("want one flagged PR: res=%+v", res) + } + if rules := res.Flagged[0].Rules(); len(rules) != 1 || rules[0] != sentinel.RuleSensitivePath { + t.Fatalf("rules=%v, want only sensitive_path", rules) + } + }) + } +}