feat(elasticache): support cache parameter groups (#2392)

* feat(elasticache): support cache parameter groups

CreateCacheParameterGroup was unsupported, so a Redis module that sets any
parameter could not apply at all — most set at least maxmemory-policy. The
describe was a stub that answered with an empty list whatever was asked of it.

Adds the group surface over the Query protocol:

- CreateCacheParameterGroup, DescribeCacheParameterGroups,
  ModifyCacheParameterGroup, DescribeCacheParameters, DeleteCacheParameterGroup
- ListTagsForResource for a parameter group ARN, without which the tags a create
  carries would be stored and never readable
- the default.* groups AWS publishes for all 13 families, derived rather than
  stored: nothing can modify or delete them, so persisting them would only add
  records to migrate and a writer to race

Taken from a live account: the create response and its ARN, IsGlobal, and the
error each rejection carries — CacheParameterGroupAlreadyExists for a duplicate,
CacheParameterGroupNotFound for an unknown group, and the identifier rule that
rejects a name containing a dot, which is also how AWS refuses to delete a
default group.

Each writer takes one monitor keyed by the group name before it reads. Guarding
the record cannot serve a create, which has no record yet, so two of them would
both pass the existence check; and a modify that resolved its record before
locking would write back a group a concurrent delete had removed.

floci does not carry AWS's per-family catalogue of parameter names, so it stores
what a caller sets and reports it with source "user". Rejecting names missing
from a partial catalogue would refuse configurations AWS accepts, so nothing is
rejected on that basis, and a request for system parameters returns none rather
than reporting user parameters under another source.

* fix(elasticache): answer tags for the ARN that was asked about

ListTagsForResource read the trailing name out of the ARN and ignored the rest,
so an ARN naming another account or region was answered with this caller's
group of the same name — a response describing a different resource than the
request identified.

The ARN is now checked before it is used, with the errors AWS gives for each:
InvalidARN for a string that is not seven components, "Unauthorized call.
Please check the region or customer id" for another region, "The resource ARN
does not belong to the caller's account." for another account, and
"<name> is not present" for a group that does not exist, which is worded
differently from the describe's not-found.

Tightening the tolerated exception in the race test, as review asked, turned up
a second problem: a modify whose group had been deleted reported "is a default
group and cannot be modified", because absence from the store was read as
proof of a published default. The two are now told apart, and both errors are
asserted directly rather than only when the race happens to expose them.

* fix(elasticache): check every component of a tag ARN, not only region and account

An ARN in another service's namespace was accepted as long as its region and
account matched, so arn:aws:rds:<region>:<account>:parametergroup:<name> was
answered with the ElastiCache group of that name — tags for a resource the
caller did not ask about.

The partition and service are checked too, with the errors AWS gives: "partition
field is wrong. Expected value is aws" and "service field is wrong. Expected
value is elasticache".

* fix(elasticache): word each parameter group not-found the way AWS words it

Three actions, three sentences on a live account. Delete omits the space after
the type name — that is verbatim, and the line now says so, because it reads
like a typo and the next person to tidy it would silently stop matching AWS.

Modify was the one that was actually wrong: it answered with describe's
sentence. A live account words it "CacheParameterGroup not found: <name>",
which is neither describe's nor delete's.

Pinned by a test that asserts all three, so the odd one cannot be quietly
aligned with the others.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-19 15:25:05 -04:00
1 parent f8b07a78ff
commit 6b628179f3
7 files changed
+937 -5

No files matched your search

@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryResponse;
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.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
@@ -20,7 +21,9 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Query-protocol handler for all ElastiCache actions (form-encoded POST, XML response).
@@ -63,7 +66,12 @@ public class ElastiCacheQueryHandler {
case "DescribeCacheClusters" -> handleDescribeCacheClusters(params);
case "DeleteCacheCluster" -> handleDeleteCacheCluster(params);
case "DescribeCacheSubnetGroups" -> handleDescribeCacheSubnetGroups(params);
case "CreateCacheParameterGroup" -> handleCreateCacheParameterGroup(params);
case "DescribeCacheParameterGroups" -> handleDescribeCacheParameterGroups(params);
case "ModifyCacheParameterGroup" -> handleModifyCacheParameterGroup(params);
case "DescribeCacheParameters" -> handleDescribeCacheParameters(params);
case "DeleteCacheParameterGroup" -> handleDeleteCacheParameterGroup(params);
case "ListTagsForResource" -> handleListTagsForResource(params);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.EC, 400);
};
@@ -292,11 +300,172 @@ public class ElastiCacheQueryHandler {
return Response.ok(AwsQueryResponse.envelope("DescribeCacheSubnetGroups", AwsNamespaces.EC, xml.build())).build();
}
private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String> params) {
try {
CacheParameterGroup group = service.createCacheParameterGroup(
params.getFirst("CacheParameterGroupName"),
params.getFirst("CacheParameterGroupFamily"),
params.getFirst("Description"),
parseTags(params));
var xml = new XmlBuilder();
appendParameterGroup(xml, group);
return Response.ok(AwsQueryResponse.envelope("CreateCacheParameterGroup", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDescribeCacheParameterGroups(MultivaluedMap<String, String> params) {
// Cache parameter 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("CacheParameterGroups").end("CacheParameterGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheParameterGroups", AwsNamespaces.EC, xml.build())).build();
try {
List<CacheParameterGroup> groups =
service.describeCacheParameterGroups(params.getFirst("CacheParameterGroupName"));
var xml = new XmlBuilder().start("CacheParameterGroups");
groups.forEach(group -> appendParameterGroup(xml, group));
xml.end("CacheParameterGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheParameterGroups", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleModifyCacheParameterGroup(MultivaluedMap<String, String> params) {
try {
String name = params.getFirst("CacheParameterGroupName");
service.modifyCacheParameterGroup(name, parseParameterNameValues(params));
var xml = new XmlBuilder().elem("CacheParameterGroupName", name);
return Response.ok(AwsQueryResponse.envelope("ModifyCacheParameterGroup", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDescribeCacheParameters(MultivaluedMap<String, String> params) {
try {
CacheParameterGroup group = service.requireParameterGroup(params.getFirst("CacheParameterGroupName"));
// floci stores only what a caller set, so every parameter it can report has source "user".
// A request for another source gets the empty list rather than invented defaults.
String source = params.getFirst("Source");
boolean includeUserParameters = source == null || source.isBlank() || "user".equals(source);
var xml = new XmlBuilder().start("Parameters");
if (includeUserParameters) {
group.getParameters().forEach((name, value) -> xml
.start("Parameter")
.elem("ParameterName", name)
.elem("ParameterValue", value)
.elem("Source", "user")
.elem("IsModifiable", true)
.end("Parameter"));
}
xml.end("Parameters")
.start("CacheNodeTypeSpecificParameters").end("CacheNodeTypeSpecificParameters");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheParameters", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
/**
* Tags for a resource ARN. Only parameter groups carry tags in floci, so any other ARN reports
* none — which is what floci knows, rather than a guess at what AWS would hold.
*/
private Response handleListTagsForResource(MultivaluedMap<String, String> params) {
try {
String resourceName = params.getFirst("ResourceName");
String[] arn = resourceName == null ? new String[0] : resourceName.split(":", -1);
if (arn.length != 7 || !"arn".equals(arn[0])) {
throw new AwsException("InvalidARN", "Input ARN string does not have 7 components.", 400);
}
// Every component names part of the resource, so each is checked before the name is
// used: a partition, service, region or account that is not this one asks about a
// different resource, and answering from the trailing name would describe the wrong.
if (!"aws".equals(arn[1])) {
throw new AwsException("InvalidARN", "partition field is wrong. Expected value is aws", 400);
}
if (!"elasticache".equals(arn[2])) {
throw new AwsException("InvalidARN",
"service field is wrong. Expected value is elasticache", 400);
}
if (!regionResolver.getRegion().equals(arn[3])) {
throw new AwsException("InvalidParameterValue",
"Unauthorized call. Please check the region or customer id", 400);
}
if (!regionResolver.getAccountId().equals(arn[4])) {
throw new AwsException("InvalidParameterValue",
"The resource ARN does not belong to the caller's account.", 400);
}
Map<String, String> tags = Map.of();
if ("parametergroup".equals(arn[5])) {
tags = service.findParameterGroup(arn[6])
.orElseThrow(() -> new AwsException("CacheParameterGroupNotFound",
arn[6] + " is not present", 404))
.getTags();
}
var xml = new XmlBuilder().start("TagList");
tags.forEach((key, value) -> xml.start("Tag")
.elem("Key", key)
.elem("Value", value)
.end("Tag"));
xml.end("TagList");
return Response.ok(AwsQueryResponse.envelope("ListTagsForResource", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDeleteCacheParameterGroup(MultivaluedMap<String, String> params) {
try {
service.deleteCacheParameterGroup(params.getFirst("CacheParameterGroupName"));
return Response.ok(AwsQueryResponse.envelope("DeleteCacheParameterGroup", AwsNamespaces.EC, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private void appendParameterGroup(XmlBuilder xml, CacheParameterGroup group) {
xml.start("CacheParameterGroup")
.elem("CacheParameterGroupName", group.getName())
.elem("CacheParameterGroupFamily", group.getFamily())
.elem("Description", group.getDescription())
.elem("IsGlobal", false)
.elem("ARN", parameterGroupArn(group.getName()))
.end("CacheParameterGroup");
}
private String parameterGroupArn(String name) {
return "arn:aws:elasticache:" + regionResolver.getRegion() + ":"
+ regionResolver.getAccountId() + ":parametergroup:" + name;
}
/**
* Reads a Query-protocol list of pairs under every spelling it arrives in. The member element
* takes its name from the shape's {@code locationName} — {@code Tag} and
* {@code ParameterNameValue} here, not {@code member} — and SDKs differ, so each is tried.
*/
private static Map<String, String> parsePairs(MultivaluedMap<String, String> params,
List<String> prefixes, String keyName, String valueName) {
Map<String, String> pairs = new LinkedHashMap<>();
for (String prefix : prefixes) {
for (int i = 1; ; i++) {
String key = params.getFirst(prefix + "." + i + "." + keyName);
if (key == null) {
break;
}
pairs.put(key, params.getFirst(prefix + "." + i + "." + valueName));
}
}
return pairs;
}
private static Map<String, String> parseTags(MultivaluedMap<String, String> params) {
return parsePairs(params, List.of("Tags.Tag", "Tags.member", "Tag"), "Key", "Value");
}
private static Map<String, String> parseParameterNameValues(MultivaluedMap<String, String> params) {
return parsePairs(params,
List.of("ParameterNameValues.ParameterNameValue", "ParameterNameValues.member"),
"ParameterName", "ParameterValue");
}
// ── IAM Token Validation ──────────────────────────────────────────────────
@@ -8,6 +8,7 @@ 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.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
@@ -18,12 +19,15 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* Core ElastiCache business logic — replication groups and users.
@@ -36,11 +40,13 @@ public class ElastiCacheService {
private final StorageBackend<String, ReplicationGroup> groups;
private final StorageBackend<String, ElastiCacheUser> users;
private final StorageBackend<String, CacheParameterGroup> parameterGroups;
private final ElastiCacheContainerManager containerManager;
private final ElastiCacheProxyManager proxyManager;
private final EmulatorConfig config;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final Set<String> provisioningGroupIds = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<String, Object> parameterGroupLocks = new ConcurrentHashMap<>();
@Inject
public ElastiCacheService(ElastiCacheContainerManager containerManager,
@@ -54,6 +60,8 @@ public class ElastiCacheService {
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>>() {});
}
public ReplicationGroup createReplicationGroup(String groupId, String description,
@@ -312,4 +320,156 @@ public class ElastiCacheService {
private void releaseProxyPort(int port) {
usedPorts.remove(port);
}
// ── Cache Parameter Groups ────────────────────────────────────────────────
/** The families AWS accepts, and validates a create against. */
private static final List<String> PARAMETER_GROUP_FAMILIES = List.of(
"memcached1.4", "memcached1.5", "memcached1.6",
"redis2.6", "redis2.8", "redis3.2", "redis4.0", "redis5.0", "redis6.x", "redis7",
"valkey7", "valkey8", "valkey9");
/** The families AWS also publishes a cluster-mode default for. */
private static final List<String> CLUSTER_MODE_FAMILIES = List.of(
"redis3.2", "redis4.0", "redis5.0", "redis6.x", "redis7", "valkey7", "valkey8", "valkey9");
/**
* Names begin with a letter and hold only letters, digits and single interior hyphens. AWS
* applies this to deletes as well as creates, which is why a {@code default.*} group cannot be
* deleted: the dot fails this rule before anything looks the group up.
*/
private static final Pattern PARAMETER_GROUP_NAME =
Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$");
/**
* The {@code default.*} groups AWS publishes. Derived rather than stored: nothing can modify or
* delete them, so persisting them would only add records to migrate, a writer to race, and an
* install predating this that needs backfilling.
*/
private static List<CacheParameterGroup> defaultParameterGroups() {
List<CacheParameterGroup> defaults = new ArrayList<>();
for (String family : PARAMETER_GROUP_FAMILIES) {
defaults.add(new CacheParameterGroup("default." + family, family,
"Default parameter group for " + family));
if (CLUSTER_MODE_FAMILIES.contains(family)) {
defaults.add(new CacheParameterGroup("default." + family + ".cluster.on", family,
"Customized default parameter group for " + family + " with cluster mode on"));
}
}
return defaults;
}
private static void validateParameterGroupName(String name) {
if (name == null || name.isBlank() || !PARAMETER_GROUP_NAME.matcher(name).matches()) {
throw new AwsException("InvalidParameterValue",
"The parameter CacheParameterGroupName 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);
}
}
/**
* One monitor per group name, taken by every writer before it reads. Guarding the record itself
* would be too late: a create has no record yet, so two of them could both pass the existence
* check, and a modify that resolved its record before locking would write back one a concurrent
* delete had already removed.
*/
private Object lockFor(String parameterGroupName) {
return parameterGroupLocks.computeIfAbsent(parameterGroupName, key -> new Object());
}
public CacheParameterGroup createCacheParameterGroup(String name, String family,
String description, Map<String, String> tags) {
validateParameterGroupName(name);
if (family == null || !PARAMETER_GROUP_FAMILIES.contains(family)) {
throw new AwsException("InvalidParameterValue",
"CacheParameterGroupFamily " + family + " is not a valid parameter group family.", 400);
}
synchronized (lockFor(name)) {
if (parameterGroups.get(name).isPresent()) {
throw new AwsException("CacheParameterGroupAlreadyExists",
"Parameter group " + name + " already exists", 400);
}
CacheParameterGroup group = new CacheParameterGroup(name, family, description);
if (tags != null) {
group.setTags(new LinkedHashMap<>(tags));
}
parameterGroups.put(name, group);
LOG.infov("Created cache parameter group {0} ({1})", name, family);
return group;
}
}
/** Every group, or the one named. The published defaults are listed, as AWS lists them. */
public List<CacheParameterGroup> describeCacheParameterGroups(String name) {
if (name == null || name.isBlank()) {
List<CacheParameterGroup> all = new ArrayList<>(defaultParameterGroups());
all.addAll(parameterGroups.scan(key -> true));
return all;
}
return List.of(requireParameterGroup(name));
}
private static boolean isDefaultParameterGroup(String name) {
return defaultParameterGroups().stream().anyMatch(group -> group.getName().equals(name));
}
/** The group by that name, whether stored or one of the published defaults. */
public java.util.Optional<CacheParameterGroup> findParameterGroup(String name) {
return parameterGroups.get(name)
.or(() -> defaultParameterGroups().stream()
.filter(group -> group.getName().equals(name))
.findFirst());
}
public CacheParameterGroup requireParameterGroup(String name) {
return findParameterGroup(name)
.orElseThrow(() -> new AwsException("CacheParameterGroupNotFound",
"CacheParameterGroup " + name + " not found.", 404));
}
/**
* Records the parameters a caller sets. floci does not carry AWS's per-family catalogue of
* parameter names, so it cannot tell a real name from a typo and does not try: rejecting names
* missing from a partial catalogue would refuse configurations AWS accepts.
*/
public void modifyCacheParameterGroup(String name, Map<String, String> parameters) {
synchronized (lockFor(name)) {
// Read inside the lock: a record resolved before it could have been deleted since, and
// writing it back would restore the group the delete removed.
CacheParameterGroup group = parameterGroups.get(name).orElse(null);
if (group == null) {
// Absent from the store means one of two different things, and they do not share
// an error: a published default was never stored, whereas anything else is gone.
if (isDefaultParameterGroup(name)) {
throw new AwsException("InvalidParameterValue",
"The parameter group " + name + " is a default group and cannot be modified.", 400);
}
throw new AwsException("CacheParameterGroupNotFound",
"CacheParameterGroup not found: " + name, 404);
}
Map<String, String> updated = new LinkedHashMap<>(group.getParameters());
updated.putAll(parameters);
group.setParameters(updated);
parameterGroups.put(name, group);
}
LOG.debugv("Modified {0} parameter(s) on cache parameter group {1}", parameters.size(), name);
}
public void deleteCacheParameterGroup(String name) {
validateParameterGroupName(name);
synchronized (lockFor(name)) {
if (parameterGroups.get(name).isEmpty()) {
// AWS emits this without the space after the type name. Deliberately not
// corrected: matching it is the point, and each action words this differently —
// describe says "CacheParameterGroup <name> not found." and modify says
// "CacheParameterGroup not found: <name>".
throw new AwsException("CacheParameterGroupNotFound",
"CacheParameterGroupnot found: " + name, 404);
}
parameterGroups.delete(name);
}
LOG.infov("Deleted cache parameter group {0}", name);
}
}
@@ -0,0 +1,47 @@
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 CacheParameterGroup {
private String name;
private String family;
private String description;
/** Only the parameters a caller set; floci does not carry AWS's per-family defaults. */
private Map<String, String> parameters = new LinkedHashMap<>();
private Map<String, String> tags = new LinkedHashMap<>();
public CacheParameterGroup() {
}
public CacheParameterGroup(String name, String family, String description) {
this.name = name;
this.family = family;
this.description = description;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getFamily() { return family; }
public void setFamily(String family) { this.family = family; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters == null ? new LinkedHashMap<>() : parameters;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new LinkedHashMap<>() : tags;
}
}