Sub topic 2
Fixing Injection with Environment Variables
Assume you know basic YAML, shell quoting, and GitHub Actions jobs and steps. The key rule is to keep attacker-controlled values out of generated code.
Pass Values Through Environment Variables
GitHub expands ${{ }} expressions before the shell starts. If the value is inserted directly into a script, characters such as $(...), backticks, or semicolons can change the script.
Store the value in an environment variable instead. The shell then receives it as data.
name: greet
on:
issues:
types: [opened]
permissions:
contents: read
jobs:
greet:
runs-on: ubuntu-latest
steps:
- env:
ISSUE_TITLE: ${{ github.event.issue.title }}
run: |
printf 'New issue: %s\n' "$ISSUE_TITLE"The double quotes around "$ISSUE_TITLE" prevent word splitting and unwanted pathname expansion.
Injection in `actions/github-script`
actions/github-script evaluates its script input as JavaScript. Do not interpolate event data into that JavaScript source. Pass the value through env and read it with process.env.
- uses: actions/github-script@v7
env:
PR_TITLE: ${{ github.event.pull_request.title }}
with:
script: |
console.log(`Title: ${process.env.PR_TITLE}`)Here, the title is a runtime string, not part of the JavaScript source.
`pull_request` Versus `pull_request_target`
The trigger changes the trust boundary.
| Trigger | Typical fork behavior | Main security concern |
|---|---|---|
| `pull_request` | Tests the contribution with a restricted token and no fork secrets | Untrusted code still runs, so limit permissions |
| `pull_request_target` | Uses the base repository workflow and can access its token and secrets | Checking out and running fork code can expose those privileges |
Use pull_request for builds and tests. A pull_request_target workflow must not check out the pull request’s head commit and run its scripts. That pattern is commonly called a pwn request.
Restrict `GITHUB_TOKEN`
Set permissions explicitly at the workflow or job level. Grant only the access required.
permissions:
contents: read
pull-requests: writeA read-only token cannot write repository contents, even if a later step is compromised.
Exercise
A workflow uses ${{ github.event.issue.title }} inside a run block. How should you fix it?
Show answer
Assign the expression to an environment variable, then use the quoted variable in the shell. Also set the smallest required permissions block.