fix(elasticache): preserve and mutate resource tags (#6327)

* fix(elasticache): preserve and mutate resource tags

* fix(elasticache): complete resource tag mutations

* docs(elasticache): sync tag actions

* docs(services): update ElastiCache action count

* fix(elasticache): use AWS InvalidARN tag error code

* fix(elasticache): align resource tag mutations with lifecycle and AWS errors
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-23 09:04:51 -04:00
1 parent a815434e21
commit d4f454a1cf
14 files changed
+684 -14

No files matched your search

+2
View File
@@ -40,6 +40,8 @@ Floci manages real Valkey/Redis Docker containers and proxies TCP connections to
| `ModifyCacheParameterGroup` | Set parameters on a group |
| `DescribeCacheParameters` | List the parameters set on a group |
| `DeleteCacheParameterGroup` | Delete a cache parameter group |
| `AddTagsToResource` | - |
| `RemoveTagsFromResource` | - |
| `ListTagsForResource` | Read stored tags for supported ElastiCache resource ARNs |
<!-- floci:actions:end -->
+1 -1
View File
@@ -61,7 +61,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
| [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |
| [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 30 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 32 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` + TLS endpoint | REST JSON + wire | 9 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 109 |
@@ -93,6 +93,8 @@ public class ElastiCacheQueryHandler {
case "ModifyCacheParameterGroup" -> handleModifyCacheParameterGroup(params);
case "DescribeCacheParameters" -> handleDescribeCacheParameters(params);
case "DeleteCacheParameterGroup" -> handleDeleteCacheParameterGroup(params);
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.EC, 400);
@@ -276,7 +278,8 @@ public class ElastiCacheQueryHandler {
UserAuthentication auth = resolveUserAuthentication(params);
AuthMode authMode = auth != null ? auth.mode() : AuthMode.NO_AUTH;
List<String> passwords = auth != null ? auth.passwords() : List.of();
ElastiCacheUser user = service.createUser(userId, userName, authMode, passwords, accessString, engine);
ElastiCacheUser user = service.createUser(userId, userName, authMode, passwords, accessString, engine,
parseTags(params));
return Response.ok(AwsQueryResponse.envelope("CreateUser", AwsNamespaces.EC, userXml(user))).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
@@ -342,7 +345,8 @@ public class ElastiCacheQueryHandler {
private Response handleCreateUserGroup(MultivaluedMap<String, String> params, String region) {
try {
ElastiCacheUserGroup userGroup = service.createUserGroup(params.getFirst("UserGroupId"),
params.getFirst("Engine"), extractMemberList(params, "UserIds.member."), region);
params.getFirst("Engine"), extractMemberList(params, "UserIds.member."), region,
parseTags(params));
return Response.ok(AwsQueryResponse.envelope("CreateUserGroup", AwsNamespaces.EC,
userGroupXml(userGroup))).build();
} catch (AwsException e) {
@@ -817,6 +821,20 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
arn[6] + " is not present", 404))
.getTags();
}
if ("user".equals(arn[5])) {
ElastiCacheUser user = service.getUser(arn[6]);
if (user.getArn() != null && !user.getArn().equalsIgnoreCase(resourceName)) {
throw new AwsException("UserNotFound", "User " + arn[6] + " not found.", 404);
}
tags = user.getTags();
}
if ("usergroup".equals(arn[5])) {
ElastiCacheUserGroup userGroup = service.getUserGroup(arn[6]);
if (userGroup.getArn() != null && !userGroup.getArn().equalsIgnoreCase(resourceName)) {
throw new AwsException("UserGroupNotFound", "User group " + arn[6] + " not found.", 404);
}
tags = userGroup.getTags();
}
XmlBuilder xml = new XmlBuilder().start("TagList");
tags.forEach((key, value) -> xml.start("Tag")
.elem("Key", key)
@@ -829,6 +847,65 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
}
}
private Response handleAddTagsToResource(MultivaluedMap<String, String> params, String region) {
try {
String resourceArn = requiredResourceArn(params);
Map<String, String> tags = parseMutationTags(params);
Map<String, String> updated = isServerlessResource(resourceArn)
? serverlessHandler.addTagsToResource(resourceArn, tags, region)
: service.addTagsToResource(resourceArn, tags, region);
return Response.ok(AwsQueryResponse.envelope("AddTagsToResource", AwsNamespaces.EC,
tagListXml(updated))).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleRemoveTagsFromResource(MultivaluedMap<String, String> params, String region) {
try {
String resourceArn = requiredResourceArn(params);
List<String> tagKeys = extractMemberList(params, "TagKeys.member.");
if (tagKeys.isEmpty() || tagKeys.stream().anyMatch(key -> key == null || key.isBlank())) {
throw new AwsException("InvalidParameterValue", "TagKeys must contain at least one key.", 400);
}
Map<String, String> tags = isServerlessResource(resourceArn)
? serverlessHandler.removeTagsFromResource(resourceArn, tagKeys, region)
: service.removeTagsFromResource(resourceArn, tagKeys, region);
return Response.ok(AwsQueryResponse.envelope("RemoveTagsFromResource", AwsNamespaces.EC,
tagListXml(tags))).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private static String tagListXml(Map<String, String> tags) {
XmlBuilder xml = new XmlBuilder().start("TagList");
tags.forEach((key, value) -> xml.start("Tag")
.elem("Key", key)
.elem("Value", value)
.end("Tag"));
return xml.end("TagList").build();
}
private static String requiredResourceArn(MultivaluedMap<String, String> params) {
String resourceArn = params.getFirst("ResourceName");
if (resourceArn == null || resourceArn.isBlank()) {
throw new AwsException("InvalidParameterValue", "ResourceName is required.", 400);
}
return resourceArn;
}
private static boolean isServerlessResource(String resourceArn) {
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
String resource = arn.resource();
int separator = resource.indexOf(':');
return separator > 0 && "serverlesscache".equals(resource.substring(0, separator));
} catch (IllegalArgumentException e) {
return false;
}
}
private Response handleDeleteCacheParameterGroup(MultivaluedMap<String, String> params) {
try {
service.deleteCacheParameterGroup(params.getFirst("CacheParameterGroupName"));
@@ -877,6 +954,29 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
return parsePairs(params, List.of("Tags.Tag", "Tags.member", "Tag"), "Key", "Value");
}
private static Map<String, String> parseMutationTags(MultivaluedMap<String, String> params) {
Map<String, String> tags = parseTags(params);
boolean memberPresent = false;
for (String prefix : List.of("Tags.Tag", "Tags.member", "Tag")) {
for (int index = 1; ; index++) {
String key = params.getFirst(prefix + "." + index + ".Key");
String value = params.getFirst(prefix + "." + index + ".Value");
if (key == null && value == null) {
break;
}
memberPresent = true;
if (key == null || key.isBlank()) {
throw new AwsException("InvalidParameterValue", "Tag key cannot be null or empty.", 400);
}
// The AWS model permits a null tag value, so only the key is required here.
}
}
if (!memberPresent || tags.isEmpty()) {
throw new AwsException("InvalidParameterValue", "At least one tag is required.", 400);
}
return tags;
}
private static Map<String, String> parseParameterNameValues(MultivaluedMap<String, String> params) {
return parsePairs(params,
List.of("ParameterNameValues.ParameterNameValue", "ParameterNameValues.member"),
@@ -64,6 +64,14 @@ public class ElastiCacheServerlessQueryHandler {
return service.getServerlessCache(name).getTags();
}
public Map<String, String> addTagsToResource(String resourceArn, Map<String, String> tags, String region) {
return service.addTagsToResource(resourceArn, tags, region);
}
public Map<String, String> removeTagsFromResource(String resourceArn, List<String> tagKeys, String region) {
return service.removeTagsFromResource(resourceArn, tagKeys, region);
}
private static String cacheXml(ServerlessCache cache) {
return new XmlBuilder().start("ServerlessCache").raw(cacheFields(cache)).end("ServerlessCache").build();
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheTagResourceArn.TagResourceRef;
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.ServerlessCache;
@@ -243,6 +244,32 @@ public class ElastiCacheServerlessService implements Resettable {
}
}
public Map<String, String> addTagsToResource(String resourceArn, Map<String, String> tags, String region) {
TagResourceRef ref = parseTagResourceArn(resourceArn, region);
synchronized (lockFor(ref.id())) {
ServerlessCache cache = requireCache(ref.id());
requireResourceArn(cache.getArn(), ref.resourceArn(), ref.id());
Map<String, String> updatedTags = cache.getTags();
updatedTags.putAll(tags);
cache.setTags(updatedTags);
caches.put(key(ref.id()), cache);
return cache.getTags();
}
}
public Map<String, String> removeTagsFromResource(String resourceArn, List<String> tagKeys, String region) {
TagResourceRef ref = parseTagResourceArn(resourceArn, region);
synchronized (lockFor(ref.id())) {
ServerlessCache cache = requireCache(ref.id());
requireResourceArn(cache.getArn(), ref.resourceArn(), ref.id());
Map<String, String> updatedTags = cache.getTags();
tagKeys.forEach(updatedTags::remove);
cache.setTags(updatedTags);
caches.put(key(ref.id()), cache);
return cache.getTags();
}
}
private static void validateTagCount(Map<String, String> tags) {
if (tags != null && tags.size() > 50) {
throw new AwsException("TagQuotaPerResourceExceeded", "At most 50 tags are supported.", 400);
@@ -313,6 +340,17 @@ public class ElastiCacheServerlessService implements Resettable {
"Serverless cache " + name + " not found.", 404));
}
private TagResourceRef parseTagResourceArn(String resourceArn, String region) {
return ElastiCacheTagResourceArn.parse(resourceArn, region, resolver, "serverlesscache");
}
private static void requireResourceArn(String actualArn, String requestedArn, String id) {
if (actualArn == null || !actualArn.equalsIgnoreCase(requestedArn)) {
throw new AwsException("ServerlessCacheNotFoundFault",
"Serverless cache " + id + " not found.", 404);
}
}
private String key(String name) {
return resolver.getRegion() + "/" + name;
}
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheTagResourceArn.TagResourceRef;
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.container.ValkeyClusterFormation;
@@ -1860,6 +1861,12 @@ public class ElastiCacheService implements ResourceProvider {
public ElastiCacheUser createUser(String userId, String userName, AuthMode authMode,
List<String> passwords, String accessString, String engine) {
return createUser(userId, userName, authMode, passwords, accessString, engine, Map.of());
}
public ElastiCacheUser createUser(String userId, String userName, AuthMode authMode,
List<String> passwords, String accessString, String engine,
Map<String, String> tags) {
if (users.get(userId).isPresent()) {
throw new AwsException("UserAlreadyExists",
"User " + userId + " already exists.", 400);
@@ -1874,12 +1881,194 @@ public class ElastiCacheService implements ResourceProvider {
accessString != null ? accessString : "on ~* +@all",
normalizedEngine, "active", Instant.now());
user.setArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(), "user:" + userId));
user.setTags(tags);
users.put(userId, user);
LOG.infov("ElastiCache user {0} created with authMode={1}", userId, authMode);
return user;
}
public Map<String, String> addTagsToResource(String resourceArn, Map<String, String> tags,
String region) {
TagResourceRef ref = ElastiCacheTagResourceArn.parse(resourceArn, region, regionResolver);
return switch (ref.type()) {
case "user" -> updateUserTags(ref, tags);
case "usergroup" -> updateUserGroupTags(ref, tags);
case "replicationgroup" -> updateReplicationGroupTags(ref, tags);
case "cluster" -> updateCacheClusterTags(ref, tags);
case "subnetgroup" -> updateCacheSubnetGroupTags(ref, tags);
case "parametergroup" -> updateCacheParameterGroupTags(ref, tags);
default -> throw ElastiCacheTagResourceArn.invalid(resourceArn);
};
}
public Map<String, String> removeTagsFromResource(String resourceArn, List<String> tagKeys,
String region) {
TagResourceRef ref = ElastiCacheTagResourceArn.parse(resourceArn, region, regionResolver);
return switch (ref.type()) {
case "user" -> removeUserTags(ref, tagKeys);
case "usergroup" -> removeUserGroupTags(ref, tagKeys);
case "replicationgroup" -> removeReplicationGroupTags(ref, tagKeys);
case "cluster" -> removeCacheClusterTags(ref, tagKeys);
case "subnetgroup" -> removeCacheSubnetGroupTags(ref, tagKeys);
case "parametergroup" -> removeCacheParameterGroupTags(ref, tagKeys);
default -> throw ElastiCacheTagResourceArn.invalid(resourceArn);
};
}
private Map<String, String> updateUserTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (userGroupLock) {
ElastiCacheUser user = getUser(ref.id());
requireResourceArn(user.getArn(), ref.resourceArn(), "UserNotFound", ref.id());
user.getTags().putAll(tags);
users.put(ref.id(), user);
return new LinkedHashMap<>(user.getTags());
}
}
private Map<String, String> removeUserTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (userGroupLock) {
ElastiCacheUser user = getUser(ref.id());
requireResourceArn(user.getArn(), ref.resourceArn(), "UserNotFound", ref.id());
tagKeys.forEach(user.getTags()::remove);
users.put(ref.id(), user);
return new LinkedHashMap<>(user.getTags());
}
}
private Map<String, String> updateUserGroupTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (userGroupLock) {
ElastiCacheUserGroup userGroup = getUserGroup(ref.id());
requireResourceArn(userGroup.getArn(), ref.resourceArn(), "UserGroupNotFound", ref.id());
userGroup.getTags().putAll(tags);
userGroups.put(userGroup.getUserGroupId(), userGroup);
return new LinkedHashMap<>(userGroup.getTags());
}
}
private Map<String, String> removeUserGroupTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (userGroupLock) {
ElastiCacheUserGroup userGroup = getUserGroup(ref.id());
requireResourceArn(userGroup.getArn(), ref.resourceArn(), "UserGroupNotFound", ref.id());
tagKeys.forEach(userGroup.getTags()::remove);
userGroups.put(userGroup.getUserGroupId(), userGroup);
return new LinkedHashMap<>(userGroup.getTags());
}
}
private Map<String, String> updateReplicationGroupTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (lockFor("rg:" + ref.id())) {
ReplicationGroup group = getReplicationGroup(ref.id());
requireResourceArn(group.getArn(), ref.resourceArn(), "ReplicationGroupNotFoundFault", ref.id());
group.getTags().putAll(tags);
groups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private Map<String, String> removeReplicationGroupTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (lockFor("rg:" + ref.id())) {
ReplicationGroup group = getReplicationGroup(ref.id());
requireResourceArn(group.getArn(), ref.resourceArn(), "ReplicationGroupNotFoundFault", ref.id());
tagKeys.forEach(group.getTags()::remove);
groups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private Map<String, String> updateCacheClusterTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (lockFor("cc:" + ref.id())) {
StorageBackend<String, CacheCluster> store = cacheClusters.get(ref.id()).isPresent()
? cacheClusters : memcachedClusters;
CacheCluster cluster = store.get(ref.id())
.filter(value -> value.getServerlessCacheName() == null)
.orElseThrow(() -> new AwsException("CacheClusterNotFound",
"Cache cluster " + ref.id() + " not found.", 404));
requireResourceArn(cluster.getArn(), ref.resourceArn(), "CacheClusterNotFound", ref.id());
cluster.getTags().putAll(tags);
store.put(ref.id(), cluster);
return new LinkedHashMap<>(cluster.getTags());
}
}
private Map<String, String> removeCacheClusterTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (lockFor("cc:" + ref.id())) {
StorageBackend<String, CacheCluster> store = cacheClusters.get(ref.id()).isPresent()
? cacheClusters : memcachedClusters;
CacheCluster cluster = store.get(ref.id())
.filter(value -> value.getServerlessCacheName() == null)
.orElseThrow(() -> new AwsException("CacheClusterNotFound",
"Cache cluster " + ref.id() + " not found.", 404));
requireResourceArn(cluster.getArn(), ref.resourceArn(), "CacheClusterNotFound", ref.id());
tagKeys.forEach(cluster.getTags()::remove);
store.put(ref.id(), cluster);
return new LinkedHashMap<>(cluster.getTags());
}
}
private Map<String, String> updateCacheSubnetGroupTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (lockFor("sng:" + ref.id())) {
CacheSubnetGroup group = subnetGroups.get(ref.id()).orElseThrow(() ->
new AwsException("CacheSubnetGroupNotFoundFault", "Cache subnet group " + ref.id() + " not found.", 400));
requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(),
"subnetgroup:" + ref.id()).toString(), ref.resourceArn(),
"CacheSubnetGroupNotFoundFault", ref.id(), 400);
group.getTags().putAll(tags);
subnetGroups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private Map<String, String> removeCacheSubnetGroupTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (lockFor("sng:" + ref.id())) {
CacheSubnetGroup group = subnetGroups.get(ref.id()).orElseThrow(() ->
new AwsException("CacheSubnetGroupNotFoundFault", "Cache subnet group " + ref.id() + " not found.", 400));
requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(),
"subnetgroup:" + ref.id()).toString(), ref.resourceArn(),
"CacheSubnetGroupNotFoundFault", ref.id(), 400);
tagKeys.forEach(group.getTags()::remove);
subnetGroups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private Map<String, String> updateCacheParameterGroupTags(TagResourceRef ref, Map<String, String> tags) {
synchronized (lockFor(ref.id())) {
CacheParameterGroup group = parameterGroups.get(ref.id()).orElseThrow(() ->
new AwsException("CacheParameterGroupNotFound", "Cache parameter group " + ref.id() + " not found.", 404));
requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(),
"parametergroup:" + ref.id()).toString(), ref.resourceArn(),
"CacheParameterGroupNotFound", ref.id());
group.getTags().putAll(tags);
parameterGroups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private Map<String, String> removeCacheParameterGroupTags(TagResourceRef ref, List<String> tagKeys) {
synchronized (lockFor(ref.id())) {
CacheParameterGroup group = parameterGroups.get(ref.id()).orElseThrow(() ->
new AwsException("CacheParameterGroupNotFound", "Cache parameter group " + ref.id() + " not found.", 404));
requireResourceArn(regionResolver.buildArn("elasticache", regionResolver.getRegion(),
"parametergroup:" + ref.id()).toString(), ref.resourceArn(),
"CacheParameterGroupNotFound", ref.id());
tagKeys.forEach(group.getTags()::remove);
parameterGroups.put(ref.id(), group);
return new LinkedHashMap<>(group.getTags());
}
}
private static void requireResourceArn(String actualArn, String requestedArn, String errorCode, String id) {
requireResourceArn(actualArn, requestedArn, errorCode, id, 404);
}
private static void requireResourceArn(String actualArn, String requestedArn, String errorCode, String id,
int httpStatus) {
if (actualArn == null || !actualArn.equalsIgnoreCase(requestedArn)) {
throw new AwsException(errorCode, "Resource " + id + " not found.", httpStatus);
}
}
public ElastiCacheUser getUser(String userId) {
return users.get(userId).orElseThrow(() ->
new AwsException("UserNotFound", "User " + userId + " not found.", 404));
@@ -1970,6 +2159,11 @@ public class ElastiCacheService implements ResourceProvider {
public ElastiCacheUserGroup createUserGroup(String userGroupId, String engine, List<String> userIds,
String region) {
return createUserGroup(userGroupId, engine, userIds, region, Map.of());
}
public ElastiCacheUserGroup createUserGroup(String userGroupId, String engine, List<String> userIds,
String region, Map<String, String> tags) {
String id = normalizeUserGroupId(userGroupId);
// Engine is required on AWS; a missing value defaults to redis as CreateUser does.
String normalizedEngine = (engine == null || engine.isBlank()) ? "redis" : normalizeEngine(engine);
@@ -1983,6 +2177,7 @@ public class ElastiCacheService implements ResourceProvider {
ElastiCacheUserGroup userGroup = new ElastiCacheUserGroup(
id, normalizedEngine, members, "active", Instant.now());
userGroup.setArn(regionResolver.buildArn("elasticache", region, "usergroup:" + id));
userGroup.setTags(tags);
userGroups.put(id, userGroup);
LOG.infov("ElastiCache user group {0} created with {1} users", id, members.size());
return userGroup;
@@ -0,0 +1,51 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
final class ElastiCacheTagResourceArn {
record TagResourceRef(String type, String id, String resourceArn) {}
private ElastiCacheTagResourceArn() {
}
static TagResourceRef parse(String resourceArn, String region, RegionResolver resolver) {
return parse(resourceArn, region, resolver, null);
}
static TagResourceRef parse(String resourceArn, String region, RegionResolver resolver, String requiredType) {
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(resourceArn);
} catch (IllegalArgumentException e) {
throw invalid(resourceArn);
}
if (!"elasticache".equals(arn.service())
|| !resolver.partitionForRegion(region).equals(arn.partition())) {
throw invalid(resourceArn);
}
int separator = arn.resource().indexOf(':');
if (separator <= 0 || separator == arn.resource().length() - 1) {
throw invalid(resourceArn);
}
String type = arn.resource().substring(0, separator);
if (requiredType != null && !requiredType.equals(type)) {
throw invalid(resourceArn);
}
if (!region.equals(arn.region()) || !resolver.getAccountId().equals(arn.accountId())) {
throw new AwsException("InvalidParameterValue",
"The resource ARN does not belong to the requested Region or account: " + resourceArn, 400);
}
String id = arn.resource().substring(separator + 1);
if (id.isBlank()) {
throw invalid(resourceArn);
}
return new TagResourceRef(type, id, resourceArn);
}
static AwsException invalid(String resourceArn) {
return new AwsException("InvalidARN", "Invalid resource ARN: " + resourceArn, 400);
}
}
@@ -4,7 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public class ElastiCacheUser {
@@ -20,6 +22,7 @@ public class ElastiCacheUser {
private Instant createdAt;
// Minted once in the region of the CreateUser request; null for users persisted before it was stored.
private String arn;
private Map<String, String> tags = new LinkedHashMap<>();
public ElastiCacheUser() {}
@@ -63,6 +66,11 @@ public class ElastiCacheUser {
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
}
@JsonIgnore
public boolean isEnabled() {
return isAccessStringOn(accessString);
@@ -18,6 +18,7 @@ public class ElastiCacheUserGroup {
private Set<String> userIds = new LinkedHashSet<>();
private Instant createdAt;
private String arn;
private Map<String, String> tags = new LinkedHashMap<>();
// Serverless caches attached to this group, by cache name, with the engine each runs.
private Map<String, String> serverlessCacheEngines = new LinkedHashMap<>();
@@ -52,6 +53,11 @@ public class ElastiCacheUserGroup {
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
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> getServerlessCacheEngines() { return serverlessCacheEngines; }
public void setServerlessCacheEngines(Map<String, String> serverlessCacheEngines) {
this.serverlessCacheEngines = serverlessCacheEngines != null ? serverlessCacheEngines : new LinkedHashMap<>();
@@ -191,6 +191,44 @@ class ElastiCacheIntegrationTest {
@Test
@Order(8)
void userTagsCanBeAddedListedAndRemoved() {
given()
.formParam("Action", "AddTagsToResource")
.formParam("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:" + USER_ID)
.formParam("Tags.Tag.1.Key", "environment")
.formParam("Tags.Tag.1.Value", "test")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("AddTagsToResourceResponse.AddTagsToResourceResult.TagList.Tag.Key", equalTo("environment"))
.body("AddTagsToResourceResponse.AddTagsToResourceResult.TagList.Tag.Value", equalTo("test"));
given()
.formParam("Action", "ListTagsForResource")
.formParam("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:" + USER_ID)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ListTagsForResourceResponse.ListTagsForResourceResult.TagList.Tag.Key", equalTo("environment"));
given()
.formParam("Action", "RemoveTagsFromResource")
.formParam("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:" + USER_ID)
.formParam("TagKeys.member.1", "environment")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("RemoveTagsFromResourceResponse.RemoveTagsFromResourceResult.TagList", notNullValue());
}
@Test
@Order(9)
void unassociatedUserIsRejected() throws Exception {
// Before associating the user with the group, auth should fail
String reply = sendCommand(firstProxyPort, respArray("AUTH", USER_NAME, INITIAL_PASSWORD));
@@ -198,7 +236,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(9)
@Order(10)
void associateUserWithGroup() {
given()
.formParam("Action", "ModifyReplicationGroup")
@@ -213,7 +251,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(10)
@Order(11)
void describeUsersIncludesCreatedUser() {
given()
.formParam("Action", "DescribeUsers")
@@ -227,7 +265,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(11)
@Order(12)
void crossGroupAuthIsRejected() throws Exception {
// Ensure user exists if this test is run in isolation
try {
@@ -284,7 +322,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(12)
@Order(13)
void userPasswordAuthWorks() throws Exception {
try (Socket socket = openSocket(firstProxyPort)) {
write(socket, respArray("AUTH", USER_NAME, INITIAL_PASSWORD));
@@ -296,7 +334,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(13)
@Order(14)
void modifyUserPasswordInvalidatesOldPasswordAndAcceptsNewPassword() throws Exception {
given()
.formParam("Action", "ModifyUser")
@@ -323,7 +361,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(14)
@Order(15)
void deleteUserRemovesUserFromDescribeUsers() {
given()
.formParam("Action", "DeleteUser")
@@ -346,7 +384,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(15)
@Order(16)
void deleteReplicationGroupReleasesProxyPortForReuse() {
given()
.formParam("Action", "DeleteReplicationGroup")
@@ -389,7 +427,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(16)
@Order(17)
void transitEncryptionReplicationGroupAuthenticatesPasswordAndNoAuthUsers() throws Exception {
String transitGroupId = "it-ec-transit-rbac";
String passUserId = "it-transit-pass-user";
@@ -499,7 +537,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(17)
@Order(18)
void replicationGroupWithNoAuthDefaultMemberAdmitsUnauthenticatedClients() throws Exception {
String groupId = "it-ec-def-noauth";
String defUserId = "it-def-noauth-uid";
@@ -616,7 +654,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(18)
@Order(19)
void replicationGroupWithMembersWithoutDefaultMemberRequiresAuth() throws Exception {
String groupId = "it-ec-nodef-members";
String passUserId = "it-nodef-pass-uid";
@@ -695,7 +733,7 @@ class ElastiCacheIntegrationTest {
}
@Test
@Order(19)
@Order(20)
void replicationGroupWithDisabledDefaultUserRequiresAuth() throws Exception {
String groupId = "it-ec-disabled-def";
String defUserId = "it-disabled-def-uid";
@@ -73,6 +73,48 @@ class ElastiCacheQueryHandlerTest {
assertFalse(body.contains("<Marker>"), "Empty list must omit Marker");
}
@Test
void addTagsToResource_supportsUserResource() {
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:sub1");
p.add("Tags.Tag.1.Key", "env");
p.add("Tags.Tag.1.Value", "test");
when(service.addTagsToResource(anyString(), anyMap(), anyString()))
.thenReturn(Map.of("env", "test"));
Response response = handler.handle("AddTagsToResource", p, "us-east-1");
assertEquals(200, response.getStatus(), (String) response.getEntity());
assertTrue(((String) response.getEntity()).contains("<Key>env</Key><Value>test</Value>"));
}
@Test
void removeTagsFromResource_supportsUserResource() {
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:sub1");
p.add("TagKeys.member.1", "env");
when(service.removeTagsFromResource(anyString(), anyList(), anyString()))
.thenReturn(Map.of());
Response response = handler.handle("RemoveTagsFromResource", p, "us-east-1");
assertEquals(200, response.getStatus(), (String) response.getEntity());
assertTrue(((String) response.getEntity()).contains("<TagList></TagList>"));
}
@Test
void addTagsToResource_rejectsMissingTagKeyBeforeCallingService() {
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:user:sub1");
p.add("Tags.Tag.1.Value", "test");
Response response = handler.handle("AddTagsToResource", p, "us-east-1");
assertEquals(400, response.getStatus());
assertTrue(((String) response.getEntity()).contains("InvalidParameterValue"));
verifyNoInteractions(service);
}
@Test
void describeReplicationGroups_reportsClusterModeTopology() {
ReplicationGroup group = new ReplicationGroup("grp", "d", ReplicationGroupStatus.AVAILABLE,
@@ -468,4 +468,22 @@ class ElastiCacheServerlessServiceTest {
error("TagQuotaPerResourceExceeded", () -> service.replaceTags("tag-cache", tooMany));
assertEquals(Map.of("env", "dev"), service.getServerlessCache("tag-cache").getTags());
}
@Test
void tagMutationsUseAwsInvalidArnWireCode() {
error("InvalidARN", () -> service.addTagsToResource("not-an-arn", Map.of("env", "test"), "us-east-1"));
error("InvalidARN", () -> service.removeTagsFromResource("not-an-arn", List.of("env"), "us-east-1"));
String wrongTypeAndRegion = "arn:aws:elasticache:eu-west-1:000000000000:cluster:test";
error("InvalidARN", () -> service.addTagsToResource(wrongTypeAndRegion, Map.of("env", "test"), "us-east-1"));
}
@Test
void tagMutationsKeepUsingTheServerlessCacheArn() {
ServerlessCache cache = service.createServerlessCache(create("arn-tags-cache", "valkey", null));
assertEquals(Map.of("team", "local", "env", "test"),
service.addTagsToResource(cache.getArn(), Map.of("env", "test"), "us-east-1"));
assertEquals(Map.of("team", "local"),
service.removeTagsFromResource(cache.getArn(), List.of("env"), "us-east-1"));
}
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.elasticache.container.ValkeyClusterFo
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.CacheClusterStatus;
import io.github.hectorvent.floci.services.elasticache.model.CacheParameterGroup;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUserGroup;
@@ -33,6 +34,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.lang.reflect.Field;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -41,7 +43,11 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -150,6 +156,141 @@ class ElastiCacheServiceTest {
assertEquals(400, ex.getHttpStatus());
}
@Test
void userAndUserGroupTagsPersistAndCanBeMutatedByArn() {
ElastiCacheUser defaultUser = service.createUser("default-user", "default", AuthMode.PASSWORD,
List.of("password"), "on ~* +@all", "redis");
ElastiCacheUser taggedUser = service.createUser("tagged-user", "tagged", AuthMode.PASSWORD,
List.of("password"), "on ~* +@all", "redis", Map.of("owner", "platform"));
assertEquals(Map.of("owner", "platform"), taggedUser.getTags());
ElastiCacheUserGroup taggedGroup = service.createUserGroup("tagged-group", "redis",
List.of(defaultUser.getUserId()), "us-east-1", Map.of("team", "cache"));
assertEquals(Map.of("team", "cache"), taggedGroup.getTags());
service.addTagsToResource(taggedUser.getArn(), Map.of("environment", "test"), "us-east-1");
assertEquals(Map.of("owner", "platform", "environment", "test"),
service.getUser("tagged-user").getTags());
service.removeTagsFromResource(taggedUser.getArn(), List.of("owner"), "us-east-1");
assertEquals(Map.of("environment", "test"), service.getUser("tagged-user").getTags());
service.addTagsToResource(taggedGroup.getArn(), Map.of("environment", "test"), "us-east-1");
assertEquals(Map.of("team", "cache", "environment", "test"),
service.getUserGroup("tagged-group").getTags());
}
@Test
void tagResourceRejectsSameIdResourceFromAnotherRegion() {
ElastiCacheUser user = service.createUser("regional-user", "regional", AuthMode.PASSWORD,
List.of("password"), "on ~* +@all", "redis");
String foreignRegionArn = user.getArn().replace(":us-east-1:", ":eu-west-1:");
AwsException error = assertThrows(AwsException.class,
() -> service.addTagsToResource(foreignRegionArn, Map.of("env", "test"), "eu-west-1"));
assertEquals("UserNotFound", error.getErrorCode());
assertTrue(service.getUser("regional-user").getTags().isEmpty());
}
@Test
void tagMutationsUseAwsInvalidArnErrorCode() {
AwsException addError = assertThrows(AwsException.class,
() -> service.addTagsToResource("not-an-arn", Map.of("env", "test"), "us-east-1"));
AwsException removeError = assertThrows(AwsException.class,
() -> service.removeTagsFromResource("not-an-arn", List.of("env"), "us-east-1"));
assertEquals("InvalidARN", addError.getErrorCode());
assertEquals("InvalidARN", removeError.getErrorCode());
assertEquals(400, addError.getHttpStatus());
assertEquals(400, removeError.getHttpStatus());
}
@Test
void tagMutationsReportMissingSubnetGroupWithAwsFaultCode() {
String arn = "arn:aws:elasticache:us-east-1:000000000000:subnetgroup:missing-tag-subnet";
AwsException addError = assertThrows(AwsException.class,
() -> service.addTagsToResource(arn, Map.of("env", "test"), "us-east-1"));
AwsException removeError = assertThrows(AwsException.class,
() -> service.removeTagsFromResource(arn, List.of("env"), "us-east-1"));
assertEquals("CacheSubnetGroupNotFoundFault", addError.getErrorCode());
assertEquals("CacheSubnetGroupNotFoundFault", removeError.getErrorCode());
assertEquals(400, addError.getHttpStatus());
assertEquals(400, removeError.getHttpStatus());
}
@Test
void tagWritesWaitForParameterGroupDeletion() throws Exception {
String name = "tag-delete-race-pg";
String arn = "arn:aws:elasticache:us-east-1:000000000000:parametergroup:" + name;
service.createCacheParameterGroup(name, "redis7", "tagged", Map.of());
Field locksField = ElastiCacheService.class.getDeclaredField("parameterGroupLocks");
locksField.setAccessible(true);
Object monitor = ((ConcurrentHashMap<?, ?>) locksField.get(service)).get(name);
ExecutorService pool = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
try {
Future<String> tag = pool.submit(() -> {
started.countDown();
try {
service.addTagsToResource(arn, Map.of("env", "test"), "us-east-1");
return "tagged";
} catch (AwsException error) {
return error.getErrorCode();
}
});
String completedBeforeDelete = null;
synchronized (monitor) {
assertTrue(started.await(5, TimeUnit.SECONDS));
try {
completedBeforeDelete = tag.get(1, TimeUnit.SECONDS);
} catch (TimeoutException expected) {
// A tag writer using the lifecycle lock remains blocked until deletion exits.
}
service.deleteCacheParameterGroup(name);
}
assertNull(completedBeforeDelete, "tagging bypassed the parameter-group lifecycle lock");
assertEquals("CacheParameterGroupNotFound", tag.get(5, TimeUnit.SECONDS));
assertTrue(service.findParameterGroup(name).isEmpty());
} finally {
pool.shutdownNow();
}
}
@Test
void tagResourceDerivesPartitionFromRequestedRegion() {
ElastiCacheUserGroup group = service.createUserGroup("gov-group", "valkey", List.of(),
"us-gov-west-1");
service.addTagsToResource(group.getArn(), Map.of("env", "gov"), "us-gov-west-1");
assertEquals(Map.of("env", "gov"), service.getUserGroup("gov-group").getTags());
}
@Test
void tagMutationsSupportCacheClustersAndParameterGroups() {
CacheCluster cluster = service.createCacheCluster(cacheClusterRequest("tag-cluster", "redis", 1));
CacheParameterGroup parameterGroup = service.createCacheParameterGroup(
"tag-pg", "redis7", "tagged parameter group", Map.of("owner", "platform"));
service.addTagsToResource(cluster.getArn(), Map.of("environment", "test"), "us-east-1");
service.removeTagsFromResource(cluster.getArn(), List.of("environment"), "us-east-1");
assertTrue(service.findCacheClusters("tag-cluster").getFirst().getTags().isEmpty());
service.addTagsToResource("arn:aws:elasticache:us-east-1:000000000000:parametergroup:tag-pg",
Map.of("environment", "test"), "us-east-1");
assertEquals(Map.of("owner", "platform", "environment", "test"),
service.findParameterGroup(parameterGroup.getName()).orElseThrow().getTags());
AwsException wrongRegion = assertThrows(AwsException.class, () -> service.addTagsToResource(
"arn:aws:elasticache:eu-west-1:000000000000:parametergroup:tag-pg",
Map.of("wrong", "region"), "eu-west-1"));
assertEquals("CacheParameterGroupNotFound", wrongRegion.getErrorCode());
assertFalse(service.findParameterGroup("tag-pg").orElseThrow().getTags().containsKey("wrong"));
}
@Test
void singleArgAuthMatchesDefaultUserOnly() {
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1");
@@ -257,4 +257,27 @@ class ElastiCacheSubnetGroupIntegrationTest {
.statusCode(400)
.body(containsString("Cache Subnet Group " + GROUP + " does not exist"));
}
@Test
@Order(6)
void missingSubnetGroupTagMutationsUseTheAwsFaultCode() {
String arn = "arn:aws:elasticache:us-east-1:000000000000:subnetgroup:missing-tag-sng";
elasticache("AddTagsToResource")
.formParam("ResourceName", arn)
.formParam("Tags.Tag.1.Key", "env")
.formParam("Tags.Tag.1.Value", "test")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("CacheSubnetGroupNotFoundFault"));
elasticache("RemoveTagsFromResource")
.formParam("ResourceName", arn)
.formParam("TagKeys.member.1", "env")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("CacheSubnetGroupNotFoundFault"));
}
}