Sub topic 7
Pull requests from forks and pull_request_target
This chapter assumes you can write a pull_request trigger (covered earlier) and know what repository secrets and GITHUB_TOKEN are. It explains why workflows behave differently for forked pull requests, and when pull_request_target is safe to use.
What changes for a fork
A fork is a copy of your repository owned by another account. When a contributor opens a pull request from a fork, the pull_request event still fires in the base repository. The run uses the workflow file from the merge commit of the pull request, but with restrictions:
- Repository secrets are not passed to the run, except
GITHUB_TOKEN. GITHUB_TOKENhas read-only permissions.- For first-time contributors, a maintainer may need to approve the run before it starts.
These limits exist because the pull request code is untrusted. A malicious change to a workflow or a test script could otherwise print your secrets.
Two events, two trust models
pull_request_target runs in the context of the base repository. It uses the workflow file from the base branch, and secrets and a read/write token are available. By default it also checks out the base branch, not the pull request code. It suits tasks that need write access but do not need to run the contributed code, such as adding labels or posting a comment.
on:
pull_request_target:
types: [opened, reopened]
permissions:
pull-requests: write
jobs:
label:
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@v5The dangerous pattern
The risk appears when a pull_request_target workflow checks out and runs the pull request's code. That code now executes with your secrets and a write token.
# DANGEROUS: do not do this
on: pull_request_target
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- run: npm ci && npm testHere npm ci can run install scripts from the fork, and npm test runs the fork's tests. An attacker only needs to change one of those.
Choosing between them
| Need | Use |
|---|---|
| Build and test the contributed code | `pull_request` |
| Label, comment on, or triage a fork pull request without running its code | `pull_request_target` |
| Test fork code, then do a privileged step | `pull_request` for the tests, then a separate `workflow_run` workflow for the privileged step |
Set permissions: to the minimum each workflow needs. This limits the damage if something goes wrong.
Exercise
A workflow on pull_request_target checks out github.event.pull_request.head.sha and runs npm test. Why is this unsafe, and which event should run the tests instead?
Show answer
The fork's code runs with the base repository's secrets and a write-capable GITHUB_TOKEN, so a malicious test or install script can steal secrets or push changes. Run the tests on pull_request, which gives fork runs no secrets and a read-only token.