Sub topic 14
Automating configuration and reporting with gh and the REST API
This chapter assumes you can run commands in a terminal, have the GitHub CLI (gh) installed and authenticated, and know what secret scanning alerts and push protection are from earlier chapters. You will use gh api to enable the features on a repository, list and summarize alerts, and close alerts with an accurate resolution. The goal is to replace repeated clicking in settings pages with commands you can review, script and schedule.
Why automate
The web interface is fine for one repository. It does not scale to fifty. It also leaves no record of what you changed. Automation gives you three things:
- Repeatable configuration. The same command applies the same settings to every repository.
- Reporting. You can pull open alerts into a table or a file and track them over time.
- Consistency in triage. A script can enforce that an alert is closed only with a reason you chose on purpose.
The gh api command sends authenticated requests to the GitHub REST API. It handles the token, the base URL and the headers. You supply the HTTP method, the path and the fields.
Prerequisites for the API calls
Check three things before you run anything.
- Authentication. Run
gh auth status. The token must be allowed to do what you ask. Reading alerts needs thereposcope for private repositories, orsecurity_eventsfor public ones. A fine-grained token needs the "Secret scanning alerts" repository permission, read for listing and write for updating. - Role. Changing repository security settings needs admin access. Reading alerts needs admin access, or a custom role or security manager role that includes alert access.
- Availability. On private and internal repositories, secret scanning and push protection are part of GitHub Secret Protection (previously GitHub Advanced Security), which must be enabled for the repository or organization. Public repositories get the features for free. If the feature is not available, the API returns an error and the setting does not change.
Enabling secret scanning and push protection
Repository settings live under the security_and_analysis object of the repository endpoint. You update it with a PATCH request.
gh api --method PATCH repos/OWNER/REPO \
-f 'security_and_analysis[secret_scanning][status]=enabled' \
-f 'security_and_analysis[secret_scanning_push_protection][status]=enabled'The -f flag sends each value as a string parameter. The bracketed names build the nested JSON object security_and_analysis.secret_scanning.status. The single quotes stop your shell from treating the brackets as a glob pattern.
The command enables two independent settings. Secret scanning looks at content already in the repository. Push protection checks pushes as they arrive. Enabling one does not enable the other, which is why the command sets both.
To confirm the result, read the same object back:
gh api repos/OWNER/REPO --jq '.security_and_analysis'The --jq flag filters the JSON response with a jq expression, so you see only the settings object. Each feature reports a status of enabled or disabled. If the field is missing from the response, the caller probably lacks admin access, because GitHub only returns this object to users who can change it.
Applying the setting to many repositories
For an organization, you can loop over repositories. This example lists non-archived repositories and applies the same patch to each.
gh repo list ORG --no-archived --limit 200 --json nameWithOwner --jq '.[].nameWithOwner' |
while read -r repo; do
echo "Updating $repo"
gh api --method PATCH "repos/$repo" \
-f 'security_and_analysis[secret_scanning][status]=enabled' \
-f 'security_and_analysis[secret_scanning_push_protection][status]=enabled' \
--silent || echo "Failed: $repo"
done--silent hides the response body. The || branch prints the name of any repository that failed, so you can review failures afterward. A failure usually means no admin access or that the feature is unavailable for that repository.
Listing alerts
Alerts are served from the secret-scanning/alerts endpoint. This command prints the key facts for each open alert.
gh api 'repos/OWNER/REPO/secret-scanning/alerts?state=open' \
--jq '.[] | {number, secret_type_display_name, validity, push_protection_bypassed}'Each output object has four fields:
| Field | Meaning |
|---|---|
| `number` | The alert number, used to address the alert in later calls. |
| `secret_type_display_name` | A readable name for the secret type, such as a cloud provider key. |
| `validity` | Whether the provider reports the credential as `active`, `inactive` or `unknown`. |
| `push_protection_bypassed` | `true` if someone bypassed push protection to commit the secret. |
The validity field connects to the validity checks chapter. Sort your work by it: an active credential needs immediate revocation, while an inactive one may only need the alert closed. The push_protection_bypassed field shows alerts that exist because a person chose to override a block. These deserve a look at the recorded bypass reason.
Pagination
The API returns 30 alerts per page by default. Without pagination you will silently miss alerts in a busy repository. Ask for larger pages and let gh follow the links:
gh api --paginate 'repos/OWNER/REPO/secret-scanning/alerts?state=open&per_page=100' \
--jq '.[] | [.number, .secret_type_display_name, .validity] | @tsv'--paginate requests every page and applies the --jq filter to each one. The @tsv filter prints tab-separated rows that are easy to paste into a spreadsheet or pipe into sort.
Organization-wide reporting
The organization endpoint returns alerts for every repository you can see. The response includes a repository object, so you can print which repository each alert belongs to.
gh api --paginate 'orgs/ORG/secret-scanning/alerts?state=open&validity=active&per_page=100' \
--jq '.[] | [.repository.full_name, .number, .secret_type_display_name] | @tsv'The validity=active query parameter keeps only alerts whose credentials the provider confirms as live. This is a short, high-priority list you can review every day.
Closing an alert
Resolving an alert is a PATCH request that sets state and, when closing, a resolution.
gh api --method PATCH repos/OWNER/REPO/secret-scanning/alerts/42 \
-f state=resolved \
-f resolution=revokedThe valid resolutions are false_positive, wont_fix, revoked and used_in_tests. Pick the one that is true:
revoked: the credential has been revoked at the provider. Use it only after that has happened.false_positive: the match is not a real credential.used_in_tests: the value is a dummy or test credential.wont_fix: you accept the risk and are not acting on it.
You can attach a note that explains your decision. Add a resolution_comment field:
gh api --method PATCH repos/OWNER/REPO/secret-scanning/alerts/42 \
-f state=resolved \
-f resolution=false_positive \
-f resolution_comment='Example key in a vendor SDK sample.'To reopen an alert, send state=open. GitHub then clears the resolution.
Inspecting where a secret appears
An alert can reference several locations. Before you revoke, find out where the secret lives:
gh api repos/OWNER/REPO/secret-scanning/alerts/42/locations \
--jq '.[] | {type, path: .details.path, commit: .details.commit_sha}'Locations can be commits, issue text, pull request text and comments, so a path is not always present for every entry. A secret pasted into an issue comment is not removed by rewriting git history. You must edit or delete the comment as well.
Putting it together: a triage workflow
The sequence below turns the commands into a daily routine.
The script below applies the first two stages. It prints active alerts and their locations, and leaves closing to a person.
#!/usr/bin/env bash
set -euo pipefail
REPO="${1:?usage: $0 OWNER/REPO}"
gh api --paginate "repos/$REPO/secret-scanning/alerts?state=open&validity=active&per_page=100" \
--jq '.[].number' |
while read -r n; do
echo "Alert $n"
gh api "repos/$REPO/secret-scanning/alerts/$n/locations" \
--jq '.[] | " \(.type) \(.details.path // .details.html_url // "n/a")"'
doneThe script keeps the final decision with a human on purpose. A script cannot know whether the credential was really revoked.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `404 Not Found` on alerts | Secret scanning is off, or the token lacks access to the repository | Enable the feature and check token scope and role |
| `403 Forbidden` on `PATCH` | The caller is not a repository admin | Use an admin token or ask an admin to run it |
| Settings unchanged, no error shown | The feature is not available for the repository's plan | Check the Secret Protection licensing for private repositories |
| Fewer alerts than expected | Missing `--paginate`, or the `state` filter hides closed alerts | Add `--paginate` and `per_page=100`; check `state` |
| `422 Unprocessable` when closing | `resolution` missing or misspelled | Send one of the four valid values with `state=resolved` |
| Brackets cause a shell error | Unquoted `[` characters expanded by the shell | Wrap the `-f` argument in single quotes |
Exercise
You want a daily report of every active-credential alert across your organization, and you notice the output has exactly 30 rows even though you expect more. What is the likely cause, and how do you fix the command? Also, which resolution would you use after revoking one of those credentials at its provider?
Show answer
The API returns 30 results per page by default, and the command did not follow additional pages. Add --paginate to gh api and per_page=100 to the query string, for example gh api --paginate 'orgs/ORG/secret-scanning/alerts?state=open&validity=active&per_page=100'. After revoking the credential at its provider, close the alert with -f state=resolved -f resolution=revoked, ideally with a resolution_comment describing the rotation.
Exercise
Write the single command that turns on both secret scanning and push protection for the repository acme/billing, and name one way to verify that it worked.
Show answer
gh api --method PATCH repos/acme/billing -f 'security_and_analysis[secret_scanning][status]=enabled' -f 'security_and_analysis[secret_scanning_push_protection][status]=enabled'. Verify with gh api repos/acme/billing --jq '.security_and_analysis' and check that both features report status as enabled.