Skip to content

Interview PrepSecrets · Core

Secrets and Keys ​

30. How should secrets and environment variables be protected? ​

The short answer

A secret is anything that grants access: database passwords, API keys, signing keys, OAuth client secrets. Never put one in source code, in git, in a Docker image, in front-end code or in logs. Load secrets at runtime from a secrets manager or the platform's secret store, injected as environment variables or mounted files. Give each service only the secrets it needs. Validate at startup that every required one is present. Rotate them on a schedule. Scan commits for leaked secrets, and treat any leaked secret as compromised: rotate it, do not just delete the commit.

Where secrets leak, and the fix for each:

LeakFix
Committed in a .env file.env in .gitignore; commit only .env.example with fake values
Baked into a Docker imageInject at runtime; never COPY .env or ENV API_KEY=… in a Dockerfile
Sent to the browserOnly VITE_ variables reach the bundle; never put a secret there (the Vite env question)
Printed in logs or error pagesRedact known fields in the logger; no stack traces to clients
Shared in chat or ticketsShare through the secrets manager, never paste the value
One key used by every serviceOne key per service and environment

Validate and freeze config at startup:

ts
import { z } from 'zod'

const Env = z.object({
  NODE_ENV: z.enum(['development', 'production']),
  DATABASE_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().startsWith('sk_'),                            // (1)
  SESSION_SECRET: z.string().min(32),                                         // (2)
})

export const config = Object.freeze(Env.parse(process.env))                   // (3)

logger.info({ env: config.NODE_ENV }, 'config loaded')                        // (4)
  1. Check the shape, so a test key or an empty value fails at boot, not on the first payment.
  2. Enforce a minimum length for signing secrets, so nobody ships secret123.
  3. Fail fast and freeze. A missing secret crashes the process at startup with a clear message, before it takes traffic. Freezing stops code from changing config at runtime.
  4. Log that config loaded, never the values.

Environment variables are convenient, not secure. They are visible to the whole process, to child processes, and sometimes in crash dumps and process listings. That is fine when the environment itself is protected. For very sensitive keys, a mounted file with tight permissions, or a fetch from a vault at startup, exposes less.

If a secret is pushed to git: removing it in a new commit does not help, because it stays in history and in every clone. Rotate the secret immediately, then clean history if you must. Turn on GitHub secret scanning and push protection, or a pre-commit scanner such as gitleaks, so it is caught before the push.

31. What is secret management, and how is a vault used? ​

The short answer

Secret management means storing all secrets in one dedicated, encrypted, access-controlled service instead of scattering them across files and servers. A vault, such as HashiCorp Vault, AWS Secrets Manager, Azure Key Vault or Google Secret Manager, stores secrets encrypted, lets each application read only the secrets its identity is allowed to, records every read in an audit log, and supports rotation and versioning. The app authenticates with its platform identity, such as its cloud role, not with another stored password, and fetches secrets at startup or has them injected.

orders serviceidentity: role ordersvault② policy: orders may readprod/orders/*encrypted secretsversions · audit logdatabase④ connect① who am I③ secrets
The app proves its identity, not a password. ① The service authenticates with its platform identity. ② The vault's policy decides which secrets that identity may read. ③ Only those are returned, and the read is logged. ④ The service uses them. Nothing secret lives in git or in the image.

The "secret zero" problem. To read from a vault, the app must authenticate. If that needs a password, where does that password live? The answer is to use an identity the platform gives the workload for free: an AWS IAM role, an Azure managed identity, a Kubernetes service account token. The platform vouches for the workload, so no first secret has to be stored anywhere.

Two ways secrets reach the app:

WayHowTrade-off
App fetches at startupSDK call to the vaultApp code depends on the vault; can refresh live
Platform injectsSecret appears as an env variable or file, e.g. through a sidecar or CSI driverApp stays simple; a restart may be needed to pick up a change

Dynamic secrets, the advanced answer. Vault can create a brand-new database user for each app instance, valid for one hour, and delete it afterwards. A leaked password then expires on its own, and every credential traces back to one instance.

32. What is a key management service (KMS)? ​

The short answer

A KMS, such as AWS KMS, Azure Key Vault keys or Google Cloud KMS, holds encryption keys inside hardened hardware and never lets the key leave. Your app sends data, or a small data key, to the KMS and asks it to encrypt, decrypt or sign. Access is controlled by identity policies, and every use is logged. It is used for encrypting data at rest, through envelope encryption, and for signing tokens. The difference from a vault: a vault hands you the secret; a KMS does the cryptography for you so you never hold the master key.

Envelope encryption, the way KMS is normally used:

  1. Your app asks the KMS for a fresh data key. The KMS returns it twice: once in plain form, and once encrypted under the master key that never leaves the KMS.
  2. Your app encrypts the customer's file locally with the plain data key, which is fast for large data.
  3. Your app throws away the plain data key and stores the encrypted data key next to the encrypted file.
  4. To read the file later, your app sends the encrypted data key to the KMS, gets the plain key back, and decrypts locally.

Why not send the whole file to the KMS? KMS calls are limited to small payloads, a few kilobytes, and have rate limits. Encrypting gigabytes locally with a data key is fast. The master key still controls everything: revoke access to it and every file becomes unreadable.

Vault / secrets managerKMS
StoresPasswords, API keys, any secretEncryption and signing keys
Gives youThe secret valueThe result of a crypto operation
Key leaves the service?Yes, to your appNever
Typical useDatabase passwordEncrypting files, signing JWTs

33. What is key rotation, and why is it important? ​

The short answer

Key rotation means replacing a key or secret with a new one on a schedule, and immediately after any suspected leak. It limits the damage of a leak you did not notice, because a stolen key only works until the next rotation. It also limits how much data any one key protects, and proves your system can change keys, so an emergency rotation is a routine operation instead of an outage. The trick is to support two keys at once during the changeover, so nothing breaks.

Rotating a JWT signing key with no downtime:

  1. Add the new key and publish both public keys, each with a key ID, kid, in your JWKS endpoint. Keep signing with the old key.
  2. Wait until every verifier has refreshed its cached key set.
  3. Switch signing to the new key. New tokens carry the new kid. Verifiers pick the right key by kid, so old and new tokens both pass.
  4. Wait until the longest-lived old token has expired.
  5. Remove the old key.
ts
const keys = new Map([
  ['2026-09', loadPublicKey('2026-09')],                                      // (1)
  ['2026-10', loadPublicKey('2026-10')],
])

function verifyToken(token: string) {
  const { kid } = decodeHeader(token)                                          // (2)
  const key = keys.get(kid)
  if (!key) throw new HttpError(401, 'Unknown signing key')                   // (3)
  return jwtVerify(token, key)
}
  1. Two keys are live during the changeover: last month's and this month's.
  2. The token's header names which key signed it.
  3. An unknown kid is rejected, never "try every key".

The same "two at once" idea for other secrets:

SecretHow to overlap
Database passwordCreate a second user, switch apps over, drop the old user
API key from a vendorMost vendors allow two active keys; switch, then revoke the old one
Encryption key for dataEncrypt new data with the new key; keep the old key for decryption, or re-encrypt in the background
Session secretAccept cookies signed with old or new; sign with new only

34. What is certificate rotation, and how can it be performed safely? ​

The short answer

TLS certificates expire, and public ones keep getting shorter. Since March 2026 a public certificate may last at most 200 days. That falls to 100 days in March 2027 and to 47 days in March 2029. So rotation must be automatic. Use ACME, the protocol behind Let's Encrypt, or your cloud's certificate manager to renew well before expiry, about a third of the lifetime ahead. Deploy the new certificate next to the old one, reload the server without dropping connections, check the full chain is served, and alert on any certificate within a couple of weeks of expiring.

A safe rotation, step by step:

  1. Renew early. For a 90-day certificate, renew at around 60 days. A failed renewal then has weeks to be fixed.
  2. Issue the new certificate with the same names. A new private key each time is better.
  3. Install it with its full chain, the intermediate certificates included. A missing intermediate works in some browsers and fails in others and in API clients.
  4. Reload, do not restart. Nginx and most proxies can reload certificates gracefully. A Node server can call server.setSecureContext() with the new key and certificate.
  5. Verify from outside: check the served expiry date and the chain.
  6. Alert on any certificate with less than 14 days left, from monitoring that runs independently of the renewal job.
ts
import { readFileSync, watch } from 'node:fs'
import https from 'node:https'

const load = () => ({ key: readFileSync(KEY_PATH), cert: readFileSync(CERT_PATH) })
const server = https.createServer(load(), app)

watch(CERT_PATH, () => {
  server.setSecureContext(load())                                              // (1)
  logger.info('TLS certificate reloaded')
})
  1. Swap the certificate in place. New connections use the new certificate. Existing connections finish on the old one. Nothing restarts.

Why outages still happen. The most common certificate outage is a forgotten manually issued certificate, often on an internal service or a partner integration. Keep an inventory of every certificate, and automate all of them.

Rotating internal certificates for mTLS follows the same overlap rule as keys: trust both the old and new certificate authority during the changeover, then remove the old one (the mTLS question).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Web & API Security
Attacks
Browser rules
Abuse
Secrets
Architecture
Other topics
Nothing picked yet