Sub topic 15
Designing workflows that keep secrets out of code
Secret scanning and push protection catch mistakes. They are a safety net, not a design. This chapter covers how to arrange your code, tooling and team habits so that credentials rarely reach a commit at all. It assumes you can use Git, understand what API keys and tokens are, and have read the earlier chapters on alerts and remediation.
Why prevention comes after remediation
Every leaked secret costs work. You must revoke it, rotate it, find every place that used it, and clean history. Prevention removes most of that work. The goal is simple: a developer should never need to paste a real credential into a file that Git tracks.
Three ideas support this:
- Keep secrets out of the working tree. Code reads them at runtime from somewhere else.
- Make the safe path the easy path. If the secure option takes ten extra steps, people will skip it.
- Layer controls. No single control catches everything, so several checks run at different points.
Read secrets at runtime
The simplest change is to stop hard-coding values. The code asks the environment for the credential when it starts.
import os
api_key = os.environ["PAYMENTS_API_KEY"]Using os.environ[...] with square brackets is deliberate. If the variable is missing, the program fails immediately with a KeyError. That is better than silently running with an empty or default key.
A common mistake is adding a fallback default, such as os.environ.get("PAYMENTS_API_KEY", "sk_live_..."). The default is a hard-coded secret again, and scanning will flag it.
Local development files
Developers often keep local values in a .env file. This is fine only if Git never tracks the file. Do two things:
- Add
.envto.gitignorebefore anyone creates the file. - Commit a
.env.examplefile that lists variable names with placeholder values.
# .env.example
PAYMENTS_API_KEY=replace-me
DATABASE_URL=postgres://user:password@localhost:5432/appPlaceholders must look obviously fake. A realistic-looking example can trigger a false alert, and a real value pasted "just for the example" is a leak.
A .gitignore entry only affects untracked files. If .env was already committed once, ignoring it later does not remove it from the repository or its history. You must remove it with git rm --cached .env and treat any value it held as exposed.
Use a secrets store for shared and production values
Environment variables on a laptop are fine for development. For shared environments, store credentials in a managed location and inject them when the application or job starts.
| Place | Typical use | Notes |
|---|---|---|
| Local environment or `.env` | Individual development | Never tracked by Git |
| GitHub Actions secrets | CI and deployment workflows | Set per repository, environment or organization |
| Cloud secrets manager | Production applications | Supports access policies, audit logs and rotation |
| Short-lived credentials via OIDC | CI jobs reaching a cloud provider | No stored long-lived key at all |
The last row is the strongest option for pipelines. With OpenID Connect (OIDC), a GitHub Actions job proves its identity to your cloud provider and receives a temporary credential. There is no long-lived key to leak, so there is nothing for scanning to find.
Using Actions secrets correctly
Reference a stored secret in a workflow through the secrets context.
name: deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Call the payments API
env:
PAYMENTS_API_KEY: ${{ secrets.PAYMENTS_API_KEY }}
run: ./scripts/check-payments.shPass the secret through env on the step that needs it. Do not interpolate it directly into a shell command line, and do not scope it to the whole job if only one step uses it. Narrow scope limits what a compromised step can read.
Secrets can also appear in logs through careless output. Do not echo them, and avoid running scripts with shell tracing (set -x) when they handle credentials.
Layer checks at each stage
A secret can be caught at several points between the developer's keyboard and the remote. Earlier is cheaper.
Each layer has a different strength:
- Local hooks run before a commit exists. They catch a secret before it enters history, but they depend on each developer installing them.
- Push protection runs on the server and cannot be skipped by forgetting to install something. It blocks supported patterns during the push.
- Secret scanning covers the repository after the fact, including content that push protection did not block or that was bypassed.
- Code review catches things no pattern can, such as a credential in an unusual format or a risky design choice.
Because local hooks are optional, never rely on them alone. Treat push protection as the enforced control and hooks as a convenience that shortens the feedback loop.
Make the safe configuration the default
Configuration that depends on each repository owner remembering to enable it will drift. Apply settings at the organization level so new repositories inherit them.
- In the organization settings, open the code security configuration area.
- Enable secret scanning and push protection for all existing repositories.
- Turn on the option that enables the features automatically for new repositories.
- Review the organization's bypass settings so only the right people approve exceptions.
You can also audit state with the API. Run a check on a repository to confirm the settings you expect are on.
gh api repos/OWNER/REPO \
--jq '.security_and_analysis | {secret_scanning, secret_scanning_push_protection}'Run a loop like this across your repositories on a schedule, and treat any repository reporting disabled as a defect to fix.
Reduce noise so alerts stay meaningful
If people see many false alerts, they stop reading alerts. Keep the signal high.
- Put dummy values in test fixtures and documentation, then exclude those paths from scanning.
- Use clearly synthetic values such as
example-token-not-realin tests. - Close alerts with the accurate resolution reason, so reports reflect what actually happened.
# .github/secret_scanning.yml
paths-ignore:
- "docs/**/*.md"
- "test/fixtures/**"Be careful with exclusions. A broad pattern such as ** or a whole source directory hides real leaks. Keep the list short, review it when it changes, and never exclude a path only because it generates alerts you have not investigated.
Cover internal secrets with custom patterns
Provider patterns do not know your internal token formats. If your company issues its own tokens, define a custom pattern so those are detected too. For a hypothetical token made of a fixed prefix and 32 alphanumeric characters:
acme_[A-Za-z0-9]{32}A good internal format makes detection easier. Give tokens a distinctive prefix, a fixed length and a known character set. That is a prevention practice in itself, because it lets scanning find your own credentials with few false matches.
Limit the damage when something leaks
Assume that one day a secret will escape. Design so the consequence is small.
- Short lifetimes. Credentials that expire quickly are often useless by the time someone finds them.
- Least privilege. A key that can only read one bucket is far less dangerous than an admin key.
- One secret per purpose. If each service has its own key, revoking one does not break the others.
- A rotation procedure that works. Practice it before an incident. A rotation you have never tested often fails under pressure.
These choices make the revoke-and-rotate step from the remediation chapter quick and low risk.
Build team habits
Tools do not replace habits. Agree on a few rules and write them down.
- Never paste credentials into issues, pull request comments, chat or screenshots. Scanning covers many of these places, but not all of them.
- When a push is blocked, remove the secret first. Bypass only when the finding is a genuine false positive or a test value.
- If a real secret is committed, report it at once. Quick disclosure is more valuable than hiding the mistake.
- Review bypass requests and bypassed alerts regularly, looking for repeated causes you can fix in tooling.
Blame discourages reporting. A team that punishes leaks gets leaks that are found later.
Checklist
- Code reads secrets from the environment or a secrets manager.
.envfiles are ignored, and.env.exampleholds only placeholders.- CI uses Actions secrets, scoped narrowly, or OIDC where possible.
- Push protection and secret scanning are enabled at the organization level, including for new repositories.
- Custom patterns cover internal token formats.
- Exclusions are few and reviewed.
- Credentials are short-lived, least-privilege and individually revocable.
- Bypass activity is reviewed on a schedule.
Exercise
A developer adds .env to .gitignore after having committed it two weeks ago. They say the problem is fixed. Is it, and what should happen next?
Show answer
No. .gitignore only affects untracked files, so the committed .env and its history remain. The developer should run git rm --cached .env, treat every value in the file as exposed, revoke and rotate those credentials, and then clean history if needed. Rotation comes first because the secret is usable by anyone who has already seen or cloned it.
Exercise
Why is os.environ["PAYMENTS_API_KEY"] preferable to os.environ.get("PAYMENTS_API_KEY", "sk_live_abc")?
Show answer
The bracket form fails immediately and visibly when the variable is missing. The get form with a default puts a hard-coded credential back into source, where scanning will flag it and where anyone with repository access can read it.
Exercise
Name two reasons that local pre-commit hooks should not be your only protection against leaked secrets, and say which control provides the enforced backstop.
Show answer
Hooks only run for developers who install and keep them enabled, and they can be skipped (for example with --no-verify). They also never run for edits made in the web interface or by other tools. Push protection runs on the server side and provides the enforced backstop.