fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN (#2632)

* fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN

DescribeReplicationGroups wrote AtRestEncryptionEnabled and
SnapshotRetentionLimit as constants and never emitted KmsKeyId,
SnapshotWindow or ARN, so a group created with them drifted on the next
Terraform plan (kms_key_id forces replacement) and its tags, given at
create, could not even be asked for without an ARN. Store the four
settings and the tags on the group, resolve KmsKeyId through the KMS
store in the request's region to the key ARN a live account reports,
apply the snapshot settings from ModifyReplicationGroup, emit them with
the ARN, and answer ListTagsForResource for replicationgroup ARNs — for
the record the ARN names, since the store keys groups by id alone.
Delete and modify of a group now share one monitor, so a modify cannot
write the group back after a delete removed it. Validation and wording
follow a live account.

Closes #2615

* fix(elasticache): refuse a KMS key with encryption at rest omitted, and change nothing on a refused modify

An omitted AtRestEncryptionEnabled is false on a live account and a
KmsKeyId is refused with it the same way as with an explicit false.
ModifyReplicationGroup applied the snapshot settings to the store's own
object before validating the user ids, so a request refused for an
unknown user had already changed the group; every check now runs before
any change.

* fix(elasticache): read AtRestEncryptionEnabled as a live account does, and refuse an empty snapshot window

A live account reads any AtRestEncryptionEnabled value that is not
"false" as true — banana, yes and "TRUE " all created an encrypted
group — so the flag is read the same way rather than parsed strictly.
A snapshot window whose end equals its start was measured as a full day;
a live account refuses it as shorter than an hour.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-27 16:53:33 -04:00
1 parent 4affa05cea
commit 75f8f42d5f
9 files changed
+732 -35

No files matched your search

@@ -13,6 +13,7 @@ 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;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -105,7 +106,8 @@ public class ElastiCacheQueryHandler {
try {
ReplicationGroup group = service.createReplicationGroup(
groupId, description != null ? description : "", authMode, authToken, region);
groupId, description != null ? description : "", authMode, authToken, region,
replicationGroupSettings(params), parseTags(params));
String result = replicationGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
} catch (AwsException e) {
@@ -113,6 +115,28 @@ public class ElastiCacheQueryHandler {
}
}
private static ReplicationGroupSettings replicationGroupSettings(MultivaluedMap<String, String> params) {
String atRest = params.getFirst("AtRestEncryptionEnabled");
// A live account reads any value that is not "false" as true — "banana", "yes" and
// "TRUE " all created an encrypted group — so the flag is read the same way here.
return new ReplicationGroupSettings(
atRest == null ? null : !"false".equalsIgnoreCase(atRest.trim()),
params.getFirst("KmsKeyId"),
optionalInt(params.getFirst("SnapshotRetentionLimit")),
params.getFirst("SnapshotWindow"));
}
private static Integer optionalInt(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", "Value " + value + " is not a valid integer.", 400);
}
}
private Response handleDescribeReplicationGroups(MultivaluedMap<String, String> params) {
String filterId = params.getFirst("ReplicationGroupId");
try {
@@ -153,9 +177,12 @@ public class ElastiCacheQueryHandler {
List<String> userIdsToAdd = extractMemberList(params, "UserGroupIdsToAdd.member.");
List<String> userIdsToRemove = extractMemberList(params, "UserGroupIdsToRemove.member.");
try {
// AtRestEncryptionEnabled and KmsKeyId are fixed at create and not in the modify shape
ReplicationGroupSettings settings = new ReplicationGroupSettings(null, null,
optionalInt(params.getFirst("SnapshotRetentionLimit")), params.getFirst("SnapshotWindow"));
ReplicationGroup group = service.modifyReplicationGroup(groupId,
userIdsToAdd.isEmpty() ? null : userIdsToAdd,
userIdsToRemove.isEmpty() ? null : userIdsToRemove);
userIdsToRemove.isEmpty() ? null : userIdsToRemove, settings);
String result = replicationGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("ModifyReplicationGroup", AwsNamespaces.EC, result)).build();
} catch (AwsException e) {
@@ -478,6 +505,15 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
}
Map<String, String> tags = Map.of();
if ("replicationgroup".equals(arn[5])) {
// the store keys groups by id alone; the record must be the one the ARN names
ReplicationGroup group = service.getReplicationGroup(arn[6]);
if (group.getArn() != null && !group.getArn().equalsIgnoreCase(resourceName)) {
throw new AwsException("ReplicationGroupNotFoundFault",
"Replication group " + arn[6] + " not found.", 404);
}
tags = group.getTags();
}
if ("subnetgroup".equals(arn[5])) {
tags = service.describeCacheSubnetGroups(arn[6]).getFirst().getTags();
}
@@ -611,11 +647,19 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
.elem("Status", g.getStatus().name().toLowerCase())
.elem("AuthTokenEnabled", authTokenEnabled)
.elem("TransitEncryptionEnabled", authTokenEnabled)
.elem("AtRestEncryptionEnabled", false)
.elem("AtRestEncryptionEnabled", g.isAtRestEncryptionEnabled())
.elem("ClusterEnabled", false)
.elem("MultiAZ", "disabled")
.elem("AutomaticFailover", "disabled")
.elem("SnapshotRetentionLimit", 0L);
.elem("SnapshotRetentionLimit", (long) g.getSnapshotRetentionLimit());
xml.elem("SnapshotWindow", g.getSnapshotWindow() != null
? g.getSnapshotWindow() : ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW);
if (g.getKmsKeyId() != null) {
xml.elem("KmsKeyId", g.getKmsKeyId());
}
if (g.getArn() != null) {
xml.elem("ARN", g.getArn());
}
if (ep != null) {
xml.start("ConfigurationEndpoint")
.elem("Address", ep.address())
@@ -29,6 +29,9 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -53,6 +56,7 @@ public class ElastiCacheService implements ResourceProvider {
private final ElastiCacheContainerManager containerManager;
private final ElastiCacheProxyManager proxyManager;
private final EmulatorConfig config;
private final KmsService kmsService;
private final Ec2Service ec2Service;
private final RegionResolver regionResolver;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
@@ -65,7 +69,9 @@ public class ElastiCacheService implements ResourceProvider {
StorageFactory storageFactory,
EmulatorConfig config,
Ec2Service ec2Service,
RegionResolver regionResolver) {
RegionResolver regionResolver,
KmsService kmsService) {
this.kmsService = kmsService;
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.config = config;
@@ -83,6 +89,18 @@ public class ElastiCacheService implements ResourceProvider {
public ReplicationGroup createReplicationGroup(String groupId, String description,
AuthMode authMode, String authToken, String region) {
return createReplicationGroup(groupId, description, authMode, authToken, region,
ReplicationGroupSettings.defaults(), Map.of());
}
public ReplicationGroup createReplicationGroup(String groupId, String description,
AuthMode authMode, String authToken, String region,
ReplicationGroupSettings settings,
Map<String, String> tags) {
settings.validate();
// resolved with the other validations, before a port is taken or a container started
ReplicationGroupSettings resolvedSettings =
settings.withKmsKeyId(resolveKmsKeyArn(settings.kmsKeyId(), region));
if (groups.get(groupId).isPresent()) {
throw new AwsException("ReplicationGroupAlreadyExistsFault",
"Replication group " + groupId + " already exists.", 400);
@@ -116,6 +134,11 @@ public class ElastiCacheService implements ResourceProvider {
group.setAuthToken(authToken);
group.setArn(regionResolver.buildArn("elasticache", region, "replicationgroup:" + groupId));
group.setRegion(region);
group.setSnapshotWindow(ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW);
resolvedSettings.applyTo(group);
if (tags != null && !tags.isEmpty()) {
group.setTags(new LinkedHashMap<>(tags));
}
proxyManager.startProxy(groupId, authMode, proxyPort,
handle.getHost(), handle.getPort(),
@@ -173,41 +196,88 @@ public class ElastiCacheService implements ResourceProvider {
}
public void deleteReplicationGroup(String groupId) {
ReplicationGroup group = groups.get(groupId).orElseThrow(() ->
new AwsException("ReplicationGroupNotFoundFault",
"Replication group " + groupId + " not found.", 404));
// one monitor per group for delete and modify: a modify's read-modify-write could
// otherwise write the group back after this removed it
synchronized (lockFor("rg:" + groupId)) {
ReplicationGroup group = groups.get(groupId).orElseThrow(() ->
new AwsException("ReplicationGroupNotFoundFault",
"Replication group " + groupId + " not found.", 404));
group.setStatus(ReplicationGroupStatus.DELETING);
groups.put(groupId, group);
group.setStatus(ReplicationGroupStatus.DELETING);
groups.put(groupId, group);
proxyManager.stopProxy(groupId);
proxyManager.stopProxy(groupId);
if (group.getContainerId() != null) {
containerManager.stop(new ElastiCacheContainerHandle(
group.getContainerId(), groupId, group.getContainerHost(), group.getContainerPort()));
if (group.getContainerId() != null) {
containerManager.stop(new ElastiCacheContainerHandle(
group.getContainerId(), groupId, group.getContainerHost(), group.getContainerPort()));
}
releaseProxyPort(group.getProxyPort());
groups.delete(groupId);
LOG.infov("Replication group {0} deleted", groupId);
}
releaseProxyPort(group.getProxyPort());
groups.delete(groupId);
LOG.infov("Replication group {0} deleted", groupId);
}
public ReplicationGroup modifyReplicationGroup(String groupId, List<String> userIdsToAdd,
List<String> userIdsToRemove) {
ReplicationGroup group = getReplicationGroup(groupId);
return modifyReplicationGroup(groupId, userIdsToAdd, userIdsToRemove,
ReplicationGroupSettings.unchanged());
}
if (userIdsToAdd != null) {
for (String userId : userIdsToAdd) {
getUser(userId); // validate user exists
group.getAssociatedUserIds().add(userId);
public ReplicationGroup modifyReplicationGroup(String groupId, List<String> userIdsToAdd,
List<String> userIdsToRemove,
ReplicationGroupSettings settings) {
settings.validate();
synchronized (lockFor("rg:" + groupId)) {
ReplicationGroup group = getReplicationGroup(groupId);
// every check before any change: the store hands out its own object, so a mutation
// made before a later refusal would stay visible
if (userIdsToAdd != null) {
for (String userId : userIdsToAdd) {
getUser(userId);
}
}
settings.applyTo(group);
if (userIdsToAdd != null) {
group.getAssociatedUserIds().addAll(userIdsToAdd);
}
if (userIdsToRemove != null) {
group.getAssociatedUserIds().removeAll(userIdsToRemove);
}
}
if (userIdsToRemove != null) {
group.getAssociatedUserIds().removeAll(userIdsToRemove);
}
groups.put(groupId, group);
return group;
groups.put(groupId, group);
return group;
}
}
/**
* A live account takes the key as a key id, key ARN or alias and reports the key ARN on the
* group; a key it cannot use is one fault whatever the reason.
*/
private String resolveKmsKeyArn(String kmsKeyId, String region) {
if (kmsKeyId == null || kmsKeyId.isBlank()) {
return null;
}
if (kmsService == null) {
throw new IllegalStateException("ElastiCacheService was built without a KmsService; "
+ "a KmsKeyId cannot be resolved");
}
KmsKey key;
try {
key = kmsService.describeKey(kmsKeyId, region);
} catch (AwsException e) {
throw kmsKeyNotAccessible(kmsKeyId);
}
if (!key.isEnabled() || "PendingDeletion".equals(key.getKeyState())) {
throw kmsKeyNotAccessible(kmsKeyId);
}
return key.getArn();
}
private static AwsException kmsKeyNotAccessible(String kmsKeyId) {
return new AwsException("InvalidParameterValue",
"KMS key does not exist with key id: " + kmsKeyId, 400);
}
public ElastiCacheUser createUser(String userId, String userName, AuthMode authMode,
@@ -4,6 +4,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
@RegisterForReflection
@@ -20,6 +22,11 @@ public class ReplicationGroup {
private Set<String> associatedUserIds = new HashSet<>();
private String arn;
private String region;
private boolean atRestEncryptionEnabled;
private String kmsKeyId;
private int snapshotRetentionLimit;
private String snapshotWindow;
private Map<String, String> tags = new LinkedHashMap<>();
// Transient fields — not persisted, restored on container restart
private transient String containerId;
@@ -78,6 +85,21 @@ public class ReplicationGroup {
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
public boolean isAtRestEncryptionEnabled() { return atRestEncryptionEnabled; }
public void setAtRestEncryptionEnabled(boolean atRestEncryptionEnabled) { this.atRestEncryptionEnabled = atRestEncryptionEnabled; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
public int getSnapshotRetentionLimit() { return snapshotRetentionLimit; }
public void setSnapshotRetentionLimit(int snapshotRetentionLimit) { this.snapshotRetentionLimit = snapshotRetentionLimit; }
public String getSnapshotWindow() { return snapshotWindow; }
public void setSnapshotWindow(String snapshotWindow) { this.snapshotWindow = snapshotWindow; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new LinkedHashMap<>() : tags; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.elasticache.model;
import io.github.hectorvent.floci.core.common.AwsException;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The encryption and snapshot settings of a replication group as a request carries them: a null
* member is one the request left out — the AWS default on create, unchanged on modify.
*/
@RegisterForReflection
public record ReplicationGroupSettings(Boolean atRestEncryptionEnabled,
String kmsKeyId,
Integer snapshotRetentionLimit,
String snapshotWindow) {
private static final Pattern TIME = Pattern.compile("^([01]\\d|2[0-3]):([0-5]\\d)$");
private static final int MINUTES_PER_DAY = 24 * 60;
private static final int MINIMUM_WINDOW_MINUTES = 60;
/** Where AWS picks a random one-hour window, Floci picks this. */
public static final String DEFAULT_SNAPSHOT_WINDOW = "00:00-01:00";
public static ReplicationGroupSettings defaults() {
return new ReplicationGroupSettings(null, null, null, null);
}
public static ReplicationGroupSettings unchanged() {
return defaults();
}
/** The checks a live account applies to these parameters, with its wording. */
public void validate() {
// an omitted AtRestEncryptionEnabled is false on a live account, and refused the same way
if (kmsKeyId != null && !kmsKeyId.isBlank() && !Boolean.TRUE.equals(atRestEncryptionEnabled)) {
throw new AwsException("InvalidParameterCombination",
"Please enable encryption at rest to use Customer Managed CMK", 400);
}
if (snapshotRetentionLimit != null && (snapshotRetentionLimit < 0 || snapshotRetentionLimit > 35)) {
throw new AwsException("InvalidParameterValue", "Invalid snapshot retention limit: "
+ snapshotRetentionLimit + ". Retention limit must be between 0 and 35.", 400);
}
if (snapshotWindow != null) {
parseWindow(snapshotWindow);
}
}
private static void parseWindow(String window) {
String[] parts = window.split("-", -1);
if (parts.length != 2) {
throw invalidWindow(window);
}
int start = minuteOfDay(parts[0], window);
int end = minuteOfDay(parts[1], window);
// an end before the start wraps midnight; an end equal to the start is an empty window,
// which a live account refuses as shorter than an hour, not a full day
if (end < start) {
end += MINUTES_PER_DAY;
}
if (end - start < MINIMUM_WINDOW_MINUTES) {
throw new AwsException("InvalidParameterValue",
"Snapshot window must be at least " + MINIMUM_WINDOW_MINUTES + " minutes.", 400);
}
}
private static int minuteOfDay(String time, String window) {
Matcher m = TIME.matcher(time);
if (!m.matches()) {
throw invalidWindow(window);
}
return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
}
private static AwsException invalidWindow(String window) {
return new AwsException("InvalidParameterValue", "Invalid backup window format. Should be "
+ "specified as a range hh24:mi-hh24:mi (24H Clock UTC). Example: 03:15-08:15", 400);
}
public ReplicationGroupSettings withKmsKeyId(String resolvedKmsKeyId) {
return new ReplicationGroupSettings(atRestEncryptionEnabled, resolvedKmsKeyId,
snapshotRetentionLimit, snapshotWindow);
}
public void applyTo(ReplicationGroup group) {
if (atRestEncryptionEnabled != null) {
group.setAtRestEncryptionEnabled(atRestEncryptionEnabled);
}
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
group.setKmsKeyId(kmsKeyId);
}
if (snapshotRetentionLimit != null) {
group.setSnapshotRetentionLimit(snapshotRetentionLimit);
}
if (snapshotWindow != null && !snapshotWindow.isBlank()) {
group.setSnapshotWindow(snapshotWindow);
}
}
}