More GitHub Actions Adventures

Recently I wrote a post about my GitHub Actions not being triggered on the main branch upon merging a PR1, the fix being to add a custom auth token as a secret. At first, this appeared to have solved my issue, as the main job was once again triggering after I merged PRs. The problem was, it was only succeeding for my PRs, not PRs opened by dependabot. PRs opened by dependabot failed with the following error message:

gh: To use GitHub CLI in a GitHub Actions workflow, set the GH_TOKEN environment variable. Example:
  env:
    GH_TOKEN: ${{ github.token }}

At first, I was quite confused because I had set the GH_TOKEN environment variable, and it worked just fine on PRs I opened myself. As it turns out though, the token was in fact missing for PRs from dependabot, and this is also by design2:

With the exception of GITHUB_TOKEN, secrets are not passed to the runner when a workflow is triggered from a forked repository. The GITHUB_TOKEN has read-only permissions in pull requests from forked repositories. For more information, see "Automatic token authentication."

Note: Workflows triggered by Dependabot pull requests are treated as though they are from a forked repository, and are also subject to these restrictions.

The fix then was to use the pull_request_target trigger instead of pull_request, like so:

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - edited
    branches:
      - main

With this, whenever a PR is opened, reopened, or edited on the main branch, the workflow to enable auto-merge will execute and the secrets will be present. Of note is that this workflow runs on the target branch, so in my case the main branch, which is in contrast to the pull_request trigger that runs on the base branch, or the branch that contains the proposed changes. This is for security reasons, to prevent malicious workflows from extracting secrets. For my purposes, this was fine, as I just split my auto-merge workflow out into its own file, and kept my pull_request workflow in another file so I could still perform testing and validation on the new code without the security risks.