diff --git a/changelog.d/added-pin-only-human-merge-relay.md b/changelog.d/added-pin-only-human-merge-relay.md new file mode 100644 index 0000000000..17ad64d9b1 --- /dev/null +++ b/changelog.d/added-pin-only-human-merge-relay.md @@ -0,0 +1 @@ +- Enforce the configured trusted-author pin-only exception in the GitHub merge-request relay with the same checks as the automerge sweep (complete pin-only diff, verified trusted-author commits, upstream-anchored action pins) plus an exact requested head before and after fetching files, while preserving all other merge gates. diff --git a/changelog.d/added-pin-only-human-merge-sweep.md b/changelog.d/added-pin-only-human-merge-sweep.md index 6f68c92ee2..53de8298b1 100644 --- a/changelog.d/added-pin-only-human-merge-sweep.md +++ b/changelog.d/added-pin-only-human-merge-sweep.md @@ -1 +1 @@ -- Enforce the `auto_merge.human_merge_pin_only` exception in the automerge sweep lanes and `/hive approve` (#16266): a PR by a listed trusted author whose complete diff is pin replacements on guarded paths is no longer held for a person. Any other changed file, including an unguarded changelog or doc, keeps the hold (#16326). Repos without an enabled entry are unchanged, and the `hive-merge` relay does not apply the exception yet (#16265). +- Enforce the `auto_merge.human_merge_pin_only` exception in the automerge sweep lanes and `/hive approve` (#16266): a PR by a listed trusted author whose complete diff is pin replacements on guarded paths is no longer held for a person. Any other changed file, including an unguarded changelog or doc, keeps the hold (#16326). Repos without an enabled entry are unchanged; the `hive-merge` relay enforces the same exception as of #16265. diff --git a/src/cmd/hive/notifywire.go b/src/cmd/hive/notifywire.go index cb6b6698fa..cda8a8d6a2 100644 --- a/src/cmd/hive/notifywire.go +++ b/src/cmd/hive/notifywire.go @@ -35,6 +35,13 @@ func syncAutoMergePolicyToGitHubClient(cfg *config.Config, ghClient *github.Clie ghClient.SetMergeRequestNoCIAllowedRepos(cfg.AutoMerge.NoCIOKSet()) // The merge-request relay refuses PRs touching these paths (#11039). ghClient.SetHumanMergePaths(cfg.AutoMerge.HumanMergePaths) + pinOnly := make(map[string]github.PinOnlySpec) + for repo := range cfg.AutoMerge.HumanMergePinOnly { + if ex, enabled := cfg.AutoMerge.HumanMergePinOnlyFor(repo); enabled { + pinOnly[repo] = github.PinOnlySpec{Enabled: true, Paths: ex.Paths, Kinds: ex.Kinds, TrustedAuthors: ex.TrustedAuthors} + } + } + ghClient.SetHumanMergePinOnly(pinOnly) ghClient.SetAutoMergeMinHeadAge(cfg.AutoMerge.EffectiveMinHeadAge()) return set, ok } diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 9b9fffb750..517541732c 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -170,12 +170,11 @@ sweep lanes whatever the intent tier. If the changed-file list for a configured repo cannot be fetched completely, the merge is withheld (fail closed). See [operator-reference.md](operator-reference.md). -**Pin-only policy (enforced by the automerge sweep and `/approve`; relay pending).** +**Pin-only policy (enforced by the automerge sweep, `/approve`, and relay).** `auto_merge.human_merge_pin_only` provides the schema and conservative diff classifier for #16242 / #16262. **The automerge sweep lanes and `/approve` -enforce it (#16266); the `hive-merge` relay does not yet** (#16265) and still -requires the existing human-merge path policy. The native merge queue is entered +enforce it (#16266), as does the `hive-merge` relay (#16265)**. The native merge queue is entered only after a lane's human-merge-path gate, so queued PRs inherit the exception. A sweep lane does not hold a PR on its human-merge-path matches when the repo has an enabled entry, the PR author is in `trusted_authors` (case-insensitive login match), @@ -236,8 +235,10 @@ This classifier proves **syntax only**, not authenticated identity, exact-head binding, file-list completeness, semantic interpretation or review of upstream references. The sweep supplies the author (GitHub's PR author login), the verified-commit provenance of the head, file-list completeness and the -upstream anchoring of each action SHA itself (#16399); the relay integration -remains #16265; +upstream anchoring of each action SHA itself (#16399). The relay applies +the same checks through `Client.SetHumanMergePinOnly` (#16265) and additionally +requires a nonempty requested head SHA matching the PR head before and after +fetching files; attribution and safe hold release are tracked in #16269. None of the schema or classifier APIs grants permission to merge or clears a hold. Native required checks and producer bindings, freshness, current reviews, substantive @@ -245,9 +246,9 @@ objections, unrelated holds and configured soak must remain independent gates. Operators stage the key in the controller's configured `hive.yaml` seed, not in the image repository (reload behaviour is documented in the operator reference -linked above). On an image that contains #16266, reloading the seed enables -the sweep and `/approve` exception at once; the `hive-merge` relay still -ignores the key until #16265 lands, so relay merges keep holding matching PRs. +linked above). On an image that contains #16266 and #16265, reloading the seed enables +the sweep, `/approve`, and `hive-merge` relay exception at once. Non-GitHub +forge relays retain the existing fail-closed human-merge-path policy. There is **no minimum deployable version enabling this lane yet**. Utah rollout and current-head positive/negative deployment evidence remain tracked by @@ -257,7 +258,7 @@ projectbluefin/utah#1082 and #16242; projectbluefin/utah#1068 is not pre-authori `auto_merge.human_merge_pin_only`; see the [operator reference](operator-reference/README.md#human-merge-pin-only-rollout) for its configuration and deployment prerequisites. The schema/classifier -(#16262), relay admission (#16265), and sweep admission (#16266, landed) are +(#16262), relay admission (#16265, landed), and sweep admission (#16266, landed) are separate changes: this attribution change alone does **not** enable the exception. New path-hold comments retain `` and append `` only when Hive diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 467be2b382..d291c3b8ef 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -254,7 +254,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `config.refuse_gate_regression` | `false` | Safety-gate regression guard ([#16438](https://github.com/hivecommons/hive/issues/16438)). At boot the hive compares the effective config against any previous runtime overlay still on the PVC (`/data/hive.yaml.runtime`, an operator's `hive.yaml.runtime.bak`, `/data/hive.yaml.dashboard`) for `review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos` and `writeback.per_repo` modes. A gate the overlay carried that the effective config lacks or loosens — typically a boot from the ConfigMap seed after the overlay was moved aside — is logged once per gate as `WARN safety gate dropped: (was ) — effective config has `, listed in `/api/status` under `config.gate_regressions`, and shown as a banner at the top of Settings. `true` makes it fatal: the hive exits (code 21) with the gates named instead of running with weaker gates. Set it in the overlay itself; the ConfigMap seed is the file the regression usually comes from. Legacy `/data/hive.yaml.bak` is not consulted — it is frozen at the rename and would warn forever about gates removed on purpose. | | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | -| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | +| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), and by the `hive-merge` relay (#16265), which additionally requires the requested head SHA to match the PR head before and after fetching files. | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | | `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge. Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. Details in the sweep key table below. | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | Title prefixes (after trimming) that mark a PR as a breaking change a person must merge. Every auto-merge lane and the merge train skip the PR; the tracker parks it at 090 *Ready for human merge · human merge*. Set to `[]` to disable. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive) that mark a PR a person must merge; same effect as the title prefixes. Set to `[]` to disable. | @@ -457,7 +457,7 @@ advanced into the merge path. | `auto_merge.repos..required_checks` | inherits default | Per-repo override for heterogeneous hives. `` may be the bare name from `project.repos` or `owner/repo`; an explicit empty list declares that GitHub has no required contexts, while Hive still requires positive CI evidence from at least one real successful check-run before merge. | | `auto_merge.allow_unprotected_base` | deprecated no-op | Accepted for compatibility only. [`hive-merge`](../hive-merge.md) no longer refuses solely because a base branch has no GitHub branch protection; it may merge into any branch the App can write after positive CI evidence. | | `auto_merge.no_ci_ok` | unset (refuse) | **Merge-request watcher key, not a sweep key.** Per-repo opt-in that downgrades only the "unverified" CI verdict (zero statuses, check runs, and workflow runs) to green, for adopted repos with no CI by design. Red and pending verdicts are never downgraded (#6281). See [hive-merge.md](../hive-merge.md). | -| `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge, e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. The sweep lanes skip that hold only for a PR admitted by `auto_merge.human_merge_pin_only` (#16266); the relay does not apply that exception yet. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). | +| `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge, e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. The sweep lanes and GitHub relay skip that hold only for a PR admitted by `auto_merge.human_merge_pin_only` (#16266, #16265); the relay also requires the exact requested head before and after fetching files. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | PR-title prefixes that mean "breaking change — owner merges" (U+26A0 with or without the VS16 selector by default, matched after trimming leading whitespace). One shared predicate, `automerge.RequiresHumanMerge(pr)`, runs where each lane computes eligibility — App self-merge, label-queued, trusted-author and contributor lanes, plus the refetch before a merge — so a matching PR is never merged by hive and never fronts a merge train, however green and however approved. The PR parks at stage 090 *Ready for human merge* with the `human merge` chip and reason *breaking change — owner merges*; the owner merges it with **Approve & merge as maintainer** or on GitHub. Hive posts one writeback-gated comment saying it will wait for a human. Set to `[]` to turn the title rule off. Added after a ⚠️-titled PR was auto-merged by the trusted-author lane while its owner was still deciding whether to ship it. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive, trimmed) that carry the same "a person merges this" meaning as the title prefixes above; either match is enough. Set to `[]` to turn the label rule off. | | `auto_merge.require_current_base` | unset | Repo list (`owner/repo`) with an explicit **on** override for the current-base merge gate (Settings → Repos → "Merge only on current base"). On a gated repo the App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base ([#13634](https://github.com/hivecommons/hive/issues/13634), [#15335](https://github.com/hivecommons/hive/issues/15335)). Costs one compare call per merge candidate. Listing a repo here is also **strict**: a behind head the App cannot update (fork without maintainer edits, branch protection or a missing `contents: write`) is parked (`fork-not-editable` / `update-branch`) rather than merged as tested. Wins over `skip_current_base` and over the default. | @@ -498,8 +498,8 @@ hosted spoke changes survive restarts without editing `hive.yaml`. ### Human-merge pin-only rollout -**Availability:** the automerge sweep lanes and `/approve` enforce the -exception (#16266); the relay does not yet. Minimum +**Availability:** the automerge sweep lanes and `/approve` (#16266) and the +GitHub relay (#16265) enforce the exception. Minimum supported version: the first deployed v5 release containing the schema/classifier (#16262), relay (#16265), sweep (#16266), and hold-release admission integration (#16269). No released version is established here; do not assume an existing @@ -508,7 +508,7 @@ digest/version and live positive/negative evidence in projectbluefin/utah#1082 before enabling that rollout. The additive configuration (schema #16262; enforced by the automerge sweep lanes -and `/approve` per #16266, relay pending #16265) is: +and `/approve` per #16266, and the GitHub relay per #16265) is: ```yaml auto_merge: diff --git a/src/pkg/config/automerge_pin_only.go b/src/pkg/config/automerge_pin_only.go index 8a2088d3f6..11cd07ce39 100644 --- a/src/pkg/config/automerge_pin_only.go +++ b/src/pkg/config/automerge_pin_only.go @@ -13,8 +13,8 @@ import ( // and commit provenance: every commit behind the head must have a trusted // author login, a committer that is GitHub itself (web-flow) or a trusted // login, and a GitHub-verified signature (#16399). It does not prove upstream -// review (separate gates handle that). The hive-merge relay does not yet apply -// it (#16265). +// review (separate gates handle that). The hive-merge relay applies the same +// policy through Client.SetHumanMergePinOnly (#16265). type PinOnlyException struct { Enabled bool `yaml:"enabled" json:"enabled"` Paths []string `yaml:"paths" json:"paths"` diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 6c85fe185d..7711d7a4e1 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -8349,8 +8349,8 @@ type AutoMergeConfig struct { HumanMergePaths map[string][]string `yaml:"human_merge_paths,omitempty" json:"human_merge_paths,omitempty"` // HumanMergePinOnly holds the opt-in pin-only exception, enforced by the - // automerge sweep and /approve gates via humanMergePinOnlyExempt (#16266); - // the hive-merge relay does not apply it yet (#16265). + // automerge sweep and /approve gates (#16266), and the hive-merge relay + // (#16265). HumanMergePinOnly map[string]PinOnlyException `yaml:"human_merge_pin_only,omitempty" json:"human_merge_pin_only,omitempty"` // HumanMergeTitlePrefixes lists title prefixes (matched after trimming // the title) that mark a PR as one the owner merges by hand; no lane and diff --git a/src/pkg/github/automerge/automerge_human_paths.go b/src/pkg/github/automerge/automerge_human_paths.go index 08025015a2..a5cb507228 100644 --- a/src/pkg/github/automerge/automerge_human_paths.go +++ b/src/pkg/github/automerge/automerge_human_paths.go @@ -2,7 +2,6 @@ package automerge import ( "context" - "fmt" "strings" gh "github.com/google/go-github/v72/github" @@ -10,7 +9,6 @@ import ( hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/intent" "github.com/hivecommons/hive/pkg/stageengine/prstage" - "github.com/hivecommons/hive/pkg/stagelabels" ) // Skip reasons reported by the human-merge-path gate (#11038). @@ -122,148 +120,20 @@ func (c *Engine) humanMergePinOnlyExempt(ctx context.Context, owner, repo string return true, "all changes are approved pin replacements by verified trusted-author commits, anchored upstream" } -// pinOnlyMaxTagDepth bounds annotated-tag dereferencing (a tag of a tag). -const pinOnlyMaxTagDepth = 3 - -// pinOnlyActionPinsUpstream returns "" when every accepted action-sha pin is -// a commit of its upstream action repository. GitHub resolves a `uses:` SHA -// through the whole fork network, so a 40-hex commit pushed to any fork of -// owner/repo is a valid pin; the classifier sees syntax only. A pin with a -// version comment must be exactly what tags/ (dereferenced through -// annotated tags) points at; one without must be an ancestor of the upstream -// default branch. Any API error, 404 or mismatch fails closed with a reason. -// Image digests are content-addressed and need no such anchor. +// pinOnlyActionPinsUpstream, pinOnlyCommitsTrusted and pinOnlyTrustedLogin +// delegate to the pkg/github helpers the merge-request relay also uses +// (#16265), so the sweep, /approve and the relay apply one provenance policy +// (#16399). func (c *Engine) pinOnlyActionPinsUpstream(ctx context.Context, pins []intent.ActionPin) string { - if len(pins) == 0 { - return "" - } - ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") - for _, pin := range pins { - if why := c.pinOnlyActionPinUpstream(ctx, pin); why != "" { - return fmt.Sprintf("action %s@%s: %s", pin.Repo, stagelabels.ShortSHA(pin.SHA), why) - } - } - return "" -} - -func (c *Engine) pinOnlyActionPinUpstream(ctx context.Context, pin intent.ActionPin) string { - owner, repo, ok := strings.Cut(pin.Repo, "/") - if !ok || owner == "" || repo == "" || pin.SHA == "" { - return "upstream repository or commit unknown" - } - if pin.Version != "" { - ref, _, err := c.gh.Git.GetRef(ctx, owner, repo, "tags/"+pin.Version) - if err != nil { - return fmt.Sprintf("tag %s could not be resolved upstream: %v", pin.Version, err) - } - obj := ref.GetObject() - for depth := 0; obj.GetType() == "tag"; depth++ { - if depth == pinOnlyMaxTagDepth { - return fmt.Sprintf("tag %s nests too deeply", pin.Version) - } - tag, _, err := c.gh.Git.GetTag(ctx, owner, repo, obj.GetSHA()) - if err != nil { - return fmt.Sprintf("annotated tag %s could not be resolved upstream: %v", pin.Version, err) - } - obj = tag.GetObject() - } - if obj.GetType() != "commit" || !strings.EqualFold(obj.GetSHA(), pin.SHA) { - return fmt.Sprintf("upstream tag %s does not point at the pinned commit", pin.Version) - } - return "" - } - upstream, _, err := c.gh.Repositories.Get(ctx, owner, repo) - if err != nil { - return fmt.Sprintf("upstream repository could not be read: %v", err) - } - branch := upstream.GetDefaultBranch() - if branch == "" { - return "upstream default branch unknown" - } - // base=pin, head=default: "ahead" or "identical" means the pinned commit - // is an ancestor of (reachable from) the upstream default branch. - cmp, _, err := c.gh.Repositories.CompareCommits(ctx, owner, repo, pin.SHA, branch, &gh.ListOptions{PerPage: 1}) - if err != nil { - return fmt.Sprintf("pinned commit could not be compared with upstream %s: %v", branch, err) - } - if status := cmp.GetStatus(); status != "ahead" && status != "identical" { - return fmt.Sprintf("pinned commit is not on upstream %s (compare status %q)", branch, status) - } - return "" + return hgithub.PinOnlyActionPinsUpstream(ctx, c.gh, pins) } -func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { - login = strings.TrimSpace(login) - if login == "" { - return false - } - for _, trusted := range policy.TrustedAuthors { - if strings.EqualFold(strings.TrimSpace(trusted), login) { - return true - } - } - return false -} - -// pinOnlyCommitsTrusted returns "" when every commit of pr is attributed to a -// trusted author, was committed by a trusted login or by GitHub itself -// (web-flow), carries a signature GitHub verified, and the current head is -// the newest listed commit. GitHub verifies a signature against the -// committer's email only, so a verified commit proves the committer, not the -// author: a write-access principal with their own signing key can craft a -// commit whose author is a bot's noreply address and sign it as themselves -// (see pr_merge_state.go on verification reasons). Requiring the committer to -// be web-flow (GitHub-created and GitHub-signed, so GitHub set the author) or -// a trusted login (a human trusted author signing locally) closes that; a -// spoofed committer email fails verification because it is not on the -// signer's account. Any listing error, an empty or truncated list, or a head -// not in the list fails closed with a reason. func (c *Engine) pinOnlyCommitsTrusted(ctx context.Context, owner, repo string, pr *gh.PullRequest, policy config.PinOnlyException) string { - head := pr.GetHead().GetSHA() - if head == "" { - return "PR head SHA unknown" - } - ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") - all, complete, err := hgithub.ListPRRepositoryCommits(ctx, c.gh, owner, repo, pr.GetNumber()) - if err != nil { - return fmt.Sprintf("PR commits could not be listed: %v", err) - } - if !complete { - return "PR commit list too long to verify" - } - if len(all) == 0 { - return "PR has no commits to verify" - } - if all[len(all)-1].GetSHA() != head { - return "PR commit list does not end at the current head" - } - for _, rc := range all { - sha := rc.GetSHA() - if sha == "" { - return "PR commit without a SHA" - } - if login := hgithub.SafeGetLogin(rc.GetAuthor()); !pinOnlyTrustedLogin(policy, login) { - return fmt.Sprintf("commit %s author %q is not in trusted_authors", stagelabels.ShortSHA(sha), login) - } - if committer := hgithub.SafeGetLogin(rc.GetCommitter()); !pinOnlyTrustedCommitter(policy, committer) { - return fmt.Sprintf("commit %s committer %q is neither GitHub nor in trusted_authors", stagelabels.ShortSHA(sha), committer) - } - if !rc.GetCommit().GetVerification().GetVerified() { - return fmt.Sprintf("commit %s has no GitHub-verified signature", stagelabels.ShortSHA(sha)) - } - } - return "" + return hgithub.PinOnlyCommitsTrusted(ctx, c.gh, owner, repo, pr, policy.TrustedAuthors) } -// pinOnlyWebFlowLogin is the login GitHub attaches as committer to commits it -// creates and signs itself (web UI, Apps such as Dependabot and Renovate). -const pinOnlyWebFlowLogin = "web-flow" - -// pinOnlyTrustedCommitter accepts GitHub's own committer identity or a -// trusted author committing (and signing) locally; the signature check then -// binds to this identity. -func pinOnlyTrustedCommitter(policy config.PinOnlyException, login string) bool { - return strings.EqualFold(strings.TrimSpace(login), pinOnlyWebFlowLogin) || pinOnlyTrustedLogin(policy, login) +func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { + return hgithub.PinOnlyTrustedLogin(policy.TrustedAuthors, login) } // humanMergePathGate refuses a PR that touches a path a person must merge. diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 92823f7cbf..ef1b3cd937 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -151,8 +151,9 @@ type Client struct { mergePolicyMu sync.RWMutex allowUnprotectedBaseRepos map[string]bool noCIAllowedRepos map[string]bool - humanMergePaths map[string][]string // auto_merge.human_merge_paths; see SetHumanMergePaths - sentinelHeads sentinelHeadsSeen // head SHAs the sentinel sweep already evaluated + humanMergePaths map[string][]string // auto_merge.human_merge_paths; see SetHumanMergePaths + humanMergePinOnly map[string]PinOnlySpec // guarded by mergePolicyMu + sentinelHeads sentinelHeadsSeen // head SHAs the sentinel sweep already evaluated autoMergeMinHeadAge time.Duration mergeAlertMu sync.Mutex mergeAlertSink MergeFailureAlertSink diff --git a/src/pkg/github/human_merge_paths.go b/src/pkg/github/human_merge_paths.go index 2531bcf8e5..5082e66f73 100644 --- a/src/pkg/github/human_merge_paths.go +++ b/src/pkg/github/human_merge_paths.go @@ -13,7 +13,8 @@ import ( // Human-merge paths (#11027): auto_merge.human_merge_paths lists, per repo, // paths a person must merge. Every App merge path (the automerge sweep lanes // and the merge-request relay) refuses a PR that touches one, adds `hold`, -// and leaves one marker-stamped comment naming the path(s). +// and leaves one marker-stamped comment naming the path(s), unless the +// configured pin-only exception is proven. const ( // HumanMergePathsConfigKey is the config key named in every refusal. HumanMergePathsConfigKey = "auto_merge.human_merge_paths" @@ -192,9 +193,58 @@ func (c *Client) humanMergePathsFor(repo string) []string { return c.humanMergePaths[repoPolicyKey(c.org, repo)] } +// PinOnlySpec is the relay's config-independent pin-only exception policy. +// It only lifts the human-merge-path gate, never any other merge requirement. +type PinOnlySpec struct { + Enabled bool + Paths []string + Kinds []string + TrustedAuthors []string +} + +func (p PinOnlySpec) clone() PinOnlySpec { + p.Paths = append([]string(nil), p.Paths...) + p.Kinds = append([]string(nil), p.Kinds...) + p.TrustedAuthors = append([]string(nil), p.TrustedAuthors...) + return p +} + +// SetHumanMergePinOnly replaces the relay policy on config reload; nil clears it. +// Duplicate normalized repository keys fail closed. +func (c *Client) SetHumanMergePinOnly(policies map[string]PinOnlySpec) { + if c == nil { + return + } + normalized := make(map[string]PinOnlySpec, len(policies)) + for repo, policy := range policies { + key := repoPolicyKey(c.org, repo) + if key == "" { + continue + } + if _, duplicate := normalized[key]; duplicate { + normalized[key] = PinOnlySpec{} + continue + } + normalized[key] = policy.clone() + } + c.mergePolicyMu.Lock() + defer c.mergePolicyMu.Unlock() + c.humanMergePinOnly = normalized +} + +func (c *Client) humanMergePinOnlyFor(repo string) PinOnlySpec { + if c == nil { + return PinOnlySpec{} + } + c.mergePolicyMu.RLock() + defer c.mergePolicyMu.RUnlock() + return c.humanMergePinOnly[repoPolicyKey(c.org, repo)].clone() +} + // mergeRequestHumanMergePathRefusal checks a merge request against the // repo's human-merge paths. It returns a non-empty refusal (terminal) when -// the PR touches one — after adding `hold` and the single marker comment — +// the PR touches one without a proven pin-only exception — after adding +// `hold` and the single marker comment — // and an error when the repo has paths configured but the complete // changed-file list cannot be established (fail closed). An unconfigured // repo costs no API call. @@ -216,8 +266,52 @@ func (c *Client) mergeRequestHumanMergePathRefusal(ctx context.Context, req Merg if len(matches) == 0 { return "", nil } + if ex := c.humanMergePinOnlyFor(req.Repo); ex.Enabled { + reason := "PR author is not trusted" + if PinOnlyTrustedLogin(ex.TrustedAuthors, SafeGetLogin(pr.GetUser())) { + switch { + case req.ExpectSHA == "" || pr.GetHead().GetSHA() != req.ExpectSHA: + reason = "PR head does not match requested head" + case pr.ChangedFiles == nil || pr.GetChangedFiles() != len(files): + reason = "complete changed-file count is unavailable" + default: + reason = c.pinOnlyProvenance(ctx, owner, name, req, pr, files, matches, ex) + if reason == "" { + return "", nil + } + } + } + c.warn("merge-request watcher: pin-only exception rejected", "repo", req.Repo, "pr", req.Number, "reason", reason) + } if err := HoldForHumanMergePaths(ctx, c.client, owner, name, req.Number, matches, pr.GetHead().GetSHA()); err != nil { c.warn("merge-request watcher: human-merge-path hold failed", "repo", req.Repo, "pr", req.Number, "error", err) } return HumanMergePathReason(matches), nil } + +// pinOnlyProvenance applies the relay's share of the pin-only exception once +// the author, requested head and file count have qualified: the whole diff +// must classify as pin replacements, every commit must be a verified +// trusted-author commit, every new action SHA must be anchored upstream +// (#16399, the same checks the sweep applies), and the head must still be the +// requested SHA after the file listing. It returns "" when the PR qualifies +// and the refusal reason otherwise. +func (c *Client) pinOnlyProvenance(ctx context.Context, owner, name string, req MergeRequest, pr *gh.PullRequest, files []intent.ChangedFile, matches []string, ex PinOnlySpec) string { + ok, reason, pins := intent.ClassifyPinOnlyActions(files, matches, intent.PinOnlySpec{Paths: ex.Paths, Kinds: ex.Kinds}) + if !ok { + return reason + } + if why := PinOnlyCommitsTrusted(ctx, c.client, owner, name, pr, ex.TrustedAuthors); why != "" { + return why + } + if why := PinOnlyActionPinsUpstream(ctx, c.client, pins); why != "" { + return why + } + // The files endpoint is not SHA-addressable. Ensure the head did not + // move while paging; the eventual merge also uses req.ExpectSHA. + current, _, err := c.client.PullRequests.Get(ctx, owner, name, req.Number) + if err != nil || current.GetHead().GetSHA() != req.ExpectSHA { + return "PR head could not be confirmed after listing files" + } + return "" +} diff --git a/src/pkg/github/human_merge_paths_test.go b/src/pkg/github/human_merge_paths_test.go index cf45762c5e..28c614e65e 100644 --- a/src/pkg/github/human_merge_paths_test.go +++ b/src/pkg/github/human_merge_paths_test.go @@ -19,6 +19,16 @@ import ( type humanPathMergeFixture struct { mu sync.Mutex files []string + fileDetails []map[string]any + prPayload map[string]any + movedHead string + // commits is served for GET pulls/42/commits; nil serves one verified + // web-flow commit by alice at the head "abc" (what the pin-only exception + // needs). upstream maps "/repos//" to a payload (or + // an int status) for the action-pin anchoring reads. + commits []map[string]any + upstream map[string]any + ci *ciFixture prStatus int filesStatus int filesHits int @@ -29,7 +39,10 @@ type humanPathMergeFixture struct { func newHumanPathMergeServer(t *testing.T, f *humanPathMergeFixture) *httptest.Server { t.Helper() - green := greenFixture() + green := f.ci + if green == nil { + green = greenFixture() + } return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() @@ -38,13 +51,26 @@ func newHumanPathMergeServer(t *testing.T, f *humanPathMergeFixture) *httptest.S case r.Method == http.MethodGet && p == "/repos/o/r/pulls/42" && f.prStatus != 0: w.WriteHeader(f.prStatus) return + case r.Method == http.MethodGet && p == "/repos/o/r/pulls/42" && f.prPayload != nil: + if f.movedHead != "" && f.filesHits > 0 { + f.prPayload["head"] = map[string]any{"sha": f.movedHead} + } + _ = json.NewEncoder(w).Encode(f.prPayload) + return + case r.Method == http.MethodGet && p == "/repos/o/r/pulls/42/commits": + commits := f.commits + if commits == nil { + commits = []map[string]any{pinOnlyTestCommit("abc", "alice", "web-flow", true)} + } + _ = json.NewEncoder(w).Encode(commits) + return case r.Method == http.MethodGet && p == "/repos/o/r/pulls/42/files": f.filesHits++ if f.filesStatus != 0 { w.WriteHeader(f.filesStatus) return } - var out []map[string]any + out := f.fileDetails for _, name := range f.files { out = append(out, map[string]any{"filename": name, "status": "modified"}) } @@ -75,6 +101,19 @@ func newHumanPathMergeServer(t *testing.T, f *humanPathMergeFixture) *httptest.S if green.serveCI(w, r) { return } + if r.Method == http.MethodGet && f.upstream != nil { + for suffix, payload := range f.upstream { + if p != "/repos/upstream/action"+suffix { + continue + } + if status, ok := payload.(int); ok { + w.WriteHeader(status) + return + } + _ = json.NewEncoder(w).Encode(payload) + return + } + } if r.Method == http.MethodPut && strings.HasSuffix(p, "/merge") { f.merges++ w.Header().Set("Content-Type", "application/json") @@ -85,12 +124,15 @@ func newHumanPathMergeServer(t *testing.T, f *humanPathMergeFixture) *httptest.S })) } -func runHumanPathMergeRequest(t *testing.T, f *humanPathMergeFixture, paths map[string][]string) (string, MergeResponse) { +func runHumanPathMergeRequest(t *testing.T, f *humanPathMergeFixture, paths map[string][]string, pinOnly ...map[string]PinOnlySpec) (string, MergeResponse) { t.Helper() srv := newHumanPathMergeServer(t, f) t.Cleanup(srv.Close) c := testMergeClient(t, srv.URL) c.SetHumanMergePaths(paths) + if len(pinOnly) > 0 { + c.SetHumanMergePinOnly(pinOnly[0]) + } dir := t.TempDir() mergeRequestDirForTest = dir @@ -227,3 +269,185 @@ func TestHumanMergePathHelpersGuardNilInputs(t *testing.T) { t.Fatalf("reason = %q", reason) } } + +// pinOnlyTestCommit builds a pulls/N/commits entry with the author login, +// committer login and GitHub signature verification the exception inspects. +func pinOnlyTestCommit(sha, author, committer string, verified bool) map[string]any { + return map[string]any{ + "sha": sha, + "author": map[string]any{"login": author}, + "committer": map[string]any{"login": committer}, + "commit": map[string]any{"verification": map[string]any{"verified": verified}}, + } +} + +const ( + pinOnlyTestOldSHA = "1111111111111111111111111111111111111111" + pinOnlyTestNewSHA = "2222222222222222222222222222222222222222" +) + +// pinOnlyActionPatch is a single-line uses: SHA bump of upstream/action with a +// # v5 version comment. +func pinOnlyActionPatch(version string) string { + suffix := "" + if version != "" { + suffix = " # " + version + } + return "@@ -1 +1 @@\n- - uses: upstream/action@" + pinOnlyTestOldSHA + suffix + "\n+ - uses: upstream/action@" + pinOnlyTestNewSHA + suffix +} + +func pinOnlyRelayFixture() *humanPathMergeFixture { + return &humanPathMergeFixture{ + prPayload: map[string]any{"number": 42, "state": "open", "user": map[string]any{"login": "alice", "type": "User"}, "head": map[string]any{"sha": "abc", "repo": map[string]any{"full_name": "o/r"}}, "base": map[string]any{"ref": "main", "repo": map[string]any{"full_name": "o/r"}}, "changed_files": 1}, + fileDetails: []map[string]any{{"filename": "Containerfile", "status": "modified", "additions": 1, "deletions": 1, "patch": "@@ -1 +1 @@\n-FROM image@sha256:" + strings.Repeat("a", 64) + "\n+FROM image@sha256:" + strings.Repeat("b", 64)}}, + } +} + +func TestMergeRequestPinOnlyException(t *testing.T) { + for _, tc := range []struct { + name string + change func(*humanPathMergeFixture, *PinOnlySpec) + wantPass bool + wantUnknown bool + }{ + {name: "trusted pin", wantPass: true}, + {name: "disabled", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { ex.Enabled = false }}, + {name: "untrusted", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { ex.TrustedAuthors = []string{"bob"} }}, + {name: "empty trust list", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { ex.TrustedAuthors = nil }}, + {name: "mixed diff", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.fileDetails[0]["patch"] = strings.Replace(f.fileDetails[0]["patch"].(string), "@@ -1 +1 @@", "@@ -1 +1,2 @@", 1) + "\n+RUN echo unsafe" + f.fileDetails[0]["additions"] = 2 + }}, + {name: "unguarded extra file", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.prPayload["changed_files"] = 2 + f.files = []string{"README.md"} + }}, + {name: "outside exception paths", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { ex.Paths = []string{".github/workflows/*.yml"} }}, + {name: "missing patch", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { delete(f.fileDetails[0], "patch") }}, + {name: "missing count", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { delete(f.prPayload, "changed_files") }}, + {name: "incomplete list", wantUnknown: true, change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { f.prPayload["changed_files"] = 2 }}, + {name: "wrong head", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { f.prPayload["head"] = map[string]any{"sha": "other"} }}, + {name: "head moves during file fetch", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { f.movedHead = "other" }}, + {name: "commit by untrusted author", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("abc", "mallory", "web-flow", true)} + }}, + {name: "commit by untrusted committer", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("abc", "alice", "mallory", true)} + }}, + {name: "unverified commit", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("abc", "alice", "web-flow", false)} + }}, + {name: "later untrusted commit", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("aaa", "alice", "web-flow", true), pinOnlyTestCommit("abc", "mallory", "mallory", true)} + }}, + {name: "commit list not at head", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("stale", "alice", "web-flow", true)} + }}, + {name: "empty commit list", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{} + }}, + {name: "trusted author signing locally", wantPass: true, change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + f.commits = []map[string]any{pinOnlyTestCommit("abc", "alice", "alice", true)} + }}, + {name: "action pin anchored by upstream tag", wantPass: true, change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + pinOnlyActionCase(f, ex, "v5", map[string]any{"/git/ref/tags/v5": map[string]any{"object": map[string]any{"type": "commit", "sha": pinOnlyTestNewSHA}}}) + }}, + {name: "action pin tag points elsewhere", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + pinOnlyActionCase(f, ex, "v5", map[string]any{"/git/ref/tags/v5": map[string]any{"object": map[string]any{"type": "commit", "sha": pinOnlyTestOldSHA}}}) + }}, + {name: "action pin tag missing upstream", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + pinOnlyActionCase(f, ex, "v5", map[string]any{"/git/ref/tags/v5": http.StatusNotFound}) + }}, + {name: "action pin on upstream default branch", wantPass: true, change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + pinOnlyActionCase(f, ex, "", map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + pinOnlyTestNewSHA + "...main": map[string]any{"status": "ahead"}}) + }}, + {name: "action pin off upstream default branch", change: func(f *humanPathMergeFixture, ex *PinOnlySpec) { + pinOnlyActionCase(f, ex, "", map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + pinOnlyTestNewSHA + "...main": map[string]any{"status": "diverged"}}) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f := pinOnlyRelayFixture() + ex := PinOnlySpec{Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"ALICE"}} + if tc.change != nil { + tc.change(f, &ex) + } + _, resp := runHumanPathMergeRequest(t, f, map[string][]string{"o/r": {"Containerfile", ".github/workflows/*.yml"}}, map[string]PinOnlySpec{"O/R": ex}) + if tc.wantPass { + if !resp.OK || f.merges != 1 || len(f.labels) != 0 || len(f.comments) != 0 { + t.Fatalf("result=%+v merges=%d labels=%v comments=%v; want merge without hold", resp, f.merges, f.labels, f.comments) + } + } else { + if resp.OK || f.merges != 0 { + t.Fatalf("result=%+v merges=%d; want refusal", resp, f.merges) + } + if tc.wantUnknown { + if !strings.Contains(resp.Error, "fail closed") || len(f.labels) != 0 || len(f.comments) != 0 { + t.Fatalf("unknown list must fail closed without a hold: %+v", resp) + } + } else if len(f.labels) != 1 || len(f.comments) != 1 || !strings.Contains(f.comments[0], HumanMergePathMarker) { + t.Fatalf("labels=%v comments=%v; want hold and marker", f.labels, f.comments) + } + } + }) + } +} + +// pinOnlyActionCase turns the fixture into a workflow action-sha bump of +// upstream/action and serves upstream for the anchoring reads. +func pinOnlyActionCase(f *humanPathMergeFixture, ex *PinOnlySpec, version string, upstream map[string]any) { + f.fileDetails = []map[string]any{{"filename": ".github/workflows/ci.yml", "status": "modified", "additions": 1, "deletions": 1, "patch": pinOnlyActionPatch(version)}} + f.upstream = upstream + ex.Paths = []string{".github/workflows/*.yml"} + ex.Kinds = []string{"action-sha"} +} + +func TestMergeRequestPinOnlyStillRequiresGreenCI(t *testing.T) { + f := pinOnlyRelayFixture() + f.ci = greenFixture() + f.ci.checks[0].conclusion = "failure" + _, resp := runHumanPathMergeRequest(t, f, map[string][]string{"o/r": {"Containerfile"}}, map[string]PinOnlySpec{"r": {Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"alice"}}}) + if resp.OK || f.merges != 0 || len(f.labels) != 0 || len(f.comments) != 0 { + t.Fatalf("result=%+v merges=%d labels=%v comments=%v; pin exception must still fail CI", resp, f.merges, f.labels, f.comments) + } +} + +func TestSetHumanMergePinOnlyReload(t *testing.T) { + c := NewClientForTest("http://127.0.0.1:0", "o", []string{"r"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + ex := PinOnlySpec{Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"alice"}} + c.SetHumanMergePinOnly(map[string]PinOnlySpec{" O/R ": ex}) + ex.Paths[0] = "unsafe" + got := c.humanMergePinOnlyFor("r") + if !got.Enabled || got.Paths[0] != "Containerfile" { + t.Fatalf("policy not normalized or copied: %+v", got) + } + got.Paths[0] = "unsafe" + if c.humanMergePinOnlyFor("r").Paths[0] != "Containerfile" { + t.Fatal("lookup must return a copy") + } + c.SetHumanMergePinOnly(map[string]PinOnlySpec{"r": ex, "O/R": ex}) + if c.humanMergePinOnlyFor("r").Enabled { + t.Fatal("duplicate normalized keys must fail closed") + } + c.SetHumanMergePinOnly(nil) + if c.humanMergePinOnlyFor("r").Enabled { + t.Fatal("nil must clear policy") + } + var absent *Client + absent.SetHumanMergePinOnly(nil) + if absent.humanMergePinOnlyFor("r").Enabled { + t.Fatal("nil client must have no policy") + } +} + +func TestMergeRequestPinOnlyRequiresExpectedHead(t *testing.T) { + f := pinOnlyRelayFixture() + srv := newHumanPathMergeServer(t, f) + defer srv.Close() + c := testMergeClient(t, srv.URL) + c.SetHumanMergePaths(map[string][]string{"o/r": {"Containerfile"}}) + c.SetHumanMergePinOnly(map[string]PinOnlySpec{"o/r": {Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"alice"}}}) + refusal, err := c.mergeRequestHumanMergePathRefusal(context.Background(), MergeRequest{Repo: "o/r", Number: 42}) + if err != nil || refusal == "" || len(f.labels) != 1 || len(f.comments) != 1 { + t.Fatalf("refusal=%q err=%v labels=%v comments=%v; missing requested head must hold", refusal, err, f.labels, f.comments) + } +} diff --git a/src/pkg/github/merge_request_watcher.go b/src/pkg/github/merge_request_watcher.go index cd8aa3796e..9dd0a114c8 100644 --- a/src/pkg/github/merge_request_watcher.go +++ b/src/pkg/github/merge_request_watcher.go @@ -423,8 +423,8 @@ func (c *Client) handleOneMergeRequest(ctx context.Context, path string, nowFn f return } // Human-merge paths (#11039): a PR touching a path listed in - // auto_merge.human_merge_paths for its repo is never merged by the App, - // whatever agent asks. A match is terminal (the request is refused, the + // auto_merge.human_merge_paths for its repo requires a person unless the + // configured pin-only exception is proven, whatever agent asks. A match is terminal (the request is refused, the // PR gets `hold` and one marker comment); an unknown changed-file list on // a configured repo fails closed through the bounded retry path. Checked // before the optional branch-update so a refused PR receives no push. diff --git a/src/pkg/github/pin_only_provenance.go b/src/pkg/github/pin_only_provenance.go new file mode 100644 index 0000000000..aa37bd7f32 --- /dev/null +++ b/src/pkg/github/pin_only_provenance.go @@ -0,0 +1,167 @@ +package github + +import ( + "context" + "fmt" + "strings" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/intent" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// Pin-only exception provenance (#16399): once the classifier accepts a diff +// as pin replacements, every App merge path (the automerge sweep lanes, +// /approve and the merge-request relay) must also prove that every commit +// behind the head is the trusted author's and that every new action SHA is +// anchored in its upstream repository. The helpers live here so the sweep and +// the relay share one implementation and can never disagree. + +// pinOnlyMaxTagDepth bounds annotated-tag dereferencing (a tag of a tag). +const pinOnlyMaxTagDepth = 3 + +// PinOnlyWebFlowLogin is the login GitHub attaches as committer to commits it +// creates and signs itself (web UI, Apps such as Dependabot and Renovate). +const PinOnlyWebFlowLogin = "web-flow" + +// pinOnlyRESTCaller labels the REST reads the provenance checks make. +const pinOnlyRESTCaller = "hive:automerge_pin_only" + +// PinOnlyTrustedLogin reports whether login is one of trusted (case-insensitive, +// whitespace-trimmed). An empty login is never trusted. +func PinOnlyTrustedLogin(trusted []string, login string) bool { + login = strings.TrimSpace(login) + if login == "" { + return false + } + for _, t := range trusted { + if strings.EqualFold(strings.TrimSpace(t), login) { + return true + } + } + return false +} + +// PinOnlyTrustedCommitter accepts GitHub's own committer identity or a +// trusted author committing (and signing) locally; the signature check then +// binds to this identity. +func PinOnlyTrustedCommitter(trusted []string, login string) bool { + return strings.EqualFold(strings.TrimSpace(login), PinOnlyWebFlowLogin) || PinOnlyTrustedLogin(trusted, login) +} + +// PinOnlyCommitsTrusted returns "" when every commit of pr is attributed to a +// trusted author, was committed by a trusted login or by GitHub itself +// (web-flow), carries a signature GitHub verified, and the current head is +// the newest listed commit. GitHub verifies a signature against the +// committer's email only, so a verified commit proves the committer, not the +// author: a write-access principal with their own signing key can craft a +// commit whose author is a bot's noreply address and sign it as themselves +// (see pr_merge_state.go on verification reasons). Requiring the committer to +// be web-flow (GitHub-created and GitHub-signed, so GitHub set the author) or +// a trusted login (a human trusted author signing locally) closes that; a +// spoofed committer email fails verification because it is not on the +// signer's account. Any listing error, an empty or truncated list, or a head +// not in the list fails closed with a reason. +func PinOnlyCommitsTrusted(ctx context.Context, client *gh.Client, owner, repo string, pr *gh.PullRequest, trusted []string) string { + head := pr.GetHead().GetSHA() + if head == "" { + return "PR head SHA unknown" + } + ctx = WithRESTCaller(ctx, pinOnlyRESTCaller) + all, complete, err := ListPRRepositoryCommits(ctx, client, owner, repo, pr.GetNumber()) + if err != nil { + return fmt.Sprintf("PR commits could not be listed: %v", err) + } + if !complete { + return "PR commit list too long to verify" + } + if len(all) == 0 { + return "PR has no commits to verify" + } + if all[len(all)-1].GetSHA() != head { + return "PR commit list does not end at the current head" + } + for _, rc := range all { + sha := rc.GetSHA() + if sha == "" { + return "PR commit without a SHA" + } + if login := SafeGetLogin(rc.GetAuthor()); !PinOnlyTrustedLogin(trusted, login) { + return fmt.Sprintf("commit %s author %q is not in trusted_authors", stagelabels.ShortSHA(sha), login) + } + if committer := SafeGetLogin(rc.GetCommitter()); !PinOnlyTrustedCommitter(trusted, committer) { + return fmt.Sprintf("commit %s committer %q is neither GitHub nor in trusted_authors", stagelabels.ShortSHA(sha), committer) + } + if !rc.GetCommit().GetVerification().GetVerified() { + return fmt.Sprintf("commit %s has no GitHub-verified signature", stagelabels.ShortSHA(sha)) + } + } + return "" +} + +// PinOnlyActionPinsUpstream returns "" when every accepted action-sha pin is +// a commit of its upstream action repository. GitHub resolves a `uses:` SHA +// through the whole fork network, so a 40-hex commit pushed to any fork of +// owner/repo is a valid pin; the classifier sees syntax only. A pin with a +// version comment must be exactly what tags/ (dereferenced through +// annotated tags) points at; one without must be an ancestor of the upstream +// default branch. Any API error, 404 or mismatch fails closed with a reason. +// Image digests are content-addressed and need no such anchor. +func PinOnlyActionPinsUpstream(ctx context.Context, client *gh.Client, pins []intent.ActionPin) string { + if len(pins) == 0 { + return "" + } + ctx = WithRESTCaller(ctx, pinOnlyRESTCaller) + for _, pin := range pins { + if why := pinOnlyActionPinUpstream(ctx, client, pin); why != "" { + return fmt.Sprintf("action %s@%s: %s", pin.Repo, stagelabels.ShortSHA(pin.SHA), why) + } + } + return "" +} + +func pinOnlyActionPinUpstream(ctx context.Context, client *gh.Client, pin intent.ActionPin) string { + owner, repo, ok := strings.Cut(pin.Repo, "/") + if !ok || owner == "" || repo == "" || pin.SHA == "" { + return "upstream repository or commit unknown" + } + if pin.Version != "" { + ref, _, err := client.Git.GetRef(ctx, owner, repo, "tags/"+pin.Version) + if err != nil { + return fmt.Sprintf("tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj := ref.GetObject() + for depth := 0; obj.GetType() == "tag"; depth++ { + if depth == pinOnlyMaxTagDepth { + return fmt.Sprintf("tag %s nests too deeply", pin.Version) + } + tag, _, err := client.Git.GetTag(ctx, owner, repo, obj.GetSHA()) + if err != nil { + return fmt.Sprintf("annotated tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj = tag.GetObject() + } + if obj.GetType() != "commit" || !strings.EqualFold(obj.GetSHA(), pin.SHA) { + return fmt.Sprintf("upstream tag %s does not point at the pinned commit", pin.Version) + } + return "" + } + upstream, _, err := client.Repositories.Get(ctx, owner, repo) + if err != nil { + return fmt.Sprintf("upstream repository could not be read: %v", err) + } + branch := upstream.GetDefaultBranch() + if branch == "" { + return "upstream default branch unknown" + } + // base=pin, head=default: "ahead" or "identical" means the pinned commit + // is an ancestor of (reachable from) the upstream default branch. + cmp, _, err := client.Repositories.CompareCommits(ctx, owner, repo, pin.SHA, branch, &gh.ListOptions{PerPage: 1}) + if err != nil { + return fmt.Sprintf("pinned commit could not be compared with upstream %s: %v", branch, err) + } + if status := cmp.GetStatus(); status != "ahead" && status != "identical" { + return fmt.Sprintf("pinned commit is not on upstream %s (compare status %q)", branch, status) + } + return "" +}