Sub topic 14
Storing, rotating and revoking credentials safely
This chapter assumes you can already create a fine-grained personal access token (PAT) and authenticate as a GitHub App. You should also be comfortable with environment variables and curl. Here you learn how to keep those credentials from leaking, how to replace them without downtime, and how to cut them off when something goes wrong.
Know what you are protecting
Each credential has a different lifetime and a different blast radius. That decides how much care it needs.
| Credential | Typical lifetime | What an attacker gets | How to revoke |
|---|---|---|---|
| Fine-grained PAT | Up to the expiration you set | The user's access to the selected repositories, limited to the granted permissions | Delete it in Settings, or an organization owner revokes it |
| App private key | Until you delete it | Ability to mint JWTs, then installation tokens for every installation | Delete the key in the app settings |
| App JWT | At most 10 minutes | Access to app-level endpoints only | Wait for expiry, or delete the signing key |
| Installation access token | 1 hour | Access to that installation's repositories and permissions | `DELETE /installation/token`, or wait for expiry |
| User access token (from an app) | Short, refreshable if expiry is enabled | Actions as that user, within the app's permissions | Revoke the authorization, or reset the token |
| Webhook secret | Until you change it | Ability to forge webhook deliveries to your server | Replace it in the app settings and in your server |
The private key is the most valuable item in the table. Anyone who holds it can mint new installation tokens indefinitely, so it needs the most protection.
Storing credentials
Follow one rule first: a credential never appears in source control, in a container image, in a log line or in a chat message.
Where secrets should live
- Local development: Use an environment variable set from your shell session or a password manager. If you use a
.envfile, add it to.gitignorebefore you create it. - CI/CD: Use the platform's encrypted secret store, such as GitHub Actions secrets. Inside Actions, prefer the built-in
GITHUB_TOKEN, which is scoped to the workflow run and expires when the job ends. You then have no long-lived credential to store. - Servers and containers: Use a secrets manager (AWS Secrets Manager, HashiCorp Vault, Kubernetes Secrets backed by encryption at rest). Inject the secret at start-up as a mounted file or environment variable. Never bake it into an image.
- App private keys: Treat the key as a file with restrictive permissions, or keep it in a managed key store. Where you can, avoid keeping the PEM in an environment variable. Multi-line values are easy to mangle, and environment variables leak into crash dumps and child processes.
# Create the key file with owner-only permissions before writing to it
umask 077
install -m 600 /dev/null /run/secrets/github-app.pem
# Then write the key from your secrets manager into that file.
ls -l /run/secrets/github-app.pemKeep tokens out of logs and URLs
Send tokens only in the Authorization header. Never put one in a query string or in a clone URL such as https://[email protected]/..., because URLs end up in shell history, proxy logs and error messages. When you log an HTTP request, redact the header.
function redactHeaders(headers) {
const copy = { ...headers };
for (const name of Object.keys(copy)) {
if (name.toLowerCase() === "authorization") {
copy[name] = "[REDACTED]";
}
}
return copy;
}
console.log(redactHeaders({ Authorization: "Bearer ghp_example", Accept: "application/json" }));Let GitHub help you catch mistakes
Secret scanning looks for known token formats in repositories, and push protection can block a push that contains one. Enable both on repositories where you have the option. Treat a detection as a real leak, even in a private repository, and follow the revocation steps below.
Rotating credentials
Rotation means replacing a credential on a schedule or after a suspected exposure, without breaking anything that depends on it. The pattern is always the same: create the new credential, deploy it, confirm it works, then remove the old one.
Rotating a fine-grained PAT
A fine-grained PAT always has an expiration, so rotation is built in. Choose the shortest lifetime your use case tolerates. Watch for expiry with the github-authentication-token-expiration response header, which GitHub sends on calls made with an expiring token.
curl -s -D - -o /dev/null \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/user | grep -i "github-authentication-token-expiration"When a token nears expiry, regenerate it in Settings under Developer settings. The new value keeps the same repositories and permissions. Update your secret store and then restart the consumers. Do not extend the lifetime just to avoid the chore. A scheduled reminder, or a job that checks the header and alerts at 14 days left, is cheaper than an outage.
Rotating an app private key
A GitHub App can hold more than one private key at a time. This lets you rotate with no downtime.
Do not delete the old key before every running instance has switched over. Instances that still sign with it will start failing with 401 responses as soon as it is gone.
Rotating the other secrets
- Webhook secret: Your server uses it to verify the
X-Hub-Signature-256header. Update the server first so it accepts both the old and new values for a short window. Then change the secret in the app settings, and finally drop the old value from the server. - Client secret and user tokens: If your app acts on behalf of users, enable user token expiration. User access tokens then last only a few hours and are renewed with a refresh token. A stolen access token becomes useless quickly.
- Installation tokens: You do not rotate these. Because they expire after one hour, you only need to request a new one when the cached one is close to expiry.
Cache installation tokens correctly
A common mistake is to create a new installation token for every API call. That wastes requests and adds latency. The opposite mistake is to store one in a file for reuse across restarts. Keep it in memory and refresh it before it expires. Octokit's App class does this for you.
import fs from "node:fs";
import { App } from "octokit";
const app = new App({
appId: process.env.GITHUB_APP_ID,
privateKey: fs.readFileSync(process.env.GITHUB_APP_PRIVATE_KEY_PATH, "utf8"),
});
// The returned client creates and refreshes the installation token as needed.
const octokit = await app.getInstallationOctokit(Number(process.env.INSTALLATION_ID));
const { data } = await octokit.request("GET /installation/repositories");
console.log(data.total_count);Because the private key is read from a file path, rotation only needs a file replacement and a restart.
Revoking credentials
Revocation is what you do when a credential may be exposed, or when it is no longer needed. Act first and investigate afterward, because revoking a token that was not actually leaked costs very little.
Revoke an installation token early
If a one-hour token has leaked, do not wait for it to expire. Call the endpoint using the leaked token itself:
curl -L -X DELETE \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $INSTALLATION_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/installation/tokenA successful call returns 204 No Content. The app can still create new tokens afterward. This only kills that one token.
Revoke a PAT
A user deletes a PAT in Settings under Developer settings. Organization owners can also revoke a fine-grained PAT's access to the organization. That is useful when a former contributor's token still exists but must no longer reach company repositories. Revoking removes the token's access to the organization's resources without needing the token owner to act.
Respond to a leaked private key
A leaked private key is the serious case, because the attacker can keep minting tokens. Work through these steps in order:
- Generate a new private key and deploy it, so your service keeps running.
- Delete the compromised key in the app settings. Every JWT signed with it stops working.
- Revoke any installation tokens you know were issued recently. They expire within an hour anyway.
- Review the audit log and the app's recent activity for actions you did not expect.
- Find out how the key leaked and close that path before you finish.
If you cannot tell which key leaked, delete all of them and issue a fresh one. Short downtime is better than ongoing exposure.
Reduce what there is to leak
The safest credential is one that never existed or is nearly worthless when stolen. These habits keep your exposure small:
- Pick fine-grained PATs over classic tokens, and select only the repositories and permissions the task needs.
- Prefer a GitHub App with installation tokens for automation that runs unattended, so no personal token is tied to one person's account.
- Prefer
GITHUB_TOKENinside Actions workflows, and set the workflowpermissionsblock to the minimum. - Give each service its own credential. Then a leak affects one service, and revoking it breaks only that service.
- Review the list of active tokens and installed apps regularly, and delete anything unused.
Exercise
Your service uses a GitHub App. Its private key is stored in a secrets manager, and you want to replace it without any downtime. In what order should you generate the new key, delete the old key and deploy, and why does the order matter?
Show answer
Generate the new key first, store it, and deploy the service so every instance signs with it. Confirm that JWT signing and installation token creation work. Delete the old key last. The app supports multiple keys at once, so both are valid during the switch. If you deleted the old key before every instance had moved to the new one, instances still signing with it would get 401 errors.
Exercise
An installation access token appeared in a CI log 10 minutes ago. Which request revokes it, which credential do you send in that request, and what can the app still do afterward?
Show answer
Send DELETE https://api.github.com/installation/token with the leaked installation token in the Authorization header. A 204 response means it is revoked. The app itself is unaffected, so it can still sign a JWT and request new installation tokens. You should also remove the token from the log and find out why it was logged.
Exercise
A fine-grained PAT expires in 5 days and a nightly job depends on it. How can you detect this in advance, and what do you do when the date approaches?
Show answer
Read the github-authentication-token-expiration header from any API response made with the token, and have a scheduled job alert when the remaining time is short. Before it expires, regenerate the token in Developer settings, which keeps the same repositories and permissions. Then update the secret store and restart the job's consumers.