Explaining Secrets-in-DB Pattern
The user wants an explanation of the Secrets-in-DB pattern, focusing on envelope encryption, HSM/KMS, and ciphertext queries. I’ll structure the guidance to cover topics like envelope encryption, DEK/KEK usage, storage in DB, rotation, and access control, along with threat modeling. I should mention deterministic encryption, tokenization, and how KMS helps in wrapping DEKs. Additionally, I'll touch on caching decrypted secrets, multi-tenancy considerations, and potential trade-offs involved. Lastly, I'll suggest using Postgres with pgcrypto for implementation and outline the guidelines.Explaining and Implementing Secrets Management
I want to provide a thorough explanation along with practical steps and recommended algorithms for managing secrets in a database, like API keys. I should include minimal pseudocode examples and relevant checklists for clarity. It’s essential to reference the envelope encryption pattern here. I’ll highlight that simply storing ciphertext is insufficient if the application handles the key; therefore, strong access control and KMS are crucial for restricting and auditing key usage effectively. Let's craft something clear and practical!Designing Secrets Storage in a DB
I want to design a system for storing secrets in a database that allows for retrieval and occasional searching by secret or other fields. The core pattern involves encrypting the secret with a DEK, wrapping the DEK using a KMS key (KEK), and storing the wrapped DEK alongside the ciphertext, nonce, additional authenticated data, and version. When reading, I'll unwrap the DEK via KMS and decrypt with AEAD. I’ll also rotate the KEK as needed and handle ciphertext queries with a blind index for equality searches.Addressing Secrets and Range Queries
Range queries can be challenging, so I'll consider storing normalized values separately or using application-level filtering and specialized searchable encryption. I need to be explicit about potential leakage, as deterministic tokens can reveal duplicates through frequency analysis. Using peppered keyed hashes and rotating keys can help mitigate this with per-tenant keys.
I’ll highlight the importance of DB indexes, include AAD for binding to row and tenant IDs, and minimize KMS calls by caching DEKs. Lastly, I should mention the option to use client-side field-level encryption as seen in Mongo or AWS DynamoDB encryption client.Explaining Secrets-in-DB Pattern
The user has queried about the Secrets-in-DB pattern, specifically focusing on envelope encryption, HSM/KMS, and ciphertext queries. They might be looking for design notes or best practices to follow. I want to provide a clear explanation along with the relevant patterns involved. This will help ensure they understand how to securely manage secrets within databases. Let’s dive into the details and create a comprehensive overview for them!
1) Goal and threat model (what “Secrets-in-DB” usually means)
You want to store sensitive values (API keys, tokens, credentials, PII) in a database such that:
- A DB dump / read-only DB compromise doesn’t reveal plaintext.
- Key use is controlled, audited, and supports rotation.
- You can still use the secret in the application when authorized.
- Sometimes you also want to find rows by a secret-derived value (ciphertext queries).
If the application runtime is fully compromised, the attacker can usually decrypt (because the app can). KMS/HSM reduces blast radius and improves control/audit, but it doesn’t make secrets “safe from the app that uses them”.
2) Envelope encryption pattern (recommended baseline)
Core idea: encrypt each secret with a data encryption key (DEK), and store the DEK encrypted (“wrapped”) under a key encryption key (KEK) held by KMS/HSM.
Write path
- Generate DEK (random 256-bit).
- Encrypt secret with AEAD (e.g., AES-256-GCM or XChaCha20-Poly1305):
- outputs:
ciphertext, nonce/iv, tag
- include AAD (associated authenticated data) like
tenant_id, record_id, purpose, version so ciphertext can’t be moved between rows/tenants without detection.
- Wrap DEK using KMS/HSM (KEK):
wrapped_dek = KMS.Encrypt(KEK, dek) (or GenerateDataKey APIs that return plaintext DEK + wrapped DEK).
- Store
{ciphertext, nonce, wrapped_dek, alg, aad_context, key_id/version} in DB.
Read path
- Load row.
- Unwrap DEK via KMS/HSM:
dek = KMS.Decrypt(KEK, wrapped_dek).
- AEAD-decrypt
ciphertext with dek + nonce + same AAD context.
Minimal schema sketch
secret_ciphertext VARBINARY
secret_nonce VARBINARY
wrapped_dek VARBINARY
kek_key_id TEXT (or ARN / key reference)
alg TEXT (and maybe enc_version INT)
aad_context not necessarily stored verbatim if derivable (e.g., tenant_id + record_id), but store what you need to reconstruct it exactly.
Why this is useful
- DB compromise → ciphertext only.
- KMS policies can restrict which service/role can unwrap keys; every unwrap can be audited.
- Rotation is feasible:
- Rotate KEK in KMS without re-encrypting all data (rewrap DEKs as needed).
- Rotate DEKs by re-encrypting individual secrets lazily on read/write.
3) HSM vs KMS (what you get, what you don’t)
KMS (cloud) typical benefits
- Central key custody, IAM-based access control
- Audit logs for key usage
- Built-in rotation/versioning
- Rate limits/latency you must design around
HSM (dedicated / on-prem or cloud HSM)
- Stronger isolation guarantees, compliance needs
- More operational complexity
- Often used when you need strict “keys never leave hardware” assurances
Important: In envelope encryption, the DEK does exist in plaintext in the application (even if briefly) unless you use a model where encryption/decryption is done inside a secure boundary (HSM-based “encrypt/decrypt API” service), which trades simplicity for stronger containment.
4) Performance and operational details that matter
- Don’t call KMS per secret if you can avoid it:
- Common pattern: per-tenant (or per-integration) DEK wrapped once; decrypt it once and use it to encrypt many fields. Store one wrapped tenant key + per-row nonces/ciphertexts.
- Cache unwrapped DEKs carefully:
- Short TTL in memory; never write to disk; scope to process/request.
- Use AEAD (not raw AES-CBC):
- You want integrity/authenticity (tamper detection) and nonce handling.
- AAD binding:
- Include
tenant_id and record_id at minimum to prevent ciphertext swapping.
5) “Ciphertext queries” (how to search without decrypting everything)
If you only fetch by primary key / foreign key, you don’t need ciphertext queries: just retrieve row and decrypt.
If you need queries like “find the row whose secret equals X” or “does this token already exist?”, you have a few options. None are perfect; they trade off leakage vs functionality.
Option A: Blind index (recommended for equality search)
Store an additional indexed column computed as a keyed hash of a normalized plaintext:
search_token = HMAC(search_key, normalize(plaintext))
- Store
search_token in DB with an index
- Query by computing the HMAC of the input and matching
Properties
- Supports equality queries efficiently.
- Leaks duplicates (same plaintext → same token).
- Resistant to rainbow tables if the HMAC key is secret and well-protected.
- Use a separate key from encryption keys (and rotate independently).
Typical schema
secret_ciphertext ...
secret_nonce ...
wrapped_dek ...
secret_eq_token BINARY(32) (indexed)
Notes
- Normalization must be consistent (trim, lower, canonical formats).
- Consider per-tenant search keys to limit cross-tenant correlation.
Option B: Deterministic encryption for equality
Encrypt with a deterministic scheme so identical plaintext → identical ciphertext, then index ciphertext.
Usually not preferred vs blind indexes because:
- Deterministic encryption leaks duplicates and can be more fragile/misused.
- Many AEAD modes require random nonces; deterministic usage is specialized.
Option C: Range queries / LIKE / order-by on encrypted fields
This is where things get ugly:
- Order-preserving / order-revealing encryption leaks a lot and is generally discouraged for secrets.
- Practical pattern: don’t do range queries on secrets. Instead:
- Store a non-sensitive derived value for querying (e.g., last4, issuer, type).
- Or decrypt in application after narrowing candidate set by other indexed columns.
Option D: Advanced searchable encryption / enclaves / FHE
Exists, but complexity is high and leakage is still non-trivial. Only worth it for niche requirements.
6) Rotation strategies (what to rotate and when)
- KEK rotation (KMS key rotation):
- Often just update KMS key version/alias; old ciphertext DEKs still unwrap via old versions.
- Optionally rewrap DEKs asynchronously to the newest KEK.
- DEK rotation:
- Re-encrypt secrets with a new DEK (per row or per tenant).
- Often done lazily: on read, decrypt with old DEK then re-encrypt with new and update row.
- Blind index / search key rotation:
- Requires recomputing tokens. Plan for dual-write / dual-read during transition (store
token_v1, token_v2 until complete).
7) What this pattern does not solve (common pitfalls)
- If attackers can run code as your service role, they can call KMS decrypt and recover secrets.
- “Encryption at rest” at the DB volume layer is not a substitute for application-layer envelope encryption (it mainly protects lost disks/snapshots).
- Logging/telemetry often becomes the weakest link: don’t log plaintext, decrypted values, or HMAC tokens if those tokens are effectively identifiers.
8) Quick recommended default design
- Envelope encryption with per-tenant DEK (wrapped in KMS).
- AEAD: AES-256-GCM (or XChaCha20-Poly1305) with per-record random nonce.
- AAD includes
{tenant_id, record_id, field_name, enc_version}.
- Optional blind index column(s) using HMAC-SHA-256 with a separate per-tenant search key (itself wrapped in KMS).
- Strict KMS IAM: only the specific service identity can decrypt, with audit logs enabled and alerts on unusual decrypt volume.
If you share: (a) DB type, (b) whether you need equality search and on which fields, (c) single-tenant vs multi-tenant, I can propose a concrete schema + rotation + query plan that fits your exact use case.