Secrets Management in 2026: Vault, SOPS and Workload Identity
Derar SattoufUpdated Security

Every production incident report about a leaked credential reads the same way. A key was committed to a repository, pasted into a chat, baked into an image, printed in a CI log, or left in a .env file on a laptop. It lived for months. Nobody knew who used it, so nobody dared rotate it. Then someone else found it first.
Secrets management is the discipline of making that story impossible, or at least short. The modern answer has three layers. First, do not have static secrets where you can avoid them: use workload identity and OIDC federation so that a pipeline or a pod proves who it is and receives short-lived credentials. Second, where you must have secrets, keep them in a purpose-built system (a cloud secret manager, Vault or OpenBao, or encrypted files with SOPS) with access control, audit logs and rotation. Third, assume leaks will happen and build detection, revocation and a rehearsed playbook.
Start by eliminating static credentials. Use OIDC federation (GitHub Actions to AWS, GCP, Azure), IAM roles for service accounts (IRSA), EKS Pod Identity, GKE Workload Identity Federation, and Azure Workload Identity. No long-lived key means nothing to leak. Prefer dynamic, short-lived secrets (Vault database credentials, STS tokens) over static ones, because a leaked 15-minute credential is a small incident.
For the secrets that remain (third-party API keys, database passwords, signing keys), use a secret manager: AWS Secrets Manager or Parameter Store, GCP Secret Manager, Azure Key Vault, or HashiCorp Vault and its open source fork OpenBao for dynamic secrets. Git is not a secret store, with one exception: encrypted files with SOPS plus age (or a cloud KMS) are a good fit for GitOps repositories. In Kubernetes, sync from a manager with the External Secrets Operator or the Secrets Store CSI Driver, and encrypt Kubernetes Secrets at rest in etcd. Remember that base64 is not encryption.
Scan everything: pre-commit hooks, CI scans with gitleaks or TruffleHog, host-side push protection, and history scans. Scanning finds secrets; it does not make them safe. When a secret leaks, revoke first and investigate second: rotate, check audit logs for use, and remove it from history only after the rotation, because history rewriting does not un-leak anything. Design for rotation from day one, with two active versions, graceful reload and no redeploy needed.
AI agents and MCP servers are new secret consumers. Give them scoped, short-lived credentials, keep secrets out of prompts and tool arguments, and never let the model see the raw secret. And pair every secret with an owner, a purpose, an expiry and an audit trail, because an unowned secret is a liability.
This pairs with OWASP Top 10 for Developers (cryptographic failures and supply chain) and OAuth 2.1 and OIDC: Common API Security Pitfalls, whose token concepts underpin workload identity.
Tool names, action versions, flags and pricing change, so where a detail is likely to drift the text says "verify against current docs". The concepts are stable; copy the structure, then confirm syntax against the vendor documentation linked at the end.
Which tool should I use?
| Situation | Recommended approach |
|---|---|
| Single cloud, a few services | The cloud's native secret manager plus IAM-based access |
| Multi-cloud or on-prem, need dynamic DB credentials, PKI, or SSH signing | Vault or OpenBao |
| GitOps repository with Kubernetes manifests | SOPS with age or KMS, or External Secrets Operator with no secrets in Git |
| CI/CD to cloud | OIDC federation, no stored cloud keys |
| Kubernetes pod to cloud API | Workload identity (IRSA, Pod Identity, GKE WIF, Azure Workload Identity) |
| Small team, one VPS | SOPS plus age, or a managed secret service; avoid hand-edited .env on servers |
| Third-party API key that cannot rotate automatically | Secret manager with scheduled rotation reminders and a documented procedure |
| Local development | A dev-only secret per developer from a manager CLI, or encrypted dotenv, never production values |
What counts as a secret
A secret is any value that grants access or proves identity, and whose disclosure causes harm. The obvious ones get attention. The less obvious ones cause the breaches.
| Category | Examples | Notes |
|---|---|---|
| Credentials | Database passwords, SMTP passwords, service account passwords | Prefer IAM auth where the database supports it |
| API keys and tokens | Stripe secret keys, OpenAI or Anthropic API keys, GitHub tokens, Slack bot tokens | Scope them narrowly; many providers offer restricted keys |
| Cloud credentials | AWS access keys, GCP service account JSON keys, Azure client secrets | The highest-value target; replace with federation |
| Cryptographic keys | TLS private keys, JWT signing keys, SSH private keys, age or GPG keys, encryption data keys | Keep in KMS or HSM where possible |
| Session and signing secrets | Cookie secrets, CSRF secrets, webhook signing secrets | Rotation invalidates sessions, plan for it |
| Connection strings | Anything with user:password@host embedded | Often missed by scanners |
| Infrastructure secrets | Terraform state (contains secrets), kubeconfig, Docker registry credentials | State files and kubeconfigs are frequently overlooked |
| Personal tokens | Developer PATs, npm and PyPI publish tokens | Long-lived, powerful, and attached to humans |
| Derived or session data | Short-lived access tokens, presigned URLs | Lower risk, but still treat as sensitive in logs |
Things that are not secrets but are often handled as if they were: public client IDs, publishable keys (Stripe pk_, Firebase web config), public keys, feature flags, and non-sensitive configuration. Misclassifying them creates noise that trains people to ignore real alerts. Separate configuration (safe to commit, differs per environment) from secrets (never committed in plaintext).
The secret lifecycle
Generate -> Store -> Distribute -> Use -> Rotate -> Revoke -> Destroy
| | | | | | |
strong manager identity- memory scheduled on leak delete
random + ACL based only or event or exit versions
(CSPRNG) + audit delivery no logs driven fast + auditEvery stage has a failure mode:
| Stage | Typical failure | Control |
|---|---|---|
| Generate | Human-chosen or reused passwords | Generate randomly with at least 128 bits of entropy; one secret per purpose |
| Store | Plaintext in repo, wiki, chat, tickets, shared drives | Secret manager, SOPS, or KMS-encrypted store |
| Distribute | Emailing a password, passing through CI logs | Pull-based, identity-authenticated delivery |
| Use | Logged, put in command-line arguments, visible in ps or crash dumps | Environment or file with tight permissions, log redaction |
| Rotate | Never done; fear of breaking things | Dual-version support, automation, game days |
| Revoke | Do not know where the secret is used | Inventory and audit logs; one purpose per secret |
| Destroy | Old versions linger in backups and history | Retention policy, version deletion, backup expiry |
The single most useful property is knowing what uses a secret. If you can answer "who and what reads this secret" in one query, rotation and revocation are routine. If you cannot, every leak becomes a crisis.
The problem with .env files, CI variables and "just env vars"
.env files are fine as a developer convenience for non-sensitive local settings. As the production secret mechanism they have predictable problems.
| Problem | How it bites |
|---|---|
| Copied everywhere | One file becomes ten copies on laptops, servers, backups, screenshots, and chat history |
| No access control | Anyone who can read the file or the process environment has everything |
| No audit | You cannot tell who read a value or when |
| No rotation story | Changing a value means editing files on every machine and restarting |
| Accidentally committed | Missing .gitignore entry, a renamed file, a .env.production nobody ignored |
| Baked into images | COPY . . includes the .env; layers keep it forever |
| Leaks via process listing | Environment variables are visible to same-user processes, crash reporters and debug endpoints |
| Leaks via logs | Frameworks dump the environment in error pages; docker inspect shows env vars |
The Docker image trap
# BAD: secret is baked into a layer even if you delete it later
FROM node:22-slim
WORKDIR /app
COPY . .
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && npm ci && rm .npmrcThe ARG value and the file are recoverable from the image history. Use a BuildKit secret mount instead, which never lands in a layer:
# GOOD: secret exists only during that RUN step
# syntax=docker/dockerfile:1
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
COPY . .docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:ci .Also add a .dockerignore that excludes .env*, *.pem, .git, and credentials directories.
CI secrets
Repository or organization secrets in GitHub Actions, GitLab CI variables and similar are encrypted at rest and masked in logs, which is a decent baseline, but they have limits:
- They are long-lived static values that any workflow with access can read.
- Log masking is pattern-based. A transformed secret (base64, URL-encoded, split across lines) is not masked.
- Pull requests from forks,
pull_request_target, third-party actions, and compromised dependencies are all routes to exfiltration. - They are hard to audit: you see that the secret was injected, not what it did.
The rule of thumb: use CI secrets for third-party tokens you cannot federate, and use OIDC for anything in your own cloud. Scope secrets to environments with required reviewers, and never expose them to untrusted code paths. See the section on workload identity and OIDC federation.
Environment variables: use with care
Env vars are the lowest-common-denominator interface and are fine as the final hop (the platform injects them from a manager into the process). The risks are in how they get there and what else can read them. Where the platform supports it, prefer files on a tmpfs (Kubernetes secret volumes, Docker and Compose secrets, systemd LoadCredential) because they can have restrictive permissions, are not inherited by child processes, and do not appear in docker inspect.
Secret scanning: pre-commit, CI, push protection and history
Scanning is detective and preventive. Run it at four points.
developer laptop pre-commit hook (gitleaks / trufflehog) -> fastest feedback
git host push protection (GitHub, GitLab) -> blocks the push
CI gitleaks / trufflehog on the diff -> backstop, covers other hosts
scheduled full-history and org-wide scans -> finds the old stuffgitleaks
# .gitleaks.toml
title = "project gitleaks config"
[extend]
useDefault = true
[[rules]]
id = "internal-service-token"
description = "Internal service token"
regex = '''svc_[A-Za-z0-9]{32}'''
keywords = ["svc_"]
[allowlist]
description = "Test fixtures and docs"
paths = [
'''docs/.*''',
'''tests/fixtures/.*''',
]
regexes = ['''EXAMPLE_NOT_A_REAL_KEY''']# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.x.y # pin to a current release tag; verify the latest
hooks:
- id: gitleaks# Scan the working tree and the full history, redacting values in output
gitleaks detect --source . --redact --verbose
# Scan only staged changes (what a pre-commit hook does)
gitleaks protect --staged --redactSubcommand names have changed between gitleaks releases; run gitleaks --help and verify against current docs.
TruffleHog
TruffleHog's differentiator is verification: it can test whether a detected credential is still live against the provider, which cuts triage time.
trufflehog git file://. --only-verified --fail
trufflehog github --org=my-org --only-verified # org-wide, needs a read token
trufflehog filesystem ./build --only-verifiedScan more than Git: container images (trufflehog docker --image ...), build artifacts, S3 buckets and Slack exports are all places where secrets hide.
Platform push protection
GitHub secret scanning with push protection blocks pushes that contain recognized provider tokens, and partner providers are notified to revoke their own leaked tokens. GitLab has comparable secret push protection. Enable them organization-wide. Verify the current feature set and plan availability in the host's docs, because some features depend on plan and visibility.
CI backstop
# .github/workflows/secrets-scan.yml
name: secrets-scan
on: [pull_request]
permissions:
contents: read
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: gitleaks
run: |
docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest \
detect --source /repo --redact --exit-code 1 \
--log-opts="origin/${{ github.base_ref }}..HEAD"Scanning limits
- Entropy-based detection has false positives; regex detection has false negatives. Use both.
- Scanners miss passwords (no recognizable shape), custom internal tokens (add rules), and encoded or split values.
- Finding a secret in history means it is compromised. Cleaning history is cosmetic.
- Baseline existing findings, fix them, then block new ones. A scanner that fails on 400 historic findings gets disabled.
A secret leaked: the rotation playbook
When a secret is exposed, speed beats elegance. The order matters.
T+0 DETECT scanner alert, provider notification, a report, a log search
T+5m CONTAIN revoke or disable the credential at the provider (or deny via policy)
T+15m ROTATE issue a replacement; deploy it through the normal secret path
T+30m ASSESS audit logs: was it used? from where? what did it access?
T+1h ERADICATE remove from code/history/artifacts; fix the root cause
T+1d RECOVER verify services healthy; widen monitoring for the identity
T+1w LEARN blameless post-incident review; add a preventive controlStep by step
- Revoke before you investigate. The reflex is to first work out who committed it. Resist. Disable or rotate the credential immediately. If rotation would cause an outage, first apply a compensating control (an IP allow-list, a deny policy, a temporary rate limit) and rotate inside minutes, not days.
- Treat the secret as burned, even if the repository is private, the commit was reverted, or the push was blocked after the fact. Bots scrape public pushes within seconds; private repositories can be cloned, forked, or opened up later.
- Pull audit logs for the credential's window of exposure: AWS CloudTrail, GCP Cloud Audit Logs, Azure Activity and Entra sign-in logs, database audit logs, provider dashboards. Look for unfamiliar IPs, regions, user agents, and unusual API calls such as listing buckets, creating users, spinning up compute (cryptomining is common), or disabling logging.
- Scope the blast radius. What could this credential do? Data read, data written, resources created, other credentials obtainable (an IAM role that can read other secrets means those are also burned).
- Remove the secret from the source (code, config, wiki, chat export) and from artifacts (container images, build logs, package registries). Only after rotating, rewrite history with
git filter-repoor BFG if policy demands it, and tell everyone to re-clone. Remember forks and caches may keep copies. - Fix the cause. Why was it in the code? No manager available, a bad example in the README, a test that needed a real key, a missing hook? Add the control that would have stopped this.
- Notify according to your obligations. Customer data exposure may trigger legal notification windows (for example under GDPR). Involve the security or legal contact early. Do not guess at the law; verify with your counsel.
- Document the timeline, evidence, and actions.
Provider quick reference
| Secret | Where to revoke | Notes |
|---|---|---|
| AWS access key | IAM, deactivate then delete the key; check CloudTrail | Also check for newly created keys, roles and users |
| GCP service account key | IAM, delete the key; consider disabling the service account | Check Cloud Audit Logs for the key ID |
| Azure client secret | Entra ID app registration, delete the secret | Review sign-in logs for the service principal |
| GitHub PAT or app token | Settings, revoke; for apps, rotate the private key or secret | Review the audit log |
| Stripe, Twilio, SendGrid, etc. | Provider dashboard, roll the key | Many support rolling with a grace period |
| Database password | Change password; terminate existing sessions | Check for new users, extensions, exfil queries |
| JWT signing key | Rotate with a key ID (kid) overlap; invalidate sessions if compromise is likely | Requires verifiers to support multiple keys |
| SSH key | Remove from authorized_keys and host provider settings | Audit logins |
| npm or PyPI token | Revoke at the registry; review recently published versions | A compromised publish token is a supply chain incident |
A runbook script skeleton
Keep a tested script for your most common credential types, and rehearse it. This example shows an AWS access key containment sequence; adapt and test in a sandbox account.
#!/usr/bin/env bash
# contain-aws-key.sh ACCESS_KEY_ID USER_NAME
set -euo pipefail
KEY_ID="$1"; USER_NAME="$2"
# 1. Deactivate (reversible) rather than delete, to keep evidence and allow rollback
aws iam update-access-key --user-name "$USER_NAME" --access-key-id "$KEY_ID" --status Inactive
# 2. Capture recent activity for this key (CloudTrail lookups are limited to 90 days of management events)
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=AccessKeyId,AttributeValue="$KEY_ID" \
--max-results 50 --output json > "evidence-${KEY_ID}.json"
# 3. List what the user can do, to scope blast radius
aws iam list-attached-user-policies --user-name "$USER_NAME"
aws iam list-user-policies --user-name "$USER_NAME"
aws iam list-groups-for-user --user-name "$USER_NAME"Common mistakes during a leak
- Deleting the commit and calling it fixed.
- Rotating one key but not its siblings (staging, other regions, other services that shared it).
- Forgetting the secret also lives in CI variables, Terraform state, Docker layers, and local
.envfiles. - Skipping the audit log review because "it was only exposed for a minute".
- Announcing in a public channel with the secret still quoted in the message.
A practical drill
Run a quarterly secret rotation game day: pick a non-critical credential, declare it leaked, and time the steps from detection to confirmed rotation. The first run reveals every hidden copy of the secret. Track the time and drive it down.
Cloud secret managers
All three major clouds provide a managed secret store with encryption, IAM, versioning and audit logs. They are the right default for most teams.
Comparison
| Feature | AWS Secrets Manager | AWS SSM Parameter Store | GCP Secret Manager | Azure Key Vault |
|---|---|---|---|---|
| Primary use | Secrets with rotation | Config and secrets (SecureString) | Secrets | Secrets, keys, certificates |
| Versioning | Yes, with staging labels (AWSCURRENT, AWSPENDING) | Yes | Yes, numbered versions and aliases | Yes |
| Built-in rotation | Yes (Lambda-based, with managed rotation for some services) | No (DIY) | Rotation notifications via Pub/Sub; you implement rotation | Rotation policy for keys; secrets by event plus automation |
| Encryption | KMS | KMS for SecureString | Google-managed or CMEK | Software or HSM-backed |
| Access control | IAM and resource policies | IAM | IAM | Azure RBAC (recommended) or access policies |
| Audit | CloudTrail | CloudTrail | Cloud Audit Logs | Azure Monitor diagnostic logs |
| Cost model | Per secret per month plus API calls | Standard tier has no per-parameter charge (verify) | Per active version plus access operations | Per operation; premium tier for HSM |
| Cross-region | Replication supported | Manual | Replication policy per secret | Geo-redundancy by region pairs |
Pricing changes; check each provider's current pricing page.
AWS Secrets Manager
# Create
aws secretsmanager create-secret \
--name prod/api/stripe \
--secret-string '{"api_key":"REPLACE_ME"}' \
--kms-key-id alias/prod-secrets
# Read (never echo to logs in real automation)
aws secretsmanager get-secret-value --secret-id prod/api/stripe --query SecretString --output textLeast-privilege policy for one application role, restricted to its own prefix:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadOwnSecrets",
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret"],
"Resource": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:prod/api/*"
},
{
"Sid": "DecryptWithAppKey",
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "arn:aws:kms:eu-west-1:111122223333:key/REPLACE-KEY-ID",
"Condition": {
"StringEquals": { "kms:ViaService": "secretsmanager.eu-west-1.amazonaws.com" }
}
}
]
}Fetching from TypeScript with the AWS SDK v3, with a short in-memory cache:
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({}); // credentials come from the role, never from code
const cache = new Map<string, { value: string; fetchedAt: number }>();
const TTL_MS = 5 * 60 * 1000;
export async function getSecret(id: string): Promise<string> {
const hit = cache.get(id);
if (hit && Date.now() - hit.fetchedAt < TTL_MS) return hit.value;
const res = await client.send(new GetSecretValueCommand({ SecretId: id }));
if (!res.SecretString) throw new Error(`secret ${id} has no string value`);
cache.set(id, { value: res.SecretString, fetchedAt: Date.now() });
return res.SecretString;
}Parameter Store is a cheaper option for configuration and low-rate secrets (SecureString), but lacks built-in rotation. A common split: Parameter Store for configuration, Secrets Manager for credentials that need rotation.
GCP Secret Manager
gcloud secrets create stripe-api-key --replication-policy=automatic
printf '%s' "$VALUE" | gcloud secrets versions add stripe-api-key --data-file=-
gcloud secrets add-iam-policy-binding stripe-api-key \
--member="serviceAccount:api@my-project.iam.gserviceaccount.com" \
--role="roles/secretmanager.secretAccessor"from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient() # Application Default Credentials; no key file
def get_secret(project: str, name: str, version: str = "latest") -> str:
path = f"projects/{project}/secrets/{name}/versions/{version}"
return client.access_secret_version(request={"name": path}).payload.data.decode("utf-8")Prefer pinning a version number or alias in production rather than latest, so a bad rotation does not instantly break every consumer, and promote deliberately.
Azure Key Vault
az keyvault create --name kv-prod-myapp --resource-group rg-prod --enable-rbac-authorization true
az keyvault secret set --vault-name kv-prod-myapp --name stripe-api-key --value "REPLACE_ME"
# Grant read to a managed identity with RBAC (least privilege role)
az role assignment create \
--assignee-object-id "$PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \
--role "Key Vault Secrets User" \
--scope "$(az keyvault show --name kv-prod-myapp --query id -o tsv)"import { DefaultAzureCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";
const client = new SecretClient("https://kv-prod-myapp.vault.azure.net", new DefaultAzureCredential());
export async function getSecret(name: string) {
const s = await client.getSecret(name);
return s.value!;
}Enable soft delete and purge protection on vaults holding anything you cannot afford to lose.
What the managers do not do
They store and authorize. They do not remove the need for: network restrictions (private endpoints, VPC endpoints), tight IAM, separating dev and prod accounts or projects, rotation automation for each third-party credential, and monitoring access. A secret manager with secretsmanager:* granted to every role is a very expensive .env file.
HashiCorp Vault and OpenBao
Vault is the reference implementation of a secrets platform. OpenBao is the community fork, hosted under the Linux Foundation, that continued from the last open source Vault release after HashiCorp changed Vault's license in 2023. For core concepts and API they are close cousins; for details such as features, versions and plugin compatibility, verify against each project's current docs. The concepts below apply to both, and vault and bao CLIs use the same shapes.
Why use it over a cloud manager
| Capability | Value |
|---|---|
| Dynamic secrets | Generate database, cloud and SSH credentials on demand with a TTL and automatic revocation |
| Leases | Every dynamic secret has a lease; revoke a lease or a whole path in one command |
| Multi-cloud, on-prem | One API and policy language everywhere |
| PKI | Run an internal certificate authority, issue short-lived certificates |
| Transit | Encryption as a service: apps send plaintext, get ciphertext, never see keys |
| Auth methods | Kubernetes, JWT/OIDC, AppRole, AWS/GCP/Azure identity, LDAP, and more |
| Fine-grained policy | Path-based policies, response wrapping, control groups (edition dependent) |
The cost is operations. Vault is a stateful, security-critical system: unsealing, HA with integrated Raft storage, backups, upgrades, audit device management, and disaster recovery. If you are single-cloud and do not need dynamic secrets or PKI, a cloud manager is usually cheaper in total cost. If you want Vault without running it, look at hosted offerings and verify their current terms.
Architecture
App pod / CI job
| 1. authenticate with platform identity (K8s SA JWT, OIDC token, cloud IAM)
v
+-----------------------+ +-----------------------------+
| Vault / OpenBao | -----> | Secrets engines |
| auth methods | | kv, database, pki, transit |
| policies (ACL) | <----- | aws, gcp, azure, ssh |
| audit devices | +-----------------------------+
+-----------------------+
| 2. returns a short-lived token bound to policies
| 3. app requests secret -> gets value + lease
v
Backends: PostgreSQL / MySQL / cloud APIs (creates a temporary user or credential)Dynamic database credentials
vault secrets enable database
vault write database/config/appdb \
plugin_name=postgresql-database-plugin \
allowed_roles="app-readwrite" \
connection_url="postgresql://{{username}}:{{password}}@db.internal:5432/app?sslmode=verify-full" \
username="vault_admin" password="REPLACE_ME"
vault write database/roles/app-readwrite \
db_name=appdb \
creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT app_rw TO \"{{name}}\";" \
default_ttl="1h" max_ttl="24h"
# Each read returns a brand-new username and password with a 1h lease
vault read database/creds/app-readwriteAfter rotating the root credential (vault write -f database/rotate-root/appdb), even the administrator password is known only to Vault. The creation statements above use Vault's templating tokens; the double braces are Vault syntax, shown inside code fences only.
Policy
# policy: app-readwrite-policy
path "database/creds/app-readwrite" {
capabilities = ["read"]
}
path "kv/data/prod/api/*" {
capabilities = ["read"]
}
# Explicitly nothing else. Vault is deny-by-default.vault policy write app-readwrite-policy app-readwrite-policy.hclKubernetes authentication
The pod presents its service account token; Vault verifies it through the Kubernetes TokenReview API and maps the service account and namespace to a role and policies.
vault auth enable kubernetes
vault write auth/kubernetes/config \
kubernetes_host="https://kubernetes.default.svc" \
kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
vault write auth/kubernetes/role/api \
bound_service_account_names=api \
bound_service_account_namespaces=prod \
policies=app-readwrite-policy \
ttl=15mRole bindings should name an exact service account and namespace. Wildcards (*) turn a namespace into a trust boundary you do not control.
Delivery options for the app:
| Pattern | How it works | Trade-off |
|---|---|---|
| Vault Agent sidecar or injector | Mutating webhook adds an agent container that authenticates, renders secrets to a shared in-memory volume, renews leases | Extra container per pod; app reads files; supports templates and re-render on change |
| Vault Secrets Operator (VSO) | Operator syncs to Kubernetes Secrets or dynamic secrets, handles renewal and rollout | Secrets land in Kubernetes Secret objects (and etcd) |
| CSI provider | Mounts secrets as volumes through the Secrets Store CSI Driver | Needs the driver; optional sync to Kubernetes Secrets |
| App uses the API or SDK directly | App authenticates and fetches itself | Most control, most code; good for dynamic credentials with in-process pooling |
| External Secrets Operator | Sync from Vault KV into Kubernetes Secrets | Convenient and uniform with other backends; dynamic secrets support is limited, so verify |
OpenBao ships equivalents of the injector and agent; some operator and CSI integrations are named differently or live in separate projects, so check the OpenBao docs for your delivery option.
Operating notes
- Unseal: use cloud KMS auto-unseal (or a transit seal from another Vault) rather than manual key shares in production.
- Audit devices: enable at least two (file and syslog or socket). Vault blocks requests if no audit device can record them, by design.
- Do not use the root token after bootstrap; revoke it and use policy-limited identities.
- Backups: snapshot the Raft storage regularly and test restore.
- Namespaces (an enterprise Vault feature; OpenBao has its own namespace support, verify the current status) isolate teams.
- Upgrade cadence: security releases matter; subscribe to advisories.
Common mistakes
- A wildcard policy such as
path "secret/*" { capabilities = ["read", "list"] }for every app. - Long default TTLs that defeat the point of dynamic secrets.
- Apps that fetch dynamic credentials once at start and never renew them (connection failures after the TTL).
- Using static root tokens in CI.
- Forgetting that Kubernetes auth trusts whoever can create pods using a given service account.
SOPS with age, and the External Secrets Operator
Two tools cover the "GitOps and Kubernetes" case from opposite directions. SOPS encrypts values inside files so ciphertext lives in Git. External Secrets Operator (ESO) keeps secrets out of Git entirely and syncs them from a manager into the cluster.
SOPS with age
SOPS (originally from Mozilla, now a CNCF project) encrypts the values of YAML, JSON, ENV and INI files while leaving keys readable, so diffs still make sense. It supports age, PGP, and cloud KMS backends (AWS KMS, GCP KMS, Azure Key Vault) and HashiCorp Vault transit. age is a small, modern file encryption tool; it is generally preferred over PGP for new setups.
# One-time: create an age key pair (store the private key in a password manager or secret manager)
age-keygen -o ~/.config/sops/age/keys.txt
# Public key: age1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs3290gq (example format)# .sops.yaml (repository root)
creation_rules:
- path_regex: ^environments/prod/.*\.enc\.ya?ml$
encrypted_regex: ^(data|stringData)$ # Kubernetes Secret manifests
age: age1PROD_PUBLIC_KEY_HERE,age1CI_PUBLIC_KEY_HERE
- path_regex: ^environments/dev/.*\.enc\.ya?ml$
age: age1DEV_PUBLIC_KEY_HEREsops --encrypt --in-place environments/prod/db-secret.enc.yaml
sops environments/prod/db-secret.enc.yaml # opens $EDITOR with decrypted view; saves encrypted
sops --decrypt environments/prod/db-secret.enc.yaml | kubectl apply -f -Key points:
- Multiple recipients: each developer, the CI system and the cluster controller get their own key. Removing a person means removing their recipient and re-encrypting (
sops updatekeys), then rotating the secrets they could read. - Environment separation: separate keys per environment so a developer with dev access cannot decrypt prod.
- Cloud KMS backend gives audit logs and IAM control over who can decrypt; age keys are files and have no built-in audit.
- Keep the private key out of the repository. The classic mistake is committing
keys.txtnext to the encrypted files. - Enforce encryption in CI: fail a commit that adds a plaintext file matching
*.enc.yaml. A simple check is that every such file contains a top-levelsops:key.
# pre-commit or CI guard: every *.enc.* file must carry SOPS metadata
for f in $(git ls-files '*.enc.yaml' '*.enc.yml' '*.enc.json'); do
grep -q '^sops:' "$f" || grep -q '"sops":' "$f" || { echo "NOT ENCRYPTED: $f"; exit 1; }
doneFlux has native SOPS decryption in the Kustomize controller:
# Flux Kustomization with SOPS decryption
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: apps-prod
namespace: flux-system
spec:
interval: 10m
path: ./environments/prod
prune: true
sourceRef:
kind: GitRepository
name: platform
decryption:
provider: sops
secretRef:
name: sops-age # Secret containing the age private key (bootstrap manually)Argo CD does not decrypt SOPS natively; common patterns use a plugin or KSOPS, or use ESO instead. Verify the current recommended integration in the Argo CD docs.
SOPS limits: secrets are still ultimately a file with a key; rotation means re-encrypting and committing; the Git history keeps old ciphertext (so rotate the data key and the secrets if a key leaks). There is no runtime access control or audit beyond what KMS gives you.
External Secrets Operator
ESO runs in the cluster and reconciles ExternalSecret resources into Kubernetes Secrets, reading from AWS Secrets Manager and Parameter Store, GCP Secret Manager, Azure Key Vault, Vault and OpenBao, 1Password, and many others. Git contains only references, never values. The API group and version have changed across ESO releases; verify the current apiVersion against the project docs.
# 1. Tell ESO how to authenticate to the backend (here: AWS via IRSA / pod identity on the controller)
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
name: aws-secrets
spec:
provider:
aws:
service: SecretsManager
region: eu-west-1
auth:
jwt:
serviceAccountRef:
name: external-secrets
namespace: external-secrets
---
# 2. Declare what to sync
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: api-secrets
namespace: prod
spec:
refreshInterval: 10m
secretStoreRef:
kind: ClusterSecretStore
name: aws-secrets
target:
name: api-secrets
creationPolicy: Owner
data:
- secretKey: STRIPE_API_KEY
remoteRef:
key: prod/api/stripe
property: api_key
- secretKey: DATABASE_URL
remoteRef:
key: prod/api/database
property: urlDesign notes:
refreshIntervalgoverns how fast rotation propagates to the Kubernetes Secret. Pods need to re-read it (volume mounts update; env vars do not) or be restarted by a tool like Reloader.- Namespace-scoped
SecretStoreoverClusterSecretStorewhen tenants should not be able to read each other's secrets; a ClusterSecretStore can be used from any namespace unless you restrict it with conditions. - ESO is a sync tool: the value still ends up in a Kubernetes Secret, so enable encryption at rest for etcd (with a KMS provider), restrict RBAC on
secrets, and keepget/liston Secrets off developer roles. - For no-Secret-object delivery, use the Secrets Store CSI Driver or Vault Agent.
Decision table
| Need | SOPS + age/KMS | ESO | Sealed Secrets | Vault Agent / CSI |
|---|---|---|---|---|
| Secrets in Git (encrypted) | Yes | No (references only) | Yes (cluster-key encrypted) | No |
| Central rotation, audit | Limited (KMS) | Yes (from backend) | No | Yes |
| Works outside Kubernetes | Yes | No | No | Partly |
| Operational burden | Low | Medium (operator) | Low (controller) | Medium to high |
| Dynamic secrets | No | Limited | No | Yes (Vault) |
| Good for | Small teams, GitOps, bootstrap secrets | Multi-service clusters with a cloud manager | Simple GitOps, single cluster | Strict, regulated, dynamic credentials |
A pragmatic combination: SOPS for bootstrap secrets (the ESO credentials, the Flux age key, anything needed before the manager is reachable) and ESO for everything else.
Workload identity and OIDC federation: no static keys
The best secret is the one that does not exist. Workload identity replaces "here is a key file" with "I am workload X, here is a short-lived signed token from an issuer you trust; exchange it for temporary cloud credentials".
GitHub Actions job Cloud identity provider Cloud API
------------------- ----------------------- ---------
1. request OIDC token ----------> GitHub OIDC issuer signs JWT
(id-token: write) claims: repo, ref, environment, workflow
2. present JWT -----------------> STS / token exchange verifies signature,
issuer, audience, and trust-policy conditions
3. <----------------------------- short-lived access token (minutes to 1 hour)
4. call API with temporary token ----------------------------------------> authorized by roleThe trust policy is the security boundary. A policy that trusts "any token from GitHub" is a vulnerability: any repository on GitHub could assume your role. Always restrict by repository, and ideally by branch, environment, or workflow ref.
GitHub Actions to AWS
# Terraform: OIDC provider and a role only your repo's main branch (and prod environment) can assume
resource "aws_iam_openid_connect_provider" "github" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
# AWS validates GitHub's certificate chain; thumbprint requirements have changed, verify current docs
thumbprint_list = ["6938fd4d98bab03faadb97b34396831e3780aea1"]
}
data "aws_iam_policy_document" "trust" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:my-org/my-repo:environment:production"]
}
}
}
resource "aws_iam_role" "deploy" {
name = "gha-deploy-prod"
assume_role_policy = data.aws_iam_policy_document.trust.json
max_session_duration = 3600
}# .github/workflows/deploy.yml
name: deploy
on:
push:
branches: [main]
permissions:
id-token: write # required to request the OIDC token
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # environment protection rules + the sub claim above
steps:
- uses: actions/checkout@v4
with: { persist-credentials: false }
- uses: aws-actions/configure-aws-credentials@v4 # verify the current major version; pin by SHA
with:
role-to-assume: arn:aws:iam::111122223333:role/gha-deploy-prod
aws-region: eu-west-1
- run: aws sts get-caller-identity
- run: ./scripts/deploy.shThe sub claim format depends on the trigger: repo:ORG/REPO:ref:refs/heads/main for branch runs, repo:ORG/REPO:environment:NAME when a job uses an environment, repo:ORG/REPO:pull_request for PRs. GitHub also supports customizing the subject claim template per organization or repository; check the current docs for the exact claim names.
GitHub Actions to GCP
gcloud iam workload-identity-pools create github --location=global --display-name="GitHub"
gcloud iam workload-identity-pools providers create-oidc github-oidc \
--location=global --workload-identity-pool=github \
--issuer-uri="https://token.actions.githubusercontent.com" \
--attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \
--attribute-condition="assertion.repository=='my-org/my-repo' && assertion.ref=='refs/heads/main'"
gcloud iam service-accounts add-iam-policy-binding deploy@my-project.iam.gserviceaccount.com \
--role="roles/iam.workloadIdentityUser" \
--member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/my-org/my-repo" - uses: google-github-actions/auth@v2 # verify current major version
with:
workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-oidc
service_account: deploy@my-project.iam.gserviceaccount.com
- uses: google-github-actions/setup-gcloud@v2
- run: gcloud run deploy api --image "$IMAGE" --region europe-west1GCP requires an attribute condition on providers for external identities in current configurations; verify the exact requirement in the docs.
GitHub Actions to Azure
# Create an app registration and a federated credential (no client secret)
az ad app create --display-name gha-deploy
APP_ID=$(az ad app list --display-name gha-deploy --query "[0].appId" -o tsv)
az ad sp create --id "$APP_ID"
az ad app federated-credential create --id "$APP_ID" --parameters '{
"name": "gha-prod",
"issuer": "https://token.actions.githubusercontent.com",
"subject": "repo:my-org/my-repo:environment:production",
"audiences": ["api://AzureADTokenExchange"]
}' - uses: azure/login@v2 # verify current major version
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }} # identifiers, not secrets; vars also fine
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}Client, tenant and subscription IDs are identifiers, not secrets. Storing them as repository variables is fine and avoids confusion.
Kubernetes workloads to cloud APIs
| Platform | Mechanism | How it works |
|---|---|---|
| AWS EKS | IRSA (IAM Roles for Service Accounts) or EKS Pod Identity | Projected service account token exchanged for role credentials; Pod Identity uses an agent and simpler association API |
| GCP GKE | Workload Identity Federation for GKE | Kubernetes service accounts map to IAM principals directly or via impersonated Google service accounts |
| Azure AKS | Microsoft Entra Workload ID | Projected token federated with a managed identity or app registration |
| Any cluster | SPIFFE/SPIRE | Issues workload identities (SVIDs) usable for mTLS and OIDC-style federation |
# EKS IRSA: annotate the service account (Pod Identity uses an association instead)
apiVersion: v1
kind: ServiceAccount
metadata:
name: api
namespace: prod
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/prod-api
automountServiceAccountToken: true# GKE: grant the Kubernetes service account direct access to a secret (no key file anywhere)
# roles/secretmanager.secretAccessor bound to the principal:
# principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/prod/sa/apiPod-level rules: one service account per workload; do not share the namespace's default account; disable automounting tokens for pods that do not need them; make sure the IMDS (instance metadata) path cannot be used by pods to obtain the node's broader credentials (IMDSv2 with hop limit 1, or network policy).
Publishing packages without long-lived tokens
npm and PyPI both support trusted publishing via OIDC, so a release workflow gets a short-lived credential tied to a repository and workflow rather than a stored publish token. Enable it where available and remove the old tokens. Verify the setup steps against the current npm and PyPI docs, since the UI and requirements are evolving.
Common mistakes with OIDC federation
- Trust policy matches only the issuer, not the
sub,repository, orref. - Wildcard subjects such as
repo:my-org/*. - Allowing
pull_requesttriggers from forks to assume deploy roles. - Forgetting
permissions: id-token: write, then falling back to static keys "just to get it working". - Overly broad role permissions: the identity is keyless but the role is
AdministratorAccess. - Keeping the old access keys after the migration. Delete them.
Migration checklist: static keys to OIDC
- Inventory every static cloud key (IAM access keys, service account JSON files, client secrets) using the cloud's credential report.
- Create the OIDC provider and one role per pipeline, scoped to the minimum actions.
- Update the workflow; run it in a non-production account first.
- Compare the actions in CloudTrail or audit logs to confirm the new role is used.
- Deactivate the old key, wait a week, delete it, and remove the CI secret.
Application patterns: fetch at start, sidecar, env injection
How the secret reaches the process matters as much as where it is stored.
| Pattern | Flow | Pros | Cons | Use when |
|---|---|---|---|---|
| Platform env injection | Platform (ECS, Cloud Run, App Service, Kubernetes) injects secret refs as env vars at start | Simple; no SDK; works for any language | Needs restart to rotate; visible in process env and some consoles | Static secrets, 12-factor style apps |
| Mounted file (tmpfs or CSI) | Secret appears at a path; app reads the file | Updates without restart if app re-reads; permissions; no env leak | App must handle reload | Certificates, config, rotating secrets |
| Fetch at startup via SDK | App authenticates and pulls secrets once | Minimal infrastructure; fine-grained | Rotation requires restart; startup depends on the manager | Small services |
| Fetch with refresh | App caches and refreshes on TTL or on auth failure | Rotation without redeploy | More code; cache invalidation logic | Rotating API keys and DB passwords |
| Sidecar or agent | Agent authenticates, renders, renews, re-templates | App stays simple; supports dynamic secrets | Extra container; more moving parts | Vault dynamic secrets, legacy apps |
| Transit / encryption service | App never holds the key; calls an API to encrypt or sign | Key never leaves the vault | Latency; availability dependency | Field encryption, signing |
| Proxy injection | Egress proxy adds the API key to outbound requests | App never sees the key at all | Needs a proxy and policy | AI agents, third-party API calls |
An in-app pattern that holds up: lazy fetch with refresh on failure
// secrets.ts: central access point; nothing else in the codebase reads process.env for secrets
type Loader = () => Promise<string>;
class Secret {
private value?: string;
private fetchedAt = 0;
constructor(private load: Loader, private ttlMs = 5 * 60_000) {}
async get(): Promise<string> {
if (!this.value || Date.now() - this.fetchedAt > this.ttlMs) await this.refresh();
return this.value!;
}
async refresh(): Promise<void> {
this.value = await this.load();
this.fetchedAt = Date.now();
}
}
export const stripeKey = new Secret(() => getSecret("prod/api/stripe"));
// Caller pattern: on 401, refresh once and retry (handles rotation mid-flight)
export async function callStripe(path: string, init: RequestInit = {}) {
for (let attempt = 0; attempt < 2; attempt++) {
const key = await stripeKey.get();
const res = await fetch(`https://api.stripe.com${path}`, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${key}` },
});
if (res.status !== 401 || attempt === 1) return res;
await stripeKey.refresh();
}
throw new Error("unreachable");
}# Python: same idea with functools-style TTL cache
import time, threading
class RefreshingSecret:
def __init__(self, loader, ttl=300):
self._loader, self._ttl = loader, ttl
self._value, self._at, self._lock = None, 0.0, threading.Lock()
def get(self) -> str:
with self._lock:
if self._value is None or time.time() - self._at > self._ttl:
self._value, self._at = self._loader(), time.time()
return self._value
def invalidate(self):
with self._lock:
self._value = NoneHygiene inside the process
- Wrap secrets in a type that refuses to print. A class whose
toStringand JSON serialization return[REDACTED]prevents the accidentalconsole.log(config). - Redact at the logger (pino
redact, structlog processors) for headers and known keys. - Never put secrets in command-line arguments (visible in
psand shell history) or URLs (logged by proxies). - Fail fast with a clear error (without the value) when a required secret is missing at startup.
- Disable core dumps and debug endpoints in production.
export class Redacted<T extends string> {
constructor(private readonly value: T) {}
reveal(): T { return this.value; }
toString() { return "[REDACTED]"; }
toJSON() { return "[REDACTED]"; }
[Symbol.for("nodejs.util.inspect.custom")]() { return "[REDACTED]"; }
}Docker and Compose secrets
# compose.yaml: file-based secrets mounted at /run/secrets/NAME
services:
api:
image: ghcr.io/my-org/api:1.4.2
secrets:
- db_password
environment:
DB_PASSWORD_FILE: /run/secrets/db_password
secrets:
db_password:
file: ./secrets/db_password.txt # git-ignored; or use `environment:` / external sourcesMany official images (PostgreSQL, MySQL) support the _FILE convention. Read the file in your own app the same way.
Systemd on a VPS
# /etc/systemd/system/api.service
[Service]
ExecStart=/usr/local/bin/api
LoadCredential=db_password:/etc/api/secrets/db_password
# App reads $CREDENTIALS_DIRECTORY/db_password; file is private to the service
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strictRotation without downtime
Rotation is the control that turns a leak from a catastrophe into a non-event, but only if it is routine. Unrehearsed rotation breaks production.
The dual-credential pattern
Phase 1 Create new credential B alongside A. (A active, B active)
Phase 2 Deploy/refresh consumers so they use B. (verify via metrics/logs)
Phase 3 Confirm nothing uses A (audit logs, 0 reads).
Phase 4 Disable A, wait a safe period.
Phase 5 Delete A.The system must accept two valid credentials at once during the window. How to get that:
| Secret type | Dual-valid mechanism |
|---|---|
| Database password | Two database roles (alternating "blue" and "green" users), or Vault dynamic credentials where every client has its own |
| API keys at a provider | Providers with multiple active keys; create the new key, deploy, revoke the old |
| JWT signing keys | Publish a JWKS with multiple keys; sign with the new kid, keep verifying with the old until tokens expire |
| Webhook signing secrets | Verify against a list of secrets for a grace period |
| TLS certificates | Automated renewal (ACME) with overlapping validity |
| Encryption keys | Envelope encryption: rotate the key-encryption key, re-wrap data keys lazily; keep old key versions for decryption |
| Session or cookie secrets | Accept an array of secrets: sign with the first, verify with all |
// Verifying with an overlapping list of webhook secrets
import crypto from "node:crypto";
export function verifyAny(raw: Buffer, signature: string, secrets: string[]): boolean {
return secrets.some((s) => {
const expected = crypto.createHmac("sha256", s).update(raw).digest("hex");
return expected.length === signature.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
});
}AWS Secrets Manager rotation labels
Secrets Manager uses staging labels: AWSCURRENT (in use), AWSPENDING (new, being tested), AWSPREVIOUS (prior version). A rotation function runs four steps: create, set, test, finish. The "alternating users" strategy keeps one valid user while updating the other. Use the managed rotation templates for supported databases rather than writing your own Lambda where possible; verify the current list of supported services.
Making applications rotation-friendly
- Reload on change: re-read mounted files (file watcher or periodic), or refresh on 401 as in the in-app pattern earlier.
- Connection pools: when a DB password changes, existing connections remain valid, but new connections must use the new one. Recycle pools gradually.
- Short-lived credentials by design: Vault dynamic secrets or IAM database authentication (RDS and Cloud SQL IAM auth give 15-minute tokens as passwords) eliminate rotation as a task.
- Restart as a rotation strategy is acceptable if rolling restarts are safe. A
Reloaderannotation or a rollout triggered from the secret change works well. - Rotation observability: emit a metric or log (without the value) when a secret version changes, and alert when a secret exceeds its maximum age.
# Kubernetes: restart pods when a referenced Secret changes (Stakater Reloader annotation)
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
annotations:
secret.reloader.stakater.com/reload: "api-secrets"Rotation schedule guidance
| Secret | Suggested approach |
|---|---|
| Cloud credentials | Eliminate static ones; if unavoidable, 90 days or less with automation |
| Database passwords | Dynamic credentials, or 30 to 90 days with automation |
| Third-party API keys | On personnel change, on suspected leak, and at least yearly; more often if the provider supports automation |
| Signing keys (JWT, webhook) | On a schedule (for example 90 to 180 days) with overlap |
| TLS certificates | Automated; lifetimes are getting shorter industry-wide, verify current CA/B Forum rules |
| Human passwords | Per current NIST guidance, change on evidence of compromise, not on a fixed calendar |
These intervals are starting points, not mandates. Choose what you can automate and verify, and what your compliance regime requires.
Local development
Developers need working credentials without production exposure.
| Practice | Why |
|---|---|
| Use dev-only secrets for dev services; never copy production values to laptops | A lost laptop must not equal a production breach |
| Pull secrets at run time from a manager CLI | No long-lived file on disk |
| Use per-developer credentials where the provider allows | Attribution and individual revocation |
| Use local emulators (LocalStack, Stripe CLI test mode, fake SMTP) | Fewer real secrets needed at all |
Use a dev container or compose stack with fake values committed as .env.example | New hire runs the app without asking for secrets |
| Authenticate to the cloud using SSO and short-lived sessions | aws sso login, gcloud auth login, az login instead of access keys |
# Run a command with secrets injected from a manager without writing a file.
# Examples (choose the tool you actually use; verify syntax in each tool's docs):
op run --env-file=.env.tpl -- npm run dev # 1Password CLI: .env.tpl holds op:// references
doppler run -- npm run dev # Doppler
sops exec-env secrets.dev.enc.env 'npm run dev' # SOPS: decrypt into the child's environment only# .env.example (committed): shape and safe defaults only
DATABASE_URL=postgresql://app:app@localhost:5432/app_dev
STRIPE_API_KEY=sk_test_REPLACE_WITH_YOUR_OWN_TEST_KEY
SESSION_SECRET=generate-with-openssl-rand-base64-32# Generate strong local secrets
openssl rand -base64 32Also: add .env, .env.* (except .env.example), *.pem, *.key, *.tfstate* to .gitignore and .dockerignore; install the pre-commit scanner in the repository's setup script so it is not optional; and never paste secrets into issue trackers or chats. Use a one-time-secret sharing link or the manager's sharing feature when a human-to-human handoff is unavoidable.
Audit, least privilege and ownership
A secret manager with weak policy and no logs gives false comfort.
Least privilege
- One identity per workload, one role per purpose. Do not reuse the CI role for runtime.
- Path or prefix scoping:
prod/api/*for the API, not*. - Separate environments in separate accounts, projects or vaults. A staging bug should not read production secrets.
- Deny by default; add explicit permissions and review them.
- Separate read from manage: apps get
GetSecretValue; only a small admin group or automation canPutSecretValue, delete or change policies. - Break-glass access with approvals, time limits and alerts.
- Condition keys (source VPC endpoint, IP, MFA, tag-based access control) add depth.
Audit and alerting
| Signal | Why it matters |
|---|---|
| Reads of a secret from an unexpected principal or IP | Possible theft or misconfigured access |
| Read spike | Scraping or a loop bug |
| Policy changes on secrets or keys | Privilege escalation prep |
| Secret deletion or scheduled key deletion | Sabotage or a mistake |
| Failed access attempts | Probing |
| Secret age over maximum | Rotation drift |
| Disabling of audit logs | Anti-forensics |
Send audit logs (CloudTrail, Cloud Audit Logs, Azure diagnostics, Vault audit devices) to a separate, write-restricted logging account. Create alerts for the first four rows, and a weekly report for the last two.
Inventory and ownership
Maintain a registry (a table in your secret manager's tags, a catalog in the developer portal, or a YAML file in the platform repo):
# secrets-inventory.yaml (no values, only metadata)
- name: prod/api/stripe
owner: payments-team
purpose: Server-side Stripe API calls
consumers: [api, billing-worker]
rotation: manual-quarterly # provider supports rolling keys
last_rotated: 2026-09-14
data_class: high
runbook: https://wiki.example.com/runbooks/rotate-stripeTag secrets in the manager with owner, environment, rotation, data_class, and use tag-based IAM conditions and cost reports. Every secret must answer: who owns it, what is it for, who uses it, when does it expire, how do I rotate it.
Secrets for AI agents and MCP servers
AI coding agents, chat assistants with tools, and MCP servers are a fast-growing class of secret consumers, with extra risks because a language model can be manipulated by content it reads (see Prompt Injection Defense for AI Agents). The threat model: an injected instruction convinces the agent to read a secret and send it somewhere, or to print it into a log, a pull request or a chat.
Principles
- The model should never see the raw secret. Prompts, tool arguments, tool results and conversation logs are all places secrets get retained and leaked. Let the tool runtime or a proxy attach credentials after the model decides to call a tool.
- Least privilege per tool. An agent that reads issues needs a read-only, repository-scoped token, not a personal token with full account access.
- Short-lived, task-scoped credentials. Mint a token for the task (GitHub app installation tokens expire in an hour; cloud STS tokens expire in minutes) and let it die.
- Separate the agent's identity from the human's. Give agents their own service accounts so actions are attributable and revocable.
- Block exfiltration paths. Egress allow-lists for agent sandboxes; no ambient credentials in the environment; deny reading
~/.aws,~/.ssh,.env, and token stores. - Human approval for high-impact actions such as publishing packages, rotating production secrets, or deploying.
- Scan agent output. Run secret scanning on agent-authored commits and pull requests, and redact secrets in transcripts.
Patterns for MCP servers
| Concern | Recommendation |
|---|---|
| Where the server's credentials live | In the server process environment or its secret manager, never in the client config checked into a repository, and never in the tool schema or prompts |
| Remote MCP servers | Use OAuth 2.1 flows as defined by the MCP authorization specification (verify the current spec revision) with scoped, expiring tokens, rather than static API keys shared among users |
| Per-user access | Delegate with the user's own authorization (token exchange or on-behalf-of) so the server cannot do more than the user can |
| Tool design | Tools like get_secret(name) returning values to the model are an anti-pattern. Prefer tools that perform the action (for example deploy(service)) with credentials the model never sees |
| Config files | Keep .mcp.json and agent settings free of tokens; reference environment variables that the launcher injects from a manager |
| Third-party servers | Treat them as untrusted code with access to whatever credentials you give them; run in a container with limited egress; pin versions |
// .mcp.json (committed): references only, no values
{
"mcpServers": {
"github": {
"command": "node",
"args": ["./tools/github-mcp/index.js"],
"env": {
// The launcher resolves this from a secret manager at start; the file holds no token
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}The exact configuration format and variable expansion support differ between clients; verify against your client's current documentation.
A credential-injecting proxy for agents
For model-driven HTTP calls, run an egress proxy in front of the agent sandbox that adds the Authorization header for allow-listed hosts and drops everything else. The model asks for "call the billing API"; the proxy supplies the credential. A compromised or manipulated model can misuse the allowed actions, but cannot exfiltrate the key or reach other hosts.
Agent sandbox (no secrets, no direct internet)
| HTTP request to api.billing.example.com (no auth header)
v
Egress proxy ---- policy: allow host, allow methods, rate limit, log
| injects Authorization from secret manager (short-lived token)
v
api.billing.example.comAgent checklist
- Agent runs with its own identity and the minimum scopes.
- No secrets in prompts, rules files, memory stores, or chat logs.
- Credentials injected outside the model's context; short-lived where possible.
- Sandboxed filesystem excludes credential locations; network egress restricted.
- Secret scanning on every agent-authored change.
- High-impact actions require human confirmation.
A worked example: a small SaaS from .env to workload identity
Starting point: a Next.js and worker app on Kubernetes, with a Postgres database on AWS RDS, Stripe, and a GitHub Actions pipeline that deploys with a stored AWS_ACCESS_KEY_ID. Secrets live in a .env.production file copied to the servers.
Target state
GitHub Actions --OIDC--> AWS role (deploy only, environment: production)
Kubernetes pods --IRSA/Pod Identity--> AWS role (read prod/api/* secrets only)
External Secrets Operator --> syncs Stripe key + DB URL to Kubernetes Secrets
RDS --> IAM database authentication for the worker; password rotated by Secrets Manager for the app
Git repo --> SOPS-encrypted bootstrap secrets only; gitleaks + push protectionStep by step
- Stop the bleeding (day 1). Enable GitHub push protection and add gitleaks to CI. Scan history; rotate anything found. Add
.env*to.gitignoreand.dockerignore. Check images for baked-in secrets (trufflehog docker). - Inventory (day 2). List every secret, its consumers and the owner using a spreadsheet or the YAML format from the inventory and ownership section. Delete unused ones.
- Move to a manager (week 1). Create entries in AWS Secrets Manager under
prod/api/. Grant read to a new role for the app. Deploy ESO and anExternalSecret. Switch the Deployment to read from the generated Kubernetes Secret. - Pod identity (week 1). Bind the service account to the role; delete any AWS keys from the pod environment.
- OIDC for CI (week 2). Create the OIDC provider and deploy role, update the workflow, remove the AWS key from CI secrets, deactivate then delete the IAM user key.
- Rotation (week 3). Enable managed rotation for the DB secret using the alternating users strategy; make the app refresh pools. Add Reloader. Run a rotation game day.
- Audit (week 4). Enable CloudTrail data events for Secrets Manager reads, alert on reads from unknown principals, and set up secret age alerts.
- Etcd and RBAC. Enable KMS-backed encryption of Secrets at rest in the cluster; remove
get secretsfrom developer roles. - Document and rehearse the leak playbook from the rotation playbook section.
The resulting workflow, in short
# deployment fragment: no secret values anywhere in Git
spec:
template:
spec:
serviceAccountName: api # bound to an IAM role via IRSA / Pod Identity
containers:
- name: api
image: ghcr.io/my-org/api@sha256:REPLACE_WITH_DIGEST
envFrom:
- secretRef:
name: api-secrets # created and refreshed by External Secrets OperatorWhere this usually goes wrong
- One shared secret for everything. Blast radius is the sum of everything it unlocks.
- Secrets in Terraform state or Helm values committed to Git. State holds secret values in plaintext; encrypt the backend, restrict access, and use ephemeral or write-only attributes where your tooling supports them (verify).
- Trusting log masking. Secrets printed in transformed form are not masked.
- Base64 equals encrypted. It does not. Kubernetes Secrets are base64-encoded by default.
- Wildcard trust in OIDC conditions.
- No owner. The secret everyone depends on and nobody maintains.
- Rotation designed but never exercised. The first real rotation then becomes the outage.
- Moving secrets into a manager but granting everyone access to it.
- Keeping the old key "just in case". It is the one that leaks.
- Different treatment for non-production. Staging credentials that reach production data, or staging breaches that pivot into production.
- Using human credentials in automation. When the person leaves, builds break or, worse, nothing is revoked.
- Ignoring non-obvious secrets: Terraform state, kubeconfigs, container registry auth files (
~/.docker/config.json), browser session cookies on build machines.
When not to do this (or when simpler is fine)
- Do not run Vault or OpenBao for five secrets. The operational burden outweighs the benefit. A cloud manager or SOPS is enough until you need dynamic secrets, PKI, or multi-cloud.
- Do not adopt ESO, CSI drivers, and Vault Agent together. Pick one delivery mechanism per platform.
- Do not build your own secret manager or encryption scheme.
- Do not rotate everything weekly if you cannot do it safely. A failed automated rotation causes outages and teaches people to disable rotation. Start with the credentials that matter most and can rotate safely, and automate gradually.
- Do not put public or low-risk configuration through the secret manager. It adds latency, cost and friction without risk reduction.
- Do not use SOPS as a runtime access control system. It protects storage, not usage.
- Do not replace secrets with OIDC where the other side does not support federation. Third-party SaaS APIs often only offer static keys; store them well, scope them, and rotate manually on a schedule.
- Hobby project on one server: an encrypted file with SOPS and age, a systemd credential or Docker secret, a secret scanning hook and a password manager is a respectable and sufficient setup.
Maturity roadmap
| Level | Description | Key actions |
|---|---|---|
| 0. Ad hoc | Secrets in code, .env everywhere, shared passwords | Stop the bleeding: scanning, push protection, .gitignore, rotate exposed secrets |
| 1. Baseline | Secrets out of Git; a manager exists; CI scanning | Pick one secret manager; move production secrets; inventory and owners |
| 2. Federated | No static cloud keys in CI or workloads | OIDC for CI; workload identity for pods and serverless; delete old keys |
| 3. Managed rotation | Automated rotation for the key credentials; apps handle rotation | Dual-credential patterns; reloaders; rotation game days |
| 4. Dynamic and audited | Short-lived credentials, anomaly alerts, ownership enforced | Vault/OpenBao or IAM database auth; audit alerts; secret age SLOs |
| 5. Defense in depth | Tamper-resistant audit, break-glass, agent-safe credential injection | Egress proxies, per-task credentials, regular drills, policy as code |
A sensible 90-day plan for a small team: weeks 1 to 2 on level 0 to 1 actions, weeks 3 to 8 on OIDC and workload identity, weeks 9 to 12 on rotation and audit. Measure progress with a few numbers: count of static long-lived cloud keys (target: zero), count of secrets without an owner (zero), median secret age, time to rotate a leaked credential in a drill, and scanner findings open longer than the SLA.
If you take only one action from all of this, list every static credential your CI and workloads use today and replace the cloud ones with federation this quarter. It removes your highest-value leak targets and teaches the team the pattern for everything else.
Questions that come up
Is it safe to commit encrypted secrets with SOPS to a public repository? It is as safe as your key management. Ciphertext stays in Git history forever, so any future key compromise exposes every past version. For public repositories, prefer references to an external manager. If you do commit ciphertext, use a KMS backend with audit logs and rotate the secrets (not just the key) when people leave.
Are Kubernetes Secrets secure?
They are access-controlled objects stored base64-encoded in etcd, not encrypted by default. Enable encryption at rest (preferably with a KMS provider), restrict RBAC, avoid giving developers broad get secrets, and consider mounting from an external manager through CSI.
Do I still need secret scanning if I use a secret manager? Yes. Humans still paste secrets into code, configs, tickets, and chats. Scanning is the safety net, and push protection is the cheapest control with the most return.
How do I handle secrets in serverless and PaaS? Use the platform's native integrations: Lambda with Secrets Manager or Parameters extension, Cloud Run with Secret Manager references, Azure Functions and App Service with Key Vault references. All can resolve secrets at deploy or start using the platform's identity, so no credentials are in your config.
What do I do about secrets already in Git history? Rotate them, then decide whether rewriting history is worth it. Rewriting is helpful for hygiene and for reducing accidental rediscovery, but it never un-leaks a secret that was already public.
Is a .env file ever acceptable?
For local development with non-production values, yes. For production, use platform injection from a manager.
Sources and docs
- GitHub Docs: About security hardening with OpenID Connect: trust conditions and claims.
- GitHub Docs: Secret scanning and push protection: enabling and configuring.
- AWS: IAM roles for GitHub Actions via OIDC and AWS Secrets Manager rotation.
- Google Cloud: Workload Identity Federation and Secret Manager.
- Microsoft Entra Workload ID and Azure Key Vault.
- HashiCorp Vault documentation and OpenBao documentation.
- SOPS and age.
- External Secrets Operator and the Secrets Store CSI Driver.
- gitleaks and TruffleHog.
- OWASP Secrets Management Cheat Sheet.
- Kubernetes: Good practices for Secrets and encrypting Secret data at rest.
- SPIFFE and SPIRE: workload identity beyond a single cloud.
- On this site: OWASP Top 10 for Developers, OAuth 2.1 and OIDC: Common API Security Pitfalls, Prompt Injection Defense for AI Agents, Threat Modeling for Developers, Docker: The Complete Course.