From a8130d58b26536c98a5fdd905d004016e50d32e2 Mon Sep 17 00:00:00 2001 From: rcooney Date: Tue, 27 Oct 2026 03:44:27 +0000 Subject: [PATCH] Refuse fork PR checkouts in pull_request_target/workflow_run unless allow-unsafe-pr-checkout is set Ports upstream actions/checkout's unsafe-pr-checkout-helper and its tests so a pull_request_target or workflow_run job cannot check out a fork's code with the base repository's secrets and token unless the step opts in, matching the guard upstream has shipped since v4.4.0 / v5.1.0. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 1 + __test__/git-auth-helper.test.ts | 3 +- __test__/unsafe-pr-checkout-helper.test.ts | 256 ++++++++++++++++++++ action.yml | 265 +++++++++++---------- dist/index.js | 118 +++++++++ src/git-source-settings.ts | 6 + src/input-helper.ts | 20 ++ src/ref-helper.ts | 2 +- src/unsafe-pr-checkout-helper.ts | 88 +++++++ 9 files changed, 629 insertions(+), 130 deletions(-) create mode 100644 __test__/unsafe-pr-checkout-helper.test.ts create mode 100644 src/unsafe-pr-checkout-helper.ts diff --git a/README.md b/README.md index 9e993ad..b752f5c 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,7 @@ In addition to all upstream `actions/checkout` inputs, this action provides: | `dissociate` | `false` | Copies objects from the mirror into the workspace so it no longer depends on the Sticky Disk mount. | | `allow-inside-container` | `false` | Attempts to use the Sticky Disk cache inside a container job whose runner devices have been passed through. | | `verbose` | `false` | Enables verbose Git tracing for mirror operations when debugging checkout or cache performance. | +| `allow-unsafe-pr-checkout` | `false` | Required to check out fork pull request code from a `pull_request_target` or `workflow_run` workflow, matching upstream `actions/checkout`. Those workflows run with the base repository's secrets and token, so review https://gh.io/securely-using-pull_request_target before enabling. | ## Documentation diff --git a/__test__/git-auth-helper.test.ts b/__test__/git-auth-helper.test.ts index 68c3021..f06d01e 100644 --- a/__test__/git-auth-helper.test.ts +++ b/__test__/git-auth-helper.test.ts @@ -1176,7 +1176,8 @@ async function setup(testName: string): Promise { setSafeDirectory: true, githubServerUrl: githubServerUrl, dissociate: false, - verbose: false + verbose: false, + allowUnsafePrCheckout: false } } diff --git a/__test__/unsafe-pr-checkout-helper.test.ts b/__test__/unsafe-pr-checkout-helper.test.ts new file mode 100644 index 0000000..8bf5797 --- /dev/null +++ b/__test__/unsafe-pr-checkout-helper.test.ts @@ -0,0 +1,256 @@ +import * as github from '@actions/github' +import {assertSafePrCheckout} from '../lib/unsafe-pr-checkout-helper' + +const BASE_REPO_ID = 100 +const FORK_REPO_ID = 200 +const PR_HEAD_SHA = '1111111111111111111111111111111111111111' +const PR_MERGE_SHA = '2222222222222222222222222222222222222222' +const SAFE_BASE_SHA = '3333333333333333333333333333333333333333' +const WORKFLOW_RUN_HEAD_COMMIT_SHA = '4444444444444444444444444444444444444444' +const BASE_QUALIFIED_REPO = 'some-owner/some-repo' +const FORK_QUALIFIED_REPO = 'another-repo/fork' + +const originalEventName = github.context.eventName +const originalPayload = github.context.payload + +function setContext(eventName: string, payload: object): void { + github.context.eventName = eventName + github.context.payload = payload +} + +function forkPullRequestTargetPayload(): object { + return { + repository: {id: BASE_REPO_ID}, + pull_request: { + head: { + sha: PR_HEAD_SHA, + repo: {id: FORK_REPO_ID, full_name: FORK_QUALIFIED_REPO} + }, + merge_commit_sha: PR_MERGE_SHA + } + } +} + +function sameRepoPullRequestTargetPayload(): object { + return { + repository: {id: BASE_REPO_ID}, + pull_request: { + head: { + sha: PR_HEAD_SHA, + repo: {id: BASE_REPO_ID, full_name: BASE_QUALIFIED_REPO} + }, + merge_commit_sha: PR_MERGE_SHA + } + } +} + +function forkWorkflowRunPayload(): object { + return { + repository: {id: BASE_REPO_ID}, + workflow_run: { + event: 'pull_request', + head_commit: {id: WORKFLOW_RUN_HEAD_COMMIT_SHA}, + head_repository: {id: FORK_REPO_ID, full_name: FORK_QUALIFIED_REPO} + } + } +} + +describe('unsafe-pr-checkout-helper', () => { + afterEach(() => { + github.context.eventName = originalEventName + github.context.payload = originalPayload + }) + + afterAll(() => { + github.context.eventName = originalEventName + github.context.payload = originalPayload + }) + + it('allows pull_request events untouched', () => { + setContext('pull_request', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: 'attacker/fork', + ref: 'refs/pull/1/merge', + commit: '', + allowUnsafePrCheckout: false + }) + ).not.toThrow() + }) + + it('allows pull_request_target default checkout (base branch)', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: 'refs/heads/main', + commit: SAFE_BASE_SHA, + allowUnsafePrCheckout: false + }) + ).not.toThrow() + }) + + it('allows same-repo pull_request_target checkout of PR head', () => { + setContext('pull_request_target', sameRepoPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: PR_HEAD_SHA, + allowUnsafePrCheckout: false + }) + ).not.toThrow() + }) + + it('refuses pull_request_target fork PR head SHA checkout', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: PR_HEAD_SHA, + allowUnsafePrCheckout: false + }) + ).toThrow(/Refusing to check out fork pull request code/) + }) + + it('refuses pull_request_target fork PR merge_commit_sha checkout', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: PR_MERGE_SHA, + allowUnsafePrCheckout: false + }) + ).toThrow(/allow-unsafe-pr-checkout/) + }) + + it('refuses pull_request_target fork PR ref pattern (head)', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: 'refs/pull/42/head', + commit: '', + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('refuses pull_request_target fork PR ref pattern (merge)', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: 'refs/pull/42/merge', + commit: '', + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('refuses pull_request_target when repository points at the fork', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: FORK_QUALIFIED_REPO, + ref: 'refs/heads/main', + commit: '', + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('allows pull_request_target checkout of an unrelated third-party repo', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: 'some-other/unrelated', + ref: 'refs/heads/main', + commit: '', + allowUnsafePrCheckout: false + }) + ).not.toThrow() + }) + + it('refuses pull_request_target ignoring repository case differences', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: FORK_QUALIFIED_REPO.toUpperCase(), + ref: '', + commit: '', + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('refuses pull_request_target ignoring commit SHA case differences', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: PR_HEAD_SHA.toUpperCase(), + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('allows pull_request_target fork PR checkout when opted in', () => { + setContext('pull_request_target', forkPullRequestTargetPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: 'refs/pull/42/merge', + commit: '', + allowUnsafePrCheckout: true + }) + ).not.toThrow() + }) + + it('refuses workflow_run fork PR head_commit.id checkout', () => { + setContext('workflow_run', forkWorkflowRunPayload()) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: WORKFLOW_RUN_HEAD_COMMIT_SHA, + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('refuses workflow_run with pull_request_target underlying event', () => { + const payload = forkWorkflowRunPayload() as { + workflow_run: {event: string} + } + payload.workflow_run.event = 'pull_request_target' + setContext('workflow_run', payload) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: WORKFLOW_RUN_HEAD_COMMIT_SHA, + allowUnsafePrCheckout: false + }) + ).toThrow() + }) + + it('allows workflow_run same-repo PR (head_repository.id matches base)', () => { + const payload = forkWorkflowRunPayload() as { + workflow_run: {head_repository: {id: number}} + } + payload.workflow_run.head_repository.id = BASE_REPO_ID + setContext('workflow_run', payload) + expect(() => + assertSafePrCheckout({ + qualifiedRepository: BASE_QUALIFIED_REPO, + ref: '', + commit: WORKFLOW_RUN_HEAD_COMMIT_SHA, + allowUnsafePrCheckout: false + }) + ).not.toThrow() + }) +}) diff --git a/action.yml b/action.yml index 4c4863e..a6615d8 100644 --- a/action.yml +++ b/action.yml @@ -1,128 +1,137 @@ -name: 'Checkout' -description: 'Checkout a Git repository at a particular version' -inputs: - repository: - description: 'Repository name with owner. For example, actions/checkout' - default: ${{ github.repository }} - ref: - description: > - The branch, tag or SHA to checkout. When checking out the repository that - triggered a workflow, this defaults to the reference or SHA for that - event. Otherwise, uses the default branch. - token: - description: > - Personal access token (PAT) used to fetch the repository. The PAT is configured - with the local git config, which enables your scripts to run authenticated git - commands. The post-job step removes the PAT. - - - We recommend using a service account with the least permissions necessary. - Also when generating a new PAT, select the least scopes necessary. - - - [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) - default: ${{ github.token }} - ssh-key: - description: > - SSH key used to fetch the repository. The SSH key is configured with the local - git config, which enables your scripts to run authenticated git commands. - The post-job step removes the SSH key. - - - We recommend using a service account with the least permissions necessary. - - - [Learn more about creating and using - encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) - ssh-known-hosts: - description: > - Known hosts in addition to the user and global host key database. The public - SSH keys for a host may be obtained using the utility `ssh-keyscan`. For example, - `ssh-keyscan github.com`. The public key for github.com is always implicitly added. - ssh-strict: - description: > - Whether to perform strict host key checking. When true, adds the options `StrictHostKeyChecking=yes` - and `CheckHostIP=no` to the SSH command line. Use the input `ssh-known-hosts` to - configure additional hosts. - default: true - ssh-user: - description: > - The user to use when connecting to the remote SSH host. By default 'git' is used. - default: git - persist-credentials: - description: 'Whether to configure the token or SSH key with the local git config' - default: true - path: - description: 'Relative path under $GITHUB_WORKSPACE to place the repository' - clean: - description: 'Whether to execute `git clean -ffdx && git reset --hard HEAD` before fetching' - default: true - filter: - description: > - Partially clone against a given filter. - Overrides sparse-checkout if set. - default: null - sparse-checkout: - description: > - Do a sparse checkout on given patterns. - Each pattern should be separated with new lines. - default: null - sparse-checkout-cone-mode: - description: > - Specifies whether to use cone-mode when doing a sparse checkout. - default: true - fetch-depth: - description: 'Number of commits to fetch. 0 indicates all history for all branches and tags.' - default: 1 - fetch-tags: - description: 'Whether to fetch tags, even if fetch-depth > 0.' - default: false - show-progress: - description: 'Whether to show progress status output when fetching.' - default: true - lfs: - description: 'Whether to download Git-LFS files' - default: false - submodules: - description: > - Whether to checkout submodules: `true` to checkout submodules or `recursive` to - recursively checkout submodules. - - - When the `ssh-key` input is not provided, SSH URLs beginning with `git@github.com:` are - converted to HTTPS. - default: false - set-safe-directory: - description: Add repository path as safe.directory for Git global config by running `git config --global --add safe.directory ` - default: true - github-server-url: - description: The base URL for the GitHub instance that you are trying to clone from, will use environment defaults to fetch from the same instance that the workflow is running from unless specified. Example URLs are https://github.com or https://my-ghes-server.example.com - required: false - dissociate: - description: > - Copy objects from Blacksmith git mirror cache to make checkout independent. - Use this when running Docker-based actions that may not have access to the mirror mount. - default: false - allow-inside-container: - description: > - Allow using the Blacksmith git mirror cache inside container jobs. - By default, container jobs skip the git mirror because the sticky disk - block device is not visible inside the container. Set this to true when - the container is started with the runner's devices passed through - (e.g. `options: --privileged -v /dev:/dev`). Can also be enabled via the - BLACKSMITH_ALLOW_INSIDE_CONTAINER=true environment variable. - default: false - verbose: - description: > - Enable verbose output for git mirror operations. Outputs GIT_TRACE and GIT_CURL_VERBOSE - for debugging connection and performance issues. - default: false -outputs: - ref: - description: 'The branch, tag or SHA that was checked out' - commit: - description: 'The commit SHA that was checked out' -runs: - using: node24 - main: dist/index.js - post: dist/index.js +name: 'Checkout' +description: 'Checkout a Git repository at a particular version' +inputs: + repository: + description: 'Repository name with owner. For example, actions/checkout' + default: ${{ github.repository }} + ref: + description: > + The branch, tag or SHA to checkout. When checking out the repository that + triggered a workflow, this defaults to the reference or SHA for that + event. Otherwise, uses the default branch. + token: + description: > + Personal access token (PAT) used to fetch the repository. The PAT is configured + with the local git config, which enables your scripts to run authenticated git + commands. The post-job step removes the PAT. + + + We recommend using a service account with the least permissions necessary. + Also when generating a new PAT, select the least scopes necessary. + + + [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) + default: ${{ github.token }} + ssh-key: + description: > + SSH key used to fetch the repository. The SSH key is configured with the local + git config, which enables your scripts to run authenticated git commands. + The post-job step removes the SSH key. + + + We recommend using a service account with the least permissions necessary. + + + [Learn more about creating and using + encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) + ssh-known-hosts: + description: > + Known hosts in addition to the user and global host key database. The public + SSH keys for a host may be obtained using the utility `ssh-keyscan`. For example, + `ssh-keyscan github.com`. The public key for github.com is always implicitly added. + ssh-strict: + description: > + Whether to perform strict host key checking. When true, adds the options `StrictHostKeyChecking=yes` + and `CheckHostIP=no` to the SSH command line. Use the input `ssh-known-hosts` to + configure additional hosts. + default: true + ssh-user: + description: > + The user to use when connecting to the remote SSH host. By default 'git' is used. + default: git + persist-credentials: + description: 'Whether to configure the token or SSH key with the local git config' + default: true + path: + description: 'Relative path under $GITHUB_WORKSPACE to place the repository' + clean: + description: 'Whether to execute `git clean -ffdx && git reset --hard HEAD` before fetching' + default: true + filter: + description: > + Partially clone against a given filter. + Overrides sparse-checkout if set. + default: null + sparse-checkout: + description: > + Do a sparse checkout on given patterns. + Each pattern should be separated with new lines. + default: null + sparse-checkout-cone-mode: + description: > + Specifies whether to use cone-mode when doing a sparse checkout. + default: true + fetch-depth: + description: 'Number of commits to fetch. 0 indicates all history for all branches and tags.' + default: 1 + fetch-tags: + description: 'Whether to fetch tags, even if fetch-depth > 0.' + default: false + show-progress: + description: 'Whether to show progress status output when fetching.' + default: true + lfs: + description: 'Whether to download Git-LFS files' + default: false + submodules: + description: > + Whether to checkout submodules: `true` to checkout submodules or `recursive` to + recursively checkout submodules. + + + When the `ssh-key` input is not provided, SSH URLs beginning with `git@github.com:` are + converted to HTTPS. + default: false + set-safe-directory: + description: Add repository path as safe.directory for Git global config by running `git config --global --add safe.directory ` + default: true + github-server-url: + description: The base URL for the GitHub instance that you are trying to clone from, will use environment defaults to fetch from the same instance that the workflow is running from unless specified. Example URLs are https://github.com or https://my-ghes-server.example.com + required: false + dissociate: + description: > + Copy objects from Blacksmith git mirror cache to make checkout independent. + Use this when running Docker-based actions that may not have access to the mirror mount. + default: false + allow-inside-container: + description: > + Allow using the Blacksmith git mirror cache inside container jobs. + By default, container jobs skip the git mirror because the sticky disk + block device is not visible inside the container. Set this to true when + the container is started with the runner's devices passed through + (e.g. `options: --privileged -v /dev:/dev`). Can also be enabled via the + BLACKSMITH_ALLOW_INSIDE_CONTAINER=true environment variable. + default: false + verbose: + description: > + Enable verbose output for git mirror operations. Outputs GIT_TRACE and GIT_CURL_VERBOSE + for debugging connection and performance issues. + default: false + allow-unsafe-pr-checkout: + description: > + Required to check out fork pull request code from a workflow triggered by + `pull_request_target` or `workflow_run`. These workflows run with the + base repository's GITHUB_TOKEN, secrets, default-branch cache scope, and + runner access; fetching and executing a fork's code in that trusted + context commonly leads to "pwn request" vulnerabilities. Set to `true` + only after reviewing the risks at https://gh.io/securely-using-pull_request_target. + default: false +outputs: + ref: + description: 'The branch, tag or SHA that was checked out' + commit: + description: 'The commit SHA that was checked out' +runs: + using: node24 + main: dist/index.js + post: dist/index.js diff --git a/dist/index.js b/dist/index.js index d1d1519..eae0bcd 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4388,6 +4388,7 @@ const fsHelper = __importStar(__nccwpck_require__(7219)); const github = __importStar(__nccwpck_require__(5438)); const path = __importStar(__nccwpck_require__(1017)); const workflowContextHelper = __importStar(__nccwpck_require__(9568)); +const unsafePrCheckoutHelper = __importStar(__nccwpck_require__(843)); function getInputs() { return __awaiter(this, void 0, void 0, function* () { const result = {}; @@ -4516,6 +4517,23 @@ function getInputs() { result.verbose = (core.getInput('verbose') || 'false').toUpperCase() === 'TRUE'; core.debug(`verbose = ${result.verbose}`); + result.allowUnsafePrCheckout = + (core.getInput('allow-unsafe-pr-checkout') || 'false').toUpperCase() === + 'TRUE'; + core.debug(`allow unsafe PR checkout = ${result.allowUnsafePrCheckout}`); + // The default self-checkout (this repository with no explicit ref) always + // resolves to the trusted ref/commit GitHub set for the triggering event, so + // the fork-checkout guard only needs to run when the caller customized the + // repository or ref. + const isDefaultCheckout = isWorkflowRepository && !core.getInput('ref'); + if (!isDefaultCheckout) { + unsafePrCheckoutHelper.assertSafePrCheckout({ + qualifiedRepository, + ref: result.ref, + commit: result.commit, + allowUnsafePrCheckout: result.allowUnsafePrCheckout + }); + } return result; }); } @@ -5149,6 +5167,7 @@ exports.getRefSpecForAllHistory = getRefSpecForAllHistory; exports.getRefSpec = getRefSpec; exports.testRef = testRef; exports.checkCommitInfo = checkCommitInfo; +exports.fromPayload = fromPayload; const core = __importStar(__nccwpck_require__(2186)); const github = __importStar(__nccwpck_require__(5438)); const url_helper_1 = __nccwpck_require__(9437); @@ -5933,6 +5952,105 @@ function hasAnyStepFailed(runnerBasePath) { } +/***/ }), + +/***/ 843: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertSafePrCheckout = assertSafePrCheckout; +const github = __importStar(__nccwpck_require__(5438)); +const ref_helper_1 = __nccwpck_require__(8601); +const PR_REF_PATTERN = /^refs\/pull\/[0-9]+\/(?:head|merge)$/; +function assertSafePrCheckout(input) { + if (input.allowUnsafePrCheckout) { + return; + } + const eventName = github.context.eventName; + if (eventName !== 'pull_request_target' && eventName !== 'workflow_run') { + return; + } + const baseRepoId = (0, ref_helper_1.fromPayload)('repository.id'); + if (typeof baseRepoId !== 'number') { + return; + } + let prHeadRepoId; + let prHeadRepoFullName; + const prShas = []; + if (eventName === 'pull_request_target') { + prHeadRepoId = (0, ref_helper_1.fromPayload)('pull_request.head.repo.id'); + prHeadRepoFullName = (0, ref_helper_1.fromPayload)('pull_request.head.repo.full_name'); + pushIfSha(prShas, (0, ref_helper_1.fromPayload)('pull_request.head.sha')); + pushIfSha(prShas, (0, ref_helper_1.fromPayload)('pull_request.merge_commit_sha')); + } + else { + const wrEvent = (0, ref_helper_1.fromPayload)('workflow_run.event'); + if (typeof wrEvent !== 'string' || !wrEvent.startsWith('pull_request')) { + return; + } + prHeadRepoId = (0, ref_helper_1.fromPayload)('workflow_run.head_repository.id'); + prHeadRepoFullName = (0, ref_helper_1.fromPayload)('workflow_run.head_repository.full_name'); + pushIfSha(prShas, (0, ref_helper_1.fromPayload)('workflow_run.head_commit.id')); + // For `pull_request_target`-triggered workflow_run, `head_sha` is the base + // default branch SHA (not the PR head) + if (wrEvent !== 'pull_request_target') { + pushIfSha(prShas, (0, ref_helper_1.fromPayload)('workflow_run.head_sha')); + } + } + // (A) Fork PR? + if (typeof prHeadRepoId !== 'number' || prHeadRepoId === baseRepoId) { + return; + } + // (B) We cannot check for all fork PR refs so check to see + // if the resolved input points to the fork PR sha we have in the payload + const repositoryMatchesPrHead = typeof prHeadRepoFullName === 'string' && + input.qualifiedRepository.toLowerCase() === prHeadRepoFullName.toLowerCase(); + const refMatchesPullPattern = PR_REF_PATTERN.test(input.ref); + const commitMatchesPrHeadSha = !!input.commit && prShas.includes(input.commit.toLowerCase()); + if (!repositoryMatchesPrHead && + !refMatchesPullPattern && + !commitMatchesPrHeadSha) { + return; + } + throw new Error(`Refusing to check out fork pull request code from a '${eventName}' workflow. ` + + `This workflow runs with the base repository's GITHUB_TOKEN, secrets, default-branch ` + + `cache scope, and runner access. Fetching and executing a fork's code in that trusted ` + + `context commonly leads to "pwn request" vulnerabilities. To opt in, review the risks ` + + `at https://gh.io/securely-using-pull_request_target and set 'allow-unsafe-pr-checkout: true' ` + + `on the actions/checkout step.`); +} +function pushIfSha(target, value) { + if (typeof value === 'string' && value.length > 0) { + target.push(value.toLowerCase()); + } +} + + /***/ }), /***/ 9437: diff --git a/src/git-source-settings.ts b/src/git-source-settings.ts index 093b95f..7cfb264 100644 --- a/src/git-source-settings.ts +++ b/src/git-source-settings.ts @@ -131,4 +131,10 @@ export interface IGitSourceSettings { * When true, outputs GIT_TRACE and GIT_CURL_VERBOSE for debugging. */ verbose: boolean + + /** + * Opt in to checking out fork pull request code from a `pull_request_target` + * or `workflow_run` workflow. See https://gh.io/securely-using-pull_request_target. + */ + allowUnsafePrCheckout: boolean } diff --git a/src/input-helper.ts b/src/input-helper.ts index a7e8b3e..0d3eef9 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -3,6 +3,7 @@ import * as fsHelper from './fs-helper' import * as github from '@actions/github' import * as path from 'path' import * as workflowContextHelper from './workflow-context-helper' +import * as unsafePrCheckoutHelper from './unsafe-pr-checkout-helper' import {IGitSourceSettings} from './git-source-settings' export async function getInputs(): Promise { @@ -171,5 +172,24 @@ export async function getInputs(): Promise { (core.getInput('verbose') || 'false').toUpperCase() === 'TRUE' core.debug(`verbose = ${result.verbose}`) + result.allowUnsafePrCheckout = + (core.getInput('allow-unsafe-pr-checkout') || 'false').toUpperCase() === + 'TRUE' + core.debug(`allow unsafe PR checkout = ${result.allowUnsafePrCheckout}`) + + // The default self-checkout (this repository with no explicit ref) always + // resolves to the trusted ref/commit GitHub set for the triggering event, so + // the fork-checkout guard only needs to run when the caller customized the + // repository or ref. + const isDefaultCheckout = isWorkflowRepository && !core.getInput('ref') + if (!isDefaultCheckout) { + unsafePrCheckoutHelper.assertSafePrCheckout({ + qualifiedRepository, + ref: result.ref, + commit: result.commit, + allowUnsafePrCheckout: result.allowUnsafePrCheckout + }) + } + return result } diff --git a/src/ref-helper.ts b/src/ref-helper.ts index 58f9290..925be86 100644 --- a/src/ref-helper.ts +++ b/src/ref-helper.ts @@ -268,7 +268,7 @@ export async function checkCommitInfo( } } -function fromPayload(path: string): any { +export function fromPayload(path: string): any { return select(github.context.payload, path) } diff --git a/src/unsafe-pr-checkout-helper.ts b/src/unsafe-pr-checkout-helper.ts new file mode 100644 index 0000000..f6bf389 --- /dev/null +++ b/src/unsafe-pr-checkout-helper.ts @@ -0,0 +1,88 @@ +import * as github from '@actions/github' +import {fromPayload} from './ref-helper' + +const PR_REF_PATTERN = /^refs\/pull\/[0-9]+\/(?:head|merge)$/ + +export interface IUnsafePrCheckoutInput { + qualifiedRepository: string + ref: string + commit: string | undefined + allowUnsafePrCheckout: boolean +} + +export function assertSafePrCheckout(input: IUnsafePrCheckoutInput): void { + if (input.allowUnsafePrCheckout) { + return + } + + const eventName = github.context.eventName + if (eventName !== 'pull_request_target' && eventName !== 'workflow_run') { + return + } + + const baseRepoId = fromPayload('repository.id') + if (typeof baseRepoId !== 'number') { + return + } + + let prHeadRepoId: unknown + let prHeadRepoFullName: unknown + const prShas: string[] = [] + + if (eventName === 'pull_request_target') { + prHeadRepoId = fromPayload('pull_request.head.repo.id') + prHeadRepoFullName = fromPayload('pull_request.head.repo.full_name') + pushIfSha(prShas, fromPayload('pull_request.head.sha')) + pushIfSha(prShas, fromPayload('pull_request.merge_commit_sha')) + } else { + const wrEvent = fromPayload('workflow_run.event') + if (typeof wrEvent !== 'string' || !wrEvent.startsWith('pull_request')) { + return + } + prHeadRepoId = fromPayload('workflow_run.head_repository.id') + prHeadRepoFullName = fromPayload('workflow_run.head_repository.full_name') + pushIfSha(prShas, fromPayload('workflow_run.head_commit.id')) + // For `pull_request_target`-triggered workflow_run, `head_sha` is the base + // default branch SHA (not the PR head) + if (wrEvent !== 'pull_request_target') { + pushIfSha(prShas, fromPayload('workflow_run.head_sha')) + } + } + + // (A) Fork PR? + if (typeof prHeadRepoId !== 'number' || prHeadRepoId === baseRepoId) { + return + } + + // (B) We cannot check for all fork PR refs so check to see + // if the resolved input points to the fork PR sha we have in the payload + const repositoryMatchesPrHead = + typeof prHeadRepoFullName === 'string' && + input.qualifiedRepository.toLowerCase() === prHeadRepoFullName.toLowerCase() + const refMatchesPullPattern = PR_REF_PATTERN.test(input.ref) + const commitMatchesPrHeadSha = + !!input.commit && prShas.includes(input.commit.toLowerCase()) + + if ( + !repositoryMatchesPrHead && + !refMatchesPullPattern && + !commitMatchesPrHeadSha + ) { + return + } + + throw new Error( + `Refusing to check out fork pull request code from a '${eventName}' workflow. ` + + `This workflow runs with the base repository's GITHUB_TOKEN, secrets, default-branch ` + + `cache scope, and runner access. Fetching and executing a fork's code in that trusted ` + + `context commonly leads to "pwn request" vulnerabilities. To opt in, review the risks ` + + `at https://gh.io/securely-using-pull_request_target and set 'allow-unsafe-pr-checkout: true' ` + + `on the actions/checkout step.` + ) +} + +function pushIfSha(target: string[], value: unknown): void { + if (typeof value === 'string' && value.length > 0) { + target.push(value.toLowerCase()) + } +}