From 18f77a0f53d930535cee9bb9176377e8002e187e Mon Sep 17 00:00:00 2001 From: mendezr Date: Mon, 2 Nov 2026 19:50:41 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feat(config):=20stage=20bounded?= =?UTF-8?q?=20human-merge=20pin-only=20policy=20and=20classifier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement the shared foundation from #16262 for #16242 without loosening any merge admission gate. Carry complete patch evidence, reject unsupported or mixed diffs, and make the remaining trust, review and exact-head obligations explicit. Hive-Run: hivecommons/hive#16242 Hive-Plan: ordered-children/16262-config-and-classifier Hive-Spec: issue-16242#required-behavior Co-authored-by: hanthor <5840441+hanthor@users.noreply.github.com> Signed-off-by: mendezr --- .../added-pin-only-human-merge-config.md | 1 + src/docs/hive-merge.md | 50 +++++ src/docs/operator-reference/README.md | 1 + src/pkg/config/automerge_pin_only.go | 90 ++++++++ src/pkg/config/automerge_pin_only_test.go | 88 ++++++++ src/pkg/config/config.go | 4 + src/pkg/config/validate.go | 3 + .../github/automerge/automerge_intent_test.go | 4 +- src/pkg/github/human_merge_paths.go | 1 + src/pkg/github/pin_only_files_test.go | 50 +++++ src/pkg/intent/intent.go | 2 + src/pkg/intent/pin_only.go | 203 ++++++++++++++++++ src/pkg/intent/pin_only_test.go | 115 ++++++++++ 13 files changed, 610 insertions(+), 2 deletions(-) create mode 100644 changelog.d/added-pin-only-human-merge-config.md create mode 100644 src/pkg/config/automerge_pin_only.go create mode 100644 src/pkg/config/automerge_pin_only_test.go create mode 100644 src/pkg/github/pin_only_files_test.go create mode 100644 src/pkg/intent/pin_only.go create mode 100644 src/pkg/intent/pin_only_test.go diff --git a/changelog.d/added-pin-only-human-merge-config.md b/changelog.d/added-pin-only-human-merge-config.md new file mode 100644 index 0000000000..8b08b91c56 --- /dev/null +++ b/changelog.d/added-pin-only-human-merge-config.md @@ -0,0 +1 @@ +- Add validated per-repository `auto_merge.human_merge_pin_only` schema, changed-file patch evidence and a fail-closed pin-replacement syntax classifier as building blocks for #16242; merge-path exceptions are not yet enabled and existing human-merge protections remain unchanged. diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index fa451fc8ba..8a8b2293c9 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -154,6 +154,56 @@ 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). +**Staged pin-only policy (not yet enforced).** + +`auto_merge.human_merge_pin_only` provides the schema and conservative diff +classifier for #16242 / #16262. **It does not currently enable an exception:** +relay, sweep, `/approve` and native-queue gates still require the existing +human-merge path policy. Do not remove `human_merge_paths` or manually clear a +hold to simulate this feature. + +```yaml +auto_merge: + human_merge_paths: + owner/repo: [".github/workflows/*.yml", "Containerfile"] + human_merge_pin_only: + owner/repo: + enabled: true + paths: [".github/workflows/*.yml", "Containerfile"] + kinds: [action-sha, image-digest, version-pin] + trusted_authors: [maintainer-login] +``` + +Repository keys are case-insensitive; duplicate normalized keys are rejected. +Absent/disabled entries have no effect. Enabled entries require nonempty paths, +kinds and trusted authors; unknown kinds are rejected, including when disabled. +The classifier accepts only existing modified files in both the actual guarded +path matches and exception paths, and checks **all** files in the PR. Every +changed line must be a paired pin replacement. Supported forms are unquoted +`uses: owner/repo[/path]@<40-hex>` (an existing simple `# vN[.N[.N]]` +comment may change), `FROM image@sha256:<64-hex>` / `image: image@sha256:...`, +and literal `version: 1.2.3` / `ARG TOOL_VERSION=1.2.3` updates. Other syntax, +missing patches, line-count mismatches, added/renamed files, owner files, +permission/credential/signing text and non-pin edits fail closed. + +This classifier proves **syntax only**, not authenticated identity, exact-head +binding, file-list completeness, semantic interpretation or review of upstream +references. Those proofs must be added by the integration children (#16265, +#16266); 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 +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. The existing config-file watcher reloads the seed with the +dashboard overlay via `LoadWithDashboardOverlay`; invalid configuration is not +installed. Reloading this schema alone still does **not** enable admission. The +integration PRs must wire live policy updates into every merge path. + +There is **no minimum deployable version enabling this lane yet**. Utah rollout +and current-head positive/negative deployment evidence remain tracked by +projectbluefin/utah#1082 and #16242; projectbluefin/utah#1068 is not pre-authorized. + **Contributor PRs are held to the contributor-lane policy.** A merge request for a PR whose author is not the hive App, a configured trusted bot, or a trusted-author role is evaluated against the same `auto_merge.contributor_lane` diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 97abd1aa21..f366bbe675 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -253,6 +253,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `project.label_driven_supersede_park_actors` | `[]` (off) | Automation logins (for example a lifecycle bot running as `github-actions[bot]`) whose park labels a later trusted acceptance supersedes on label-driven repos: Hive removes the label, says so in the release comment, and releases the issue ([#13605](https://github.com/hivecommons/hive/issues/13605)). Park labels added by people, by unlisted bots, or by a listed bot after the acceptance still block; `hold` is never superseded. Per-repo override: `project.repo_policies[].label_driven_supersede_park_actors`. | | `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); **not yet enforced**. | Staged per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. Provides syntax-classification building blocks only: no merge route grants an exception or clears a 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. | diff --git a/src/pkg/config/automerge_pin_only.go b/src/pkg/config/automerge_pin_only.go new file mode 100644 index 0000000000..603a90caa2 --- /dev/null +++ b/src/pkg/config/automerge_pin_only.go @@ -0,0 +1,90 @@ +package config + +import ( + "fmt" + "strings" + + "github.com/hivecommons/hive/pkg/intent" +) + +// PinOnlyException is staged policy, not authorization to merge. The eventual +// admission gates must supply authenticated identity, exact-head diff and review +// evidence before consulting the purely syntactic classifier. +type PinOnlyException struct { + Enabled bool `yaml:"enabled" json:"enabled"` + Paths []string `yaml:"paths" json:"paths"` + Kinds []string `yaml:"kinds" json:"kinds"` + TrustedAuthors []string `yaml:"trusted_authors" json:"trusted_authors"` +} + +func (p PinOnlyException) validate() error { + for _, kind := range p.Kinds { + switch kind { + case "action-sha", "image-digest", "version-pin": + default: + return fmt.Errorf("unknown kind %q", kind) + } + } + if !p.Enabled { + return nil + } + for name, values := range map[string][]string{"paths": p.Paths, "kinds": p.Kinds, "trusted_authors": p.TrustedAuthors} { + if len(values) == 0 { + return fmt.Errorf("enabled policy requires nonempty %s", name) + } + for _, value := range values { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("%s contains an empty value", name) + } + } + } + return nil +} + +// Spec returns classifier input only; it deliberately contains no merge grant. +func (p PinOnlyException) Spec() intent.PinOnlySpec { + return intent.PinOnlySpec{Paths: append([]string(nil), p.Paths...), Kinds: append([]string(nil), p.Kinds...)} +} + +// ValidateHumanMergePinOnly rejects ambiguous repository keys and invalid policy. +// Paths are checked against actual human-merge matches by the classifier, rather +// than attempting to infer containment between arbitrary glob languages. +func (a AutoMergeConfig) ValidateHumanMergePinOnly() error { + seen := make(map[string]bool) + for repo, policy := range a.HumanMergePinOnly { + key := strings.ToLower(strings.TrimSpace(repo)) + parts := strings.Split(key, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" || strings.ContainsAny(key, " \t\n\r*") || seen[key] { + return fmt.Errorf("auto_merge.human_merge_pin_only: invalid or duplicate repository %q", repo) + } + seen[key] = true + if err := policy.validate(); err != nil { + return fmt.Errorf("auto_merge.human_merge_pin_only[%s]: %w", repo, err) + } + } + return nil +} + +// HumanMergePinOnlyFor returns a defensive copy of an enabled, valid policy. +// Ambiguous case-insensitive keys fail closed even before config validation. +func (a AutoMergeConfig) HumanMergePinOnlyFor(repo string) (PinOnlyException, bool) { + var result PinOnlyException + found := false + for key, policy := range a.HumanMergePinOnly { + if !strings.EqualFold(strings.TrimSpace(key), strings.TrimSpace(repo)) { + continue + } + if found { + return PinOnlyException{}, false + } + found = true + result = policy + } + if !found || !result.Enabled || result.validate() != nil { + return PinOnlyException{}, false + } + result.Paths = append([]string(nil), result.Paths...) + result.Kinds = append([]string(nil), result.Kinds...) + result.TrustedAuthors = append([]string(nil), result.TrustedAuthors...) + return result, true +} diff --git a/src/pkg/config/automerge_pin_only_test.go b/src/pkg/config/automerge_pin_only_test.go new file mode 100644 index 0000000000..e4e5f7b9d2 --- /dev/null +++ b/src/pkg/config/automerge_pin_only_test.go @@ -0,0 +1,88 @@ +package config + +import ( + "testing" + + "gopkg.in/yaml.v3" +) + +func TestHumanMergePinOnlyConfig(t *testing.T) { + var cfg Config + if err := yaml.Unmarshal([]byte(`auto_merge: + human_merge_pin_only: + Owner/Repo: + enabled: true + paths: [".github/workflows/*.yml"] + kinds: [action-sha] + trusted_authors: [maintainer] +`), &cfg); err != nil { + t.Fatal(err) + } + if err := cfg.AutoMerge.ValidateHumanMergePinOnly(); err != nil { + t.Fatal(err) + } + policy, ok := cfg.AutoMerge.HumanMergePinOnlyFor(" owner/REPO ") + if !ok || len(policy.Spec().Paths) != 1 || policy.TrustedAuthors[0] != "maintainer" { + t.Fatalf("policy = %+v, %v", policy, ok) + } + policy.Paths[0] = "*" + policy.Kinds[0] = "anything" + policy.TrustedAuthors[0] = "attacker" + again, _ := cfg.AutoMerge.HumanMergePinOnlyFor("owner/repo") + if again.Paths[0] == "*" || again.Kinds[0] != "action-sha" || again.TrustedAuthors[0] != "maintainer" { + t.Fatal("accessor leaked config slices") + } + if _, ok := cfg.AutoMerge.HumanMergePinOnlyFor("other/repo"); ok { + t.Fatal("unknown repo enabled") + } + if _, ok := (AutoMergeConfig{}).HumanMergePinOnlyFor("owner/repo"); ok { + t.Fatal("absent config enabled") + } +} + +func TestHumanMergePinOnlyInvalidConfig(t *testing.T) { + valid := func() PinOnlyException { + return PinOnlyException{Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"maintainer"}} + } + for _, tc := range []struct { + name string + change func(*PinOnlyException) + valid bool + }{ + {"valid", func(_ *PinOnlyException) {}, true}, + {"disabled", func(p *PinOnlyException) { *p = PinOnlyException{} }, true}, + {"no paths", func(p *PinOnlyException) { p.Paths = nil }, false}, + {"no kinds", func(p *PinOnlyException) { p.Kinds = nil }, false}, + {"no authors", func(p *PinOnlyException) { p.TrustedAuthors = nil }, false}, + {"blank author", func(p *PinOnlyException) { p.TrustedAuthors = []string{" "} }, false}, + {"blank path", func(p *PinOnlyException) { p.Paths = []string{""} }, false}, + {"unknown kind", func(p *PinOnlyException) { p.Kinds = []string{"sha-shaped-text"} }, false}, + {"disabled unknown kind", func(p *PinOnlyException) { p.Enabled = false; p.Kinds = []string{"anything"} }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := valid() + tc.change(&p) + a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{"o/r": p}} + if err := a.ValidateHumanMergePinOnly(); (err == nil) != tc.valid { + t.Fatalf("validation = %v", err) + } + _, ok := a.HumanMergePinOnlyFor("O/R") + if ok != (tc.valid && p.Enabled) { + t.Fatalf("accessor enabled = %v", ok) + } + }) + } + for _, key := range []string{"", "owner", "o/", "/r", "o/r/extra", "o /r", "*/r"} { + a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{key: valid()}} + if err := a.ValidateHumanMergePinOnly(); err == nil { + t.Errorf("accepted invalid key %q", key) + } + } + a := AutoMergeConfig{HumanMergePinOnly: map[string]PinOnlyException{"o/r": valid(), "O/R": valid()}} + if err := a.ValidateHumanMergePinOnly(); err == nil { + t.Fatal("accepted duplicate key") + } + if _, ok := a.HumanMergePinOnlyFor("o/r"); ok { + t.Fatal("ambiguous policy enabled") + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 7b455118c2..6f90dee1e4 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -8336,6 +8336,10 @@ type AutoMergeConfig struct { // means no such paths. This key only declares the paths; enforcement // lives in the merge sweeps. HumanMergePaths map[string][]string `yaml:"human_merge_paths,omitempty" json:"human_merge_paths,omitempty"` + + // HumanMergePinOnly stages opt-in pin-only policy. Admission wiring must + // independently prove trusted identity, exact-head evidence and upstream review. + 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 // no merge train merges it (hivecommons/hive#15442). Unset means the diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index ef95afbc59..d7ff413ffc 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -200,6 +200,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.validateSpektacularRecheckDiscovery(); err != nil { return err } + if err := c.AutoMerge.ValidateHumanMergePinOnly(); err != nil { + return err + } if err := c.AutoMerge.TrustedAuthors.Validate(); err != nil { return err } diff --git a/src/pkg/github/automerge/automerge_intent_test.go b/src/pkg/github/automerge/automerge_intent_test.go index a1a9666ced..291ffe9cba 100644 --- a/src/pkg/github/automerge/automerge_intent_test.go +++ b/src/pkg/github/automerge/automerge_intent_test.go @@ -312,7 +312,7 @@ func TestListChangedFilesPagesThroughFilesAPI(t *testing.T) { switch r.URL.Query().Get("page") { case "": w.Header().Set("Link", `<`+base+`/repos/acme/widget/pulls/7/files?page=2>; rel="next"`) - json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentSourceFile, "status": "modified", "additions": 1, "deletions": 2}}) + json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentSourceFile, "status": "modified", "additions": 1, "deletions": 2, "patch": "@@ -1,2 +1 @@\n-old\n-old2\n+new"}}) case "2": json.NewEncoder(w).Encode([]map[string]any{{"filename": testIntentDocsFile, "status": "added", "additions": 3, "deletions": 0}}) default: @@ -329,7 +329,7 @@ func TestListChangedFilesPagesThroughFilesAPI(t *testing.T) { t.Fatalf("ListChangedFiles() error = %v, want nil for a complete two-page list", err) } want := []intent.ChangedFile{ - {Filename: testIntentSourceFile, Status: "modified", Additions: 1, Deletions: 2}, + {Filename: testIntentSourceFile, Status: "modified", Additions: 1, Deletions: 2, Patch: "@@ -1,2 +1 @@\n-old\n-old2\n+new"}, {Filename: testIntentDocsFile, Status: "added", Additions: 3, Deletions: 0}, } if !reflect.DeepEqual(files, want) { diff --git a/src/pkg/github/human_merge_paths.go b/src/pkg/github/human_merge_paths.go index 2d45f338bc..7450c2b986 100644 --- a/src/pkg/github/human_merge_paths.go +++ b/src/pkg/github/human_merge_paths.go @@ -53,6 +53,7 @@ func ListPRChangedFiles(ctx context.Context, client *gh.Client, owner, repo stri Status: f.GetStatus(), Additions: f.GetAdditions(), Deletions: f.GetDeletions(), + Patch: f.GetPatch(), }) } if resp == nil || resp.NextPage == 0 { diff --git a/src/pkg/github/pin_only_files_test.go b/src/pkg/github/pin_only_files_test.go new file mode 100644 index 0000000000..b0d0cde9c3 --- /dev/null +++ b/src/pkg/github/pin_only_files_test.go @@ -0,0 +1,50 @@ +package github + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/intent" +) + +func TestPinOnlyChangedFileEvidence(t *testing.T) { + patch := "@@ -1 +1 @@\n-FROM image@sha256:" + strings.Repeat("a", 64) + "\n+FROM image@sha256:" + strings.Repeat("b", 64) + for _, present := range []bool{true, false} { + t.Run(map[bool]string{true: "patch present", false: "patch omitted"}[present], func(t *testing.T) { + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/repos/o/r/pulls/1/files" { + http.NotFound(w, r) + return + } + file := map[string]any{"filename": "Containerfile", "status": "modified", "additions": 1, "deletions": 1} + if present { + file["patch"] = patch + } + _ = json.NewEncoder(w).Encode([]map[string]any{file}) + })) + defer api.Close() + client := gh.NewClient(api.Client()) + client.BaseURL, _ = url.Parse(api.URL + "/") + pr := &gh.PullRequest{Number: gh.Ptr(1), ChangedFiles: gh.Ptr(1)} + files, err := ListPRChangedFiles(context.Background(), client, "o", "r", pr) + if err != nil { + t.Fatal(err) + } + ok, why := intent.ClassifyPinOnly(files, []string{"Containerfile"}, intent.PinOnlySpec{Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}}) + if ok != present { + t.Fatalf("classification = %v, %s", ok, why) + } + pr.ChangedFiles = gh.Ptr(2) + if _, err := ListPRChangedFiles(context.Background(), client, "o", "r", pr); !errors.Is(err, ErrIncompletePRFileList) { + t.Fatalf("incomplete list: %v", err) + } + }) + } +} diff --git a/src/pkg/intent/intent.go b/src/pkg/intent/intent.go index fe4a232060..5b2e59ad9a 100644 --- a/src/pkg/intent/intent.go +++ b/src/pkg/intent/intent.go @@ -102,6 +102,8 @@ type ChangedFile struct { Status string Additions int Deletions int + // Patch is the unified diff from the files API; empty means unavailable. + Patch string } type PR struct { diff --git a/src/pkg/intent/pin_only.go b/src/pkg/intent/pin_only.go new file mode 100644 index 0000000000..7955852c6d --- /dev/null +++ b/src/pkg/intent/pin_only.go @@ -0,0 +1,203 @@ +package intent + +import ( + "fmt" + "path" + "regexp" + "strconv" + "strings" +) + +// PinOnlySpec is syntax policy, not a trust or merge authorization decision. +type PinOnlySpec struct { + Paths []string + Kinds []string +} + +var ( + pinHunkRE = regexp.MustCompile(`^@@ -[0-9]+(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@(?: .*)?$`) + actionPinRE = regexp.MustCompile(`^([ \t]*(?:- )?uses: [A-Za-z0-9_.-]+/[A-Za-z0-9_./-]+@)([0-9a-fA-F]{40})([ \t]*(?:# v[0-9]+(?:\.[0-9]+){0,2})?)$`) + imagePinRE = regexp.MustCompile(`^([ \t]*(?:FROM |image: )[A-Za-z0-9][A-Za-z0-9._/:\-]*@sha256:)([0-9a-fA-F]{64})([ \t]*(?:AS [A-Za-z0-9_-]+)?)$`) + versionPinRE = regexp.MustCompile(`^([ \t]*(?:version: |ARG [A-Z][A-Z0-9_]*_VERSION=))(["']?v?[0-9]+\.[0-9]+\.[0-9]+["']?)([ \t]*)$`) + unsafePinRE = regexp.MustCompile(`(?i)(permissions|secrets[.]|\benv\b|\brun:|\bwith:|id-token|cosign|attest|provenance|credential|signing|codeowners)`) +) + +// ClassifyPinOnly checks the entire supplied diff, not only guarded files: a +// mixed PR must not acquire a pin-only exception. Every file must be an existing +// modified file in both the actual human-merge matches and the exception paths. +// Missing/truncated/malformed patches fail closed, including mismatched API +// addition/deletion counts. Deliberately supports only narrow line grammars. +// +// Callers MUST separately prove a complete file list bound to the current head, +// authenticated trusted authorship, and review of each referenced upstream +// change. A true result proves syntax only, NEVER those facts or merge safety. +func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (bool, string) { + if len(files) == 0 || len(matches) == 0 || len(spec.Paths) == 0 || len(spec.Kinds) == 0 { + return false, "missing pin-only evidence or policy" + } + kinds := make(map[string]bool) + for _, kind := range spec.Kinds { + switch kind { + case "action-sha", "image-digest", "version-pin": + kinds[kind] = true + default: + return false, "unknown pin kind: " + kind + } + } + guarded := make(map[string]bool) + for _, match := range matches { + guarded[match] = true + } + seen := make(map[string]bool) + for _, file := range files { + name := file.Filename + if name == "" || path.Clean(name) != name || strings.HasPrefix(name, "../") || strings.HasPrefix(name, "/") || seen[name] { + return false, "invalid or duplicate path: " + name + } + seen[name] = true + if !guarded[name] || !PathMatchesAny(name, spec.Paths) { + return false, name + ": outside approved human-merge paths" + } + if strings.Contains(strings.ToLower(name), "owners") || file.Status != "modified" || file.Patch == "" { + return false, name + ": not an existing modified pin file with a patch" + } + if err := classifyPinPatch(file, kinds); err != nil { + return false, name + ": " + err.Error() + } + } + for match := range guarded { + if !seen[match] { + return false, match + ": missing matched file" + } + } + return true, "all changes are approved pin replacements (syntax only)" +} + +func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { + var removed, added []string + oldLeft, newLeft, additions, deletions, hunks := 0, 0, 0, 0, 0 + flush := func() error { + if len(removed) != len(added) { + return fmt.Errorf("unpaired addition/removal") + } + for i := range removed { + if !pinReplacement(removed[i], added[i], kinds) { + return fmt.Errorf("non-pin or unsafe replacement") + } + } + removed, added = nil, nil + return nil + } + lines := strings.Split(strings.TrimSuffix(file.Patch, "\n"), "\n") + for i, line := range lines { + if m := pinHunkRE.FindStringSubmatch(line); m != nil { + if err := flush(); err != nil { + return err + } + if oldLeft != 0 || newLeft != 0 { + return fmt.Errorf("incomplete hunk before line %d", i+1) + } + oldLeft, newLeft = 1, 1 + var err error + if m[1] != "" { + oldLeft, err = strconv.Atoi(m[1]) + if err != nil { + return fmt.Errorf("invalid old hunk count") + } + } + if m[2] != "" { + newLeft, err = strconv.Atoi(m[2]) + if err != nil { + return fmt.Errorf("invalid new hunk count") + } + } + hunks++ + continue + } + if hunks == 0 || line == "" { + return fmt.Errorf("invalid patch line %d", i+1) + } + switch line[0] { + case ' ': + if err := flush(); err != nil { + return err + } + oldLeft-- + newLeft-- + case '-': + if len(added) != 0 { + return fmt.Errorf("interleaved replacement") + } + removed = append(removed, line[1:]) + deletions++ + oldLeft-- + case '+': + added = append(added, line[1:]) + additions++ + newLeft-- + default: + // Even newline/format metadata is outside this bounded grammar. + return fmt.Errorf("unsupported patch line %d", i+1) + } + if oldLeft < 0 || newLeft < 0 { + return fmt.Errorf("hunk count exceeded") + } + } + if err := flush(); err != nil { + return err + } + if hunks == 0 || oldLeft != 0 || newLeft != 0 || additions == 0 || additions != file.Additions || deletions != file.Deletions { + return fmt.Errorf("incomplete patch or mismatched changed-line counts") + } + return nil +} + +func pinReplacement(old, next string, kinds map[string]bool) bool { + if old == next || unsafePinRE.MatchString(old) || unsafePinRE.MatchString(next) { + return false + } + for _, kind := range []string{"action-sha", "image-digest", "version-pin"} { + if !kinds[kind] { + continue + } + re := actionPinRE + switch kind { + case "image-digest": + re = imagePinRE + case "version-pin": + re = versionPinRE + } + a, b := re.FindStringSubmatch(old), re.FindStringSubmatch(next) + if a == nil || b == nil || a[1] != b[1] || a[2] == b[2] { + continue + } + // Only action version comments may change; all other suffixes (image + // aliases, whitespace and quoting) must remain byte-identical. + if kind == "action-sha" { + if strings.Contains(a[3], "#") != strings.Contains(b[3], "#") { + continue + } + return true + } + if kind == "version-pin" { + // Do not permit quote changes to alter YAML interpretation. + quote := func(s string) byte { + if s[0] == '\'' || s[0] == '"' { + return s[0] + } + return 0 + } + q := quote(a[2]) + if q != quote(b[2]) || (q != 0 && (a[2][len(a[2])-1] != q || b[2][len(b[2])-1] != q)) { + continue + } + if q == 0 && (strings.HasSuffix(a[2], "'") || strings.HasSuffix(a[2], "\"") || strings.HasSuffix(b[2], "'") || strings.HasSuffix(b[2], "\"")) { + continue + } + } + if a[3] == b[3] { + return true + } + } + return false +} diff --git a/src/pkg/intent/pin_only_test.go b/src/pkg/intent/pin_only_test.go new file mode 100644 index 0000000000..245d73f263 --- /dev/null +++ b/src/pkg/intent/pin_only_test.go @@ -0,0 +1,115 @@ +package intent + +import ( + "strings" + "testing" +) + +func TestClassifyPinOnly(t *testing.T) { + old := " uses: actions/checkout@" + strings.Repeat("a", 40) + " # v4" + next := " uses: actions/checkout@" + strings.Repeat("b", 40) + " # v5" + patch := func(a, b string) string { return "@@ -1 +1 @@\n-" + a + "\n+" + b } + file := ChangedFile{Filename: ".github/workflows/build.yml", Status: "modified", Additions: 1, Deletions: 1, Patch: patch(old, next)} + spec := PinOnlySpec{Paths: []string{".github/workflows/*.yml", "Containerfile"}, Kinds: []string{"action-sha", "image-digest", "version-pin"}} + for _, tc := range []struct { + name string + mutate func(*ChangedFile, *PinOnlySpec) + want bool + }{ + {"pure action SHA", func(_ *ChangedFile, _ *PinOnlySpec) {}, true}, + {"image digest", func(f *ChangedFile, _ *PinOnlySpec) { + f.Filename = "Containerfile" + f.Patch = patch("FROM ghcr.io/org/image@sha256:"+strings.Repeat("a", 64), "FROM ghcr.io/org/image@sha256:"+strings.Repeat("b", 64)) + }, true}, + {"version literal", func(f *ChangedFile, _ *PinOnlySpec) { + f.Filename = "Containerfile" + f.Patch = patch("ARG TOOL_VERSION=1.2.3", "ARG TOOL_VERSION=1.2.4") + }, true}, + {"added step", func(f *ChangedFile, _ *PinOnlySpec) { + f.Additions++ + f.Patch = strings.Replace(f.Patch, "@@ -1 +1 @@", "@@ -1 +1,2 @@", 1) + "\n+- run: evil" + }, false}, + {"permission change", func(f *ChangedFile, _ *PinOnlySpec) { + f.Additions++ + f.Deletions++ + f.Patch += "\n@@ -4 +4 @@\n-permissions: read-all\n+permissions: write-all" + }, false}, + {"missing patch", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch = "" }, false}, + {"truncated patch", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch += "\n@@ -4,3 +4,3 @@\n context" }, false}, + {"counts disagree", func(f *ChangedFile, _ *PinOnlySpec) { f.Additions++ }, false}, + {"added file", func(f *ChangedFile, _ *PinOnlySpec) { f.Status = "added" }, false}, + {"renamed file", func(f *ChangedFile, _ *PinOnlySpec) { f.Status = "renamed" }, false}, + {"outside exception paths", func(_ *ChangedFile, s *PinOnlySpec) { s.Paths = []string{"Containerfile"} }, false}, + {"kind disabled", func(_ *ChangedFile, s *PinOnlySpec) { s.Kinds = []string{"image-digest"} }, false}, + {"unknown kind", func(_ *ChangedFile, s *PinOnlySpec) { s.Kinds = append(s.Kinds, "anything") }, false}, + {"changed source", func(f *ChangedFile, _ *PinOnlySpec) { + f.Patch = patch(old, strings.Replace(next, "actions/checkout", "attacker/checkout", 1)) + }, false}, + {"SHA-shaped command", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch = patch("run: echo "+old, "run: echo "+next) }, false}, + {"arbitrary comment", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch = patch(old, next+" execute something") }, false}, + {"trust boundary pin", func(f *ChangedFile, _ *PinOnlySpec) { + f.Patch = patch(strings.Replace(old, "actions/checkout", "sigstore/cosign", 1), strings.Replace(next, "actions/checkout", "sigstore/cosign", 1)) + }, false}, + {"owners file", func(f *ChangedFile, s *PinOnlySpec) { f.Filename = "CODEOWNERS"; s.Paths = []string{"*"} }, false}, + {"metadata only", func(f *ChangedFile, _ *PinOnlySpec) { + f.Patch = "@@ -1 +1 @@\n unchanged" + f.Additions = 0 + f.Deletions = 0 + }, false}, + {"malformed line", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch += "\n" + "not a diff" }, false}, + {"extra diff lines", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch += "\n extra" }, false}, + {"unpaired removal", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch = "@@ -1 +1,0 @@\n-" + old; f.Additions = 0 }, false}, + {"invalid hunk count", func(f *ChangedFile, _ *PinOnlySpec) { + f.Patch = "@@ -1,99999999999999999999999999999999 +1 @@\n-" + old + "\n+" + next + }, false}, + {"no hunk", func(f *ChangedFile, _ *PinOnlySpec) { f.Patch = "-" + old + "\n+" + next }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + f, s := file, PinOnlySpec{Paths: append([]string(nil), spec.Paths...), Kinds: append([]string(nil), spec.Kinds...)} + tc.mutate(&f, &s) + ok, reason := ClassifyPinOnly([]ChangedFile{f}, []string{f.Filename}, s) + if ok != tc.want || reason == "" { + t.Fatalf("got (%v, %q), want %v", ok, reason, tc.want) + } + }) + } + for _, tc := range []struct { + name string + files []ChangedFile + matches []string + }{ + {"empty files", nil, []string{file.Filename}}, + {"no guarded paths", []ChangedFile{file}, nil}, + {"missing matched file", []ChangedFile{file}, []string{file.Filename, "Containerfile"}}, + {"duplicate file", []ChangedFile{file, file}, []string{file.Filename}}, + {"unguarded file", []ChangedFile{file, {Filename: "other.yml", Status: "modified", Additions: 1, Deletions: 1, Patch: file.Patch}}, []string{file.Filename}}, + } { + t.Run(tc.name, func(t *testing.T) { + if ok, why := ClassifyPinOnly(tc.files, tc.matches, spec); ok { + t.Fatalf("unexpected eligibility: %s", why) + } + }) + } +} + +func TestPinReplacementNarrowGrammar(t *testing.T) { + kinds := map[string]bool{"version-pin": true, "image-digest": true} + for _, tc := range []struct { + old, next string + want bool + }{ + {"version: '1.2.3'", "version: '1.2.4'", true}, + {"version: 1.2.3", "version: 1.2.4'", false}, + {"version: '1.2.3'", "version: \"1.2.4\"", false}, + {"ARG TOOL_VERSION=1.2.3", "ARG TOOL_VERSION=1.2.4; evil", false}, + {"env: 1.2.3", "env: 1.2.4", false}, + {"with: 1.2.3", "with: 1.2.4", false}, + {"version: 1.2.3", "version: 1.2.3", false}, + {"version: 1.2.3", "version: 1.2.4", true}, + {"ARG SIGNING_VERSION=1.2.3", "ARG SIGNING_VERSION=1.2.4", false}, + } { + if got := pinReplacement(tc.old, tc.next, kinds); got != tc.want { + t.Errorf("%q -> %q: got %v", tc.old, tc.next, got) + } + } +} From 2b90d73dacdee8ee51e20d27584efeb5f5d09aea Mon Sep 17 00:00:00 2001 From: mendezr Date: Mon, 2 Nov 2026 20:02:47 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20fix(intent):=20explicitly=20?= =?UTF-8?q?project=20changed=20files=20into=20alignment=20summaries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: mendezr --- src/pkg/intent/alignment.go | 10 ++++++-- src/pkg/intent/alignment_files_test.go | 34 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/pkg/intent/alignment_files_test.go diff --git a/src/pkg/intent/alignment.go b/src/pkg/intent/alignment.go index c922d8c77f..e4da50932e 100644 --- a/src/pkg/intent/alignment.go +++ b/src/pkg/intent/alignment.go @@ -274,7 +274,10 @@ func boundedFiles(files []ChangedFile) ([]DiffFileSummary, int) { } out := make([]DiffFileSummary, 0, limit) for _, f := range files[:limit] { - out = append(out, DiffFileSummary(f)) + out = append(out, DiffFileSummary{ + Filename: f.Filename, Status: f.Status, + Additions: f.Additions, Deletions: f.Deletions, + }) } return out, len(files) - limit } @@ -282,7 +285,10 @@ func boundedFiles(files []ChangedFile) ([]DiffFileSummary, int) { func allFiles(files []ChangedFile) []DiffFileSummary { out := make([]DiffFileSummary, 0, len(files)) for _, f := range files { - out = append(out, DiffFileSummary(f)) + out = append(out, DiffFileSummary{ + Filename: f.Filename, Status: f.Status, + Additions: f.Additions, Deletions: f.Deletions, + }) } return out } diff --git a/src/pkg/intent/alignment_files_test.go b/src/pkg/intent/alignment_files_test.go new file mode 100644 index 0000000000..56e7c341a5 --- /dev/null +++ b/src/pkg/intent/alignment_files_test.go @@ -0,0 +1,34 @@ +package intent + +import ( + "reflect" + "testing" +) + +func TestAlignmentFileSummaries(t *testing.T) { + files := make([]ChangedFile, MaxAlignmentFiles+1) + want := make([]DiffFileSummary, len(files)) + for i := range files { + files[i] = ChangedFile{ + Filename: "src/example.go", Status: "modified", + Additions: i + 1, Deletions: i + 2, + Patch: "@@ -1 +1 @@\n-old\n+new", + } + want[i] = DiffFileSummary{ + Filename: "src/example.go", Status: "modified", + Additions: i + 1, Deletions: i + 2, + } + } + + if got := allFiles(files); !reflect.DeepEqual(got, want) { + t.Fatalf("allFiles() = %v, want %v", got, want) + } + bounded, truncated := boundedFiles(files) + if !reflect.DeepEqual(bounded, want[:MaxAlignmentFiles]) || truncated != 1 { + t.Fatalf("boundedFiles() = %v, %d; want %v, 1", bounded, truncated, want[:MaxAlignmentFiles]) + } + bounded, truncated = boundedFiles(files[:1]) + if !reflect.DeepEqual(bounded, want[:1]) || truncated != 0 { + t.Fatalf("boundedFiles(single file) = %v, %d; want %v, 0", bounded, truncated, want[:1]) + } +}