Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elasticache): restore groups and clusters of every account (#5244)
Allen Sanborn05e1bebe1e66
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex ae159a70c3..56eb0f1ac5 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -5,6 +5,8 @@ import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;import software.amazon.awssdk.core.SdkBytes;import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;import software.amazon.awssdk.core.exception.SdkClientException;+import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy;+import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;import software.amazon.awssdk.endpoints.Endpoint;import software.amazon.awssdk.http.Protocol;import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;@@ -226,6 +228,23 @@ public final class TestFixtures {await(condition, resourceName, expected, timeoutNanos, pollMillis, () -> "");}+ /**+ * A waiter override that bounds the wait by {@code timeout} and, against Floci, checks once a+ * second. A waiter otherwise sleeps out the published AWS cadence between checks, from 6+ * seconds for ECS {@code TasksStopped} and 15 for {@code ServicesStable} to 30 for the+ * CloudFormation and EKS waiters, where Floci has usually settled within one. The attempt limit+ * grows to match, since the published one is sized for the published delay. Against real AWS+ * the waiter keeps its own cadence.+ */+ public static WaiterOverrideConfiguration waiterOverride(Duration timeout) {+ WaiterOverrideConfiguration.Builder override = WaiterOverrideConfiguration.builder().waitTimeout(timeout);+ if (!isRealAws()) {+ override.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))+ .maxAttempts((int) timeout.toSeconds() + 1);+ }+ return override.build();+ }+/** Polls a condition and appends lazily produced diagnostics when the wait expires. */public static void await(BooleanSupplier condition, String resourceName, String expected,long timeoutNanos, long pollMillis, Supplier<String> timeoutDetails)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcsServiceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcsServiceTest.javaindex 4554dd5260..d1e9340ce5 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcsServiceTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEcsServiceTest.java@@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Test;import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;import software.amazon.awssdk.services.cloudformation.model.Parameter;import software.amazon.awssdk.services.cloudformation.model.StackStatus;import software.amazon.awssdk.services.ec2.Ec2Client;@@ -91,8 +92,8 @@ class CloudFormationEcsServiceTest {void cleanup() {if (stackCreated) {cfn.deleteStack(r -> r.stackName(stackName));- cfn.waiter().waitUntilStackDeleteComplete(r -> r.stackName(stackName),- w -> w.waitTimeout(Duration.ofMinutes(5)));+ cfn.waiter().waitUntilStackDeleteComplete(DescribeStacksRequest.builder().stackName(stackName).build(),+ TestFixtures.waiterOverride(Duration.ofMinutes(5)));}}@@ -109,8 +110,9 @@ class CloudFormationEcsServiceTest {cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameter("Name", stackName), parameter("Subnet", defaultSubnet())));stackCreated = true;- StackStatus status = cfn.waiter().waitUntilStackCreateComplete(r -> r.stackName(stackName),- w -> w.waitTimeout(Duration.ofMinutes(10)))+ StackStatus status = cfn.waiter().waitUntilStackCreateComplete(+ DescribeStacksRequest.builder().stackName(stackName).build(),+ TestFixtures.waiterOverride(Duration.ofMinutes(10))).matched().response().orElseThrow().stacks().get(0).stackStatus();assertThat(status).isEqualTo(StackStatus.CREATE_COMPLETE);diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.javaindex e2db81d7c1..5e0a516e8b 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java@@ -4,7 +4,6 @@ import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.Arguments;import org.junit.jupiter.params.provider.MethodSource;-import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;import software.amazon.awssdk.services.ec2.Ec2Client;import software.amazon.awssdk.services.ecs.EcsClient;import software.amazon.awssdk.services.ecs.model.CapacityProviderStrategyItem;@@ -59,7 +58,10 @@ class EcsCapacityProviderServiceTest {.cpu("256").memory("512").containerDefinitions(ContainerDefinition.builder().name("app").image("alpine:3").memory(128)- .command("sleep", "3600").essential(true).build())).taskDefinition();+ // PID 1 gets no default SIGTERM handler, so a bare "sleep 3600" sits out+ // the whole stopTimeout grace period for each task deleteService stops.+ .command("sh", "-c", "trap 'exit 0' TERM; sleep 3600 & wait")+ .essential(true).build())).taskDefinition();try {ecs.createService(request -> request.cluster(name).serviceName(name).taskDefinition(definition.taskDefinitionArn()).desiredCount(2)@@ -83,8 +85,7 @@ class EcsCapacityProviderServiceTest {List<CapacityProviderStrategyItem> strategy,Map<String, Long> expected) {DescribeServicesRequest describe = DescribeServicesRequest.builder().cluster(name).services(name).build();- assertThat(ecs.waiter().waitUntilServicesStable(describe,- WaiterOverrideConfiguration.builder().waitTimeout(Duration.ofSeconds(30)).build())+ assertThat(ecs.waiter().waitUntilServicesStable(describe, TestFixtures.waiterOverride(Duration.ofSeconds(30))).matched().response()).isPresent();int count = expected.values().stream().mapToInt(Long::intValue).sum();diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsEphemeralVolumeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsEphemeralVolumeTest.javaindex 2bcfab9f52..3d30a6565e 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsEphemeralVolumeTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsEphemeralVolumeTest.java@@ -3,7 +3,6 @@ package com.floci.test;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;-import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;import software.amazon.awssdk.services.ec2.Ec2Client;import software.amazon.awssdk.services.ecs.EcsClient;import software.amazon.awssdk.services.ecs.model.Compatibility;@@ -86,7 +85,7 @@ class EcsEphemeralVolumeTest {DescribeTasksRequest describe = DescribeTasksRequest.builder().cluster(name).tasks(task.taskArn()).build();assertThat(ecs.waiter().waitUntilTasksStopped(describe,- WaiterOverrideConfiguration.builder().waitTimeout(Duration.ofSeconds(30)).build())+ TestFixtures.waiterOverride(Duration.ofSeconds(30))).matched().response()).isPresent();Task stopped = ecs.describeTasks(describe).tasks().get(0);assertThat(stopped.containers()).hasSize(2).allSatisfy(container -> {diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsOneShotTaskLifecycleTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsOneShotTaskLifecycleTest.javaindex 6cb99b1596..3d94648389 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsOneShotTaskLifecycleTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsOneShotTaskLifecycleTest.java@@ -1,7 +1,6 @@package com.floci.test;import org.junit.jupiter.api.*;-import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;import software.amazon.awssdk.core.waiters.WaiterResponse;import software.amazon.awssdk.services.ecs.EcsClient;import software.amazon.awssdk.services.ecs.model.*;@@ -123,19 +122,15 @@ class EcsOneShotTaskLifecycleTest {@Order(2)@DisplayName("WaitTasksStopped - transitions to STOPPED within 60 s")void waitForTaskStopped() {- // The container runs for ~2 s; the reconciler fires every 5 s; the waiter- // polls every 6 s. Allow 60 s total to be CI-safe.- WaiterOverrideConfiguration overrides = WaiterOverrideConfiguration.builder()- .waitTimeout(Duration.ofSeconds(60))- .build();-+ // The container runs for ~2 s and the reconciler fires every 5 s. Allow 60 s total to be+ // CI-safe.try (EcsWaiter waiter = EcsWaiter.builder().client(ecs).build()) {WaiterResponse<DescribeTasksResponse> response = waiter.waitUntilTasksStopped(DescribeTasksRequest.builder().cluster(clusterName).tasks(taskArn).build(),- overrides);+ TestFixtures.waiterOverride(Duration.ofSeconds(60)));assertThat(response.matched().response()).isPresent();Task task = response.matched().response().get().tasks().get(0);@@ -207,7 +202,9 @@ class EcsOneShotTaskLifecycleTest {.containerDefinitions(ContainerDefinition.builder().name("main").image("busybox:latest")- .command("sh", "-c", "sleep 300")+ // PID 1 gets no default SIGTERM handler, so a bare "sleep 300" sits out the+ // whole stopTimeout grace period when the test stops it.+ .command("sh", "-c", "trap 'exit 0' TERM; sleep 300 & wait").essential(true).cpu(256).memory(64)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.javaindex 3a84ee6dc0..d2cf346fe8 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java@@ -1,7 +1,6 @@package com.floci.test;import org.junit.jupiter.api.*;-import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;import software.amazon.awssdk.core.waiters.WaiterResponse;import software.amazon.awssdk.services.ecs.EcsClient;import software.amazon.awssdk.services.ecs.model.*;@@ -853,9 +852,7 @@ class EcsTests {.cluster(clusterName).services(serviceName).build(),- WaiterOverrideConfiguration.builder()- .waitTimeout(Duration.ofSeconds(30))- .build());+ TestFixtures.waiterOverride(Duration.ofSeconds(30)));assertThat(response.matched().response()).isPresent();assertThat(response.matched().response().get().services().get(0).deployments()).hasSize(1);diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksAccessEntryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksAccessEntryTest.javaindex 3a9a12a785..259d763999 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksAccessEntryTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksAccessEntryTest.java@@ -67,8 +67,8 @@ class EksAccessEntryTest {.bootstrapClusterCreatorAdminPermissions(false).build()));try (EksWaiter waiter = eks.waiter()) {WaiterResponse<DescribeClusterResponse> result = waiter.waitUntilClusterActive(- request -> request.name(name),- configuration -> configuration.waitTimeout(Duration.ofMinutes(3)));+ DescribeClusterRequest.builder().name(name).build(),+ TestFixtures.waiterOverride(Duration.ofMinutes(3)));assertThat(result.matched().response()).withFailMessage("Cluster %s did not become ACTIVE: %s", name, result.matched().exception()).isPresent();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.javaindex b533cccf53..141e774b57 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java@@ -73,6 +73,21 @@ public final class SigV4RequestValidator {*/public boolean validate(String rawQuery, String canonicalHostHeaderValue, String identityParamName,boolean identityRequired, String expectedIdentityValue, String logLabel) {+ return validate(rawQuery, canonicalHostHeaderValue, identityParamName, identityRequired,+ expectedIdentityValue, logLabel, null);+ }++ /**+ * As above, for a caller that knows which account owns the target: a long-term access key is+ * accepted only when that account holds it. A proxy checks tokens on its own thread, outside+ * any request, where the plain lookup sees the default account rather than the owner's.+ *+ * @param ownerAccountId the account that owns the target, or null to look the key up in the+ * calling request's account+ */+ public boolean validate(String rawQuery, String canonicalHostHeaderValue, String identityParamName,+ boolean identityRequired, String expectedIdentityValue, String logLabel,+ String ownerAccountId) {try {List<QueryParameter> parameters = decodeQuery(rawQuery);String action = findParam(parameters, "Action");@@ -116,8 +131,8 @@ public final class SigV4RequestValidator {if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {secretKey = LEGACY_SECRET_KEY;} else {- Optional<String> registeredSecretKey = iamService.findSecretKey(- accessKeyId, findParam(parameters, "X-Amz-Security-Token"));+ Optional<String> registeredSecretKey = registeredSecretKey(+ accessKeyId, findParam(parameters, "X-Amz-Security-Token"), ownerAccountId);if (registeredSecretKey.isEmpty()) {LOG.debugv("{0} references unregistered access key={1}", logLabel, sanitizeForLog(accessKeyId));return false;@@ -153,6 +168,19 @@ public final class SigV4RequestValidator {}}+ /**+ * A temporary key's owner is null: its session is found whichever account issued it, as+ * {@link IamService#findSecretKey(String, String)} finds it.+ */+ private Optional<String> registeredSecretKey(String accessKeyId, String sessionToken, String ownerAccountId) {+ if (ownerAccountId == null) {+ return iamService.findSecretKey(accessKeyId, sessionToken);+ }+ return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken)+ .filter(key -> key.accountId() == null || ownerAccountId.equals(key.accountId()))+ .map(IamService.OwnedSecretKey::secretAccessKey);+ }+private record QueryParameter(String name, String value) {}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.javaindex a2d38b6ea7..b0bd92a45f 100644--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.resource.ExplorerResource;import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend.AccountEntry;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ec2.Ec2Service;@@ -69,7 +70,7 @@ public class ElastiCacheService implements ResourceProvider {private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);- private final StorageBackend<String, ReplicationGroup> groups;+ private final AccountAwareStorageBackend<ReplicationGroup> groups;private final AccountAwareStorageBackend<CacheCluster> cacheClusters;/*** The Memcached cluster store, the one {@link ElastiCacheMemcachedService} writes.@@ -107,6 +108,15 @@ public class ElastiCacheService implements ResourceProvider {* the two kinds cannot collide here either.*/private final Set<String> recordsHoldingTheirPort = ConcurrentHashMap.newKeySet();++ /**+ * A record's entry in {@link #recordsHoldingTheirPort}: its owning account, then its id. Ids+ * are unique only within an account, so two accounts' records of the same name each hold+ * their own port and a delete in one must not release the other's.+ */+ private static String recordKey(String accountId, String id) {+ return accountId + "/" + id;+ }private final ConcurrentHashMap<String, Object> parameterGroupLocks = new ConcurrentHashMap<>();/*** Parameter groups claimed by in-flight creates, keyed by account and name (see@@ -366,14 +376,14 @@ public class ElastiCacheService implements ResourceProvider {if (handle != null) {proxyManager.startProxy(groupId, authMode, proxyPort,handle.getHost(), handle.getPort(),- groupAuthenticator(groupId));+ groupAuthenticator(groups.accountId(), groupId));} else {LOG.warnv("Replication group {0} created without a backing cache container: no "+ "Docker daemon is reachable. Metadata operations work; connections to "+ "the cache do not until a daemon appears.", groupId);}// Under the same monitor as the put, for the reason given on recordsHoldingTheirPort.- recordsHoldingTheirPort.add(groupId);+ recordsHoldingTheirPort.add(recordKey(groups.accountId(), groupId));}LOG.infov("Replication group {0} created, endpoint={1}:{2}", groupId, endpointHost, String.valueOf(proxyPort));@@ -444,7 +454,7 @@ public class ElastiCacheService implements ResourceProvider {ElastiCacheContainerHandle handle = handles.get(i);proxyManager.startProxy(node.getMemberClusterId(), authMode, node.getProxyPort(),handle.getHost(), handle.getPort(),- groupAuthenticator(groupId));+ groupAuthenticator(groups.accountId(), groupId));startedProxyKeys.add(node.getMemberClusterId());}@@ -649,26 +659,38 @@ public class ElastiCacheService implements ResourceProvider {* or to the failure status their store models as their restoration finishes.*/public CompletableFuture<Void> restorePersistedRuntime() {- List<ReplicationGroup> clusterModeToRestore = new ArrayList<>();- List<ReplicationGroup> singleNodeToRestore = new ArrayList<>();- List<CacheCluster> cacheClustersToRestore = new ArrayList<>();- for (ReplicationGroup group : groups.scan(k -> true)) {+ // Every account's records, each written back under the account that owns it: there is no+ // request context at boot, so the plain scan and put see and write the default account only,+ // leaving other accounts' groups without a data plane and their ports free for the next create.+ // Records stored before account prefixing are moved under the default account first, as+ // get() would on first read. Restored in place, they would come back on every boot and+ // outlive a delete, which only removes the prefixed key.+ String defaultAccountId = regionResolver.getDefaultAccountId();+ groups.migrateLegacyEntries(defaultAccountId, key -> !key.contains("/"),+ ReplicationGroup::getReplicationGroupId, group -> true);+ cacheClusters.migrateLegacyEntries(defaultAccountId, key -> !key.contains("/"),+ CacheCluster::getCacheClusterId, cluster -> true);+ List<AccountEntry<ReplicationGroup>> clusterModeToRestore = new ArrayList<>();+ List<AccountEntry<ReplicationGroup>> singleNodeToRestore = new ArrayList<>();+ List<AccountEntry<CacheCluster>> cacheClustersToRestore = new ArrayList<>();+ for (AccountEntry<ReplicationGroup> entry : groups.scanAllAccountEntries(k -> true)) {+ ReplicationGroup group = entry.value();if (group.getStatus() == ReplicationGroupStatus.DELETING) {continue;}if (group.isClusterEnabled() && !group.getClusterNodes().isEmpty()) {- reserveClusterModeGroup(group, clusterModeToRestore);+ reserveClusterModeGroup(entry, clusterModeToRestore);} else {- reserveSingleNodeGroup(group, singleNodeToRestore);+ reserveSingleNodeGroup(entry, singleNodeToRestore);}- groups.put(group.getReplicationGroupId(), group);+ groups.putForAccount(entry.accountId(), entry.key(), group);}- for (CacheCluster cluster : runtimeCacheClusters()) {- if (cluster.getCacheClusterStatus() == CacheClusterStatus.DELETING) {+ for (AccountEntry<CacheCluster> entry : cacheClusters.scanAllAccountEntries(k -> true)) {+ if (entry.value().getCacheClusterStatus() == CacheClusterStatus.DELETING) {continue;}- reserveCacheCluster(cluster, cacheClustersToRestore);- putRuntimeCluster(cluster);+ reserveCacheCluster(entry, cacheClustersToRestore);+ cacheClusters.putForAccount(entry.accountId(), entry.key(), entry.value());}if (clusterModeToRestore.isEmpty() && singleNodeToRestore.isEmpty()&& cacheClustersToRestore.isEmpty()) {@@ -685,7 +707,9 @@ public class ElastiCacheService implements ResourceProvider {});}- private void reserveClusterModeGroup(ReplicationGroup group, List<ReplicationGroup> toRestore) {+ private void reserveClusterModeGroup(AccountEntry<ReplicationGroup> entry,+ List<AccountEntry<ReplicationGroup>> toRestore) {+ ReplicationGroup group = entry.value();List<Integer> reserved = new ArrayList<>();try {for (ClusterNode node : group.getClusterNodes()) {@@ -693,7 +717,7 @@ public class ElastiCacheService implements ResourceProvider {reserved.add(node.getProxyPort());}group.setStatus(ReplicationGroupStatus.CREATING);- toRestore.add(group);+ toRestore.add(entry);} catch (RuntimeException e) {reserved.forEach(this::releaseProxyPort);group.setStatus(ReplicationGroupStatus.CREATE_FAILED);@@ -709,7 +733,9 @@ public class ElastiCacheService implements ResourceProvider {* configuration rather than replayed from the record, so a group restored under a changed* {@code FLOCI_HOSTNAME} advertises the name this process actually answers to.*/- private void reserveSingleNodeGroup(ReplicationGroup group, List<ReplicationGroup> toRestore) {+ private void reserveSingleNodeGroup(AccountEntry<ReplicationGroup> entry,+ List<AccountEntry<ReplicationGroup>> toRestore) {+ ReplicationGroup group = entry.value();try {group.setProxyPort(reserveOrAllocateProxyPort(group.getProxyPort()));group.setConfigurationEndpoint(new Endpoint(resolveEndpointHost(), group.getProxyPort()));@@ -717,8 +743,8 @@ public class ElastiCacheService implements ResourceProvider {// The reservation above succeeded, so this process owns the port whether or not it is// the one the record came back with. Without this the delete path would decline to// free a port nothing else holds, and the reservation would outlive the group.- recordsHoldingTheirPort.add(group.getReplicationGroupId());- toRestore.add(group);+ recordsHoldingTheirPort.add(recordKey(entry.accountId(), group.getReplicationGroupId()));+ toRestore.add(entry);} catch (RuntimeException e) {group.setStatus(ReplicationGroupStatus.CREATE_FAILED);group.setConfigurationEndpoint(null);@@ -737,15 +763,16 @@ public class ElastiCacheService implements ResourceProvider {* AWS models on {@code CacheCluster}; a replication group reports {@code create-failed},* which is the value its own model carries.*/- private void reserveCacheCluster(CacheCluster cluster, List<CacheCluster> toRestore) {+ private void reserveCacheCluster(AccountEntry<CacheCluster> entry, List<AccountEntry<CacheCluster>> toRestore) {+ CacheCluster cluster = entry.value();String clusterId = cluster.getCacheClusterId();try {Endpoint persisted = cluster.getConfigurationEndpoint();int proxyPort = reserveOrAllocateProxyPort(persisted != null ? persisted.port() : 0);cluster.setConfigurationEndpoint(new Endpoint(resolveEndpointHost(), proxyPort));cluster.setCacheClusterStatus(CacheClusterStatus.CREATING);- recordsHoldingTheirPort.add(clusterId);- toRestore.add(cluster);+ recordsHoldingTheirPort.add(recordKey(entry.accountId(), clusterId));+ toRestore.add(entry);} catch (RuntimeException e) {cluster.setCacheClusterStatus(CacheClusterStatus.RESTORE_FAILED);cluster.setConfigurationEndpoint(null);@@ -772,13 +799,15 @@ public class ElastiCacheService implements ResourceProvider {* monitor and re-reads the record, because a delete taken while the container started has* already removed it.*/- private void restoreCacheCluster(CacheCluster cluster) {+ private void restoreCacheCluster(AccountEntry<CacheCluster> entry) {+ String accountId = entry.accountId();+ CacheCluster cluster = entry.value();String clusterId = cluster.getCacheClusterId();String image = config.services().elasticache().defaultImage();try {ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, regionOf(cluster.getArn()));synchronized (lockFor("cc:" + clusterId)) {- if (cacheClusterRestoreTargetLost(cluster)) {+ if (cacheClusterRestoreTargetLost(accountId, clusterId)) {abandonRestoredCacheClusterContainer(clusterId, handle);return;}@@ -786,7 +815,7 @@ public class ElastiCacheService implements ResourceProvider {cluster.setContainerId(handle.getContainerId());cluster.setContainerHost(handle.getHost());cluster.setContainerPort(handle.getPort());- startCacheClusterProxy(cluster, handle);+ startCacheClusterProxy(accountId, cluster, handle);} else {// Cleared rather than left alone: whatever the record carried describes a// container from the previous process, and nothing must read it as live.@@ -798,13 +827,13 @@ public class ElastiCacheService implements ResourceProvider {+ "the cache do not until a daemon appears.", clusterId);}cluster.setCacheClusterStatus(CacheClusterStatus.AVAILABLE);- putRuntimeCluster(cluster);+ cacheClusters.putForAccount(accountId, clusterId, cluster);LOG.infov("Restored cache cluster {0}, endpoint={1}:{2}", clusterId,cluster.getConfigurationEndpoint().address(),String.valueOf(cluster.getConfigurationEndpoint().port()));}} catch (RuntimeException e) {- failCacheClusterRestore(cluster, e);+ failCacheClusterRestore(accountId, cluster, e);}}@@ -813,8 +842,8 @@ public class ElastiCacheService implements ResourceProvider {* Callers must hold the cluster's monitor, for the reason given on* {@link #restoreTargetLost}.*/- private boolean cacheClusterRestoreTargetLost(CacheCluster cluster) {- return runtimeCluster(cluster.getCacheClusterId(), cluster.getOwnerAccountId())+ private boolean cacheClusterRestoreTargetLost(String accountId, String clusterId) {+ return cacheClusters.getForAccount(accountId, clusterId).map(current -> current.getCacheClusterStatus() == CacheClusterStatus.DELETING).orElse(true);}@@ -848,7 +877,7 @@ public class ElastiCacheService implements ResourceProvider {* <p>A cluster deleted while the failed attempt ran gets the teardown but no write-back and* no port release, for the reasons {@link #failSingleNodeRestore} gives.*/- private void failCacheClusterRestore(CacheCluster cluster, RuntimeException cause) {+ private void failCacheClusterRestore(String accountId, CacheCluster cluster, RuntimeException cause) {String clusterId = cluster.getCacheClusterId();synchronized (lockFor("cc:" + clusterId)) {try {@@ -861,13 +890,13 @@ public class ElastiCacheService implements ResourceProvider {} catch (RuntimeException e) {LOG.warnv("Error stopping container for cache cluster {0}: {1}", clusterId, e.getMessage());}- if (cacheClusterRestoreTargetLost(cluster)) {+ if (cacheClusterRestoreTargetLost(accountId, clusterId)) {LOG.warnv(cause, "Failed to restore cache cluster {0}, which was deleted while it "+ "was being restored", clusterId);return;}Endpoint endpoint = cluster.getConfigurationEndpoint();- if (endpoint != null && recordsHoldingTheirPort.remove(clusterId)) {+ if (endpoint != null && recordsHoldingTheirPort.remove(recordKey(accountId, clusterId))) {releaseProxyPort(endpoint.port());}cluster.setContainerId(null);@@ -876,7 +905,7 @@ public class ElastiCacheService implements ResourceProvider {cluster.setCacheClusterStatus(CacheClusterStatus.RESTORE_FAILED);cluster.setConfigurationEndpoint(null);try {- putRuntimeCluster(cluster);+ cacheClusters.putForAccount(accountId, clusterId, cluster);} catch (RuntimeException persistFailure) {cause.addSuppressed(persistFailure);}@@ -899,13 +928,15 @@ public class ElastiCacheService implements ResourceProvider {* takes the monitor and re-reads the record, because a delete taken while the container* started has already removed it.*/- private void restoreSingleNodeGroup(ReplicationGroup group) {+ private void restoreSingleNodeGroup(AccountEntry<ReplicationGroup> entry) {+ String accountId = entry.accountId();+ ReplicationGroup group = entry.value();String groupId = group.getReplicationGroupId();String image = config.services().elasticache().defaultImage();try {ElastiCacheContainerHandle handle = containerManager.tryStart(groupId, image, regionOf(group.getArn()));synchronized (lockFor("rg:" + groupId)) {- if (restoreTargetLost(groupId)) {+ if (restoreTargetLost(accountId, groupId)) {abandonRestoredContainer(groupId, handle);return;}@@ -915,7 +946,7 @@ public class ElastiCacheService implements ResourceProvider {group.setContainerPort(handle.getPort());proxyManager.startProxy(groupId, group.getAuthMode(), group.getProxyPort(),handle.getHost(), handle.getPort(),- groupAuthenticator(groupId));+ groupAuthenticator(accountId, groupId));} else {// Cleared rather than left alone: whatever the record carried describes a// container from the previous process, and nothing must read it as live.@@ -927,13 +958,13 @@ public class ElastiCacheService implements ResourceProvider {+ "the cache do not until a daemon appears.", groupId);}group.setStatus(ReplicationGroupStatus.AVAILABLE);- groups.put(groupId, group);+ groups.putForAccount(accountId, groupId, group);LOG.infov("Restored replication group {0}, endpoint={1}:{2}", groupId,group.getConfigurationEndpoint().address(),String.valueOf(group.getProxyPort()));}} catch (RuntimeException e) {- failSingleNodeRestore(group, e);+ failSingleNodeRestore(accountId, group, e);}}@@ -944,8 +975,8 @@ public class ElastiCacheService implements ResourceProvider {* group the caller was told had been deleted, as {@code available}, with a fresh container* behind it.*/- private boolean restoreTargetLost(String groupId) {- return groups.get(groupId)+ private boolean restoreTargetLost(String accountId, String groupId) {+ return groups.getForAccount(accountId, groupId).map(current -> current.getStatus() == ReplicationGroupStatus.DELETING).orElse(true);}@@ -979,7 +1010,7 @@ public class ElastiCacheService implements ResourceProvider {* port release: reporting {@code create-failed} would put a deleted group back, and the* delete released the port itself.*/- private void failSingleNodeRestore(ReplicationGroup group, RuntimeException cause) {+ private void failSingleNodeRestore(String accountId, ReplicationGroup group, RuntimeException cause) {String groupId = group.getReplicationGroupId();synchronized (lockFor("rg:" + groupId)) {try {@@ -992,14 +1023,14 @@ public class ElastiCacheService implements ResourceProvider {} catch (RuntimeException e) {LOG.warnv("Error stopping container for replication group {0}: {1}", groupId, e.getMessage());}- if (restoreTargetLost(groupId)) {+ if (restoreTargetLost(accountId, groupId)) {LOG.warnv(cause, "Failed to restore replication group {0}, which was deleted while "+ "it was being restored", groupId);return;}// Dropped from the holders as it is released, so the delete of a failed group does// not free the port a second time and hand a live record's port to the next create.- if (recordsHoldingTheirPort.remove(groupId)) {+ if (recordsHoldingTheirPort.remove(recordKey(accountId, groupId))) {releaseProxyPort(group.getProxyPort());}group.setContainerId(null);@@ -1008,7 +1039,7 @@ public class ElastiCacheService implements ResourceProvider {group.setStatus(ReplicationGroupStatus.CREATE_FAILED);group.setConfigurationEndpoint(null);try {- groups.put(groupId, group);+ groups.putForAccount(accountId, groupId, group);} catch (RuntimeException persistFailure) {cause.addSuppressed(persistFailure);}@@ -1022,7 +1053,9 @@ public class ElastiCacheService implements ResourceProvider {* only the write-back takes it, so a delete that ran in the meantime is seen before the* group is put back.*/- private void restoreClusterModeGroup(ReplicationGroup group) {+ private void restoreClusterModeGroup(AccountEntry<ReplicationGroup> entry) {+ String accountId = entry.accountId();+ ReplicationGroup group = entry.value();String groupId = group.getReplicationGroupId();String image = config.services().elasticache().defaultImage();String endpointHost = resolveClusterAnnounceHost();@@ -1054,7 +1087,7 @@ public class ElastiCacheService implements ResourceProvider {clusterFormation.form(groupId, formationNodes, group.getNumNodeGroups());synchronized (lockFor("rg:" + groupId)) {- if (restoreTargetLost(groupId)) {+ if (restoreTargetLost(accountId, groupId)) {// No ports: the delete that removed the record released every one of them.rollbackClusterModeGroup(groupId, startedProxyKeys, handles, inFlightMemberId,List.of());@@ -1067,19 +1100,19 @@ public class ElastiCacheService implements ResourceProvider {ElastiCacheContainerHandle handle = handles.get(i);proxyManager.startProxy(node.getMemberClusterId(), group.getAuthMode(), node.getProxyPort(),handle.getHost(), handle.getPort(),- groupAuthenticator(groupId));+ groupAuthenticator(accountId, groupId));startedProxyKeys.add(node.getMemberClusterId());}group.setConfigurationEndpoint(new Endpoint(endpointHost, nodes.getFirst().getProxyPort()));group.setStatus(ReplicationGroupStatus.AVAILABLE);- groups.put(groupId, group);+ groups.putForAccount(accountId, groupId, group);LOG.infov("Restored cluster-mode replication group {0}: {1} node(s), configuration endpoint={2}:{3}",groupId, String.valueOf(nodes.size()), endpointHost,String.valueOf(group.getConfigurationEndpoint().port()));}} catch (RuntimeException e) {- failClusterModeRestore(group, startedProxyKeys, handles, inFlightMemberId, reservedPorts, e);+ failClusterModeRestore(accountId, group, startedProxyKeys, handles, inFlightMemberId, reservedPorts, e);}}@@ -1089,13 +1122,13 @@ public class ElastiCacheService implements ResourceProvider {* endpoint, unless a delete removed it while the attempt ran. In that case the rollback still* runs but the ports are left to the delete that released them, and nothing is written back.*/- private void failClusterModeRestore(ReplicationGroup group, List<String> startedProxyKeys,+ private void failClusterModeRestore(String accountId, ReplicationGroup group, List<String> startedProxyKeys,List<ElastiCacheContainerHandle> handles,String inFlightMemberId, Collection<Integer> reservedPorts,RuntimeException cause) {String groupId = group.getReplicationGroupId();synchronized (lockFor("rg:" + groupId)) {- boolean lost = restoreTargetLost(groupId);+ boolean lost = restoreTargetLost(accountId, groupId);rollbackClusterModeGroup(groupId, startedProxyKeys, handles, inFlightMemberId,lost ? List.of() : reservedPorts);if (lost) {@@ -1111,7 +1144,7 @@ public class ElastiCacheService implements ResourceProvider {group.setStatus(ReplicationGroupStatus.CREATE_FAILED);group.setConfigurationEndpoint(null);try {- groups.put(groupId, group);+ groups.putForAccount(accountId, groupId, group);} catch (RuntimeException persistFailure) {cause.addSuppressed(persistFailure);}@@ -1138,7 +1171,7 @@ public class ElastiCacheService implements ResourceProvider {LOG.warnv("Error stopping container for replication group {0}: {1}", groupId, e.getMessage());} finally {groups.delete(groupId);- recordsHoldingTheirPort.remove(groupId);+ recordsHoldingTheirPort.remove(recordKey(groups.accountId(), groupId));releaseProxyPort(proxyPort);}}@@ -1194,7 +1227,7 @@ public class ElastiCacheService implements ResourceProvider {// Only a port this process reserved for this record, as on the cluster path: a// restored group whose port was already taken advertises one it does not own.- if (recordsHoldingTheirPort.remove(groupId)) {+ if (recordsHoldingTheirPort.remove(recordKey(groups.accountId(), groupId))) {releaseProxyPort(group.getProxyPort());}}@@ -1412,10 +1445,13 @@ public class ElastiCacheService implements ResourceProvider {cluster.setContainerPort(handle.getPort());}+ // Resolved here, inside the request: the proxy calls the validator on its own thread,+ // where the store's implicit account is the default one rather than the owner's.+ String ownerAccountId = cacheClusters.accountId();synchronized (lockFor("cc:" + clusterId)) {cacheClusters.put(clusterId, cluster);if (handle != null) {- startCacheClusterProxy(cluster, handle);+ startCacheClusterProxy(ownerAccountId, cluster, handle);} else {LOG.warnv("Cache cluster {0} created without a backing cache container: no "+ "Docker daemon is reachable. Metadata operations work; connections to "@@ -1423,7 +1459,7 @@ public class ElastiCacheService implements ResourceProvider {}// Under the same monitor as the put: a delete slipping into the gap would find// no claim on the port and leave the reservation behind for good.- recordsHoldingTheirPort.add(clusterId);+ recordsHoldingTheirPort.add(recordKey(ownerAccountId, clusterId));}LOG.infov("Cache cluster {0} created, endpoint={1}:{2}", clusterId,@@ -1483,7 +1519,7 @@ public class ElastiCacheService implements ResourceProvider {LOG.warnv("Error stopping container for cache cluster {0}: {1}", clusterId, e.getMessage());} finally {cacheClusters.delete(clusterId);- recordsHoldingTheirPort.remove(clusterId);+ recordsHoldingTheirPort.remove(recordKey(cacheClusters.accountId(), clusterId));releaseProxyPort(proxyPort);}}@@ -1531,7 +1567,8 @@ public class ElastiCacheService implements ResourceProvider {// Only a port this process reserved for this record: a restored cluster whose port// was already taken advertises one it does not own, and freeing it would hand the// holder's port to the next create.- if (cluster.getConfigurationEndpoint() != null && recordsHoldingTheirPort.remove(clusterId)) {+ if (cluster.getConfigurationEndpoint() != null+ && recordsHoldingTheirPort.remove(recordKey(cacheClusters.accountId(), clusterId))) {releaseProxyPort(cluster.getConfigurationEndpoint().port());}@@ -1547,24 +1584,22 @@ public class ElastiCacheService implements ResourceProvider {* carries no user list.*/public boolean validateCacheClusterPassword(String clusterId, String username, String password) {- CacheCluster cluster = cacheClusters.get(clusterId).orElse(null);+ return validateCacheClusterPassword(cacheClusters.accountId(), clusterId, username, password);+ }++ /**+ * The account-explicit form the proxy calls: it authenticates on its own thread, outside any+ * request, where the store's implicit account is the default one rather than the owner's.+ */+ private boolean validateCacheClusterPassword(String accountId, String clusterId, String username,+ String password) {+ CacheCluster cluster = cacheClusters.getForAccount(accountId, clusterId).orElse(null);if (cluster == null || cluster.getAuthToken() == null) {return false;}return (username == null || username.isEmpty()) && cluster.getAuthToken().equals(password);}- private List<CacheCluster> runtimeCacheClusters() {- List<CacheCluster> records = new ArrayList<>(findCacheClusters(null));- records.addAll(cacheClusters.scanAllAccounts().stream()- .filter(cluster -> cluster.getServerlessCacheName() != null).toList());- return records;- }-- private Optional<CacheCluster> runtimeCluster(String id, String accountId) {- return accountId == null ? cacheClusters.get(id) : cacheClusters.getForAccount(accountId, id);- }-private void putRuntimeCluster(CacheCluster cluster) {if (cluster.getOwnerAccountId() == null) {cacheClusters.put(cluster.getCacheClusterId(), cluster);@@ -1587,11 +1622,12 @@ public class ElastiCacheService implements ResourceProvider {}}- private void startCacheClusterProxy(CacheCluster cluster, ElastiCacheContainerHandle handle) {+ private void startCacheClusterProxy(String accountId, CacheCluster cluster, ElastiCacheContainerHandle handle) {if (cluster.getServerlessCacheName() == null) {proxyManager.startProxy(cluster.getCacheClusterId(), cluster.getAuthMode(),cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),- (username, password) -> validateCacheClusterPassword(cluster.getCacheClusterId(), username, password));+ (username, password) -> validateCacheClusterPassword(+ accountId, cluster.getCacheClusterId(), username, password));} else {proxyManager.startProxy(cluster.getCacheClusterId(), AuthMode.NO_AUTH,cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),@@ -1638,6 +1674,11 @@ public class ElastiCacheService implements ResourceProvider {ElastiCacheUser user = member(username);return user == null ? null : user.getAuthMode();}++ @Override+ public String ownerAccountId() {+ return account;+ }};}@@ -2058,10 +2099,10 @@ public class ElastiCacheService implements ResourceProvider {* groups, read at the time of the check so a ModifyUserGroup applies at once, plus any user* associated with it directly.*/- private Set<String> effectiveUserIds(ReplicationGroup group) {+ private Set<String> effectiveUserIds(String accountId, ReplicationGroup group) {Set<String> userIds = new LinkedHashSet<>(group.getAssociatedUserIds());for (String userGroupId : group.getUserGroupIds()) {- userGroups.get(userGroupId).ifPresent(g -> userIds.addAll(g.getUserIds()));+ userGroups.getForAccount(accountId, userGroupId).ifPresent(g -> userIds.addAll(g.getUserIds()));}return userIds;}@@ -2137,7 +2178,15 @@ public class ElastiCacheService implements ResourceProvider {* ModifyReplicationGroup are checked, preventing cross-group credential leakage.*/public boolean validatePassword(String groupId, String username, String password) {- ReplicationGroup group = groups.get(groupId).orElse(null);+ return validatePassword(groups.accountId(), groupId, username, password);+ }++ /**+ * The account-explicit form {@link #groupAuthenticator} calls, for the reason given on+ * {@link #validateCacheClusterPassword(String, String, String, String)}.+ */+ private boolean validatePassword(String accountId, String groupId, String username, String password) {+ ReplicationGroup group = groups.getForAccount(accountId, groupId).orElse(null);if (group == null) {return false;}@@ -2149,9 +2198,9 @@ public class ElastiCacheService implements ResourceProvider {return true;}// Fall back to the "default" user among this group's members- Set<String> groupUserIds = effectiveUserIds(group);+ Set<String> groupUserIds = effectiveUserIds(accountId, group);ElastiCacheUser defaultUser = groupUserIds.stream()- .map(id -> users.get(id).orElse(null))+ .map(id -> users.getForAccount(accountId, id).orElse(null)).filter(u -> u != null && "default".equals(u.getUserName())).findFirst().orElse(null);@@ -2167,9 +2216,9 @@ public class ElastiCacheService implements ResourceProvider {return false;}// AUTH username password form: find user by userName, scoped to group- Set<String> groupUserIds = effectiveUserIds(group);+ Set<String> groupUserIds = effectiveUserIds(accountId, group);ElastiCacheUser targetUser = groupUserIds.stream()- .map(id -> users.get(id).orElse(null))+ .map(id -> users.getForAccount(accountId, id).orElse(null)).filter(u -> u != null && username.equals(u.getUserName())).findFirst().orElse(null);@@ -2190,50 +2239,70 @@ public class ElastiCacheService implements ResourceProvider {* even while it has no members, since RBAC then admits nobody rather than every caller.*/public boolean hasMembers(String groupId) {- ReplicationGroup group = groups.get(groupId).orElse(null);+ return hasMembers(groups.accountId(), groupId);+ }++ private boolean hasMembers(String accountId, String groupId) {+ ReplicationGroup group = groups.getForAccount(accountId, groupId).orElse(null);if (group == null) {return false;}if (!group.getUserGroupIds().isEmpty()) {return true;}- return group.getAssociatedUserIds().stream().anyMatch(id -> users.get(id).isPresent());+ return group.getAssociatedUserIds().stream()+ .anyMatch(id -> users.getForAccount(accountId, id).isPresent());}public AuthMode memberAuthMode(String groupId, String username) {- ReplicationGroup group = groups.get(groupId).orElse(null);+ return memberAuthMode(groups.accountId(), groupId, username);+ }++ private AuthMode memberAuthMode(String accountId, String groupId, String username) {+ ReplicationGroup group = groups.getForAccount(accountId, groupId).orElse(null);if (group == null) {return null;}String target = (username == null || username.isEmpty()) ? "default" : username;- return effectiveUserIds(group).stream()- .map(id -> users.get(id).orElse(null))+ return effectiveUserIds(accountId, group).stream()+ .map(id -> users.getForAccount(accountId, id).orElse(null)).filter(u -> u != null && target.equals(u.getUserName()) && u.isEnabled()).map(ElastiCacheUser::getAuthMode).findFirst().orElse(null);}- private ElastiCacheAuthProxy.PasswordValidator groupAuthenticator(String groupId) {+ /**+ * Bound to the account that owns the group, captured when the proxy is registered: the proxy+ * calls back on its own thread, where the store's implicit account is always the default one,+ * so a lookup by id alone would miss another account's group or find the default account's+ * group of the same name.+ */+ private ElastiCacheAuthProxy.PasswordValidator groupAuthenticator(String accountId, String groupId) {return new ElastiCacheAuthProxy.PasswordValidator() {@Overridepublic boolean validatePassword(String username, String password) {- return ElastiCacheService.this.validatePassword(groupId, username, password);+ return ElastiCacheService.this.validatePassword(accountId, groupId, username, password);}@Overridepublic boolean hasMembers() {- return ElastiCacheService.this.hasMembers(groupId);+ return ElastiCacheService.this.hasMembers(accountId, groupId);}@Overridepublic AuthMode memberAuthMode(String username) {- return ElastiCacheService.this.memberAuthMode(groupId, username);+ return ElastiCacheService.this.memberAuthMode(accountId, groupId, username);}@Overridepublic AuthMode authMode() {- return groups.get(groupId).map(ReplicationGroup::getAuthMode).orElse(null);+ return groups.getForAccount(accountId, groupId).map(ReplicationGroup::getAuthMode).orElse(null);+ }++ @Override+ public String ownerAccountId() {+ return accountId;}};}diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.javaindex 77bf01b053..00c96e2708 100644--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java@@ -56,7 +56,7 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {defaultMode = passwordValidator.memberAuthMode(username);}if (defaultMode == AuthMode.IAM) {- return sigV4Validator.validate(password, groupId, "default");+ return sigV4Validator.validate(password, groupId, "default", passwordValidator.ownerAccountId());}return false;}@@ -67,7 +67,8 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {}if (userMode != null) {return switch (userMode) {- case IAM -> sigV4Validator.validate(password, groupId, effectiveUser);+ case IAM -> sigV4Validator.validate(password, groupId, effectiveUser,+ passwordValidator.ownerAccountId());case PASSWORD, NO_AUTH -> passwordValidator.validatePassword(effectiveUser, password);};}@@ -75,7 +76,7 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {}return switch (currentAuthMode()) {- case IAM -> sigV4Validator.validate(password, groupId, effectiveUser);+ case IAM -> sigV4Validator.validate(password, groupId, effectiveUser, passwordValidator.ownerAccountId());case PASSWORD -> passwordValidator.validatePassword(username, password);case NO_AUTH -> true;};@@ -122,5 +123,13 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {default AuthMode authMode() {return null;}++ /**+ * The account that owns the cache, whose long-term access keys an IAM token may be signed+ * with, or null to look keys up in the default account.+ */+ default String ownerAccountId() {+ return null;+ }}}diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.javaindex 07378c82e9..34bf828612 100644--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java@@ -39,6 +39,14 @@ public class SigV4Validator {* @return true if the token is valid, identities match, and the token is not expired*/public boolean validate(String token, String expectedGroupId, String expectedUsername) {+ return validate(token, expectedGroupId, expectedUsername, null);+ }++ /**+ * As above, accepting a long-term access key only when {@code ownerAccountId} holds it, for+ * the auth proxy, which checks tokens on its own thread outside any request.+ */+ public boolean validate(String token, String expectedGroupId, String expectedUsername, String ownerAccountId) {try {URI uri = URI.create("http://" + token);String clusterId = uri.getHost();@@ -54,7 +62,8 @@ public class SigV4Validator {return false;}- return requestValidator.validate(rawQuery, clusterId, "User", false, expectedUsername, "IAM token");+ return requestValidator.validate(rawQuery, clusterId, "User", false, expectedUsername, "IAM token",+ ownerAccountId);} catch (Exception e) {LOG.debugv("IAM token validation error: {0}", e.getMessage());return false;diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.javaindex cb0f69f588..22a450f341 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceDockerIntegrationTest.java@@ -161,7 +161,9 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {ContainerSpec spec = containerBuilder.newContainer("alpine:3.21").withName(containerName).withPrivileged(true)- .withEntrypoint(List.of("sleep", "3600"))+ // PID 1 gets no default SIGTERM handler, so a bare "sleep 3600" sits out the whole+ // grace period of every stop: 30 seconds when stopInstances stops it, 2 in cleanup.+ .withEntrypoint(List.of("sh", "-c", "trap 'exit 0' TERM; sleep 3600 & wait")).build();String containerId = lifecycleManager.createAndStart(spec).containerId();@@ -337,7 +339,8 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {ContainerSpec spec = containerBuilder.newContainer("alpine:3.21").withName(containerName).withPrivileged(true)- .withEntrypoint(List.of("sleep", "3600"))+ // As in createRunningTestInstance: lets cleanup's stop return at once.+ .withEntrypoint(List.of("sh", "-c", "trap 'exit 0' TERM; sleep 3600 & wait")).build();String containerId = lifecycleManager.createAndStart(spec).containerId();diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.javaindex 2922e00b63..60404c184d 100644--- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java@@ -357,6 +357,7 @@ class ElastiCacheServerlessServiceTest {validator.capture(), eq("account-cache"));assertTrue(validator.getValue().validatePassword("alice", "owner-secret"));assertFalse(validator.getValue().validatePassword("alice", "password-a"));+ assertEquals("111111111111", validator.getValue().ownerAccountId());AccountAwareStorageBackend<CacheCluster> backing = factory.create("elasticache", "elasticache-redis-clusters.json", null);assertTrue(backing.getForAccount("000000000000", original.getBackingCacheClusterId()).isEmpty());assertTrue(backing.getForAccount("111111111111", original.getBackingCacheClusterId()).isPresent());diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.javaindex bbd2d0003d..67284fd710 100644--- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.elasticache.model.Endpoint;import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;+import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheAuthProxy;import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;import io.github.hectorvent.floci.services.kms.KmsService;import io.github.hectorvent.floci.services.kms.model.KmsKey;@@ -970,6 +971,253 @@ class ElastiCacheServiceTest {"A restored group's port must be reserved again so new groups cannot take it");}+ @Test+ void restorePersistedRuntimeRestoresEveryAccountUnderItsOwnAccount() {+ String other = "111111111111";+ StorageFactory storageFactory = sharedStorageFactory();+ ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);+ stubSingleNodeContainer(beforeRestart);+ ElastiCacheService before = serviceWith(storageFactory, beforeRestart,+ mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));+ before.createReplicationGroup("grp", "test", AuthMode.NO_AUTH, null, "us-east-1");+ before.createCacheCluster(cacheClusterRequest("cc", "redis", 1));+ // Move both records to a non-default account, as a request under that account would have stored them.+ AccountAwareStorageBackend<ReplicationGroup> groups =+ storageFactory.<ReplicationGroup>create("elasticache", "elasticache-groups.json", null);+ AccountAwareStorageBackend<CacheCluster> clusters =+ storageFactory.<CacheCluster>create("elasticache", "elasticache-redis-clusters.json", null);+ groups.putForAccount(other, "grp", groups.getForAccount("000000000000", "grp").orElseThrow());+ groups.deleteForAccount("000000000000", "grp");+ clusters.putForAccount(other, "cc", clusters.getForAccount("000000000000", "cc").orElseThrow());+ clusters.deleteForAccount("000000000000", "cc");++ ElastiCacheContainerManager restartedContainers = mock(ElastiCacheContainerManager.class);+ stubSingleNodeContainer(restartedContainers);+ ElastiCacheService restarted = serviceWith(storageFactory, restartedContainers,+ mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));++ restarted.restorePersistedRuntime().join();++ verify(restartedContainers).tryStart(eq("grp"), anyString(), any());+ verify(restartedContainers).tryStart(eq("cc"), anyString(), any());+ assertEquals(ReplicationGroupStatus.AVAILABLE,+ groups.getForAccount(other, "grp").orElseThrow().getStatus());+ assertEquals(CacheClusterStatus.AVAILABLE,+ clusters.getForAccount(other, "cc").orElseThrow().getCacheClusterStatus());+ assertTrue(groups.getForAccount("000000000000", "grp").isEmpty(),+ "A restore must not copy another account's group into the default account");+ assertTrue(clusters.getForAccount("000000000000", "cc").isEmpty(),+ "A restore must not copy another account's cluster into the default account");++ ReplicationGroup next =+ restarted.createReplicationGroup("grp2", "test", AuthMode.NO_AUTH, null, "us-east-1");+ assertEquals(16381, next.getProxyPort(),+ "Both restored records' ports (16379, 16380) must be reserved again");+ }++ @Test+ void restoreMigratesUnprefixedLegacyRecordsInsteadOfRestoringThemEveryBoot() {+ InMemoryStorage<String, Object> rawGroups = new InMemoryStorage<>();+ InMemoryStorage<String, Object> rawClusters = new InMemoryStorage<>();+ StorageFactory storageFactory = mock(StorageFactory.class);+ Map<String, Object> backends = new ConcurrentHashMap<>();+ backends.put("elasticache-groups.json", new AccountAwareStorageBackend<>(rawGroups, null, "000000000000"));+ backends.put("elasticache-redis-clusters.json",+ new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"));+ when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->+ backends.computeIfAbsent(inv.getArgument(1, String.class),+ key -> AccountAwareStorageBackend.inMemory("000000000000")));+ ElastiCacheContainerManager beforeRestart = mock(ElastiCacheContainerManager.class);+ stubSingleNodeContainer(beforeRestart);+ ElastiCacheService before = serviceWith(storageFactory, beforeRestart,+ mock(ElastiCacheProxyManager.class), mock(ValkeyClusterFormation.class));+ before.createReplicationGroup("grp", "test", AuthMode.NO_AUTH, null, "us-east-1");+ before.createCacheCluster(cacheClusterRequest("cc", "redis", 1));+ // Rewrite both records under the unprefixed key data from before account prefixing used.+ rawGroups.put("grp", rawGroups.get("000000000000/grp").orElseThrow());+ rawGroups.delete("000000000000/grp");+ rawClusters.put("cc", rawClusters.get("000000000000/cc").orElseThrow());+ rawClusters.delete("000000000000/cc");++ for (int boot = 1; boot <= 2; boot++) {+ ElastiCacheContainerManager containers = mock(ElastiCacheContainerManager.class);+ stubSingleNodeContainer(containers);+ serviceWith(storageFactory, containers, mock(ElastiCacheProxyManager.class),+ mock(ValkeyClusterFormation.class)).restorePersistedRuntime().join();+ verify(containers, times(1)).tryStart(eq("grp"), anyString(), any());+ verify(containers, times(1)).tryStart(eq("cc"), anyString(), any());+ }+ assertEquals(Set.of("000000000000/grp"), rawGroups.keys(),+ "The legacy key must be migrated, not left beside the restored copy");+ assertEquals(Set.of("000000000000/cc"), rawClusters.keys(),+ "The legacy key must be migrated, not left beside the restored copy");+ }++ /**+ * Storage whose implicit account is whatever {@code account} holds, as a request's context+ * sets it, so a test can act as another account and then fall back to the default one, the+ * way the proxy thread does.+ */+ private static StorageFactory storageFollowing(AtomicReference<String> account) {+ RequestContext requestContext = mock(RequestContext.class);+ when(requestContext.getAccountId()).thenAnswer(inv -> account.get());+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requestContextInstance = mock(Instance.class);+ when(requestContextInstance.get()).thenReturn(requestContext);+ StorageFactory storageFactory = mock(StorageFactory.class);+ Map<String, Object> backends = new ConcurrentHashMap<>();+ when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->+ backends.computeIfAbsent(inv.getArgument(1, String.class), key ->+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requestContextInstance,+ "000000000000")));+ return storageFactory;+ }++ private static void seedPasswordGroup(StorageFactory storageFactory, String accountId, int port) {+ ReplicationGroup group = new ReplicationGroup();+ group.setReplicationGroupId("grp");+ group.setStatus(ReplicationGroupStatus.AVAILABLE);+ group.setProxyPort(port);+ group.setAuthMode(AuthMode.PASSWORD);+ group.setAuthToken("secret-token");+ storageFactory.<ReplicationGroup>create("elasticache", "elasticache-groups.json", null)+ .putForAccount(accountId, "grp", group);+ }++ @Test+ void restoredGroupOfAnotherAccountAcceptsItsPassword() {+ StorageFactory storageFactory = storageFollowing(new AtomicReference<>("000000000000"));+ ElastiCacheService svc = serviceWith(storageFactory, containerManager, proxyManager, clusterFormation);+ seedPasswordGroup(storageFactory, "111111111111", 16379);++ svc.restorePersistedRuntime().join();++ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("grp"), eq(AuthMode.PASSWORD), eq(16379), anyString(), anyInt(),+ validator.capture());+ assertTrue(validator.getValue().validatePassword(null, "secret-token"));+ assertEquals("111111111111", validator.getValue().ownerAccountId(),+ "IAM tokens must be checked against the restored group's own account");+ }++ @Test+ void deletingSameNamedRestoredGroupsOfTwoAccountsReleasesBothPorts() {+ AtomicReference<String> account = new AtomicReference<>("000000000000");+ StorageFactory storageFactory = storageFollowing(account);+ ElastiCacheService svc = serviceWith(storageFactory, containerManager, proxyManager, clusterFormation);+ seedPasswordGroup(storageFactory, "000000000000", 16379);+ seedPasswordGroup(storageFactory, "111111111111", 16380);+ svc.restorePersistedRuntime().join();++ svc.deleteReplicationGroup("grp");+ account.set("111111111111");+ svc.deleteReplicationGroup("grp");++ assertEquals(16379, svc.createReplicationGroup("new1", "test", AuthMode.NO_AUTH, null,+ "us-east-1").getProxyPort());+ assertEquals(16380, svc.createReplicationGroup("new2", "test", AuthMode.NO_AUTH, null,+ "us-east-1").getProxyPort());+ }++ @Test+ void restoredCacheClusterOfAnotherAccountAcceptsItsPassword() {+ StorageFactory storageFactory = storageFollowing(new AtomicReference<>("000000000000"));+ ElastiCacheService svc = serviceWith(storageFactory, containerManager, proxyManager, clusterFormation);+ CacheCluster cluster = new CacheCluster();+ cluster.setCacheClusterId("cc");+ cluster.setCacheClusterStatus(CacheClusterStatus.AVAILABLE);+ cluster.setConfigurationEndpoint(new Endpoint("localhost", 16379));+ cluster.setAuthMode(AuthMode.PASSWORD);+ cluster.setAuthToken("secret-token");+ storageFactory.<CacheCluster>create("elasticache", "elasticache-redis-clusters.json", null)+ .putForAccount("111111111111", "cc", cluster);++ svc.restorePersistedRuntime().join();++ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("cc"), eq(AuthMode.PASSWORD), eq(16379), anyString(), anyInt(),+ validator.capture());+ assertTrue(validator.getValue().validatePassword(null, "secret-token"));+ }++ @Test+ void groupCreatedUnderAnotherAccountAcceptsItsPasswordOutsideTheRequest() {+ AtomicReference<String> account = new AtomicReference<>("111111111111");+ ElastiCacheService svc = serviceWith(storageFollowing(account), containerManager, proxyManager,+ clusterFormation);+ svc.createReplicationGroup("grp", "test", AuthMode.PASSWORD, "secret-token", "us-east-1");+ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("grp"), eq(AuthMode.PASSWORD), anyInt(), anyString(), anyInt(),+ validator.capture());++ // The proxy authenticates on its own thread, where the store falls back to the default account.+ account.set("000000000000");+ assertTrue(validator.getValue().validatePassword(null, "secret-token"));+ assertEquals("111111111111", validator.getValue().ownerAccountId());+ }++ @Test+ void userGroupMemberOfAnotherAccountAuthenticatesOutsideTheRequest() {+ AtomicReference<String> account = new AtomicReference<>("111111111111");+ ElastiCacheService svc = serviceWith(storageFollowing(account), containerManager, proxyManager,+ clusterFormation);+ svc.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1");+ svc.createUser("default-user-id", "default", AuthMode.PASSWORD, List.of("default-pass"),+ "on ~* +@all", null);+ svc.createUser("app-user-id", "app", AuthMode.PASSWORD, List.of("app-pass"), "on ~* +@all", null);+ svc.createUserGroup("app-group", "redis", List.of("default-user-id", "app-user-id"), "us-east-1");+ svc.modifyReplicationGroup("grp", List.of("app-group"), null);+ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("grp"), any(), anyInt(), anyString(), anyInt(), validator.capture());++ // The proxy authenticates on its own thread, where the store falls back to the default account.+ account.set("000000000000");+ assertTrue(validator.getValue().validatePassword("app", "app-pass"));+ }++ @Test+ void groupOfAnotherAccountDroppingItsLastUserGroupChangesTheProxyAuthModeOutsideTheRequest() {+ AtomicReference<String> account = new AtomicReference<>("111111111111");+ ElastiCacheService svc = serviceWith(storageFollowing(account), containerManager, proxyManager,+ clusterFormation);+ svc.createReplicationGroup("grp", "test", AuthMode.PASSWORD, "group-token", "us-east-1");+ svc.createUser("default-user-id", "default", AuthMode.PASSWORD, List.of("default-pass"),+ "on ~* +@all", null);+ svc.createUserGroup("redis-users", "redis", List.of("default-user-id"), "us-east-1");+ svc.modifyReplicationGroup("grp", List.of("redis-users"), null, false, true,+ ReplicationGroupSettings.unchanged());+ svc.modifyReplicationGroup("grp", null, List.of("redis-users"));+ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("grp"), eq(AuthMode.PASSWORD), anyInt(), anyString(), anyInt(),+ validator.capture());++ // ModifyReplicationGroup does not restart the proxy, which reads the mode on its own+ // thread, where the store falls back to the default account.+ account.set("000000000000");+ assertEquals(AuthMode.NO_AUTH, validator.getValue().authMode());+ }++ @Test+ void cacheClusterCreatedUnderAnotherAccountAcceptsItsPasswordOutsideTheRequest() {+ AtomicReference<String> account = new AtomicReference<>("111111111111");+ ElastiCacheService svc = serviceWith(storageFollowing(account), containerManager, proxyManager,+ clusterFormation);+ svc.createCacheCluster(cacheClusterRequest("cc", "redis", null, AuthMode.PASSWORD, "secret-token", null));+ ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator =+ ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);+ verify(proxyManager).startProxy(eq("cc"), eq(AuthMode.PASSWORD), anyInt(), anyString(), anyInt(),+ validator.capture());++ // The proxy authenticates on its own thread, where the store falls back to the default account.+ account.set("000000000000");+ assertTrue(validator.getValue().validatePassword(null, "secret-token"));+ }+@Testvoid singleNodeRestoreFailureReportsCreateFailedAndReleasesThePort() {StorageFactory storageFactory = storageWithSingleNodeGroup("grp");diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxyTest.javaindex 2544cfb4c8..d2298aabaf 100644--- a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxyTest.java@@ -68,8 +68,8 @@ class ElastiCacheAuthProxyTest {@Testvoid groupWithPasswordAuthModeAuthenticatesIamUserWhenAssociated() {SigV4Validator sigV4Validator = mock(SigV4Validator.class);- when(sigV4Validator.validate("valid-sigv4", "grp-2", "iam-user")).thenReturn(true);- when(sigV4Validator.validate("bad-sigv4", "grp-2", "iam-user")).thenReturn(false);+ when(sigV4Validator.validate("valid-sigv4", "grp-2", "iam-user", null)).thenReturn(true);+ when(sigV4Validator.validate("bad-sigv4", "grp-2", "iam-user", null)).thenReturn(false);ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {@Override@@ -157,7 +157,7 @@ class ElastiCacheAuthProxyTest {@Testvoid groupWithMembersNormalizesEmptyUsernameToDefaultForIamValidation() {SigV4Validator sigV4Validator = mock(SigV4Validator.class);- when(sigV4Validator.validate("valid-sigv4", "grp-empty", "default")).thenReturn(true);+ when(sigV4Validator.validate("valid-sigv4", "grp-empty", "default", null)).thenReturn(true);ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {@Override@@ -186,7 +186,7 @@ class ElastiCacheAuthProxyTest {@Testvoid groupWithNoMembersRequiresDefaultUserForSingleArgIamAuth() {SigV4Validator sigV4Validator = mock(SigV4Validator.class);- when(sigV4Validator.validate("valid-sigv4", "grp-legacy-iam", "default")).thenReturn(true);+ when(sigV4Validator.validate("valid-sigv4", "grp-legacy-iam", "default", null)).thenReturn(true);ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {@Override@@ -210,7 +210,7 @@ class ElastiCacheAuthProxyTest {@Testvoid groupWithNoMembersPreservesLegacyIamAndAuthTokenBehaviour() {SigV4Validator sigV4Validator = mock(SigV4Validator.class);- when(sigV4Validator.validate("valid-sigv4", "grp-4", "anyone")).thenReturn(true);+ when(sigV4Validator.validate("valid-sigv4", "grp-4", "anyone", null)).thenReturn(true);ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {@Override@@ -421,4 +421,55 @@ class ElastiCacheAuthProxyTest {assertTrue(proxy.authenticate("app-user", "secret-123"),"Configured password user must be able to authenticate");}++ @Test+ void iamTokenIsCheckedAgainstTheAccountThatOwnsTheCache() {+ SigV4Validator sigV4Validator = mock(SigV4Validator.class);+ when(sigV4Validator.validate("valid-sigv4", "grp-owned", "iam-user", "111111111111")).thenReturn(true);+ when(sigV4Validator.validate("valid-sigv4", "grp-owned", "default", "111111111111")).thenReturn(true);+ ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {+ @Override+ public boolean validatePassword(String username, String password) {+ return false;+ }++ @Override+ public boolean hasMembers() {+ return true;+ }++ @Override+ public AuthMode memberAuthMode(String username) {+ return AuthMode.IAM;+ }++ @Override+ public String ownerAccountId() {+ return "111111111111";+ }+ };++ ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-owned", AuthMode.IAM, "127.0.0.1", 6379,+ passwordValidator, sigV4Validator);++ assertTrue(proxy.authenticate("iam-user", "valid-sigv4"));+ assertTrue(proxy.authenticate(null, "valid-sigv4"));++ when(sigV4Validator.validate("valid-sigv4", "grp-owned", "anyone", "111111111111")).thenReturn(true);+ ElastiCacheAuthProxy.PasswordValidator withoutMembers = new ElastiCacheAuthProxy.PasswordValidator() {+ @Override+ public boolean validatePassword(String username, String password) {+ return false;+ }++ @Override+ public String ownerAccountId() {+ return "111111111111";+ }+ };+ ElastiCacheAuthProxy legacyProxy = new ElastiCacheAuthProxy("grp-owned", AuthMode.IAM, "127.0.0.1", 6379,+ withoutMembers, sigV4Validator);++ assertTrue(legacyProxy.authenticate("anyone", "valid-sigv4"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.javaindex c57657f98a..8a332f826e 100644--- a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java@@ -118,6 +118,31 @@ class SigV4ValidatorTest {assertFalse(validator.validate(token, "cache-cluster-01", "default"));}+ /**+ * The proxy validates on its own thread, where the implicit account is the default one. A key+ * held by the account that owns the cache is still found, and one held by another account is+ * not.+ */+ @Test+ void validateFindsTheOwningAccountsKeyOutsideARequest() throws Exception {+ IamService iamService = IamServiceTestHelper.iamServiceWithAccessKeyInAccount(+ "AKIDCACHE", "secret-cache", "111111111111", "000000000000");++ SigV4Validator validator = new SigV4Validator(iamService);+ String token = SigV4TokenTestHelper.createElastiCacheToken(+ "cache-cluster-01",+ "default",+ "AKIDCACHE",+ "secret-cache",+ Instant.now().minusSeconds(60),+ 900+ );++ assertTrue(validator.validate(token, "cache-cluster-01", "default", "111111111111"));+ assertFalse(validator.validate(token, "cache-cluster-01", "default", "222222222222"));+ assertFalse(validator.validate(token, "cache-cluster-01", "default", "000000000000"));+ }+/*** A bare 12-digit access key ID that isn't registered in IAM must be rejected like any* other unknown key, not resolved to the well-known "test" secret. That fallback would let@@ -245,6 +270,8 @@ class SigV4ValidatorTest {Instant.now().minusSeconds(60), 900, "session-token");assertTrue(validator.validate(token, "cache-cluster-01", "default"));+ assertTrue(validator.validate(token, "cache-cluster-01", "default", "111111111111"),+ "A session is found whichever account issued it, with or without an owner to check");}/** A Lambda execution role's session token carries {@code +}, {@code /} and {@code =}. */