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.
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 managed | AWS managed | AWS owned | |
|---|---|---|---|
| Who creates it | You | A service, in your account | A service, in its own account |
| Example | alias/invoices | alias/aws/s3, alias/aws/ssm | S3's default SSE-S3 keys |
| You control the key policy | Yes | No (viewable only) | No (not even viewable) |
| Rotation | Optional, you choose | Every year, automatic | Decided by the service |
| CloudTrail shows its use | Yes | Yes | No |
| Usable from another account | Yes | No | Not 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:
{
"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/invoicesare 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:GrantIsForAWSResourcecondition. - 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:
The app asks KMS for a fresh 256-bit data key.
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.
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.
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)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:
- S3 Bucket Keys for SSE-KMS buckets: one setting, up to 99% fewer KMS calls.
- Data key caching in your own envelope encryption (the AWS Encryption SDK supports it), with limits on age and number of messages per key.
- 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:Decrypton 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 Manager | Parameter Store | |
|---|---|---|
| Built for | Credentials, API keys, certificates | Configuration, feature flags, some secrets |
| Max value size | 64 KB | 4 KB standard, 8 KB advanced |
| Encryption | Always, with a KMS key | Only SecureString parameters, with a KMS key |
| Rotation | Built in: managed rotation or a Lambda rotation function | None built in |
| Versions | Versions with staging labels AWSCURRENT, AWSPREVIOUS, AWSPENDING | Numbered versions and labels |
| Cross-account | Resource policy on the secret, plus the KMS key policy | Advanced tier parameters, shared with AWS RAM |
| Multi-Region | Replica secrets | No replication |
| Billing | Per secret per month plus API calls | Standard 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 each item to where it belongs.
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:
"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:
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 valueNever 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):
createSecret: generate a new password and store it as a new version labeledAWSPENDING.setSecret: change the password in the database.testSecret: log in with the pending version.finishSecret: moveAWSCURRENTto the new version. The old one becomesAWSPREVIOUS.
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.
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.
secrets in the task definition. The secret rotates with the single-user strategy at 02:00. What happens to running tasks?- 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.