Skip to content

Web security basics · Part 8 of 10

Managing secrets: keep keys out of code and rotate them

API keys, passwords and certificates need their own lifecycle: stored encrypted, scoped narrowly, injected at runtime and rotated. What to do after a leak.

· 2 min read

securitysecrets

A secret is anything that grants access: database passwords, API keys, signing keys, tokens, private keys. Most breaches that involve secrets come from the same few mistakes.

Never commit them

Once a secret enters version control it lives in the history, forks and clones, even after you delete it. Treat a committed secret as leaked: rotate it first, and clean the history only as a second step.

  • Add secret files to .gitignore before creating them.
  • Run a secret scanner in a pre-commit hook and in CI to catch accidents.
  • Never put secrets in container images, front-end bundles or logs.

Where to keep them

  1. A secret manager such as a cloud service or a self-hosted vault gives access control, audit logs and versioning.
  2. Encrypted files in the repository with a tool such as SOPS and age give versioned secrets reviewed like code, decrypted only where needed.
  3. Environment variables injected at deploy time are a delivery mechanism, not storage. Their source must be one of the above.

Least privilege

Give each service its own credentials with the minimum permissions: a read-only database user for a reporting job, a token scoped to one repository, a storage key limited to one bucket. When one leaks, the damage stays small.

Rotation

Change secrets on a schedule and immediately after any suspected exposure or when a person with access leaves. Rotation is painless only if it is automated and the application can accept the new value without a long outage, for example by supporting two valid keys during the switch.

shell
# Generate a strong random secret instead of inventing one.
openssl rand -base64 32

If a secret leaks

  1. Revoke or rotate it at the provider right away.
  2. Check the logs for use during the exposure window.
  3. Remove it from the history, then add a scanner rule so it cannot happen again.
  4. Write a short note about the cause.

Takeaway

Keep secrets out of code, give each one a narrow scope, rotate on a schedule and have a leak procedure ready before you need it.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.