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..56253cfe61c --- /dev/null +++ b/.changeset/strict-pull-request-target-bounded-forks.md @@ -0,0 +1,7 @@ +--- +"gh-aw": major +--- + +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 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 bf685e51a6f..2c5cfa1a489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,17 @@ and mixed edits continue to require write-or-higher repository permission. ### Breaking changes +`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. 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-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 `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 new file mode 100644 index 00000000000..859c613bd1c --- /dev/null +++ b/docs/adr/72579-apply-fork-filters-to-pull-request-target.md @@ -0,0 +1,56 @@ +# ADR-72579: Compile PR Fork Filters With Same-Repository Defaults + +**Date**: 2026-10-27 +**Status**: Proposed +**Deciders**: Unknown (PR #72579) + +--- + +### 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. + +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. 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. + +### 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: Require an explicit empty fork list in strict mode + +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 + +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 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. 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 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 f312d31b82b..8e523a3f734 100644 --- a/docs/src/content/docs/reference/checkout.md +++ b/docs/src/content/docs/reference/checkout.md @@ -263,6 +263,7 @@ on: pull_request_target: types: [closed] branches: [main] + forks: ["dotnet/*"] acknowledge-risk: true allowed-checkouts: - repository: dotnet/AspNetCore.Docs @@ -278,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 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 [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 d8355aaffde..a617edb412f 100644 --- a/docs/src/content/docs/reference/frontmatter-full.md +++ b/docs/src/content/docs/reference/frontmatter-full.md @@ -793,9 +793,15 @@ 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). 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. # (optional) # Accepted formats: @@ -807,7 +813,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 + # 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 e5edeca4197..b2068f59d79 100644 --- a/docs/src/content/docs/reference/triggers.md +++ b/docs/src/content/docs/reference/triggers.md @@ -194,7 +194,7 @@ GitHub's fork-contributor workflow approval setting does not protect `pull_reque #### 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: @@ -207,6 +207,10 @@ 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 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. + +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:`) 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/go.sum b/go.sum index 78656ca6798..377fda3a589 100644 --- a/go.sum +++ b/go.sum @@ -244,8 +244,6 @@ 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= diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index e6bc1ce3768..93377403d5e 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -2044,12 +2044,12 @@ } } ], - "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). 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. Checkout validation remains 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.go b/pkg/workflow/filters.go index 5036169877a..677c0a6183a 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, 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,36 +127,36 @@ 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 } - // 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"} { + event, exists := onMap[eventName] + if !exists { + continue + } + prMap, ok := event.(map[string]any) + if !ok && (eventName != "pull_request_target" || event != nil) { + 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 +174,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 +201,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..ecea7f0e073 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,175 @@ import ( "github.com/stretchr/testify/require" ) +func TestTriggerForkFilterCompilation(t *testing.T) { + tests := []struct { + name string + 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'"}, + {"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 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 + 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") + 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 +218,22 @@ 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+"'") + 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 +280,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..2e54459dbcf 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,10 +63,12 @@ type onSectionCleanupState struct { inWorkflowRun bool inWorkflowRunConclusionArray bool inForksArray bool + forksIndent int inSkipIfMatch bool inSkipIfNoMatch bool inSkipIfCheckFailing bool inSkipAuthorAssociations bool + skipAuthorAssociationsIndent int inSkipRolesArray bool inSkipBotsArray bool inRolesArray bool @@ -77,7 +79,9 @@ type onSectionCleanupState struct { allowedCheckoutsIndent int inGitHubApp bool inOnSteps bool + onStepsIndent int inOnPermissions bool + onPermissionsIndent int commentBlockIndent string inCommentBlock bool currentSection string @@ -264,8 +268,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 @@ -287,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 } } @@ -308,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"))) { @@ -322,25 +330,25 @@ 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 } } 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) { @@ -364,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, "#") } @@ -555,9 +563,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..9dc5e8562ab 100644 --- a/pkg/workflow/frontmatter_on_section_cleanup_test.go +++ b/pkg/workflow/frontmatter_on_section_cleanup_test.go @@ -3,10 +3,87 @@ 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 _, 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/* +%s types: + - labeled + branches: + - main + paths: + - src/** + workflow_dispatch: +`, 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]) + }) + } + } + } +} + +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 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..8fbcbaf2cc3 --- /dev/null +++ b/pkg/workflow/pull_request_target_forks_test.go @@ -0,0 +1,181 @@ +//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", "", true}, + {"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}, + {"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 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 { + require.NoError(t, err) + } + }) + } + } +} + +func TestPullRequestTargetBoundedForkAdmissionCLIOverride(t *testing.T) { + source := `--- +strict: false +on: + pull_request_target: + acknowledge-risk: true + forks: ["trusted/repo*"] +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 supported fork patterns") +} + +func TestPullRequestTargetBoundedForkAdmissionShorthand(t *testing.T) { + for _, tt := range []struct { + on string + wantError string + }{ + {"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: {}", ""}, + } { + 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)) + 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) + } + }) + } +} + +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 74cb7f43ed1..25bdf33bb86 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, warn about unrestricted fork admission and recommend +// bounded patterns regardless of checkout or trigger risk acknowledgment. +// // # References // // See: https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/ @@ -38,6 +41,8 @@ package workflow import ( "fmt" "os" + "regexp" + "slices" "strings" "github.com/goccy/go-yaml" @@ -49,6 +54,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 +94,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,17 +120,44 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, } break } + if effectiveStrictMode && !hasSupportedPullRequestTargetForks(workflowData.RawFrontmatter) { + return formatCompilerError(markdownPath, "error", + "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. 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. @@ -194,6 +222,37 @@ func (c *Compiler) validatePullRequestTargetTrigger(workflowData *WorkflowData, return nil } +func hasSupportedPullRequestTargetForks(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 + } + trigger, ok := on["pull_request_target"].(map[string]any) + if !ok { + return false + } + if _, hasForks := trigger["forks"]; !hasForks { + return true + } + switch forks := trigger["forks"].(type) { + case string: + return forks == "*" || boundedForkPattern.MatchString(forks) + case []any: + for _, fork := range forks { + pattern, ok := fork.(string) + if !ok || (pattern != "*" && !boundedForkPattern.MatchString(pattern)) { + return false + } + } + return true + default: + return false + } +} + func dangerouslyAllowsRolesReadAndPullRequestTarget(workflowData *WorkflowData) bool { value, found := getFeatureValueCaseInsensitive( workflowData.Features,