Sub topic 13
Guarding Secrets and Fork Pull Requests
This chapter assumes you can read a workflow file, know the difference between a job and a step, and know how github.event_name and github.ref work in a condition. It shows how to keep deploy and publish steps from running when they can't, or shouldn't, have access to secrets.
Why secrets need a guard
Repository secrets are not passed to workflows triggered by a pull request from a fork. In those runs, secrets.DEPLOY_TOKEN evaluates to an empty string. A deploy step then fails with a confusing authentication error, or worse, runs without credentials and does something unintended. Dependabot pull requests have a similar restriction, since they receive a separate set of secrets.
An if condition lets you skip the work cleanly instead.
Skip fork pull requests at the job level
A pull request from a fork has a different head repository than the repository running the workflow. You can compare the two names.
jobs:
deploy:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
env:
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
steps:
- name: Deploy
if: ${{ env.DEPLOY_TOKEN != '' }}
run: ./deploy.shThe job-level condition reads as follows:
- If the event is not a pull request, the job runs. This covers pushes.
- If the event is a pull request, the job runs only when the head repository is the same as the current repository. Pull requests from forks are skipped.
Why the secret is copied into env
The secrets context is not available in an if expression. Writing if: secrets.DEPLOY_TOKEN != '' makes the workflow invalid. The workaround is to copy the secret into an environment variable at the job level, then test the env context in the step condition.
An empty string is falsy, so ${{ env.DEPLOY_TOKEN != '' }} is true only when the secret exists. This also helps in your own repository when a secret has not been configured yet.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `if: secrets.TOKEN` | Workflow is rejected | Copy the secret into `env`, then test `env.TOKEN` |
| Checking only `github.event_name == 'push'` | Pull requests are skipped, including safe ones from your own branches | Compare head and base repositories |
| Using `pull_request_target` to get secrets for fork code | Untrusted code can run with access to secrets | Keep fork code away from secret-bearing jobs |
Exercise
A deploy job runs on both push and pull_request. Write a job-level condition that skips it for pull requests from forks. Then explain why a step cannot use if: secrets.DEPLOY_TOKEN != ''.
Show answer
Use if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository. The secrets context is not available in if expressions. Copy the secret into env (DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}) and test ${{ env.DEPLOY_TOKEN != '' }} instead.