Sub topic 15
Auditing and enforcing least privilege
This chapter assumes you can write a permissions block at workflow and job level. It also assumes you know the repository default workflow permissions setting and how to use gh with the GitHub API. Earlier chapters showed how to write minimal permissions for one workflow. Here the goal is to check every workflow you own, find the broad ones, and keep them from coming back.
What an audit looks for
An audit asks four questions about each workflow:
- Does it declare
permissionsat workflow level, or does it inherit the repository default? - Is any scope set to
write, or iswrite-allused, at workflow level where only one job needs it? - Does any job grant a scope that none of its steps use?
- Does a checkout step leave the token in the local git config when later steps don't need it?
Questions 1, 2 and 4 can be checked mechanically. Question 3 needs a person to read the steps, or a test run, as described in the chapter on finding the minimal set for a job.
Step 1: audit the settings
A workflow with no permissions key gets the repository default. That default is the first thing to check. For one repository:
gh api repos/OWNER/REPO/actions/permissions/workflowThe response contains default_workflow_permissions (read or write) and can_approve_pull_request_reviews. To sweep an organization, loop over its repositories. You need admin access to each one, and repositories you can't read will report an error.
for repo in $(gh repo list ORG --limit 500 --json nameWithOwner --jq '.[].nameWithOwner'); do
gh api "repos/$repo/actions/permissions/workflow" \
--jq "\"$repo \(.default_workflow_permissions) approve=\(.can_approve_pull_request_reviews)\"" \
|| echo "$repo: no access"
doneAny line that shows write is a repository where every workflow without its own permissions key gets a read/write token. The organization-level value is available from orgs/ORG/actions/permissions/workflow. A repository can't be more permissive than its organization allows, so fixing the organization setting fixes many repositories at once.
Step 2: audit the workflow files
A quick text search finds workflow files with no top-level permissions key:
grep -L '^permissions:' .github/workflows/*.yml .github/workflows/*.yamlThis has false positives. A file where every job declares its own permissions is fine, but grep lists it anyway. It also can't tell permissions: write-all from permissions: {}. For a more accurate check, parse the YAML. This script resolves the effective permissions for each job. A job's own block replaces the workflow-level block, and the two are not merged.
import pathlib
import sys
import yaml # pip install pyyaml
findings = []
for path in sorted(pathlib.Path(".github/workflows").glob("*.y*ml")):
wf = yaml.safe_load(path.read_text()) or {}
top = wf.get("permissions")
for name, job in (wf.get("jobs") or {}).items():
own = job.get("permissions")
effective = own if own is not None else top
if effective is None:
findings.append(f"{path}: job '{name}' inherits the repository default")
elif effective == "write-all":
findings.append(f"{path}: job '{name}' uses write-all")
elif isinstance(effective, dict) and own is None:
writes = sorted(k for k, v in effective.items() if v == "write")
if writes:
findings.append(
f"{path}: workflow-level write for {', '.join(writes)} "
f"reaches job '{name}'"
)
print("\n".join(findings) or "no findings")
sys.exit(1 if findings else 0)Run it from the repository root. A nonzero exit code lets you reuse it as a CI check.
The script finds missing or broad blocks. It can't tell whether a granted scope is actually used.
Step 3: use dedicated tools
Purpose-built analyzers cover more cases than a script you maintain yourself:
| Tool | What it reports about tokens | Typical command |
|---|---|---|
| zizmor | Excessive permissions, and checkout steps that persist credentials | `zizmor .github/workflows` |
| OpenSSF Scorecard | A Token-Permissions score for a repository | `scorecard --repo=github.com/OWNER/REPO --checks=Token-Permissions` |
Both read the workflow files and don't run anything. Treat their output as leads to review. A finding such as "write permission at workflow level" tells you where to look, and you still decide what the job needs.
Step 4: compare declared and actual permissions
Static checks tell you what a workflow asks for. To see what a job actually received, open a run and expand the Set up job step in the log. It lists a "GITHUB_TOKEN Permissions" section with each scope and its level. Compare that list with the steps:
- A
pull-requests: writescope is justified by a step that comments on or labels a pull request. - A
packages: writescope is justified by a step that pushes an image or package. - A
contents: writescope needs a step that pushes commits, tags, or creates releases. If the job only runs tests, it should becontents: read.
When a scope has no matching step, remove it and re-run the workflow. If the job fails with "Resource not accessible by integration", the error message tells you which scope to add back.
Step 5: enforce
Fixing today's workflows is not enough, because the next pull request can add a new one without a permissions block. Enforce the policy in layers:
- Set the organization default to read-only, and turn off
can_approve_pull_request_reviews. Repository-level calls do the same for one repository:
``bash gh api --method PUT repos/OWNER/REPO/actions/permissions/workflow \ -f default_workflow_permissions=read \ -F can_approve_pull_request_reviews=false ``
- Add a CODEOWNERS entry so changes to workflow files need review from people who know this policy:
``text /.github/workflows/ @OWNER/security-reviewers ``
Pair it with a branch protection rule or ruleset that requires code owner review.
- Run an audit as a pull request check, so a workflow that violates the policy can't merge. The audit workflow itself follows the policy:
```yaml name: audit-workflows on: pull_request: paths: ['.github/workflows/**']
permissions: contents: read
jobs: audit: runs-on: ubuntu-latest steps:
- uses: actions/checkout@v4
with: persist-credentials: false
- run: pipx run zizmor --offline .github/workflows
```
zizmor exits nonzero when it reports findings, which fails the job. Mark this job as a required status check in branch protection. Otherwise a failure doesn't block the merge.
- Re-run the organization sweep from Step 1 on a schedule. Settings can drift, and new repositories may be created with the old default.
Edge cases
- Reusable workflows. A called workflow can only keep or reduce the permissions its caller grants. Audit the caller's
permissionsas well as the called file. - Scheduled and manual runs. These events use the default branch's workflow file, so audit that branch first.
- Forks and Dependabot. Pull requests from forks and from Dependabot get a read-only token for most events regardless of your declaration. A workflow that looks correct can still fail there, and that isn't a finding in itself.
- Policy exceptions. Some jobs must hold
id-token: writeorcontents: write. Record the reason in a comment next to the scope so the next audit doesn't remove it by mistake, or flag it again.
Exercise
The text search grep -L '^permissions:' .github/workflows/*.yml lists a file called release.yml. When you open it, both of its jobs declare their own permissions block and there is no top-level block. Is this a violation of least privilege? What should you check next?
Show answer
Not necessarily. The search only tests for a top-level key, so it flags files where every job sets its own block. If each job's block is minimal, the workflow is fine. Check that every job has a block, because a job without one would inherit the repository default. Also check that no job asks for more than its steps use, such as contents: write on a job that only builds.
Exercise
Your organization sweep shows a repository with default_workflow_permissions set to write. Name two ways to reduce the risk, one that changes the setting and one that changes the workflow files.
Show answer
Set the default to read-only with gh api --method PUT repos/OWNER/REPO/actions/permissions/workflow -f default_workflow_permissions=read -F can_approve_pull_request_reviews=false. In the workflow files, add a workflow-level permissions: {} or permissions: contents: read block, and give write scopes only to the jobs that need them.