From e44f9137be451b196fa07fb0003e889677555a62 Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:50:29 +0100 Subject: [PATCH] fix: keep EMR security configurations, ElastiCache parameter groups and Glue Schema Registry resources in their Region (#8611) EMR security configurations, ElastiCache cache parameter groups and Glue Schema Registry registries and schemas are now stored under their Region, so each is listed and reached only in the Region it was created in, and its name is free in other Regions. Another Region's resource answers the error each service already gives for one that does not exist, and each Region gets its own default Glue registry. Records stored before move at startup, in every account: to the Region their ARN names, or to the default Region, with a copy in each other Region whose clusters or replication groups name one, through the new AccountAwareStorageBackend.migrateLegacyEntriesToRegions. A Glue schema stored in another Region than its registry gets a copy of that registry there. Part of #8218. --- .../storage/AccountAwareStorageBackend.java | 26 ++ .../elasticache/ElastiCacheService.java | 150 ++++++++--- .../io/floci/aws/services/emr/EmrHandler.java | 24 +- .../io/floci/aws/services/emr/EmrService.java | 83 +++++-- .../aws/services/glue/GlueJsonHandler.java | 24 +- .../floci/aws/services/glue/GlueService.java | 6 +- .../GlueSchemaRegistryService.java | 235 +++++++++++++----- .../AccountAwareStorageBackendTest.java | 34 +++ ...astiCacheParameterGroupLegacyKeysTest.java | 54 ++++ ...astiCacheRegionScopingIntegrationTest.java | 34 ++- .../elasticache/ElastiCacheServiceTest.java | 3 +- .../emr/EmrClusterRegionIntegrationTest.java | 35 +++ .../aws/services/emr/EmrIntegrationTest.java | 2 +- ...mrSecurityConfigurationLegacyKeysTest.java | 69 +++++ .../GlueSchemaRegistryLegacyKeysTest.java | 110 ++++++++ ...aRegistryRegionScopingIntegrationTest.java | 85 +++++++ .../GlueSchemaRegistryServiceTest.java | 76 +++--- 17 files changed, 863 insertions(+), 187 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/elasticache/ElastiCacheParameterGroupLegacyKeysTest.java create mode 100644 src/test/java/io/floci/aws/services/emr/EmrSecurityConfigurationLegacyKeysTest.java create mode 100644 src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryLegacyKeysTest.java create mode 100644 src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryRegionScopingIntegrationTest.java diff --git a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java index 3595e390d4..76b05d7b5e 100644 --- a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java @@ -18,6 +18,7 @@ import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; /** @@ -305,6 +306,31 @@ public class AccountAwareStorageBackend implements StorageBackend } } + /** + * For records stored before they were keyed by Region, which recorded none and which every Region saw: in every + * account, copies each legacy entry {@code legacyKeyFilter} accepts onto {@code keyIn}'s key of each Region other + * than {@code defaultRegion} that {@code regionsUsing} gives for it (the Regions whose resources name it), where + * that key is free, then moves the legacy entries onto {@code defaultRegion}'s key, as + * {@link #migrateLegacyEntriesInAllAccounts(Predicate, Function)} moves them. {@code regionsUsing} is handed the + * account holding the entry, and {@code keyIn} returning null leaves that entry where it is. + */ + public synchronized void migrateLegacyEntriesToRegions( + Predicate legacyKeyFilter, + String defaultRegion, + BiFunction> regionsUsing, + BiFunction keyIn, + UnaryOperator copy) { + for (AccountEntry entry : scanAllAccountEntries(legacyKeyFilter)) { + for (String region : regionsUsing.apply(entry.accountId(), entry.value())) { + String key = keyIn.apply(region, entry.value()); + if (!region.equals(defaultRegion) && key != null && getForAccount(entry.accountId(), key).isEmpty()) { + putForAccount(entry.accountId(), key, copy.apply(entry.value())); + } + } + } + migrateLegacyEntriesInAllAccounts(legacyKeyFilter, value -> keyIn.apply(defaultRegion, value)); + } + private synchronized void migrateLegacyEntries( String accountId, Predicate legacyKeyFilter, diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java index c73731122c..6b39f5f6e2 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -5,6 +5,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.BackupWindows; +import io.floci.aws.core.common.MemoizedSupplier; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; @@ -15,6 +16,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.StorageJson; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.model.SecurityGroup; import io.floci.aws.services.ec2.model.Subnet; @@ -42,6 +44,7 @@ import io.floci.aws.services.kms.KmsService; import io.floci.aws.services.kms.model.KmsKey; import io.floci.aws.services.kms.model.KmsKeySpec; import io.floci.aws.services.kms.model.KmsKeyUsage; +import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -64,6 +67,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Pattern; @@ -130,6 +134,8 @@ public class ElastiCacheService implements ResourceProvider { return accountId + "/" + id; } private final ConcurrentHashMap parameterGroupLocks = new ConcurrentHashMap<>(); + // Separates a cache parameter group's key's Region from its name (parameterGroupKey). + private static final String PARAMETER_GROUP_KEY_SEPARATOR = "::"; /** * Parameter groups claimed by in-flight creates, keyed by account and name (see * {@link #parameterGroupReservationKey}) with the number of creates holding each. A @@ -328,7 +334,7 @@ public class ElastiCacheService implements ResourceProvider { String groupId = request.replicationGroupId(); // Held until the group is persisted (or the attempt fails) so a concurrent // DeleteCacheParameterGroup sees the dependency before the stored-groups scan can. - String parameterGroupReservation = reserveParameterGroup(request.cacheParameterGroupName()); + String parameterGroupReservation = reserveParameterGroup(request.cacheParameterGroupName(), request.region()); try { // A standalone cache cluster of that id counts as taken, memcached included: see // provisioningIds, and cacheClusterIdTaken for the same test the other way round. @@ -372,13 +378,13 @@ public class ElastiCacheService implements ResourceProvider { * can't straddle a delete. Returns the reservation key, or {@code null} when the request * names no parameter group, for the matching {@link #releaseParameterGroup} call. */ - private String reserveParameterGroup(String requestedName) { + private String reserveParameterGroup(String requestedName, String region) { if (requestedName == null || requestedName.isBlank()) { return null; } - synchronized (lockFor(requestedName)) { - requireParameterGroup(requestedName); - String reservation = parameterGroupReservationKey(requestedName); + synchronized (lockFor(parameterGroupKey(region, requestedName))) { + requireParameterGroup(requestedName, region); + String reservation = parameterGroupReservationKey(region, requestedName); reservedParameterGroups.merge(reservation, 1, Integer::sum); return reservation; } @@ -393,13 +399,17 @@ public class ElastiCacheService implements ResourceProvider { } /** - * Parameter groups are stored per account, so a reservation is scoped the same way: the - * account the store is currently prefixing keys with, then the name. Without that, one - * account's in-flight create would block another account's delete of its own group of the + * Parameter groups are stored per account and Region, so a reservation is scoped the same way: the + * account the store is currently prefixing keys with, then the group's key. Without that, one + * account's or Region's in-flight create would block another's delete of its own group of the * same name. */ private String parameterGroupReservationKey(String name) { - return parameterGroups.accountId() + "/" + name; + return parameterGroupReservationKey(regionResolver.getRegion(), name); + } + + private String parameterGroupReservationKey(String region, String name) { + return parameterGroups.accountId() + "/" + parameterGroupKey(region, name); } private ReplicationGroup provisionSingleNodeGroup(CreateReplicationGroupRequest request, @@ -665,7 +675,7 @@ public class ElastiCacheService implements ResourceProvider { if (parameterGroupName.endsWith(".cluster.on")) { return true; } - boolean customClusterGroup = findParameterGroup(parameterGroupName) + boolean customClusterGroup = findParameterGroup(parameterGroupName, request.region()) .map(group -> "yes".equalsIgnoreCase(group.getParameters().get("cluster-enabled"))) .orElse(false); if (customClusterGroup) { @@ -1738,7 +1748,7 @@ public class ElastiCacheService implements ResourceProvider { BackupWindows.parseMaintenanceWindow(request.preferredMaintenanceWindow()); } requireCacheSubnetGroup(subnetGroups, request.cacheSubnetGroupName()); - String parameterGroupReservation = reserveParameterGroup(request.cacheParameterGroupName()); + String parameterGroupReservation = reserveParameterGroup(request.cacheParameterGroupName(), request.region()); try { if (cacheClusterIdTaken(clusterId)) { throw new AwsException("CacheClusterAlreadyExists", @@ -2623,27 +2633,27 @@ public class ElastiCacheService implements ResourceProvider { } private Map updateCacheParameterGroupTags(TagResourceRef ref, Map tags) { - synchronized (lockFor(ref.id())) { - CacheParameterGroup group = parameterGroups.get(ref.id()).orElseThrow(() -> + synchronized (parameterGroupLock(ref.id())) { + CacheParameterGroup group = parameterGroups.get(parameterGroupKey(ref.id())).orElseThrow(() -> new AwsException("CacheParameterGroupNotFound", "Cache parameter group " + ref.id() + " not found.", 404)); requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(), "parametergroup:" + ref.id()).toString(), ref.resourceArn(), "CacheParameterGroupNotFound", ref.id()); group.getTags().putAll(tags); - parameterGroups.put(ref.id(), group); + parameterGroups.put(parameterGroupKey(ref.id()), group); return new LinkedHashMap<>(group.getTags()); } } private Map removeCacheParameterGroupTags(TagResourceRef ref, List tagKeys) { - synchronized (lockFor(ref.id())) { - CacheParameterGroup group = parameterGroups.get(ref.id()).orElseThrow(() -> + synchronized (parameterGroupLock(ref.id())) { + CacheParameterGroup group = parameterGroups.get(parameterGroupKey(ref.id())).orElseThrow(() -> new AwsException("CacheParameterGroupNotFound", "Cache parameter group " + ref.id() + " not found.", 404)); requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(), "parametergroup:" + ref.id()).toString(), ref.resourceArn(), "CacheParameterGroupNotFound", ref.id()); tagKeys.forEach(group.getTags()::remove); - parameterGroups.put(ref.id(), group); + parameterGroups.put(parameterGroupKey(ref.id()), group); return new LinkedHashMap<>(group.getTags()); } } @@ -3614,6 +3624,64 @@ public class ElastiCacheService implements ResourceProvider { return parameterGroupLocks.computeIfAbsent(parameterGroupName, key -> new Object()); } + /** {@link #lockFor} for the parameter group by that name in the request's Region: groups are Regional. */ + private Object parameterGroupLock(String name) { + return lockFor(parameterGroupKey(name)); + } + + /** + * A cache parameter group's key. Parameter groups are Regional, so the key holds the request's Region and the + * name, and the same name can be used in another Region. + */ + private String parameterGroupKey(String name) { + return parameterGroupKey(regionResolver.getRegion(), name); + } + + private static String parameterGroupKey(String region, String name) { + return region + PARAMETER_GROUP_KEY_SEPARATOR + name; + } + + /** + * Moves the parameter groups stored before they were keyed by Region from their bare name onto the default + * Region's key: they recorded no Region, and every Region saw them. Every other Region where one of the account's + * replication groups or cache clusters names one gets a copy of its own, so it still finds it there. + */ + @PostConstruct + void migrateLegacyParameterGroups() { + // Built only if a group is still stored under its bare name. + Supplier>> regionsUsing = new MemoizedSupplier<>(this::parameterGroupUses); + parameterGroups.migrateLegacyEntriesToRegions(key -> !key.contains(PARAMETER_GROUP_KEY_SEPARATOR), + regionResolver.getDefaultRegion(), + (accountId, group) -> regionsUsing.get().getOrDefault(accountId + "/" + group.getName(), Set.of()), + (region, group) -> group.getName() == null ? null : parameterGroupKey(region, group.getName()), + StorageJson::copy); + } + + /** The Regions where each account's replication groups and cache clusters name each group, by account and name. */ + private Map> parameterGroupUses() { + Map> uses = new HashMap<>(); + for (AccountEntry group : groups.scanAllAccountEntries(k -> true)) { + recordParameterGroupUse(uses, group.accountId(), group.value().getCacheParameterGroupName(), + group.value().getArn()); + } + List> clusters = new ArrayList<>(cacheClusters.scanAllAccountEntries(k -> true)); + if (memcachedClusters instanceof AccountAwareStorageBackend memcached) { + clusters.addAll(memcached.scanAllAccountEntries(k -> true)); + } + for (AccountEntry cluster : clusters) { + recordParameterGroupUse(uses, cluster.accountId(), cluster.value().getCacheParameterGroupName(), + cluster.value().getArn()); + } + return uses; + } + + private void recordParameterGroupUse(Map> regionsUsing, String accountId, String name, + String arn) { + if (name != null) { + regionsUsing.computeIfAbsent(accountId + "/" + name, ignored -> new LinkedHashSet<>()).add(regionOf(arn)); + } + } + public CacheParameterGroup createCacheParameterGroup(String name, String family, String description, Map tags) { validateParameterGroupName(name); @@ -3622,8 +3690,8 @@ public class ElastiCacheService implements ResourceProvider { "CacheParameterGroupFamily " + family + " is not a valid parameter group family.", 400); } - synchronized (lockFor(name)) { - if (parameterGroups.get(name).isPresent()) { + synchronized (parameterGroupLock(name)) { + if (parameterGroups.get(parameterGroupKey(name)).isPresent()) { throw new AwsException("CacheParameterGroupAlreadyExists", "Parameter group " + name + " already exists", 400); } @@ -3631,17 +3699,18 @@ public class ElastiCacheService implements ResourceProvider { if (tags != null) { group.setTags(new LinkedHashMap<>(tags)); } - parameterGroups.put(name, group); + parameterGroups.put(parameterGroupKey(name), group); LOG.infov("Created cache parameter group {0} ({1})", name, family); return group; } } - /** Every group, or the one named. The published defaults are listed, as AWS lists them. */ + /** Every group of the request's Region, or the one named. The published defaults are listed, as AWS lists them. */ public List describeCacheParameterGroups(String name) { if (name == null || name.isBlank()) { List all = new ArrayList<>(defaultParameterGroups()); - all.addAll(parameterGroups.scan(key -> true)); + String prefix = parameterGroupKey(""); + all.addAll(parameterGroups.scan(key -> key.startsWith(prefix))); return all; } return List.of(requireParameterGroup(name)); @@ -3651,16 +3720,25 @@ public class ElastiCacheService implements ResourceProvider { return defaultParameterGroups().stream().anyMatch(group -> group.getName().equals(name)); } - /** The group by that name, whether stored or one of the published defaults. */ + /** The group by that name in the request's Region, whether stored or one of the published defaults. */ public Optional findParameterGroup(String name) { - return parameterGroups.get(name) + return findParameterGroup(name, regionResolver.getRegion()); + } + + /** As above; in {@code region}, the Region of the create naming the group. */ + private Optional findParameterGroup(String name, String region) { + return parameterGroups.get(parameterGroupKey(region, name)) .or(() -> defaultParameterGroups().stream() .filter(group -> group.getName().equals(name)) .findFirst()); } public CacheParameterGroup requireParameterGroup(String name) { - return findParameterGroup(name) + return requireParameterGroup(name, regionResolver.getRegion()); + } + + private CacheParameterGroup requireParameterGroup(String name, String region) { + return findParameterGroup(name, region) .orElseThrow(() -> new AwsException("CacheParameterGroupNotFound", "CacheParameterGroup " + name + " not found.", 404)); } @@ -3671,10 +3749,10 @@ public class ElastiCacheService implements ResourceProvider { * missing from a partial catalogue would refuse configurations AWS accepts. */ public void modifyCacheParameterGroup(String name, Map parameters) { - synchronized (lockFor(name)) { + synchronized (parameterGroupLock(name)) { // Read inside the lock: a record resolved before it could have been deleted since, and // writing it back would restore the group the delete removed. - CacheParameterGroup group = parameterGroups.get(name).orElse(null); + CacheParameterGroup group = parameterGroups.get(parameterGroupKey(name)).orElse(null); if (group == null) { // Absent from the store means one of two different things, and they do not share // an error: a published default was never stored, whereas anything else is gone. @@ -3688,15 +3766,15 @@ public class ElastiCacheService implements ResourceProvider { Map updated = new LinkedHashMap<>(group.getParameters()); updated.putAll(parameters); group.setParameters(updated); - parameterGroups.put(name, group); + parameterGroups.put(parameterGroupKey(name), group); } LOG.debugv("Modified {0} parameter(s) on cache parameter group {1}", parameters.size(), name); } public void deleteCacheParameterGroup(String name) { validateParameterGroupName(name); - synchronized (lockFor(name)) { - if (parameterGroups.get(name).isEmpty()) { + synchronized (parameterGroupLock(name)) { + if (parameterGroups.get(parameterGroupKey(name)).isEmpty()) { // AWS emits this without the space after the type name. Deliberately not // corrected: matching it is the point, and each action words this differently — // describe says "CacheParameterGroup not found." and modify says @@ -3709,21 +3787,23 @@ public class ElastiCacheService implements ResourceProvider { "One or more cache clusters are still members of this parameter group " + name + ", so the group cannot be deleted.", 400); } - parameterGroups.delete(name); + parameterGroups.delete(parameterGroupKey(name)); } LOG.infov("Deleted cache parameter group {0}", name); } /** - * Whether a stored replication group or cache cluster still references the parameter group by - * that name, or a create that named it is still provisioning and about to store one. + * Whether a stored replication group or cache cluster of the request's Region still references the parameter + * group by that name, or a create that named it is still provisioning and about to store one. */ private boolean isParameterGroupInUse(String name) { return reservedParameterGroups.containsKey(parameterGroupReservationKey(name)) || groups.scan(key -> true).stream() - .anyMatch(group -> name.equals(group.getCacheParameterGroupName())) + .anyMatch(group -> name.equals(group.getCacheParameterGroupName()) + && inRequestRegion(group.getArn())) || cacheClusters.scan(key -> true).stream() - .anyMatch(cluster -> name.equals(cluster.getCacheParameterGroupName())); + .anyMatch(cluster -> name.equals(cluster.getCacheParameterGroupName()) + && inRequestRegion(cluster.getArn())); } @Override diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index 784427239a..e4acb95a96 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -78,10 +78,10 @@ public class EmrHandler { case "AddInstanceFleet" -> handleAddInstanceFleet(request); case "ListInstanceFleets" -> handleListInstanceFleets(request); case "ListInstances" -> handleListInstances(request); - case "CreateSecurityConfiguration" -> handleCreateSecurityConfiguration(request); - case "DescribeSecurityConfiguration" -> handleDescribeSecurityConfiguration(request); - case "DeleteSecurityConfiguration" -> handleDeleteSecurityConfiguration(request); - case "ListSecurityConfigurations" -> handleListSecurityConfigurations(); + case "CreateSecurityConfiguration" -> handleCreateSecurityConfiguration(request, region); + case "DescribeSecurityConfiguration" -> handleDescribeSecurityConfiguration(request, region); + case "DeleteSecurityConfiguration" -> handleDeleteSecurityConfiguration(request, region); + case "ListSecurityConfigurations" -> handleListSecurityConfigurations(region); case "AddTags" -> handleAddTags(request); case "RemoveTags" -> handleRemoveTags(request); case "ModifyInstanceGroups" -> handleModifyInstanceGroups(request, region); @@ -485,17 +485,17 @@ public class EmrHandler { // ──────────────────────────── Security configurations ──────────────────────────── - private Response handleCreateSecurityConfiguration(JsonNode request) { + private Response handleCreateSecurityConfiguration(JsonNode request, String region) { SecurityConfiguration sc = service.createSecurityConfiguration( - text(request, "Name"), text(request, "SecurityConfiguration")); + text(request, "Name"), text(request, "SecurityConfiguration"), region); ObjectNode response = objectMapper.createObjectNode(); response.put("Name", sc.getName()); response.put("CreationDateTime", epoch(sc.getCreationDateTime())); return Response.ok(response).build(); } - private Response handleDescribeSecurityConfiguration(JsonNode request) { - SecurityConfiguration sc = service.describeSecurityConfiguration(text(request, "Name")); + private Response handleDescribeSecurityConfiguration(JsonNode request, String region) { + SecurityConfiguration sc = service.describeSecurityConfiguration(text(request, "Name"), region); ObjectNode response = objectMapper.createObjectNode(); response.put("Name", sc.getName()); response.put("SecurityConfiguration", sc.getSecurityConfiguration()); @@ -503,8 +503,8 @@ public class EmrHandler { return Response.ok(response).build(); } - private Response handleDeleteSecurityConfiguration(JsonNode request) { - service.deleteSecurityConfiguration(text(request, "Name")); + private Response handleDeleteSecurityConfiguration(JsonNode request, String region) { + service.deleteSecurityConfiguration(text(request, "Name"), region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -573,10 +573,10 @@ public class EmrHandler { return node.asInt(); } - private Response handleListSecurityConfigurations() { + private Response handleListSecurityConfigurations(String region) { ObjectNode response = objectMapper.createObjectNode(); ArrayNode arr = response.putArray("SecurityConfigurations"); - for (SecurityConfiguration sc : service.listSecurityConfigurations()) { + for (SecurityConfiguration sc : service.listSecurityConfigurations(region)) { ObjectNode node = objectMapper.createObjectNode(); node.put("Name", sc.getName()); node.put("CreationDateTime", epoch(sc.getCreationDateTime())); diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index dc30ee435e..0ffb7ec8df 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -11,6 +11,7 @@ import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.ContainerTeardown; +import io.floci.aws.core.common.MemoizedSupplier; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; @@ -21,6 +22,7 @@ import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.StorageJson; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.ec2.model.InstanceState; import io.floci.aws.services.ec2.model.Placement; @@ -52,6 +54,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -125,9 +128,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // which publishes none. Hadoop keeps its wire protocols compatible across a major version's minor releases, so // a newer client, such as the runtime's, reaches its NameNode. static final String SPARK_RUNTIME_HDFS_RELEASE = "emr-7.5.0"; + // Separates a security configuration key's Region from its name. + private static final String KEY_SEPARATOR = "::"; private final AccountAwareStorageBackend clusterStore; - private final StorageBackend secConfigStore; + // A security configuration is Regional: keyed by Region and name (securityConfigurationKey). + private final AccountAwareStorageBackend secConfigStore; // Block public access is an account setting per Region, so this store is keyed by Region. private final StorageBackend blockPublicAccessStore; private final RegionResolver regionResolver; @@ -281,6 +287,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear this.blockPublicAccessStore = storageFactory.create("emr", "emr-block-public-access.json", new TypeReference>() {}); this.regionResolver = regionResolver; + migrateLegacySecurityConfigurations(); this.eventPublisher = eventPublisher; this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel(); this.sparkRunner = sparkRunner; @@ -419,8 +426,6 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear throw new AwsException("ValidationException", "The RunJobFlow request can contain InstanceFleets" + " parameters or InstanceGroups parameters, but not both.", 400); } - // A security configuration is created first and named here; no source gives AWS's answer for one that is - // not there, so the code is RunJobFlow's own for its input and the wording that of the other calls. if (outOfStepConcurrencyRange(cluster.getStepConcurrencyLevel())) { throw new AwsException("ValidationException", stepConcurrencyOutOfRange(cluster.getStepConcurrencyLevel()), 400); @@ -429,8 +434,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (cluster.getSteps().size() > MAX_ACTIVE_STEPS) { throw new AwsException("ValidationException", tooManyActiveSteps(cluster.getSteps().size()), 400); } + // A security configuration of the cluster's Region is created first and named here; no source gives + // AWS's answer for one that is not there, so the code is RunJobFlow's own for its input and the wording + // that of the other calls. if (cluster.getSecurityConfiguration() != null - && secConfigStore.get(cluster.getSecurityConfiguration()).isEmpty()) { + && secConfigStore.get(securityConfigurationKey(region, cluster.getSecurityConfiguration())) + .isEmpty()) { throw new AwsException("ValidationException", "Security configuration does not exist: " + cluster.getSecurityConfiguration(), 400); } @@ -838,11 +847,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // ──────────────────────────── Security configurations ──────────────────────────── - public SecurityConfiguration createSecurityConfiguration(String name, String json) { + public SecurityConfiguration createSecurityConfiguration(String name, String json, String region) { if (name == null || name.isBlank()) { throw new AwsException("InvalidRequestException", "Name is required.", 400); } - if (secConfigStore.get(name).isPresent()) { + String key = securityConfigurationKey(region, name); + if (secConfigStore.get(key).isPresent()) { throw new AwsException("InvalidRequestException", "Security configuration already exists: " + name, 400); } @@ -850,21 +860,64 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear sc.setName(name); sc.setSecurityConfiguration(json); sc.setCreationDateTime(Instant.now()); - secConfigStore.put(name, sc); + secConfigStore.put(key, sc); return sc; } - public SecurityConfiguration describeSecurityConfiguration(String name) { - return secConfigStore.get(name).orElseThrow(() -> new AwsException( + public SecurityConfiguration describeSecurityConfiguration(String name, String region) { + return secConfigStore.get(securityConfigurationKey(region, name)).orElseThrow(() -> new AwsException( "InvalidRequestException", "Security configuration does not exist: " + name, 400)); } - public void deleteSecurityConfiguration(String name) { - if (secConfigStore.get(name).isEmpty()) { + public void deleteSecurityConfiguration(String name, String region) { + String key = securityConfigurationKey(region, name); + if (secConfigStore.get(key).isEmpty()) { throw new AwsException("InvalidRequestException", "Security configuration does not exist: " + name, 400); } - secConfigStore.delete(name); + secConfigStore.delete(key); + } + + private static String securityConfigurationKey(String region, String name) { + return region + KEY_SEPARATOR + name; + } + + /** + * Moves the security configurations stored before they were keyed by Region from their bare name onto the + * default Region's key: they recorded no Region, and every Region saw them. Every other Region where one of its + * account's clusters names one gets a copy of its own, so the cluster's configuration is still described there. + */ + private void migrateLegacySecurityConfigurations() { + // Built only if a configuration is still stored under its bare name. + Supplier>> regionsUsing = new MemoizedSupplier<>(this::securityConfigurationUses); + secConfigStore.migrateLegacyEntriesToRegions(key -> !isRegionalKey(key), + regionResolver.getDefaultRegion(), + (accountId, sc) -> regionsUsing.get().getOrDefault(accountId + "/" + sc.getName(), Set.of()), + (region, sc) -> sc.getName() == null ? null : securityConfigurationKey(region, sc.getName()), + StorageJson::copy); + } + + /** + * Whether {@code key} is a Region's configuration's, {@code ::}. A name may hold "::" itself, so a key + * stored before is told apart by what precedes the first one: a Region {@link RegionResolver#isKnownRegion} + * admits, as {@code RegionScopedStorage} tells its keys apart. + */ + private static boolean isRegionalKey(String key) { + int separator = key.indexOf(KEY_SEPARATOR); + return separator > 0 && RegionResolver.isKnownRegion(key.substring(0, separator)); + } + + /** The Regions where each account's clusters name each security configuration, by account and name. */ + private Map> securityConfigurationUses() { + Map> uses = new HashMap<>(); + for (AccountAwareStorageBackend.AccountEntry cluster : clusterStore.scanAllAccountEntries(k -> true)) { + String name = cluster.value().getSecurityConfiguration(); + String region = cluster.value().getRegion(); + if (name != null && region != null) { + uses.computeIfAbsent(cluster.accountId() + "/" + name, ignored -> new LinkedHashSet<>()).add(region); + } + } + return uses; } // ──────────────────────────── Release catalogue ──────────────────────────── @@ -958,8 +1011,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return new AwsException("InvalidRequestException", "Invalid pagination token: " + token, 400); } - public List listSecurityConfigurations() { - return new ArrayList<>(secConfigStore.scan(k -> true)); + /** The security configurations of {@code region}. */ + public List listSecurityConfigurations(String region) { + String prefix = region + KEY_SEPARATOR; + return new ArrayList<>(secConfigStore.scan(k -> k.startsWith(prefix))); } // ──────────────────────────── Tags ──────────────────────────── diff --git a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java index b96c51f601..3b0cb47ff3 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java +++ b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java @@ -269,7 +269,7 @@ public class GlueJsonHandler { case "DeleteUserDefinedFunction" -> handleDeleteUserDefinedFunction(request); case "CreateRegistry" -> handleCreateRegistry(request, region); case "GetRegistry" -> handleGetRegistry(request, region); - case "ListRegistries" -> handleListRegistries(request); + case "ListRegistries" -> handleListRegistries(request, region); case "UpdateRegistry" -> handleUpdateRegistry(request, region); case "DeleteRegistry" -> handleDeleteRegistry(request, region); case "CreateSchema" -> handleCreateSchema(request, region); @@ -284,9 +284,9 @@ public class GlueJsonHandler { case "DeleteSchemaVersions" -> handleDeleteSchemaVersions(request, region); case "GetSchemaVersionsDiff" -> handleGetSchemaVersionsDiff(request, region); case "CheckSchemaVersionValidity" -> handleCheckSchemaVersionValidity(request); - case "PutSchemaVersionMetadata" -> handlePutSchemaVersionMetadata(request); - case "RemoveSchemaVersionMetadata" -> handleRemoveSchemaVersionMetadata(request); - case "QuerySchemaVersionMetadata" -> handleQuerySchemaVersionMetadata(request); + case "PutSchemaVersionMetadata" -> handlePutSchemaVersionMetadata(request, region); + case "RemoveSchemaVersionMetadata" -> handleRemoveSchemaVersionMetadata(request, region); + case "QuerySchemaVersionMetadata" -> handleQuerySchemaVersionMetadata(request, region); case "TagResource" -> handleTagResource(request, region); case "UntagResource" -> handleUntagResource(request, region); case "GetTags" -> handleGetTags(request, region); @@ -930,8 +930,8 @@ public class GlueJsonHandler { return Response.ok(registry).build(); } - private Response handleListRegistries(JsonNode request) { - GlueSchemaRegistryService.Page page = schemaRegistryService.listRegistries(readMaxResults(request), readNextToken(request)); + private Response handleListRegistries(JsonNode request, String region) { + GlueSchemaRegistryService.Page page = schemaRegistryService.listRegistries(region, readMaxResults(request), readNextToken(request)); return Response.ok(pageResponse("Registries", registryListItems(page.items()), page.nextToken())).build(); } @@ -1269,25 +1269,25 @@ public class GlueJsonHandler { return instant != null ? instant.toString() : null; } - private Response handlePutSchemaVersionMetadata(JsonNode request) { + private Response handlePutSchemaVersionMetadata(JsonNode request, String region) { String svId = request.path("SchemaVersionId").asText(null); JsonNode kv = request.get("MetadataKeyValue"); String key = kv != null ? kv.path("MetadataKey").asText(null) : null; String value = kv != null ? kv.path("MetadataValue").asText(null) : null; - GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.putSchemaVersionMetadata(svId, key, value); + GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.putSchemaVersionMetadata(svId, key, value, region); return Response.ok(buildMetadataPutResponse(result)).build(); } - private Response handleRemoveSchemaVersionMetadata(JsonNode request) { + private Response handleRemoveSchemaVersionMetadata(JsonNode request, String region) { String svId = request.path("SchemaVersionId").asText(null); JsonNode kv = request.get("MetadataKeyValue"); String key = kv != null ? kv.path("MetadataKey").asText(null) : null; String value = kv != null ? kv.path("MetadataValue").asText(null) : null; - GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.removeSchemaVersionMetadata(svId, key, value); + GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.removeSchemaVersionMetadata(svId, key, value, region); return Response.ok(buildMetadataPutResponse(result)).build(); } - private Response handleQuerySchemaVersionMetadata(JsonNode request) { + private Response handleQuerySchemaVersionMetadata(JsonNode request, String region) { String svId = request.path("SchemaVersionId").asText(null); List filters = new ArrayList<>(); JsonNode list = request.get("MetadataList"); @@ -1298,7 +1298,7 @@ public class GlueJsonHandler { filters.add(new GlueSchemaRegistryService.MetadataKeyValueFilter(k, v)); } } - Map infoMap = schemaRegistryService.querySchemaVersionMetadata(svId, filters); + Map infoMap = schemaRegistryService.querySchemaVersionMetadata(svId, filters, region); Map response = new LinkedHashMap<>(); response.put("MetadataInfoMap", infoMap); response.put("SchemaVersionId", svId); diff --git a/src/main/java/io/floci/aws/services/glue/GlueService.java b/src/main/java/io/floci/aws/services/glue/GlueService.java index 2e25aabfe2..35ddbaa55f 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueService.java @@ -3230,7 +3230,7 @@ public class GlueService { public void tagResource(String arn, Map tags, String region) { validateArn(arn); if (arn.contains(":registry/") || arn.contains(":schema/")) { - schemaRegistryService.tagResource(arn, tags); + schemaRegistryService.tagResource(arn, tags, region); } else { validateResourceExists(arn); resourceGroupsTaggingService.tagResources(List.of(arn), tags, region); @@ -3240,7 +3240,7 @@ public class GlueService { public void untagResource(String arn, List tagKeys, String region) { validateArn(arn); if (arn.contains(":registry/") || arn.contains(":schema/")) { - schemaRegistryService.untagResource(arn, tagKeys); + schemaRegistryService.untagResource(arn, tagKeys, region); } else { validateResourceExists(arn); resourceGroupsTaggingService.untagResources(List.of(arn), tagKeys, region); @@ -3250,7 +3250,7 @@ public class GlueService { public Map getTags(String arn, String region) { validateArn(arn); if (arn.contains(":registry/") || arn.contains(":schema/")) { - return schemaRegistryService.getTags(arn); + return schemaRegistryService.getTags(arn, region); } else { validateResourceExists(arn); return resourceGroupsTaggingService.getTagsForResource(region, arn); diff --git a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java index 448c3752a1..e9d6f2a4ed 100644 --- a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java +++ b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java @@ -6,9 +6,11 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.StorageJson; import io.floci.aws.services.glue.schemaregistry.model.MetadataInfo; import io.floci.aws.services.glue.schemaregistry.model.Registry; import io.floci.aws.services.glue.schemaregistry.model.RegistryId; @@ -35,8 +37,13 @@ import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; +import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.regex.Pattern; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount; + @ApplicationScoped public class GlueSchemaRegistryService { @@ -44,6 +51,8 @@ public class GlueSchemaRegistryService { static final String DEFAULT_REGISTRY_NAME = "default-registry"; private static final Pattern NAME_PATTERN = Pattern.compile("^[A-Za-z0-9_$#.\\-]+$"); + // Separates a key's Region from the registry name: names hold no ':', so a key stored before is told apart. + private static final String KEY_SEPARATOR = "::"; private static final int NAME_MAX_LENGTH = 255; private static final int DEFAULT_MAX_RESULTS = 100; private static final int MAX_MAX_RESULTS = 100; @@ -99,6 +108,7 @@ public class GlueSchemaRegistryService { @PostConstruct void afterCdiInit() { + migrateLegacyKeys(); rebuildVersionIndexes(); } @@ -106,51 +116,57 @@ public class GlueSchemaRegistryService { public Registry createRegistry(String name, String description, Map tags, String region) { validateName(name, "RegistryName"); - if (registryStore.get(name).isPresent()) { + if (registryStore.get(registryKey(region, name)).isPresent()) { throw new AwsException("AlreadyExistsException", "Registry already exists: " + name, 400); } Registry registry = new Registry(name); registry.setDescription(description); registry.setTags(tags); registry.setRegistryArn(buildRegistryArn(region, name)); - registryStore.put(name, registry); + registryStore.put(registryKey(region, name), registry); LOG.infov("Created Glue Registry: {0}", name); return registry; } + /** + * The registry of {@code region} that {@code registryId} names. Registries are Regional: another Region's, + * by name or by ARN, is not found, as one that doesn't exist. + */ public Registry getRegistry(RegistryId registryId, String region) { String name = resolveRegistryName(registryId); - if (DEFAULT_REGISTRY_NAME.equals(name) && registryStore.get(name).isEmpty()) { + requireArnInRegion(registryId == null ? null : registryId.getRegistryArn(), region, + () -> new AwsException("EntityNotFoundException", "Registry not found: " + name, 400)); + if (DEFAULT_REGISTRY_NAME.equals(name) && registryStore.get(registryKey(region, name)).isEmpty()) { return autoCreateDefaultRegistry(region); } - return registryStore.get(name) + return registryStore.get(registryKey(region, name)) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Registry not found: " + name, 400)); } - public List listRegistries() { - return sortedRegistries(); + public List listRegistries(String region) { + return sortedRegistries(region); } - public Page listRegistries(Integer maxResults, String nextToken) { - return paginate(sortedRegistries(), maxResults, nextToken); + public Page listRegistries(String region, Integer maxResults, String nextToken) { + return paginate(sortedRegistries(region), maxResults, nextToken); } public Registry updateRegistry(RegistryId registryId, String description, String region) { Registry registry = getRegistry(registryId, region); registry.setDescription(description); registry.setUpdatedTime(Instant.now()); - registryStore.put(registry.getRegistryName(), registry); + registryStore.put(registryKey(region, registry.getRegistryName()), registry); return registry; } public synchronized Registry deleteRegistry(RegistryId registryId, String region) { Registry registry = getRegistry(registryId, region); - String prefix = registry.getRegistryName() + ":"; + String prefix = registryKey(region, registry.getRegistryName()) + ":"; for (Schema schema : schemaStore.scan(k -> k.startsWith(prefix))) { - deleteSchemaByKey(schemaKey(schema.getRegistryName(), schema.getSchemaName()), schema); + deleteSchemaByKey(schemaKey(schema), schema); } registry.setStatus("DELETING"); - registryStore.delete(registry.getRegistryName()); + registryStore.delete(registryKey(region, registry.getRegistryName())); LOG.infov("Deleted Glue Registry: {0}", registry.getRegistryName()); return registry; } @@ -171,7 +187,7 @@ public class GlueSchemaRegistryService { validateCompatibility(compat); validateDefinitionRequired(definition); Registry registry = getRegistry(registryId, region); - String schemaKey = schemaKey(registry.getRegistryName(), schemaName); + String schemaKey = schemaKey(region, registry.getRegistryName(), schemaName); if (schemaStore.get(schemaKey).isPresent()) { throw new AwsException("AlreadyExistsException", "Schema already exists: " + registry.getRegistryName() + "/" + schemaName, 400); @@ -222,13 +238,13 @@ public class GlueSchemaRegistryService { public List listSchemas(RegistryId registryId, String region) { Registry registry = getRegistry(registryId, region); - String prefix = registry.getRegistryName() + ":"; + String prefix = registryKey(region, registry.getRegistryName()) + ":"; return sortedSchemas(prefix); } public Page listSchemas(RegistryId registryId, String region, Integer maxResults, String nextToken) { Registry registry = getRegistry(registryId, region); - String prefix = registry.getRegistryName() + ":"; + String prefix = registryKey(region, registry.getRegistryName()) + ":"; return paginate(sortedSchemas(prefix), maxResults, nextToken); } @@ -257,13 +273,13 @@ public class GlueSchemaRegistryService { schema.setSchemaCheckpoint(checkpointVersionNumber); } schema.setUpdatedTime(Instant.now()); - schemaStore.put(schemaKey(schema.getRegistryName(), schema.getSchemaName()), schema); + schemaStore.put(schemaKey(schema), schema); return schema; } public synchronized Schema deleteSchema(SchemaId schemaId, String region) { Schema schema = resolveSchema(schemaId, region); - String key = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String key = schemaKey(schema); int versionsDeleted = deleteSchemaByKey(key, schema); schema.setSchemaStatus("DELETING"); LOG.infov("Deleted Glue Schema {0}/{1} ({2} versions)", @@ -283,7 +299,7 @@ public class GlueSchemaRegistryService { "Schema definition is not valid " + dataFormat + ": " + defError, 400); } - String schemaKey = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String schemaKey = schemaKey(schema); String hash = canonicalHash(definition, dataFormat); Map hashIndex = versionByDefinitionHash.computeIfAbsent(schemaKey, k -> new ConcurrentHashMap<>()); String existingId = hashIndex.get(hash); @@ -335,12 +351,10 @@ public class GlueSchemaRegistryService { boolean latestVersion, String region) { if (schemaVersionId != null && !schemaVersionId.isBlank()) { - return versionStore.get(schemaVersionId) - .orElseThrow(() -> new AwsException("EntityNotFoundException", - "Schema version not found: " + schemaVersionId, 400)); + return versionIn(schemaVersionId, region); } Schema schema = resolveSchema(schemaId, region); - String schemaKey = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String schemaKey = schemaKey(schema); NavigableMap byNumber = versionByNumber.get(schemaKey); if (byNumber == null || byNumber.isEmpty()) { throw new AwsException("EntityNotFoundException", "No schema versions for " + schemaKey, 400); @@ -376,7 +390,7 @@ public class GlueSchemaRegistryService { } private List sortedSchemaVersions(Schema schema) { - String key = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String key = schemaKey(schema); NavigableMap byNumber = versionByNumber.get(key); if (byNumber == null || byNumber.isEmpty()) { return List.of(); @@ -395,7 +409,7 @@ public class GlueSchemaRegistryService { throw new AwsException("InvalidInputException", "Versions expression is required", 400); } Schema schema = resolveSchema(schemaId, region); - String key = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String key = schemaKey(schema); NavigableMap byNumber = versionByNumber.get(key); if (byNumber == null) { byNumber = new ConcurrentSkipListMap<>(); @@ -475,11 +489,10 @@ public class GlueSchemaRegistryService { public synchronized MetadataPutResult putSchemaVersionMetadata(String schemaVersionId, String key, - String value) { + String value, + String region) { validateMetadataKeyValue(key, value); - SchemaVersion version = versionStore.get(schemaVersionId) - .orElseThrow(() -> new AwsException("EntityNotFoundException", - "Schema version not found: " + schemaVersionId, 400)); + SchemaVersion version = versionIn(schemaVersionId, region); Map metadata = metadataStore.get(schemaVersionId).orElseGet(LinkedHashMap::new); MetadataInfo info = metadata.get(key); @@ -513,11 +526,10 @@ public class GlueSchemaRegistryService { public synchronized MetadataPutResult removeSchemaVersionMetadata(String schemaVersionId, String key, - String value) { + String value, + String region) { validateMetadataKeyValue(key, value); - SchemaVersion version = versionStore.get(schemaVersionId) - .orElseThrow(() -> new AwsException("EntityNotFoundException", - "Schema version not found: " + schemaVersionId, 400)); + SchemaVersion version = versionIn(schemaVersionId, region); Map metadata = metadataStore.get(schemaVersionId) .orElseThrow(() -> new AwsException("EntityNotFoundException", @@ -566,11 +578,9 @@ public class GlueSchemaRegistryService { } public Map querySchemaVersionMetadata(String schemaVersionId, - List metadataList) { - if (versionStore.get(schemaVersionId).isEmpty()) { - throw new AwsException("EntityNotFoundException", - "Schema version not found: " + schemaVersionId, 400); - } + List metadataList, + String region) { + versionIn(schemaVersionId, region); Map stored = metadataStore.get(schemaVersionId).orElse(Map.of()); if (metadataList == null || metadataList.isEmpty()) { return stored; @@ -597,11 +607,11 @@ public class GlueSchemaRegistryService { // ---- Tags ------------------------------------------------------------ - public synchronized void tagResource(String resourceArn, Map tagsToAdd) { + public synchronized void tagResource(String resourceArn, Map tagsToAdd, String region) { if (tagsToAdd == null || tagsToAdd.isEmpty()) { return; } - TaggedResource resource = resolveTaggedResource(resourceArn); + TaggedResource resource = resolveTaggedResource(resourceArn, region); Map tags = resource.getTags(); if (tags == null) { tags = new LinkedHashMap<>(); @@ -613,11 +623,11 @@ public class GlueSchemaRegistryService { resource.persist(); } - public synchronized void untagResource(String resourceArn, List tagKeysToRemove) { + public synchronized void untagResource(String resourceArn, List tagKeysToRemove, String region) { if (tagKeysToRemove == null || tagKeysToRemove.isEmpty()) { return; } - TaggedResource resource = resolveTaggedResource(resourceArn); + TaggedResource resource = resolveTaggedResource(resourceArn, region); Map tags = resource.getTags(); if (tags == null || tags.isEmpty()) { return; @@ -631,8 +641,8 @@ public class GlueSchemaRegistryService { } /** - * A copy of the tags of the registry or the schema stored under {@code arn} in the account it names, matched on the - * whole ARN and read in place; empty for an ARN naming nothing stored, or any other resource. + * A copy of the tags of the registry or the schema stored under {@code arn} in the account and Region it names, + * matched on the whole ARN and read in place; empty for an ARN naming nothing stored, or any other resource. */ public Map storedTags(String arn) { AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); @@ -640,7 +650,7 @@ public class GlueSchemaRegistryService { Map tags = null; if (resource.startsWith("registry/")) { tags = AccountAwareStorageBackend.readInAccount(registryStore, parsed.accountId(), - resource.substring("registry/".length())) + registryKey(parsed.region(), resource.substring("registry/".length()))) .filter(registry -> arn.equals(registry.getRegistryArn())) .map(Registry::getTags) .orElse(null); @@ -648,7 +658,7 @@ public class GlueSchemaRegistryService { String[] names = resource.substring("schema/".length()).split("/", 2); if (names.length == 2) { tags = AccountAwareStorageBackend.readInAccount(schemaStore, parsed.accountId(), - schemaKey(names[0], names[1])) + schemaKey(parsed.region(), names[0], names[1])) .filter(schema -> arn.equals(schema.getSchemaArn())) .map(Schema::getTags) .orElse(null); @@ -657,8 +667,8 @@ public class GlueSchemaRegistryService { return tags == null ? Map.of() : new LinkedHashMap<>(tags); } - public Map getTags(String resourceArn) { - TaggedResource resource = resolveTaggedResource(resourceArn); + public Map getTags(String resourceArn, String region) { + TaggedResource resource = resolveTaggedResource(resourceArn, region); Map tags = resource.getTags(); return tags != null ? tags : Map.of(); } @@ -678,7 +688,7 @@ public class GlueSchemaRegistryService { public SchemaVersion getSchemaByDefinition(SchemaId schemaId, String definition, String region) { validateDefinitionRequired(definition); Schema schema = resolveSchema(schemaId, region); - String schemaKey = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String schemaKey = schemaKey(schema); String dataFormat = schema.getDataFormat(); for (int attempt = 0; attempt < MAX_LOOKUP_FORMAT_ATTEMPTS; attempt++) { String hash = canonicalHash(definition, dataFormat); @@ -726,27 +736,31 @@ public class GlueSchemaRegistryService { void persist(); } - private TaggedResource resolveTaggedResource(String resourceArn) { + /** The registry or schema {@code resourceArn} names, if it is of {@code region}: another Region's is not found. */ + private TaggedResource resolveTaggedResource(String resourceArn, String region) { if (resourceArn == null || resourceArn.isBlank()) { throw new AwsException("InvalidInputException", "ResourceArn is required", 400); } if (resourceArn.contains(":registry/")) { String name = parseRegistryNameFromArn(resourceArn); - Registry r = registryStore.get(name) - .orElseThrow(() -> new AwsException("EntityNotFoundException", - "Registry not found: " + name, 400)); + Supplier notFound = () -> new AwsException("EntityNotFoundException", + "Registry not found: " + name, 400); + requireArnInRegion(resourceArn, region, notFound); + String key = registryKey(region, name); + Registry r = registryStore.get(key).orElseThrow(notFound); return new TaggedResource() { @Override public Map getTags() { return r.getTags(); } @Override public void setTags(Map tags) { r.setTags(tags); } - @Override public void persist() { registryStore.put(r.getRegistryName(), r); } + @Override public void persist() { registryStore.put(key, r); } }; } if (resourceArn.contains(":schema/")) { String[] parts = parseSchemaArn(resourceArn); - String key = schemaKey(parts[0], parts[1]); - Schema s = schemaStore.get(key) - .orElseThrow(() -> new AwsException("EntityNotFoundException", - "Schema not found: " + parts[0] + "/" + parts[1], 400)); + Supplier notFound = () -> new AwsException("EntityNotFoundException", + "Schema not found: " + parts[0] + "/" + parts[1], 400); + requireArnInRegion(resourceArn, region, notFound); + String key = schemaKey(region, parts[0], parts[1]); + Schema s = schemaStore.get(key).orElseThrow(notFound); return new TaggedResource() { @Override public Map getTags() { return s.getTags(); } @Override public void setTags(Map tags) { s.setTags(tags); } @@ -858,6 +872,8 @@ public class GlueSchemaRegistryService { String schemaName; if (schemaId.getSchemaArn() != null && !schemaId.getSchemaArn().isBlank()) { String[] parsed = parseSchemaArn(schemaId.getSchemaArn()); + requireArnInRegion(schemaId.getSchemaArn(), region, () -> new AwsException("EntityNotFoundException", + "Schema is not found. " + parsed[0] + "/" + parsed[1], 400)); registryName = parsed[0]; schemaName = parsed[1]; } else { @@ -872,13 +888,13 @@ public class GlueSchemaRegistryService { registryName = reg.getRegistryName(); } else { registryName = requested; - if (registryStore.get(registryName).isEmpty()) { + if (registryStore.get(registryKey(region, registryName)).isEmpty()) { throw new AwsException("EntityNotFoundException", "Registry not found: " + registryName, 400); } } } - String key = schemaKey(registryName, schemaName); + String key = schemaKey(region, registryName, schemaName); return schemaStore.get(key) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Schema is not found. " + registryName + "/" + schemaName, 400)); @@ -909,8 +925,9 @@ public class GlueSchemaRegistryService { return defs; } - private List sortedRegistries() { - List registries = new ArrayList<>(registryStore.scan(k -> true)); + private List sortedRegistries(String region) { + String prefix = registryKey(region, ""); + List registries = new ArrayList<>(registryStore.scan(k -> k.startsWith(prefix))); registries.sort(Comparator.comparing(Registry::getRegistryName, Comparator.nullsLast(String::compareTo))); return registries; @@ -949,7 +966,7 @@ public class GlueSchemaRegistryService { if (checkpointVersionNumber < 1) { throw new AwsException("InvalidInputException", "Schema checkpoint version must be at least 1", 400); } - String key = schemaKey(schema.getRegistryName(), schema.getSchemaName()); + String key = schemaKey(schema); NavigableMap byNumber = versionByNumber.get(key); if (byNumber == null || !byNumber.containsKey(checkpointVersionNumber)) { throw new AwsException("EntityNotFoundException", @@ -975,7 +992,7 @@ public class GlueSchemaRegistryService { private Schema schemaForVersion(SchemaVersion version) { String[] parts = parseSchemaArn(version.getSchemaArn()); - String key = schemaKey(parts[0], parts[1]); + String key = schemaKey(regionOf(version.getSchemaArn()), parts[0], parts[1]); return schemaStore.get(key) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Schema not found for version: " + version.getSchemaVersionId(), 400)); @@ -996,7 +1013,7 @@ public class GlueSchemaRegistryService { versionByDefinitionHash.clear(); Map arnToSchemaKey = new HashMap<>(); for (Schema s : schemaStore.scan(k -> true)) { - arnToSchemaKey.put(s.getSchemaArn(), schemaKey(s.getRegistryName(), s.getSchemaName())); + arnToSchemaKey.put(s.getSchemaArn(), schemaKey(s)); } List versions = new ArrayList<>(versionStore.scan(k -> true)); versions.sort(Comparator.comparing(SchemaVersion::getVersionNumber)); @@ -1022,7 +1039,7 @@ public class GlueSchemaRegistryService { private Registry autoCreateDefaultRegistry(String region) { Registry registry = new Registry(DEFAULT_REGISTRY_NAME); registry.setRegistryArn(buildRegistryArn(region, DEFAULT_REGISTRY_NAME)); - registryStore.put(DEFAULT_REGISTRY_NAME, registry); + registryStore.put(registryKey(region, DEFAULT_REGISTRY_NAME), registry); LOG.infov("Auto-created default Glue Registry"); return registry; } @@ -1060,10 +1077,94 @@ public class GlueSchemaRegistryService { return regionResolver.buildArn("glue", region, "schema/" + registryName + "/" + schemaName); } - private static String schemaKey(String registryName, String schemaName) { - return registryName + ":" + schemaName; + /** A registry's key: registries are Regional, so it holds their Region and name. */ + private static String registryKey(String region, String registryName) { + return region + KEY_SEPARATOR + registryName; } + /** A schema's key: its registry's key, then the schema's name. */ + private static String schemaKey(String region, String registryName, String schemaName) { + return registryKey(region, registryName) + ":" + schemaName; + } + + /** A stored schema's key, in the Region its ARN names. */ + private String schemaKey(Schema schema) { + return schemaKey(regionOf(schema.getSchemaArn()), schema.getRegistryName(), schema.getSchemaName()); + } + + /** The Region an ARN this service minted names; one stored without an ARN counts as the default Region's. */ + private String regionOf(String arn) { + return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion()); + } + + /** The version by that id, if its schema is of {@code region}: another Region's is not found. */ + private SchemaVersion versionIn(String schemaVersionId, String region) { + return versionStore.get(schemaVersionId) + .filter(version -> region.equals(regionOf(version.getSchemaArn()))) + .orElseThrow(() -> new AwsException("EntityNotFoundException", + "Schema version not found: " + schemaVersionId, 400)); + } + + /** Refuses an ARN naming another Region: registries and schemas are Regional, so it names none here. */ + private void requireArnInRegion(String arn, String region, Supplier notFound) { + if (arn != null && !arn.isBlank() && !region.equals(regionOf(arn))) { + throw notFound.get(); + } + } + + /** + * Moves the registries and schemas stored before they were keyed by Region, under their bare name or + * {@code registry:schema}, onto the key of the Region their ARN names. Every Region saw every registry then, so a + * schema could be created in another Region than its registry: that registry gets a copy in the schema's Region, + * which the schema then names, so it still has its registry there. + */ + private void migrateLegacyKeys() { + // Records stored before are in the factory's account stores, the only stores production has. + if (!(registryStore instanceof AccountAwareStorageBackend registryAccounts) + || !(schemaStore instanceof AccountAwareStorageBackend schemaAccounts)) { + return; + } + Map> registries = new HashMap<>(); + for (AccountEntry registry : registryAccounts.scanAllAccountEntries(LEGACY_KEY)) { + registries.put(registry.accountId() + "/" + registry.value().getRegistryName(), registry); + } + List> renamed = new ArrayList<>(); + for (AccountEntry entry : schemaAccounts.scanAllAccountEntries(LEGACY_KEY)) { + Schema schema = entry.value(); + String region = regionOf(schema.getSchemaArn()); + AccountEntry registry = registries.get(entry.accountId() + "/" + schema.getRegistryName()); + if (registry == null || region.equals(regionOf(registry.value().getRegistryArn()))) { + continue; + } + String key = registryKey(region, schema.getRegistryName()); + Registry copy = getInAccount(registryStore, entry.accountId(), key) + .orElseGet(() -> copyIn(registry.value(), region, entry.accountId())); + putInAccount(registryStore, entry.accountId(), key, copy); + schema.setRegistryArn(copy.getRegistryArn()); + // A record already under the new key is the newer one, which the move keeps. + if (getInAccount(schemaStore, entry.accountId(), schemaKey(schema)).isEmpty()) { + renamed.add(entry); + } + } + registryAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY, + registry -> registryKey(regionOf(registry.getRegistryArn()), registry.getRegistryName())); + schemaAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY, this::schemaKey); + // Written once moved, under the new key: a schema stored before accounts prefixed keys would otherwise + // leave its unprefixed record beside a second legacy one. + for (AccountEntry entry : renamed) { + putInAccount(schemaStore, entry.accountId(), schemaKey(entry.value()), entry.value()); + } + } + + /** {@code registry} as a registry of {@code region}, in {@code accountId}, its ARN naming that Region. */ + private Registry copyIn(Registry registry, String region, String accountId) { + Registry copy = StorageJson.copy(registry); + copy.setRegistryArn(regionResolver.buildArn("glue", region, accountId, "registry/" + registry.getRegistryName())); + return copy; + } + + private static final Predicate LEGACY_KEY = key -> !key.contains(KEY_SEPARATOR); + private void validateName(String name, String field) { if (name == null || name.isBlank()) { throw new AwsException("InvalidInputException", field + " is required", 400); diff --git a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java index 663ad41bc4..00c76d2ff0 100644 --- a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java +++ b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java @@ -472,6 +472,40 @@ class AccountAwareStorageBackendTest { Set.copyOf(raw.keys())); } + /** + * A legacy entry is copied to each other Region its account's resources name it in, keeping a record already + * there, and then moves to the default Region; one no resource names moves only. The default Region named too + * gets the moved entry, not a copy. + */ + @Test + void migrateLegacyEntriesToRegionsCopiesEachToTheRegionsUsingItThenMovesItToTheDefaultRegion() { + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("123456789012/used", "used"); + raw.put("123456789012/unused", "unused"); + raw.put("123456789012/eu-west-1::used", "already there"); + raw.put("gen0", "default-account"); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, "000000000000"); + List asked = new ArrayList<>(); + + storage.migrateLegacyEntriesToRegions(key -> !key.contains("::"), "us-east-1", + (account, value) -> { + asked.add(account + " " + value); + return value.equals("used") ? Set.of("us-east-1", "eu-central-1", "eu-west-1") : Set.of(); + }, + (region, value) -> region + "::" + value, value -> value + " (copy)"); + + assertEquals(List.of("000000000000 default-account", "123456789012 unused", "123456789012 used"), + asked.stream().sorted().toList()); + assertEquals(Map.of( + "123456789012/us-east-1::used", "used", + "123456789012/eu-central-1::used", "used (copy)", + "123456789012/eu-west-1::used", "already there", + "123456789012/us-east-1::unused", "unused", + "000000000000/us-east-1::default-account", "default-account"), + raw.keys().stream().collect(Collectors.toMap(key -> key, key -> raw.get(key).orElseThrow()))); + } + /** * {@code get} and {@code getForAccountMigratingLegacy} both migrate a pre-multi-account entry, and * both delete the legacy key once they have copied it. Unless they hold the same monitor, two readers diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheParameterGroupLegacyKeysTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheParameterGroupLegacyKeysTest.java new file mode 100644 index 0000000000..a43209b509 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheParameterGroupLegacyKeysTest.java @@ -0,0 +1,54 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.elasticache.model.CacheParameterGroup; +import io.floci.aws.services.elasticache.model.ReplicationGroup; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Cache parameter groups stored before they were keyed by Region, under their bare name, move at startup to the + * default Region, and every other Region where one of the account's replication groups names one gets a copy of it, + * so that group still finds it there. + */ +class ElastiCacheParameterGroupLegacyKeysTest { + + private static final String ACCOUNT = "000000000000"; + + @Test + @SuppressWarnings("unchecked") + void aLegacyGroupMovesToTheDefaultRegionAndIsCopiedToTheRegionOfAReplicationGroupNamingIt() { + ElastiCacheServiceFixture fixture = new ElastiCacheServiceFixture(); + AccountAwareStorageBackend parameterGroups = (AccountAwareStorageBackend) + fixture.backendsByFile.get("elasticache-parameter-groups.json"); + AccountAwareStorageBackend groups = (AccountAwareStorageBackend) + fixture.backendsByFile.get("elasticache-groups.json"); + CacheParameterGroup used = new CacheParameterGroup("used", "redis7", "named by a group"); + used.setParameters(new LinkedHashMap<>(Map.of("maxmemory-policy", "allkeys-lru"))); + parameterGroups.put("used", used); + parameterGroups.put("unused", new CacheParameterGroup("unused", "redis7", "named by none")); + ReplicationGroup group = new ReplicationGroup(); + group.setReplicationGroupId("in-frankfurt"); + group.setArn("arn:aws:elasticache:eu-central-1:" + ACCOUNT + ":replicationgroup:in-frankfurt"); + group.setCacheParameterGroupName("used"); + groups.put("in-frankfurt", group); + + fixture.service.migrateLegacyParameterGroups(); + + assertEquals(Set.of("us-east-1::used", "us-east-1::unused", "eu-central-1::used"), + parameterGroups.keysForAccount(ACCOUNT)); + assertEquals(Map.of("maxmemory-policy", "allkeys-lru"), + parameterGroups.get("eu-central-1::used").orElseThrow().getParameters()); + // Outside a request, the service answers for the default Region, us-east-1. + assertEquals(Set.of("used", "unused"), fixture.service.describeCacheParameterGroups(null).stream() + .map(CacheParameterGroup::getName) + .filter(name -> !name.startsWith("default.")) + .collect(Collectors.toSet())); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java index c6fe086e75..293e6f5c22 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheRegionScopingIntegrationTest.java @@ -11,10 +11,10 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; /** - * Replication groups, cache clusters, users and user groups are Regional on AWS: one created in a Region of an - * account is listed, and found by its id, only from that Region of that account. Each case creates the resource - * in {@link #HOME} of {@link #ACCOUNT} and checks the unfiltered listing and the id filter from there, from - * {@link #OTHER_REGION} of the same account, and from {@link #HOME} of {@link #OTHER_ACCOUNT}. + * Replication groups, cache clusters, users, user groups and cache parameter groups are Regional on AWS: one + * created in a Region of an account is listed, and found by its id, only from that Region of that account. Each case + * creates the resource in {@link #HOME} of {@link #ACCOUNT} and checks the unfiltered listing and the id filter from + * there, from {@link #OTHER_REGION} of the same account, and from {@link #HOME} of {@link #OTHER_ACCOUNT}. */ @QuarkusTest class ElastiCacheRegionScopingIntegrationTest { @@ -106,6 +106,32 @@ class ElastiCacheRegionScopingIntegrationTest { assertCacheClusterIsRegional("region-scoped-memcached", "memcached"); } + @Test + void cacheParameterGroupIsOnlyVisibleInItsRegionAndAccountAndItsNameIsFreeElsewhere() { + String name = "region-scoped-params"; + String[] create = {"CacheParameterGroupName", name, "CacheParameterGroupFamily", "redis7", + "Description", "scoped"}; + send(ACCOUNT, HOME, "CreateCacheParameterGroup", create).then().statusCode(200); + try { + assertRegional("DescribeCacheParameterGroups", "CacheParameterGroupName", name, + "" + name + ""); + send(ACCOUNT, OTHER_REGION, "ModifyCacheParameterGroup", "CacheParameterGroupName", name, + "ParameterNameValues.ParameterNameValue.1.ParameterName", "maxmemory-policy", + "ParameterNameValues.ParameterNameValue.1.ParameterValue", "allkeys-lru") + .then().statusCode(404); + send(ACCOUNT, OTHER_REGION, "DeleteCacheParameterGroup", "CacheParameterGroupName", name) + .then().statusCode(404); + + send(ACCOUNT, OTHER_REGION, "CreateCacheParameterGroup", create).then().statusCode(200); + send(ACCOUNT, OTHER_REGION, "DeleteCacheParameterGroup", "CacheParameterGroupName", name) + .then().statusCode(200); + send(ACCOUNT, HOME, "DescribeCacheParameterGroups", "CacheParameterGroupName", name) + .then().statusCode(200); + } finally { + send(ACCOUNT, HOME, "DeleteCacheParameterGroup", "CacheParameterGroupName", name).then().statusCode(200); + } + } + private static void assertCacheClusterIsRegional(String cluster, String engine) { send(ACCOUNT, HOME, "CreateCacheCluster", "CacheClusterId", cluster, "Engine", engine, "NumCacheNodes", "1", "CacheNodeType", "cache.t3.micro").then().statusCode(200); diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java index 78913b8c64..20f73a22b0 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheServiceTest.java @@ -234,7 +234,8 @@ class ElastiCacheServiceTest { Field locksField = ElastiCacheService.class.getDeclaredField("parameterGroupLocks"); locksField.setAccessible(true); - Object monitor = ((ConcurrentHashMap) locksField.get(service)).get(name); + // Each group's monitor is keyed by its Region and name, as the group is. + Object monitor = ((ConcurrentHashMap) locksField.get(service)).get("us-east-1::" + name); ExecutorService pool = Executors.newSingleThreadExecutor(); AtomicReference writer = new AtomicReference<>(); try { diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterRegionIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterRegionIntegrationTest.java index 7bb9986195..7cbfd8e6a9 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterRegionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterRegionIntegrationTest.java @@ -5,6 +5,8 @@ import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.util.UUID; + import static io.floci.aws.testing.EmrRequests.emr; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; @@ -61,6 +63,39 @@ class EmrClusterRegionIntegrationTest { .then().statusCode(200); } + @Test + void aSecurityConfigurationIsListedDescribedAndNamedOnlyInItsRegion() { + String name = "sec-" + UUID.randomUUID().toString().substring(0, 8); + String create = "{\"Name\":\"" + name + "\",\"SecurityConfiguration\":\"{\\\"EncryptionConfiguration\\\":{}}\"}"; + String byName = "{\"Name\":\"" + name + "\"}"; + emr(HOME, "CreateSecurityConfiguration", create).then().statusCode(200); + try { + emr(OTHER, "ListSecurityConfigurations", "{}").then().statusCode(200) + .body("SecurityConfigurations.Name", not(hasItem(name))); + emr(OTHER, "DescribeSecurityConfiguration", byName).then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("Security configuration does not exist: " + name)); + emr(OTHER, "DeleteSecurityConfiguration", byName).then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr(OTHER, "RunJobFlow", "{\"Name\":\"secured\",\"ReleaseLabel\":\"emr-7.5.0\",\"SecurityConfiguration\":\"" + + name + "\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"Name\":\"master\",\"InstanceRole\":\"MASTER\"," + + "\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + + emr(OTHER, "CreateSecurityConfiguration", create).then().statusCode(200); + emr(OTHER, "DeleteSecurityConfiguration", byName).then().statusCode(200); + + emr(HOME, "ListSecurityConfigurations", "{}").then().statusCode(200) + .body("SecurityConfigurations.Name", hasItem(name)); + emr(HOME, "DescribeSecurityConfiguration", byName).then().statusCode(200) + .body("Name", equalTo(name)); + } finally { + emr(HOME, "DeleteSecurityConfiguration", byName); + } + } + // Catches: an instance's or the master's private DNS name in the wrong region's domain. @Test void listedInstancesUseTheClustersRegionalPrivateDnsDomain() { diff --git a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java index 6fc0fd988a..f36274017a 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java @@ -291,7 +291,7 @@ class EmrIntegrationTest { .then().statusCode(200) .body("SecurityConfiguration", equalTo("{\"EncryptionConfiguration\":{}}")); - emrService.describeSecurityConfiguration("floci-emr-sec") + emrService.describeSecurityConfiguration("floci-emr-sec", "us-east-1") .setCreationDateTime(Instant.ofEpochMilli(1_761_000_000_123L)); try { JsonNode describedTime = objectMapper.readTree(emr("DescribeSecurityConfiguration", diff --git a/src/test/java/io/floci/aws/services/emr/EmrSecurityConfigurationLegacyKeysTest.java b/src/test/java/io/floci/aws/services/emr/EmrSecurityConfigurationLegacyKeysTest.java new file mode 100644 index 0000000000..1b23082ab0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrSecurityConfigurationLegacyKeysTest.java @@ -0,0 +1,69 @@ +package io.floci.aws.services.emr; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.emr.model.EmrCluster; +import io.floci.aws.services.emr.model.SecurityConfiguration; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT; +import static io.floci.aws.services.emr.EmrServiceFixture.REGION; +import static io.floci.aws.services.emr.EmrServiceFixture.cluster; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Security configurations stored before they were keyed by Region, under their bare name, move at startup to the + * default Region, and every other Region where one of the account's clusters names one gets a copy of it, so the + * cluster's configuration is still described there. + */ +class EmrSecurityConfigurationLegacyKeysTest { + + private static final String CLUSTER_REGION = "eu-central-1"; + + @Test + void aLegacyConfigurationMovesToTheDefaultRegionAndIsCopiedToTheRegionsOfTheClustersNamingIt() { + EmrServiceFixture fixture = new EmrServiceFixture(); + AccountAwareStorageBackend configurations = fixture.storage.create("emr", + "emr-security-configs.json", new TypeReference>() {}); + configurations.put("used", configuration("used")); + configurations.put("unused", configuration("unused")); + // A name may hold the separator itself: it is still a key stored before. + configurations.put("team::prod", configuration("team::prod")); + // A key already of a Region, any Region a partition publishes, stays where it is. + configurations.put("eusc-de-east-1::sovereign", configuration("sovereign")); + String clusterId = fixture.service.runJobFlow(cluster("secured", true), CLUSTER_REGION).getId(); + AccountAwareStorageBackend clusters = fixture.storage.create("emr", "emr-clusters.json", + new TypeReference>() {}); + EmrCluster stored = clusters.get(clusterId).orElseThrow(); + stored.setSecurityConfiguration("used"); + clusters.put(clusterId, stored); + + EmrService restarted = fixture.restartImmediate().service; + + assertEquals(Set.of(REGION + "::used", REGION + "::unused", REGION + "::team::prod", CLUSTER_REGION + "::used", + "eusc-de-east-1::sovereign"), configurations.keysForAccount(ACCOUNT)); + assertEquals(Set.of("sovereign"), names(restarted.listSecurityConfigurations("eusc-de-east-1"))); + assertEquals(Set.of("used", "unused", "team::prod"), names(restarted.listSecurityConfigurations(REGION))); + assertEquals(Set.of("used"), names(restarted.listSecurityConfigurations(CLUSTER_REGION))); + assertEquals(Set.of(), names(restarted.listSecurityConfigurations("eu-west-1"))); + assertEquals("{\"EncryptionConfiguration\":{}}", + restarted.describeSecurityConfiguration("used", CLUSTER_REGION).getSecurityConfiguration()); + } + + private static SecurityConfiguration configuration(String name) { + SecurityConfiguration configuration = new SecurityConfiguration(); + configuration.setName(name); + configuration.setSecurityConfiguration("{\"EncryptionConfiguration\":{}}"); + configuration.setCreationDateTime(Instant.parse("2026-11-01T00:00:00Z")); + return configuration; + } + + private static Set names(List configurations) { + return Set.copyOf(configurations.stream().map(SecurityConfiguration::getName).toList()); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryLegacyKeysTest.java b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryLegacyKeysTest.java new file mode 100644 index 0000000000..21fbbd6f7d --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryLegacyKeysTest.java @@ -0,0 +1,110 @@ +package io.floci.aws.services.glue.schemaregistry; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.glue.schemaregistry.model.Registry; +import io.floci.aws.services.glue.schemaregistry.model.RegistryId; +import io.floci.aws.services.glue.schemaregistry.model.Schema; +import io.floci.aws.services.glue.schemaregistry.model.SchemaId; +import io.floci.aws.services.glue.schemaregistry.model.SchemaVersion; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Instant; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Registries and schemas stored before they were keyed by Region, under their bare name and {@code registry:schema}, + * move at startup onto the key of the Region their ARN names, or the default Region's when they have no ARN. Each is + * then listed and reached there, its versions with it, and a schema of another Region than its registry keeps a copy + * of that registry in its own Region. The stores are account stores, as the storage factory gives the service. + */ +class GlueSchemaRegistryLegacyKeysTest { + + private static final String ACCOUNT = "000000000000"; + private static final String DEFAULT = "us-east-1"; + private static final String FRANKFURT = "eu-central-1"; + private static final String DEFINITION = + "{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"x\",\"fields\":[{\"name\":\"id\",\"type\":\"long\"}]}"; + + @Test + void storedRegistriesAndSchemasMoveToTheRegionTheirArnNames() { + AccountAwareStorageBackend registries = AccountAwareStorageBackend.inMemory(ACCOUNT); + AccountAwareStorageBackend schemas = AccountAwareStorageBackend.inMemory(ACCOUNT); + AccountAwareStorageBackend versions = AccountAwareStorageBackend.inMemory(ACCOUNT); + Registry frankfurt = new Registry("reg"); + frankfurt.setRegistryArn("arn:aws:glue:" + FRANKFURT + ":" + ACCOUNT + ":registry/reg"); + registries.put("reg", frankfurt); + registries.put("bare", new Registry("bare")); + Schema schema = new Schema(); + schema.setRegistryName("reg"); + schema.setRegistryArn(frankfurt.getRegistryArn()); + schema.setSchemaName("users"); + schema.setSchemaArn("arn:aws:glue:" + FRANKFURT + ":" + ACCOUNT + ":schema/reg/users"); + schema.setDataFormat("AVRO"); + schema.setCompatibility("BACKWARD"); + schema.setLatestSchemaVersion(1L); + schema.setNextSchemaVersion(2L); + schemas.put("reg:users", schema); + SchemaVersion version = new SchemaVersion(); + version.setSchemaVersionId("version-1"); + version.setSchemaArn(schema.getSchemaArn()); + version.setVersionNumber(1L); + version.setStatus("AVAILABLE"); + version.setSchemaDefinition(DEFINITION); + version.setDataFormat("AVRO"); + version.setCreatedTime(Instant.parse("2026-11-01T00:00:00Z")); + versions.put("version-1", version); + + GlueSchemaRegistryService service = new GlueSchemaRegistryService(registries, schemas, versions, + AccountAwareStorageBackend.inMemory(ACCOUNT), new RegionResolver(DEFAULT, ACCOUNT)); + service.afterCdiInit(); + + assertEquals(Set.of(FRANKFURT + "::reg", DEFAULT + "::bare"), registries.keysForAccount(ACCOUNT)); + assertEquals(Set.of(FRANKFURT + "::reg:users"), schemas.keysForAccount(ACCOUNT)); + assertEquals(List.of("reg"), service.listRegistries(FRANKFURT).stream().map(Registry::getRegistryName).toList()); + assertEquals(List.of("bare"), service.listRegistries(DEFAULT).stream().map(Registry::getRegistryName).toList()); + assertEquals(List.of("users"), service.listSchemas(new RegistryId("reg", null), FRANKFURT).stream() + .map(Schema::getSchemaName).toList()); + assertEquals("version-1", service.getSchemaByDefinition(new SchemaId("reg", "users", null), DEFINITION, + FRANKFURT).getSchemaVersionId()); + assertEquals("version-1", service.getSchemaVersion(null, "version-1", null, false, FRANKFURT) + .getSchemaVersionId()); + } + + /** The copy's ARN names its Region whether the registry was stored with an ARN or, the default Region's, without. */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void aSchemaOfAnotherRegionThanItsRegistryKeepsACopyOfItsRegistryThere(boolean storedWithAnArn) { + AccountAwareStorageBackend registries = AccountAwareStorageBackend.inMemory(ACCOUNT); + AccountAwareStorageBackend schemas = AccountAwareStorageBackend.inMemory(ACCOUNT); + Registry home = new Registry("orders"); + home.setRegistryArn(storedWithAnArn ? "arn:aws:glue:" + DEFAULT + ":" + ACCOUNT + ":registry/orders" : null); + home.setDescription("orders"); + registries.put("orders", home); + // Every Region saw every registry, so a schema of it could be created in another Region. + Schema schema = new Schema(); + schema.setRegistryName("orders"); + schema.setRegistryArn(home.getRegistryArn()); + schema.setSchemaName("o1"); + schema.setSchemaArn("arn:aws:glue:" + FRANKFURT + ":" + ACCOUNT + ":schema/orders/o1"); + schema.setDataFormat("AVRO"); + schemas.put("orders:o1", schema); + + GlueSchemaRegistryService service = new GlueSchemaRegistryService(registries, schemas, AccountAwareStorageBackend.inMemory(ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), new RegionResolver(DEFAULT, ACCOUNT)); + service.afterCdiInit(); + + assertEquals(Set.of(DEFAULT + "::orders", FRANKFURT + "::orders"), registries.keysForAccount(ACCOUNT)); + Registry copy = service.getRegistry(new RegistryId("orders", null), FRANKFURT); + assertEquals("arn:aws:glue:" + FRANKFURT + ":" + ACCOUNT + ":registry/orders", copy.getRegistryArn()); + assertEquals("orders", copy.getDescription()); + Schema moved = service.getSchema(new SchemaId("orders", "o1", null), FRANKFURT); + assertEquals(copy.getRegistryArn(), moved.getRegistryArn()); + assertEquals(List.of(), service.listSchemas(new RegistryId("orders", null), DEFAULT)); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryRegionScopingIntegrationTest.java new file mode 100644 index 0000000000..5acef6f851 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryRegionScopingIntegrationTest.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.glue.schemaregistry; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; + +/** + * Glue Schema Registry registries and their schemas are Regional: each is listed and reached only in the Region it + * was created in, by its name, its ARN or a schema version's id, and its name can be used again in another Region. + * Another Region's answers {@code EntityNotFoundException}, as one that doesn't exist does. + */ +@QuarkusTest +class GlueSchemaRegistryRegionScopingIntegrationTest { + + private static final String HOME = "eu-west-1"; + private static final String OTHER = "eu-central-1"; + private static final String AVRO = "{\\\"type\\\":\\\"record\\\",\\\"name\\\":\\\"User\\\",\\\"namespace\\\":\\\"x\\\"," + + "\\\"fields\\\":[{\\\"name\\\":\\\"id\\\",\\\"type\\\":\\\"long\\\"}]}"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aRegistryAndItsSchemaAreListedAndReachedOnlyInTheirRegion() { + String registry = "reg-" + UUID.randomUUID().toString().substring(0, 8); + String byName = "{\"RegistryId\":{\"RegistryName\":\"" + registry + "\"}}"; + String registryArn = call(HOME, "CreateRegistry", "{\"RegistryName\":\"" + registry + "\"}").statusCode(200) + .extract().path("RegistryArn"); + try { + ValidatableResponse schema = call(HOME, "CreateSchema", "{\"RegistryId\":{\"RegistryName\":\"" + registry + + "\"},\"SchemaName\":\"users\",\"DataFormat\":\"AVRO\",\"SchemaDefinition\":\"" + AVRO + "\"}") + .statusCode(200); + String schemaArn = schema.extract().path("SchemaArn"); + String versionId = schema.extract().path("SchemaVersionId"); + + call(OTHER, "ListRegistries", "{}").statusCode(200).body("Registries.RegistryName", not(hasItem(registry))); + notFound(call(OTHER, "GetRegistry", byName)); + notFound(call(OTHER, "GetRegistry", "{\"RegistryId\":{\"RegistryArn\":\"" + registryArn + "\"}}")); + notFound(call(OTHER, "ListSchemas", byName)); + notFound(call(OTHER, "GetSchema", "{\"SchemaId\":{\"SchemaArn\":\"" + schemaArn + "\"}}")); + notFound(call(OTHER, "GetSchemaVersion", "{\"SchemaVersionId\":\"" + versionId + "\"}")); + notFound(call(OTHER, "PutSchemaVersionMetadata", "{\"SchemaVersionId\":\"" + versionId + "\"," + + "\"MetadataKeyValue\":{\"MetadataKey\":\"owner\",\"MetadataValue\":\"alice\"}}")); + notFound(call(OTHER, "GetTags", "{\"ResourceArn\":\"" + registryArn + "\"}")); + notFound(call(OTHER, "DeleteRegistry", byName)); + + call(OTHER, "CreateRegistry", "{\"RegistryName\":\"" + registry + "\"}").statusCode(200) + .body("RegistryArn", startsWith("arn:aws:glue:" + OTHER + ":")); + call(OTHER, "DeleteRegistry", byName).statusCode(200); + + call(HOME, "ListRegistries", "{}").statusCode(200).body("Registries.RegistryName", hasItem(registry)); + call(HOME, "GetSchema", "{\"SchemaId\":{\"SchemaArn\":\"" + schemaArn + "\"}}").statusCode(200) + .body("SchemaName", equalTo("users")); + call(HOME, "GetSchemaVersion", "{\"SchemaVersionId\":\"" + versionId + "\"}").statusCode(200) + .body("SchemaArn", equalTo(schemaArn)); + } finally { + call(HOME, "DeleteRegistry", byName); + } + } + + private static ValidatableResponse call(String region, String action, String body) { + return given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSGlue." + action) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + region + "/glue/aws4_request") + .body(body) + .when().post("/").then(); + } + + private static void notFound(ValidatableResponse response) { + response.statusCode(400).body("__type", equalTo("EntityNotFoundException")); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryServiceTest.java b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryServiceTest.java index be4673ff37..01540b6e1f 100644 --- a/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryServiceTest.java +++ b/src/test/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryServiceTest.java @@ -141,7 +141,7 @@ class GlueSchemaRegistryServiceTest { assertEquals("default-registry", registry.getRegistryName()); assertEquals("AVAILABLE", registry.getStatus()); - assertEquals(1, service.listRegistries().size()); + assertEquals(1, service.listRegistries(REGION).size()); } @Test @@ -163,7 +163,7 @@ class GlueSchemaRegistryServiceTest { service.createRegistry("a", null, null, REGION); service.createRegistry("b", null, null, REGION); - List registries = service.listRegistries(); + List registries = service.listRegistries(REGION); assertEquals(2, registries.size()); } @@ -174,8 +174,8 @@ class GlueSchemaRegistryServiceTest { service.createRegistry("b", null, null, REGION); service.createRegistry("c", null, null, REGION); - GlueSchemaRegistryService.Page first = service.listRegistries(2, null); - GlueSchemaRegistryService.Page second = service.listRegistries(2, first.nextToken()); + GlueSchemaRegistryService.Page first = service.listRegistries(REGION, 2, null); + GlueSchemaRegistryService.Page second = service.listRegistries(REGION, 2, first.nextToken()); assertEquals(2, first.items().size()); assertEquals("2", first.nextToken()); @@ -186,7 +186,7 @@ class GlueSchemaRegistryServiceTest { @Test void listRegistriesEmptyByDefault() { - assertTrue(service.listRegistries().isEmpty()); + assertTrue(service.listRegistries(REGION).isEmpty()); } @Test @@ -218,7 +218,7 @@ class GlueSchemaRegistryServiceTest { service.createRegistry("r1", null, null, REGION); SchemaVersion first = service.createSchema(new RegistryId("r1", null), "users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).firstVersion(); - service.putSchemaVersionMetadata(first.getSchemaVersionId(), "team", "platform"); + service.putSchemaVersionMetadata(first.getSchemaVersionId(), "team", "platform", REGION); service.deleteRegistry(new RegistryId("r1", null), REGION); service.createRegistry("r1", null, null, REGION); @@ -228,7 +228,7 @@ class GlueSchemaRegistryServiceTest { service.getSchemaVersion(null, first.getSchemaVersionId(), null, false, REGION)); assertEquals("EntityNotFoundException", versionEx.getErrorCode()); AwsException metadataEx = assertThrows(AwsException.class, () -> - service.querySchemaVersionMetadata(first.getSchemaVersionId(), null)); + service.querySchemaVersionMetadata(first.getSchemaVersionId(), null, REGION)); assertEquals("EntityNotFoundException", metadataEx.getErrorCode()); } @@ -606,7 +606,7 @@ class GlueSchemaRegistryServiceTest { public Optional get(String key) { Optional schema = super.get(key); if (Thread.currentThread() == lookupThread.get() - && key.equals("reg:users") && paused.compareAndSet(false, true)) { + && key.equals(REGION + "::reg:users") && paused.compareAndSet(false, true)) { firstSchemaRead.countDown(); awaitRelease(finishLookup); } @@ -1097,32 +1097,32 @@ class GlueSchemaRegistryServiceTest { void putSchemaVersionMetadataStoresKeyValue() { String svId = firstVersionId(); - GlueSchemaRegistryService.MetadataPutResult r = service.putSchemaVersionMetadata(svId, "team", "platform"); + GlueSchemaRegistryService.MetadataPutResult r = service.putSchemaVersionMetadata(svId, "team", "platform", REGION); assertEquals("team", r.metadataKey()); assertEquals("platform", r.metadataValue()); - Map map = service.querySchemaVersionMetadata(svId, null); + Map map = service.querySchemaVersionMetadata(svId, null, REGION); assertEquals("platform", map.get("team").getMetadataValue()); } @Test void putSchemaVersionMetadataDuplicateKeyValueRejected() { String svId = firstVersionId(); - service.putSchemaVersionMetadata(svId, "team", "platform"); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION); AwsException ex = assertThrows(AwsException.class, () -> - service.putSchemaVersionMetadata(svId, "team", "platform")); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION)); assertEquals("AlreadyExistsException", ex.getErrorCode()); } @Test void putSchemaVersionMetadataSameKeyNewValueDemotesOld() { String svId = firstVersionId(); - service.putSchemaVersionMetadata(svId, "team", "platform"); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION); - service.putSchemaVersionMetadata(svId, "team", "data"); + service.putSchemaVersionMetadata(svId, "team", "data", REGION); - Map map = service.querySchemaVersionMetadata(svId, null); + Map map = service.querySchemaVersionMetadata(svId, null, REGION); assertEquals("data", map.get("team").getMetadataValue()); assertEquals(1, map.get("team").getOtherMetadataValueList().size()); assertEquals("platform", map.get("team").getOtherMetadataValueList().get(0).getMetadataValue()); @@ -1131,19 +1131,19 @@ class GlueSchemaRegistryServiceTest { @Test void putSchemaVersionMetadataForUnknownVersionThrows() { AwsException ex = assertThrows(AwsException.class, () -> - service.putSchemaVersionMetadata("does-not-exist", "team", "platform")); + service.putSchemaVersionMetadata("does-not-exist", "team", "platform", REGION)); assertEquals("EntityNotFoundException", ex.getErrorCode()); } @Test void removeSchemaVersionMetadataCurrentPromotesNext() { String svId = firstVersionId(); - service.putSchemaVersionMetadata(svId, "team", "platform"); - service.putSchemaVersionMetadata(svId, "team", "data"); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION); + service.putSchemaVersionMetadata(svId, "team", "data", REGION); - service.removeSchemaVersionMetadata(svId, "team", "data"); + service.removeSchemaVersionMetadata(svId, "team", "data", REGION); - Map map = service.querySchemaVersionMetadata(svId, null); + Map map = service.querySchemaVersionMetadata(svId, null, REGION); assertEquals("platform", map.get("team").getMetadataValue()); assertNull(map.get("team").getOtherMetadataValueList()); } @@ -1151,29 +1151,29 @@ class GlueSchemaRegistryServiceTest { @Test void removeSchemaVersionMetadataLastValueDeletesKey() { String svId = firstVersionId(); - service.putSchemaVersionMetadata(svId, "team", "platform"); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION); - service.removeSchemaVersionMetadata(svId, "team", "platform"); + service.removeSchemaVersionMetadata(svId, "team", "platform", REGION); - assertTrue(service.querySchemaVersionMetadata(svId, null).isEmpty()); + assertTrue(service.querySchemaVersionMetadata(svId, null, REGION).isEmpty()); } @Test void removeSchemaVersionMetadataNotFoundThrows() { String svId = firstVersionId(); AwsException ex = assertThrows(AwsException.class, () -> - service.removeSchemaVersionMetadata(svId, "missing", "x")); + service.removeSchemaVersionMetadata(svId, "missing", "x", REGION)); assertEquals("EntityNotFoundException", ex.getErrorCode()); } @Test void querySchemaVersionMetadataWithFilterReturnsSubset() { String svId = firstVersionId(); - service.putSchemaVersionMetadata(svId, "team", "platform"); - service.putSchemaVersionMetadata(svId, "owner", "alice"); + service.putSchemaVersionMetadata(svId, "team", "platform", REGION); + service.putSchemaVersionMetadata(svId, "owner", "alice", REGION); Map filtered = service.querySchemaVersionMetadata(svId, - List.of(new GlueSchemaRegistryService.MetadataKeyValueFilter("team", null))); + List.of(new GlueSchemaRegistryService.MetadataKeyValueFilter("team", null)), REGION); assertEquals(1, filtered.size()); assertTrue(filtered.containsKey("team")); @@ -1186,12 +1186,12 @@ class GlueSchemaRegistryServiceTest { "a", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).firstVersion(); service.registerSchemaVersion(new SchemaId("reg", "a", null), AVRO_V2_BACKWARD_OK, REGION); service.updateSchema(new SchemaId("reg", "a", null), null, null, 2L, REGION); - service.putSchemaVersionMetadata(first.getSchemaVersionId(), "team", "platform"); + service.putSchemaVersionMetadata(first.getSchemaVersionId(), "team", "platform", REGION); service.deleteSchemaVersions(new SchemaId("reg", "a", null), "1", REGION); AwsException ex = assertThrows(AwsException.class, () -> - service.querySchemaVersionMetadata(first.getSchemaVersionId(), null)); + service.querySchemaVersionMetadata(first.getSchemaVersionId(), null, REGION)); assertEquals("EntityNotFoundException", ex.getErrorCode()); } @@ -1199,9 +1199,9 @@ class GlueSchemaRegistryServiceTest { void tagAndGetTagsForRegistry() { Registry r = service.createRegistry("reg", null, null, REGION); - service.tagResource(r.getRegistryArn(), Map.of("env", "prod", "team", "platform")); + service.tagResource(r.getRegistryArn(), Map.of("env", "prod", "team", "platform"), REGION); - Map tags = service.getTags(r.getRegistryArn()); + Map tags = service.getTags(r.getRegistryArn(), REGION); assertEquals(2, tags.size()); assertEquals("prod", tags.get("env")); } @@ -1212,20 +1212,20 @@ class GlueSchemaRegistryServiceTest { Schema schema = service.createSchema(new RegistryId("reg", null), "a", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).schema(); - service.tagResource(schema.getSchemaArn(), Map.of("owner", "alice")); + service.tagResource(schema.getSchemaArn(), Map.of("owner", "alice"), REGION); - Map tags = service.getTags(schema.getSchemaArn()); + Map tags = service.getTags(schema.getSchemaArn(), REGION); assertEquals("alice", tags.get("owner")); } @Test void untagResourceRemovesKeys() { Registry r = service.createRegistry("reg", null, null, REGION); - service.tagResource(r.getRegistryArn(), Map.of("env", "prod", "team", "platform")); + service.tagResource(r.getRegistryArn(), Map.of("env", "prod", "team", "platform"), REGION); - service.untagResource(r.getRegistryArn(), List.of("env")); + service.untagResource(r.getRegistryArn(), List.of("env"), REGION); - Map tags = service.getTags(r.getRegistryArn()); + Map tags = service.getTags(r.getRegistryArn(), REGION); assertEquals(1, tags.size()); assertTrue(tags.containsKey("team")); } @@ -1233,7 +1233,7 @@ class GlueSchemaRegistryServiceTest { @Test void tagResourceWithMalformedArnThrows() { AwsException ex = assertThrows(AwsException.class, () -> - service.tagResource("not-an-arn", Map.of("a", "b"))); + service.tagResource("not-an-arn", Map.of("a", "b"), REGION)); assertEquals("InvalidInputException", ex.getErrorCode()); } @@ -1242,7 +1242,7 @@ class GlueSchemaRegistryServiceTest { AwsException ex = assertThrows(AwsException.class, () -> service.tagResource( "arn:aws:glue:us-east-1:" + ACCOUNT_ID + ":registry/missing", - Map.of("a", "b"))); + Map.of("a", "b"), REGION)); assertEquals("EntityNotFoundException", ex.getErrorCode()); } }