Skip to content

Lesson 9 of 30Identity and security

KMS, Secrets Manager and Parameter Store

How KMS keys, key policies and envelope encryption really work, and how to store, consume and rotate secrets without downtime.

21 min read0/3 questions

A security review lands on your team's API: "The database password is in a .env file baked into the image, the S3 exports use the default key, and nobody can say who decrypted what last month." Fixing it touches three services. KMS holds the keys and decides who may use them. Secrets Manager and Parameter Store hold the secrets and configuration your code reads. Getting them right is mostly about permissions, caching and rotation, and the mistakes are the kind that cause either a breach or a 2 a.m. outage when a password rotates. You met encryption at rest in the S3 lesson and execution roles reading secrets in the Lambda and containers lessons. This lesson goes underneath.

Three kinds of KMS key

A KMS key is a logical key: an ID, an ARN, a key policy and one or more versions of key material that never leave KMS's hardware security modules unencrypted. You never see the key material. You send data to KMS, or ask it for data keys, and every call is checked against policy and logged in CloudTrail.

Customer managedAWS managedAWS owned
Who creates itYouA service, in your accountA service, in its own account
Examplealias/invoicesalias/aws/s3, alias/aws/ssmS3's default SSE-S3 keys
You control the key policyYesNo (viewable only)No (not even viewable)
RotationOptional, you chooseEvery year, automaticDecided by the service
CloudTrail shows its useYesYesNo
Usable from another accountYesNoNot applicable

The practical rule: use a customer managed key whenever you need to control who can decrypt, audit its use, or share encrypted data across accounts. AWS managed keys are a legacy type that new services no longer create. They are fine for single-account encryption, but you cannot change their policy, so cross-account access to data encrypted with aws/s3 is impossible. People find that out the hard way during the multi-account migration.

Key policies are the root of access

For almost every AWS resource, an IAM policy in the same account is enough to grant access. KMS is the big exception. Every KMS key has exactly one key policy, it is mandatory, and nothing works unless the key policy allows it, directly or by delegating to IAM.

The default key policy created by the API contains one statement:

the statement that makes IAM policies work
{
  "Sid": "Enable IAM User Permissions",
  "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::111111111111:root" },
  "Action": "kms:*",
  "Resource": "*"
}

It does not give everyone in the account access. The account principal means "this account may use IAM policies to grant access to this key". With it, an IAM policy allowing kms:Decrypt on the key works. Remove it and IAM Allows on that key are ignored (IAM Denies still apply), and if the only principal left in the key policy is deleted, the key becomes unmanageable until AWS Support helps you recover it.

A good production key policy separates key administrators (manage the key, cannot use it to decrypt) from key users (encrypt and decrypt, cannot change the policy). Admins who can edit the policy can always grant themselves decrypt, so keep that group small and audited.

Three more pieces you will meet:

  • Aliases like alias/invoices are friendly names that point at a key. Code refers to the alias, and you can repoint it to a new key during a manual rotation.
  • Grants are narrow, delegated permissions that services create on your behalf. When you attach an encrypted EBS volume, EC2 creates a grant so it can decrypt for that volume only. The default console key policy lets key users create grants only for AWS resources, via the kms:GrantIsForAWSResource condition.
  • Deletion is scheduled, with a waiting period of 7 to 30 days. Deleting a key destroys every piece of data encrypted under it, so prefer disabling a key first and watch CloudTrail for failed calls.

Envelope encryption

KMS Encrypt accepts at most 4,096 bytes. That is enough for a password, not for a PDF or a database page. Sending gigabytes to KMS would be slow anyway. So AWS services and the AWS Encryption SDK use envelope encryption:

Envelope encryption of one file
AppKMSS3GenerateDataKey(alias/invoices, context)plaintext key + encrypted keyAES-GCM encrypt file, wipe plaintext keyPUT ciphertext + wrapped keyDecrypt(wrapped key, same context)plaintext data key

The app asks KMS for a fresh 256-bit data key.

1/6

The encryption context is a set of non-secret key-value pairs, like {"tenant": "acme"}, bound to the ciphertext as additional authenticated data. Decrypt must present exactly the same context or it fails. It is written to CloudTrail in plaintext, so it doubles as an audit trail ("who decrypted acme's data?"), and you can require it in key policies with kms:EncryptionContext:tenant. Never put secrets in it.

Here is the whole thing with a fake KMS. The cipher is a toy built from the standard library so it runs in your browser; real code uses AES-GCM through the AWS Encryption SDK or a vetted library.

Pythonenvelope.py
import hashlib, hmac, json, os def toy_seal(key, plaintext, aad=b""): # Toy authenticated cipher for the demo ONLY. Real code uses AES-GCM. nonce = os.urandom(12) stream = hashlib.shake_256(key + nonce).digest(len(plaintext)) ct = bytes(a ^ b for a, b in zip(plaintext, stream)) tag = hmac.new(key, nonce + aad + ct, "sha256").digest() return {"nonce": nonce, "ct": ct, "tag": tag} def toy_open(key, box, aad=b""): good = hmac.new(key, box["nonce"] + aad + box["ct"], "sha256").digest() if not hmac.compare_digest(good, box["tag"]): raise ValueError("InvalidCiphertextException") stream = hashlib.shake_256(key + box["nonce"]).digest(len(box["ct"])) return bytes(a ^ b for a, b in zip(box["ct"], stream)) class FakeKMS: def __init__(self): self.keys, self.calls = {}, 0 def create_key(self, key_id, allowed): self.keys[key_id] = {"material": [os.urandom(32)], "allowed": set(allowed)} def rotate(self, key_id): self.keys[key_id]["material"].append(os.urandom(32)) # old versions are kept def _check(self, key_id, caller): self.calls += 1 if caller not in self.keys[key_id]["allowed"]: raise PermissionError(f"AccessDenied: key policy does not allow {caller}") def encrypt(self, key_id, caller, plaintext, context=None): self._check(key_id, caller) if len(plaintext) > 4096: raise ValueError(f"ValidationException: {len(plaintext)} bytes, max 4096") k = self.keys[key_id] version = len(k["material"]) - 1 aad = json.dumps(context or {}, sort_keys=True).encode() return {"key": key_id, "v": version, **toy_seal(k["material"][version], plaintext, aad)} def decrypt(self, blob, caller, context=None): self._check(blob["key"], caller) aad = json.dumps(context or {}, sort_keys=True).encode() return toy_open(self.keys[blob["key"]]["material"][blob["v"]], blob, aad) def generate_data_key(self, key_id, caller, context=None): data_key = os.urandom(32) return data_key, self.encrypt(key_id, caller, data_key, context) kms = FakeKMS()APP = "role/invoice-api"kms.create_key("alias/invoices", allowed=[APP])ctx = {"tenant": "acme"}pdf = b"%PDF invoice 2026-10 " * 50_000 # about 1 MB try: kms.encrypt("alias/invoices", APP, pdf, ctx)except ValueError as e: print("1 direct Encrypt:", e) data_key, wrapped_key = kms.generate_data_key("alias/invoices", APP, ctx)stored = {"wrapped_key": wrapped_key, "body": toy_seal(data_key, pdf)}del data_key # never store the plaintext keyprint("2 stored:", len(stored["body"]["ct"]), "bytes body,", len(wrapped_key["ct"]), "byte wrapped key") key = kms.decrypt(stored["wrapped_key"], APP, ctx)print("3 round trip ok:", toy_open(key, stored["body"]) == pdf) try: kms.decrypt(stored["wrapped_key"], APP, {"tenant": "globex"})except ValueError as e: print("4 wrong context:", e) kms.rotate("alias/invoices")print("5 after rotation, old file opens:", toy_open(kms.decrypt(stored["wrapped_key"], APP, ctx), stored["body"]) == pdf, "| new data keys use version", kms.generate_data_key("alias/invoices", APP, ctx)[1]["v"]) try: kms.decrypt(stored["wrapped_key"], "role/analytics", ctx)except PermissionError as e: print("6", e)print("KMS calls so far:", kms.calls)
Output
Press Run (⌘ Enter) to see what happens.

Line 5 shows rotation in action: the old file still opens because the wrapped key records which version of key material encrypted it, and KMS keeps every version. Rotation never re-encrypts your data, it only changes what new encryptions use.

Predict the outputPython

Your service encrypts 1,000 uploads, each with its own fresh data key, then reads each upload back once. Using the fake KMS above, how many KMS calls does that add?

for i in range(1000):
  dk, wrapped = kms.generate_data_key("alias/invoices", APP, ctx)
  box = toy_seal(dk, b"upload %d" % i)
  toy_open(kms.decrypt(wrapped, APP, ctx), box)
Need a nudge? Hints walk you through it.

Rotation, quotas and the S3 Bucket Key

Automatic rotation applies to symmetric customer managed keys with KMS-generated material. It is off by default; once enabled, the default period is 365 days, and you can set anything from 90 to 2,560 days. You can also rotate on demand. The key ID, ARN, alias and policy stay the same, so no code changes. Asymmetric keys, HMAC keys and keys in custom key stores cannot rotate automatically: you rotate them manually by creating a new key and moving the alias.

KMS has request quotas, shared across all keys in an account and Region for cryptographic operations. Exceed them and you get ThrottlingException, which shows up as mysterious S3, DynamoDB or SQS errors because those services call KMS for you. The exact numbers vary by Region and operation, so check the KMS quotas page and Service Quotas before a big launch. The fixes, in order:

  1. S3 Bucket Keys for SSE-KMS buckets: one setting, up to 99% fewer KMS calls.
  2. Data key caching in your own envelope encryption (the AWS Encryption SDK supports it), with limits on age and number of messages per key.
  3. Retries with backoff, and a quota increase request if you still need it.

Every KMS request is also billed, which is a second reason Bucket Keys are on by default in most modern setups.

Cross-account and multi-Region keys

To let a role in account A decrypt with a key in account B, both sides must agree, just like any cross-account request:

  • B's key policy allows A's role (or account A as a whole, delegating to A's IAM) to call kms:Decrypt.
  • A's IAM policy for the role allows kms:Decrypt on the key's full ARN. Aliases cannot be used to name a key in another account's IAM policy, so use the key ARN.

This is the third policy in the "Lambda reads an encrypted bucket in another account" interview question from IAM Policies in Depth, and the most often forgotten.

Multi-Region keys are sets of keys in several Regions that share the same key ID (starting with mrk-) and key material. Data encrypted in eu-west-1 can be decrypted in eu-central-1 by the replica without calling across Regions. Use them for disaster recovery and globally replicated data such as DynamoDB global tables with client-side encryption. Each replica still has its own key policy. Do not use them by default: one shared key across Regions widens the blast radius of a policy mistake.

Secrets Manager vs Parameter Store

Both store values your app reads at runtime. They overlap, and most companies use both.

Secrets ManagerParameter Store
Built forCredentials, API keys, certificatesConfiguration, feature flags, some secrets
Max value size64 KB4 KB standard, 8 KB advanced
EncryptionAlways, with a KMS keyOnly SecureString parameters, with a KMS key
RotationBuilt in: managed rotation or a Lambda rotation functionNone built in
VersionsVersions with staging labels AWSCURRENT, AWSPREVIOUS, AWSPENDINGNumbered versions and labels
Cross-accountResource policy on the secret, plus the KMS key policyAdvanced tier parameters, shared with AWS RAM
Multi-RegionReplica secretsNo replication
BillingPer secret per month plus API callsStandard tier: no additional charge; advanced tier is billed

A sensible default: database credentials and third-party API keys in Secrets Manager, because rotation and auditing matter. Plain configuration (/payments/prod/log-level, feature flags, endpoint URLs) in Parameter Store's standard tier, organized as a path hierarchy so a role can read /payments/prod/* and nothing else. For cross-account secrets, remember the KMS rule: a secret encrypted with the default aws/secretsmanager key cannot be read from another account. Use a customer managed key.

Match the pairs0/5 matched

Match each item to where it belongs.

Choose an item, then its match on the other side.

Consuming secrets in your code

How your app reads a secret decides how it behaves when the secret changes.

ECS resolves secrets in the task definition once, at task start, using the execution role, and injects them as environment variables. Pick a JSON field with the valueFrom suffix:

task definition excerpt
"secrets": [
  { "name": "DB_PASSWORD",
    "valueFrom": "arn:aws:secretsmanager:eu-west-1:111111111111:secret:prod/db-AbCdEf:password::" },
  { "name": "LOG_LEVEL",
    "valueFrom": "arn:aws:ssm:eu-west-1:111111111111:parameter/payments/prod/log-level" }
]

After a rotation, running tasks still hold the old value. You need a new deployment to pick up the new one, or the app must fetch the secret itself.

Lambda functions should not call GetSecretValue on every invocation. The AWS Parameters and Secrets Lambda Extension runs a local HTTP cache on port 2773 inside the execution environment, with a default TTL of 300 seconds. Powertools for AWS Lambda offers the same idea as a library.

Your own code (boto3 in a container, a long-running worker) should cache with a TTL and refetch when the database rejects the password:

app/secrets.py
import json
import time
 
import boto3
 
_client = boto3.client("secretsmanager")
_cache: dict[str, tuple[float, dict]] = {}
 
def get_secret(secret_id: str, ttl: int = 300, force: bool = False) -> dict:
    now = time.monotonic()
    hit = _cache.get(secret_id)
    if hit and not force and now - hit[0] < ttl:
        return hit[1]
    value = json.loads(_client.get_secret_value(SecretId=secret_id)["SecretString"])
    _cache[secret_id] = (now, value)
    return value

Never put secrets in Lambda environment variables, Docker images, CDK or Terraform code, or .env files in git. Anyone with read access to the function configuration, the image or the repo has them, and they never rotate.

Rotation without downtime

Secrets Manager rotation runs four steps, each a call to your rotation function (or AWS's, for managed rotation):

  1. createSecret: generate a new password and store it as a new version labeled AWSPENDING.
  2. setSecret: change the password in the database.
  3. testSecret: log in with the pending version.
  4. finishSecret: move AWSCURRENT to the new version. The old one becomes AWSPREVIOUS.

The danger is the gap between steps 2 and 4, and between step 4 and the moment every app instance refreshes its cache. With the single-user strategy, the old password stops working the instant setSecret runs, so any instance still holding it fails until its cache expires. The alternating-users strategy keeps two database users, app and app_clone, and changes the password of the one not currently in use. The old credentials stay valid until the next rotation.

Simulate both. Requests arrive every 10 seconds for 30 minutes, the app caches the secret for 300 seconds, and the secret rotates twice.

Pythonrotation.py
import itertools def simulate(strategy, retry_on_auth_failure, ttl=300): db = {"app": "pw1", "app_clone": None} # live database users versions = {"AWSCURRENT": ("app", "pw1")} # the secret's staging labels counter = itertools.count(2) cache, fetched_at, failures = None, -10**9, 0 def rotate(): old_user, _ = versions["AWSCURRENT"] if strategy == "single": user = old_user # change the one user's password else: user = "app_clone" if old_user == "app" else "app" # flip to the other user new = (user, f"pw{next(counter)}") versions["AWSPENDING"] = new # createSecret db[user] = new[1] # setSecret assert db[new[0]] == new[1] # testSecret versions["AWSPREVIOUS"] = versions["AWSCURRENT"] versions["AWSCURRENT"] = versions.pop("AWSPENDING") # finishSecret for t in range(0, 1800, 10): # one request every 10 seconds if t in (650, 1250): rotate() if t - fetched_at >= ttl: # cache expired: GetSecretValue cache, fetched_at = versions["AWSCURRENT"], t user, pw = cache if db[user] != pw: # database rejects the login if retry_on_auth_failure: cache, fetched_at = versions["AWSCURRENT"], t user, pw = cache if db[user] != pw: failures += 1 return failures print("single user, plain TTL cache: ", simulate("single", False), "failed requests")print("single user, refetch on failure: ", simulate("single", True), "failed requests")print("alternating users, plain cache: ", simulate("alternating", False), "failed requests")
Output
Press Run (⌘ Enter) to see what happens.

Single user with a plain cache fails every request between the rotation and the next cache refresh, twice. Refetching on an authentication error fixes it, because the new password is already AWSCURRENT. Alternating users never fails, as long as rotations are further apart than your cache TTL and your longest-lived connection. Use both in production: alternating users for high-traffic databases, and refetch-on-auth-failure in every client, because some secret, someday, will rotate on a schedule you forgot.

Quick check
An ECS service reads its DB password through secrets in the task definition. The secret rotates with the single-user strategy at 02:00. What happens to running tasks?
Need a nudge? A hint rules out a wrong answer.
Key terms
customer managed key
A KMS key you create and control: its policy, rotation, aliases and deletion. Required for cross-account sharing.
key policy
The mandatory resource policy on a KMS key. Access works only if it allows the caller or delegates to the account's IAM.
envelope encryption
Encrypting data locally with a data key, and storing that data key encrypted under a KMS key next to the data.
data key
A symmetric key from GenerateDataKey, returned in plaintext and wrapped, used to encrypt the actual data.
encryption context
Non-secret key-value pairs bound to a ciphertext. Decrypt must match it exactly, and it appears in CloudTrail.
staging label
A pointer such as AWSCURRENT or AWSPENDING to one version of a Secrets Manager secret.
alternating users
A rotation strategy that switches between two database users so old credentials stay valid during rotation.