From a9603cf046caf2aedeb61d4ae6e778622b7dbf5d Mon Sep 17 00:00:00 2001 From: pelikhan Date: Tue, 27 Oct 2026 22:04:51 -0700 Subject: [PATCH 1/8] fix(workflow): keep compiler-only PR filters out of Actions triggers Exit compiler-only on subsections before detecting the next event and compile explicit pull_request_target fork filters into event-scoped job conditions. Preserve native trigger fields and existing default fork behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/src/content/docs/reference/triggers.md | 4 +- pkg/workflow/filters.go | 35 +++--- pkg/workflow/filters_forks_test.go | 115 ++++++++++++++++-- .../frontmatter_on_section_cleanup.go | 12 +- .../frontmatter_on_section_cleanup_test.go | 61 ++++++++++ 5 files changed, 189 insertions(+), 38 deletions(-) diff --git a/docs/src/content/docs/reference/triggers.md b/docs/src/content/docs/reference/triggers.md index 3db86b26e5a..35f40aa9893 100644 --- a/docs/src/content/docs/reference/triggers.md +++ b/docs/src/content/docs/reference/triggers.md @@ -190,7 +190,7 @@ Strict mode rejects `pull_request_target` when `on.roles` contains `all` or `rea #### Fork Filtering (`forks:`) -Pull request workflows block forks by default for security. Use the `forks:` field to allow specific fork patterns: +`pull_request` workflows block forks by default for security. Use the `forks:` field to allow specific fork patterns: ```yaml wrap on: @@ -203,6 +203,8 @@ Use `["owner/repo"]` for a specific repository, `["owner/*"]` for an entire org/ Alternatively, use `forks: {author-association: [OWNER, MEMBER, COLLABORATOR]}` to allow fork PRs by the author's relationship to the base repository rather than the fork owner. Same-repository PRs remain allowed, and no association is implicitly included. See [author associations](/gh-aw/reference/fork-support/#author-associations) for trust and secret-availability considerations. +`pull_request_target` also supports explicit fork repository patterns; same-repository PRs remain allowed. Omitting `forks:` does not add a fork restriction for this event. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. + #### Stacked PR Filtering (`max-stack:`) When using stacked pull requests (a chain of PRs each targeting the previous one), every PR in the stack normally triggers workflows. This multiplies CI cost for identical changes being reviewed at multiple layers. The `max-stack:` field lets you limit which stack layers run the workflow. diff --git a/pkg/workflow/filters.go b/pkg/workflow/filters.go index 5036169877a..4c35cc8a58c 100644 --- a/pkg/workflow/filters.go +++ b/pkg/workflow/filters.go @@ -103,9 +103,9 @@ func (c *Compiler) applyPullRequestDraftFilter(data *WorkflowData, frontmatter m data.If = RenderCondition(conditionTree) } -// applyPullRequestForkFilter applies fork filter conditions for pull_request triggers +// applyPullRequestForkFilter applies fork filter conditions for pull_request and pull_request_target triggers. // Supports repository patterns or an explicit author-association list. -// Default behavior: When forks field is not specified, only same-repo PRs are allowed (forks are disallowed by default) +// Without an explicit forks field, only pull_request defaults to same-repo PRs. func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter map[string]any) { filtersLog.Print("Applying pull request fork filter") @@ -130,33 +130,29 @@ func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter ma return } - // Check if there's a pull_request section - prValue, hasPR := onMap["pull_request"] - if !hasPR { - return - } - - // Check if pull_request is an object with fork settings - prMap, isPRMap := prValue.(map[string]any) - if !isPRMap { - return + for _, eventName := range []string{"pull_request", "pull_request_target"} { + prMap, ok := onMap[eventName].(map[string]any) + if !ok { + continue + } + if _, hasForks := prMap["forks"]; eventName == "pull_request_target" && !hasForks { + continue + } + c.applyPullRequestEventForkFilter(data, eventName, prMap) } +} - // Check for "forks" field (string, array, or author-association object) +func (c *Compiler) applyPullRequestEventForkFilter(data *WorkflowData, eventName string, prMap map[string]any) { forksValue, hasForks := prMap["forks"] - // Default behavior: If forks field is not specified, only allow same-repo PRs (disallow all forks by default) var allowedForks []string var allowedAssociations []string if !hasForks { filtersLog.Print("No forks field specified - applying default fork filter (disallow all forks)") - // Empty allowedForks array means only same-repo PRs are allowed allowedForks = []string{} } else { filtersLog.Print("Found forks filter configuration") - // Parse repository patterns or author associations. - // Handle string format (e.g., forks: "*" or forks: "org/*") if forksStr, isForksStr := forksValue.(string); isForksStr { allowedForks = []string{forksStr} } else if forksArray, isForksArray := forksValue.([]any); isForksArray { @@ -174,16 +170,14 @@ func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter ma } } - // If "*" wildcard is present, skip fork filtering (allow all forks) if slices.Contains(allowedForks, "*") { filtersLog.Print("Wildcard fork pattern detected, allowing all forks") return // No fork filtering needed } - // Build condition for allowed forks with glob support notPullRequestEvent := BuildNotEquals( BuildPropertyAccess("github.event_name"), - BuildStringLiteral("pull_request"), + BuildStringLiteral(eventName), ) allowedForksCondition := BuildFromAllowedForks(allowedForks) if len(allowedAssociations) > 0 { @@ -203,7 +197,6 @@ func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter ma Right: allowedForksCondition, } - // Build condition tree and render existingCondition := data.If conditionTree := BuildConditionTree(existingCondition, forkCondition.Render()) data.If = RenderCondition(conditionTree) diff --git a/pkg/workflow/filters_forks_test.go b/pkg/workflow/filters_forks_test.go index 5391b98978e..a32c1e585ed 100644 --- a/pkg/workflow/filters_forks_test.go +++ b/pkg/workflow/filters_forks_test.go @@ -3,8 +3,10 @@ package workflow import ( + "fmt" "os" "path/filepath" + "strings" "testing" "github.com/github/gh-aw/pkg/testutil" @@ -13,6 +15,77 @@ import ( "github.com/stretchr/testify/require" ) +func TestTriggerForkFilterCompilation(t *testing.T) { + tests := []struct { + name string + forks string + expected string + }{ + {"wildcard", `["*"]`, ""}, + {"empty", "[]", "github.event.pull_request.head.repo.id == github.repository_id"}, + {"exact", `"trusted/repo"`, "github.event.pull_request.head.repo.full_name == 'trusted/repo'"}, + {"patterns", "\n - trusted/*\n - partner/repo", "startsWith(github.event.pull_request.head.repo.full_name, 'trusted/') || github.event.pull_request.head.repo.full_name == 'partner/repo'"}, + } + for _, event := range []string{"pull_request", "pull_request_target"} { + for _, tt := range tests { + t.Run(event+"/"+tt.name, func(t *testing.T) { + names := "" + if event == "pull_request" { + names = "\n names: [community-contribution]" + } + source := fmt.Sprintf(`--- +if: ${{ github.event.repository.fork == false }} +on: + permissions: {} + %s: + types: [labeled] + forks: %s%s + branches: [main] + workflow_dispatch: +engine: copilot +checkout: false +permissions: + contents: read +network: + allowed: [defaults] +--- +Review the contribution. +`, event, tt.forks, names) + compiled := compileTriggerFilterFixture(t, source) + on := compiled["on"].(map[string]any) + assert.Equal(t, map[string]any{"types": []any{"labeled"}, "branches": []any{"main"}}, on[event]) + assert.Contains(t, on, "workflow_dispatch") + jobs := compiled["jobs"].(map[string]any) + condition := jobs["activation"].(map[string]any)["if"].(string) + assert.Contains(t, condition, "github.event.repository.fork == false") + if tt.expected != "" { + assert.Contains(t, condition, "github.event_name != '"+event+"'") + assert.Contains(t, condition, tt.expected) + } else { + assert.NotContains(t, condition, "github.event.pull_request.head.repo") + } + if names != "" { + assert.Contains(t, condition, "github.event.label.name == 'community-contribution'") + } + }) + } + } +} + +func compileTriggerFilterFixture(t *testing.T, source string) map[string]any { + t.Helper() + workflowFile := filepath.Join(testutil.TempDir(t, "trigger-filters"), "filters.md") + require.NoError(t, os.WriteFile(workflowFile, []byte(source), 0644)) + compiler := NewCompiler() + require.NoError(t, compiler.CompileWorkflow(workflowFile)) + content, err := os.ReadFile(filepath.Join(filepath.Dir(workflowFile), "filters.lock.yml")) + require.NoError(t, err) + var compiled map[string]any + require.NoError(t, yaml.Unmarshal(content, &compiled)) + require.NoError(t, compiler.validateGitHubActionsSchemaFromParsed(compiled)) + return compiled +} + func TestApplyPullRequestForkFilter(t *testing.T) { const sameRepo = "github.event_name != 'pull_request' || github.event.pull_request.head.repo.id == github.repository_id" tests := []struct { @@ -47,19 +120,25 @@ func TestApplyPullRequestForkFilter(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - for _, existing := range []string{"", "github.actor != 'dependabot[bot]'"} { - data := &WorkflowData{If: existing} - NewCompiler().applyPullRequestForkFilter(data, map[string]any{ - "on": map[string]any{"pull_request": tt.pr, "push": nil, "workflow_dispatch": nil}, - }) - expected := tt.expected - if existing != "" { - expected = existing - if tt.expected != "" { - expected = "(" + existing + ") && (" + tt.expected + ")" + for _, event := range []string{"pull_request", "pull_request_target"} { + for _, existing := range []string{"", "github.actor != 'dependabot[bot]'"} { + data := &WorkflowData{If: existing} + NewCompiler().applyPullRequestForkFilter(data, map[string]any{ + "on": map[string]any{event: tt.pr, "push": nil, "workflow_dispatch": nil}, + }) + filter := strings.ReplaceAll(tt.expected, "'pull_request'", "'"+event+"'") + if _, hasForks := tt.pr["forks"]; event == "pull_request_target" && !hasForks { + filter = "" + } + expected := filter + if existing != "" { + expected = existing + if filter != "" { + expected = "(" + existing + ") && (" + filter + ")" + } } + assert.Equal(t, expected, data.If, "event: %s", event) } - assert.Equal(t, expected, data.If) } }) } @@ -106,3 +185,17 @@ engine: copilot assert.Contains(t, condition, `|| contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)`) assert.Contains(t, string(content), "github.event.pull_request.base.sha || github.sha") } + +func TestApplyPullRequestForkFilterMultipleEvents(t *testing.T) { + data := &WorkflowData{} + NewCompiler().applyPullRequestForkFilter(data, map[string]any{ + "on": map[string]any{ + "pull_request": map[string]any{"forks": "pr-org/*"}, + "pull_request_target": map[string]any{"forks": "target-org/*"}, + }, + }) + assert.Equal(t, + "(github.event_name != 'pull_request' || github.event.pull_request.head.repo.id == github.repository_id || startsWith(github.event.pull_request.head.repo.full_name, 'pr-org/')) && "+ + "(github.event_name != 'pull_request_target' || github.event.pull_request.head.repo.id == github.repository_id || startsWith(github.event.pull_request.head.repo.full_name, 'target-org/'))", + data.If) +} diff --git a/pkg/workflow/frontmatter_on_section_cleanup.go b/pkg/workflow/frontmatter_on_section_cleanup.go index cf288aebdee..b3ea44df3b0 100644 --- a/pkg/workflow/frontmatter_on_section_cleanup.go +++ b/pkg/workflow/frontmatter_on_section_cleanup.go @@ -20,6 +20,7 @@ func (c *Compiler) commentOutProcessedFieldsInOnSection(yamlStr string, frontmat for _, line := range lines { info := newOnSectionLine(line) + state.leaveSubsections(info) if state.handleEventSectionEntry(info, &result) { continue } @@ -28,7 +29,6 @@ func (c *Compiler) commentOutProcessedFieldsInOnSection(yamlStr string, frontmat continue } state.enterSubsections(info) - state.leaveSubsections(info) shouldComment, commentReason := state.determineComment(info, result, nativeLabelFilterSections) result = state.appendLine(result, info, shouldComment, commentReason) } @@ -63,6 +63,7 @@ type onSectionCleanupState struct { inWorkflowRun bool inWorkflowRunConclusionArray bool inForksArray bool + forksIndent int inSkipIfMatch bool inSkipIfNoMatch bool inSkipIfCheckFailing bool @@ -264,8 +265,9 @@ func (s *onSectionCleanupState) enterSubsections(info onSectionLine) { } func (s *onSectionCleanupState) enterArraySections(info onSectionLine) { - if s.inPullRequest && strings.HasPrefix(info.trimmed, "forks:") { + if (s.inPullRequest || s.inPullRequestTarget) && strings.HasPrefix(info.trimmed, "forks:") { s.inForksArray = true + s.forksIndent = info.indent } if !s.inEventSection() && strings.HasPrefix(info.trimmed, "skip-roles:") { s.inSkipRolesArray = true @@ -340,7 +342,7 @@ func (s *onSectionCleanupState) leaveObjectSections(info onSectionLine) { } func (s *onSectionCleanupState) leaveArraySections(info onSectionLine) { - if s.inForksArray && s.inPullRequest && isLeavingArray(info, "forks:", 4) { + if s.inForksArray && isLeavingArray(info, "forks:", s.forksIndent) { s.inForksArray = false } if s.inSkipRolesArray && isLeavingArray(info, "skip-roles:", 2) { @@ -555,9 +557,9 @@ func (s *onSectionCleanupState) commentPullRequestAndTriggerField(info onSection return true, " # Draft filtering applied via job conditions" case (s.inPullRequest || s.inPullRequestReview) && strings.HasPrefix(info.trimmed, "max-stack:"): return true, " # Stack filtering applied via job conditions" - case s.inPullRequest && strings.HasPrefix(info.trimmed, "forks:"): + case (s.inPullRequest || s.inPullRequestTarget) && strings.HasPrefix(info.trimmed, "forks:"): return true, " # Fork filtering applied via job conditions" - case s.inForksArray && (strings.HasPrefix(info.trimmed, "-") || info.indent > 4): + case s.inForksArray && (strings.HasPrefix(info.trimmed, "-") || info.indent > s.forksIndent): return true, " # Fork filtering applied via job conditions" case s.inDeploymentStatus && strings.HasPrefix(info.trimmed, "state:"): return true, " # State filtering compiled into if condition" diff --git a/pkg/workflow/frontmatter_on_section_cleanup_test.go b/pkg/workflow/frontmatter_on_section_cleanup_test.go index 5c0e739251b..f472eedd555 100644 --- a/pkg/workflow/frontmatter_on_section_cleanup_test.go +++ b/pkg/workflow/frontmatter_on_section_cleanup_test.go @@ -3,10 +3,71 @@ package workflow import ( + "fmt" "strings" "testing" + + "github.com/goccy/go-yaml" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +func TestOnSectionFiltersAfterCompilerOnlyFields(t *testing.T) { + for _, prefix := range []string{ + "permissions: {}", + "permissions:\n contents: read", + "steps:\n - name: setup\n run: echo setup", + "skip-author-associations:\n - BOT", + } { + for _, event := range []string{"pull_request", "pull_request_target"} { + t.Run(prefix+"/"+event, func(t *testing.T) { + input := fmt.Sprintf(`on: + %s + %s: + forks: + - trusted/* + names: + - community-contribution + types: + - labeled + branches: + - main + workflow_dispatch: +`, prefix, event) + result := NewCompiler().commentOutProcessedFieldsInOnSection(input, nil) + var compiled map[string]any + require.NoError(t, yaml.Unmarshal([]byte(result), &compiled)) + on := compiled["on"].(map[string]any) + assert.Equal(t, map[string]any{ + "types": []any{"labeled"}, + "branches": []any{"main"}, + }, on[event]) + assert.Contains(t, on, "workflow_dispatch") + assert.NotContains(t, on, strings.Split(prefix, ":")[0]) + }) + } + } +} + +func TestOnSectionForkFilterFourSpaceIndentation(t *testing.T) { + for _, event := range []string{"pull_request", "pull_request_target"} { + t.Run(event, func(t *testing.T) { + input := fmt.Sprintf(`on: + %s: + forks: + - trusted/* + types: + - labeled +`, event) + result := NewCompiler().commentOutProcessedFieldsInOnSection(input, nil) + var compiled map[string]any + require.NoError(t, yaml.Unmarshal([]byte(result), &compiled)) + on := compiled["on"].(map[string]any) + assert.Equal(t, map[string]any{"types": []any{"labeled"}}, on[event]) + }) + } +} + func TestDedentTrailingOnCommentBlock(t *testing.T) { tests := []struct { name string From 40048946c3667263924badd8570065bed7293c2d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:18:27 +0000 Subject: [PATCH 2/8] docs(adr): add draft ADR-72579 for PR fork filter compilation --- ...ply-fork-filters-to-pull-request-target.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 docs/adr/72579-apply-fork-filters-to-pull-request-target.md diff --git a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md new file mode 100644 index 00000000000..fa5230ac6b3 --- /dev/null +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -0,0 +1,50 @@ +# ADR-72579: Compile Fork Filters for Both PR Events, With an Asymmetric Default + +**Date**: 2026-07-22 +**Status**: Draft +**Deciders**: Unknown (PR #72579) + +--- + +### Context + +gh-aw lets workflow authors write compiler-only filters such as `forks:` and `names:` under `on.pull_request` / `on.pull_request_target`. GitHub Actions does not accept these keys, so the compiler must convert them into job `if:` conditions and comment them out of the generated `on:` block. Two problems showed up. First, the on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) left compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations` only *after* checking for the next event. When one of those fields came before a PR event, `forks`/`names` leaked into the lock file, and `gh aw compile --validate` then rejected it. Second, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) only read `on.pull_request`. An explicit `forks:` under `pull_request_target` was silently ignored and was never turned into an admission check. + +### Decision + +We will handle fork filters the same way for `pull_request` and `pull_request_target`. Each event gets its own job condition, guarded by `github.event_name != '' || ...`, and the processed `forks` field is removed from the trigger for both events. The defaults stay different on purpose: `pull_request` keeps its existing same-repository-only default when `forks` is omitted, while `pull_request_target` gets no fork restriction unless `forks` is set explicitly. We will also fix the cleanup state machine so it leaves compiler-only subsections *before* it detects the next event section. It now records `forks` indentation, which lets it handle multiline lists at any indent. The main driver is correctness: compiled lock files must pass GitHub Actions schema validation, and a fork restriction the author wrote down must never be silently dropped. + +### Alternatives Considered + +#### Alternative 1: Reject `forks:` under `pull_request_target` at schema/compile time + +The compiler could treat `forks` as a `pull_request`-only key and raise an error when it appears under `pull_request_target`. That would also stop the silent drop. It was rejected because the field is documented and useful: authors of `pull_request_target` workflows sometimes want to admit only specific fork owners. An error would take away that control instead of providing it. + +#### Alternative 2: Apply the same same-repository default to `pull_request_target` + +Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. It was rejected because it would quietly change the behavior of existing `pull_request_target` workflows. Many of them exist specifically to handle fork PRs, so recompiling would stop them from running on forks. The asymmetric default keeps existing behavior unless the author opts in. + +#### Alternative 3: Fix only the cleanup leak and keep `pull_request`-only fork filtering + +A narrower bug fix would remove the leaked keys and leave admission logic alone. It was rejected because removing `forks` from `pull_request_target` without compiling it into a condition would make the silent drop permanent. The author would get a lock file that looks valid but does not enforce the restriction they configured. + +### Consequences + +#### Positive +- Lock files no longer contain `forks`/`names` trigger properties, so `compile --validate` succeeds regardless of where compiler-only `on.*` fields appear. +- An explicit `forks:` pattern under `pull_request_target` is now enforced as an event-scoped job condition instead of being ignored. +- Event-scoped guards let workflows that set both PR events use independent fork filters, and existing `if:` and label (`names`) conditions are kept. + +#### Negative +- The two PR events now have different defaults for an omitted `forks`, so authors must remember that only `pull_request` blocks forks by default. +- Recompiling workflows that already had a `forks:` key under `pull_request_target` will start enforcing it. This could stop runs that previously, and unintentionally, admitted all forks. +- The line-oriented cleanup state machine depends on event-ordering logic and indent tracking, which remain fragile compared with editing the YAML AST. + +#### Neutral +- Documentation (`docs/src/content/docs/reference/triggers.md`) now describes the `pull_request_target` semantics explicitly. +- Regression tests cover wildcard, empty, exact, multiline, and mixed patterns, with both two-space and four-space indentation. +- This builds on the fork-admission model in [ADR-69374](69374-fork-pr-admission-by-author-association.md). Whether the author-association object form applies to `pull_request_target` is [TODO: verify]. + +--- + +*ADR created by [adr-writer agent]. Review and finalize before changing status from Draft to Accepted.* From ffd196651df6254b90dc6faea6386dc18ef1d2b6 Mon Sep 17 00:00:00 2001 From: pelikhan Date: Tue, 27 Oct 2026 22:23:40 -0700 Subject: [PATCH 3/8] docs(adr): finalize PR fork filter compilation decision Document preserved event defaults and confirm that author-association objects remain supported only for pull_request. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...ply-fork-filters-to-pull-request-target.md | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md index fa5230ac6b3..497bb049767 100644 --- a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -1,18 +1,18 @@ # ADR-72579: Compile Fork Filters for Both PR Events, With an Asymmetric Default -**Date**: 2026-07-22 -**Status**: Draft +**Date**: 2026-10-27 +**Status**: Proposed **Deciders**: Unknown (PR #72579) --- ### Context -gh-aw lets workflow authors write compiler-only filters such as `forks:` and `names:` under `on.pull_request` / `on.pull_request_target`. GitHub Actions does not accept these keys, so the compiler must convert them into job `if:` conditions and comment them out of the generated `on:` block. Two problems showed up. First, the on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) left compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations` only *after* checking for the next event. When one of those fields came before a PR event, `forks`/`names` leaked into the lock file, and `gh aw compile --validate` then rejected it. Second, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) only read `on.pull_request`. An explicit `forks:` under `pull_request_target` was silently ignored and was never turned into an admission check. +gh-aw supports compiler-only `forks:` filters under both PR events and label-name filters (`names:`) under `on.pull_request`; these belong in job conditions, not native GitHub Actions trigger properties. The on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) checked for the next event before leaving compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations`, so filters after those fields could leak into lock files and fail Actions schema validation. Separately, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) read only `on.pull_request`, silently ignoring explicit `pull_request_target.forks` restrictions. Correct compilation must enforce configured fork admission without changing the existing behavior of workflows that omit the field. ### Decision -We will handle fork filters the same way for `pull_request` and `pull_request_target`. Each event gets its own job condition, guarded by `github.event_name != '' || ...`, and the processed `forks` field is removed from the trigger for both events. The defaults stay different on purpose: `pull_request` keeps its existing same-repository-only default when `forks` is omitted, while `pull_request_target` gets no fork restriction unless `forks` is set explicitly. We will also fix the cleanup state machine so it leaves compiler-only subsections *before* it detects the next event section. It now records `forks` indentation, which lets it handle multiline lists at any indent. The main driver is correctness: compiled lock files must pass GitHub Actions schema validation, and a fork restriction the author wrote down must never be silently dropped. +The compiler will apply explicit fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. For configured event objects, omitting `forks` retains the same-repository-only default for `pull_request` and adds no fork restriction for `pull_request_target`; explicit patterns always admit same-repository PRs, `[]` admits only those PRs, and `*` adds no fork restriction. The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.json` accepts string and list patterns for both events, but accepts the `forks: {author-association: [...]}` form from [ADR-69374](69374-fork-pr-admission-by-author-association.md) only for `pull_request`; the shared helper's ability to process that object does not make it supported for `pull_request_target`, and this decision does not extend the schema. To produce valid lock files without silently dropping configured admission rules, the cleanup state machine will leave compiler-only subsections before detecting the next event and track `forks` indentation for nested content, including the supported two-space and four-space event layouts. ### Alternatives Considered @@ -22,7 +22,7 @@ The compiler could treat `forks` as a `pull_request`-only key and raise an error #### Alternative 2: Apply the same same-repository default to `pull_request_target` -Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. It was rejected because it would quietly change the behavior of existing `pull_request_target` workflows. Many of them exist specifically to handle fork PRs, so recompiling would stop them from running on forks. The asymmetric default keeps existing behavior unless the author opts in. +Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. It was rejected because it would change the behavior of existing `pull_request_target` workflows that admit fork PRs, even when their authors had not configured a fork restriction. The asymmetric default preserves existing fork-admission behavior unless the author opts in. #### Alternative 3: Fix only the cleanup leak and keep `pull_request`-only fork filtering @@ -31,7 +31,7 @@ A narrower bug fix would remove the leaked keys and leave admission logic alone. ### Consequences #### Positive -- Lock files no longer contain `forks`/`names` trigger properties, so `compile --validate` succeeds regardless of where compiler-only `on.*` fields appear. +- Recognizing PR events after compiler-only `on.*` fields prevents `forks`/`names` from leaking into native triggers and failing Actions schema validation. - An explicit `forks:` pattern under `pull_request_target` is now enforced as an event-scoped job condition instead of being ignored. - Event-scoped guards let workflows that set both PR events use independent fork filters, and existing `if:` and label (`names`) conditions are kept. @@ -39,12 +39,9 @@ A narrower bug fix would remove the leaked keys and leave admission logic alone. - The two PR events now have different defaults for an omitted `forks`, so authors must remember that only `pull_request` blocks forks by default. - Recompiling workflows that already had a `forks:` key under `pull_request_target` will start enforcing it. This could stop runs that previously, and unintentionally, admitted all forks. - The line-oriented cleanup state machine depends on event-ordering logic and indent tracking, which remain fragile compared with editing the YAML AST. +- The author-association object form remains unavailable for `pull_request_target`, despite the shared helper accepting it internally. #### Neutral -- Documentation (`docs/src/content/docs/reference/triggers.md`) now describes the `pull_request_target` semantics explicitly. -- Regression tests cover wildcard, empty, exact, multiline, and mixed patterns, with both two-space and four-space indentation. -- This builds on the fork-admission model in [ADR-69374](69374-fork-pr-admission-by-author-association.md). Whether the author-association object form applies to `pull_request_target` is [TODO: verify]. - ---- - -*ADR created by [adr-writer agent]. Review and finalize before changing status from Draft to Accepted.* +- The [trigger reference](../src/content/docs/reference/triggers.md) describes the `pull_request_target` pattern-filter semantics explicitly. +- Regression tests in `pkg/workflow/filters_forks_test.go` and `pkg/workflow/frontmatter_on_section_cleanup_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, and two-space/four-space event indentation. +- Fork admission does not grant permissions or secrets and does not make checking out or executing untrusted fork code safe. From eb0e9ea66d71f00918e42069abe2d50b7d5afb7c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:07:47 +0000 Subject: [PATCH 4/8] fix(ci): update x/net and grant Windows probe checks access Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- .github/workflows/windows-grower.lock.yml | 7 ++++--- .github/workflows/windows-grower.md | 1 + go.mod | 2 +- go.sum | 4 ++-- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/windows-grower.lock.yml b/.github/workflows/windows-grower.lock.yml index 52d0d344929..826a1012c2c 100644 --- a/.github/workflows/windows-grower.lock.yml +++ b/.github/workflows/windows-grower.lock.yml @@ -1,4 +1,4 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"af0497176404fb4f291649715c481aa2e9389ae33e8e0b388dff069593a6233c","body_hash":"d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd","strict":true,"agent_id":"codex","agent_model":"openai/gpt-5.6-terra","engine_versions":{"codex":"0.164.0"}} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"c53e25b44bc2a33ba784791814f94fe18f68acc6c6541cb34321b0fe5b3b17f9","body_hash":"d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd","strict":true,"agent_id":"codex","agent_model":"openai/gpt-5.6-terra","engine_versions":{"codex":"0.164.0"}} # gh-aw-manifest: {"version":1,"secrets":["CODEX_API_KEY","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN","OPENAI_API_KEY"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.0","digest":"sha256:b14bd399376180b5649a9324be3b50fbfc82bfe8f0c80045840416b5a4e65b96","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.29.0@sha256:b14bd399376180b5649a9324be3b50fbfc82bfe8f0c80045840416b5a4e65b96"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.0","digest":"sha256:baff00b856a4bdc93bce134928c70af3d3492f2e518757115042040674d56b0b","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.0@sha256:baff00b856a4bdc93bce134928c70af3d3492f2e518757115042040674d56b0b"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.0","digest":"sha256:087a8e4efff8ac62d46e106cd22005c002822b1481fc233097799511be353b5d","pinned_image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.0@sha256:087a8e4efff8ac62d46e106cd22005c002822b1481fc233097799511be353b5d"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.0","digest":"sha256:6e0cbf7f980beb78b5461563a8164f6439ca959bc93733d5a6b52972e523ed50","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.29.0@sha256:6e0cbf7f980beb78b5461563a8164f6439ca959bc93733d5a6b52972e523ed50"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.0","digest":"sha256:d3544a4222e7efeeeb38669d8a1af0c72691c55b8f6506b15aa5920f7f31b7bc","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.0@sha256:d3544a4222e7efeeeb38669d8a1af0c72691c55b8f6506b15aa5920f7f31b7bc"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:2c2ea524e648b91c8333ce246e3838fcf5b19ac70e45baac1a51b9207299749f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:2c2ea524e648b91c8333ce246e3838fcf5b19ac70e45baac1a51b9207299749f"},{"image":"ghcr.io/github/github-mcp-server:v2.0.3","digest":"sha256:250bc6ce70788207608ef74cef4397230ff2e8481218da74d6093e4bd9101132","pinned_image":"ghcr.io/github/github-mcp-server:v2.0.3@sha256:250bc6ce70788207608ef74cef4397230ff2e8481218da74d6093e4bd9101132"}],"mcp_servers":[{"name":"safeoutputs","tools":["create_issue","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":true} # This file was automatically generated by gh-aw. DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # @@ -478,7 +478,7 @@ jobs: GH_AW_DEFAULT_ADMISSION_URL: ${{ vars.GH_AW_DEFAULT_ADMISSION_URL }} GH_AW_DEFAULT_ADMISSION_AUDIENCE: ${{ vars.GH_AW_DEFAULT_ADMISSION_AUDIENCE }} GH_AW_DEFAULT_ADMISSION_ON_OUTAGE: ${{ vars.GH_AW_DEFAULT_ADMISSION_ON_OUTAGE }} - GH_AW_ADMISSION_WORKFLOW_HASH: "af0497176404fb4f291649715c481aa2e9389ae33e8e0b388dff069593a6233c:d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd" + GH_AW_ADMISSION_WORKFLOW_HASH: "c53e25b44bc2a33ba784791814f94fe18f68acc6c6541cb34321b0fe5b3b17f9:d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GITHUB_ACTOR: ${{ github.actor }} GITHUB_TRIGGERING_ACTOR: ${{ github.triggering_actor }} @@ -1764,7 +1764,7 @@ jobs: GH_AW_DEFAULT_ADMISSION_URL: ${{ vars.GH_AW_DEFAULT_ADMISSION_URL }} GH_AW_DEFAULT_ADMISSION_AUDIENCE: ${{ vars.GH_AW_DEFAULT_ADMISSION_AUDIENCE }} GH_AW_DEFAULT_ADMISSION_ON_OUTAGE: ${{ vars.GH_AW_DEFAULT_ADMISSION_ON_OUTAGE }} - GH_AW_ADMISSION_WORKFLOW_HASH: "af0497176404fb4f291649715c481aa2e9389ae33e8e0b388dff069593a6233c:d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd" + GH_AW_ADMISSION_WORKFLOW_HASH: "c53e25b44bc2a33ba784791814f94fe18f68acc6c6541cb34321b0fe5b3b17f9:d56c86ad2ec27d707218d2837589b524ccdc3e56b9f39fb8325347cc8924e5fd" GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }} GITHUB_ACTOR: ${{ github.actor }} GITHUB_TRIGGERING_ACTOR: ${{ github.triggering_actor }} @@ -2415,6 +2415,7 @@ jobs: # Reusable callers must grant the union of the callee's job permissions. permissions: actions: read + checks: read contents: read copilot-requests: write discussions: write diff --git a/.github/workflows/windows-grower.md b/.github/workflows/windows-grower.md index 049896b3a98..78334126f2f 100644 --- a/.github/workflows/windows-grower.md +++ b/.github/workflows/windows-grower.md @@ -33,6 +33,7 @@ jobs: # Reusable callers must grant the union of the callee's job permissions. permissions: actions: read + checks: read contents: read copilot-requests: write discussions: write diff --git a/go.mod b/go.mod index 5301f7edb40..943d586620c 100644 --- a/go.mod +++ b/go.mod @@ -33,7 +33,7 @@ require ( // .golangci.yml. golang.org/x/crypto v0.58.0 golang.org/x/mod v0.42.0 - golang.org/x/net v0.61.0 + golang.org/x/net v0.62.0 golang.org/x/sync v0.24.0 golang.org/x/term v0.47.0 golang.org/x/tools v0.52.0 diff --git a/go.sum b/go.sum index f949e7a22de..377fda3a589 100644 --- a/go.sum +++ b/go.sum @@ -244,8 +244,8 @@ golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWB golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= -golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= -golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= From 7edd984db3d90e41210633595c50e469ce8558b0 Mon Sep 17 00:00:00 2001 From: pelikhan Date: Wed, 28 Oct 2026 03:54:12 -0700 Subject: [PATCH 5/8] fix(workflow): handle indented trigger subsections and clarify filter validation Track subsection indentation, cover schema rejection of malformed fork and unsupported target label filters, and correct the generated target fork-filter reference. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../docs/reference/frontmatter-full.md | 8 ++- pkg/parser/schemas/main_workflow_schema.json | 2 +- pkg/workflow/filters_forks_test.go | 66 +++++++++++++++++++ .../frontmatter_on_section_cleanup.go | 24 ++++--- .../frontmatter_on_section_cleanup_test.go | 64 +++++++++++------- 5 files changed, 127 insertions(+), 37 deletions(-) diff --git a/docs/src/content/docs/reference/frontmatter-full.md b/docs/src/content/docs/reference/frontmatter-full.md index d8355aaffde..f09963f4adb 100644 --- a/docs/src/content/docs/reference/frontmatter-full.md +++ b/docs/src/content/docs/reference/frontmatter-full.md @@ -793,9 +793,11 @@ on: # (optional) draft: true - # When true, allows workflow to run on pull requests from forked repositories with - # write permissions. Security consideration: use cautiously as fork PRs run with - # base repository permissions. + # Filter fork pull requests by repository pattern (string or list). + # Same-repository PRs remain allowed; an empty list allows only same-repository + # PRs, and '*' allows all forks. Omitting this field adds no fork restriction. + # This does not change GitHub's base-repository permissions or secret availability + # for pull_request_target. # (optional) # Accepted formats: diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index e6bc1ce3768..b0c7afe3a4d 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -2044,7 +2044,7 @@ } } ], - "description": "When true, allows workflow to run on pull requests from forked repositories with write permissions. Security consideration: use cautiously as fork PRs run with base repository permissions." + "description": "Filter fork pull requests by repository pattern (string or list). Same-repository PRs remain allowed; an empty list allows only same-repository PRs, and '*' allows all forks. Omitting this field adds no fork restriction. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." }, "acknowledge-risk": { "type": "boolean", diff --git a/pkg/workflow/filters_forks_test.go b/pkg/workflow/filters_forks_test.go index a32c1e585ed..6f91c0297df 100644 --- a/pkg/workflow/filters_forks_test.go +++ b/pkg/workflow/filters_forks_test.go @@ -21,6 +21,7 @@ func TestTriggerForkFilterCompilation(t *testing.T) { forks string expected string }{ + {"wildcard string", `"*"`, ""}, {"wildcard", `["*"]`, ""}, {"empty", "[]", "github.event.pull_request.head.repo.id == github.repository_id"}, {"exact", `"trusted/repo"`, "github.event.pull_request.head.repo.full_name == 'trusted/repo'"}, @@ -72,6 +73,71 @@ Review the contribution. } } +func TestTriggerForkFilterCompilationRejectsMalformedValues(t *testing.T) { + tests := []struct { + name string + forks string + }{ + {"boolean true", "true"}, + {"boolean false", "false"}, + {"number", "42"}, + {"null", "null"}, + {"empty object", "{}"}, + {"non-string list item", "[trusted/repo, true]"}, + } + for _, event := range []string{"pull_request", "pull_request_target"} { + for _, tt := range tests { + t.Run(event+"/"+tt.name, func(t *testing.T) { + assertTriggerFilterCompilationRejected(t, event, "forks: "+tt.forks, "forks") + }) + } + } +} + +func TestPullRequestTargetCompilationRejectsUnsupportedFilters(t *testing.T) { + tests := []struct { + name string + filter string + field string + }{ + {"author associations", "forks: {author-association: [OWNER, MEMBER, COLLABORATOR]}", "forks"}, + {"label string", "names: community-contribution", "names"}, + {"label list", "names: [community-contribution]", "names"}, + {"label boolean", "names: true", "names"}, + {"label number", "names: 42", "names"}, + {"label object", "names: {label: community-contribution}", "names"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertTriggerFilterCompilationRejected(t, "pull_request_target", tt.filter, tt.field) + }) + } +} + +func assertTriggerFilterCompilationRejected(t *testing.T, event, filter, field string) { + t.Helper() + workflowFile := filepath.Join(testutil.TempDir(t, "invalid-trigger-filters"), "filters.md") + source := fmt.Sprintf(`--- +on: + %s: + types: [labeled] + %s +engine: copilot +checkout: false +permissions: + contents: read +network: + allowed: [defaults] +--- +Review the contribution. +`, event, filter) + require.NoError(t, os.WriteFile(workflowFile, []byte(source), 0644)) + err := NewCompiler().CompileWorkflow(workflowFile) + require.Error(t, err) + assert.Contains(t, err.Error(), field) + assert.NoFileExists(t, filepath.Join(filepath.Dir(workflowFile), "filters.lock.yml")) +} + func compileTriggerFilterFixture(t *testing.T, source string) map[string]any { t.Helper() workflowFile := filepath.Join(testutil.TempDir(t, "trigger-filters"), "filters.md") diff --git a/pkg/workflow/frontmatter_on_section_cleanup.go b/pkg/workflow/frontmatter_on_section_cleanup.go index b3ea44df3b0..2e54459dbcf 100644 --- a/pkg/workflow/frontmatter_on_section_cleanup.go +++ b/pkg/workflow/frontmatter_on_section_cleanup.go @@ -68,6 +68,7 @@ type onSectionCleanupState struct { inSkipIfNoMatch bool inSkipIfCheckFailing bool inSkipAuthorAssociations bool + skipAuthorAssociationsIndent int inSkipRolesArray bool inSkipBotsArray bool inRolesArray bool @@ -78,7 +79,9 @@ type onSectionCleanupState struct { allowedCheckoutsIndent int inGitHubApp bool inOnSteps bool + onStepsIndent int inOnPermissions bool + onPermissionsIndent int commentBlockIndent string inCommentBlock bool currentSection string @@ -289,9 +292,11 @@ func (s *onSectionCleanupState) enterArraySections(info onSectionLine) { } if !s.inEventSection() && strings.HasPrefix(info.trimmed, "steps:") { s.inOnSteps = true + s.onStepsIndent = info.indent } if !s.inEventSection() && !s.inOnPermissions && strings.HasPrefix(info.trimmed, "permissions:") { s.inOnPermissions = true + s.onPermissionsIndent = info.indent } } @@ -310,6 +315,7 @@ func (s *onSectionCleanupState) enterObjectSections(info onSectionLine) { } if !s.inEventSection() && !s.inSkipAuthorAssociations && strings.HasPrefix(info.trimmed, "skip-author-associations:") && info.trimmed == "skip-author-associations:" { s.inSkipAuthorAssociations = true + s.skipAuthorAssociationsIndent = info.indent } if !s.inEventSection() && !s.inGitHubApp && ((strings.HasPrefix(info.trimmed, "github-app:") && info.trimmed == "github-app:") || (strings.HasPrefix(info.trimmed, "# github-app:") && strings.Contains(info.trimmed, "pre-activation job"))) { @@ -324,19 +330,19 @@ func (s *onSectionCleanupState) leaveSubsections(info onSectionLine) { } func (s *onSectionCleanupState) leaveObjectSections(info onSectionLine) { - if s.inSkipIfMatch && isLeavingTopLevelObject(info, "skip-if-match:", "# skip-if-match:") { + if s.inSkipIfMatch && isLeavingTopLevelObject(info, "skip-if-match:", "# skip-if-match:", 2) { s.inSkipIfMatch = false } - if s.inSkipIfNoMatch && isLeavingTopLevelObject(info, "skip-if-no-match:", "# skip-if-no-match:") { + if s.inSkipIfNoMatch && isLeavingTopLevelObject(info, "skip-if-no-match:", "# skip-if-no-match:", 2) { s.inSkipIfNoMatch = false } - if s.inSkipIfCheckFailing && isLeavingTopLevelObject(info, "skip-if-check-failing:", "# skip-if-check-failing:") { + if s.inSkipIfCheckFailing && isLeavingTopLevelObject(info, "skip-if-check-failing:", "# skip-if-check-failing:", 2) { s.inSkipIfCheckFailing = false } - if s.inSkipAuthorAssociations && isLeavingTopLevelObject(info, "skip-author-associations:", "# skip-author-associations:") { + if s.inSkipAuthorAssociations && isLeavingTopLevelObject(info, "skip-author-associations:", "# skip-author-associations:", s.skipAuthorAssociationsIndent) { s.inSkipAuthorAssociations = false } - if s.inGitHubApp && isLeavingTopLevelObject(info, "github-app:", "# github-app:") { + if s.inGitHubApp && isLeavingTopLevelObject(info, "github-app:", "# github-app:", 2) { s.inGitHubApp = false } } @@ -366,19 +372,19 @@ func (s *onSectionCleanupState) leaveArraySections(info onSectionLine) { } func (s *onSectionCleanupState) leaveStepsAndPermissions(info onSectionLine) { - if s.inOnSteps && isLeavingArray(info, "steps:", 2) { + if s.inOnSteps && isLeavingArray(info, "steps:", s.onStepsIndent) { s.inOnSteps = false } - if s.inOnPermissions && isLeavingTopLevelObject(info, "permissions:", "# permissions:") { + if s.inOnPermissions && isLeavingTopLevelObject(info, "permissions:", "# permissions:", s.onPermissionsIndent) { s.inOnPermissions = false } } -func isLeavingTopLevelObject(info onSectionLine, key, commentedKey string) bool { +func isLeavingTopLevelObject(info onSectionLine, key, commentedKey string, indent int) bool { return info.trimmed != "" && !strings.HasPrefix(info.trimmed, key) && !strings.HasPrefix(info.trimmed, commentedKey) && - info.indent == 2 && + info.indent == indent && !strings.HasPrefix(info.trimmed, "#") } diff --git a/pkg/workflow/frontmatter_on_section_cleanup_test.go b/pkg/workflow/frontmatter_on_section_cleanup_test.go index f472eedd555..9dc5e8562ab 100644 --- a/pkg/workflow/frontmatter_on_section_cleanup_test.go +++ b/pkg/workflow/frontmatter_on_section_cleanup_test.go @@ -13,38 +13,54 @@ import ( ) func TestOnSectionFiltersAfterCompilerOnlyFields(t *testing.T) { - for _, prefix := range []string{ - "permissions: {}", - "permissions:\n contents: read", - "steps:\n - name: setup\n run: echo setup", - "skip-author-associations:\n - BOT", - } { - for _, event := range []string{"pull_request", "pull_request_target"} { - t.Run(prefix+"/"+event, func(t *testing.T) { - input := fmt.Sprintf(`on: + for _, indent := range []int{2, 4} { + for _, prefix := range []string{ + "permissions: {}", + "permissions:\n contents: read", + "steps:\n - name: setup\n run: echo setup", + "skip-author-associations:\n - BOT", + } { + for _, event := range []string{"pull_request", "pull_request_target"} { + t.Run(fmt.Sprintf("indent-%d/%s/%s", indent, prefix, event), func(t *testing.T) { + names := "" + if event == "pull_request" { + names = " names:\n - community-contribution\n" + } + input := fmt.Sprintf(`on: %s %s: forks: - trusted/* - names: - - community-contribution - types: +%s types: - labeled branches: - main + paths: + - src/** workflow_dispatch: -`, prefix, event) - result := NewCompiler().commentOutProcessedFieldsInOnSection(input, nil) - var compiled map[string]any - require.NoError(t, yaml.Unmarshal([]byte(result), &compiled)) - on := compiled["on"].(map[string]any) - assert.Equal(t, map[string]any{ - "types": []any{"labeled"}, - "branches": []any{"main"}, - }, on[event]) - assert.Contains(t, on, "workflow_dispatch") - assert.NotContains(t, on, strings.Split(prefix, ":")[0]) - }) +`, prefix, event, names) + if indent == 4 { + lines := strings.Split(input, "\n") + for i, line := range lines { + lineIndent := newOnSectionLine(line).indent + lines[i] = strings.Repeat(" ", lineIndent) + line + } + input = strings.Join(lines, "\n") + } + result := NewCompiler().commentOutProcessedFieldsInOnSection(input, nil) + var compiled map[string]any + require.NoError(t, yaml.Unmarshal([]byte(result), &compiled)) + on, ok := compiled["on"].(map[string]any) + require.True(t, ok, "on must retain its native events:\n%s", result) + assert.Equal(t, map[string]any{ + "types": []any{"labeled"}, + "branches": []any{"main"}, + "paths": []any{"src/**"}, + }, on[event]) + assert.Contains(t, on, "workflow_dispatch") + assert.NotContains(t, on, strings.Split(prefix, ":")[0]) + }) + } } } } From 63bc0aed838da26b2c87e0a6fcca27e75f3c3150 Mon Sep 17 00:00:00 2001 From: pelikhan Date: Wed, 28 Oct 2026 04:23:32 -0700 Subject: [PATCH 6/8] Require bounded fork admission for strict pull_request_target workflows Reject omitted and unrestricted target fork filters before checkout exemptions. Preserve non-strict behavior, actor authorization, and checkout restrictions, and document the strict-mode migration. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...trict-pull-request-target-bounded-forks.md | 7 + CHANGELOG.md | 8 ++ ...ply-fork-filters-to-pull-request-target.md | 18 ++- docs/src/content/docs/reference/checkout.md | 4 +- .../docs/reference/frontmatter-full.md | 17 ++- docs/src/content/docs/reference/triggers.md | 5 +- pkg/parser/schemas/main_workflow_schema.json | 4 +- pkg/workflow/concurrency_command_test.go | 2 +- pkg/workflow/filters_forks_test.go | 6 +- .../pr_ready_for_review_checkout_test.go | 1 + .../pull_request_target_forks_test.go | 126 ++++++++++++++++++ .../pull_request_target_validation.go | 49 ++++++- .../pull_request_target_validation_test.go | 15 +++ 13 files changed, 236 insertions(+), 26 deletions(-) create mode 100644 .changeset/strict-pull-request-target-bounded-forks.md create mode 100644 pkg/workflow/pull_request_target_forks_test.go diff --git a/.changeset/strict-pull-request-target-bounded-forks.md b/.changeset/strict-pull-request-target-bounded-forks.md new file mode 100644 index 00000000000..f455798f799 --- /dev/null +++ b/.changeset/strict-pull-request-target-bounded-forks.md @@ -0,0 +1,7 @@ +--- +"gh-aw": major +--- + +Require explicit bounded fork admission for `pull_request_target` in strict mode. + +Migration: replace omitted `on.pull_request_target.forks` or any `"*"` entry with `forks: []` for same-repository PRs only, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns, then recompile. Expressions and other wildcard patterns are rejected. Actor authorization and trusted-checkout restrictions remain mandatory; `acknowledge-risk`, `checkout: false`, and trusted checkouts do not bypass fork admission. Non-strict behavior is unchanged. diff --git a/CHANGELOG.md b/CHANGELOG.md index bf685e51a6f..e4855b14c37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ and mixed edits continue to require write-or-higher repository permission. ### Breaking changes +Strict-mode `pull_request_target` workflows now require explicit bounded fork +admission. Replace omitted `forks` or any `"*"` entry with `forks: []` for +same-repository PRs only, exact `owner/repo` entries, or deliberately trusted +`owner/*` patterns, then recompile. Expressions and other wildcard patterns are +rejected. Actor authorization and trusted-checkout restrictions remain mandatory; +`acknowledge-risk`, disabled checkout, and trusted checkout policies do not bypass +fork admission. Non-strict compilation retains its existing behavior. + The `gh aw outcomes` command has been removed. Use `gh aw logs --outcomes` to evaluate selected runs, or pipe a run ID to `gh aw logs --stdin --repo owner/repo --outcomes`. JSON reports now carry diff --git a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md index 497bb049767..007f9dc93eb 100644 --- a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -1,4 +1,4 @@ -# ADR-72579: Compile Fork Filters for Both PR Events, With an Asymmetric Default +# ADR-72579: Compile PR Fork Filters and Require Bounded Target Admission **Date**: 2026-10-27 **Status**: Proposed @@ -8,11 +8,15 @@ ### Context -gh-aw supports compiler-only `forks:` filters under both PR events and label-name filters (`names:`) under `on.pull_request`; these belong in job conditions, not native GitHub Actions trigger properties. The on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) checked for the next event before leaving compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations`, so filters after those fields could leak into lock files and fail Actions schema validation. Separately, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) read only `on.pull_request`, silently ignoring explicit `pull_request_target.forks` restrictions. Correct compilation must enforce configured fork admission without changing the existing behavior of workflows that omit the field. +gh-aw supports compiler-only `forks:` filters under both PR events and label-name filters (`names:`) under `on.pull_request`; these belong in job conditions, not native GitHub Actions trigger properties. The on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) checked for the next event before leaving compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations`, so filters after those fields could leak into lock files and fail Actions schema validation. Separately, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) read only `on.pull_request`, silently ignoring explicit `pull_request_target.forks` restrictions. + +Security review also identified that omitted target fork filters and `"*"` both admit arbitrary forks. Trusted actor authorization is insufficient: a maintainer can label an attacker-controlled PR, and an agent can consume malicious PR content with privileged capabilities even when checkout is disabled. Strict mode therefore needs explicit bounded admission, independently of actor authorization, checkout policy, and risk acknowledgment. ### Decision -The compiler will apply explicit fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. For configured event objects, omitting `forks` retains the same-repository-only default for `pull_request` and adds no fork restriction for `pull_request_target`; explicit patterns always admit same-repository PRs, `[]` admits only those PRs, and `*` adds no fork restriction. The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.json` accepts string and list patterns for both events, but accepts the `forks: {author-association: [...]}` form from [ADR-69374](69374-fork-pr-admission-by-author-association.md) only for `pull_request`; the shared helper's ability to process that object does not make it supported for `pull_request_target`, and this decision does not extend the schema. To produce valid lock files without silently dropping configured admission rules, the cleanup state machine will leave compiler-only subsections before detecting the next event and track `forks` indentation for nested content, including the supported two-space and four-space event layouts. +The compiler will apply explicit fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. Explicit patterns always admit same-repository PRs, and `[]` admits only those PRs. Strict-mode `pull_request_target` requires `forks: []`, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns. Omission, `"*"` anywhere in a list, expressions, and other wildcard patterns are rejected before checkout exemptions. Neither `acknowledge-risk` nor trusted/disabled checkout bypasses admission; actor authorization and checkout restrictions remain mandatory. Non-strict mode retains unrestricted target admission for omission or `"*"`. The same-repository default for configured `pull_request` event objects is unchanged. + +The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.json` accepts string and list patterns for both events, but accepts the `forks: {author-association: [...]}` form from [ADR-69374](69374-fork-pr-admission-by-author-association.md) only for `pull_request`; the shared helper's ability to process that object does not make it supported for `pull_request_target`, and this decision does not extend the schema. To produce valid lock files without silently dropping configured admission rules, the cleanup state machine will leave compiler-only subsections before detecting the next event and track `forks` indentation for nested content, including the supported two-space and four-space event layouts. ### Alternatives Considered @@ -22,7 +26,7 @@ The compiler could treat `forks` as a `pull_request`-only key and raise an error #### Alternative 2: Apply the same same-repository default to `pull_request_target` -Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. It was rejected because it would change the behavior of existing `pull_request_target` workflows that admit fork PRs, even when their authors had not configured a fork restriction. The asymmetric default preserves existing fork-admission behavior unless the author opts in. +Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. Strict target compilation instead rejects omission and requires maintainers to state the intended trust boundary explicitly. Non-strict mode retains its asymmetric defaults for compatibility. #### Alternative 3: Fix only the cleanup leak and keep `pull_request`-only fork filtering @@ -34,14 +38,16 @@ A narrower bug fix would remove the leaked keys and leave admission logic alone. - Recognizing PR events after compiler-only `on.*` fields prevents `forks`/`names` from leaking into native triggers and failing Actions schema validation. - An explicit `forks:` pattern under `pull_request_target` is now enforced as an event-scoped job condition instead of being ignored. - Event-scoped guards let workflows that set both PR events use independent fork filters, and existing `if:` and label (`names`) conditions are kept. +- Strict-mode target workflows cannot silently admit arbitrary forks, including through risk acknowledgment or checkout exemptions. #### Negative -- The two PR events now have different defaults for an omitted `forks`, so authors must remember that only `pull_request` blocks forks by default. +- Existing strict-mode target workflows with omitted or unrestricted fork admission must migrate to explicit bounded admission and recompile. This is documented as a breaking change. +- Non-strict mode retains different defaults for the two PR events. - Recompiling workflows that already had a `forks:` key under `pull_request_target` will start enforcing it. This could stop runs that previously, and unintentionally, admitted all forks. - The line-oriented cleanup state machine depends on event-ordering logic and indent tracking, which remain fragile compared with editing the YAML AST. - The author-association object form remains unavailable for `pull_request_target`, despite the shared helper accepting it internally. #### Neutral - The [trigger reference](../src/content/docs/reference/triggers.md) describes the `pull_request_target` pattern-filter semantics explicitly. -- Regression tests in `pkg/workflow/filters_forks_test.go` and `pkg/workflow/frontmatter_on_section_cleanup_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, and two-space/four-space event indentation. +- Regression tests in `pkg/workflow/filters_forks_test.go`, `pkg/workflow/frontmatter_on_section_cleanup_test.go`, and `pkg/workflow/pull_request_target_forks_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, indentation, strict bounded admission, and non-strict compatibility. - Fork admission does not grant permissions or secrets and does not make checking out or executing untrusted fork code safe. diff --git a/docs/src/content/docs/reference/checkout.md b/docs/src/content/docs/reference/checkout.md index f312d31b82b..f1c8ac52108 100644 --- a/docs/src/content/docs/reference/checkout.md +++ b/docs/src/content/docs/reference/checkout.md @@ -247,6 +247,7 @@ To check out a trusted ref such as the base SHA, opt in explicitly with a `check on: pull_request_target: types: [opened, synchronize] + forks: [] # Same-repository PRs only checkout: repository: ${{ github.repository }} ref: ${{ github.event.pull_request.base.sha }} @@ -263,6 +264,7 @@ on: pull_request_target: types: [closed] branches: [main] + forks: ["dotnet/*"] acknowledge-risk: true allowed-checkouts: - repository: dotnet/AspNetCore.Docs @@ -278,7 +280,7 @@ checkout: `on.pull_request_target.allowed-checkouts` defaults to no additional trusted checkouts. Each entry requires a literal `owner/repository` and a non-empty literal branch, tag, or commit SHA. Matching is exact and case-sensitive; repository/ref pairs cannot be combined across entries. Expressions, wildcards, and `refs/pull/...` refs are rejected in the policy. Every configured checkout must independently satisfy the policy or the existing base-checkout rules. Do not configure `checkout.fetch` for these checkouts: follow-up fetches can add refs beyond the trusted checkout, so they do not satisfy the policy. External repositories with omitted or PR-dependent refs remain rejected. Wiki checkouts are not covered by this allowlist. -`on.pull_request_target.acknowledge-risk` defaults to `false`. Setting it to `true` suppresses **only** the strict-mode dangerous-trigger warning, including for `checkout: false` or a supported base checkout. It neither allows other checkouts nor disables unrelated warnings, strict validation, or safe-update checks. An allowlist without acknowledgment still emits the trigger warning. +`on.pull_request_target.acknowledge-risk` defaults to `false`. Setting it to `true` suppresses **only** the strict-mode dangerous-trigger warning, including for `checkout: false` or a supported base checkout. It neither allows other checkouts nor bypasses [bounded fork admission](/gh-aw/reference/triggers/#fork-filtering-forks), actor authorization, unrelated warnings, strict validation, or safe-update checks. An allowlist without acknowledgment still emits the trigger warning. > [!CAUTION] > This policy records maintainer trust, not proof that checked-out code is safe. Prefer immutable commit SHAs; literal branches and tags can move. Keep workflow code and helpers on trusted base refs, read source PR changes as data, and never execute PR-controlled code with privileged credentials. Checkout authentication (`github-app` or `github-token`) and safe-output publication must still be configured separately. This example illustrates compilation policy, not runtime authentication or publication validation. diff --git a/docs/src/content/docs/reference/frontmatter-full.md b/docs/src/content/docs/reference/frontmatter-full.md index f09963f4adb..945c2685936 100644 --- a/docs/src/content/docs/reference/frontmatter-full.md +++ b/docs/src/content/docs/reference/frontmatter-full.md @@ -793,11 +793,14 @@ on: # (optional) draft: true - # Filter fork pull requests by repository pattern (string or list). - # Same-repository PRs remain allowed; an empty list allows only same-repository - # PRs, and '*' allows all forks. Omitting this field adds no fork restriction. - # This does not change GitHub's base-repository permissions or secret availability - # for pull_request_target. + # Filter fork pull requests by repository pattern (string or list). Strict mode + # requires an explicit empty list (same-repository PRs only), exact owner/repo + # entries, or trusted owner/* patterns; omission and any '*' entry are rejected. + # In non-strict mode, omission or '*' adds no fork restriction. Same-repository + # PRs remain allowed. Actor authorization and checkout restrictions remain + # mandatory in strict mode; acknowledge-risk does not bypass them. This does not + # change GitHub's base-repository permissions or secret availability for + # pull_request_target. # (optional) # Accepted formats: @@ -809,8 +812,8 @@ on: # Array items: string # Acknowledge elevated permissions and secret access to suppress only the - # strict-mode pull_request_target trigger warning. Checkout validation remains - # enforced. + # strict-mode pull_request_target trigger warning. Bounded fork admission, actor + # authorization, and checkout validation remain enforced. # (optional) acknowledge-risk: true diff --git a/docs/src/content/docs/reference/triggers.md b/docs/src/content/docs/reference/triggers.md index 35f40aa9893..361c06e4f7d 100644 --- a/docs/src/content/docs/reference/triggers.md +++ b/docs/src/content/docs/reference/triggers.md @@ -182,6 +182,7 @@ Trigger on pull request events in the context of the base repository. Use this o on: pull_request_target: types: [opened, ready_for_review] + forks: [] # Same-repository PRs only ``` `pull_request_target.types` accepts the same activity names as `pull_request`, including `ready_for_review`. @@ -203,7 +204,9 @@ Use `["owner/repo"]` for a specific repository, `["owner/*"]` for an entire org/ Alternatively, use `forks: {author-association: [OWNER, MEMBER, COLLABORATOR]}` to allow fork PRs by the author's relationship to the base repository rather than the fork owner. Same-repository PRs remain allowed, and no association is implicitly included. See [author associations](/gh-aw/reference/fork-support/#author-associations) for trust and secret-availability considerations. -`pull_request_target` also supports explicit fork repository patterns; same-repository PRs remain allowed. Omitting `forks:` does not add a fork restriction for this event. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. +`pull_request_target` requires explicit bounded fork admission in strict mode: `forks: []` for same-repository PRs only, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns. Same-repository PRs remain allowed. Omission, `"*"`, and any list containing `"*"` are rejected, as are expressions and other wildcard patterns. This requirement applies even with `checkout: false`, trusted checkouts, or `acknowledge-risk: true`; actor authorization and checkout restrictions remain enforced independently. + +Non-strict mode retains compatibility: omitting `pull_request_target.forks` or including `"*"` adds no fork restriction. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. Bounded fork admission is defense in depth, not proof of safe PR content: a trusted actor can label an attacker-controlled PR, and disabling checkout does not prevent an agent from reading malicious content with privileged capabilities. #### Stacked PR Filtering (`max-stack:`) diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index b0c7afe3a4d..1f75faa0971 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -2044,12 +2044,12 @@ } } ], - "description": "Filter fork pull requests by repository pattern (string or list). Same-repository PRs remain allowed; an empty list allows only same-repository PRs, and '*' allows all forks. Omitting this field adds no fork restriction. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." + "description": "Filter fork pull requests by repository pattern (string or list). Strict mode requires an explicit empty list (same-repository PRs only), exact owner/repo entries, or trusted owner/* patterns; omission and any '*' entry are rejected. In non-strict mode, omission or '*' adds no fork restriction. Same-repository PRs remain allowed. Actor authorization and checkout restrictions remain mandatory in strict mode; acknowledge-risk does not bypass them. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." }, "acknowledge-risk": { "type": "boolean", "default": false, - "description": "Acknowledge elevated permissions and secret access to suppress only the strict-mode pull_request_target trigger warning. Checkout validation remains enforced." + "description": "Acknowledge elevated permissions and secret access to suppress only the strict-mode pull_request_target trigger warning. Bounded fork admission, actor authorization, and checkout validation remain enforced." }, "allowed-checkouts": { "type": "array", diff --git a/pkg/workflow/concurrency_command_test.go b/pkg/workflow/concurrency_command_test.go index fb84879e118..f87a295eb4d 100644 --- a/pkg/workflow/concurrency_command_test.go +++ b/pkg/workflow/concurrency_command_test.go @@ -23,7 +23,7 @@ func TestCommandConcurrencyCompilation(t *testing.T) { {name: "PR comment alias", on: " slash_command:\n name: test-bot\n events: [pull_request_comment]"}, {name: "PR review comment", on: " slash_command:\n name: test-bot\n events: [pull_request_review_comment]"}, {name: "PR review", on: " slash_command: test-bot\n pull_request_review:\n types: [submitted]"}, - {name: "PR target", on: " slash_command: test-bot\n pull_request_target:\n types: [opened]"}, + {name: "PR target", on: " slash_command: test-bot\n pull_request_target:\n types: [opened]\n forks: []"}, {name: "centralized command", on: " slash_command:\n name: test-bot\n strategy: centralized"}, {name: "centralized command and PR", on: " slash_command:\n name: test-bot\n strategy: centralized\n pull_request:\n types: [opened, synchronize]", mixedPR: true}, {name: "label command only", on: " label_command: test-bot"}, diff --git a/pkg/workflow/filters_forks_test.go b/pkg/workflow/filters_forks_test.go index 6f91c0297df..40d0e7e0454 100644 --- a/pkg/workflow/filters_forks_test.go +++ b/pkg/workflow/filters_forks_test.go @@ -31,10 +31,14 @@ func TestTriggerForkFilterCompilation(t *testing.T) { for _, tt := range tests { t.Run(event+"/"+tt.name, func(t *testing.T) { names := "" + strict := true if event == "pull_request" { names = "\n names: [community-contribution]" + } else if tt.expected == "" { + strict = false } source := fmt.Sprintf(`--- +strict: %t if: ${{ github.event.repository.fork == false }} on: permissions: {} @@ -51,7 +55,7 @@ network: allowed: [defaults] --- Review the contribution. -`, event, tt.forks, names) +`, strict, event, tt.forks, names) compiled := compileTriggerFilterFixture(t, source) on := compiled["on"].(map[string]any) assert.Equal(t, map[string]any{"types": []any{"labeled"}, "branches": []any{"main"}}, on[event]) diff --git a/pkg/workflow/pr_ready_for_review_checkout_test.go b/pkg/workflow/pr_ready_for_review_checkout_test.go index 0991755dc26..765b6bff218 100644 --- a/pkg/workflow/pr_ready_for_review_checkout_test.go +++ b/pkg/workflow/pr_ready_for_review_checkout_test.go @@ -280,6 +280,7 @@ Workflow triggered when a PR is closed. workflowContent: `--- on: pull_request_target: + forks: [] types: [opened] permissions: contents: read diff --git a/pkg/workflow/pull_request_target_forks_test.go b/pkg/workflow/pull_request_target_forks_test.go new file mode 100644 index 00000000000..0c89afc7c26 --- /dev/null +++ b/pkg/workflow/pull_request_target_forks_test.go @@ -0,0 +1,126 @@ +//go:build !integration + +package workflow + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/github/gh-aw/pkg/testutil" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPullRequestTargetBoundedForkAdmission(t *testing.T) { + tests := []struct { + name string + forks string + allows bool + }{ + {"omitted", "", false}, + {"wildcard string", "'*'", false}, + {"wildcard list", "['*']", false}, + {"mixed wildcard", "[trusted/repo, '*']", false}, + {"wildcard first", "['*', trusted/repo]", false}, + {"empty list", "[]", true}, + {"exact string", "trusted/repo", true}, + {"owner string", "'trusted/*'", true}, + {"mixed bounded", "[trusted/repo, 'partner/*']", true}, + {"literal punctuation", "[trusted/repo.name-1_2]", true}, + {"empty string", "''", false}, + {"wildcard owner", "'*/repo'", false}, + {"partial owner", "'trust*/*'", false}, + {"partial repo", "'trusted/repo*'", false}, + {"recursive wildcard", "'trusted/**'", false}, + {"expression", "'${{ github.repository }}'", false}, + {"whitespace", "' trusted/repo '", false}, + {"missing repo", "'trusted/'", false}, + } + for _, tt := range tests { + for _, strict := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/strict=%t", tt.name, strict), func(t *testing.T) { + forks := "" + if tt.forks != "" { + forks = " forks: " + tt.forks + "\n" + } + source := fmt.Sprintf(`--- +strict: %t +on: + pull_request_target: + types: [labeled] + acknowledge-risk: true +%s workflow_dispatch: +checkout: false +tools: + github: false +--- +Review the contribution. +`, strict, forks) + file := filepath.Join(testutil.TempDir(t, "bounded-target-forks"), "workflow.md") + require.NoError(t, os.WriteFile(file, []byte(source), 0600)) + err := NewCompiler().CompileWorkflow(file) + if strict && !tt.allows { + require.ErrorContains(t, err, "requires explicit bounded fork admission") + assert.Contains(t, err.Error(), "acknowledge-risk do not bypass") + assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) + } else { + require.NoError(t, err) + } + }) + } + } +} + +func TestPullRequestTargetBoundedForkAdmissionCLIOverride(t *testing.T) { + source := `--- +strict: false +on: + pull_request_target: + acknowledge-risk: true + forks: ["*"] +checkout: + ref: ${{ github.event.pull_request.base.sha }} +tools: + github: false +--- +Review the contribution. +` + file := filepath.Join(testutil.TempDir(t, "bounded-target-cli"), "workflow.md") + require.NoError(t, os.WriteFile(file, []byte(source), 0600)) + compiler := NewCompiler() + compiler.SetStrictMode(true) + require.ErrorContains(t, compiler.CompileWorkflow(file), "requires explicit bounded fork admission") +} + +func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { + for _, tt := range []struct { + on string + wantError string + }{ + {"pull_request_target", "requires explicit bounded fork admission"}, + {"[pull_request_target, workflow_dispatch]", "expected string or object"}, + {"\n pull_request_target:", "expected string or object"}, + {"\n pull_request_target: null", "expected string or object"}, + {"\n pull_request_target: {}", "requires explicit bounded fork admission"}, + } { + t.Run(tt.on, func(t *testing.T) { + source := "---\non: " + tt.on + "\ncheckout: false\ntools:\n github: false\n---\nReview the contribution.\n" + file := filepath.Join(testutil.TempDir(t, "bounded-target-shorthand"), "workflow.md") + require.NoError(t, os.WriteFile(file, []byte(source), 0600)) + require.ErrorContains(t, NewCompiler().CompileWorkflow(file), tt.wantError) + assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) + }) + } +} + +func TestHasBoundedPullRequestTargetForksRejectsMalformedValues(t *testing.T) { + for _, forks := range []any{nil, true, 1, []any{nil}, []any{true}, []any{"trusted/repo", "*"}, map[string]any{"author-association": []any{"OWNER"}}} { + assert.False(t, hasBoundedPullRequestTargetForks(map[string]any{ + "on": map[string]any{ + "pull_request_target": map[string]any{"forks": forks}, + }, + }), "forks: %#v", forks) + } +} diff --git a/pkg/workflow/pull_request_target_validation.go b/pkg/workflow/pull_request_target_validation.go index 74cb7f43ed1..c39f48b319a 100644 --- a/pkg/workflow/pull_request_target_validation.go +++ b/pkg/workflow/pull_request_target_validation.go @@ -20,6 +20,9 @@ // 3. With on.roles containing all or read: reject in strict mode and warn in // non-strict mode, regardless of checkout or trigger risk acknowledgment. // +// 4. In strict mode, require explicit bounded fork admission regardless of +// checkout or trigger risk acknowledgment. +// // # References // // See: https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/ @@ -38,6 +41,7 @@ package workflow import ( "fmt" "os" + "regexp" "strings" "github.com/goccy/go-yaml" @@ -49,6 +53,8 @@ import ( var pullRequestTargetLog = logger.New("workflow:pull_request_target_validation") +var boundedForkPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/([A-Za-z0-9_.-]+|\*)$`) + // validatePullRequestTargetTrigger validates security requirements for pull_request_target triggers. // // The pull_request_target trigger runs with full write permissions and repository secret access @@ -87,13 +93,7 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, return nil } - onMap, isMap := onData.(map[string]any) - if !isMap { - return nil - } - - _, hasPRT := onMap["pull_request_target"] - if !hasPRT { + if !frontmatterHasTrigger(onData, "pull_request_target") { return nil } @@ -119,6 +119,16 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, } break } + if effectiveStrictMode && !hasBoundedPullRequestTargetForks(workflowData.RawFrontmatter) { + return formatCompilerError(markdownPath, "error", + "pull_request_target requires explicit bounded fork admission in strict mode.\n"+ + "Set on.pull_request_target.forks: [] for same-repository PRs only, or list exact\n"+ + "repositories (owner/repo) or trusted owner/* patterns. Omission, '*' (including\n"+ + "inside a list), expressions, and other patterns are not allowed.\n"+ + "Trusted event actors can still act on attacker-controlled PR content.\n"+ + "checkout: false and on.pull_request_target.acknowledge-risk do not bypass this requirement.\n"+ + "Actor authorization and trusted-checkout restrictions remain mandatory.", nil) + } var acknowledged bool var allowedCheckouts []any if on, ok := workflowData.RawFrontmatter["on"].(map[string]any); ok { @@ -194,6 +204,31 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, return nil } +func hasBoundedPullRequestTargetForks(frontmatter map[string]any) bool { + on, ok := frontmatter["on"].(map[string]any) + if !ok { + return false + } + trigger, ok := on["pull_request_target"].(map[string]any) + if !ok { + return false + } + switch forks := trigger["forks"].(type) { + case string: + return boundedForkPattern.MatchString(forks) + case []any: + for _, fork := range forks { + pattern, ok := fork.(string) + if !ok || !boundedForkPattern.MatchString(pattern) { + return false + } + } + return true + default: + return false + } +} + func dangerouslyAllowsRolesReadAndPullRequestTarget(workflowData *WorkflowData) bool { value, found := getFeatureValueCaseInsensitive( workflowData.Features, diff --git a/pkg/workflow/pull_request_target_validation_test.go b/pkg/workflow/pull_request_target_validation_test.go index 9011c83ebb4..d7489e37c6d 100644 --- a/pkg/workflow/pull_request_target_validation_test.go +++ b/pkg/workflow/pull_request_target_validation_test.go @@ -36,6 +36,7 @@ func TestPullRequestTargetValidation(t *testing.T) { strict: false on: pull_request_target: + forks: [] types: [opened] tools: github: false @@ -60,6 +61,7 @@ Test workflow content.`, strict: false on: pull_request_target: + forks: [] types: [opened] tools: github: false @@ -83,6 +85,7 @@ Test workflow content.`, strict: false on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -155,6 +158,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -177,6 +181,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -199,6 +204,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -222,6 +228,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -246,6 +253,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -269,6 +277,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -292,6 +301,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -316,6 +326,7 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -343,6 +354,7 @@ Test workflow content.`, strict: false on: pull_request_target: + forks: [] types: [opened] tools: github: @@ -493,6 +505,7 @@ func TestPullRequestTargetPolicy(t *testing.T) { //nolint:largefunc // Table cov content := fmt.Sprintf(`--- on: pull_request_target: + forks: [] types: [closed] branches: [main] %s @@ -603,6 +616,7 @@ func TestPullRequestTargetRoleValidation(t *testing.T) { strict: %t on: pull_request_target: + forks: [] types: [opened] acknowledge-risk: true %scheckout: false @@ -722,6 +736,7 @@ func TestPullRequestTargetRoleValidationFeatureOptOut(t *testing.T) { strict: %t on: pull_request_target: + forks: [] acknowledge-risk: true roles: read checkout: false From 96e2ca7499504837dc9280b2b63102e428f47b1e Mon Sep 17 00:00:00 2001 From: pelikhan Date: Wed, 28 Oct 2026 04:35:09 -0700 Subject: [PATCH 7/8] Default target PR fork admission to same-repository pulls Treat omitted forks like an empty list in both compilation modes, including target trigger shorthand. Keep unrestricted fork patterns forbidden in strict mode and preserve authorization and checkout requirements. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...trict-pull-request-target-bounded-forks.md | 4 +-- CHANGELOG.md | 14 ++++---- ...ply-fork-filters-to-pull-request-target.md | 13 ++++--- docs/src/content/docs/reference/checkout.md | 1 - .../docs/reference/frontmatter-full.md | 16 ++++----- docs/src/content/docs/reference/triggers.md | 5 ++- pkg/parser/schemas/main_workflow_schema.json | 2 +- pkg/workflow/concurrency_command_test.go | 2 +- pkg/workflow/filters.go | 12 ++++--- pkg/workflow/filters_forks_test.go | 35 +++++++++++++++++-- .../pr_ready_for_review_checkout_test.go | 1 - .../pull_request_target_forks_test.go | 19 ++++++---- .../pull_request_target_validation.go | 14 +++++--- .../pull_request_target_validation_test.go | 15 -------- 14 files changed, 90 insertions(+), 63 deletions(-) diff --git a/.changeset/strict-pull-request-target-bounded-forks.md b/.changeset/strict-pull-request-target-bounded-forks.md index f455798f799..818458abeae 100644 --- a/.changeset/strict-pull-request-target-bounded-forks.md +++ b/.changeset/strict-pull-request-target-bounded-forks.md @@ -2,6 +2,6 @@ "gh-aw": major --- -Require explicit bounded fork admission for `pull_request_target` in strict mode. +Default `pull_request_target` to same-repository PRs only and require bounded fork patterns in strict mode. -Migration: replace omitted `on.pull_request_target.forks` or any `"*"` entry with `forks: []` for same-repository PRs only, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns, then recompile. Expressions and other wildcard patterns are rejected. Actor authorization and trusted-checkout restrictions remain mandatory; `acknowledge-risk`, `checkout: false`, and trusted checkouts do not bypass fork admission. Non-strict behavior is unchanged. +Migration: omit `on.pull_request_target.forks` for same-repository PRs only (`forks: []` remains equivalent but is not required). Workflows that need fork PRs must list exact `owner/repo` entries or deliberately trusted `owner/*` patterns, then recompile. Strict mode rejects any `"*"` entry, expressions, and other wildcard patterns; non-strict mode permits explicitly using `"*"` for unrestricted admission. Actor authorization and trusted-checkout restrictions remain mandatory in strict mode; `acknowledge-risk`, `checkout: false`, and trusted checkouts do not bypass fork admission. diff --git a/CHANGELOG.md b/CHANGELOG.md index e4855b14c37..ef01cc922c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,13 +13,15 @@ and mixed edits continue to require write-or-higher repository permission. ### Breaking changes -Strict-mode `pull_request_target` workflows now require explicit bounded fork -admission. Replace omitted `forks` or any `"*"` entry with `forks: []` for -same-repository PRs only, exact `owner/repo` entries, or deliberately trusted -`owner/*` patterns, then recompile. Expressions and other wildcard patterns are -rejected. Actor authorization and trusted-checkout restrictions remain mandatory; +`pull_request_target` workflows now default to same-repository PRs only in both +strict and non-strict mode. Omitting `forks` is equivalent to `forks: []`; no +explicit empty list is required. To admit forks, configure exact `owner/repo` +entries or deliberately trusted `owner/*` patterns, then recompile. Strict mode +rejects any `"*"` entry, expressions, and other wildcard patterns; non-strict +mode permits explicitly using `"*"` for unrestricted admission. Actor +authorization and trusted-checkout restrictions remain mandatory in strict mode; `acknowledge-risk`, disabled checkout, and trusted checkout policies do not bypass -fork admission. Non-strict compilation retains its existing behavior. +fork admission. The `gh aw outcomes` command has been removed. Use `gh aw logs --outcomes` to evaluate selected runs, or pipe a run ID to diff --git a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md index 007f9dc93eb..b5fcc64049b 100644 --- a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -10,11 +10,11 @@ gh-aw supports compiler-only `forks:` filters under both PR events and label-name filters (`names:`) under `on.pull_request`; these belong in job conditions, not native GitHub Actions trigger properties. The on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) checked for the next event before leaving compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations`, so filters after those fields could leak into lock files and fail Actions schema validation. Separately, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) read only `on.pull_request`, silently ignoring explicit `pull_request_target.forks` restrictions. -Security review also identified that omitted target fork filters and `"*"` both admit arbitrary forks. Trusted actor authorization is insufficient: a maintainer can label an attacker-controlled PR, and an agent can consume malicious PR content with privileged capabilities even when checkout is disabled. Strict mode therefore needs explicit bounded admission, independently of actor authorization, checkout policy, and risk acknowledgment. +Security review also identified that omitted target fork filters previously admitted arbitrary forks, like `"*"`. Trusted actor authorization is insufficient: a maintainer can label an attacker-controlled PR, and an agent can consume malicious PR content with privileged capabilities even when checkout is disabled. The target event therefore needs the same same-repository default as `pull_request`, and strict mode must reject unrestricted patterns independently of actor authorization, checkout policy, and risk acknowledgment. ### Decision -The compiler will apply explicit fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. Explicit patterns always admit same-repository PRs, and `[]` admits only those PRs. Strict-mode `pull_request_target` requires `forks: []`, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns. Omission, `"*"` anywhere in a list, expressions, and other wildcard patterns are rejected before checkout exemptions. Neither `acknowledge-risk` nor trusted/disabled checkout bypasses admission; actor authorization and checkout restrictions remain mandatory. Non-strict mode retains unrestricted target admission for omission or `"*"`. The same-repository default for configured `pull_request` event objects is unchanged. +The compiler will apply fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. For `pull_request_target`, omission and `forks: []` both admit only same-repository PRs, in strict and non-strict mode, including scalar trigger shorthand. Explicit patterns always admit same-repository PRs. Strict-mode target workflows may admit forks through exact `owner/repo` entries or deliberately trusted `owner/*` patterns; `"*"` anywhere in a list, expressions, and other wildcard patterns are rejected before checkout exemptions. Neither `acknowledge-risk` nor trusted/disabled checkout bypasses admission; actor authorization and checkout restrictions remain mandatory. Non-strict mode permits explicitly using `"*"` for unrestricted target admission. The same-repository default for configured `pull_request` event objects is unchanged. The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.json` accepts string and list patterns for both events, but accepts the `forks: {author-association: [...]}` form from [ADR-69374](69374-fork-pr-admission-by-author-association.md) only for `pull_request`; the shared helper's ability to process that object does not make it supported for `pull_request_target`, and this decision does not extend the schema. To produce valid lock files without silently dropping configured admission rules, the cleanup state machine will leave compiler-only subsections before detecting the next event and track `forks` indentation for nested content, including the supported two-space and four-space event layouts. @@ -24,9 +24,9 @@ The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.jso The compiler could treat `forks` as a `pull_request`-only key and raise an error when it appears under `pull_request_target`. That would also stop the silent drop. It was rejected because the field is documented and useful: authors of `pull_request_target` workflows sometimes want to admit only specific fork owners. An error would take away that control instead of providing it. -#### Alternative 2: Apply the same same-repository default to `pull_request_target` +#### Alternative 2: Require an explicit empty fork list in strict mode -Using one rule for both events would be simpler: omitting `forks` would block forks everywhere. Strict target compilation instead rejects omission and requires maintainers to state the intended trust boundary explicitly. Non-strict mode retains its asymmetric defaults for compatibility. +Requiring `forks: []` would make every strict target workflow state its admission policy. It was rejected because omission can enforce the same same-repository-only condition without redundant configuration. The compiler must emit that condition rather than merely accept omission in validation. #### Alternative 3: Fix only the cleanup leak and keep `pull_request`-only fork filtering @@ -41,13 +41,12 @@ A narrower bug fix would remove the leaked keys and leave admission logic alone. - Strict-mode target workflows cannot silently admit arbitrary forks, including through risk acknowledgment or checkout exemptions. #### Negative -- Existing strict-mode target workflows with omitted or unrestricted fork admission must migrate to explicit bounded admission and recompile. This is documented as a breaking change. -- Non-strict mode retains different defaults for the two PR events. +- Existing target workflows that omitted `forks` and relied on unrestricted admission must configure the intended fork patterns and recompile. Strict-mode workflows using unrestricted patterns must migrate to bounded admission. This is documented as a breaking change. - Recompiling workflows that already had a `forks:` key under `pull_request_target` will start enforcing it. This could stop runs that previously, and unintentionally, admitted all forks. - The line-oriented cleanup state machine depends on event-ordering logic and indent tracking, which remain fragile compared with editing the YAML AST. - The author-association object form remains unavailable for `pull_request_target`, despite the shared helper accepting it internally. #### Neutral - The [trigger reference](../src/content/docs/reference/triggers.md) describes the `pull_request_target` pattern-filter semantics explicitly. -- Regression tests in `pkg/workflow/filters_forks_test.go`, `pkg/workflow/frontmatter_on_section_cleanup_test.go`, and `pkg/workflow/pull_request_target_forks_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, indentation, strict bounded admission, and non-strict compatibility. +- Regression tests in `pkg/workflow/filters_forks_test.go`, `pkg/workflow/frontmatter_on_section_cleanup_test.go`, and `pkg/workflow/pull_request_target_forks_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, indentation, strict bounded admission, same-repository defaults, and non-strict wildcard support. - Fork admission does not grant permissions or secrets and does not make checking out or executing untrusted fork code safe. diff --git a/docs/src/content/docs/reference/checkout.md b/docs/src/content/docs/reference/checkout.md index f1c8ac52108..596ebfe833e 100644 --- a/docs/src/content/docs/reference/checkout.md +++ b/docs/src/content/docs/reference/checkout.md @@ -247,7 +247,6 @@ To check out a trusted ref such as the base SHA, opt in explicitly with a `check on: pull_request_target: types: [opened, synchronize] - forks: [] # Same-repository PRs only checkout: repository: ${{ github.repository }} ref: ${{ github.event.pull_request.base.sha }} diff --git a/docs/src/content/docs/reference/frontmatter-full.md b/docs/src/content/docs/reference/frontmatter-full.md index 945c2685936..443baada13a 100644 --- a/docs/src/content/docs/reference/frontmatter-full.md +++ b/docs/src/content/docs/reference/frontmatter-full.md @@ -793,14 +793,14 @@ on: # (optional) draft: true - # Filter fork pull requests by repository pattern (string or list). Strict mode - # requires an explicit empty list (same-repository PRs only), exact owner/repo - # entries, or trusted owner/* patterns; omission and any '*' entry are rejected. - # In non-strict mode, omission or '*' adds no fork restriction. Same-repository - # PRs remain allowed. Actor authorization and checkout restrictions remain - # mandatory in strict mode; acknowledge-risk does not bypass them. This does not - # change GitHub's base-repository permissions or secret availability for - # pull_request_target. + # Filter fork pull requests by repository pattern (string or list). Omission and + # an empty list both allow only same-repository PRs. Strict mode permits exact + # owner/repo entries or trusted owner/* patterns and rejects any '*' entry, + # expressions, and other patterns. Non-strict mode permits '*' to allow all forks. + # Same-repository PRs remain allowed. Actor authorization and checkout + # restrictions remain mandatory in strict mode; acknowledge-risk does not bypass + # them. This does not change GitHub's base-repository permissions or secret + # availability for pull_request_target. # (optional) # Accepted formats: diff --git a/docs/src/content/docs/reference/triggers.md b/docs/src/content/docs/reference/triggers.md index 361c06e4f7d..cd49a81a175 100644 --- a/docs/src/content/docs/reference/triggers.md +++ b/docs/src/content/docs/reference/triggers.md @@ -182,7 +182,6 @@ Trigger on pull request events in the context of the base repository. Use this o on: pull_request_target: types: [opened, ready_for_review] - forks: [] # Same-repository PRs only ``` `pull_request_target.types` accepts the same activity names as `pull_request`, including `ready_for_review`. @@ -204,9 +203,9 @@ Use `["owner/repo"]` for a specific repository, `["owner/*"]` for an entire org/ Alternatively, use `forks: {author-association: [OWNER, MEMBER, COLLABORATOR]}` to allow fork PRs by the author's relationship to the base repository rather than the fork owner. Same-repository PRs remain allowed, and no association is implicitly included. See [author associations](/gh-aw/reference/fork-support/#author-associations) for trust and secret-availability considerations. -`pull_request_target` requires explicit bounded fork admission in strict mode: `forks: []` for same-repository PRs only, exact `owner/repo` entries, or deliberately trusted `owner/*` patterns. Same-repository PRs remain allowed. Omission, `"*"`, and any list containing `"*"` are rejected, as are expressions and other wildcard patterns. This requirement applies even with `checkout: false`, trusted checkouts, or `acknowledge-risk: true`; actor authorization and checkout restrictions remain enforced independently. +`pull_request_target` also defaults to same-repository PRs only: omitting `forks:` is equivalent to `forks: []` in both strict and non-strict mode. To admit forks in strict mode, list exact `owner/repo` entries or deliberately trusted `owner/*` patterns. Same-repository PRs remain allowed. `"*"` and any list containing `"*"` are rejected in strict mode, as are expressions and other wildcard patterns. This restriction applies even with `checkout: false`, trusted checkouts, or `acknowledge-risk: true`; actor authorization and checkout restrictions remain enforced independently. -Non-strict mode retains compatibility: omitting `pull_request_target.forks` or including `"*"` adds no fork restriction. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. Bounded fork admission is defense in depth, not proof of safe PR content: a trusted actor can label an attacker-controlled PR, and disabling checkout does not prevent an agent from reading malicious content with privileged capabilities. +Non-strict mode permits explicitly including `"*"` to remove the fork restriction. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. Bounded fork admission is defense in depth, not proof of safe PR content: a trusted actor can label an attacker-controlled PR, and disabling checkout does not prevent an agent from reading malicious content with privileged capabilities. #### Stacked PR Filtering (`max-stack:`) diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index 1f75faa0971..9f753bf940a 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -2044,7 +2044,7 @@ } } ], - "description": "Filter fork pull requests by repository pattern (string or list). Strict mode requires an explicit empty list (same-repository PRs only), exact owner/repo entries, or trusted owner/* patterns; omission and any '*' entry are rejected. In non-strict mode, omission or '*' adds no fork restriction. Same-repository PRs remain allowed. Actor authorization and checkout restrictions remain mandatory in strict mode; acknowledge-risk does not bypass them. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." + "description": "Filter fork pull requests by repository pattern (string or list). Omission and an empty list both allow only same-repository PRs. Strict mode permits exact owner/repo entries or trusted owner/* patterns and rejects any '*' entry, expressions, and other patterns. Non-strict mode permits '*' to allow all forks. Same-repository PRs remain allowed. Actor authorization and checkout restrictions remain mandatory in strict mode; acknowledge-risk does not bypass them. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." }, "acknowledge-risk": { "type": "boolean", diff --git a/pkg/workflow/concurrency_command_test.go b/pkg/workflow/concurrency_command_test.go index f87a295eb4d..fb84879e118 100644 --- a/pkg/workflow/concurrency_command_test.go +++ b/pkg/workflow/concurrency_command_test.go @@ -23,7 +23,7 @@ func TestCommandConcurrencyCompilation(t *testing.T) { {name: "PR comment alias", on: " slash_command:\n name: test-bot\n events: [pull_request_comment]"}, {name: "PR review comment", on: " slash_command:\n name: test-bot\n events: [pull_request_review_comment]"}, {name: "PR review", on: " slash_command: test-bot\n pull_request_review:\n types: [submitted]"}, - {name: "PR target", on: " slash_command: test-bot\n pull_request_target:\n types: [opened]\n forks: []"}, + {name: "PR target", on: " slash_command: test-bot\n pull_request_target:\n types: [opened]"}, {name: "centralized command", on: " slash_command:\n name: test-bot\n strategy: centralized"}, {name: "centralized command and PR", on: " slash_command:\n name: test-bot\n strategy: centralized\n pull_request:\n types: [opened, synchronize]", mixedPR: true}, {name: "label command only", on: " label_command: test-bot"}, diff --git a/pkg/workflow/filters.go b/pkg/workflow/filters.go index 4c35cc8a58c..677c0a6183a 100644 --- a/pkg/workflow/filters.go +++ b/pkg/workflow/filters.go @@ -105,7 +105,7 @@ func (c *Compiler) applyPullRequestDraftFilter(data *WorkflowData, frontmatter m // applyPullRequestForkFilter applies fork filter conditions for pull_request and pull_request_target triggers. // Supports repository patterns or an explicit author-association list. -// Without an explicit forks field, only pull_request defaults to same-repo PRs. +// Without an explicit forks field, configured PR events default to same-repo PRs. func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter map[string]any) { filtersLog.Print("Applying pull request fork filter") @@ -127,15 +127,19 @@ func (c *Compiler) applyPullRequestForkFilter(data *WorkflowData, frontmatter ma // Check if "on" is an object (not a string) onMap, isOnMap := onValue.(map[string]any) if !isOnMap { + if frontmatterHasTrigger(onValue, "pull_request_target") { + c.applyPullRequestEventForkFilter(data, "pull_request_target", nil) + } return } for _, eventName := range []string{"pull_request", "pull_request_target"} { - prMap, ok := onMap[eventName].(map[string]any) - if !ok { + event, exists := onMap[eventName] + if !exists { continue } - if _, hasForks := prMap["forks"]; eventName == "pull_request_target" && !hasForks { + prMap, ok := event.(map[string]any) + if !ok && (eventName != "pull_request_target" || event != nil) { continue } c.applyPullRequestEventForkFilter(data, eventName, prMap) diff --git a/pkg/workflow/filters_forks_test.go b/pkg/workflow/filters_forks_test.go index 40d0e7e0454..928e2391a0e 100644 --- a/pkg/workflow/filters_forks_test.go +++ b/pkg/workflow/filters_forks_test.go @@ -77,6 +77,38 @@ Review the contribution. } } +func TestPullRequestTargetDefaultForkFilterCompilation(t *testing.T) { + const sameRepo = "github.event_name != 'pull_request_target' || github.event.pull_request.head.repo.id == github.repository_id" + for _, strict := range []bool{false, true} { + for _, on := range []string{ + "pull_request_target", + "\n pull_request_target: {}", + "\n pull_request_target:\n types: [labeled]\n workflow_dispatch:", + "\n pull_request_target:\n types: [labeled]\n forks: []\n workflow_dispatch:", + "\n pull_request_target:\n types: [labeled]\n pull_request:\n forks: ['*']", + } { + t.Run(fmt.Sprintf("strict=%t/on=%s", strict, on), func(t *testing.T) { + compiled := compileTriggerFilterFixture(t, fmt.Sprintf(`--- +strict: %t +on: %s +if: github.actor != 'dependabot[bot]' +checkout: false +tools: + github: false +--- +Review the contribution. +`, strict, on)) + jobs := compiled["jobs"].(map[string]any) + condition := jobs["activation"].(map[string]any)["if"].(string) + assert.Contains(t, condition, sameRepo) + assert.Contains(t, condition, "github.actor != 'dependabot[bot]'") + assert.NotContains(t, condition, "startsWith") + assert.NotContains(t, condition, "github.event_name != 'pull_request' ||") + }) + } + } +} + func TestTriggerForkFilterCompilationRejectsMalformedValues(t *testing.T) { tests := []struct { name string @@ -197,9 +229,6 @@ func TestApplyPullRequestForkFilter(t *testing.T) { "on": map[string]any{event: tt.pr, "push": nil, "workflow_dispatch": nil}, }) filter := strings.ReplaceAll(tt.expected, "'pull_request'", "'"+event+"'") - if _, hasForks := tt.pr["forks"]; event == "pull_request_target" && !hasForks { - filter = "" - } expected := filter if existing != "" { expected = existing diff --git a/pkg/workflow/pr_ready_for_review_checkout_test.go b/pkg/workflow/pr_ready_for_review_checkout_test.go index 765b6bff218..0991755dc26 100644 --- a/pkg/workflow/pr_ready_for_review_checkout_test.go +++ b/pkg/workflow/pr_ready_for_review_checkout_test.go @@ -280,7 +280,6 @@ Workflow triggered when a PR is closed. workflowContent: `--- on: pull_request_target: - forks: [] types: [opened] permissions: contents: read diff --git a/pkg/workflow/pull_request_target_forks_test.go b/pkg/workflow/pull_request_target_forks_test.go index 0c89afc7c26..2d04d507e3d 100644 --- a/pkg/workflow/pull_request_target_forks_test.go +++ b/pkg/workflow/pull_request_target_forks_test.go @@ -19,7 +19,7 @@ func TestPullRequestTargetBoundedForkAdmission(t *testing.T) { forks string allows bool }{ - {"omitted", "", false}, + {"omitted", "", true}, {"wildcard string", "'*'", false}, {"wildcard list", "['*']", false}, {"mixed wildcard", "[trusted/repo, '*']", false}, @@ -62,7 +62,7 @@ Review the contribution. require.NoError(t, os.WriteFile(file, []byte(source), 0600)) err := NewCompiler().CompileWorkflow(file) if strict && !tt.allows { - require.ErrorContains(t, err, "requires explicit bounded fork admission") + require.ErrorContains(t, err, "requires bounded fork admission") assert.Contains(t, err.Error(), "acknowledge-risk do not bypass") assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) } else { @@ -91,7 +91,7 @@ Review the contribution. require.NoError(t, os.WriteFile(file, []byte(source), 0600)) compiler := NewCompiler() compiler.SetStrictMode(true) - require.ErrorContains(t, compiler.CompileWorkflow(file), "requires explicit bounded fork admission") + require.ErrorContains(t, compiler.CompileWorkflow(file), "requires bounded fork admission") } func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { @@ -99,18 +99,23 @@ func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { on string wantError string }{ - {"pull_request_target", "requires explicit bounded fork admission"}, + {"pull_request_target", ""}, {"[pull_request_target, workflow_dispatch]", "expected string or object"}, {"\n pull_request_target:", "expected string or object"}, {"\n pull_request_target: null", "expected string or object"}, - {"\n pull_request_target: {}", "requires explicit bounded fork admission"}, + {"\n pull_request_target: {}", ""}, } { t.Run(tt.on, func(t *testing.T) { source := "---\non: " + tt.on + "\ncheckout: false\ntools:\n github: false\n---\nReview the contribution.\n" file := filepath.Join(testutil.TempDir(t, "bounded-target-shorthand"), "workflow.md") require.NoError(t, os.WriteFile(file, []byte(source), 0600)) - require.ErrorContains(t, NewCompiler().CompileWorkflow(file), tt.wantError) - assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) + err := NewCompiler().CompileWorkflow(file) + if tt.wantError != "" { + require.ErrorContains(t, err, tt.wantError) + assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) + } else { + require.NoError(t, err) + } }) } } diff --git a/pkg/workflow/pull_request_target_validation.go b/pkg/workflow/pull_request_target_validation.go index c39f48b319a..da3f56b210c 100644 --- a/pkg/workflow/pull_request_target_validation.go +++ b/pkg/workflow/pull_request_target_validation.go @@ -20,7 +20,7 @@ // 3. With on.roles containing all or read: reject in strict mode and warn in // non-strict mode, regardless of checkout or trigger risk acknowledgment. // -// 4. In strict mode, require explicit bounded fork admission regardless of +// 4. In strict mode, require bounded fork admission regardless of // checkout or trigger risk acknowledgment. // // # References @@ -121,9 +121,9 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, } if effectiveStrictMode && !hasBoundedPullRequestTargetForks(workflowData.RawFrontmatter) { return formatCompilerError(markdownPath, "error", - "pull_request_target requires explicit bounded fork admission in strict mode.\n"+ - "Set on.pull_request_target.forks: [] for same-repository PRs only, or list exact\n"+ - "repositories (owner/repo) or trusted owner/* patterns. Omission, '*' (including\n"+ + "pull_request_target requires bounded fork admission in strict mode.\n"+ + "Omit on.pull_request_target.forks for same-repository PRs only, or list exact\n"+ + "repositories (owner/repo) or trusted owner/* patterns. '*' (including\n"+ "inside a list), expressions, and other patterns are not allowed.\n"+ "Trusted event actors can still act on attacker-controlled PR content.\n"+ "checkout: false and on.pull_request_target.acknowledge-risk do not bypass this requirement.\n"+ @@ -205,6 +205,9 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, } func hasBoundedPullRequestTargetForks(frontmatter map[string]any) bool { + if on, ok := frontmatter["on"].(string); ok { + return on == "pull_request_target" + } on, ok := frontmatter["on"].(map[string]any) if !ok { return false @@ -213,6 +216,9 @@ func hasBoundedPullRequestTargetForks(frontmatter map[string]any) bool { if !ok { return false } + if _, hasForks := trigger["forks"]; !hasForks { + return true + } switch forks := trigger["forks"].(type) { case string: return boundedForkPattern.MatchString(forks) diff --git a/pkg/workflow/pull_request_target_validation_test.go b/pkg/workflow/pull_request_target_validation_test.go index d7489e37c6d..9011c83ebb4 100644 --- a/pkg/workflow/pull_request_target_validation_test.go +++ b/pkg/workflow/pull_request_target_validation_test.go @@ -36,7 +36,6 @@ func TestPullRequestTargetValidation(t *testing.T) { strict: false on: pull_request_target: - forks: [] types: [opened] tools: github: false @@ -61,7 +60,6 @@ Test workflow content.`, strict: false on: pull_request_target: - forks: [] types: [opened] tools: github: false @@ -85,7 +83,6 @@ Test workflow content.`, strict: false on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -158,7 +155,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -181,7 +177,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -204,7 +199,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -228,7 +222,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -253,7 +246,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -277,7 +269,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -301,7 +292,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -326,7 +316,6 @@ Test workflow content.`, frontmatter: `--- on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -354,7 +343,6 @@ Test workflow content.`, strict: false on: pull_request_target: - forks: [] types: [opened] tools: github: @@ -505,7 +493,6 @@ func TestPullRequestTargetPolicy(t *testing.T) { //nolint:largefunc // Table cov content := fmt.Sprintf(`--- on: pull_request_target: - forks: [] types: [closed] branches: [main] %s @@ -616,7 +603,6 @@ func TestPullRequestTargetRoleValidation(t *testing.T) { strict: %t on: pull_request_target: - forks: [] types: [opened] acknowledge-risk: true %scheckout: false @@ -736,7 +722,6 @@ func TestPullRequestTargetRoleValidationFeatureOptOut(t *testing.T) { strict: %t on: pull_request_target: - forks: [] acknowledge-risk: true roles: read checkout: false From 166d553d0bd0a11f29b925b9c9f3f5458c395126 Mon Sep 17 00:00:00 2001 From: pelikhan Date: Wed, 28 Oct 2026 05:08:18 -0700 Subject: [PATCH 8/8] Warn instead of rejecting unrestricted target PR forks Allow explicit wildcard fork admission in strict mode while retaining actor and checkout safeguards. Recommend bounded patterns and document the unchanged same-repository default. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...trict-pull-request-target-bounded-forks.md | 4 +- CHANGELOG.md | 9 +-- ...ply-fork-filters-to-pull-request-target.md | 16 +++-- docs/src/content/docs/reference/checkout.md | 2 +- .../docs/reference/frontmatter-full.md | 18 ++--- docs/src/content/docs/reference/triggers.md | 4 +- pkg/parser/schemas/main_workflow_schema.json | 4 +- pkg/workflow/filters_forks_test.go | 6 +- .../pull_request_target_forks_test.go | 70 ++++++++++++++++--- .../pull_request_target_validation.go | 36 +++++++--- 10 files changed, 120 insertions(+), 49 deletions(-) diff --git a/.changeset/strict-pull-request-target-bounded-forks.md b/.changeset/strict-pull-request-target-bounded-forks.md index 818458abeae..56253cfe61c 100644 --- a/.changeset/strict-pull-request-target-bounded-forks.md +++ b/.changeset/strict-pull-request-target-bounded-forks.md @@ -2,6 +2,6 @@ "gh-aw": major --- -Default `pull_request_target` to same-repository PRs only and require bounded fork patterns in strict mode. +Default `pull_request_target` to same-repository PRs only and warn about unrestricted forks in strict mode. -Migration: omit `on.pull_request_target.forks` for same-repository PRs only (`forks: []` remains equivalent but is not required). Workflows that need fork PRs must list exact `owner/repo` entries or deliberately trusted `owner/*` patterns, then recompile. Strict mode rejects any `"*"` entry, expressions, and other wildcard patterns; non-strict mode permits explicitly using `"*"` for unrestricted admission. Actor authorization and trusted-checkout restrictions remain mandatory in strict mode; `acknowledge-risk`, `checkout: false`, and trusted checkouts do not bypass fork admission. +Migration: omit `on.pull_request_target.forks` for same-repository PRs only (`forks: []` remains equivalent but is not required). Workflows that need fork PRs must explicitly configure admission and recompile. Prefer exact `owner/repo` entries or deliberately trusted `owner/*` patterns. Explicit `"*"` allows all forks in both modes; strict mode warns and recommends restricting forks instead of rejecting compilation. Strict mode still rejects expressions and unsupported pattern forms. Actor authorization and trusted-checkout restrictions remain mandatory in strict mode; `acknowledge-risk`, `checkout: false`, and trusted checkouts neither bypass them nor suppress the unrestricted-forks warning. diff --git a/CHANGELOG.md b/CHANGELOG.md index ef01cc922c0..2c5cfa1a489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,12 +16,13 @@ and mixed edits continue to require write-or-higher repository permission. `pull_request_target` workflows now default to same-repository PRs only in both strict and non-strict mode. Omitting `forks` is equivalent to `forks: []`; no explicit empty list is required. To admit forks, configure exact `owner/repo` -entries or deliberately trusted `owner/*` patterns, then recompile. Strict mode -rejects any `"*"` entry, expressions, and other wildcard patterns; non-strict -mode permits explicitly using `"*"` for unrestricted admission. Actor +entries or deliberately trusted `owner/*` patterns, then recompile. Explicit +`"*"` permits unrestricted admission in both modes; strict mode warns and +recommends restricting forks instead of rejecting compilation. Strict mode still +rejects expressions and unsupported pattern forms. Actor authorization and trusted-checkout restrictions remain mandatory in strict mode; `acknowledge-risk`, disabled checkout, and trusted checkout policies do not bypass -fork admission. +fork-pattern validation or suppress the unrestricted-forks warning. The `gh aw outcomes` command has been removed. Use `gh aw logs --outcomes` to evaluate selected runs, or pipe a run ID to diff --git a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md index b5fcc64049b..859c613bd1c 100644 --- a/docs/adr/72579-apply-fork-filters-to-pull-request-target.md +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -1,4 +1,4 @@ -# ADR-72579: Compile PR Fork Filters and Require Bounded Target Admission +# ADR-72579: Compile PR Fork Filters With Same-Repository Defaults **Date**: 2026-10-27 **Status**: Proposed @@ -10,11 +10,11 @@ gh-aw supports compiler-only `forks:` filters under both PR events and label-name filters (`names:`) under `on.pull_request`; these belong in job conditions, not native GitHub Actions trigger properties. The on-section cleanup state machine (`pkg/workflow/frontmatter_on_section_cleanup.go`) checked for the next event before leaving compiler-only subsections such as `on.permissions`, `on.steps`, or `on.skip-author-associations`, so filters after those fields could leak into lock files and fail Actions schema validation. Separately, `applyPullRequestForkFilter` (`pkg/workflow/filters.go`) read only `on.pull_request`, silently ignoring explicit `pull_request_target.forks` restrictions. -Security review also identified that omitted target fork filters previously admitted arbitrary forks, like `"*"`. Trusted actor authorization is insufficient: a maintainer can label an attacker-controlled PR, and an agent can consume malicious PR content with privileged capabilities even when checkout is disabled. The target event therefore needs the same same-repository default as `pull_request`, and strict mode must reject unrestricted patterns independently of actor authorization, checkout policy, and risk acknowledgment. +Security review also identified that omitted target fork filters previously admitted arbitrary forks, like `"*"`. Trusted actor authorization is insufficient: a maintainer can label an attacker-controlled PR, and an agent can consume malicious PR content with privileged capabilities even when checkout is disabled. The target event therefore needs the same same-repository default as `pull_request`, and strict mode should warn on explicitly unrestricted admission independently of actor authorization, checkout policy, and risk acknowledgment. ### Decision -The compiler will apply fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. For `pull_request_target`, omission and `forks: []` both admit only same-repository PRs, in strict and non-strict mode, including scalar trigger shorthand. Explicit patterns always admit same-repository PRs. Strict-mode target workflows may admit forks through exact `owner/repo` entries or deliberately trusted `owner/*` patterns; `"*"` anywhere in a list, expressions, and other wildcard patterns are rejected before checkout exemptions. Neither `acknowledge-risk` nor trusted/disabled checkout bypasses admission; actor authorization and checkout restrictions remain mandatory. Non-strict mode permits explicitly using `"*"` for unrestricted target admission. The same-repository default for configured `pull_request` event objects is unchanged. +The compiler will apply fork filters to both `pull_request` and `pull_request_target` using event-scoped job conditions (`github.event_name != '' || ...`), while preserving existing conditions and commenting out processed trigger fields. For `pull_request_target`, omission and `forks: []` both admit only same-repository PRs, in strict and non-strict mode, including scalar trigger shorthand. Explicit patterns always admit same-repository PRs. Target workflows may admit forks through exact `owner/repo` entries or deliberately trusted `owner/*` patterns. Explicit `"*"` permits unrestricted admission in both modes; strict mode warns and recommends restricting forks instead of rejecting compilation. Neither `acknowledge-risk` nor trusted/disabled checkout suppresses that warning. Actor authorization and checkout restrictions remain mandatory, and strict mode still rejects expressions and unsupported pattern forms. The same-repository default for configured `pull_request` event objects is unchanged. The supported frontmatter schema in `pkg/parser/schemas/main_workflow_schema.json` accepts string and list patterns for both events, but accepts the `forks: {author-association: [...]}` form from [ADR-69374](69374-fork-pr-admission-by-author-association.md) only for `pull_request`; the shared helper's ability to process that object does not make it supported for `pull_request_target`, and this decision does not extend the schema. To produce valid lock files without silently dropping configured admission rules, the cleanup state machine will leave compiler-only subsections before detecting the next event and track `forks` indentation for nested content, including the supported two-space and four-space event layouts. @@ -32,21 +32,25 @@ Requiring `forks: []` would make every strict target workflow state its admissio A narrower bug fix would remove the leaked keys and leave admission logic alone. It was rejected because removing `forks` from `pull_request_target` without compiling it into a condition would make the silent drop permanent. The author would get a lock file that looks valid but does not enforce the restriction they configured. +#### Alternative 4: Reject unrestricted fork admission in strict mode + +Rejecting `"*"` would force bounded admission, but would also prevent existing explicitly unrestricted workflows from compiling. A strict-mode warning preserves that explicit choice while recommending narrower fork trust and retaining actor and checkout safeguards. + ### Consequences #### Positive - Recognizing PR events after compiler-only `on.*` fields prevents `forks`/`names` from leaking into native triggers and failing Actions schema validation. - An explicit `forks:` pattern under `pull_request_target` is now enforced as an event-scoped job condition instead of being ignored. - Event-scoped guards let workflows that set both PR events use independent fork filters, and existing `if:` and label (`names`) conditions are kept. -- Strict-mode target workflows cannot silently admit arbitrary forks, including through risk acknowledgment or checkout exemptions. +- Strict-mode target workflows warn on explicitly unrestricted fork admission, including with risk acknowledgment or checkout exemptions. #### Negative -- Existing target workflows that omitted `forks` and relied on unrestricted admission must configure the intended fork patterns and recompile. Strict-mode workflows using unrestricted patterns must migrate to bounded admission. This is documented as a breaking change. +- Existing target workflows that omitted `forks` and relied on unrestricted admission must configure the intended fork patterns and recompile. This is documented as a breaking change. - Recompiling workflows that already had a `forks:` key under `pull_request_target` will start enforcing it. This could stop runs that previously, and unintentionally, admitted all forks. - The line-oriented cleanup state machine depends on event-ordering logic and indent tracking, which remain fragile compared with editing the YAML AST. - The author-association object form remains unavailable for `pull_request_target`, despite the shared helper accepting it internally. #### Neutral - The [trigger reference](../src/content/docs/reference/triggers.md) describes the `pull_request_target` pattern-filter semantics explicitly. -- Regression tests in `pkg/workflow/filters_forks_test.go`, `pkg/workflow/frontmatter_on_section_cleanup_test.go`, and `pkg/workflow/pull_request_target_forks_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, indentation, strict bounded admission, same-repository defaults, and non-strict wildcard support. +- Regression tests in `pkg/workflow/filters_forks_test.go`, `pkg/workflow/frontmatter_on_section_cleanup_test.go`, and `pkg/workflow/pull_request_target_forks_test.go` cover fork conditions, generated Actions schema validation, compiler-only field ordering, indentation, strict pattern validation, same-repository defaults, and wildcard warnings without weakening actor or checkout checks. - Fork admission does not grant permissions or secrets and does not make checking out or executing untrusted fork code safe. diff --git a/docs/src/content/docs/reference/checkout.md b/docs/src/content/docs/reference/checkout.md index 596ebfe833e..8e523a3f734 100644 --- a/docs/src/content/docs/reference/checkout.md +++ b/docs/src/content/docs/reference/checkout.md @@ -279,7 +279,7 @@ checkout: `on.pull_request_target.allowed-checkouts` defaults to no additional trusted checkouts. Each entry requires a literal `owner/repository` and a non-empty literal branch, tag, or commit SHA. Matching is exact and case-sensitive; repository/ref pairs cannot be combined across entries. Expressions, wildcards, and `refs/pull/...` refs are rejected in the policy. Every configured checkout must independently satisfy the policy or the existing base-checkout rules. Do not configure `checkout.fetch` for these checkouts: follow-up fetches can add refs beyond the trusted checkout, so they do not satisfy the policy. External repositories with omitted or PR-dependent refs remain rejected. Wiki checkouts are not covered by this allowlist. -`on.pull_request_target.acknowledge-risk` defaults to `false`. Setting it to `true` suppresses **only** the strict-mode dangerous-trigger warning, including for `checkout: false` or a supported base checkout. It neither allows other checkouts nor bypasses [bounded fork admission](/gh-aw/reference/triggers/#fork-filtering-forks), actor authorization, unrelated warnings, strict validation, or safe-update checks. An allowlist without acknowledgment still emits the trigger warning. +`on.pull_request_target.acknowledge-risk` defaults to `false`. Setting it to `true` suppresses **only** the strict-mode dangerous-trigger warning, including for `checkout: false` or a supported base checkout. It neither allows other checkouts nor bypasses [fork-pattern validation](/gh-aw/reference/triggers/#fork-filtering-forks), actor authorization, the unrestricted-forks warning, other strict validation, or safe-update checks. An allowlist without acknowledgment still emits the trigger warning. > [!CAUTION] > This policy records maintainer trust, not proof that checked-out code is safe. Prefer immutable commit SHAs; literal branches and tags can move. Keep workflow code and helpers on trusted base refs, read source PR changes as data, and never execute PR-controlled code with privileged credentials. Checkout authentication (`github-app` or `github-token`) and safe-output publication must still be configured separately. This example illustrates compilation policy, not runtime authentication or publication validation. diff --git a/docs/src/content/docs/reference/frontmatter-full.md b/docs/src/content/docs/reference/frontmatter-full.md index 443baada13a..a617edb412f 100644 --- a/docs/src/content/docs/reference/frontmatter-full.md +++ b/docs/src/content/docs/reference/frontmatter-full.md @@ -794,13 +794,14 @@ on: draft: true # Filter fork pull requests by repository pattern (string or list). Omission and - # an empty list both allow only same-repository PRs. Strict mode permits exact - # owner/repo entries or trusted owner/* patterns and rejects any '*' entry, - # expressions, and other patterns. Non-strict mode permits '*' to allow all forks. + # an empty list both allow only same-repository PRs. Exact owner/repo entries or + # trusted owner/* patterns admit matching forks; '*' allows all forks. Strict mode + # warns on any '*' entry and recommends narrower admission, but compilation + # continues. Strict mode rejects expressions and unsupported pattern forms. # Same-repository PRs remain allowed. Actor authorization and checkout - # restrictions remain mandatory in strict mode; acknowledge-risk does not bypass - # them. This does not change GitHub's base-repository permissions or secret - # availability for pull_request_target. + # restrictions remain mandatory in strict mode; acknowledge-risk neither bypasses + # them nor suppresses the fork warning. This does not change GitHub's + # base-repository permissions or secret availability for pull_request_target. # (optional) # Accepted formats: @@ -812,8 +813,9 @@ on: # Array items: string # Acknowledge elevated permissions and secret access to suppress only the - # strict-mode pull_request_target trigger warning. Bounded fork admission, actor - # authorization, and checkout validation remain enforced. + # strict-mode pull_request_target trigger warning. The unrestricted-forks warning, + # actor authorization, fork-pattern validation, and checkout validation remain + # enforced. # (optional) acknowledge-risk: true diff --git a/docs/src/content/docs/reference/triggers.md b/docs/src/content/docs/reference/triggers.md index bd77b18860c..b2068f59d79 100644 --- a/docs/src/content/docs/reference/triggers.md +++ b/docs/src/content/docs/reference/triggers.md @@ -207,9 +207,9 @@ Use `["owner/repo"]` for a specific repository, `["owner/*"]` for an entire org/ Alternatively, use `forks: {author-association: [OWNER, MEMBER, COLLABORATOR]}` to allow fork PRs by the author's relationship to the base repository rather than the fork owner. Same-repository PRs remain allowed, and no association is implicitly included. See [author associations](/gh-aw/reference/fork-support/#author-associations) for trust and secret-availability considerations. -`pull_request_target` also defaults to same-repository PRs only: omitting `forks:` is equivalent to `forks: []` in both strict and non-strict mode. To admit forks in strict mode, list exact `owner/repo` entries or deliberately trusted `owner/*` patterns. Same-repository PRs remain allowed. `"*"` and any list containing `"*"` are rejected in strict mode, as are expressions and other wildcard patterns. This restriction applies even with `checkout: false`, trusted checkouts, or `acknowledge-risk: true`; actor authorization and checkout restrictions remain enforced independently. +`pull_request_target` also defaults to same-repository PRs only: omitting `forks:` is equivalent to `forks: []` in both strict and non-strict mode. To admit specific forks, list exact `owner/repo` entries or deliberately trusted `owner/*` patterns. Same-repository PRs remain allowed. `"*"` anywhere in a list permits all forks; strict mode warns and recommends restricting fork admission instead of rejecting compilation. `acknowledge-risk: true`, disabled checkout, and trusted checkouts do not suppress this fork warning. Actor authorization and checkout restrictions remain enforced independently; strict mode still rejects expressions and unsupported pattern forms. -Non-strict mode permits explicitly including `"*"` to remove the fork restriction. Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. Bounded fork admission is defense in depth, not proof of safe PR content: a trusted actor can label an attacker-controlled PR, and disabling checkout does not prevent an agent from reading malicious content with privileged capabilities. +Fork filters and `pull_request.names` compile into job conditions, not GitHub Actions trigger properties. Bounded fork admission is defense in depth, not proof of safe PR content: a trusted actor can label an attacker-controlled PR, and disabling checkout does not prevent an agent from reading malicious content with privileged capabilities. #### Stacked PR Filtering (`max-stack:`) diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index 9f753bf940a..93377403d5e 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -2044,12 +2044,12 @@ } } ], - "description": "Filter fork pull requests by repository pattern (string or list). Omission and an empty list both allow only same-repository PRs. Strict mode permits exact owner/repo entries or trusted owner/* patterns and rejects any '*' entry, expressions, and other patterns. Non-strict mode permits '*' to allow all forks. Same-repository PRs remain allowed. Actor authorization and checkout restrictions remain mandatory in strict mode; acknowledge-risk does not bypass them. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." + "description": "Filter fork pull requests by repository pattern (string or list). Omission and an empty list both allow only same-repository PRs. Exact owner/repo entries or trusted owner/* patterns admit matching forks; '*' allows all forks. Strict mode warns on any '*' entry and recommends narrower admission, but compilation continues. Strict mode rejects expressions and unsupported pattern forms. Same-repository PRs remain allowed. Actor authorization and checkout restrictions remain mandatory in strict mode; acknowledge-risk neither bypasses them nor suppresses the fork warning. This does not change GitHub's base-repository permissions or secret availability for pull_request_target." }, "acknowledge-risk": { "type": "boolean", "default": false, - "description": "Acknowledge elevated permissions and secret access to suppress only the strict-mode pull_request_target trigger warning. Bounded fork admission, actor authorization, and checkout validation remain enforced." + "description": "Acknowledge elevated permissions and secret access to suppress only the strict-mode pull_request_target trigger warning. The unrestricted-forks warning, actor authorization, fork-pattern validation, and checkout validation remain enforced." }, "allowed-checkouts": { "type": "array", diff --git a/pkg/workflow/filters_forks_test.go b/pkg/workflow/filters_forks_test.go index 928e2391a0e..ecea7f0e073 100644 --- a/pkg/workflow/filters_forks_test.go +++ b/pkg/workflow/filters_forks_test.go @@ -31,14 +31,10 @@ func TestTriggerForkFilterCompilation(t *testing.T) { for _, tt := range tests { t.Run(event+"/"+tt.name, func(t *testing.T) { names := "" - strict := true if event == "pull_request" { names = "\n names: [community-contribution]" - } else if tt.expected == "" { - strict = false } source := fmt.Sprintf(`--- -strict: %t if: ${{ github.event.repository.fork == false }} on: permissions: {} @@ -55,7 +51,7 @@ network: allowed: [defaults] --- Review the contribution. -`, strict, event, tt.forks, names) +`, event, tt.forks, names) compiled := compileTriggerFilterFixture(t, source) on := compiled["on"].(map[string]any) assert.Equal(t, map[string]any{"types": []any{"labeled"}, "branches": []any{"main"}}, on[event]) diff --git a/pkg/workflow/pull_request_target_forks_test.go b/pkg/workflow/pull_request_target_forks_test.go index 2d04d507e3d..8fbcbaf2cc3 100644 --- a/pkg/workflow/pull_request_target_forks_test.go +++ b/pkg/workflow/pull_request_target_forks_test.go @@ -20,10 +20,10 @@ func TestPullRequestTargetBoundedForkAdmission(t *testing.T) { allows bool }{ {"omitted", "", true}, - {"wildcard string", "'*'", false}, - {"wildcard list", "['*']", false}, - {"mixed wildcard", "[trusted/repo, '*']", false}, - {"wildcard first", "['*', trusted/repo]", false}, + {"wildcard string", "'*'", true}, + {"wildcard list", "['*']", true}, + {"mixed wildcard", "[trusted/repo, '*']", true}, + {"wildcard first", "['*', trusted/repo]", true}, {"empty list", "[]", true}, {"exact string", "trusted/repo", true}, {"owner string", "'trusted/*'", true}, @@ -62,7 +62,7 @@ Review the contribution. require.NoError(t, os.WriteFile(file, []byte(source), 0600)) err := NewCompiler().CompileWorkflow(file) if strict && !tt.allows { - require.ErrorContains(t, err, "requires bounded fork admission") + require.ErrorContains(t, err, "requires supported fork patterns") assert.Contains(t, err.Error(), "acknowledge-risk do not bypass") assert.NoFileExists(t, filepath.Join(filepath.Dir(file), "workflow.lock.yml")) } else { @@ -79,7 +79,7 @@ strict: false on: pull_request_target: acknowledge-risk: true - forks: ["*"] + forks: ["trusted/repo*"] checkout: ref: ${{ github.event.pull_request.base.sha }} tools: @@ -91,7 +91,7 @@ Review the contribution. require.NoError(t, os.WriteFile(file, []byte(source), 0600)) compiler := NewCompiler() compiler.SetStrictMode(true) - require.ErrorContains(t, compiler.CompileWorkflow(file), "requires bounded fork admission") + require.ErrorContains(t, compiler.CompileWorkflow(file), "requires supported fork patterns") } func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { @@ -120,12 +120,62 @@ func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { } } -func TestHasBoundedPullRequestTargetForksRejectsMalformedValues(t *testing.T) { - for _, forks := range []any{nil, true, 1, []any{nil}, []any{true}, []any{"trusted/repo", "*"}, map[string]any{"author-association": []any{"OWNER"}}} { - assert.False(t, hasBoundedPullRequestTargetForks(map[string]any{ +func TestHasSupportedPullRequestTargetForksRejectsMalformedValues(t *testing.T) { + for _, forks := range []any{nil, true, 1, []any{nil}, []any{true}, []any{"*", "trusted/repo*"}, map[string]any{"author-association": []any{"OWNER"}}} { + assert.False(t, hasSupportedPullRequestTargetForks(map[string]any{ "on": map[string]any{ "pull_request_target": map[string]any{"forks": forks}, }, }), "forks: %#v", forks) } } + +func TestPullRequestTargetWildcardWarning(t *testing.T) { + for _, forks := range []any{"*", []any{"*"}, []any{"trusted/repo", "*"}, []any{"*", "trusted/*"}} { + for _, strict := range []bool{false, true} { + compiler := NewCompiler() + frontmatter := map[string]any{ + "strict": strict, + "on": map[string]any{ + "pull_request_target": map[string]any{ + "forks": forks, + "acknowledge-risk": true, + }, + }, + } + data := &WorkflowData{ + On: "on:\n pull_request_target:\n types: [labeled]", + RawFrontmatter: frontmatter, + CheckoutExplicitlyDisabled: true, + Roles: []string{"admin", "maintainer", "write"}, + } + output := testutil.CaptureStderr(t, func() { + require.NoError(t, compiler.validatePullRequestTargetTrigger(data, "workflow.md")) + }) + if strict { + assert.Equal(t, 1, compiler.GetWarningCount(), "forks: %#v", forks) + assert.Contains(t, output, "Prefer restricting forks") + assert.Contains(t, output, "acknowledge-risk does not suppress") + } else { + assert.Zero(t, compiler.GetWarningCount()) + assert.Empty(t, output) + } + compiler.ResetWarningCount() + data.CheckoutExplicitlyDisabled = false + err := compiler.validatePullRequestTargetTrigger(data, "workflow.md") + if strict { + require.ErrorContains(t, err, "checkout enabled is extremely insecure") + } else { + require.NoError(t, err) + } + data.CheckoutExplicitlyDisabled = true + data.Roles = []string{"all"} + err = compiler.validatePullRequestTargetTrigger(data, "workflow.md") + if strict { + require.ErrorContains(t, err, "on.roles containing 'all' or 'read'") + } else { + require.NoError(t, err) + } + } + } +} diff --git a/pkg/workflow/pull_request_target_validation.go b/pkg/workflow/pull_request_target_validation.go index da3f56b210c..25bdf33bb86 100644 --- a/pkg/workflow/pull_request_target_validation.go +++ b/pkg/workflow/pull_request_target_validation.go @@ -20,8 +20,8 @@ // 3. With on.roles containing all or read: reject in strict mode and warn in // non-strict mode, regardless of checkout or trigger risk acknowledgment. // -// 4. In strict mode, require bounded fork admission regardless of -// checkout or trigger risk acknowledgment. +// 4. In strict mode, warn about unrestricted fork admission and recommend +// bounded patterns regardless of checkout or trigger risk acknowledgment. // // # References // @@ -42,6 +42,7 @@ import ( "fmt" "os" "regexp" + "slices" "strings" "github.com/goccy/go-yaml" @@ -119,27 +120,44 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, } break } - if effectiveStrictMode && !hasBoundedPullRequestTargetForks(workflowData.RawFrontmatter) { + if effectiveStrictMode && !hasSupportedPullRequestTargetForks(workflowData.RawFrontmatter) { return formatCompilerError(markdownPath, "error", - "pull_request_target requires bounded fork admission in strict mode.\n"+ + "pull_request_target requires supported fork patterns in strict mode.\n"+ "Omit on.pull_request_target.forks for same-repository PRs only, or list exact\n"+ - "repositories (owner/repo) or trusted owner/* patterns. '*' (including\n"+ - "inside a list), expressions, and other patterns are not allowed.\n"+ + "repositories (owner/repo) or trusted owner/* patterns. Expressions and other\n"+ + "unsupported patterns are not allowed.\n"+ "Trusted event actors can still act on attacker-controlled PR content.\n"+ "checkout: false and on.pull_request_target.acknowledge-risk do not bypass this requirement.\n"+ "Actor authorization and trusted-checkout restrictions remain mandatory.", nil) } var acknowledged bool + var unrestrictedForks bool var allowedCheckouts []any if on, ok := workflowData.RawFrontmatter["on"].(map[string]any); ok { if trigger, ok := on["pull_request_target"].(map[string]any); ok { acknowledged = trigger["acknowledge-risk"] == true + switch forks := trigger["forks"].(type) { + case string: + unrestrictedForks = forks == "*" + case []any: + unrestrictedForks = slices.Contains(forks, any("*")) + } if entries, ok := trigger["allowed-checkouts"].([]any); ok { allowedCheckouts = entries } } } + if effectiveStrictMode && unrestrictedForks { + message := "pull_request_target.forks contains '*' and allows PRs from any fork.\n" + + "Prefer restricting forks to exact owner/repo entries or deliberately trusted owner/* patterns.\n" + + "Omit forks (or use forks: []) for same-repository PRs only.\n" + + "Trusted event actors can still act on attacker-controlled PR content, even with checkout disabled.\n" + + "acknowledge-risk does not suppress this warning; actor authorization and checkout restrictions remain enforced." + fmt.Fprintln(os.Stderr, formatCompilerMessage(markdownPath, "warning", message)) + c.IncrementWarningCount() + } + // In strict mode, emit a warning unless the trigger-specific risk is acknowledged, // regardless of whether checkout is disabled. The workflow still runs with full write // permissions and has access to all repository secrets. @@ -204,7 +222,7 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, return nil } -func hasBoundedPullRequestTargetForks(frontmatter map[string]any) bool { +func hasSupportedPullRequestTargetForks(frontmatter map[string]any) bool { if on, ok := frontmatter["on"].(string); ok { return on == "pull_request_target" } @@ -221,11 +239,11 @@ func hasBoundedPullRequestTargetForks(frontmatter map[string]any) bool { } switch forks := trigger["forks"].(type) { case string: - return boundedForkPattern.MatchString(forks) + return forks == "*" || boundedForkPattern.MatchString(forks) case []any: for _, fork := range forks { pattern, ok := fork.(string) - if !ok || !boundedForkPattern.MatchString(pattern) { + if !ok || (pattern != "*" && !boundedForkPattern.MatchString(pattern)) { return false } }