Polski

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.

By · · 15 min read

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
Diagram: The maturity ladder: from a password in code to no secret at all

What is a secret and what isn't

Secret – goes to the managerConfiguration – may be public
database passwords and connection stringsdatabase 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 ManagerSSM Parameter Store
What forpasswords, keys, secrets with rotationconfiguration and simple secrets (SecureString)
Cost0.40 USD per secret per month + 0.05 USD per 10k callsstandard: free; advanced: 0.05 USD per parameter per month
Sizeup to 64 KB4 KB (standard), 8 KB (advanced)
Rotationbuilt in (Lambda; ready templates for RDS, Redshift, DocumentDB)none – do it yourself
Versionslabels AWSCURRENT, AWSPENDING, AWSPREVIOUSparameter version history
Cross-account accessa resource policy on the secretlimited (advanced parameters via AWS RAM)
Cross-region replicationbuilt innone

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

src/secrets.ts
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;
src/db.ts
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);
  }
}
src/webhook-secret.ts
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

Create a free account · Sign in