mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(kms): serve the AWS managed keys under alias/aws/* in every region (#4792)
* feat(kms): serve the AWS managed keys under alias/aws/* in every region Every AWS account has a per-region AWS managed key for each service that encrypts data on the account's behalf, published under a reserved alias/aws/<service> alias. Floci had none, so a lookup that succeeds against any real account failed here: DescribeKey on alias/aws/s3 returned NotFoundException and ListAliases returned nothing in that namespace. Nothing declares these keys in a template, which is what made their absence costly to diagnose. A module that leaves a service's encryption at its default resolves one through a data source and fails at plan time. The catalog is data, in kms/aws-managed-keys.yaml, following the IAM managed policy catalog: adding a service is a line there. A region's keys are minted the first time anything reads that region's alias namespace, which is ListAliases or a lookup naming one of the reserved aliases. That mirrors AWS, where a service's key appears once the account first uses the service, and it keeps an unused region free. Minting is idempotent, so the ids survive a restart against persistent storage and ciphertext encrypted under them keeps decrypting. These are AWS's keys, not the account's, so DescribeKey now reports KeyManager per key instead of the constant CUSTOMER it returned before, GetKeyRotationStatus reports true for them, and the administrative operations AWS reserves to a key's owner are refused with AccessDeniedException: ScheduleKeyDeletion, CancelKeyDeletion, PutKeyPolicy, UpdateKeyDescription, EnableKey, DisableKey, EnableKeyRotation, DisableKeyRotation, RotateKeyOnDemand, TagResource and UntagResource. The alias/aws/ namespace is reserved too: CreateAlias under it is rejected with InvalidAliasNameException, and UpdateAlias or DeleteAlias against one of these aliases with AccessDeniedException. Cryptographic operations are unaffected, which is the point of the keys existing. Two deliberate simplifications, both documented: the key policy is the standard account-root policy rather than the service-principal policy with a kms:ViaService condition AWS attaches, and AWS distinguishes some of those refusals as unsupported operations rather than access denials. * fix(kms): seed only AWS managed keys, and rebuild them if the key store is lost Five corrections to the alias/aws/* catalog and the code that mints it. The catalog went from 40 entries to 23. An AWS managed key lives in the customer's account and has an alias/aws/<service> alias; an AWS owned key lives in an AWS-owned account and has no alias there, so DescribeKey on it fails against a real account. Seeding the second kind makes a call succeed here and fail against AWS, which is the worst error this emulator can produce: a module looks compatible when it is not, and nothing reports it. Seventeen entries could not be sourced to a customer-account context and are gone, EKS among them, whose API-data envelope encryption uses an AWS owned key by default. The YAML header now states the managed-versus-owned test so the next line added has a bar to clear. Minting is gated on the alias being present and the key that alias targets being present, not on the alias alone. The two stores are different files and PersistentStorage quarantines an unreadable one and starts that store empty by itself, so a lost kms-keys.json used to leave every alias dangling for the life of the instance: ListAliases advertised alias/aws/s3 while DescribeKey on it reported NotFoundException. The catalog is in the repository, so this is the one part of a damaged store that can rebuild itself, and now it does. ListKeys mints too. Real AWS returns the AWS managed keys from ListKeys unconditionally, and a caller that reads ListKeys, then DescribeKey, then filters on KeyManager saw them or not depending on whether something else had read the alias namespace earlier in the same process. Both stores are written once per region as a batch instead of once per entry. PersistentStorage.put serialises the whole map, so the old path cost two whole-file rewrites per catalog entry on the first read of every region, while holding the mint lock. The aliases are written before the keys deliberately: a crash between the two batches then leaves aliases whose target is missing, which the gate above repairs, rather than keys with no alias, which nothing repairs and which would sit in ListKeys forever. CreateAlias and UpdateAlias no longer accept an AWS managed key as the target. AWS excludes them, so a second alias on one of these keys is the same false-pass shape as seeding a key AWS does not have. The refusal is AccessDeniedException: it is an authorization outcome, the key's policy grants the account nothing, and CreateAlias publishes no error code for this case. Two pre-existing tests asserted counts that ListKeys and ListAliases now answer as AWS does; they select the customer-managed subset instead. * docs(kms): group the AWS managed key catalog by the strength of its evidence * fix(kms): drop alias/aws/elasticache and cite alias/aws/acm in the managed key catalog The ElastiCache at-rest encryption guide describes the default as a service managed key and serverless caches as using an AWS owned key; it never names alias/aws/elasticache, so the entry failed the catalog's own bar. The KMS ListAliases API reference prints alias/aws/acm with a TargetKeyId in its example output, so acm joins the cited group. * refactor(kms): fold requireCustomerManagedTarget into requireCustomerManaged The two helpers had identical bodies. Also narrow the ensureAwsManagedKeys Javadoc: writing aliases before keys helps only for a crash between the two batches; losing kms-aliases.json alone still mints fresh keys and orphans the old ones. * fix(kms): refuse CreateGrant on AWS managed keys An AWS managed key's policy allows kms:CreateGrant only via the owning service (kms:ViaService), never to the account directly, so a direct CreateGrant now gets AccessDeniedException like the other administrative refusals. * test(kms): concurrent cold reads mint each AWS managed key once Sixteen threads read ListAliases on a cold region at once; the key store must hold exactly the catalog's keys and each reserved alias must appear once. Replacing the awsManagedKeyLock monitor with a fresh Object makes this fail (138 keys minted against a 25-entry catalog). * fix(kms): register the AWS managed key catalog for native and re-point squatted reserved aliases - Add kms/*.yaml to quarkus.native.resources.includes. AwsManagedKeys reads kms/aws-managed-keys.yaml through a constant, which native resource analysis cannot follow (NativeImageResourceIncludesTest). - Reconcile a reserved alias as present only when its target is an AWS managed key. A store persisted before alias/aws/ was reserved could hold alias/aws/s3 on a customer key, which DescribeKey then reported as CUSTOMER and the AWS managed key guards let through. - When the alias store is lost but keys survive, re-alias the surviving AWS managed keys by description instead of minting a duplicate set. * docs(kms): cite the sqs, sns, ses, s3 and ebs managed aliases
This commit is contained in:
1 parent
39867e6bcb
commit
5ad97781ef
9 files changed
+1013
-14
No files matched your search
@@ -173,6 +173,55 @@ own the material and cannot rotate it.
|
||||
already has key material is rejected with `UnsupportedOperationException`, and
|
||||
`ListKeyRotations` is not implemented.
|
||||
|
||||
## AWS Managed Keys
|
||||
|
||||
Every AWS account has a per-region AWS managed key for each service that encrypts data on the
|
||||
account's behalf, published under the reserved `alias/aws/<service>` alias: `alias/aws/s3`,
|
||||
`alias/aws/ebs`, `alias/aws/rds` and so on. Nothing creates them, so no template declares them,
|
||||
but a module that leaves a service's encryption at its default resolves one through a data
|
||||
source. Floci ships the same catalog.
|
||||
|
||||
The catalog holds only **AWS managed** keys, which live in your account and do have that alias.
|
||||
It deliberately excludes services that encrypt with an **AWS owned** key, which lives in an
|
||||
AWS-owned account and has no alias in yours: EKS API-data envelope encryption is the clearest
|
||||
case. Resolving an alias AWS does not publish would be worse than not having it, since the call
|
||||
would succeed here and fail against a real account.
|
||||
|
||||
```bash
|
||||
aws kms list-aliases --query 'Aliases[?starts_with(AliasName, `alias/aws/`)].AliasName' \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
|
||||
aws kms describe-key --key-id alias/aws/s3 \
|
||||
--query KeyMetadata.KeyManager --endpoint-url $AWS_ENDPOINT_URL # -> "AWS"
|
||||
```
|
||||
|
||||
A region's AWS managed keys are minted the first time anything reads that region's key or alias
|
||||
namespace: `ListKeys`, `ListAliases`, or a lookup naming one of the reserved aliases. An entry is
|
||||
skipped only when its alias is present *and* targets an AWS managed key, so a lost or
|
||||
quarantined `kms-keys.json` rebuilds from the catalog rather than leaving every alias dangling,
|
||||
and a reserved alias persisted on a customer key is re-pointed. A lost `kms-aliases.json`
|
||||
re-aliases the surviving AWS managed keys instead of minting a second set.
|
||||
They behave as AWS's keys, not the account's:
|
||||
|
||||
- `DescribeKey` reports `KeyManager: AWS`, and `GetKeyRotationStatus` reports `true`, since AWS
|
||||
rotates them and the customer cannot turn that off.
|
||||
- They encrypt and decrypt like any other symmetric key.
|
||||
- Every administrative operation is refused with `AccessDeniedException`: `ScheduleKeyDeletion`,
|
||||
`CancelKeyDeletion`, `PutKeyPolicy`, `UpdateKeyDescription`, `EnableKey`, `DisableKey`,
|
||||
`EnableKeyRotation`, `DisableKeyRotation`, `RotateKeyOnDemand`, `TagResource`,
|
||||
`UntagResource` and `CreateGrant` (AWS's key policy allows grants only via the owning service).
|
||||
- The `alias/aws/` namespace is reserved. `CreateAlias` under it is rejected with
|
||||
`InvalidAliasNameException`, and `UpdateAlias` or `DeleteAlias` against one of these aliases is
|
||||
rejected with `AccessDeniedException`.
|
||||
- They cannot be given a second alias. `CreateAlias` or `UpdateAlias` naming an AWS managed key as
|
||||
the target is rejected with `AccessDeniedException`.
|
||||
|
||||
Two deliberate simplifications: the key policy is the standard account-root policy rather than
|
||||
the service-principal policy with a `kms:ViaService` condition that AWS attaches, and AWS
|
||||
distinguishes some of the refusals above as unsupported operations rather than access denials.
|
||||
The catalog itself is `src/main/resources/kms/aws-managed-keys.yaml`; adding a service is a line
|
||||
there.
|
||||
|
||||
## Grant Support Scope
|
||||
|
||||
Grant lifecycle operations (`CreateGrant`, `ListGrants`, `ListRetirableGrants`, `RevokeGrant`, `RetireGrant`) are supported. However, grant lifecycle support **does not** imply grant-based authorization enforcement on cryptographic operations (`Encrypt`, `Decrypt`, `Sign`, `Verify`, `GenerateDataKey`, etc.). Grants are stored and queryable but are not evaluated during crypto operations.
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.hectorvent.floci.services.kms;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Catalog of the AWS managed KMS keys every account has, loaded from
|
||||
* {@code kms/aws-managed-keys.yaml}.
|
||||
*
|
||||
* <p>These keys are reference data no customer creates: AWS ships one per service per region
|
||||
* and publishes it under the reserved {@code alias/aws/<service>} alias. Nothing in a Terraform
|
||||
* or CloudFormation template declares them, which is exactly why their absence is invisible to
|
||||
* dependency analysis and fatal at plan time: a module that leaves a service's encryption at its
|
||||
* default reads {@code alias/aws/s3} or {@code alias/aws/ebs} through a data source, and that
|
||||
* lookup succeeds against any real account.
|
||||
*
|
||||
* <p>The catalog is data rather than a list in Java so that adding a service is a line in the
|
||||
* YAML. It is parsed once into an immutable list. The YAML is read through a constant, which
|
||||
* Quarkus's native resource analysis cannot follow, so it is registered under
|
||||
* {@code quarkus.native.resources.includes} in {@code application.yml}.
|
||||
*/
|
||||
final class AwsManagedKeys {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsManagedKeys.class);
|
||||
|
||||
/** The alias prefix AWS reserves for its own keys. A customer alias may not use it. */
|
||||
static final String RESERVED_ALIAS_PREFIX = "alias/aws/";
|
||||
|
||||
private static final String CATALOG_RESOURCE_NAME = "kms/aws-managed-keys.yaml";
|
||||
|
||||
/**
|
||||
* One AWS managed key.
|
||||
*
|
||||
* @param aliasName the reserved alias AWS publishes the key under, e.g. {@code alias/aws/s3}
|
||||
* @param description the description DescribeKey reports for it
|
||||
*/
|
||||
record AwsManagedKeyDef(String aliasName, String description) {
|
||||
}
|
||||
|
||||
static final List<AwsManagedKeyDef> KEYS = load();
|
||||
|
||||
private AwsManagedKeys() {
|
||||
}
|
||||
|
||||
/** Whether an alias name falls in the {@code alias/aws/} namespace AWS reserves for itself. */
|
||||
static boolean isReservedAlias(String aliasName) {
|
||||
return aliasName != null && aliasName.startsWith(RESERVED_ALIAS_PREFIX);
|
||||
}
|
||||
|
||||
private static List<AwsManagedKeyDef> load() {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream(CATALOG_RESOURCE_NAME)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException(
|
||||
"AWS managed key catalog not found on the classpath: " + CATALOG_RESOURCE_NAME);
|
||||
}
|
||||
Catalog catalog = new ObjectMapper(new YAMLFactory()).readValue(in, Catalog.class);
|
||||
List<AwsManagedKeyDef> defs = new ArrayList<>();
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
Set<String> seenDescriptions = new LinkedHashSet<>();
|
||||
for (CatalogEntry entry : catalog.keys == null ? List.<CatalogEntry>of() : catalog.keys) {
|
||||
if (entry.alias == null || entry.alias.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String alias = entry.alias.trim();
|
||||
if (!isReservedAlias(alias)) {
|
||||
// A name outside the reserved namespace would mint a key an ordinary customer
|
||||
// alias could then collide with. Drop it rather than seed it.
|
||||
LOG.warnv("Ignoring AWS managed key {0}: the alias is not under {1}",
|
||||
alias, RESERVED_ALIAS_PREFIX);
|
||||
continue;
|
||||
}
|
||||
if (!seen.add(alias)) {
|
||||
LOG.warnv("Ignoring duplicate AWS managed key entry for {0}", alias);
|
||||
continue;
|
||||
}
|
||||
String description = entry.description == null ? "" : entry.description;
|
||||
if (!seenDescriptions.add(description)) {
|
||||
// Surviving keys are re-aliased by description, so a shared one could hand
|
||||
// a key the other entry's alias.
|
||||
LOG.warnv("Ignoring AWS managed key {0}: its description duplicates another entry", alias);
|
||||
continue;
|
||||
}
|
||||
defs.add(new AwsManagedKeyDef(alias, description));
|
||||
}
|
||||
LOG.debugv("Loaded {0} AWS managed keys from {1}", defs.size(), CATALOG_RESOURCE_NAME);
|
||||
return List.copyOf(defs);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(
|
||||
"Failed to read the AWS managed key catalog: " + CATALOG_RESOURCE_NAME, e);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
static final class Catalog {
|
||||
public List<CatalogEntry> keys;
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
static final class CatalogEntry {
|
||||
public String alias;
|
||||
public String description;
|
||||
}
|
||||
}
|
||||
@@ -771,7 +771,7 @@ public class KmsJsonHandler {
|
||||
if (k.getValidTo() > 0) {
|
||||
keyMetadata.put("ValidTo", k.getValidTo());
|
||||
}
|
||||
keyMetadata.put("KeyManager", "CUSTOMER");
|
||||
keyMetadata.put("KeyManager", k.getKeyManager());
|
||||
keyMetadata.put("CustomerMasterKeySpec", k.getKeySpec().name());
|
||||
keyMetadata.put("KeySpec", k.getKeySpec().name());
|
||||
keyMetadata.put("MultiRegion", k.isMultiRegion());
|
||||
|
||||
@@ -43,6 +43,7 @@ public class KmsService implements ResourceProvider {
|
||||
private static final Logger LOG = Logger.getLogger(KmsService.class);
|
||||
|
||||
private static final String AWS_KMS_ORIGIN = "AWS_KMS";
|
||||
private static final String AWS_KEY_MANAGER = "AWS";
|
||||
private static final String EXTERNAL_ORIGIN = "EXTERNAL";
|
||||
private static final String PENDING_IMPORT = "PendingImport";
|
||||
private static final String PENDING_DELETION = "PendingDeletion";
|
||||
@@ -63,6 +64,9 @@ public class KmsService implements ResourceProvider {
|
||||
// Guards the check-generate-put sequence in ensureBackingKeyMaterial so two concurrent
|
||||
// first uses of the same legacy key cannot each mint a different backing key.
|
||||
private final Object backingKeyMaterialLock = new Object();
|
||||
// Guards the scan-and-mint sequence in ensureAwsManagedKeys so two concurrent first reads of
|
||||
// a region's alias namespace cannot each mint a key for the same alias/aws/* name.
|
||||
private final Object awsManagedKeyLock = new Object();
|
||||
|
||||
@Inject
|
||||
public KmsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
@@ -366,6 +370,11 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public List<KmsKey> listKeys(String region) {
|
||||
// Real AWS returns the AWS managed keys from ListKeys unconditionally. Without this, a
|
||||
// caller that filters on KeyManager (cloud-nuke reads ListKeys, then DescribeKey, then
|
||||
// skips anything that is not CUSTOMER) would see them or not depending on whether
|
||||
// something else had read the alias namespace earlier in the same process.
|
||||
ensureAwsManagedKeys(region);
|
||||
String prefix = region + "::";
|
||||
return keyStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
@@ -491,6 +500,9 @@ public class KmsService implements ResourceProvider {
|
||||
validateGrantConstraints(constraints);
|
||||
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
// An AWS managed key's policy allows kms:CreateGrant only through the service that owns
|
||||
// it (a kms:ViaService condition), never to the account directly.
|
||||
requireCustomerManaged(key, "kms:CreateGrant");
|
||||
requireNotPendingDeletion(key);
|
||||
String grantId = UUID.randomUUID().toString();
|
||||
byte[] tokenBytes = new byte[32];
|
||||
@@ -684,6 +696,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void scheduleKeyDeletion(String keyId, int pendingWindowInDays, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:ScheduleKeyDeletion");
|
||||
requireNotPendingDeletion(key);
|
||||
key.setKeyState("PendingDeletion");
|
||||
key.setDeletionDate(Instant.now().plusSeconds((long) pendingWindowInDays * 86400).getEpochSecond());
|
||||
@@ -697,6 +710,7 @@ public class KmsService implements ResourceProvider {
|
||||
*/
|
||||
public void cancelKeyDeletion(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:CancelKeyDeletion");
|
||||
if (lacksImportedKeyMaterial(key)) {
|
||||
key.setKeyState(PENDING_IMPORT);
|
||||
key.setEnabled(false);
|
||||
@@ -721,6 +735,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void putKeyPolicy(String keyId, String policy, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:PutKeyPolicy");
|
||||
key.setPolicy(policy);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
LOG.infov("Updated key policy for KMS key: {0} in {1}", key.getKeyId(), region);
|
||||
@@ -749,6 +764,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void updateKeyDescription(String keyId, String description, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:UpdateKeyDescription");
|
||||
requireNotPendingDeletion(key);
|
||||
key.setDescription(description);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -768,6 +784,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void enableKeyRotation(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:EnableKeyRotation");
|
||||
validateRotationOrigin(key);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
validateRotationKeySpec(key);
|
||||
@@ -778,6 +795,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void disableKeyRotation(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:DisableKeyRotation");
|
||||
validateRotationOrigin(key);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
key.setKeyRotationEnabled(false);
|
||||
@@ -787,6 +805,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void enableKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:EnableKey");
|
||||
requireNotPendingDeletion(key);
|
||||
requireImportedKeyMaterial(key);
|
||||
key.setEnabled(true);
|
||||
@@ -797,6 +816,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void disableKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:DisableKey");
|
||||
requireNotPendingDeletion(key);
|
||||
requireImportedKeyMaterial(key);
|
||||
key.setEnabled(false);
|
||||
@@ -809,6 +829,7 @@ public class KmsService implements ResourceProvider {
|
||||
public String rotateKeyOnDemand(String keyId, String region) {
|
||||
synchronized (backingKeyMaterialLock) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:RotateKeyOnDemand");
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
if (MULTI_REGION_REPLICA.equals(key.getMultiRegionKeyType())) {
|
||||
throw new AwsException("UnsupportedOperationException",
|
||||
@@ -1163,13 +1184,178 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────── AWS Managed Keys ───────────────────────
|
||||
|
||||
/**
|
||||
* Materializes this region's AWS managed keys, the per-service keys every account has under
|
||||
* the reserved {@code alias/aws/*} aliases.
|
||||
*
|
||||
* <p>Nothing creates these: AWS ships them, and a module that leaves a service's encryption at
|
||||
* its default resolves one through a data source. Without them a lookup that succeeds against
|
||||
* any real account fails here, which is what makes their absence expensive: no template
|
||||
* declares them, so no dependency analysis reports them missing.
|
||||
*
|
||||
* <p>They are minted on first read of a region's key or alias namespace rather than at
|
||||
* startup, which keeps an unused region free and mirrors AWS, where the key for a service
|
||||
* appears once the account first uses that service. The entry points are the three reads of
|
||||
* those namespaces: {@link #listKeys}, {@link #listAliases(String, String)} and
|
||||
* {@link #resolveKey} for an identifier naming a reserved alias. The keys are written to the
|
||||
* key store rather than held beside it as the IAM managed policy catalog is, because unlike a
|
||||
* policy document a key carries per-account state: an id, an ARN and backing key material
|
||||
* that ciphertext is bound to. A few dozen keys of state is a different proposition from a
|
||||
* megabyte of policy documents.
|
||||
*
|
||||
* <p>An entry is skipped only when its alias is present <em>and</em> the key that alias
|
||||
* targets is present. Gating on the alias alone is not enough, because the two live in
|
||||
* different files and {@code PersistentStorage} quarantines an unreadable one and starts that
|
||||
* store empty on its own: a lost key store would leave every alias dangling for the life of
|
||||
* the instance, with {@code DescribeKey alias/aws/s3} reporting NotFoundException while
|
||||
* {@code ListAliases} still advertised it. The catalog is checked into the repository, so this
|
||||
* is the one part of a damaged store that can rebuild itself, and it does. This follows
|
||||
* {@link #ensureBackingKeyMaterial}, which self-heals a key persisted before the backing-key
|
||||
* envelope existed the same way.
|
||||
*
|
||||
* <p>Both stores are written once, as a batch, rather than per entry: {@code PersistentStorage}
|
||||
* serialises its whole map on every {@code put}, so per-entry writes cost two file rewrites per
|
||||
* catalog entry, on the first read of every region, while holding this lock. The aliases are
|
||||
* written before the keys deliberately, for the case of a crash between the two batches: it
|
||||
* then leaves aliases whose target is missing, which the gate above repairs on the next read,
|
||||
* where the other order would leave keys with no alias that sit in ListKeys forever. The order
|
||||
* does not cover {@code kms-aliases.json} alone being lost; for that, a surviving AWS managed
|
||||
* key no reserved alias targets is re-aliased by description rather than minted again. A
|
||||
* reserved alias whose target is a customer key (one created before the namespace was
|
||||
* reserved) counts as missing and is re-pointed.
|
||||
*/
|
||||
private void ensureAwsManagedKeys(String region) {
|
||||
synchronized (awsManagedKeyLock) {
|
||||
Map<String, KmsKey> newKeys = new LinkedHashMap<>();
|
||||
Map<String, KmsAlias> newAliases = new LinkedHashMap<>();
|
||||
Map<String, KmsKey> orphans = null;
|
||||
for (AwsManagedKeys.AwsManagedKeyDef def : AwsManagedKeys.KEYS) {
|
||||
String aliasStorageKey = region + "::" + def.aliasName();
|
||||
if (resolvesToAnAwsManagedKey(aliasStore.get(aliasStorageKey), region)) {
|
||||
continue;
|
||||
}
|
||||
if (orphans == null) {
|
||||
orphans = unaliasedAwsManagedKeysByDescription(region);
|
||||
}
|
||||
KmsKey orphan = orphans.remove(def.description());
|
||||
if (orphan != null) {
|
||||
newAliases.put(aliasStorageKey, new KmsAlias(def.aliasName(),
|
||||
regionResolver.buildArn("kms", region, def.aliasName()), orphan.getKeyId()));
|
||||
continue;
|
||||
}
|
||||
String keyId = UUID.randomUUID().toString();
|
||||
KmsKey key = new KmsKey();
|
||||
key.setKeyId(keyId);
|
||||
key.setArn(regionResolver.buildArn("kms", region, "key/" + keyId));
|
||||
key.setDescription(def.description());
|
||||
key.setKeyManager(AWS_KEY_MANAGER);
|
||||
key.setPolicy(buildDefaultKeyPolicy());
|
||||
// AWS rotates its own keys yearly and the customer cannot turn that off, so
|
||||
// GetKeyRotationStatus reports true for every AWS managed key.
|
||||
key.setKeyRotationEnabled(true);
|
||||
generateKeyMaterial(key, region);
|
||||
newKeys.put(region + "::" + keyId, key);
|
||||
newAliases.put(aliasStorageKey, new KmsAlias(def.aliasName(),
|
||||
regionResolver.buildArn("kms", region, def.aliasName()), keyId));
|
||||
}
|
||||
if (newAliases.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
aliasStore.putAll(newAliases);
|
||||
keyStore.putAll(newKeys);
|
||||
LOG.debugv("Minted {0} AWS managed keys in {1}", newKeys.size(), region);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a reserved alias already points at an AWS managed key. Presence of the target alone
|
||||
* is not enough: before {@code alias/aws/*} was reserved a customer could create
|
||||
* {@code alias/aws/s3} on their own key, and a store persisted then would otherwise keep that
|
||||
* customer key behind a reserved alias, where the AWS managed key guards do not apply.
|
||||
*/
|
||||
private boolean resolvesToAnAwsManagedKey(Optional<KmsAlias> alias, String region) {
|
||||
return alias.filter(a -> a.getTargetKeyId() != null)
|
||||
.flatMap(a -> keyStore.get(region + "::" + a.getTargetKeyId()))
|
||||
.map(k -> AWS_KEY_MANAGER.equals(k.getKeyManager()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS managed keys no reserved alias targets, keyed by description. They are what a lost
|
||||
* {@code kms-aliases.json} leaves behind; re-aliasing them instead of minting keeps ciphertext
|
||||
* bound to them decryptable through the alias and keeps ListKeys free of duplicates. The
|
||||
* catalog's descriptions are unique per service, which is what makes them usable as the key.
|
||||
*/
|
||||
private Map<String, KmsKey> unaliasedAwsManagedKeysByDescription(String region) {
|
||||
String prefix = region + "::";
|
||||
Set<String> aliased = new HashSet<>();
|
||||
for (KmsAlias a : aliasStore.scan(k -> k.startsWith(prefix + AwsManagedKeys.RESERVED_ALIAS_PREFIX))) {
|
||||
aliased.add(a.getTargetKeyId());
|
||||
}
|
||||
Map<String, KmsKey> byDescription = new HashMap<>();
|
||||
for (KmsKey k : keyStore.scan(key -> key.startsWith(prefix))) {
|
||||
if (AWS_KEY_MANAGER.equals(k.getKeyManager()) && !aliased.contains(k.getKeyId())) {
|
||||
byDescription.putIfAbsent(k.getDescription(), k);
|
||||
}
|
||||
}
|
||||
return byDescription;
|
||||
}
|
||||
|
||||
private static boolean referencesReservedAlias(String keyIdOrArn) {
|
||||
return keyIdOrArn != null
|
||||
&& (keyIdOrArn.startsWith(AwsManagedKeys.RESERVED_ALIAS_PREFIX)
|
||||
|| keyIdOrArn.contains(":" + AwsManagedKeys.RESERVED_ALIAS_PREFIX));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an operation that only a key's owner may perform when the key is AWS managed.
|
||||
*
|
||||
* <p>AWS states it plainly: you cannot manage an AWS managed key. You cannot rotate it,
|
||||
* change its key policy, edit its description, enable or disable it, tag it, or schedule it
|
||||
* for deletion. Cryptographic operations are unaffected, which is the entire point of the
|
||||
* key existing. The single error code here is a deliberate simplification: the customer is
|
||||
* not a principal the key's policy grants these actions to, so access denied is the honest
|
||||
* answer for all of them, even though AWS distinguishes some as unsupported operations.
|
||||
*/
|
||||
private static void requireCustomerManaged(KmsKey key, String operation) {
|
||||
if (AWS_KEY_MANAGER.equals(key.getKeyManager())) {
|
||||
throw new AwsException("AccessDeniedException",
|
||||
"User is not authorized to perform " + operation + " on resource "
|
||||
+ key.getArn() + " because it is an AWS managed key.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireUnreservedAlias(String aliasName, String operation) {
|
||||
if (AwsManagedKeys.isReservedAlias(aliasName)) {
|
||||
throw new AwsException("AccessDeniedException",
|
||||
"User is not authorized to perform " + operation + " on alias " + aliasName
|
||||
+ " because the " + AwsManagedKeys.RESERVED_ALIAS_PREFIX
|
||||
+ " namespace is reserved for AWS managed keys.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Aliases ────────────────────────────
|
||||
|
||||
public void createAlias(String aliasName, String targetKeyId, String region) {
|
||||
if (!aliasName.startsWith("alias/")) {
|
||||
throw new AwsException("InvalidAliasNameException", "Alias name must begin with 'alias/'", 400);
|
||||
}
|
||||
if (AwsManagedKeys.isReservedAlias(aliasName)) {
|
||||
// AWS reserves the whole alias/aws/ namespace for its own keys and rejects the name
|
||||
// outright, so a module that tries to claim one fails here exactly as it would there.
|
||||
throw new AwsException("InvalidAliasNameException",
|
||||
"Alias name cannot begin with '" + AwsManagedKeys.RESERVED_ALIAS_PREFIX + "'", 400);
|
||||
}
|
||||
KmsKey key = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID
|
||||
// AWS managed keys already carry the only alias they may have, the reserved one, and
|
||||
// CreateAlias cannot give them a second. Letting it through would be the same class of
|
||||
// error as seeding a key AWS does not have: the call succeeds here and fails there.
|
||||
// AccessDeniedException rather than a CreateAlias-specific code, because the refusal is an
|
||||
// authorization outcome (the key's policy grants the account nothing) and CreateAlias
|
||||
// publishes no error for this case.
|
||||
requireCustomerManaged(key, "kms:CreateAlias");
|
||||
requireNotPendingDeletion(key);
|
||||
|
||||
String aliasArn = regionResolver.buildArn("kms", region, aliasName);
|
||||
@@ -1179,6 +1365,7 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void updateAlias(String aliasName, String targetKeyId, String region) {
|
||||
requireUnreservedAlias(aliasName, "kms:UpdateAlias");
|
||||
String storageKey = region + "::" + aliasName;
|
||||
KmsAlias existing = aliasStore.get(storageKey)
|
||||
.orElseThrow(() -> aliasNotFound(aliasName, region));
|
||||
@@ -1186,6 +1373,9 @@ public class KmsService implements ResourceProvider {
|
||||
KmsKey currentKey = resolveKey(existing.getTargetKeyId(), region);
|
||||
KmsKey newKey = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID
|
||||
|
||||
// Same reason as CreateAlias: repointing a customer alias at an AWS managed key would
|
||||
// succeed here and fail against AWS.
|
||||
requireCustomerManaged(newKey, "kms:UpdateAlias");
|
||||
requireNotPendingDeletion(newKey);
|
||||
if (currentKey.getKeyUsage() != newKey.getKeyUsage() || !sameKeyFamily(currentKey.getKeySpec(), newKey.getKeySpec())) {
|
||||
throw new AwsException("ValidationException",
|
||||
@@ -1200,6 +1390,7 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteAlias(String aliasName, String region) {
|
||||
requireUnreservedAlias(aliasName, "kms:DeleteAlias");
|
||||
String key = region + "::" + aliasName;
|
||||
if (aliasStore.get(key).isEmpty()) {
|
||||
throw aliasNotFound(aliasName, region);
|
||||
@@ -1212,6 +1403,7 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public List<KmsAlias> listAliases(String keyId, String region) {
|
||||
ensureAwsManagedKeys(region);
|
||||
String prefix = region + "::";
|
||||
List<KmsAlias> all = aliasStore.scan(k -> k.startsWith(prefix));
|
||||
if (keyId == null || keyId.isBlank()) {
|
||||
@@ -1880,6 +2072,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void tagResource(String keyId, Map<String, String> tags, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:TagResource");
|
||||
requireNotPendingDeletion(key);
|
||||
ReservedTags.rejectReservedTagsOnUpdate(tags);
|
||||
key.getTags().putAll(tags);
|
||||
@@ -1888,6 +2081,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void untagResource(String keyId, List<String> tagKeys, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireCustomerManaged(key, "kms:UntagResource");
|
||||
requireNotPendingDeletion(key);
|
||||
tagKeys.forEach(key.getTags()::remove);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -1896,6 +2090,9 @@ public class KmsService implements ResourceProvider {
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private KmsKey resolveKey(String keyIdOrArn, String region) {
|
||||
if (referencesReservedAlias(keyIdOrArn)) {
|
||||
ensureAwsManagedKeys(region);
|
||||
}
|
||||
if (AwsArnUtils.isArnFor(keyIdOrArn, "kms")) {
|
||||
String arnRegion = AwsArnUtils.parse(keyIdOrArn).region();
|
||||
if (!region.equals(arnRegion)) {
|
||||
|
||||
@@ -16,6 +16,10 @@ public class KmsKey {
|
||||
private boolean enabled = true;
|
||||
private String keyState = "Enabled"; // Enabled, Disabled, PendingDeletion, PendingImport
|
||||
private String origin = "AWS_KMS";
|
||||
// CUSTOMER for keys a customer created, AWS for the per-service keys AWS ships under the
|
||||
// reserved alias/aws/* aliases. DescribeKey reports it, and it is what tells a caller the
|
||||
// key cannot be deleted, retagged or repolicied.
|
||||
private String keyManager = "CUSTOMER";
|
||||
private String expirationModel;
|
||||
private long validTo;
|
||||
private KmsImportParameters importParameters;
|
||||
@@ -64,6 +68,9 @@ public class KmsKey {
|
||||
public String getOrigin() { return origin; }
|
||||
public void setOrigin(String origin) { this.origin = origin; }
|
||||
|
||||
public String getKeyManager() { return keyManager; }
|
||||
public void setKeyManager(String keyManager) { this.keyManager = keyManager; }
|
||||
|
||||
public String getExpirationModel() { return expirationModel; }
|
||||
public void setExpirationModel(String expirationModel) { this.expirationModel = expirationModel; }
|
||||
|
||||
|
||||
@@ -42,7 +42,8 @@ quarkus:
|
||||
resources:
|
||||
# The Pricing service reads its bundled snapshot, EC2 reads its image
|
||||
# catalog (ec2/image-catalog.yaml), SageMaker reads its instance type
|
||||
# catalog (sagemaker/instance-type-catalog.yaml), AppSync's GraphQL
|
||||
# catalog (sagemaker/instance-type-catalog.yaml), KMS reads its AWS managed
|
||||
# key catalog (kms/aws-managed-keys.yaml), AppSync's GraphQL
|
||||
# parser reads its message bundles, EC2 security group enforcement builds
|
||||
# its helper image from docker/*.Dockerfile, and API Gateway's Velocity
|
||||
# engine reads its default properties at runtime via
|
||||
@@ -60,6 +61,7 @@ quarkus:
|
||||
- ec2/*.yaml
|
||||
- docker/*.Dockerfile
|
||||
- sagemaker/*.yaml
|
||||
- kms/*.yaml
|
||||
- eks/*.json
|
||||
- aws/*.json
|
||||
- cloudformation/*.json
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# AWS managed KMS keys.
|
||||
#
|
||||
# Every AWS account has a per-region AWS managed key for each service listed here, reachable
|
||||
# under the reserved alias/aws/<service> alias. No customer ever creates them, so nothing in a
|
||||
# Terraform or CloudFormation template declares them, yet a module that leaves a service's
|
||||
# encryption at its default resolves one: a data source reading alias/aws/s3 succeeds against
|
||||
# any real account and must succeed here too.
|
||||
#
|
||||
# One entry mints one key and one alias the first time a region's key or alias namespace is read.
|
||||
#
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# BEFORE ADDING A LINE: an AWS managed key is not the same thing as an AWS owned key, and only
|
||||
# the first belongs here.
|
||||
#
|
||||
# AWS MANAGED key lives in the customer's account. It appears in ListKeys and ListAliases,
|
||||
# reports KeyManager: AWS, and has an alias/aws/<service> alias. Seed it.
|
||||
#
|
||||
# AWS OWNED key lives in an AWS-owned account, not the customer's. It appears in neither
|
||||
# ListKeys nor ListAliases, and DescribeKey on alias/aws/<service> fails
|
||||
# against a real account. Do NOT seed it.
|
||||
#
|
||||
# Seeding an owned-key service would make DescribeKey succeed here and fail against AWS, which
|
||||
# is the worst failure this emulator can produce: a module looks compatible when it is not, and
|
||||
# nothing reports the error. A service we failed to seed is a visible gap someone files a bug
|
||||
# about; a service we wrongly seeded is a lie nobody notices. So the bar is asymmetric on
|
||||
# purpose: add a line only when AWS itself shows or documents the alias aws/<service> as a key
|
||||
# selectable or defaulted in *your* account, and prefer dropping an entry to guessing.
|
||||
#
|
||||
# ElastiCache is the worked example of a line that was dropped: its at-rest encryption guide
|
||||
# describes the default as a service managed key, and serverless caches as using an AWS owned
|
||||
# key, and never names alias/aws/elasticache. That is not evidence the alias exists, so it is
|
||||
# not seeded.
|
||||
#
|
||||
# The alias always takes the form aws/<service-name>, following the service's API namespace
|
||||
# rather than its brand name: EFS is alias/aws/elasticfilesystem, OpenSearch Service is
|
||||
# alias/aws/es and MSK is alias/aws/kafka. That pattern constrains the spelling but is NOT
|
||||
# evidence the key exists, which is the trap: alias/aws/eks fits it perfectly and no account
|
||||
# has one, because EKS API-data envelope encryption uses an AWS owned key by default and a
|
||||
# customer managed key otherwise.
|
||||
#
|
||||
# WHAT EACH ENTRY RESTS ON. The entries are grouped below by the strength of their evidence, so
|
||||
# a future editor knows which lines are safe to trust and which deserve a second look. Keep the
|
||||
# grouping accurate when you add or move a line.
|
||||
#
|
||||
# cited AWS documentation names the alias: elasticfilesystem, kinesisvideo, glue,
|
||||
# acm, ebs, s3, sqs, sns, ses.
|
||||
# corroborated production code in this repository already names the alias, independently of
|
||||
# any external source: ssm, redshift, codeartifact.
|
||||
# recollection not doc-verified. Believed correct, and each was checked against the test
|
||||
# above (does the service's own encryption selector offer this key in your
|
||||
# account?), but nobody has read an AWS page that prints the alias. If you are
|
||||
# touching one of these and can cite it, move it up a group.
|
||||
#
|
||||
# The descriptions follow the template AWS uses for these keys, "Default master key that
|
||||
# protects my <resources> when no other key is defined". AWS has reworded individual entries
|
||||
# over the years and a given account may show slightly different phrasing. Each description must
|
||||
# stay unique and should not be reworded casually: when kms-aliases.json is lost, the surviving
|
||||
# keys are re-aliased by matching their description, and a reworded entry mints a second key.
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
keys:
|
||||
|
||||
# ---- cited: AWS documentation names the alias ----
|
||||
|
||||
- alias: "alias/aws/elasticfilesystem"
|
||||
description: "Default master key that protects my EFS file systems when no other key is defined"
|
||||
- alias: "alias/aws/kinesisvideo"
|
||||
description: "Default master key that protects my Kinesis Video streams when no other key is defined"
|
||||
- alias: "alias/aws/glue"
|
||||
description: "Default master key that protects my Glue data when no other key is defined"
|
||||
# The KMS ListAliases API reference prints alias/aws/acm with a TargetKeyId in its example
|
||||
# output: https://docs.aws.amazon.com/kms/latest/APIReference/API_ListAliases.html
|
||||
- alias: "alias/aws/acm"
|
||||
description: "Default master key that protects my ACM private keys when no other key is defined"
|
||||
# The ECS guide describes a default AWS managed key with the alias alias/aws/ebs, unique per account per Region.
|
||||
- alias: "alias/aws/ebs"
|
||||
description: "Default master key that protects my EBS volumes when no other key is defined"
|
||||
# The CodeBuild guide shows "encryptionKey": "arn:aws:kms:region-ID:account-ID:alias/aws/s3".
|
||||
- alias: "alias/aws/s3"
|
||||
description: "Default master key that protects my S3 objects when no other key is defined"
|
||||
# The SQS guide names the "AWS managed default key (alias/aws/sqs)".
|
||||
- alias: "alias/aws/sqs"
|
||||
description: "Default master key that protects my SQS queues when no other key is defined"
|
||||
# The SNS guide: "the alias of the AWS managed AWS KMS for Amazon SNS is always alias/aws/sns".
|
||||
- alias: "alias/aws/sns"
|
||||
description: "Default master key that protects my SNS data when no other key is defined"
|
||||
# The SES guide shows the default key as arn:aws:kms:REGION:AWSACCOUNTID:alias/aws/ses.
|
||||
- alias: "alias/aws/ses"
|
||||
description: "Default master key that protects my SES messages when no other key is defined"
|
||||
|
||||
# ---- corroborated: named by production code in this repository ----
|
||||
|
||||
- alias: "alias/aws/ssm"
|
||||
description: "Default master key that protects my Systems Manager data when no other key is defined"
|
||||
- alias: "alias/aws/redshift"
|
||||
description: "Default master key that protects my Redshift clusters when no other key is defined"
|
||||
- alias: "alias/aws/codeartifact"
|
||||
description: "Default master key that protects my CodeArtifact packages when no other key is defined"
|
||||
|
||||
# ---- recollection: not doc-verified ----
|
||||
|
||||
- alias: "alias/aws/rds"
|
||||
description: "Default master key that protects my RDS database volumes when no other key is defined"
|
||||
- alias: "alias/aws/dynamodb"
|
||||
description: "Default master key that protects my DynamoDB table storage when no other key is defined"
|
||||
- alias: "alias/aws/lambda"
|
||||
description: "Default master key that protects my Lambda functions when no other key is defined"
|
||||
- alias: "alias/aws/secretsmanager"
|
||||
description: "Default master key that protects my Secrets Manager secrets when no other key is defined"
|
||||
- alias: "alias/aws/es"
|
||||
description: "Default master key that protects my OpenSearch domains when no other key is defined"
|
||||
- alias: "alias/aws/kinesis"
|
||||
description: "Default master key that protects my Kinesis data when no other key is defined"
|
||||
- alias: "alias/aws/kafka"
|
||||
description: "Default master key that protects my MSK clusters when no other key is defined"
|
||||
- alias: "alias/aws/backup"
|
||||
description: "Default master key that protects my AWS Backup data when no other key is defined"
|
||||
- alias: "alias/aws/ecr"
|
||||
description: "Default master key that protects my ECR images when no other key is defined"
|
||||
- alias: "alias/aws/fsx"
|
||||
description: "Default master key that protects my FSx file systems when no other key is defined"
|
||||
- alias: "alias/aws/dms"
|
||||
description: "Default master key that protects my DMS replication instance storage when no other key is defined"
|
||||
- alias: "alias/aws/codecommit"
|
||||
description: "Default master key that protects my CodeCommit repositories when no other key is defined"
|
||||
- alias: "alias/aws/workspaces"
|
||||
description: "Default master key that protects my WorkSpaces volumes when no other key is defined"
|
||||
@@ -29,6 +29,7 @@ import java.util.List;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
@@ -36,6 +37,8 @@ import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class KmsIntegrationTest {
|
||||
@@ -3241,6 +3244,145 @@ class KmsIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The alias/aws/* keys, over the wire. DescribeKey's KeyManager was a constant "CUSTOMER"
|
||||
* before these keys existed, so an AWS managed key has to be asked for through the handler
|
||||
* to prove the field now tracks the key rather than the code path.
|
||||
*/
|
||||
@Test
|
||||
void listAliasesExposesTheAwsManagedAliasesWithTargetKeys() {
|
||||
JsonPath aliases = given()
|
||||
.header("X-Amz-Target", "TrentService.ListAliases")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath();
|
||||
|
||||
List<String> names = aliases.getList("Aliases.AliasName");
|
||||
assertTrue(names.contains("alias/aws/s3"), "alias/aws/s3 missing from " + names);
|
||||
assertTrue(names.contains("alias/aws/ebs"), "alias/aws/ebs missing from " + names);
|
||||
|
||||
int index = names.indexOf("alias/aws/s3");
|
||||
String targetKeyId = aliases.getList("Aliases.TargetKeyId", String.class).get(index);
|
||||
assertNotNull(targetKeyId, "alias/aws/s3 resolves to nothing");
|
||||
assertFalse(targetKeyId.isBlank(), "alias/aws/s3 resolves to nothing");
|
||||
assertTrue(aliases.getList("Aliases.AliasArn", String.class).get(index).endsWith(":alias/aws/s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeKeyReportsKeyManagerPerKey() {
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.DescribeKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"alias/aws/s3\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("KeyMetadata.KeyManager", equalTo("AWS"))
|
||||
.body("KeyMetadata.Enabled", equalTo(true))
|
||||
.body("KeyMetadata.KeyState", equalTo("Enabled"));
|
||||
|
||||
String customerKeyId = given()
|
||||
.header("X-Amz-Target", "TrentService.CreateKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"Description\": \"customer managed\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("KeyMetadata.KeyId");
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.DescribeKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"" + customerKeyId + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("KeyMetadata.KeyManager", equalTo("CUSTOMER"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The lookup a module actually performs: encrypt under the service default key and read it
|
||||
* back. A resolvable alias whose key could not encrypt would satisfy DescribeKey and still
|
||||
* fail the caller.
|
||||
*/
|
||||
@Test
|
||||
void encryptsAndDecryptsUnderAnAwsManagedAlias() {
|
||||
String ciphertext = given()
|
||||
.header("X-Amz-Target", "TrentService.Encrypt")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"alias/aws/secretsmanager\", \"Plaintext\": \""
|
||||
+ Base64.getEncoder().encodeToString("default key payload".getBytes(StandardCharsets.UTF_8))
|
||||
+ "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("CiphertextBlob");
|
||||
|
||||
String plaintext = given()
|
||||
.header("X-Amz-Target", "TrentService.Decrypt")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"CiphertextBlob\": \"" + ciphertext + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("Plaintext");
|
||||
|
||||
assertEquals("default key payload",
|
||||
new String(Base64.getDecoder().decode(plaintext), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateAlias must not hand an AWS managed key a second alias. AWS excludes them as a target,
|
||||
* so accepting one here would make a template succeed against Floci and fail against AWS,
|
||||
* which is the one failure mode nothing downstream reports.
|
||||
*/
|
||||
@Test
|
||||
void refusesToPointACustomerAliasAtAnAwsManagedKey() {
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.CreateAlias")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"AliasName\": \"alias/borrowed-from-aws\", \"TargetKeyId\": \"alias/aws/s3\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.ListAliases")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Aliases.AliasName", not(hasItem("alias/borrowed-from-aws")));
|
||||
}
|
||||
|
||||
/**
|
||||
* An AWS managed key is AWS's, not the account's. ScheduleKeyDeletion takes a key id rather
|
||||
* than an alias, so the refusal has to be reached through the id the alias resolves to.
|
||||
*/
|
||||
@Test
|
||||
void refusesToScheduleDeletionOfAnAwsManagedKey() {
|
||||
String keyId = given()
|
||||
.header("X-Amz-Target", "TrentService.DescribeKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"alias/aws/ebs\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("KeyMetadata.KeyId");
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.ScheduleKeyDeletion")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"" + keyId + "\", \"PendingWindowInDays\": 7}")
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.DescribeKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\": \"" + keyId + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("KeyMetadata.KeyState", equalTo("Enabled"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps key material exactly as a caller would: the point of the round trip is that the
|
||||
* emulator unwraps what a standard RSAES-OAEP-SHA-256 client produces, not a shape of its own.
|
||||
|
||||
@@ -34,6 +34,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
@@ -80,6 +81,7 @@ class KmsServiceTest {
|
||||
|
||||
private KmsService kmsService;
|
||||
private InMemoryStorage<String, KmsKey> keyStore;
|
||||
private InMemoryStorage<String, KmsAlias> aliasStore;
|
||||
|
||||
@BeforeAll
|
||||
static void registerBouncyCastle() {
|
||||
@@ -91,9 +93,10 @@ class KmsServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new InMemoryStorage<>();
|
||||
aliasStore = new InMemoryStorage<>();
|
||||
kmsService = new KmsService(
|
||||
keyStore,
|
||||
new InMemoryStorage<>(),
|
||||
aliasStore,
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000")
|
||||
);
|
||||
@@ -331,8 +334,10 @@ class KmsServiceTest {
|
||||
kmsService.createKey("key2", REGION);
|
||||
kmsService.createKey("key3", "eu-west-1");
|
||||
|
||||
List<KmsKey> keys = kmsService.listKeys(REGION);
|
||||
assertEquals(2, keys.size());
|
||||
// ListKeys also returns the region's AWS managed keys, as it does on real AWS, so the
|
||||
// count this test is about is the customer-managed one.
|
||||
assertEquals(2, customerKeys(REGION).size());
|
||||
assertEquals(1, customerKeys("eu-west-1").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -856,12 +861,30 @@ class KmsServiceTest {
|
||||
assertEquals(0, updated.getDeletionDate());
|
||||
}
|
||||
|
||||
/** The keys a test created. ListKeys also returns the region's AWS managed keys. */
|
||||
private List<KmsKey> customerKeys(String region) {
|
||||
return kmsService.listKeys(region).stream()
|
||||
.filter(key -> !"AWS".equals(key.getKeyManager()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The aliases a test created. ListAliases also returns the alias/aws/* aliases of the AWS
|
||||
* managed keys, which every account has and no customer creates, so a test that cares about
|
||||
* its own alias has to say so.
|
||||
*/
|
||||
private List<KmsAlias> customerAliases(String region) {
|
||||
return kmsService.listAliases(region).stream()
|
||||
.filter(alias -> !alias.getAliasName().startsWith("alias/aws/"))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAlias() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
kmsService.createAlias("alias/my-key", key.getKeyId(), REGION);
|
||||
|
||||
List<KmsAlias> aliases = kmsService.listAliases(REGION);
|
||||
List<KmsAlias> aliases = customerAliases(REGION);
|
||||
assertEquals(1, aliases.size());
|
||||
assertEquals("alias/my-key", aliases.getFirst().getAliasName());
|
||||
assertEquals(key.getKeyId(), aliases.getFirst().getTargetKeyId());
|
||||
@@ -888,7 +911,7 @@ class KmsServiceTest {
|
||||
|
||||
kmsService.updateAlias("alias/my-key", keyB.getKeyId(), REGION);
|
||||
|
||||
List<KmsAlias> aliases = kmsService.listAliases(REGION);
|
||||
List<KmsAlias> aliases = customerAliases(REGION);
|
||||
assertEquals(1, aliases.size());
|
||||
assertEquals(keyB.getKeyId(), aliases.getFirst().getTargetKeyId());
|
||||
}
|
||||
@@ -911,7 +934,7 @@ class KmsServiceTest {
|
||||
kmsService.updateAlias("alias/my-key", "no-such-key", REGION));
|
||||
|
||||
assertEquals("NotFoundException", ex.getErrorCode());
|
||||
assertEquals(key.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(key.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -925,7 +948,7 @@ class KmsServiceTest {
|
||||
kmsService.updateAlias("alias/my-key", keyB.getKeyId(), REGION));
|
||||
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
assertEquals(keyA.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(keyA.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -938,7 +961,7 @@ class KmsServiceTest {
|
||||
kmsService.updateAlias("alias/my-key", hmacKey.getKeyId(), REGION));
|
||||
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(symmetricKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(symmetricKey.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -949,7 +972,7 @@ class KmsServiceTest {
|
||||
|
||||
kmsService.updateAlias("alias/my-key", rsa3072.getKeyId(), REGION);
|
||||
|
||||
assertEquals(rsa3072.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(rsa3072.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -960,7 +983,7 @@ class KmsServiceTest {
|
||||
|
||||
kmsService.updateAlias("alias/my-key", eccKey.getKeyId(), REGION);
|
||||
|
||||
assertEquals(eccKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(eccKey.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -973,7 +996,7 @@ class KmsServiceTest {
|
||||
kmsService.updateAlias("alias/my-key", rsaEncryptKey.getKeyId(), REGION));
|
||||
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(symmetricKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
|
||||
assertEquals(symmetricKey.getKeyId(), customerAliases(REGION).getFirst().getTargetKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -982,7 +1005,7 @@ class KmsServiceTest {
|
||||
kmsService.createAlias("alias/to-delete", key.getKeyId(), REGION);
|
||||
kmsService.deleteAlias("alias/to-delete", REGION);
|
||||
|
||||
assertTrue(kmsService.listAliases(REGION).isEmpty());
|
||||
assertTrue(customerAliases(REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -3680,4 +3703,340 @@ class KmsServiceTest {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-service keys AWS ships under alias/aws/*. No template declares them, so nothing
|
||||
* reports them missing; a module that leaves a service's encryption at its default simply
|
||||
* cannot resolve the key a real account would hand it.
|
||||
*/
|
||||
@Nested
|
||||
class AwsManagedKeyTests {
|
||||
|
||||
@Test
|
||||
void listAliasesMintsEveryReservedAliasWithAResolvableKey() {
|
||||
List<KmsAlias> aliases = kmsService.listAliases(REGION);
|
||||
|
||||
List<String> names = aliases.stream().map(KmsAlias::getAliasName).toList();
|
||||
assertTrue(names.contains("alias/aws/s3"), "alias/aws/s3 missing from " + names);
|
||||
assertTrue(names.contains("alias/aws/ebs"), "alias/aws/ebs missing from " + names);
|
||||
assertTrue(names.contains("alias/aws/rds"), "alias/aws/rds missing from " + names);
|
||||
|
||||
for (KmsAlias alias : aliases) {
|
||||
assertNotNull(alias.getTargetKeyId(), alias.getAliasName() + " has no target key");
|
||||
// The alias is only worth anything if it resolves; a name with a dangling target
|
||||
// fails a data source exactly as a missing name does.
|
||||
KmsKey target = kmsService.describeKey(alias.getAliasName(), REGION);
|
||||
assertEquals(alias.getTargetKeyId(), target.getKeyId());
|
||||
assertEquals("AWS", target.getKeyManager(), alias.getAliasName() + " is not AWS managed");
|
||||
assertTrue(alias.getAliasArn().endsWith(":" + alias.getAliasName()),
|
||||
"alias ARN " + alias.getAliasArn() + " does not name " + alias.getAliasName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeKeyResolvesAReservedAliasWithoutAPriorListAliases() {
|
||||
KmsKey key = kmsService.describeKey("alias/aws/s3", REGION);
|
||||
|
||||
assertEquals("AWS", key.getKeyManager());
|
||||
assertEquals("Enabled", key.getKeyState());
|
||||
assertTrue(key.isEnabled());
|
||||
// AWS rotates its own keys and the customer cannot turn that off.
|
||||
assertTrue(kmsService.getKeyRotationStatus("alias/aws/s3", REGION));
|
||||
assertTrue(key.getArn().contains(REGION), "key ARN " + key.getArn() + " is not in " + REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeKeyResolvesAReservedAliasByItsArn() {
|
||||
KmsAlias alias = kmsService.listAliases(REGION).stream()
|
||||
.filter(a -> "alias/aws/ebs".equals(a.getAliasName()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
assertEquals(alias.getTargetKeyId(),
|
||||
kmsService.describeKey(alias.getAliasArn(), REGION).getKeyId());
|
||||
}
|
||||
|
||||
/**
|
||||
* A seeded key is only real if it encrypts. Asserting that the alias resolves proves the
|
||||
* lookup; asserting that ciphertext produced under it comes back as the original bytes
|
||||
* proves the key behind it has material, which a stub entry in the alias store would not.
|
||||
*/
|
||||
@Test
|
||||
void theAwsManagedKeyEncryptsAndDecrypts() {
|
||||
byte[] plaintext = "default-encrypted object".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] ciphertext = kmsService.encrypt("alias/aws/s3", plaintext, REGION);
|
||||
|
||||
assertFalse(Arrays.equals(plaintext, ciphertext), "ciphertext is the plaintext");
|
||||
assertArrayEquals(plaintext, kmsService.decrypt(ciphertext, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void seedingIsIdempotentAcrossRepeatedLookups() {
|
||||
String first = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
int keysAfterFirst = kmsService.listKeys(REGION).size();
|
||||
int aliasesAfterFirst = kmsService.listAliases(REGION).size();
|
||||
|
||||
kmsService.listAliases(REGION);
|
||||
String second = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
|
||||
assertEquals(first, second, "the AWS managed key was minted twice");
|
||||
assertEquals(keysAfterFirst, kmsService.listKeys(REGION).size());
|
||||
assertEquals(aliasesAfterFirst, kmsService.listAliases(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachRegionGetsItsOwnAwsManagedKeys() {
|
||||
KmsKey east = kmsService.describeKey("alias/aws/s3", "us-east-1");
|
||||
KmsKey west = kmsService.describeKey("alias/aws/s3", "eu-west-1");
|
||||
|
||||
assertNotEquals(east.getKeyId(), west.getKeyId(),
|
||||
"one key is shared between regions; AWS managed keys are per region");
|
||||
assertTrue(east.getArn().contains("us-east-1"), east.getArn());
|
||||
assertTrue(west.getArn().contains("eu-west-1"), west.getArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void customerKeysStayCustomerManagedAndAdministrable() {
|
||||
KmsKey key = kmsService.createKey("mine", REGION);
|
||||
|
||||
assertEquals("CUSTOMER", key.getKeyManager());
|
||||
kmsService.tagResource(key.getKeyId(), Map.of("env", "test"), REGION);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
assertEquals("PendingDeletion", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesEveryCustomerAdministrationOfAnAwsManagedKey() {
|
||||
String alias = "alias/aws/rds";
|
||||
Map<String, Executable> denied = new LinkedHashMap<>();
|
||||
denied.put("ScheduleKeyDeletion", () -> kmsService.scheduleKeyDeletion(alias, 30, REGION));
|
||||
denied.put("CancelKeyDeletion", () -> kmsService.cancelKeyDeletion(alias, REGION));
|
||||
denied.put("PutKeyPolicy", () -> kmsService.putKeyPolicy(alias, "{}", REGION));
|
||||
denied.put("UpdateKeyDescription", () -> kmsService.updateKeyDescription(alias, "mine now", REGION));
|
||||
denied.put("EnableKeyRotation", () -> kmsService.enableKeyRotation(alias, REGION));
|
||||
denied.put("DisableKeyRotation", () -> kmsService.disableKeyRotation(alias, REGION));
|
||||
denied.put("EnableKey", () -> kmsService.enableKey(alias, REGION));
|
||||
denied.put("DisableKey", () -> kmsService.disableKey(alias, REGION));
|
||||
denied.put("RotateKeyOnDemand", () -> kmsService.rotateKeyOnDemand(alias, REGION));
|
||||
denied.put("TagResource", () -> kmsService.tagResource(alias, Map.of("a", "b"), REGION));
|
||||
denied.put("UntagResource", () -> kmsService.untagResource(alias, List.of("a"), REGION));
|
||||
// The key policy allows kms:CreateGrant only via the owning service, never directly.
|
||||
denied.put("CreateGrant", () -> kmsService.createGrant(alias, "arn:aws:iam::000000000000:role/r",
|
||||
List.of("Decrypt"), REGION));
|
||||
|
||||
denied.forEach((operation, call) -> {
|
||||
AwsException exception = assertThrows(AwsException.class, call,
|
||||
operation + " was allowed on an AWS managed key");
|
||||
assertEquals("AccessDeniedException", exception.getErrorCode(), operation);
|
||||
});
|
||||
|
||||
// The refusals must not have left the key half-changed.
|
||||
KmsKey key = kmsService.describeKey(alias, REGION);
|
||||
assertEquals("Enabled", key.getKeyState());
|
||||
assertTrue(key.getTags().isEmpty());
|
||||
assertTrue(key.isKeyRotationEnabled());
|
||||
assertEquals(List.of(), kmsService.listGrants(alias, REGION, null, null, null, null).get("Grants"),
|
||||
"CreateGrant was refused but left a grant behind");
|
||||
}
|
||||
|
||||
/**
|
||||
* Minting is check-then-write across two stores, so two cold reads racing each other must
|
||||
* not both mint: the loser's keys would sit in ListKeys unaliased forever.
|
||||
*/
|
||||
@Test
|
||||
void concurrentColdReadsMintEachAwsManagedKeyOnce() throws Exception {
|
||||
int threads = 16;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
try {
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
List<Future<List<KmsAlias>>> reads = new ArrayList<>();
|
||||
for (int i = 0; i < threads; i++) {
|
||||
reads.add(pool.submit(() -> {
|
||||
start.await();
|
||||
return kmsService.listAliases(REGION);
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (Future<List<KmsAlias>> read : reads) {
|
||||
read.get(30, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
// Read the key store directly, not through listKeys, which would mint again.
|
||||
assertEquals(AwsManagedKeys.KEYS.size(), keyStore.scan(k -> k.startsWith(REGION + "::")).size(),
|
||||
"concurrent cold reads minted more AWS managed keys than the catalog holds");
|
||||
List<String> reserved = kmsService.listAliases(REGION).stream()
|
||||
.map(KmsAlias::getAliasName)
|
||||
.filter(name -> name.startsWith("alias/aws/"))
|
||||
.toList();
|
||||
assertEquals(AwsManagedKeys.KEYS.size(), reserved.size());
|
||||
for (AwsManagedKeys.AwsManagedKeyDef def : AwsManagedKeys.KEYS) {
|
||||
assertEquals(1, reserved.stream().filter(def.aliasName()::equals).count(), def.aliasName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesToClaimAnAliasInTheReservedNamespace() {
|
||||
KmsKey mine = kmsService.createKey("mine", REGION);
|
||||
|
||||
AwsException created = assertThrows(AwsException.class,
|
||||
() -> kmsService.createAlias("alias/aws/s3", mine.getKeyId(), REGION));
|
||||
assertEquals("InvalidAliasNameException", created.getErrorCode());
|
||||
|
||||
AwsException fresh = assertThrows(AwsException.class,
|
||||
() -> kmsService.createAlias("alias/aws/not-a-real-service", mine.getKeyId(), REGION));
|
||||
assertEquals("InvalidAliasNameException", fresh.getErrorCode());
|
||||
|
||||
AwsException updated = assertThrows(AwsException.class,
|
||||
() -> kmsService.updateAlias("alias/aws/s3", mine.getKeyId(), REGION));
|
||||
assertEquals("AccessDeniedException", updated.getErrorCode());
|
||||
|
||||
AwsException deleted = assertThrows(AwsException.class,
|
||||
() -> kmsService.deleteAlias("alias/aws/s3", REGION));
|
||||
assertEquals("AccessDeniedException", deleted.getErrorCode());
|
||||
|
||||
// The alias still points where it did.
|
||||
assertEquals("AWS", kmsService.describeKey("alias/aws/s3", REGION).getKeyManager());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownAliasUnderTheReservedPrefixIsStillNotFound() {
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> kmsService.describeKey("alias/aws/not-a-real-service", REGION));
|
||||
|
||||
assertEquals("NotFoundException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The aliases and the keys live in different files, and PersistentStorage quarantines an
|
||||
* unreadable one and starts that store empty on its own. Gating minting on the alias alone
|
||||
* left every alias dangling for the life of the instance: ListAliases advertised
|
||||
* alias/aws/s3 while DescribeKey on it reported NotFoundException. The catalog is in the
|
||||
* repository, so this is the one part of a damaged store that can rebuild itself.
|
||||
*/
|
||||
@Test
|
||||
void remintsTheKeyWhenTheKeyStoreLostItAndTheAliasSurvived() {
|
||||
String original = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
keyStore.delete(REGION + "::" + original);
|
||||
|
||||
// Not a shape check: the alias has to resolve to a key that can still do the work.
|
||||
byte[] plaintext = "after the key store was lost".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ciphertext = kmsService.encrypt("alias/aws/s3", plaintext, REGION);
|
||||
|
||||
assertArrayEquals(plaintext, kmsService.decrypt(ciphertext, REGION));
|
||||
String reminted = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
assertNotEquals(original, reminted, "the alias still points at the key that was lost");
|
||||
assertEquals("AWS", kmsService.describeKey("alias/aws/s3", REGION).getKeyManager());
|
||||
// The repair must not duplicate the alias.
|
||||
assertEquals(1, kmsService.listAliases(REGION).stream()
|
||||
.filter(alias -> "alias/aws/s3".equals(alias.getAliasName())).count());
|
||||
}
|
||||
|
||||
/**
|
||||
* Before alias/aws/ was reserved, a customer could create alias/aws/s3 on their own key and
|
||||
* persist it. Gating on "the target exists" kept that alias pointing at a CUSTOMER key, so
|
||||
* DescribeKey reported CUSTOMER and the AWS managed key guards let ScheduleKeyDeletion
|
||||
* through the reserved alias.
|
||||
*/
|
||||
@Test
|
||||
void repointsAReservedAliasPersistedOnACustomerKey() {
|
||||
KmsKey mine = kmsService.createKey("mine", REGION);
|
||||
aliasStore.put(REGION + "::alias/aws/s3", new KmsAlias("alias/aws/s3",
|
||||
"arn:aws:kms:us-east-1:000000000000:alias/aws/s3", mine.getKeyId()));
|
||||
|
||||
KmsKey resolved = kmsService.describeKey("alias/aws/s3", REGION);
|
||||
|
||||
assertEquals("AWS", resolved.getKeyManager());
|
||||
assertNotEquals(mine.getKeyId(), resolved.getKeyId());
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> kmsService.scheduleKeyDeletion("alias/aws/s3", 7, REGION));
|
||||
assertEquals("AccessDeniedException", refused.getErrorCode());
|
||||
// The customer key itself is untouched.
|
||||
assertEquals("CUSTOMER", kmsService.describeKey(mine.getKeyId(), REGION).getKeyManager());
|
||||
}
|
||||
|
||||
/**
|
||||
* kms-aliases.json lost while kms-keys.json survives: the AWS managed keys are re-aliased
|
||||
* rather than minted again, so ListKeys holds no duplicates and ciphertext bound to the old
|
||||
* key still decrypts and still belongs to the key alias/aws/s3 names.
|
||||
*/
|
||||
@Test
|
||||
void reusesSurvivingAwsManagedKeysWhenTheAliasStoreIsLost() {
|
||||
byte[] plaintext = "before the alias store was lost".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ciphertext = kmsService.encrypt("alias/aws/s3", plaintext, REGION);
|
||||
String original = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
aliasStore.scan(k -> true).forEach(a -> aliasStore.delete(REGION + "::" + a.getAliasName()));
|
||||
assertTrue(aliasStore.scan(k -> true).isEmpty());
|
||||
|
||||
assertEquals(AwsManagedKeys.KEYS.size(), kmsService.listKeys(REGION).size(),
|
||||
"losing the alias store minted a second set of AWS managed keys");
|
||||
assertEquals(original, kmsService.describeKey("alias/aws/s3", REGION).getKeyId());
|
||||
assertArrayEquals(plaintext, kmsService.decrypt(ciphertext, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAliasesRepairsEveryDanglingReservedAlias() {
|
||||
kmsService.listAliases(REGION).stream()
|
||||
.filter(alias -> alias.getAliasName().startsWith("alias/aws/"))
|
||||
.forEach(alias -> keyStore.delete(REGION + "::" + alias.getTargetKeyId()));
|
||||
|
||||
for (KmsAlias alias : kmsService.listAliases(REGION)) {
|
||||
assertEquals(alias.getTargetKeyId(),
|
||||
kmsService.describeKey(alias.getAliasName(), REGION).getKeyId(),
|
||||
alias.getAliasName() + " did not resolve after the key store was emptied");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Real AWS returns the AWS managed keys from ListKeys unconditionally. Reading ListKeys
|
||||
* first on a cold service used to return nothing, so a caller that filters on KeyManager
|
||||
* saw them or not depending on call order.
|
||||
*/
|
||||
@Test
|
||||
void listKeysMintsTheAwsManagedKeysWithoutAPriorAliasRead() {
|
||||
List<KmsKey> keys = kmsService.listKeys(REGION);
|
||||
|
||||
assertEquals(AwsManagedKeys.KEYS.size(), keys.size());
|
||||
assertTrue(keys.stream().allMatch(key -> "AWS".equals(key.getKeyManager())));
|
||||
// And it did not mint a second set once the alias namespace is read as well.
|
||||
kmsService.listAliases(REGION);
|
||||
assertEquals(keys.size(), kmsService.listKeys(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesToPointACustomerAliasAtAnAwsManagedKey() {
|
||||
String awsKeyId = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
KmsKey mine = kmsService.createKey("mine", REGION);
|
||||
kmsService.createAlias("alias/mine", mine.getKeyId(), REGION);
|
||||
|
||||
for (String target : List.of("alias/aws/s3", awsKeyId)) {
|
||||
AwsException created = assertThrows(AwsException.class,
|
||||
() -> kmsService.createAlias("alias/borrowed", target, REGION),
|
||||
"CreateAlias accepted an AWS managed key as the target: " + target);
|
||||
assertEquals("AccessDeniedException", created.getErrorCode());
|
||||
|
||||
AwsException updated = assertThrows(AwsException.class,
|
||||
() -> kmsService.updateAlias("alias/mine", target, REGION),
|
||||
"UpdateAlias accepted an AWS managed key as the target: " + target);
|
||||
assertEquals("AccessDeniedException", updated.getErrorCode());
|
||||
}
|
||||
|
||||
assertTrue(customerAliases(REGION).stream()
|
||||
.noneMatch(alias -> "alias/borrowed".equals(alias.getAliasName())));
|
||||
assertEquals(mine.getKeyId(),
|
||||
kmsService.describeKey("alias/mine", REGION).getKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAliasesFilteredByKeyIdReturnsOnlyThatKeysAlias() {
|
||||
String s3KeyId = kmsService.describeKey("alias/aws/s3", REGION).getKeyId();
|
||||
|
||||
List<KmsAlias> aliases = kmsService.listAliases(s3KeyId, REGION);
|
||||
|
||||
assertEquals(List.of("alias/aws/s3"), aliases.stream().map(KmsAlias::getAliasName).toList());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user