feat(elasticache): support cache subnet groups (#2401)

* feat(elasticache): support cache subnet groups

CreateCacheSubnetGroup was unsupported, so aws_elasticache_subnet_group could
not be created and no Redis or Valkey module placing a cluster in a VPC could
apply. DescribeCacheSubnetGroups already answered with an empty list, so the
read half existed with nothing behind it.

Adds Create, Modify and Delete, and makes the describe return what was created.

A group's VpcId and each subnet's availability zone come from the subnets rather
than the request, because that is where AWS reads them: resolving the subnets
against EC2 is part of answering, not an optional check. The service follows the
RDS DB subnet group, which faces the same problem.

Taken from a live account: the create response and its ARN, SupportedNetworkTypes
on both the group and each subnet, and the error for each rejection — subnets
that do not exist, subnets spanning two VPCs, a duplicate group, and a name that
breaks the identifier rule. Describe and delete word their not-found differently
from one another, and both are reproduced as AWS words them.

Tags given at create are stored and readable through ListTagsForResource, rather
than accepted and dropped. A modify naming no subnets keeps the stored ones as
they are instead of resolving them again, which would fail a description-only
change if a subnet had since been deleted.

* fix(elasticache): resolve subnet group subnets in the caller's region

CreateCacheSubnetGroup and a subnet-changing ModifyCacheSubnetGroup looked the
subnet ids up in the configured default region. A caller in any other region had
its own subnets rejected as invalid, and the group was reported under an ARN
built from the caller's region while its VPC and availability zones came from
somewhere else.

Resolve against the request's region, which is the region the ARN already uses.

* fix(elasticache): report a subnet group's subnets in the order they were given

describeSubnets answers in the subnet store's own scan order, and the group was
built by iterating that answer, so the order a group reported its subnets in was
arbitrary between calls — the model documents the order the caller gave.

Build the zone map from the requested ids. Adds a CLI case covering the region
the subnets are resolved in, which is what caught this: it read Subnets[0] and
disagreed with itself between runs.

* fix(elasticache): answer a missing cache subnet group with 400, not 404

The service model declares CacheSubnetGroupNotFoundFault a 400, where the
parameter-group fault a few hundred lines up is a 404 — the two really differ,
in the wire code as well as the status, and the status was carried across from
the parameter-group code. All three sites answered 404, and the integration
test pinned it there, so a client reading the status saw the wrong one.

The difference is now stated where the copy would be made, since either fault
looks like a mistake beside the other.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-19 18:03:54 -04:00
1 parent 65b22ff01e
commit 06d58aad36
7 files changed
+600 -9

No files matched your search

@@ -84,3 +84,56 @@ teardown() {
assert_failure
assert_output --partial "not a valid identifier"
}
@test "ElastiCache: cache subnet group takes its VPC and zones from the subnets" {
vpc=$(aws_cmd ec2 create-vpc --cidr-block 10.30.0.0/16 --query 'Vpc.VpcId' --output text)
a=$(aws_cmd ec2 create-subnet --vpc-id "$vpc" --cidr-block 10.30.1.0/24 \
--availability-zone us-east-1a --query 'Subnet.SubnetId' --output text)
b=$(aws_cmd ec2 create-subnet --vpc-id "$vpc" --cidr-block 10.30.2.0/24 \
--availability-zone us-east-1b --query 'Subnet.SubnetId' --output text)
SNG="bats-sng-$(unique_name)"
run aws_cmd elasticache create-cache-subnet-group \
--cache-subnet-group-name "$SNG" \
--cache-subnet-group-description "bats subnet group" \
--subnet-ids "$a" "$b"
assert_success
[ "$(json_get "$output" '.CacheSubnetGroup.VpcId')" = "$vpc" ]
[ "$(json_get "$output" '.CacheSubnetGroup.Subnets | length')" = "2" ]
[ "$(json_get "$output" '.CacheSubnetGroup.Subnets[0].SubnetAvailabilityZone.Name')" = "us-east-1a" ]
run aws_cmd elasticache describe-cache-subnet-groups --cache-subnet-group-name "$SNG"
assert_success
[ "$(json_get "$output" '.CacheSubnetGroups[0].CacheSubnetGroupName')" = "$SNG" ]
run aws_cmd elasticache create-cache-subnet-group \
--cache-subnet-group-name "bats-absent-$(unique_name)" \
--cache-subnet-group-description x --subnet-ids subnet-00000000000000000
assert_failure
assert_output --partial "are invalid"
run aws_cmd elasticache delete-cache-subnet-group --cache-subnet-group-name "$SNG"
assert_success
}
@test "ElastiCache: a cache subnet group is built from subnets in the caller's region" {
# Subnets exist in the region they were created in. Resolving them in the configured default
# region instead rejects a caller's own subnets as invalid.
export AWS_DEFAULT_REGION=eu-west-1
vpc=$(aws_cmd ec2 create-vpc --cidr-block 10.31.0.0/16 --query 'Vpc.VpcId' --output text)
s=$(aws_cmd ec2 create-subnet --vpc-id "$vpc" --cidr-block 10.31.1.0/24 \
--availability-zone eu-west-1a --query 'Subnet.SubnetId' --output text)
SNG_EU="bats-sng-eu-$(unique_name)"
run aws_cmd elasticache create-cache-subnet-group \
--cache-subnet-group-name "$SNG_EU" \
--cache-subnet-group-description "bats other region" \
--subnet-ids "$s"
assert_success
[ "$(json_get "$output" '.CacheSubnetGroup.VpcId')" = "$vpc" ]
[ "$(json_get "$output" '.CacheSubnetGroup.Subnets[0].SubnetAvailabilityZone.Name')" = "eu-west-1a" ]
[[ "$(json_get "$output" '.CacheSubnetGroup.ARN')" == arn:aws:elasticache:eu-west-1:* ]]
run aws_cmd elasticache delete-cache-subnet-group --cache-subnet-group-name "$SNG_EU"
assert_success
}
+10 -1
View File
@@ -23,7 +23,10 @@ Floci manages real Valkey/Redis Docker containers and proxies TCP connections to
| `CreateCacheCluster` | - |
| `DescribeCacheClusters` | - |
| `DeleteCacheCluster` | - |
| `DescribeCacheSubnetGroups` | - |
| `CreateCacheSubnetGroup` | Create a cache subnet group |
| `DescribeCacheSubnetGroups` | List cache subnet groups |
| `ModifyCacheSubnetGroup` | Replace a group's description or subnets |
| `DeleteCacheSubnetGroup` | Delete a cache subnet group |
| `CreateCacheParameterGroup` | Create a cache parameter group |
| `DescribeCacheParameterGroups` | List parameter groups, including the AWS defaults |
| `ModifyCacheParameterGroup` | Set parameters on a group |
@@ -32,6 +35,12 @@ Floci manages real Valkey/Redis Docker containers and proxies TCP connections to
| `ListTagsForResource` | Tags on a parameter group ARN |
<!-- floci:actions:end -->
### Cache Subnet Groups
A subnet group's VPC and each subnet's availability zone are read from the subnets themselves, as
AWS reads them, so the subnets have to exist in the emulator's EC2 first. Subnets that are unknown,
or that span more than one VPC, are refused the way AWS refuses them.
### Cache Parameter Groups
The `default.*` groups AWS publishes are listed for every family it supports, and cannot be modified
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.CacheParameterGroup;
import io.github.hectorvent.floci.services.elasticache.model.CacheSubnetGroup;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
@@ -65,7 +66,10 @@ public class ElastiCacheQueryHandler {
case "CreateCacheCluster" -> handleCreateCacheCluster(params);
case "DescribeCacheClusters" -> handleDescribeCacheClusters(params);
case "DeleteCacheCluster" -> handleDeleteCacheCluster(params);
case "CreateCacheSubnetGroup" -> handleCreateCacheSubnetGroup(params);
case "DescribeCacheSubnetGroups" -> handleDescribeCacheSubnetGroups(params);
case "ModifyCacheSubnetGroup" -> handleModifyCacheSubnetGroup(params);
case "DeleteCacheSubnetGroup" -> handleDeleteCacheSubnetGroup(params);
case "CreateCacheParameterGroup" -> handleCreateCacheParameterGroup(params);
case "DescribeCacheParameterGroups" -> handleDescribeCacheParameterGroups(params);
case "ModifyCacheParameterGroup" -> handleModifyCacheParameterGroup(params);
@@ -293,14 +297,92 @@ public class ElastiCacheQueryHandler {
// ── Subnet / Parameter Groups (read-only describes for resources not modeled) ────
private Response handleDescribeCacheSubnetGroups(MultivaluedMap<String, String> params) {
// Cache subnet groups are not modeled by the emulator; return the wire-accurate
// empty result so SDK clients get a valid 200 instead of an unsupported-action 400.
var xml = new XmlBuilder().start("CacheSubnetGroups").end("CacheSubnetGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheSubnetGroups", AwsNamespaces.EC, xml.build())).build();
private Response handleCreateCacheSubnetGroup(MultivaluedMap<String, String> params) {
try {
CacheSubnetGroup group = service.createCacheSubnetGroup(
params.getFirst("CacheSubnetGroupName"),
params.getFirst("CacheSubnetGroupDescription"),
parseSubnetIds(params),
parseTags(params));
var xml = new XmlBuilder();
appendSubnetGroup(xml, group);
return Response.ok(AwsQueryResponse.envelope("CreateCacheSubnetGroup", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String> params) {
private Response handleDescribeCacheSubnetGroups(MultivaluedMap<String, String> params) {
try {
List<CacheSubnetGroup> groups =
service.describeCacheSubnetGroups(params.getFirst("CacheSubnetGroupName"));
var xml = new XmlBuilder().start("CacheSubnetGroups");
groups.forEach(group -> appendSubnetGroup(xml, group));
xml.end("CacheSubnetGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheSubnetGroups", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleModifyCacheSubnetGroup(MultivaluedMap<String, String> params) {
try {
CacheSubnetGroup group = service.modifyCacheSubnetGroup(
params.getFirst("CacheSubnetGroupName"),
params.getFirst("CacheSubnetGroupDescription"),
parseSubnetIds(params));
var xml = new XmlBuilder();
appendSubnetGroup(xml, group);
return Response.ok(AwsQueryResponse.envelope("ModifyCacheSubnetGroup", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDeleteCacheSubnetGroup(MultivaluedMap<String, String> params) {
try {
service.deleteCacheSubnetGroup(params.getFirst("CacheSubnetGroupName"));
return Response.ok(AwsQueryResponse.envelope("DeleteCacheSubnetGroup", AwsNamespaces.EC, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private void appendSubnetGroup(XmlBuilder xml, CacheSubnetGroup group) {
xml.start("CacheSubnetGroup")
.elem("CacheSubnetGroupName", group.getName())
.elem("CacheSubnetGroupDescription", group.getDescription())
.elem("VpcId", group.getVpcId())
.start("Subnets");
group.getSubnetAvailabilityZones().forEach((subnetId, availabilityZone) -> xml
.start("Subnet")
.elem("SubnetIdentifier", subnetId)
.start("SubnetAvailabilityZone").elem("Name", availabilityZone).end("SubnetAvailabilityZone")
.start("SupportedNetworkTypes").elem("member", "ipv4").end("SupportedNetworkTypes")
.end("Subnet"));
xml.end("Subnets")
.start("SupportedNetworkTypes").elem("member", "ipv4").end("SupportedNetworkTypes")
.elem("ARN", "arn:aws:elasticache:" + regionResolver.getRegion() + ":"
+ regionResolver.getAccountId() + ":subnetgroup:" + group.getName())
.end("CacheSubnetGroup");
}
/** Reads the SubnetIds list under every spelling the Query protocol sends it in. */
private static List<String> parseSubnetIds(MultivaluedMap<String, String> params) {
List<String> subnetIds = new ArrayList<>();
for (String prefix : List.of("SubnetIds.SubnetIdentifier", "SubnetIds.member")) {
for (int i = 1; ; i++) {
String subnetId = params.getFirst(prefix + "." + i);
if (subnetId == null) {
break;
}
subnetIds.add(subnetId);
}
}
return subnetIds;
}
private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String> params) {
try {
CacheParameterGroup group = service.createCacheParameterGroup(
params.getFirst("CacheParameterGroupName"),
@@ -396,6 +478,9 @@ public class ElastiCacheQueryHandler {
}
Map<String, String> tags = Map.of();
if ("subnetgroup".equals(arn[5])) {
tags = service.describeCacheSubnetGroups(arn[6]).getFirst().getTags();
}
if ("parametergroup".equals(arn[5])) {
tags = service.findParameterGroup(arn[6])
.orElseThrow(() -> new AwsException("CacheParameterGroupNotFound",
@@ -3,16 +3,20 @@ package io.github.hectorvent.floci.services.elasticache;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheParameterGroup;
import io.github.hectorvent.floci.services.elasticache.model.CacheSubnetGroup;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -41,9 +45,12 @@ public class ElastiCacheService {
private final StorageBackend<String, ReplicationGroup> groups;
private final StorageBackend<String, ElastiCacheUser> users;
private final StorageBackend<String, CacheParameterGroup> parameterGroups;
private final StorageBackend<String, CacheSubnetGroup> subnetGroups;
private final ElastiCacheContainerManager containerManager;
private final ElastiCacheProxyManager proxyManager;
private final EmulatorConfig config;
private final Ec2Service ec2Service;
private final RegionResolver regionResolver;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final Set<String> provisioningGroupIds = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<String, Object> parameterGroupLocks = new ConcurrentHashMap<>();
@@ -52,16 +59,22 @@ public class ElastiCacheService {
public ElastiCacheService(ElastiCacheContainerManager containerManager,
ElastiCacheProxyManager proxyManager,
StorageFactory storageFactory,
EmulatorConfig config) {
EmulatorConfig config,
Ec2Service ec2Service,
RegionResolver regionResolver) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.config = config;
this.ec2Service = ec2Service;
this.regionResolver = regionResolver;
this.groups = storageFactory.create("elasticache", "elasticache-groups.json",
new TypeReference<Map<String, ReplicationGroup>>() {});
this.users = storageFactory.create("elasticache", "elasticache-users.json",
new TypeReference<Map<String, ElastiCacheUser>>() {});
this.parameterGroups = storageFactory.create("elasticache", "elasticache-parameter-groups.json",
new TypeReference<Map<String, CacheParameterGroup>>() {});
this.subnetGroups = storageFactory.create("elasticache", "elasticache-subnet-groups.json",
new TypeReference<Map<String, CacheSubnetGroup>>() {});
}
public ReplicationGroup createReplicationGroup(String groupId, String description,
@@ -321,6 +334,125 @@ public class ElastiCacheService {
usedPorts.remove(port);
}
// ── Cache Subnet Groups ───────────────────────────────────────────────────
/**
* Creates a subnet group. The VPC and each subnet's availability zone are read from the
* subnets rather than the request, because that is where AWS takes them from — which makes
* resolving them against EC2 part of answering, not an optional check.
*/
public CacheSubnetGroup createCacheSubnetGroup(String name, String description,
List<String> subnetIds, Map<String, String> tags) {
validateSubnetGroupName(name);
synchronized (lockFor("sng:" + name)) {
if (subnetGroups.get(name).isPresent()) {
throw new AwsException("CacheSubnetGroupAlreadyExists",
"Cache subnet group " + name + " already exists.", 400);
}
CacheSubnetGroup group = buildSubnetGroup(name, description, subnetIds);
if (tags != null && !tags.isEmpty()) {
group.setTags(tags);
}
subnetGroups.put(name, group);
LOG.infov("Created cache subnet group {0} in {1}", name, group.getVpcId());
return group;
}
}
public List<CacheSubnetGroup> describeCacheSubnetGroups(String name) {
if (name == null || name.isBlank()) {
return subnetGroups.scan(key -> true);
}
return List.of(subnetGroups.get(name)
.orElseThrow(() -> new AwsException("CacheSubnetGroupNotFoundFault",
"Cache subnet group " + name + " not found.", 400)));
}
/** Replaces the description and, when subnets are given, the whole subnet set. */
public CacheSubnetGroup modifyCacheSubnetGroup(String name, String description, List<String> subnetIds) {
validateSubnetGroupName(name);
synchronized (lockFor("sng:" + name)) {
CacheSubnetGroup existing = subnetGroups.get(name)
.orElseThrow(() -> new AwsException("CacheSubnetGroupNotFoundFault",
"Cache subnet group " + name + " not found.", 400));
String effectiveDescription = description == null ? existing.getDescription() : description;
CacheSubnetGroup updated;
if (subnetIds == null || subnetIds.isEmpty()) {
// No subnets given means none change, so the stored ones are kept as they are:
// re-resolving them would fail a description-only change if a subnet had since
// been deleted from EC2.
updated = new CacheSubnetGroup(name, effectiveDescription, existing.getVpcId(),
existing.getSubnetAvailabilityZones());
} else {
updated = buildSubnetGroup(name, effectiveDescription, subnetIds);
}
updated.setTags(existing.getTags());
subnetGroups.put(name, updated);
return updated;
}
}
public void deleteCacheSubnetGroup(String name) {
validateSubnetGroupName(name);
synchronized (lockFor("sng:" + name)) {
if (subnetGroups.get(name).isEmpty()) {
throw new AwsException("CacheSubnetGroupNotFoundFault",
"Cache Subnet Group " + name + " does not exist.", 400);
}
subnetGroups.delete(name);
}
LOG.infov("Deleted cache subnet group {0}", name);
}
private CacheSubnetGroup buildSubnetGroup(String name, String description, List<String> subnetIds) {
if (subnetIds == null || subnetIds.isEmpty()) {
throw new AwsException("InvalidParameterValue",
"The parameter SubnetIds must be provided.", 400);
}
// The caller's region, not the configured default: subnets exist in the region they were
// created in, and the ARN this group is reported under is built from that same region.
String region = regionResolver.getRegion();
List<Subnet> resolved = ec2Service.describeSubnets(region, subnetIds, Map.of());
if (resolved.size() != subnetIds.size()) {
throw new AwsException("InvalidParameterValue",
"Some input subnets in :[" + String.join(", ", subnetIds) + "] are invalid.", 400);
}
String vpcId = resolved.getFirst().getVpcId();
List<String> foreign = resolved.stream()
.filter(subnet -> subnet.getVpcId() != null && !vpcId.equals(subnet.getVpcId()))
.map(Subnet::getSubnetId)
.toList();
if (!foreign.isEmpty()) {
throw new AwsException("InvalidSubnet", "Subnets " + resolved.getFirst().getSubnetId()
+ " and " + foreign.getFirst() + " are not in the same VPC.", 400);
}
// In the order the caller gave them: describeSubnets answers in the store's scan order,
// which would make the reported order of a group's subnets arbitrary between calls.
Map<String, String> zoneBySubnet = new LinkedHashMap<>();
resolved.forEach(subnet -> zoneBySubnet.put(subnet.getSubnetId(), subnet.getAvailabilityZone()));
Map<String, String> availabilityZones = new LinkedHashMap<>();
subnetIds.forEach(id -> availabilityZones.put(id, zoneBySubnet.get(id)));
return new CacheSubnetGroup(name, description, vpcId, availabilityZones);
}
/**
* Subnet group names take the same identifier rule as parameter group names.
*
* <p>The not-found faults do not match, though, and the difference is AWS's: the subnet-group
* fault keeps its {@code Fault} suffix on the wire and is a 400, while the parameter-group one
* drops the suffix and is a 404. Both are declared that way in the service model.
*/
private static void validateSubnetGroupName(String name) {
if (name == null || name.isBlank() || !PARAMETER_GROUP_NAME.matcher(name).matches()) {
throw new AwsException("InvalidParameterValue",
"The parameter CacheSubnetGroupName is not a valid identifier. Identifiers must "
+ "begin with a letter; must contain only ASCII letters, digits, and hyphens; "
+ "and must not end with a hyphen or contain two consecutive hyphens.", 400);
}
}
// ── Cache Parameter Groups ────────────────────────────────────────────────
/** The families AWS accepts, and validates a create against. */
@@ -0,0 +1,51 @@
package io.github.hectorvent.floci.services.elasticache.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.LinkedHashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class CacheSubnetGroup {
private String name;
private String description;
/** Taken from the subnets, which is where AWS gets it: a group cannot span VPCs. */
private String vpcId;
/** Subnet id to availability zone, in the order the subnets were given. */
private Map<String, String> subnetAvailabilityZones = new LinkedHashMap<>();
private Map<String, String> tags = new LinkedHashMap<>();
public CacheSubnetGroup() {
}
public CacheSubnetGroup(String name, String description, String vpcId,
Map<String, String> subnetAvailabilityZones) {
this.name = name;
this.description = description;
this.vpcId = vpcId;
setSubnetAvailabilityZones(subnetAvailabilityZones);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
}
public Map<String, String> getSubnetAvailabilityZones() { return subnetAvailabilityZones; }
public void setSubnetAvailabilityZones(Map<String, String> subnetAvailabilityZones) {
this.subnetAvailabilityZones = subnetAvailabilityZones == null
? new LinkedHashMap<>() : new LinkedHashMap<>(subnetAvailabilityZones);
}
}
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
@@ -58,7 +60,9 @@ class ElastiCacheServiceTest {
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
service = new ElastiCacheService(containerManager, proxyManager, storageFactory, config);
Ec2Service ec2Service = org.mockito.Mockito.mock(Ec2Service.class);
service = new ElastiCacheService(containerManager, proxyManager, storageFactory, config,
ec2Service, new RegionResolver("us-east-1", "000000000000"));
}
@Test
@@ -0,0 +1,257 @@
package io.github.hectorvent.floci.services.elasticache;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* Cache subnet groups over the Query protocol.
*
* <p>The VPC and each subnet's availability zone are read from the subnets, as AWS reads them, so
* these tests create real subnets in the emulator's EC2 first: a group cannot be answered for
* subnets that do not exist.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElastiCacheSubnetGroupIntegrationTest {
private static final String GROUP = "int-test-sng";
private static final String EC_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260412/%s/ec2/aws4_request";
private static String firstSubnet;
private static String secondSubnet;
private static String vpcId;
private static io.restassured.specification.RequestSpecification elasticache(String action) {
return given().header("Authorization", EC_AUTH)
.formParam("Action", action)
.formParam("Version", "2015-02-02");
}
private static String ec2(String region, String action, String... formParams) {
var request = given().header("Authorization", EC2_AUTH.formatted(region))
.formParam("Action", action)
.formParam("Version", "2016-11-15");
for (int i = 0; i < formParams.length; i += 2) {
request = request.formParam(formParams[i], formParams[i + 1]);
}
return request.when().post("/").then().statusCode(200).extract().body().asString();
}
private static String between(String xml, String tag) {
int start = xml.indexOf("<" + tag + ">") + tag.length() + 2;
return xml.substring(start, xml.indexOf("</" + tag + ">", start));
}
@Test
@Order(1)
void createSubnetsToPlaceTheGroupIn() {
vpcId = between(ec2("us-east-1", "CreateVpc", "CidrBlock", "10.20.0.0/16"), "vpcId");
firstSubnet = between(ec2("us-east-1", "CreateSubnet", "VpcId", vpcId, "CidrBlock", "10.20.1.0/24",
"AvailabilityZone", "us-east-1a"), "subnetId");
secondSubnet = between(ec2("us-east-1", "CreateSubnet", "VpcId", vpcId, "CidrBlock", "10.20.2.0/24",
"AvailabilityZone", "us-east-1b"), "subnetId");
}
@Test
@Order(2)
void createReportsTheVpcAndZonesTakenFromTheSubnets() {
elasticache("CreateCacheSubnetGroup")
.formParam("CacheSubnetGroupName", GROUP)
.formParam("CacheSubnetGroupDescription", "integration test")
.formParam("SubnetIds.SubnetIdentifier.1", firstSubnet)
.formParam("SubnetIds.SubnetIdentifier.2", secondSubnet)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<CacheSubnetGroupName>" + GROUP + "</CacheSubnetGroupName>"))
.body(containsString("<VpcId>" + vpcId + "</VpcId>"))
.body(containsString("<SubnetIdentifier>" + firstSubnet + "</SubnetIdentifier>"))
.body(containsString("<Name>us-east-1a</Name>"))
.body(containsString("<Name>us-east-1b</Name>"))
.body(containsString(":subnetgroup:" + GROUP + "</ARN>"))
// In the order they were given: the subnets are read back from a store whose scan
// order is its own, so the group would otherwise report them in an arbitrary order.
.body(org.hamcrest.Matchers.matchesPattern(
"(?s).*<SubnetIdentifier>" + firstSubnet + "</SubnetIdentifier>.*"
+ "<SubnetIdentifier>" + secondSubnet + "</SubnetIdentifier>.*"));
}
@Test
@Order(3)
void aSubnetThatDoesNotExistIsRejected() {
elasticache("CreateCacheSubnetGroup")
.formParam("CacheSubnetGroupName", "absent-subnet-sng")
.formParam("CacheSubnetGroupDescription", "x")
.formParam("SubnetIds.SubnetIdentifier.1", "subnet-00000000000000000")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("are invalid"));
}
@Test
@Order(3)
void subnetsFromTwoVpcsAreRejected() {
String otherVpc = between(ec2("us-east-1", "CreateVpc", "CidrBlock", "10.21.0.0/16"), "vpcId");
String otherSubnet = between(ec2("us-east-1", "CreateSubnet", "VpcId", otherVpc, "CidrBlock", "10.21.1.0/24",
"AvailabilityZone", "us-east-1a"), "subnetId");
elasticache("CreateCacheSubnetGroup")
.formParam("CacheSubnetGroupName", "cross-vpc-sng")
.formParam("CacheSubnetGroupDescription", "x")
.formParam("SubnetIds.SubnetIdentifier.1", firstSubnet)
.formParam("SubnetIds.SubnetIdentifier.2", otherSubnet)
.when().post("/")
.then()
.statusCode(400)
.body(containsString("are not in the same VPC"));
}
@Test
@Order(3)
void duplicateAndUnknownGroupsCarryTheirOwnErrors() {
elasticache("CreateCacheSubnetGroup")
.formParam("CacheSubnetGroupName", GROUP)
.formParam("CacheSubnetGroupDescription", "again")
.formParam("SubnetIds.SubnetIdentifier.1", firstSubnet)
.when().post("/")
.then()
.statusCode(400)
.body(containsString("CacheSubnetGroupAlreadyExists"));
// 400, not 404: the subnet-group fault is declared that way, unlike the parameter-group
// one a few hundred lines up, which really is a 404.
elasticache("DescribeCacheSubnetGroups")
.formParam("CacheSubnetGroupName", "no-such-sng")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("Cache subnet group no-such-sng not found"));
}
@Test
@Order(4)
void modifyReplacesTheDescriptionAndSubnets() {
elasticache("ModifyCacheSubnetGroup")
.formParam("CacheSubnetGroupName", GROUP)
.formParam("CacheSubnetGroupDescription", "changed")
.formParam("SubnetIds.SubnetIdentifier.1", firstSubnet)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<CacheSubnetGroupDescription>changed</CacheSubnetGroupDescription>"))
.body(containsString("<SubnetIdentifier>" + firstSubnet + "</SubnetIdentifier>"));
// The subnet dropped by the modify is gone from the group.
elasticache("DescribeCacheSubnetGroups")
.formParam("CacheSubnetGroupName", GROUP)
.when().post("/")
.then()
.statusCode(200)
.body(org.hamcrest.Matchers.not(containsString(secondSubnet)));
}
@Test
@Order(4)
void tagsGivenAtCreateAreKeptAndListed() {
// Dropping them would leave terraform with a diff it can never settle.
elasticache("CreateCacheSubnetGroup")
.formParam("CacheSubnetGroupName", "tagged-sng")
.formParam("CacheSubnetGroupDescription", "tagged")
.formParam("SubnetIds.SubnetIdentifier.1", firstSubnet)
.formParam("Tags.Tag.1.Key", "env")
.formParam("Tags.Tag.1.Value", "prod")
.when().post("/")
.then()
.statusCode(200);
elasticache("ListTagsForResource")
.formParam("ResourceName",
"arn:aws:elasticache:us-east-1:000000000000:subnetgroup:tagged-sng")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<Key>env</Key>"))
.body(containsString("<Value>prod</Value>"));
}
@Test
@Order(4)
void aDescriptionOnlyModifyLeavesTheSubnetsAlone() {
// Nothing is said about subnets, so none change — and the stored ones are not re-resolved,
// which would fail this call if one of them had since been deleted from EC2.
elasticache("ModifyCacheSubnetGroup")
.formParam("CacheSubnetGroupName", "tagged-sng")
.formParam("CacheSubnetGroupDescription", "description only")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<CacheSubnetGroupDescription>description only</CacheSubnetGroupDescription>"))
.body(containsString("<SubnetIdentifier>" + firstSubnet + "</SubnetIdentifier>"));
// And the tags survive a modify.
elasticache("ListTagsForResource")
.formParam("ResourceName",
"arn:aws:elasticache:us-east-1:000000000000:subnetgroup:tagged-sng")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<Key>env</Key>"));
elasticache("DeleteCacheSubnetGroup")
.formParam("CacheSubnetGroupName", "tagged-sng")
.when().post("/").then().statusCode(200);
}
@Test
@Order(4)
void subnetsAreResolvedInTheCallersRegion() {
// Subnets exist in the region they were created in. Resolving against the configured
// default region instead would reject these as invalid, and would report the group under
// an eu-west-1 ARN built from subnets read somewhere else.
String euVpc = between(ec2("eu-west-1", "CreateVpc", "CidrBlock", "10.30.0.0/16"), "vpcId");
String euSubnet = between(ec2("eu-west-1", "CreateSubnet", "VpcId", euVpc,
"CidrBlock", "10.30.1.0/24", "AvailabilityZone", "eu-west-1a"), "subnetId");
given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260412/eu-west-1/elasticache/aws4_request")
.formParam("Action", "CreateCacheSubnetGroup")
.formParam("Version", "2015-02-02")
.formParam("CacheSubnetGroupName", "eu-west-sng")
.formParam("CacheSubnetGroupDescription", "other region")
.formParam("SubnetIds.SubnetIdentifier.1", euSubnet)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<VpcId>" + euVpc + "</VpcId>"))
.body(containsString("<Name>eu-west-1a</Name>"))
.body(containsString("arn:aws:elasticache:eu-west-1:"));
}
@Test
@Order(5)
void deleteRemovesItAndSaysSoDifferentlyTheSecondTime() {
elasticache("DeleteCacheSubnetGroup")
.formParam("CacheSubnetGroupName", GROUP)
.when().post("/")
.then()
.statusCode(200);
// AWS words the delete's not-found differently from the describe's.
elasticache("DeleteCacheSubnetGroup")
.formParam("CacheSubnetGroupName", GROUP)
.when().post("/")
.then()
.statusCode(400)
.body(containsString("Cache Subnet Group " + GROUP + " does not exist"));
}
}