Secrets Handling in Production with Envelope Encryption

Authentication & Security

Protect customer credentials securely with envelope encryption, AES-GCM, AWS KMS, tenant context, safe logging, rotation, and recovery for Python services.

TL;DR

  • Do not commit credentials, put them in ordinary application settings, or rely on database disk encryption alone. Use a secret manager for service credentials and envelope encryption when a product must store customer-supplied secrets.
  • Envelope encryption uses a fresh data encryption key (DEK) for each record or secret version and a key-management service (KMS) key to wrap that DEK. Store ciphertext and the wrapped DEK, never the plaintext DEK.
  • AES-GCM provides authenticated encryption. Use a unique 12-byte nonce for each encryption under a given key, persist it with the ciphertext, and bind stable record context as associated data.
  • Plaintext must exist in application memory while a provider call is made. Python does not provide a reliable guarantee that every copy can be zeroed immediately. Minimize scope and lifetime, block logs and traces, and control process access.
  • Plan for key rotation, credential revocation, backup restoration, tenant isolation, and audit records before storing the first secret.

Protect the full secret lifecycle

An API key stored in a customer integration form may appear in a database backup, a query trace, an exception, or a support export long after the original request completed. Database encryption at rest protects storage media against some physical or infrastructure-level exposures. It does not automatically protect a credential from an application role, SQL console, query log, or developer who can read the value through the application.

Separate the problem into lifecycle steps: create or receive a credential, authorize who may use it, encrypt it before persistence, retrieve it only when an operation needs it, rotate or revoke it, and delete or retain it according to a documented policy. A secret manager can own credentials needed by your service, such as the KMS key identifier or database password. For per-customer provider keys that the application must retrieve later, application-layer envelope encryption can add a boundary between ordinary database reads and usable plaintext.

No design makes a credential safe once an authorized process has decrypted and transmitted it to its provider. The goal is to reduce where plaintext can appear, which identities can obtain it, and how long it stays useful. OWASP recommends centralized secret lifecycle management, least privilege, auditing, rotation, and preventing plaintext from entering logs. OWASP Secrets Management Cheat Sheet · OWASP Logging Cheat Sheet

Choose a storage boundary before choosing an algorithm

Prefer a managed secret store for credentials that belong to your deployment. Workload identity should authorize the running service to retrieve only the required secret versions. The application can then avoid placing long-lived KMS credentials in environment variables or source code.

Use envelope encryption when a product stores tenant-owned provider credentials in its own database. The database holds an encrypted secret payload, a wrapped DEK, a format version, a nonce, and non-sensitive metadata such as the provider name. A KMS key protects the DEK. The application role can request narrowly scoped encrypt/decrypt operations, while ordinary support and analytics roles see ciphertext only.

Do not invent a custom key derivation scheme for convenience. The planning backlog mentions PBKDF2-derived keys, but deriving a long-lived encryption key from a password does not replace a managed key hierarchy and can make rotation and authorization harder. Generate random data keys through KMS or a vetted encryption SDK. Use a library’s authenticated encryption implementation rather than assembling AES modes and tags manually.

How envelope encryption works

For each secret version, request a fresh symmetric data key from KMS. KMS returns a plaintext copy to encrypt the application payload and a ciphertext copy that only the KMS key can unwrap. Encrypt the secret locally with the plaintext DEK, then persist the ciphertext, nonce, and wrapped DEK together. Erase or release the plaintext DEK as soon as the encryption operation finishes. On retrieval, ask KMS to unwrap the DEK, authenticate and decrypt the payload, use the secret for one provider call, then discard references.

AWS KMS GenerateDataKey is designed for this envelope pattern. It returns both the plaintext key and its KMS-encrypted copy. The caller performs local data encryption and is responsible for managing the data-key output. KMS encryption context is useful as authenticated, non-secret metadata, but AWS logs that context in CloudTrail, so never include a password, token, email, or other confidential value in it. Decryption requires the same case-sensitive context values. AWS KMS GenerateDataKey API · AWS KMS encryption context

For a small single-field payload, an application-managed envelope can be represented conceptually as:

secret_record = {
  format_version: 1,
  tenant_id: "tenant-42",
  provider: "mail",
  secret_version: "credential-7",
  kms_key_id: "arn:aws:kms:region:account:key/...",
  wrapped_dek: "...",
  nonce: "...",
  ciphertext_and_tag: "..."
}

The tenant and secret identifiers should come from trusted server-side records, not from a caller-supplied encryption context. A stable associated-data value can bind the ciphertext to that record. If someone copies the ciphertext to a different tenant row, decryption should fail rather than silently returning the secret under the wrong identity.

Use AES-GCM correctly for local data encryption

AES-GCM is an authenticated-encryption-with-associated-data (AEAD) mode: it encrypts the plaintext and authenticates both ciphertext and optional associated data. Associated data remains visible but cannot be changed without causing authentication failure. AAD is a good place for a stable record ID, tenant ID, provider type, and schema version. It is not a place for secrets.

The Python cryptography package’s AESGCM API accepts 128-, 192-, or 256-bit keys and a 12-byte nonce. Its output includes the 16-byte authentication tag. Use a cryptographically secure nonce source and never reuse a nonce with the same AES-GCM key. A simple operational rule for envelope encryption is to create one random DEK for one payload encryption, which keeps the nonce uniqueness domain small. cryptography AESGCM API

import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def encrypt_secret(plaintext: bytes, dek: bytes, aad: bytes) -> tuple[bytes, bytes]:
    # Use a fresh DEK for this record version and a fresh nonce.
    nonce = os.urandom(12)
    ciphertext_and_tag = AESGCM(dek).encrypt(nonce, plaintext, aad)
    return nonce, ciphertext_and_tag

def decrypt_secret(nonce: bytes, ciphertext_and_tag: bytes,
                   dek: bytes, aad: bytes) -> bytes:
    # Invalid tag, changed AAD, or wrong key raises InvalidTag.
    return AESGCM(dek).decrypt(nonce, ciphertext_and_tag, aad)

This snippet only covers local AEAD. Production code must also retrieve the KMS data key, handle permissions and KMS availability, validate record versions, limit payload size, map failures safely, and avoid logging plaintext or cryptographic material. Prefer the AWS Encryption SDK or another maintained envelope-encryption library where its message format and multi-platform support fit the application.

Do not use an encryption key directly as an HMAC key or derive multiple unrelated purposes from it without a reviewed key hierarchy. Include a format version so that algorithm or serialization changes can be deployed without guessing how old records were encrypted.

Bind tenant identity and prevent ciphertext swapping

Encryption without binding context can leave a confused-deputy problem. Suppose the database stores an encrypted credential for tenant A and an attacker with a write path replaces tenant B’s ciphertext with it. If the application simply decrypts whichever blob is attached to the current row, it may use tenant A’s credential for a tenant B operation.

Construct associated data on the server from immutable identifiers such as tenant_id, credential record ID, provider type, and ciphertext format version. Pass those exact bytes to both encryption and decryption. Make tenant ownership part of the authorization query as well. AEAD protects integrity of the bound data, while authorization decides whether the caller is entitled to request this record. Neither replaces the other.

For KMS encryption context, use stable opaque identifiers and operation purpose, such as tenant_id and secret_type, only if your logging policy allows them. AWS KMS records context in audit logs. Do not place customer names, email addresses, access tokens, or secret values in it. Store enough non-sensitive context with the record to reconstruct the exact match required for decryption.

Restrict the decrypt capability to the integration service identity. A support dashboard may show connection status, last validation time, and masked credential metadata without receiving the secret. Audit reads by actor, workload, tenant, credential ID, action result, and time. Avoid logging the returned bytes or exception objects that could embed request headers.

Minimize plaintext lifetime without promising memory erasure

Python strings and bytes are immutable objects. The interpreter, allocator, HTTP library, exception formatter, and TLS stack may make copies. Garbage collection removes references according to runtime behavior; it does not promise that the old bytes are overwritten immediately. A bytearray can be overwritten by application code, but that does not prove other copies no longer exist.

Therefore, “zero secrets in memory” is not a realistic promise for a conventional Python process that must send a secret to a provider. Keep plaintext use within a small function, avoid global caches, do not retain decrypted values in request state, and avoid string interpolation into logs or errors. Decrypt immediately before a provider call and discard references after the call. Run the integration worker under a separate least-privilege identity and reduce access to process inspection, core dumps, crash dumps, and debugging endpoints.

Keep ciphertext out of request logs, ORM debug output, tracing attributes, task payloads, and support exports. Redaction is defense in depth, not the primary control. Prefer an allowlist of telemetry fields rather than trying to remove every possible secret name from arbitrary dictionaries. Test known secret formats against access logs, application logs, error reporting, traces, and database query logging.

Set response models that never serialize credential columns. The safest response is a non-secret status such as “configured” or “connection failed,” with provider-specific details sanitized. Do not offer an endpoint that returns a masked version and allow it to be used as a replacement value. Use separate create, rotate, validate, and revoke operations.

Rotate KMS keys and provider credentials as separate lifecycles

A KMS key protects the wrapped data key. A provider API key authorizes a business operation. Rotating one does not automatically rotate the other. Define a rotation plan for both, with ownership, failure alerts, rollback boundaries, and an audit record.

For KMS key changes, use versioned envelopes and keep old decryption permissions until all records are rewrapped or re-encrypted and backups from the retention period can still be restored. KMS can re-encrypt an encrypted data key under another KMS key without exposing plaintext key material to the application. Data ciphertext can remain unchanged when the same DEK is still used; the wrapped DEK is replaced. Test this path against restored backups before disabling an old key.

For provider credential rotation, use the provider’s overlapping-key process when available: create a new credential, encrypt and validate it, switch new operations, then revoke the old credential. If the provider allows only one active key, plan a short controlled outage or a provider-specific staged transition. A periodic rotation schedule cannot revoke a compromised key by itself; incident response needs immediate revocation.

Keep secret version records and a status such as active, pending, revoked, or failed. A retry should not accidentally roll a tenant back to an old credential. Make secret replacement atomic at the application data layer, and ensure in-flight calls have a clear policy when credentials rotate.

Build a recovery and incident path

Encrypted backups are useful only if the organization can still decrypt the records after a restore. Document which KMS keys and context values protect each data format, who can authorize decrypt operations, how key policy changes are audited, and how to restore a key after account or region failure. Rehearse recovery with a non-production copy and the same versioned envelope format.

If a secret reaches a repository, log, or support export, revoke it first. Then identify use, rotate the provider credential, remove or restrict exposed copies where possible, and review audit logs for access. Rewriting Git history does not revoke a key and may not remove clones or caches. Treat the secret as compromised until the provider confirms revocation.

Monitor unusual decrypt volume, unexpected tenants, new workload identities, failed authentication, and reads outside expected operation paths. Alerts should not include the sensitive input that caused them. Record enough context for incident responders without copying the secret into the incident system.

See our guide to isolating untrusted file handling for another example of reducing sensitive data exposure across a processing pipeline, and our tenant-isolation guide for server-side ownership checks.

Frequently asked questions

Can Python guarantee that a decrypted secret is erased from memory?

No. Python strings and bytes are immutable, and the runtime or libraries may make copies. Releasing references or overwriting a mutable buffer does not prove that every copy was erased. Minimize the lifetime and scope of plaintext, restrict process access, disable unnecessary dumps, and avoid logs and traces.

Should I store a customer API key in AWS Secrets Manager or encrypt it in my database?

Use a managed secret store when it fits the credential ownership, access pattern, and scale. Use application-layer envelope encryption when your product must store many tenant-owned credentials alongside application records. In either case, apply least privilege, auditing, rotation, revocation, and safe retrieval.

What should be used as AES-GCM associated data?

Use stable, non-secret server-side context such as the tenant ID, credential record ID, provider type, and format version. The same bytes must be supplied during decryption. Do not include plaintext credentials or personal information, and keep encryption context distinct from authorization checks.

Does rotating the KMS key require re-encrypting every customer credential?

Not necessarily. With envelope encryption, a KMS re-encryption operation can rewrap the encrypted data key under a new KMS key while leaving the data ciphertext unchanged. Keep the old key available until records, retained backups, and restore procedures no longer depend on it.

Make the boundaries testable

Security for stored credentials depends on identity, encryption format, authorization, logs, key policy, and incident response working together. Test that a wrong tenant context fails authentication, ordinary database readers see only ciphertext, masked API responses contain no secret, rotation preserves rollback options, and restored backups remain decryptable under the documented process.

Prefer managed secret delivery for deployment credentials and application-layer envelope encryption for tenant credentials that must be retrieved later. Keep plaintext use short and observable without recording the value. If you are designing customer credential storage or reviewing a secrets lifecycle, talk with our security engineering team about key boundaries, rotation, and recovery.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with application security

Discuss your project