diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index bdb5a55d66..c226848d64 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -138,7 +138,7 @@ cross-resource references. | ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` | | EKS | `Cluster`, `Nodegroup` | | RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` | -| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup` | +| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored) | | Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) | | Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) | | EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java index bbd5352ed0..bcea43b5c6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java @@ -7,9 +7,12 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.elasticache.ElastiCacheMemcachedService; import io.github.hectorvent.floci.services.elasticache.ElastiCacheService; +import io.github.hectorvent.floci.services.elasticache.UserAuthentication; 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.CacheSubnetGroup; +import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser; +import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUserGroup; import io.github.hectorvent.floci.services.elasticache.model.Endpoint; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -17,13 +20,15 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; /** - * Provisions AWS::ElastiCache::CacheCluster and SubnetGroup. A cache cluster needs the Memcached - * service as well as the Redis one, because the two engines keep their clusters in separate stores. + * Provisions AWS::ElastiCache::CacheCluster, SubnetGroup, User and UserGroup. A cache cluster needs + * the Memcached service as well as the Redis one, because the two engines keep their clusters in + * separate stores. */ @ApplicationScoped public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { @@ -33,7 +38,11 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { private static final String CACHE_CLUSTER = "AWS::ElastiCache::CacheCluster"; private static final String SUBNET_GROUP = "AWS::ElastiCache::SubnetGroup"; + private static final String USER = "AWS::ElastiCache::User"; + private static final String USER_GROUP = "AWS::ElastiCache::UserGroup"; private static final String SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR = "__FlociCacheSubnetGroupUpdateSnapshot"; + private static final String USER_UPDATE_SNAPSHOT_ATTR = "__FlociUserUpdateSnapshot"; + private static final String USER_GROUP_UPDATE_SNAPSHOT_ATTR = "__FlociUserGroupUpdateSnapshot"; private static final List UNSUPPORTED_CLUSTER_PROPERTIES = List.of("CacheSecurityGroupNames", "NotificationTopicArn", "AZMode", "PreferredAvailabilityZones", "LogDeliveryConfigurations", "SnapshotArns", "SnapshotName"); @@ -53,16 +62,20 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { - return Set.of(CACHE_CLUSTER, SUBNET_GROUP); + return Set.of(CACHE_CLUSTER, SUBNET_GROUP, USER, USER_GROUP); } @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { r.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR); + r.getAttributes().remove(USER_UPDATE_SNAPSHOT_ATTR); + r.getAttributes().remove(USER_GROUP_UPDATE_SNAPSHOT_ATTR); Map attributesBefore = Map.copyOf(r.getAttributes()); switch (r.getResourceType()) { case CACHE_CLUSTER -> provisionCacheCluster(r, props, ctx); case SUBNET_GROUP -> provisionSubnetGroup(r, props, ctx); + case USER -> provisionUser(r, props, ctx); + case USER_GROUP -> provisionUserGroup(r, props, ctx); default -> throw new IllegalStateException( "ElastiCacheCfnProvisioner cannot provision " + r.getResourceType()); } @@ -83,6 +96,8 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { public UpdateCleanupResult completeUpdate(StackResource resource) { if ("UPDATE_COMPLETE".equals(resource.getStatus())) { resource.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR); + resource.getAttributes().remove(USER_UPDATE_SNAPSHOT_ATTR); + resource.getAttributes().remove(USER_GROUP_UPDATE_SNAPSHOT_ATTR); } return ReplacementCleanup.complete(resource, this::delete); } @@ -90,6 +105,8 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { @Override public void clearUpdate(StackResource resource) { resource.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR); + resource.getAttributes().remove(USER_UPDATE_SNAPSHOT_ATTR); + resource.getAttributes().remove(USER_GROUP_UPDATE_SNAPSHOT_ATTR); ReplacementCleanup.clear(resource); } @@ -109,6 +126,33 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { } } } + if (USER.equals(resource.getResourceType())) { + String rawSnapshot = resource.getAttributes().remove(USER_UPDATE_SNAPSHOT_ATTR); + if (rawSnapshot != null) { + try { + UserSnapshot snapshot = MAPPER.readValue(rawSnapshot, UserSnapshot.class); + elastiCacheService.modifyUser(snapshot.userId(), snapshot.authMode(), + snapshot.passwords(), snapshot.accessString(), null, snapshot.engine()); + return true; + } catch (Exception e) { + LOG.errorv("Could not restore user {0} after failed update: {1}", + resource.getPhysicalId(), e.getMessage()); + } + } + } + if (USER_GROUP.equals(resource.getResourceType())) { + String rawSnapshot = resource.getAttributes().remove(USER_GROUP_UPDATE_SNAPSHOT_ATTR); + if (rawSnapshot != null) { + try { + UserGroupSnapshot snapshot = MAPPER.readValue(rawSnapshot, UserGroupSnapshot.class); + elastiCacheService.setUserGroupMembers(snapshot.userGroupId(), snapshot.userIds(), snapshot.engine()); + return true; + } catch (Exception e) { + LOG.errorv("Could not restore user group {0} after failed update: {1}", + resource.getPhysicalId(), e.getMessage()); + } + } + } return ReplacementCleanup.rollback(resource, this::delete); } @@ -297,6 +341,102 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { r.setPhysicalId(group.getName()); } + private void provisionUser(StackResource r, JsonNode props, ProvisionContext ctx) { + String userId = ctx.resolveOptional(props, "UserId"); + String userName = ctx.resolveOptional(props, "UserName"); + String engine = ctx.resolveOptional(props, "Engine"); + if (userId == null || userId.isBlank() || userName == null || userName.isBlank() + || engine == null || engine.isBlank()) { + throw new AwsException("ValidationException", "UserId, UserName and Engine are required", 400); + } + String accessString = ctx.resolveOptional(props, "AccessString"); + UserAuthentication auth = resolveAuthentication(props, ctx); + if (!ctx.resolveTags(props, "Tags").isEmpty()) { + LOG.warnv("ElastiCache user {0}: Tags are ignored, the emulator does not tag users", userId); + } + + ElastiCacheUser user; + if (ctx.reusesPriorEntity(userId)) { + ElastiCacheUser existing = elastiCacheService.getUser(userId); + if (!userName.equals(existing.getUserName())) { + throw new AwsException("InvalidParameterValue", + "UserName of user " + userId + " is create-only; use a new UserId to change it", 400); + } + UserSnapshot snapshot = new UserSnapshot( + existing.getUserId(), + existing.getAuthMode(), + existing.getPasswords(), + existing.getAccessString(), + existing.getEngine()); + try { + r.getAttributes().put(USER_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot)); + } catch (JsonProcessingException e) { + LOG.errorv("Could not snapshot user {0} before update: {1}", userId, e.getMessage()); + } + user = elastiCacheService.modifyUser(userId, + auth != null ? auth.mode() : null, + auth != null ? auth.passwords() : null, + accessString, null, engine); + } else { + AuthMode mode = auth != null ? auth.mode() : AuthMode.NO_AUTH; + user = elastiCacheService.createUser(userId, userName, mode, + auth != null ? auth.passwords() : List.of(), accessString, engine); + } + r.setPhysicalId(user.getUserId()); + r.getAttributes().put("Arn", user.getArn()); + r.getAttributes().put("Status", user.getStatus()); + } + + private void provisionUserGroup(StackResource r, JsonNode props, ProvisionContext ctx) { + String groupId = ctx.resolveOptional(props, "UserGroupId"); + String engine = ctx.resolveOptional(props, "Engine"); + if (groupId == null || groupId.isBlank() || engine == null || engine.isBlank()) { + throw new AwsException("ValidationException", "UserGroupId and Engine are required", 400); + } + if (!props.hasNonNull("UserIds")) { + throw new AwsException("ValidationException", "UserIds is required", 400); + } + // The service stores the id in lowercase, so the prior physical id only matches in that form. + groupId = groupId.toLowerCase(Locale.ROOT); + List userIds = ctx.resolveStringList(props, "UserIds"); + if (!ctx.resolveTags(props, "Tags").isEmpty()) { + LOG.warnv("ElastiCache user group {0}: Tags are ignored, the emulator does not tag user groups", groupId); + } + + ElastiCacheUserGroup group; + if (ctx.reusesPriorEntity(groupId)) { + ElastiCacheUserGroup existing = elastiCacheService.getUserGroup(groupId); + UserGroupSnapshot snapshot = new UserGroupSnapshot( + existing.getUserGroupId(), + existing.getEngine(), + new ArrayList<>(existing.getUserIds())); + try { + r.getAttributes().put(USER_GROUP_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot)); + } catch (JsonProcessingException e) { + LOG.errorv("Could not snapshot user group {0} before update: {1}", groupId, e.getMessage()); + } + group = elastiCacheService.setUserGroupMembers(groupId, userIds, engine); + } else { + group = elastiCacheService.createUserGroup(groupId, engine, userIds, ctx.region()); + } + r.setPhysicalId(group.getUserGroupId()); + r.getAttributes().put("Arn", group.getArn()); + r.getAttributes().put("Status", group.getStatus()); + } + + private UserAuthentication resolveAuthentication(JsonNode props, ProvisionContext ctx) { + JsonNode mode = props.has("AuthenticationMode") + ? ctx.engine().resolveNode(props.get("AuthenticationMode")) : null; + String type = mode != null && mode.hasNonNull("Type") ? mode.get("Type").asText() : null; + List passwords = mode != null && mode.has("Passwords") + ? ctx.engine().resolveStringList(mode.get("Passwords")) : List.of(); + if (passwords.isEmpty()) { + passwords = ctx.resolveStringList(props, "Passwords"); + } + boolean noPasswordRequired = Boolean.parseBoolean(ctx.resolveOptional(props, "NoPasswordRequired")); + return UserAuthentication.resolve(type, passwords, noPasswordRequired); + } + @Override public void delete(String resourceType, String physicalId, String region) { if (resourceType == null || physicalId == null) { @@ -312,6 +452,10 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { }, "CacheClusterNotFound"); case SUBNET_GROUP -> CfnDeletes.safeDelete("ElastiCache subnet group", physicalId, () -> elastiCacheService.deleteCacheSubnetGroup(physicalId), "CacheSubnetGroupNotFoundFault"); + case USER_GROUP -> CfnDeletes.safeDelete("ElastiCache user group", physicalId, + () -> elastiCacheService.deleteUserGroup(physicalId), "UserGroupNotFound"); + case USER -> CfnDeletes.safeDelete("ElastiCache user", physicalId, + () -> elastiCacheService.deleteUser(physicalId), "UserNotFoundFault"); default -> { } } @@ -323,4 +467,9 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { private record SubnetGroupSnapshot(String name, String description, List subnetIds, Map tags) {} + + private record UserSnapshot(String userId, AuthMode authMode, List passwords, + String accessString, String engine) {} + + private record UserGroupSnapshot(String userGroupId, String engine, List userIds) {} } diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java index 534307cb2c..8582f1b1cd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java @@ -33,7 +33,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; -import java.util.Locale; import java.util.Map; /** @@ -1179,57 +1178,13 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap regionResolver.getAccountId(), "user:" + u.getUserId()).toString(); } - private record UserAuthentication(AuthMode mode, List passwords) {} - - /** - * Resolves the authentication a CreateUser or ModifyUser request asks for. AWS accepts it - * either as an {@code AuthenticationMode} or through the top-level {@code Passwords} and - * {@code NoPasswordRequired} members, so passwords given either way mean password - * authentication. Returns null when the request names no authentication at all. - */ private static UserAuthentication resolveUserAuthentication(MultivaluedMap params) { - String type = params.getFirst("AuthenticationMode.Type"); List passwords = extractMemberList(params, "AuthenticationMode.Passwords.member."); if (passwords.isEmpty()) { passwords = extractMemberList(params, "Passwords.member."); } - boolean noPasswordRequired = Boolean.parseBoolean(params.getFirst("NoPasswordRequired")); - - if (type == null || type.isBlank()) { - if (noPasswordRequired && !passwords.isEmpty()) { - throw invalidCombination("NoPasswordRequired cannot be true when Passwords are provided."); - } - if (!passwords.isEmpty()) { - return new UserAuthentication(AuthMode.PASSWORD, passwords); - } - return noPasswordRequired ? new UserAuthentication(AuthMode.NO_AUTH, List.of()) : null; - } - - String normalizedType = type.toLowerCase(Locale.ROOT); - if (noPasswordRequired && !"no-password-required".equals(normalizedType)) { - throw invalidCombination("NoPasswordRequired cannot be true when AuthenticationMode.Type is " + type + "."); - } - return switch (normalizedType) { - case "password" -> { - if (passwords.isEmpty()) { - throw new AwsException("InvalidParameterValue", - "Passwords are required when AuthenticationMode.Type is password.", 400); - } - yield new UserAuthentication(AuthMode.PASSWORD, passwords); - } - case "iam", "no-password-required" -> { - if (!passwords.isEmpty()) { - throw invalidCombination("Passwords cannot be provided when AuthenticationMode.Type is " + type + "."); - } - yield new UserAuthentication("iam".equals(normalizedType) ? AuthMode.IAM : AuthMode.NO_AUTH, List.of()); - } - default -> throw new AwsException("InvalidParameterValue", - "Invalid AuthenticationMode.Type " + type + ". Valid values are password, no-password-required and iam.", 400); - }; - } - - private static AwsException invalidCombination(String message) { - return new AwsException("InvalidParameterCombination", message, 400); + return UserAuthentication.resolve(params.getFirst("AuthenticationMode.Type"), passwords, + Boolean.parseBoolean(params.getFirst("NoPasswordRequired"))); } private static String memberListXml(String name, Collection values) { diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java index dc33ee5f53..d1fb908dfa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java @@ -57,6 +57,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -1946,18 +1947,31 @@ public class ElastiCacheService implements ResourceProvider { public ElastiCacheUserGroup modifyUserGroup(String userGroupId, List userIdsToAdd, List userIdsToRemove, String engine) { - String id = normalizeUserGroupId(userGroupId); - synchronized (userGroupLock) { - ElastiCacheUserGroup userGroup = getUserGroup(id); - // Validate the resulting group before changing the stored object. - String newEngine = (engine == null || engine.isBlank()) ? userGroup.getEngine() : normalizeEngine(engine); - Set members = new LinkedHashSet<>(userGroup.getUserIds()); + return updateUserGroup(userGroupId, engine, current -> { + Set members = new LinkedHashSet<>(current); if (userIdsToAdd != null) { members.addAll(userIdsToAdd); } if (userIdsToRemove != null) { members.removeAll(userIdsToRemove); } + return members; + }); + } + + public ElastiCacheUserGroup setUserGroupMembers(String userGroupId, List userIds, String engine) { + return updateUserGroup(userGroupId, engine, + current -> userIds == null ? new LinkedHashSet<>() : new LinkedHashSet<>(userIds)); + } + + private ElastiCacheUserGroup updateUserGroup(String userGroupId, String engine, + UnaryOperator> membership) { + String id = normalizeUserGroupId(userGroupId); + synchronized (userGroupLock) { + ElastiCacheUserGroup userGroup = getUserGroup(id); + // Validate the resulting group before changing the stored object. + String newEngine = (engine == null || engine.isBlank()) ? userGroup.getEngine() : normalizeEngine(engine); + Set members = membership.apply(userGroup.getUserIds()); validateUserGroupMembers(newEngine, members); if (!newEngine.equals(userGroup.getEngine())) { for (ReplicationGroup group : replicationGroupsUsing(id)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/UserAuthentication.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/UserAuthentication.java new file mode 100644 index 0000000000..def9905c1f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/UserAuthentication.java @@ -0,0 +1,61 @@ +package io.github.hectorvent.floci.services.elasticache; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.elasticache.model.AuthMode; + +import java.util.List; +import java.util.Locale; + +/** + * The authentication a CreateUser or ModifyUser request, or an AWS::ElastiCache::User resource, + * asks for. AWS accepts it either as an {@code AuthenticationMode} or through the top-level + * {@code Passwords} and {@code NoPasswordRequired} members, so passwords given either way mean + * password authentication. + */ +public record UserAuthentication(AuthMode mode, List passwords) { + + /** + * Returns null when nothing names an authentication at all, so the caller can keep its own default. + * + * @param type AuthenticationMode.Type, or null when absent + * @param passwords the passwords from AuthenticationMode or the top-level member + * @param noPasswordRequired the top-level NoPasswordRequired member + */ + public static UserAuthentication resolve(String type, List passwords, boolean noPasswordRequired) { + if (type == null || type.isBlank()) { + if (noPasswordRequired && !passwords.isEmpty()) { + throw invalidCombination("NoPasswordRequired cannot be true when Passwords are provided."); + } + if (!passwords.isEmpty()) { + return new UserAuthentication(AuthMode.PASSWORD, passwords); + } + return noPasswordRequired ? new UserAuthentication(AuthMode.NO_AUTH, List.of()) : null; + } + + String normalizedType = type.toLowerCase(Locale.ROOT); + if (noPasswordRequired && !"no-password-required".equals(normalizedType)) { + throw invalidCombination("NoPasswordRequired cannot be true when AuthenticationMode.Type is " + type + "."); + } + return switch (normalizedType) { + case "password" -> { + if (passwords.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Passwords are required when AuthenticationMode.Type is password.", 400); + } + yield new UserAuthentication(AuthMode.PASSWORD, passwords); + } + case "iam", "no-password-required" -> { + if (!passwords.isEmpty()) { + throw invalidCombination("Passwords cannot be provided when AuthenticationMode.Type is " + type + "."); + } + yield new UserAuthentication("iam".equals(normalizedType) ? AuthMode.IAM : AuthMode.NO_AUTH, List.of()); + } + default -> throw new AwsException("InvalidParameterValue", + "Invalid AuthenticationMode.Type " + type + ". Valid values are password, no-password-required and iam.", 400); + }; + } + + private static AwsException invalidCombination(String message) { + return new AwsException("InvalidParameterCombination", message, 400); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java index 99ecf01bcd..d82acba0e8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java @@ -14,6 +14,8 @@ import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticache.ElastiCacheClient; import software.amazon.awssdk.services.elasticache.model.CacheCluster; import software.amazon.awssdk.services.elasticache.model.CacheSubnetGroupNotFoundException; +import software.amazon.awssdk.services.elasticache.model.ElastiCacheException; +import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException; import java.io.IOException; import java.net.URI; @@ -24,6 +26,7 @@ import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Provisions the ElastiCache resource types through CloudFormation and checks them against the @@ -46,10 +49,25 @@ class ElastiCacheCfnIntegrationTest { "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.71.0.0/24"}}, "SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup", "Properties": {"CacheSubnetGroupName": "cfn-it-sng", "Description": "example", - "SubnetIds": [{"Ref": "Subnet"}]}} + "SubnetIds": [{"Ref": "Subnet"}]}}, + "DefaultUser": {"Type": "AWS::ElastiCache::User", + "Properties": {"UserId": "cfn-it-default", "UserName": "default", "Engine": "redis", + "AccessString": "off -@all", "NoPasswordRequired": true}}, + "AppUser": {"Type": "AWS::ElastiCache::User", + "Properties": {"UserId": "cfn-it-app", "UserName": "cfn-it-app", "Engine": "redis", + "AccessString": "on ~* +@all", + "AuthenticationMode": {"Type": "password", + "Passwords": ["example-password-0123456789"]}}}, + "UserGroup": {"Type": "AWS::ElastiCache::UserGroup", + "Properties": {"UserGroupId": "cfn-it-users", "Engine": "redis", + "UserIds": [{"Ref": "DefaultUser"}, {"Ref": "AppUser"}]}} }, "Outputs": { - "SubnetGroupRef": {"Value": {"Ref": "SubnetGroup"}} + "SubnetGroupRef": {"Value": {"Ref": "SubnetGroup"}}, + "UserRef": {"Value": {"Ref": "AppUser"}}, + "UserArn": {"Value": {"Fn::GetAtt": ["AppUser", "Arn"]}}, + "GroupRef": {"Value": {"Ref": "UserGroup"}}, + "GroupArn": {"Value": {"Fn::GetAtt": ["UserGroup", "Arn"]}} } } """; @@ -83,7 +101,18 @@ class ElastiCacheCfnIntegrationTest { "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.73.0.0/24"}}, "SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup", "Properties": {"CacheSubnetGroupName": "@@SNG@@", "Description": "example", - "SubnetIds": [{"Ref": "Subnet"}]}} + "SubnetIds": [{"Ref": "Subnet"}]}}, + "DefaultUser": {"Type": "AWS::ElastiCache::User", + "Properties": {"UserId": "cfn-it-upd-default", "UserName": "default", "Engine": "redis", + "AccessString": "off -@all", "NoPasswordRequired": true}}, + "AppUser": {"Type": "AWS::ElastiCache::User", + "Properties": {"UserId": "cfn-it-upd-app", "UserName": "cfn-it-upd-app", "Engine": "redis", + "AccessString": "on ~* +@all", + "AuthenticationMode": {"Type": "password", + "Passwords": ["example-password-0123456789"]}}}, + "UserGroup": {"Type": "AWS::ElastiCache::UserGroup", + "Properties": {"UserGroupId": "cfn-it-upd-users", "Engine": "redis", + "UserIds": @@MEMBERS@@}} }, "Outputs": { "SubnetGroupRef": {"Value": {"Ref": "SubnetGroup"}} @@ -106,35 +135,50 @@ class ElastiCacheCfnIntegrationTest { } @Test - void subnetGroupIsCreatedAndRemovedWithTheStack() { + void subnetGroupUsersAndUserGroupAreCreatedAndRemovedWithTheStack() { cloudFormation(METADATA_STACK, "CreateStack", METADATA_TEMPLATE); String stacks = describeStacks(METADATA_STACK, "CREATE_COMPLETE"); assertEquals("cfn-it-sng", outputValue(stacks, "SubnetGroupRef")); + assertEquals("cfn-it-app", outputValue(stacks, "UserRef")); + assertEquals("cfn-it-users", outputValue(stacks, "GroupRef")); + assertTrue(outputValue(stacks, "UserArn").endsWith(":user:cfn-it-app")); + assertTrue(outputValue(stacks, "GroupArn").endsWith(":usergroup:cfn-it-users")); try (ElastiCacheClient client = client()) { assertEquals(1, client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-sng")) .cacheSubnetGroups().size()); + assertEquals(2, client.describeUserGroups(r -> r.userGroupId("cfn-it-users")) + .userGroups().getFirst().userIds().size()); cloudFormation(METADATA_STACK, "DeleteStack", null); CfnStackWaits.awaitStackDeleted(METADATA_STACK); + assertThrows(UserGroupNotFoundException.class, + () -> client.describeUserGroups(r -> r.userGroupId("cfn-it-users"))); + assertThrows(ElastiCacheException.class, () -> client.describeUsers(r -> r.userId("cfn-it-app"))); assertThrows(CacheSubnetGroupNotFoundException.class, () -> client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-sng"))); } } @Test - void renamedSubnetGroupIsReplaced() { + void updateChangesGroupMembershipInPlaceAndRenamedSubnetGroupIsReplaced() { String stack = "elasticache-cfn-update-it"; - cloudFormation(stack, "CreateStack", UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-a")); + String create = UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-a").replace("@@MEMBERS@@", + "[{\"Ref\": \"DefaultUser\"}]"); + cloudFormation(stack, "CreateStack", create); describeStacks(stack, "CREATE_COMPLETE"); - cloudFormation(stack, "UpdateStack", UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-b")); + String update = UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-b").replace("@@MEMBERS@@", + "[{\"Ref\": \"DefaultUser\"}, {\"Ref\": \"AppUser\"}]"); + cloudFormation(stack, "UpdateStack", update); String stacks = describeStacks(stack, "UPDATE_COMPLETE"); assertEquals("cfn-it-upd-sng-b", outputValue(stacks, "SubnetGroupRef")); try (ElastiCacheClient client = client()) { + assertEquals(2, client.describeUserGroups(r -> r.userGroupId("cfn-it-upd-users")) + .userGroups().getFirst().userIds().size()); assertThrows(CacheSubnetGroupNotFoundException.class, () -> client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-upd-sng-a"))); assertEquals(1, client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-upd-sng-b")) diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java index 0c2fbb77f6..6bc112f2fc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java @@ -12,6 +12,8 @@ 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.CacheSubnetGroup; +import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser; +import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUserGroup; import io.github.hectorvent.floci.services.elasticache.model.Endpoint; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -19,6 +21,7 @@ import org.mockito.ArgumentCaptor; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -253,6 +256,210 @@ class ElastiCacheCfnProvisionerTest { assertEquals("my-sng", r.getPhysicalId()); } + @Test + void userWithPasswordAuthenticationModeSetsArnAndStatus() throws Exception { + ElastiCacheUser user = new ElastiCacheUser("app", "app", AuthMode.PASSWORD, List.of("pw-0123456789abcd"), + "on ~* +@all", "redis", "active", Instant.now()); + user.setArn("arn:aws:elasticache:us-east-1:000000000000:user:app"); + when(cache.createUser(eq("app"), eq("app"), eq(AuthMode.PASSWORD), eq(List.of("pw-0123456789abcd")), + eq("on ~* +@all"), eq("redis"))).thenReturn(user); + StackResource r = resource("AWS::ElastiCache::User", "AppUser"); + + provisioner.provision(r, props(""" + {"UserId":"app","UserName":"app","Engine":"redis","AccessString":"on ~* +@all", + "AuthenticationMode":{"Type":"password","Passwords":["pw-0123456789abcd"]}} + """), ctx(null)); + + assertEquals("app", r.getPhysicalId()); + assertEquals("arn:aws:elasticache:us-east-1:000000000000:user:app", r.getAttributes().get("Arn")); + assertEquals("active", r.getAttributes().get("Status")); + } + + @Test + void userWithNoPasswordRequiredUsesNoAuth() throws Exception { + ElastiCacheUser user = new ElastiCacheUser("d", "default", AuthMode.NO_AUTH, List.of(), "off -@all", + "redis", "active", Instant.now()); + when(cache.createUser(eq("d"), eq("default"), eq(AuthMode.NO_AUTH), any(), eq("off -@all"), eq("redis"))) + .thenReturn(user); + StackResource r = resource("AWS::ElastiCache::User", "Default"); + + provisioner.provision(r, props(""" + {"UserId":"d","UserName":"default","Engine":"redis","AccessString":"off -@all", + "NoPasswordRequired":true} + """), ctx(null)); + + assertEquals("d", r.getPhysicalId()); + } + + @Test + void userRequiresUserIdUserNameAndEngine() throws Exception { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props("{\"Engine\":\"redis\"}"), ctx(null))); + assertThrows(AwsException.class, () -> provisioner.provision(r, props("{\"UserId\":\"u\",\"UserName\":\"u\"}"), ctx(null))); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsPasswordModeWithoutPasswords() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis", + "AuthenticationMode":{"Type":"password"}} + """), ctx(null))); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsPasswordsWithNoPasswordRequiredMode() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis", + "AuthenticationMode":{"Type":"no-password-required","Passwords":["pw"]}} + """), ctx(null))); + assertEquals("InvalidParameterCombination", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsPasswordsWithIamAuthenticationMode() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis", + "AuthenticationMode":{"Type":"iam","Passwords":["pw"]}} + """), ctx(null))); + assertEquals("InvalidParameterCombination", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsConflictingNoPasswordRequiredAndPasswords() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis","NoPasswordRequired":true,"Passwords":["pw"]} + """), ctx(null))); + assertEquals("InvalidParameterCombination", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsConflictingNoPasswordRequiredAndAuthenticationModeType() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis","NoPasswordRequired":true, + "AuthenticationMode":{"Type":"password","Passwords":["pw"]}} + """), ctx(null))); + assertEquals("InvalidParameterCombination", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userRejectsInvalidAuthenticationModeType() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis", + "AuthenticationMode":{"Type":"bogus"}} + """), ctx(null))); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userGroupRequiresUserIdsProperty() { + StackResource r = resource("AWS::ElastiCache::UserGroup", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserGroupId":"team","Engine":"valkey"} + """), ctx(null))); + assertEquals("ValidationException", ex.getErrorCode()); + verify(cache, never()).createUserGroup(any(), any(), any(), any()); + } + + @Test + void userGroupSetsArnAndStatus() throws Exception { + ElastiCacheUserGroup group = new ElastiCacheUserGroup(); + group.setUserGroupId("team"); + group.setArn("arn:aws:elasticache:us-east-1:000000000000:usergroup:team"); + group.setStatus("active"); + when(cache.createUserGroup("team", "redis", List.of("d", "app"), "us-east-1")).thenReturn(group); + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); + + provisioner.provision(r, props(""" + {"UserGroupId":"team","Engine":"redis","UserIds":["d","app"]} + """), ctx(null)); + + assertEquals("team", r.getPhysicalId()); + assertEquals("arn:aws:elasticache:us-east-1:000000000000:usergroup:team", r.getAttributes().get("Arn")); + } + + @Test + void userGroupUpdateAppliesMembershipDelta() throws Exception { + ElastiCacheUserGroup existing = new ElastiCacheUserGroup(); + existing.setUserGroupId("team"); + existing.setEngine("redis"); + existing.setUserIds(new LinkedHashSet<>(List.of("d", "old"))); + existing.setArn("arn"); + existing.setStatus("active"); + when(cache.getUserGroup("team")).thenReturn(existing); + when(cache.setUserGroupMembers(eq("team"), eq(List.of("d", "new")), eq("redis"))).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); + + provisioner.provision(r, props(""" + {"UserGroupId":"team","Engine":"redis","UserIds":["d","new"]} + """), ctx("team")); + + verify(cache, never()).createUserGroup(any(), any(), any(), any()); + verify(cache).setUserGroupMembers(eq("team"), eq(List.of("d", "new")), eq("redis")); + } + + @Test + void userNameChangeIsRejectedBecauseItIsCreateOnly() throws Exception { + ElastiCacheUser existing = new ElastiCacheUser("app", "old-name", AuthMode.NO_AUTH, List.of(), "on ~* +@all", + "redis", "active", Instant.now()); + when(cache.getUser("app")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::User", "AppUser"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, + props("{\"UserId\":\"app\",\"UserName\":\"new-name\",\"Engine\":\"redis\"}"), ctx("app"))); + verify(cache, never()).modifyUser(any(), any(), any(), any(), any(), any()); + } + + @Test + void userGroupEngineChangeIsAppliedInPlace() throws Exception { + ElastiCacheUserGroup existing = new ElastiCacheUserGroup(); + existing.setUserGroupId("team"); + existing.setEngine("redis"); + existing.setArn("arn"); + existing.setStatus("active"); + when(cache.getUserGroup("team")).thenReturn(existing); + when(cache.setUserGroupMembers(eq("team"), eq(List.of()), eq("valkey"))).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); + + provisioner.provision(r, props("{\"UserGroupId\":\"team\",\"Engine\":\"valkey\",\"UserIds\":[]}"), ctx("team")); + + verify(cache).setUserGroupMembers("team", List.of(), "valkey"); + verify(cache, never()).createUserGroup(any(), any(), any(), any()); + } + + @Test + void mixedCaseUserGroupIdIsReusedOnUpdateThroughItsLowercaseForm() throws Exception { + ElastiCacheUserGroup existing = new ElastiCacheUserGroup(); + existing.setUserGroupId("myusers"); + existing.setEngine("redis"); + existing.setArn("arn"); + existing.setStatus("active"); + when(cache.getUserGroup("myusers")).thenReturn(existing); + when(cache.setUserGroupMembers("myusers", List.of(), "redis")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); + + provisioner.provision(r, props("{\"UserGroupId\":\"MyUsers\",\"Engine\":\"redis\",\"UserIds\":[]}"), + ctx("myusers")); + + verify(cache, never()).createUserGroup(any(), any(), any(), any()); + verify(cache).setUserGroupMembers("myusers", List.of(), "redis"); + assertEquals("myusers", r.getPhysicalId()); + } + @Test void transitEncryptionDoesNotTurnOnIamAuthentication() throws Exception { when(cache.createCacheCluster(any())).thenReturn(new CacheCluster("tls", CacheClusterStatus.AVAILABLE, @@ -349,6 +556,81 @@ class ElastiCacheCfnProvisionerTest { assertNull(r.getAttributes().get("__FlociCacheSubnetGroupUpdateSnapshot")); } + @Test + void inPlaceUserUpdateCanBeRolledBackFromSnapshot() throws Exception { + ElastiCacheUser existing = new ElastiCacheUser("app", "app", AuthMode.PASSWORD, List.of("pw-old"), + "on ~* +@all", "redis", "active", Instant.now()); + when(cache.getUser("app")).thenReturn(existing); + ElastiCacheUser modified = new ElastiCacheUser("app", "app", AuthMode.PASSWORD, List.of("pw-new"), + "off -@all", "redis", "active", Instant.now()); + when(cache.modifyUser(eq("app"), eq(AuthMode.PASSWORD), eq(List.of("pw-new")), eq("off -@all"), any(), eq("redis"))) + .thenReturn(modified); + + StackResource r = resource("AWS::ElastiCache::User", "AppUser"); + provisioner.provision(r, props(""" + {"UserId":"app","UserName":"app","Engine":"redis","AccessString":"off -@all", + "AuthenticationMode":{"Type":"password","Passwords":["pw-new"]}} + """), ctx("app")); + + assertTrue(provisioner.rollbackUpdate(r)); + verify(cache).modifyUser("app", AuthMode.PASSWORD, List.of("pw-old"), "on ~* +@all", null, "redis"); + } + + @Test + void inPlaceUserGroupUpdateCanBeRolledBackFromSnapshot() throws Exception { + ElastiCacheUserGroup existing = new ElastiCacheUserGroup(); + existing.setUserGroupId("team"); + existing.setEngine("redis"); + existing.setUserIds(new LinkedHashSet<>(List.of("u1", "u2"))); + existing.setArn("arn"); + existing.setStatus("active"); + when(cache.getUserGroup("team")).thenReturn(existing); + + ElastiCacheUserGroup modified = new ElastiCacheUserGroup(); + modified.setUserGroupId("team"); + modified.setEngine("redis"); + modified.setUserIds(new LinkedHashSet<>(List.of("u1", "u3"))); + modified.setArn("arn"); + modified.setStatus("active"); + when(cache.setUserGroupMembers(eq("team"), eq(List.of("u1", "u3")), eq("redis"))).thenReturn(modified); + + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); + provisioner.provision(r, props(""" + {"UserGroupId":"team","Engine":"redis","UserIds":["u1","u3"]} + """), ctx("team")); + + assertTrue(provisioner.rollbackUpdate(r)); + verify(cache).setUserGroupMembers("team", List.of("u1", "u2"), "redis"); + } + + @Test + void committedUserAndUserGroupUpdateClearsRollbackSnapshots() { + StackResource rUser = resource("AWS::ElastiCache::User", "User"); + rUser.getAttributes().put("__FlociUserUpdateSnapshot", "snapshot-data"); + rUser.setStatus("UPDATE_COMPLETE"); + provisioner.completeUpdate(rUser); + assertNull(rUser.getAttributes().get("__FlociUserUpdateSnapshot")); + + StackResource rGroup = resource("AWS::ElastiCache::UserGroup", "Group"); + rGroup.getAttributes().put("__FlociUserGroupUpdateSnapshot", "snapshot-data"); + rGroup.setStatus("UPDATE_COMPLETE"); + provisioner.completeUpdate(rGroup); + assertNull(rGroup.getAttributes().get("__FlociUserGroupUpdateSnapshot")); + } + + @Test + void clearUpdateClearsUserAndUserGroupSnapshots() { + StackResource rUser = resource("AWS::ElastiCache::User", "User"); + rUser.getAttributes().put("__FlociUserUpdateSnapshot", "snapshot-data"); + provisioner.clearUpdate(rUser); + assertNull(rUser.getAttributes().get("__FlociUserUpdateSnapshot")); + + StackResource rGroup = resource("AWS::ElastiCache::UserGroup", "Group"); + rGroup.getAttributes().put("__FlociUserGroupUpdateSnapshot", "snapshot-data"); + provisioner.clearUpdate(rGroup); + assertNull(rGroup.getAttributes().get("__FlociUserGroupUpdateSnapshot")); + } + @Test void clusterDeletedOutsideTheStackIsRecreatedOnUpdate() throws Exception { when(cache.findCacheClusters("app-cache")).thenReturn(List.of()); @@ -380,15 +662,31 @@ class ElastiCacheCfnProvisionerTest { } @Test - void deleteToleratesAlreadyDeletedButPropagatesOtherFailures() { - doThrow(new AwsException("CacheSubnetGroupNotFoundFault", "gone", 400)) - .when(cache).deleteCacheSubnetGroup("gone"); - provisioner.delete("AWS::ElastiCache::SubnetGroup", "gone", "us-east-1"); + void renamedUserGroupReplacesAndDeletesTheOldOne() throws Exception { + ElastiCacheUserGroup created = new ElastiCacheUserGroup(); + created.setUserGroupId("new-team"); + created.setArn("arn"); + created.setStatus("active"); + when(cache.createUserGroup("new-team", "redis", List.of(), "us-east-1")).thenReturn(created); + StackResource r = resource("AWS::ElastiCache::UserGroup", "Group"); - doThrow(new AwsException("CacheSubnetGroupInUse", "busy", 400)) - .when(cache).deleteCacheSubnetGroup("busy"); + provisioner.provision(r, props("{\"UserGroupId\":\"new-team\",\"Engine\":\"redis\",\"UserIds\":[]}"), ctx("old-team")); + + assertTrue(provisioner.hasReplacementUpdate(r)); + provisioner.completeUpdate(r); + verify(cache).deleteUserGroup("old-team"); + } + + @Test + void deleteToleratesAlreadyDeletedButPropagatesOtherFailures() { + doThrow(new AwsException("UserNotFoundFault", "gone", 404)) + .when(cache).deleteUser("gone"); + provisioner.delete("AWS::ElastiCache::User", "gone", "us-east-1"); + + doThrow(new AwsException("InvalidUserGroupState", "busy", 400)) + .when(cache).deleteUserGroup("busy"); assertThrows(AwsException.class, - () -> provisioner.delete("AWS::ElastiCache::SubnetGroup", "busy", "us-east-1")); + () -> provisioner.delete("AWS::ElastiCache::UserGroup", "busy", "us-east-1")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java index 237a803731..cc8688c806 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java @@ -218,6 +218,42 @@ class ElastiCacheServiceTest { assertThrows(AwsException.class, () -> service.getUserGroup("app-group")).getErrorCode()); } + @Test + void setUserGroupMembersReplacesCompleteMembershipAndEngine() { + service.createUser("default-user-id", "default", AuthMode.PASSWORD, + List.of("default-pass"), "on ~* +@all", null); + service.createUser("app-user-id", "app", AuthMode.PASSWORD, + List.of("app-pass"), "on ~* +@all", null); + service.createUser("extra-user-id", "extra", AuthMode.PASSWORD, + List.of("extra-pass"), "on ~* +@all", null); + service.createUserGroup("set-grp", "redis", List.of("default-user-id", "app-user-id"), "us-east-1"); + + ElastiCacheUserGroup updated = service.setUserGroupMembers("set-grp", + List.of("default-user-id", "extra-user-id"), "redis"); + assertEquals(Set.of("default-user-id", "extra-user-id"), updated.getUserIds()); + assertEquals("redis", updated.getEngine()); + + ElastiCacheUserGroup fetched = service.getUserGroup("set-grp"); + assertEquals(Set.of("default-user-id", "extra-user-id"), fetched.getUserIds()); + } + + @Test + void setUserGroupMembersRejectsInvalidEngineOrMissingDefaultUserForRedis() { + service.createUser("default-user-id", "default", AuthMode.PASSWORD, + List.of("default-pass"), "on ~* +@all", null); + service.createUser("app-user-id", "app", AuthMode.PASSWORD, + List.of("app-pass"), "on ~* +@all", null); + service.createUserGroup("val-grp", "redis", List.of("default-user-id"), "us-east-1"); + + AwsException exMissing = assertThrows(AwsException.class, + () -> service.setUserGroupMembers("val-grp", List.of("app-user-id"), "redis")); + assertEquals("DefaultUserRequired", exMissing.getErrorCode()); + + AwsException exEngine = assertThrows(AwsException.class, + () -> service.setUserGroupMembers("val-grp", List.of("default-user-id"), "unknown")); + assertEquals("InvalidParameterValue", exEngine.getErrorCode()); + } + @Test void userGroupNeedsInTransitEncryptionOnTheReplicationGroup() { service.createReplicationGroup("open", "test", AuthMode.NO_AUTH, null, "us-east-1"); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/UserAuthenticationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/UserAuthenticationTest.java new file mode 100644 index 0000000000..69082d1bcd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/UserAuthenticationTest.java @@ -0,0 +1,60 @@ +package io.github.hectorvent.floci.services.elasticache; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.elasticache.model.AuthMode; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UserAuthenticationTest { + + @Test + void nothingGivenResolvesToNull() { + assertNull(UserAuthentication.resolve(null, List.of(), false)); + } + + @Test + void passwordsWithoutTypeMeanPasswordAuthentication() { + UserAuthentication auth = UserAuthentication.resolve(null, List.of("p"), false); + assertEquals(AuthMode.PASSWORD, auth.mode()); + assertEquals(List.of("p"), auth.passwords()); + } + + @Test + void noPasswordRequiredWithoutTypeMeansNoAuth() { + assertEquals(AuthMode.NO_AUTH, UserAuthentication.resolve(null, List.of(), true).mode()); + } + + @Test + void typeIsMatchedCaseInsensitively() { + assertEquals(AuthMode.IAM, UserAuthentication.resolve("IAM", List.of(), false).mode()); + assertEquals(AuthMode.NO_AUTH, UserAuthentication.resolve("No-Password-Required", List.of(), false).mode()); + } + + @Test + void passwordTypeWithoutPasswordsIsRejected() { + AwsException e = assertThrows(AwsException.class, + () -> UserAuthentication.resolve("password", List.of(), false)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + } + + @Test + void conflictingInputsAreRejected() { + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, + () -> UserAuthentication.resolve(null, List.of("p"), true)).getErrorCode()); + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, + () -> UserAuthentication.resolve("password", List.of("p"), true)).getErrorCode()); + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, + () -> UserAuthentication.resolve("iam", List.of("p"), false)).getErrorCode()); + } + + @Test + void unknownTypeIsRejected() { + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, + () -> UserAuthentication.resolve("kerberos", List.of(), false)).getErrorCode()); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index e9e475ac0b..0ed1f75d55 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -92,6 +92,8 @@ AWS::EKS::Cluster EksCfnProvisioner AWS::EKS::Nodegroup EksCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner AWS::ElastiCache::SubnetGroup ElastiCacheCfnProvisioner +AWS::ElastiCache::User ElastiCacheCfnProvisioner +AWS::ElastiCache::UserGroup ElastiCacheCfnProvisioner AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 8284295185..9d347bc821 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -87,7 +87,7 @@ type_order: AWS::RDS: [DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup] AWS::ElastiCache: - [CacheCluster, SubnetGroup] + [CacheCluster, SubnetGroup, User, UserGroup] AWS::Redshift: [Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup] AWS::RedshiftServerless: @@ -174,6 +174,8 @@ notes: AWS::RDS::DBInstance: starts a real container AWS::RDS::DBCluster: starts a real container AWS::ElastiCache::CacheCluster: 'starts a real container; modifying an existing cluster in place is not supported' + AWS::ElastiCache::User: Tags are ignored + AWS::ElastiCache::UserGroup: Tags are ignored AWS::Redshift::ClusterSecurityGroup: accepted; no EC2-Classic security group model AWS::Redshift::Cluster: single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported AWS::RedshiftServerless::Namespace: 'ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form'