fix(elasticache): enforce IAM auth engine version, TLS, and user constraints (#6502)

Enforce ElastiCache IAM authentication's engine version floor (Redis OSS 7.0, Valkey 7.2), in-transit encryption and IAM user ID rules on create and modify, and refuse an AuthToken with TransitEncryptionEnabled=false. TransitEncryptionEnabled no longer implies IAM authentication.

Refs #4502
This commit is contained in:
noy-solvin authored and GitHub committed 2026-11-03 08:15:21 -04:00
1 parent 70a185a3aa
commit 886f626b4d
5 files changed
+488 -42

No files matched your search

@@ -113,13 +113,11 @@ public class ElastiCacheQueryHandler {
"ReplicationGroupId is required.", AwsNamespaces.EC, 400);
}
String transitEncryption = params.getFirst("TransitEncryptionEnabled");
AuthMode authMode;
if (authToken != null && !authToken.isBlank()) {
authMode = AuthMode.PASSWORD;
} else if ("true".equalsIgnoreCase(transitEncryption)) {
authMode = AuthMode.IAM;
} else {
// Bug #4502: Do not conflate TransitEncryptionEnabled=true with IAM auth mode
authMode = AuthMode.NO_AUTH;
}
@@ -162,7 +160,8 @@ public class ElastiCacheQueryHandler {
atRest == null ? null : !"false".equalsIgnoreCase(atRest.trim()),
params.getFirst("KmsKeyId"),
optionalInt(params.getFirst("SnapshotRetentionLimit")),
params.getFirst("SnapshotWindow"), params.getFirst("TransitEncryptionMode"));
params.getFirst("SnapshotWindow"), params.getFirst("TransitEncryptionMode"),
boolParam(params, "TransitEncryptionEnabled"));
}
private static Integer optionalInt(String value) {
@@ -455,7 +454,8 @@ public class ElastiCacheQueryHandler {
boolParam(params, "AtRestEncryptionEnabled"),
region,
parseTags(params),
boolParam(params, "AutoMinorVersionUpgrade"));
boolParam(params, "AutoMinorVersionUpgrade"),
boolParam(params, "TransitEncryptionEnabled"));
CacheCluster cluster = "memcached".equalsIgnoreCase(engine)
? memcachedService.createCacheCluster(request)
: service.createCacheCluster(request);
@@ -472,9 +472,7 @@ public class ElastiCacheQueryHandler {
if (authToken != null && !authToken.isBlank()) {
return AuthMode.PASSWORD;
}
if ("true".equalsIgnoreCase(params.getFirst("TransitEncryptionEnabled"))) {
return AuthMode.IAM;
}
// Bug #4502: Open-access TLS clusters remain NO_AUTH
return AuthMode.NO_AUTH;
}
@@ -1058,7 +1056,7 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
} else {
xml.elem("NumCacheNodes", (long) numCacheNodes)
.elem("AuthTokenEnabled", c.getAuthMode() == AuthMode.PASSWORD)
.elem("TransitEncryptionEnabled", c.getAuthMode() != null && c.getAuthMode() != AuthMode.NO_AUTH)
.elem("TransitEncryptionEnabled", c.isEncryptedInTransit())
.elem("AtRestEncryptionEnabled", c.isAtRestEncryptionEnabled())
.elem("SnapshotRetentionLimit", (long) c.getSnapshotRetentionLimit())
.elem("SnapshotWindow", c.getSnapshotWindow() != null
@@ -72,6 +72,8 @@ public class ElastiCacheService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);
private static final Pattern USER_ID_PATTERN =
Pattern.compile("^[a-zA-Z][a-zA-Z0-9-]{0,127}$");
private final AccountAwareStorageBackend<ReplicationGroup> groups;
private final AccountAwareStorageBackend<CacheCluster> cacheClusters;
/**
@@ -224,7 +226,11 @@ public class ElastiCacheService implements ResourceProvider {
ReplicationGroupSettings settings = request.settings() != null
? request.settings() : ReplicationGroupSettings.defaults();
settings.validate();
settings.validateTransitEncryption(request.authMode() != AuthMode.NO_AUTH);
// In AWS ElastiCache, auth tokens require in-transit encryption.
// Issue #4502: Reject upfront before provisioning rather than creating plaintext cache.
requireTransitEncryptionWithAuthToken(request.authMode(), request.authToken(),
settings.transitEncryptionEnabled());
settings.validateTransitEncryption(effectiveTransitEncryption(request));
// resolved with the other validations, before a port is taken or a container started
ReplicationGroupSettings resolvedSettings =
settings.withKmsKeyId(resolveKmsKeyArn(settings.kmsKeyId(), request.region()));
@@ -236,6 +242,30 @@ public class ElastiCacheService implements ResourceProvider {
}
}
static boolean isEngineVersionAtLeast(String version, String required) {
if (version == null || version.isBlank()) {
return true;
}
String[] vParts = version.split("\\.");
String[] rParts = required.split("\\.");
int max = Math.max(vParts.length, rParts.length);
for (int i = 0; i < max; i++) {
int v = i < vParts.length ? parseVersionPart(vParts[i]) : 0;
int r = i < rParts.length ? parseVersionPart(rParts[i]) : 0;
if (v != r) {
return v > r;
}
}
return true;
}
private static int parseVersionPart(String s) {
try {
return Integer.parseInt(s.replaceAll("\\D.*", ""));
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Checks the user groups a create names and marks them in use until the create finishes,
* under {@link #userGroupLock} so the check and the claim cannot straddle a DeleteUserGroup.
@@ -245,11 +275,13 @@ public class ElastiCacheService implements ResourceProvider {
return List.of();
}
String engine = engineFor(request);
String engineVersion = request.engineVersion() != null ? request.engineVersion() : defaultEngineVersion(engine);
boolean transitEncrypted = effectiveTransitEncryption(request);
synchronized (userGroupLock) {
List<String> reserved = new ArrayList<>();
for (String userGroupId : request.userGroupIds()) {
ElastiCacheUserGroup userGroup = getUserGroup(userGroupId);
requireAssociable(userGroup, request.authMode() != null && request.authMode() != AuthMode.NO_AUTH, engine);
requireAssociable(userGroup, transitEncrypted, engine, engineVersion);
reserved.add(userGroupReservationKey(userGroup.getUserGroupId()));
}
reserved.forEach(key -> reservedUserGroups.merge(key, 1, Integer::sum));
@@ -290,6 +322,15 @@ public class ElastiCacheService implements ResourceProvider {
}
try {
String engine = engineFor(request);
String engineVersion = request.engineVersion() != null ? request.engineVersion() : defaultEngineVersion(engine);
if (request.authMode() == AuthMode.IAM) {
requireIamEngineVersionCompatible(engine, engineVersion);
if (!isTransitEncryptionRequested(request)) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
}
if (resolveClusterEnabled(request)) {
return provisionClusterModeGroup(request, resolvedSettings);
}
@@ -377,7 +418,16 @@ public class ElastiCacheService implements ResourceProvider {
}
synchronized (lockFor("rg:" + groupId)) {
groups.put(groupId, group);
// Re-verify under userGroupLock immediately before publishing to close race window (#4502)
synchronized (userGroupLock) {
if (group.getUserGroupIds() != null) {
for (String userGroupId : group.getUserGroupIds()) {
ElastiCacheUserGroup userGroup = getUserGroup(userGroupId);
requireAssociable(userGroup, group.isEncryptedInTransit(), group.getEngine(), group.getEngineVersion());
}
}
groups.put(groupId, group);
}
if (handle != null) {
proxyManager.startProxy(groupId, authMode, proxyPort,
handle.getHost(), handle.getPort(),
@@ -478,7 +528,16 @@ public class ElastiCacheService implements ResourceProvider {
group.setClusterNodes(nodes);
applyCommonAttributes(group, request, resolvedSettings);
groups.put(groupId, group);
// Re-verify under userGroupLock immediately before publishing to close race window (#4502)
synchronized (userGroupLock) {
if (group.getUserGroupIds() != null) {
for (String userGroupId : group.getUserGroupIds()) {
ElastiCacheUserGroup userGroup = getUserGroup(userGroupId);
requireAssociable(userGroup, group.isEncryptedInTransit(), group.getEngine(), group.getEngineVersion());
}
}
groups.put(groupId, group);
}
LOG.infov("Cluster-mode replication group {0} created, configuration endpoint={1}:{2}",
groupId, endpointHost, String.valueOf(configurationEndpoint.port()));
return group;
@@ -515,6 +574,28 @@ public class ElastiCacheService implements ResourceProvider {
}
}
private static boolean isTransitEncryptionRequested(CreateReplicationGroupRequest request) {
return request.settings() != null && Boolean.TRUE.equals(request.settings().transitEncryptionEnabled());
}
private static void requireTransitEncryptionWithAuthToken(AuthMode authMode, String authToken,
Boolean transitEncryptionEnabled) {
boolean hasAuthToken = (authToken != null && !authToken.isBlank())
|| authMode == AuthMode.PASSWORD;
if (hasAuthToken && Boolean.FALSE.equals(transitEncryptionEnabled)) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use an auth token.", 400);
}
}
private static boolean effectiveTransitEncryption(CreateReplicationGroupRequest request) {
if (request.settings() != null && request.settings().transitEncryptionEnabled() != null) {
return request.settings().transitEncryptionEnabled();
}
return request.authMode() == AuthMode.PASSWORD
|| (request.authToken() != null && !request.authToken().isBlank());
}
private String engineFor(CreateReplicationGroupRequest request) {
return request.engine() != null && !request.engine().isBlank()
? normalizeEngine(request.engine())
@@ -1272,18 +1353,64 @@ public class ElastiCacheService implements ResourceProvider {
Boolean atRestEncryptionEnabled,
String region,
Map<String, String> tags,
Boolean autoMinorVersionUpgrade) {
public CreateCacheClusterRequest(String cacheClusterId, String engine, String engineVersion,
String cacheNodeType, Integer numCacheNodes, Integer port, AuthMode authMode,
String authToken, String cacheParameterGroupName, String cacheSubnetGroupName,
Integer snapshotRetentionLimit, String snapshotWindow, String preferredMaintenanceWindow,
String preferredAvailabilityZone, List<String> securityGroupIds, String networkType,
String ipDiscovery, Boolean atRestEncryptionEnabled, String region,
Boolean autoMinorVersionUpgrade,
Boolean transitEncryptionEnabled) {
public CreateCacheClusterRequest(
String cacheClusterId,
String engine,
String engineVersion,
String cacheNodeType,
Integer numCacheNodes,
Integer port,
AuthMode authMode,
String authToken,
String cacheParameterGroupName,
String cacheSubnetGroupName,
Integer snapshotRetentionLimit,
String snapshotWindow,
String preferredMaintenanceWindow,
String preferredAvailabilityZone,
List<String> securityGroupIds,
String networkType,
String ipDiscovery,
Boolean atRestEncryptionEnabled,
String region,
Map<String, String> tags) {
this(cacheClusterId, engine, engineVersion, cacheNodeType, numCacheNodes, port, authMode,
authToken, cacheParameterGroupName, cacheSubnetGroupName, snapshotRetentionLimit,
snapshotWindow, preferredMaintenanceWindow, preferredAvailabilityZone, securityGroupIds,
networkType, ipDiscovery, atRestEncryptionEnabled, region, tags, null);
this(cacheClusterId, engine, engineVersion, cacheNodeType, numCacheNodes, port,
authMode, authToken, cacheParameterGroupName, cacheSubnetGroupName,
snapshotRetentionLimit, snapshotWindow, preferredMaintenanceWindow,
preferredAvailabilityZone, securityGroupIds, networkType, ipDiscovery,
atRestEncryptionEnabled, region, tags, null, null);
}
public CreateCacheClusterRequest(
String cacheClusterId,
String engine,
String engineVersion,
String cacheNodeType,
Integer numCacheNodes,
Integer port,
AuthMode authMode,
String authToken,
String cacheParameterGroupName,
String cacheSubnetGroupName,
Integer snapshotRetentionLimit,
String snapshotWindow,
String preferredMaintenanceWindow,
String preferredAvailabilityZone,
List<String> securityGroupIds,
String networkType,
String ipDiscovery,
Boolean atRestEncryptionEnabled,
String region,
Map<String, String> tags,
Boolean autoMinorVersionUpgrade) {
this(cacheClusterId, engine, engineVersion, cacheNodeType, numCacheNodes, port,
authMode, authToken, cacheParameterGroupName, cacheSubnetGroupName,
snapshotRetentionLimit, snapshotWindow, preferredMaintenanceWindow,
preferredAvailabilityZone, securityGroupIds, networkType, ipDiscovery,
atRestEncryptionEnabled, region, tags, autoMinorVersionUpgrade, null);
}
}
@@ -1350,6 +1477,10 @@ public class ElastiCacheService implements ResourceProvider {
throw new AwsException("InvalidParameterValue",
"NumCacheNodes should be 1 if engine is " + engine, 400);
}
// In AWS ElastiCache, auth tokens require in-transit encryption.
// Issue #4502: Reject upfront before provisioning rather than creating plaintext cache.
requireTransitEncryptionWithAuthToken(request.authMode(), request.authToken(),
request.transitEncryptionEnabled());
// The snapshot members take the replication group's checks, so one request worded one way
// is refused the same way whichever action carries it.
cacheClusterSettings(request).validate();
@@ -1514,6 +1645,7 @@ public class ElastiCacheService implements ResourceProvider {
cluster.setIpDiscovery(request.ipDiscovery() != null && !request.ipDiscovery().isBlank()
? request.ipDiscovery() : "ipv4");
cluster.setAtRestEncryptionEnabled(Boolean.TRUE.equals(request.atRestEncryptionEnabled()));
cluster.setTransitEncryptionEnabled(request.transitEncryptionEnabled());
cluster.setAutoMinorVersionUpgrade(request.autoMinorVersionUpgrade());
if (request.securityGroupIds() != null && !request.securityGroupIds().isEmpty()) {
cluster.setSecurityGroupIds(new ArrayList<>(request.securityGroupIds()));
@@ -1654,7 +1786,7 @@ public class ElastiCacheService implements ResourceProvider {
@Override
public TransitEncryption transitEncryption() {
return cluster.getAuthMode() != AuthMode.NO_AUTH
return cluster.isEncryptedInTransit()
? TransitEncryption.REQUIRED : TransitEncryption.NONE;
}
});
@@ -1814,9 +1946,17 @@ public class ElastiCacheService implements ResourceProvider {
for (String id : userGroupIdsToAdd) {
Optional<ElastiCacheUserGroup> userGroup = userGroups.get(normalizeUserGroupId(id));
if (userGroup.isPresent()) {
requireAssociable(userGroup.get(), encryptedInTransit, group.getEngine());
requireAssociable(userGroup.get(), encryptedInTransit, group.getEngine(), group.getEngineVersion());
userGroupsToAdd.add(userGroup.get().getUserGroupId());
} else if (findUser(id).isPresent()) {
ElastiCacheUser u = findUser(id).get();
if (u.getAuthMode() == AuthMode.IAM) {
if (!encryptedInTransit) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
requireIamEngineVersionCompatible(group.getEngine(), group.getEngineVersion());
}
directUsersToAdd.add(id);
} else {
throw userGroupNotFound(id);
@@ -1922,6 +2062,9 @@ public class ElastiCacheService implements ResourceProvider {
public ElastiCacheUser createUser(String userId, String userName, AuthMode authMode,
List<String> passwords, String accessString, String engine,
Map<String, String> tags) {
if (authMode == AuthMode.IAM) {
validateIamUser(userId, userName);
}
if (findUser(userId).isPresent()) {
throw new AwsException("UserAlreadyExists",
"User " + userId + " already exists.", 400);
@@ -2226,6 +2369,30 @@ public class ElastiCacheService implements ResourceProvider {
synchronized (userGroupLock) {
String nextEngine = normalizedEngine != null ? normalizedEngine : user.getEngine();
AuthMode nextAuthMode = authMode != null ? authMode : user.getAuthMode();
if (nextAuthMode == AuthMode.IAM) {
validateIamUser(userId, user.getUserName());
for (ElastiCacheUserGroup userGroup : userGroups.scan(k -> true)) {
if (userGroup.getUserIds().contains(userId)) {
for (ReplicationGroup group : replicationGroupsUsing(userGroup.getUserGroupId())) {
if (!group.isEncryptedInTransit()) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
requireIamEngineVersionCompatible(group.getEngine(), group.getEngineVersion());
}
}
}
// Validate replication groups where user is directly associated (#4502)
for (ReplicationGroup group : groups.scan(k -> true)) {
if (group.getAssociatedUserIds() != null && group.getAssociatedUserIds().contains(userId)) {
if (!group.isEncryptedInTransit()) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
requireIamEngineVersionCompatible(group.getEngine(), group.getEngineVersion());
}
}
}
if (!nextEngine.equals(user.getEngine()) || nextAuthMode != user.getAuthMode()) {
// the user must still satisfy every user group that holds it
for (ElastiCacheUserGroup userGroup : userGroups.scan(k -> true)) {
@@ -2354,6 +2521,15 @@ public class ElastiCacheService implements ResourceProvider {
requireEngineCompatible(newEngine, id, cacheEngine);
}
}
if (hasIamUser(members)) {
for (ReplicationGroup group : replicationGroupsUsing(id)) {
if (!group.isEncryptedInTransit()) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
requireIamEngineVersionCompatible(group.getEngine(), group.getEngineVersion());
}
}
userGroup.setEngine(newEngine);
userGroup.setUserIds(members);
userGroups.put(id, userGroup);
@@ -2474,7 +2650,14 @@ public class ElastiCacheService implements ResourceProvider {
}
/** RBAC needs in-transit encryption, and a valkey user group only serves valkey caches. */
private static void requireAssociable(ElastiCacheUserGroup userGroup, boolean encryptedInTransit, String engine) {
private void requireAssociable(ElastiCacheUserGroup userGroup, boolean encryptedInTransit, String engine, String engineVersion) {
if (hasIamUser(userGroup)) {
if (!encryptedInTransit) {
throw new AwsException("InvalidParameterCombination",
"Transit encryption must be enabled to use IAM authentication.", 400);
}
requireIamEngineVersionCompatible(engine, engineVersion);
}
if (!encryptedInTransit) {
throw new AwsException("InvalidParameterCombination",
"User group " + userGroup.getUserGroupId()
@@ -2483,6 +2666,49 @@ public class ElastiCacheService implements ResourceProvider {
requireEngineCompatible(userGroup.getEngine(), userGroup.getUserGroupId(), engine);
}
private boolean hasIamUser(Collection<String> userIds) {
if (userIds == null) {
return false;
}
for (String uid : userIds) {
ElastiCacheUser u = users.get(uid).orElse(null);
if (u != null && u.getAuthMode() == AuthMode.IAM) {
return true;
}
}
return false;
}
private boolean hasIamUser(ElastiCacheUserGroup userGroup) {
return userGroup != null && hasIamUser(userGroup.getUserIds());
}
private static void validateIamUser(String userId, String userName) {
if (!USER_ID_PATTERN.matcher(userId).matches()) {
throw new AwsException("InvalidParameterValue",
"The parameter UserId must be between 1 and 128 characters long, must contain only letters, numbers, and hyphens, and must start with a letter.", 400);
}
if ("default".equalsIgnoreCase(userName)) {
throw new AwsException("InvalidParameterValue",
"The default user cannot be configured to use IAM authentication.", 400);
}
if (!userId.equals(userName)) {
throw new AwsException("InvalidParameterCombination",
"UserId must be equal to UserName when AuthenticationMode Type is IAM.", 400);
}
}
private static void requireIamEngineVersionCompatible(String engine, String engineVersion) {
if ("redis".equalsIgnoreCase(engine) && !isEngineVersionAtLeast(engineVersion, "7.0")) {
throw new AwsException("InvalidParameterCombination",
"IAM authentication is only supported for Redis version 7.0 and above.", 400);
}
if ("valkey".equalsIgnoreCase(engine) && !isEngineVersionAtLeast(engineVersion, "7.2")) {
throw new AwsException("InvalidParameterCombination",
"IAM authentication is only supported for Valkey version 7.2 and above.", 400);
}
}
private static void requireEngineCompatible(String userGroupEngine, String userGroupId, String replicationGroupEngine) {
if ("valkey".equals(userGroupEngine) && !"valkey".equals(replicationGroupEngine)) {
throw new AwsException("InvalidParameterCombination",
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elasticache.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -37,6 +38,7 @@ public class CacheCluster {
private boolean atRestEncryptionEnabled;
private List<String> securityGroupIds = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
private Boolean transitEncryptionEnabled;
private String serverlessCacheName;
private String ownerAccountId;
private String userGroupId;
@@ -148,4 +150,12 @@ public class CacheCluster {
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
public Boolean getTransitEncryptionEnabled() { return transitEncryptionEnabled; }
public void setTransitEncryptionEnabled(Boolean transitEncryptionEnabled) { this.transitEncryptionEnabled = transitEncryptionEnabled; }
@JsonIgnore
public boolean isEncryptedInTransit() {
return transitEncryptionEnabled != null ? transitEncryptionEnabled : (authMode != null && authMode != AuthMode.NO_AUTH);
}
}
@@ -6,6 +6,7 @@ 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.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
@@ -46,6 +47,7 @@ class ElastiCacheQueryHandlerTest {
memcachedService = mock(ElastiCacheMemcachedService.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getRegion()).thenReturn("us-east-1");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
when(regionResolver.getAccountId()).thenReturn("000000000000");
handler = new ElastiCacheQueryHandler(sigV4Validator, service, memcachedService, regionResolver,
mock(ElastiCacheServerlessQueryHandler.class));
@@ -891,4 +893,54 @@ class ElastiCacheQueryHandlerTest {
assertTrue(((String) response.getEntity()).contains("<TagList></TagList>"),
(String) response.getEntity());
}
@Test
void describeUsers_outputsMinimumEngineVersion6ForBothIamAndNonIam() {
ElastiCacheUser iamUser = new ElastiCacheUser(
"iam-app", "iam-app", AuthMode.IAM, List.of(), "on ~* +@all", "redis", "active", Instant.now());
ElastiCacheUser passUser = new ElastiCacheUser(
"pass-app", "pass-app", AuthMode.PASSWORD, List.of("secret"), "on ~* +@all", "redis", "active", Instant.now());
when(service.listUsers(eq("iam-app"), isNull())).thenReturn(List.of(iamUser));
when(service.listUsers(eq("pass-app"), isNull())).thenReturn(List.of(passUser));
MultivaluedMap<String, String> iamParams = params();
iamParams.putSingle("UserId", "iam-app");
Response iamResponse = handler.handle("DescribeUsers", iamParams, "us-east-1");
assertEquals(200, iamResponse.getStatus());
String iamBody = (String) iamResponse.getEntity();
assertTrue(iamBody.contains("<MinimumEngineVersion>6.0</MinimumEngineVersion>"),
"IAM user XML representation must output MinimumEngineVersion 6.0");
assertFalse(iamBody.contains("<MinimumEngineVersion>7.0</MinimumEngineVersion>"));
MultivaluedMap<String, String> passParams = params();
passParams.putSingle("UserId", "pass-app");
Response passResponse = handler.handle("DescribeUsers", passParams, "us-east-1");
assertEquals(200, passResponse.getStatus());
String passBody = (String) passResponse.getEntity();
assertTrue(passBody.contains("<MinimumEngineVersion>6.0</MinimumEngineVersion>"),
"Non-IAM user XML representation must output MinimumEngineVersion 6.0");
assertFalse(passBody.contains("<MinimumEngineVersion>7.0</MinimumEngineVersion>"));
}
@Test
void createReplicationGroup_transitEncryptionWithoutAuthTokenDoesNotDefaultToIam() {
MultivaluedMap<String, String> params = params();
params.putSingle("ReplicationGroupId", "tls-grp");
params.putSingle("ReplicationGroupDescription", "TLS replication group");
params.putSingle("TransitEncryptionEnabled", "true");
ArgumentCaptor<ElastiCacheService.CreateReplicationGroupRequest> captor =
ArgumentCaptor.forClass(ElastiCacheService.CreateReplicationGroupRequest.class);
ReplicationGroup mockGroup = new ReplicationGroup("tls-grp", "TLS replication group",
ReplicationGroupStatus.AVAILABLE, AuthMode.NO_AUTH, new Endpoint("localhost", 6379), Instant.now(), 6379);
when(service.createReplicationGroup(captor.capture())).thenReturn(mockGroup);
Response response = handler.handle("CreateReplicationGroup", params, "us-east-1");
assertEquals(200, response.getStatus());
ElastiCacheService.CreateReplicationGroupRequest capturedRequest = captor.getValue();
assertEquals(AuthMode.NO_AUTH, capturedRequest.authMode(),
"TransitEncryptionEnabled=true without AuthToken must not default to IAM (should be NO_AUTH)");
}
}
@@ -450,14 +450,16 @@ class ElastiCacheServiceTest {
@Test
void userGroupMembersDecideEachUsersAuthenticationMode() {
service.createReplicationGroup("grp", "test", AuthMode.IAM, null, "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0",
null, null, null, null, null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
assertFalse(service.hasMembers("grp"),
"a cache with no users associated keeps the group level authentication mode");
service.createUser("default-user-id", "default", AuthMode.PASSWORD,
List.of("default-pass"), "on ~* +@all", null);
service.createUser("iam-user-id", "iam-app", AuthMode.IAM, List.of(), "on ~* +@all", null);
service.createUserGroup("iam-users", "redis", List.of("default-user-id", "iam-user-id"), "us-east-1");
service.createUser("iam-app", "iam-app", AuthMode.IAM, List.of(), "on ~* +@all", null);
service.createUserGroup("iam-users", "redis", List.of("default-user-id", "iam-app"), "us-east-1");
service.modifyReplicationGroup("grp", List.of("iam-users"), null);
assertTrue(service.hasMembers("grp"));
@@ -466,7 +468,7 @@ class ElastiCacheServiceTest {
"a password user cannot connect with an IAM token");
assertNull(service.memberAuthMode("grp", "anyone"));
service.modifyUserGroup("iam-users", null, List.of("iam-user-id"), null);
service.modifyUserGroup("iam-users", null, List.of("iam-app"), null);
assertNull(service.memberAuthMode("grp", "iam-app"), "removing the member revokes its access");
}
@@ -474,7 +476,7 @@ class ElastiCacheServiceTest {
void anEmptyUserGroupAdmitsNobody() {
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp", "test", AuthMode.IAM, null, "us-east-1", "valkey", null, null, null, null, null,
null, null, null, null, null, null, ReplicationGroupSettings.defaults(), Map.of(), null, null));
null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
service.createUserGroup("empty-users", "valkey", List.of(), "us-east-1");
service.modifyReplicationGroup("grp", List.of("empty-users"), null);
@@ -524,7 +526,9 @@ class ElastiCacheServiceTest {
@Test
void removeUserGroupsDropsEveryUserGroupAndTheAccessControl() {
service.createReplicationGroup("grp", "test", AuthMode.IAM, null, "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0",
null, null, null, null, null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
service.createUser("default-user-id", "default", AuthMode.PASSWORD,
List.of("default-pass"), "on ~* +@all", null);
service.createUserGroup("first-users", "redis", List.of("default-user-id"), "us-east-1");
@@ -756,7 +760,9 @@ class ElastiCacheServiceTest {
@Test
void validatePasswordAdmitsNoAuthUserWithAnyPassword() {
service.createReplicationGroup("grp-nopass", "test", AuthMode.IAM, null, "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp-nopass", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0",
null, null, null, null, null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
service.createUser("nopass-user-id", "nopass-user", AuthMode.NO_AUTH,
List.of(), "on ~* +@all", null);
service.modifyReplicationGroup("grp-nopass", List.of("nopass-user-id"), null);
@@ -769,11 +775,13 @@ class ElastiCacheServiceTest {
@Test
void memberAuthModeResolvesPasswordIamAndNoAuthUsers() {
service.createReplicationGroup("grp-mixed", "test", AuthMode.IAM, null, "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp-mixed", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0",
null, null, null, null, null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
service.createUser("u-def", "default", AuthMode.PASSWORD, List.of("def-pass"), "on ~* +@all", null);
service.createUser("u-iam", "iam-user", AuthMode.IAM, List.of(), "on ~* +@all", null);
service.createUser("iam-user", "iam-user", AuthMode.IAM, List.of(), "on ~* +@all", null);
service.createUser("u-nopass", "nopass-user", AuthMode.NO_AUTH, List.of(), "on ~* +@all", null);
service.modifyReplicationGroup("grp-mixed", List.of("u-def", "u-iam", "u-nopass"), null);
service.modifyReplicationGroup("grp-mixed", List.of("u-def", "iam-user", "u-nopass"), null);
assertTrue(service.hasMembers("grp-mixed"));
assertEquals(AuthMode.PASSWORD, service.memberAuthMode("grp-mixed", "default"));
@@ -785,13 +793,15 @@ class ElastiCacheServiceTest {
@Test
void disabledUserCannotAuthenticateAndHasNoMemberAuthMode() {
service.createReplicationGroup("grp-disabled", "test", AuthMode.IAM, null, "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp-disabled", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0",
null, null, null, null, null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(), null, null));
service.createUser("u-def-off", "default", AuthMode.NO_AUTH, List.of(), "off -@all", null);
service.createUser("u-pass-off", "disabled-pass", AuthMode.PASSWORD, List.of("secret"), "off -@all", null);
service.createUser("u-iam-off", "disabled-iam", AuthMode.IAM, List.of(), "off -@all", null);
service.createUser("disabled-iam", "disabled-iam", AuthMode.IAM, List.of(), "off -@all", null);
service.createUser("u-pass-on", "enabled-pass", AuthMode.PASSWORD, List.of("secret"), "on ~* +@all", null);
service.modifyReplicationGroup("grp-disabled",
List.of("u-def-off", "u-pass-off", "u-iam-off", "u-pass-on"), null);
List.of("u-def-off", "u-pass-off", "disabled-iam", "u-pass-on"), null);
assertTrue(service.hasMembers("grp-disabled"));
@@ -2098,8 +2108,8 @@ class ElastiCacheServiceTest {
List.of("default-pass"), "on ~* +@all", null);
svc.createUserGroup("shared-ug", "redis", List.of("default-user-id"), "us-east-1");
svc.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"grp", "test", AuthMode.IAM, null, "us-east-1", "redis", null, null, null, null, null,
null, null, null, null, null, null, ReplicationGroupSettings.defaults(), Map.of(),
"grp", "test", AuthMode.IAM, null, "us-east-1", "redis", "7.0", null, null, null, null,
null, null, null, null, null, null, new ReplicationGroupSettings(null, null, null, null, null, true), Map.of(),
List.of("shared-ug"), null));
});
accountA.start();
@@ -2204,6 +2214,22 @@ class ElastiCacheServiceTest {
assertTrue(service.findCacheClusters("too-big").isEmpty());
}
@Test
void createCacheClusterWithAuthTokenAndTransitEncryptionDisabledIsRefused() {
ElastiCacheService.CreateCacheClusterRequest req = new ElastiCacheService.CreateCacheClusterRequest(
"no-tls-auth", "redis", null, null,
1, null, AuthMode.PASSWORD, "secret-auth-token", null, null,
null, null, null, null, null, null, null, null, "us-east-1", Map.of(), null, false);
AwsException ex = assertThrows(AwsException.class, () -> service.createCacheCluster(req));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("Transit encryption must be enabled to use an auth token.", ex.getMessage());
verify(containerManager, never()).tryStart(eq("no-tls-auth"), anyString(), any());
assertTrue(service.findCacheClusters("no-tls-auth").isEmpty());
}
@Test
void duplicateCacheClusterIdIsRefused() {
service.createCacheCluster(cacheClusterRequest("dupe", "redis", 1));
@@ -2833,4 +2859,138 @@ class ElastiCacheServiceTest {
verify(containerManager, never()).stop(any());
verify(containerManager).stopByGroupId("no-docker");
}
@Test
void createIamUserRejectsInvalidUserIdFormat() {
AwsException ex = assertThrows(AwsException.class, () ->
service.createUser("1-invalid-id", "1-invalid-id", AuthMode.IAM, List.of(), "on ~* +@all", "redis"));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void createIamUserRejectsMismatchedUserIdAndUserName() {
AwsException ex = assertThrows(AwsException.class, () ->
service.createUser("iam-user-1", "iam-user-2", AuthMode.IAM, List.of(), "on ~* +@all", "redis"));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("UserId must be equal to UserName when AuthenticationMode Type is IAM."));
}
@Test
void createIamUserRejectsDefaultUserName() {
AwsException ex = assertThrows(AwsException.class, () ->
service.createUser("default", "default", AuthMode.IAM, List.of(), "on ~* +@all", "redis"));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("The default user cannot be configured to use IAM authentication."));
}
@Test
void modifyUserSwitchingToIamRejectsMismatchedUserIdAndUserName() {
service.createUser("mismatch-id", "mismatch-name", AuthMode.PASSWORD, List.of("pass"), "on ~* +@all", "redis");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyUser("mismatch-id", AuthMode.IAM, List.of(), null, null, null));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("UserId must be equal to UserName when AuthenticationMode Type is IAM."));
}
@Test
void modifyUserSwitchingToIamRejectsDefaultUserName() {
service.createUser("custom-default", "default", AuthMode.PASSWORD, List.of("pass"), "on ~* +@all", "redis");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyUser("custom-default", AuthMode.IAM, List.of(), null, null, null));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("The default user cannot be configured to use IAM authentication."));
}
@Test
void modifyUserSwitchingToIamRejectsInvalidUserIdFormat() {
service.createUser("1-bad-id", "1-bad-id", AuthMode.PASSWORD, List.of("pass"), "on ~* +@all", "redis");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyUser("1-bad-id", AuthMode.IAM, List.of(), null, null, null));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void createReplicationGroupWithIamRequiresTransitEncryption() {
AwsException ex = assertThrows(AwsException.class, () ->
service.createReplicationGroup("grp-iam-no-tls", "test", AuthMode.IAM, null, "us-east-1"));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("Transit encryption must be enabled to use IAM authentication."));
}
@Test
void createReplicationGroupWithIamRejectsRedisVersionBelow7() {
ElastiCacheService.CreateReplicationGroupRequest req = new ElastiCacheService.CreateReplicationGroupRequest(
"grp-redis-62", "test", AuthMode.IAM, null, "us-east-1", "redis", "6.2",
null, null, null, null, null, null, null, null, null, null,
ReplicationGroupSettings.defaults(), Map.of(), null, null);
AwsException ex = assertThrows(AwsException.class, () -> service.createReplicationGroup(req));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("IAM authentication is only supported for Redis version 7.0 and above."));
}
@Test
void createReplicationGroupWithIamRejectsValkeyVersionBelow72() {
ElastiCacheService.CreateReplicationGroupRequest req = new ElastiCacheService.CreateReplicationGroupRequest(
"grp-valkey-70", "test", AuthMode.IAM, null, "us-east-1", "valkey", "7.0",
null, null, null, null, null, null, null, null, null, null,
ReplicationGroupSettings.defaults(), Map.of(), null, null);
AwsException ex = assertThrows(AwsException.class, () -> service.createReplicationGroup(req));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertTrue(ex.getMessage().contains("IAM authentication is only supported for Valkey version 7.2 and above."));
}
@Test
void modifyReplicationGroupAssociatingUserGroupWithIamUsersRequiresTransitEncryption() {
service.createReplicationGroup("grp-no-transit", "test", AuthMode.NO_AUTH, null, "us-east-1");
service.createUser("iam-member", "iam-member", AuthMode.IAM, List.of(), "on ~* +@all", "redis");
service.createUserGroup("iam-ug-notls", "redis", List.of("default", "iam-member"), "us-east-1");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyReplicationGroup("grp-no-transit", List.of("iam-ug-notls"), null));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void modifyReplicationGroupAssociatingUserGroupWithIamUsersRejectsRedisVersionBelow7() {
ElastiCacheService.CreateReplicationGroupRequest req = new ElastiCacheService.CreateReplicationGroupRequest(
"grp-redis-62-enc", "test", AuthMode.PASSWORD, "some-token", "us-east-1", "redis", "6.2",
null, null, null, null, null, null, null, null, null, null,
ReplicationGroupSettings.defaults(), Map.of(), null, null);
service.createReplicationGroup(req);
service.createUser("iam-redis-user", "iam-redis-user", AuthMode.IAM, List.of(), "on ~* +@all", "redis");
service.createUserGroup("iam-redis-ug", "redis", List.of("default", "iam-redis-user"), "us-east-1");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyReplicationGroup("grp-redis-62-enc", List.of("iam-redis-ug"), null));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void modifyReplicationGroupAssociatingUserGroupWithIamUsersRejectsValkeyVersionBelow72() {
ElastiCacheService.CreateReplicationGroupRequest req = new ElastiCacheService.CreateReplicationGroupRequest(
"grp-valkey-70-enc", "test", AuthMode.PASSWORD, "some-token", "us-east-1", "valkey", "7.0",
null, null, null, null, null, null, null, null, null, null,
ReplicationGroupSettings.defaults(), Map.of(), null, null);
service.createReplicationGroup(req);
service.createUser("iam-valkey-user", "iam-valkey-user", AuthMode.IAM, List.of(), "on ~* +@all", "valkey");
service.createUserGroup("iam-valkey-ug", "valkey", List.of("iam-valkey-user"), "us-east-1");
AwsException ex = assertThrows(AwsException.class, () ->
service.modifyReplicationGroup("grp-valkey-70-enc", List.of("iam-valkey-ug"), null));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
}