Tutorial · Secrets management · AWS IAM
Secrets management in practice – environment variables, AWS Secrets Manager and Parameter Store, Vault, rotation, Git leaks and CI/CD
A .env.production file in a public repository for 20 minutes was enough for someone to start crypto miners in the pierogi shop's AWS account. We build proper secrets management – what counts as a secret, where environment variables stop being enough, AWS Secrets Manager vs Parameter Store, cached and rotation-aware reads in Node.js, CDK with database password rotation, dynamic secrets in Vault, gitleaks in pre-commit and CI, and OIDC instead of keys in the pipeline.
On a Friday afternoon a pierogi shop developer pushed a .env.production file to a public repository – for 20 minutes, before someone noticed and removed the commit. On Sunday an AWS budget alert arrived: in a region nobody used, dozens of large instances were running crypto miners. Bots scanning GitHub find keys within minutes, and removing a commit undoes nothing. In this tutorial we build secrets management so that such a leak is unlikely – and when it happens, not very harmful.
Prerequisites: AWS basics (IAM, ECS) and IAM with least privilege, Node.js 22+, AWS CDK v2, Git.
- 0.40 USD
- per secret per month – Secrets Manager, + 0.05 USD per 10k reads
- 0 USD
- standard parameter – SSM Parameter Store
- 64 KB
- max secret size – Secrets Manager
- minutes
- to find a key – for bots scanning public repositories
What is a secret and what isn't
| Secret – goes to the manager | Configuration – may be public |
|---|---|
| database passwords and connection strings | database name, host, port |
| partner API keys (courier, SMS, email) | the partner's API URL, limits, timeouts |
| webhook secrets and signing keys (JWT, cookies) | key ID (kid), algorithm |
| private keys (TLS, CloudFront URL signing) | the public certificate |
| publishing tokens (npm, image registries) | package name, version |
| AWS access keys (ideally – none) | role ARN, region |
The line is simple: if someone who reads it can impersonate your application or get to data – it's a secret.
Environment variables: convenient, but not a vault
The Twelve-Factor App says: configuration in environment variables. That's good advice for configuration and a reasonable way to deliver a secret to a process. The trouble starts when environment variables are the only place a secret is stored:
Environment variables
- simple, work in every language and platform
- separate configuration from code and the container image
- ECS, Lambda and Kubernetes can fill them from a secrets manager
Where they leak
- visible in `docker inspect`, `/proc/<pid>/environ` and the task definition to anyone with access
- inherited by child processes and attached to error reports (Sentry, crash dumps)
- diagnostic endpoints and CI logs can print them in full
- no read audit and no rotation – a change needs a restart
.env files are fine locally – as long as they're in .gitignore, hold development values rather than production ones, and the repository has an .env.example template without secrets.
Secrets Manager or Parameter Store?
| AWS Secrets Manager | SSM Parameter Store | |
|---|---|---|
| What for | passwords, keys, secrets with rotation | configuration and simple secrets (SecureString) |
| Cost | 0.40 USD per secret per month + 0.05 USD per 10k calls | standard: free; advanced: 0.05 USD per parameter per month |
| Size | up to 64 KB | 4 KB (standard), 8 KB (advanced) |
| Rotation | built in (Lambda; ready templates for RDS, Redshift, DocumentDB) | none – do it yourself |
| Versions | labels AWSCURRENT, AWSPENDING, AWSPREVIOUS | parameter version history |
| Cross-account access | a resource policy on the secret | limited (advanced parameters via AWS RAM) |
| Cross-region replication | built in | none |
At the pierogi shop: the database password and the courier webhook secret go to Secrets Manager (rotation), partner API URLs and flags to Parameter Store, AWS access keys – don't exist at all.
Step 1. Reading secrets in the application
Secrets Manager in Node.js: caching, database password rotation, two webhook secrets
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager';
const sm = new SecretsManagerClient({}); // credentials: the task role – no keys anywhere
const TTL_MS = 5 * 60_000;
const cache = new Map<string, { value: string; expires: number }>();
/** Reads a secret with an in-memory cache: one API call per 5 min, not one per request. */
export async function getSecret(id: string, opts: { forceRefresh?: boolean; stage?: 'AWSCURRENT' | 'AWSPREVIOUS' } = {}) {
const key = `${id}#${opts.stage ?? 'AWSCURRENT'}`;
const hit = cache.get(key);
if (!opts.forceRefresh && hit && hit.expires > Date.now()) return hit.value;
const out = await sm.send(new GetSecretValueCommand({ SecretId: id, VersionStage: opts.stage }));
if (!out.SecretString) throw new Error(`secret ${id} has no string value`); // never log the value itself
cache.set(key, { value: out.SecretString, expires: Date.now() + TTL_MS });
return out.SecretString;
}
export const getJsonSecret = async <T>(id: string, opts?: Parameters<typeof getSecret>[1]) =>
JSON.parse(await getSecret(id, opts)) as T;import pg from 'pg';
import { getJsonSecret } from './secrets.js';
interface DbSecret { host: string; port: number; username: string; password: string; dbname: string }
let pool: pg.Pool | undefined;
async function createPool(forceRefresh = false) {
const s = await getJsonSecret<DbSecret>(process.env.DB_SECRET_ARN!, { forceRefresh });
return new pg.Pool({ host: s.host, port: s.port, user: s.username, password: s.password, database: s.dbname, max: 10 });
}
/** Rotation-aware: when the password was rotated, reload the secret once and retry. */
export async function query<T extends pg.QueryResultRow>(text: string, params: unknown[] = []) {
pool ??= await createPool();
try {
return await pool.query<T>(text, params);
} catch (err) {
if ((err as { code?: string }).code !== '28P01') throw err; // 28P01 = invalid_password
const old = pool;
pool = await createPool(true);
void old.end().catch(() => undefined);
return pool.query<T>(text, params);
}
}import { createHmac, timingSafeEqual } from 'node:crypto';
import { getSecret } from './secrets.js';
/**
* Zero-downtime rotation of a webhook secret: during the transition the partner may still
* sign with the previous version, so accept AWSCURRENT or AWSPREVIOUS.
*/
export async function verifyCourierSignature(payload: string, signatureHex: string) {
const given = Buffer.from(signatureHex, 'hex');
for (const stage of ['AWSCURRENT', 'AWSPREVIOUS'] as const) {
const secret = await getSecret('prod/courier/webhook-secret', { stage }).catch(() => null);
if (!secret) continue;
const expected = createHmac('sha256', secret).update(payload).digest();
if (given.length === expected.length && timingSafeEqual(given, expected)) return true;
}
return false;
}The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step 2. Infrastructure in CDK
- Rotation: strategies
- HashiCorp Vault: dynamic secrets
- Git leaks: prevent and respond
- Secrets in CI/CD
- Common mistakes
- Test yourself
- What's next