feat(elasticache): authenticate each RBAC user by its own authentication mode (#4536)

* feat(elasticache): authenticate each RBAC user by its own authentication mode

Resolve issue #4457.

- Add hasMembers and memberAuthMode resolution to ElastiCacheService and PasswordValidator callback.
- Allow AuthMode.NO_AUTH users to be admitted with any password (Redis ACL nopass semantics).
- Refactor ElastiCacheAuthProxy to validate each user according to their configured AuthMode (IAM, PASSWORD, NO_AUTH) when the cluster has members.
- Fallback single-arg AUTH to authToken or default user.
- Add comprehensive unit and integration tests.

* fix(elasticache): address review feedback on per-user RBAC authentication

- Allow passwordless access when default member requires no auth
- Support explicit default username with group auth token
- Clean up group associations when deleting users to avoid lockout
- Reject duplicate usernames in ModifyReplicationGroup with DuplicateUserNameFault
- Validate password strictly against the resolved user's auth mode

* fix(elasticache): require auth when default member is missing and handle HELLO AUTH

- ElastiCacheAuthProxy: require auth when group has members but no default member

- AbstractRedisAuthProxy: intercept HELLO with AUTH option on open caches and validate credentials before forwarding

- Add unit and integration tests for missing default user and HELLO AUTH on open cache

* fix(elasticache): require auth for disabled default user and reject disabled members

- ElastiCacheUser: evaluate ACL accessString to determine whether user is enabled (on) or disabled (off)

- ElastiCacheService: reject authentication for disabled users and exclude them from memberAuthMode

- ElastiCacheAuthProxy: remove obsolete unreachable comment on NO_AUTH switch arm

- Add unit and integration tests covering disabled default user and disabled members
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-30 10:41:51 -04:00
1 parent 955c11dc56
commit 184b50e2ba
9 files changed
+1164 -20

No files matched your search

@@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheAuthProxy;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
@@ -41,6 +42,7 @@ import java.net.UnknownHostException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -298,7 +300,7 @@ public class ElastiCacheService implements ResourceProvider {
if (handle != null) {
proxyManager.startProxy(groupId, authMode, proxyPort,
handle.getHost(), handle.getPort(),
(username, password) -> validatePassword(groupId, username, password));
groupAuthenticator(groupId));
} else {
LOG.warnv("Replication group {0} created without a backing cache container: no "
+ "Docker daemon is reachable. Metadata operations work; connections to "
@@ -376,7 +378,7 @@ public class ElastiCacheService implements ResourceProvider {
ElastiCacheContainerHandle handle = handles.get(i);
proxyManager.startProxy(node.getMemberClusterId(), authMode, node.getProxyPort(),
handle.getHost(), handle.getPort(),
(username, password) -> validatePassword(groupId, username, password));
groupAuthenticator(groupId));
startedProxyKeys.add(node.getMemberClusterId());
}
@@ -837,7 +839,7 @@ public class ElastiCacheService implements ResourceProvider {
group.setContainerPort(handle.getPort());
proxyManager.startProxy(groupId, group.getAuthMode(), group.getProxyPort(),
handle.getHost(), handle.getPort(),
(username, password) -> validatePassword(groupId, username, password));
groupAuthenticator(groupId));
} else {
// Cleared rather than left alone: whatever the record carried describes a
// container from the previous process, and nothing must read it as live.
@@ -989,7 +991,7 @@ public class ElastiCacheService implements ResourceProvider {
ElastiCacheContainerHandle handle = handles.get(i);
proxyManager.startProxy(node.getMemberClusterId(), group.getAuthMode(), node.getProxyPort(),
handle.getHost(), handle.getPort(),
(username, password) -> validatePassword(groupId, username, password));
groupAuthenticator(groupId));
startedProxyKeys.add(node.getMemberClusterId());
}
@@ -1459,11 +1461,26 @@ public class ElastiCacheService implements ResourceProvider {
ReplicationGroup group = getReplicationGroup(groupId);
// every check before any change: the store hands out its own object, so a mutation
// made before a later refusal would stay visible
Set<String> nextUserIds = new HashSet<>(group.getAssociatedUserIds());
if (userIdsToRemove != null) {
nextUserIds.removeAll(userIdsToRemove);
}
if (userIdsToAdd != null) {
for (String userId : userIdsToAdd) {
getUser(userId);
}
nextUserIds.addAll(userIdsToAdd);
}
Set<String> seenUserNames = new HashSet<>();
for (String userId : nextUserIds) {
ElastiCacheUser u = users.get(userId).orElse(null);
if (u != null && !seenUserNames.add(u.getUserName())) {
throw new AwsException("DuplicateUserNameFault",
"Duplicate user name " + u.getUserName() + " in user group.", 400);
}
}
settings.applyTo(group);
if (userIdsToAdd != null) {
group.getAssociatedUserIds().addAll(userIdsToAdd);
@@ -1583,6 +1600,13 @@ public class ElastiCacheService implements ResourceProvider {
throw new AwsException("UserNotFoundFault", "User " + userId + " not found.", 404);
}
users.delete(userId);
for (ReplicationGroup group : groups.scan(k -> true)) {
synchronized (lockFor("rg:" + group.getReplicationGroupId())) {
if (group.getAssociatedUserIds().remove(userId)) {
groups.put(group.getReplicationGroupId(), group);
}
}
}
LOG.infov("ElastiCache user {0} deleted", userId);
}
@@ -1604,21 +1628,82 @@ public class ElastiCacheService implements ResourceProvider {
if (group.getAuthToken() != null && password.equals(group.getAuthToken())) {
return true;
}
// Fall back to the "default" PASSWORD user associated with this group
// Fall back to the "default" user associated with this group
Set<String> groupUserIds = group.getAssociatedUserIds();
return groupUserIds.stream()
ElastiCacheUser defaultUser = groupUserIds.stream()
.map(id -> users.get(id).orElse(null))
.filter(u -> u != null
&& "default".equals(u.getUserName())
&& u.getAuthMode() == AuthMode.PASSWORD)
.anyMatch(u -> u.getPasswords() != null && u.getPasswords().contains(password));
.filter(u -> u != null && "default".equals(u.getUserName()))
.findFirst()
.orElse(null);
if (defaultUser == null || !defaultUser.isEnabled()) {
return false;
}
if (defaultUser.getAuthMode() == AuthMode.NO_AUTH) {
return true;
}
if (defaultUser.getAuthMode() == AuthMode.PASSWORD) {
return defaultUser.getPasswords() != null && defaultUser.getPasswords().contains(password);
}
return false;
}
// AUTH username password form: find user by userName, scoped to group
Set<String> groupUserIds = group.getAssociatedUserIds();
return groupUserIds.stream()
ElastiCacheUser targetUser = groupUserIds.stream()
.map(id -> users.get(id).orElse(null))
.filter(u -> u != null && username.equals(u.getUserName()) && u.getAuthMode() == AuthMode.PASSWORD)
.anyMatch(u -> u.getPasswords() != null && u.getPasswords().contains(password));
.filter(u -> u != null && username.equals(u.getUserName()))
.findFirst()
.orElse(null);
if (targetUser == null || !targetUser.isEnabled()) {
return false;
}
if (targetUser.getAuthMode() == AuthMode.NO_AUTH) {
return true;
}
if (targetUser.getAuthMode() == AuthMode.PASSWORD) {
return targetUser.getPasswords() != null && targetUser.getPasswords().contains(password);
}
return false;
}
public boolean hasMembers(String groupId) {
ReplicationGroup group = groups.get(groupId).orElse(null);
if (group == null) {
return false;
}
return group.getAssociatedUserIds().stream().anyMatch(id -> users.get(id).isPresent());
}
public AuthMode memberAuthMode(String groupId, String username) {
ReplicationGroup group = groups.get(groupId).orElse(null);
if (group == null) {
return null;
}
String target = (username == null || username.isEmpty()) ? "default" : username;
return group.getAssociatedUserIds().stream()
.map(id -> users.get(id).orElse(null))
.filter(u -> u != null && target.equals(u.getUserName()) && u.isEnabled())
.map(ElastiCacheUser::getAuthMode)
.findFirst()
.orElse(null);
}
private ElastiCacheAuthProxy.PasswordValidator groupAuthenticator(String groupId) {
return new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return ElastiCacheService.this.validatePassword(groupId, username, password);
}
@Override
public boolean hasMembers() {
return ElastiCacheService.this.hasMembers(groupId);
}
@Override
public AuthMode memberAuthMode(String username) {
return ElastiCacheService.this.memberAuthMode(groupId, username);
}
};
}
// AWS allows only redis and valkey.
@@ -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;
@@ -56,4 +57,24 @@ public class ElastiCacheUser {
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
@JsonIgnore
public boolean isEnabled() {
return isAccessStringOn(accessString);
}
public static boolean isAccessStringOn(String accessString) {
if (accessString == null || accessString.isBlank()) {
return false;
}
boolean on = false;
for (String token : accessString.trim().split("\\s+")) {
if ("on".equalsIgnoreCase(token)) {
on = true;
} else if ("off".equalsIgnoreCase(token)) {
on = false;
}
}
return on;
}
}
@@ -154,7 +154,7 @@ public abstract class AbstractRedisAuthProxy {
return;
}
if (cmd[0].equalsIgnoreCase("HELLO")) {
if (authRequired()) {
if (authRequired() || hasAuthOption(cmd)) {
if (handleHello(client, cmd)) {
return;
}
@@ -199,7 +199,7 @@ public abstract class AbstractRedisAuthProxy {
return;
}
boolean authenticated = !authRequired() || authenticate(username, password);
boolean authenticated = authenticate(username, password);
if (!authenticated) {
writeResponse(client, INVALID_AUTH_RESPONSE);
closeQuietly(client);
@@ -267,7 +267,7 @@ public abstract class AbstractRedisAuthProxy {
writeResponse(client, HELLO_NOAUTH_RESPONSE);
return false;
}
if (authRequired() && !authenticate(username, password)) {
if (authProvided && !authenticate(username, password)) {
writeResponse(client, WRONGPASS_RESPONSE);
return false;
}
@@ -390,4 +390,13 @@ public abstract class AbstractRedisAuthProxy {
}
out.flush();
}
private static boolean hasAuthOption(String[] cmd) {
for (int i = 2; i < cmd.length; i++) {
if ("AUTH".equalsIgnoreCase(cmd[i])) {
return true;
}
}
return false;
}
}
@@ -33,15 +33,51 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
@Override
protected boolean authRequired() {
if (passwordValidator.hasMembers()) {
AuthMode defaultMode = passwordValidator.memberAuthMode("default");
if (defaultMode != null) {
return defaultMode != AuthMode.NO_AUTH;
}
return true;
}
return authMode != AuthMode.NO_AUTH;
}
@Override
protected boolean authenticate(String username, String password) {
String effectiveUser = (username == null || username.isEmpty()) ? "default" : username;
if (passwordValidator.hasMembers()) {
if ("default".equals(effectiveUser)) {
if (passwordValidator.validatePassword(username, password)) {
return true;
}
AuthMode defaultMode = passwordValidator.memberAuthMode("default");
if (defaultMode == null) {
defaultMode = passwordValidator.memberAuthMode(username);
}
if (defaultMode == AuthMode.IAM) {
return sigV4Validator.validate(password, groupId, "default");
}
return false;
}
AuthMode userMode = passwordValidator.memberAuthMode(effectiveUser);
if (userMode == null && username != null) {
userMode = passwordValidator.memberAuthMode(username);
}
if (userMode != null) {
return switch (userMode) {
case IAM -> sigV4Validator.validate(password, groupId, effectiveUser);
case PASSWORD, NO_AUTH -> passwordValidator.validatePassword(effectiveUser, password);
};
}
return false;
}
return switch (authMode) {
case IAM -> sigV4Validator.validate(password, groupId, username);
case IAM -> sigV4Validator.validate(password, groupId, effectiveUser);
case PASSWORD -> passwordValidator.validatePassword(username, password);
case NO_AUTH -> true; // unreachable: authRequired() is false for NO_AUTH
case NO_AUTH -> true;
};
}
@@ -62,10 +98,18 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
}
/**
* Callback interface for password validation, provided by ElastiCacheService.
* Callback interface for credential checks, provided by ElastiCacheService.
*/
@FunctionalInterface
public interface PasswordValidator {
boolean validatePassword(String username, String password);
default boolean hasMembers() {
return false;
}
default AuthMode memberAuthMode(String username) {
return null;
}
}
}
@@ -381,6 +381,426 @@ class ElastiCacheIntegrationTest {
equalTo(GROUP_ID + "-reused"));
}
@Test
@Order(16)
void transitEncryptionReplicationGroupAuthenticatesPasswordAndNoAuthUsers() throws Exception {
String transitGroupId = "it-ec-transit-rbac";
String passUserId = "it-transit-pass-user";
String passUserName = "it-transit-pass-name";
String passUserPass = "secret-pass-123";
String noAuthUserId = "it-transit-noauth-user";
String noAuthUserName = "it-transit-noauth-name";
// Create replication group with TransitEncryptionEnabled=true and NO AuthToken -> AuthMode.IAM
int proxyPort =
given()
.formParam("Action", "CreateReplicationGroup")
.formParam("ReplicationGroupId", transitGroupId)
.formParam("ReplicationGroupDescription", "Transit encryption RBAC test group")
.formParam("TransitEncryptionEnabled", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath()
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port");
try {
// Create a password user and a no-password user
given()
.formParam("Action", "CreateUser")
.formParam("UserId", passUserId)
.formParam("UserName", passUserName)
.formParam("AuthenticationMode.Type", "password")
.formParam("AuthenticationMode.Passwords.member.1", passUserPass)
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "CreateUser")
.formParam("UserId", noAuthUserId)
.formParam("UserName", noAuthUserName)
.formParam("AuthenticationMode.Type", "no-password-required")
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Associate users with the replication group
given()
.formParam("Action", "ModifyReplicationGroup")
.formParam("ReplicationGroupId", transitGroupId)
.formParam("UserGroupIdsToAdd.member.1", passUserId)
.formParam("UserGroupIdsToAdd.member.2", noAuthUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// 1. Password user authenticates with correct password
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("AUTH", passUserName, passUserPass));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
// 2. Password user with wrong password is rejected
String wrongPassReply = sendCommand(proxyPort, respArray("AUTH", passUserName, "wrong-password"));
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", wrongPassReply);
// 3. No-password user is admitted with any password
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("AUTH", noAuthUserName, "arbitrary-password"));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
} finally {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", transitGroupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", noAuthUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
}
}
@Test
@Order(17)
void replicationGroupWithNoAuthDefaultMemberAdmitsUnauthenticatedClients() throws Exception {
String groupId = "it-ec-def-noauth";
String defUserId = "it-def-noauth-uid";
String passUserId = "it-def-pass-uid";
String passUserName = "custom-user";
String password = "secret-pass-123";
// Create replication group with AuthMode.NO_AUTH
int proxyPort =
given()
.formParam("Action", "CreateReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("ReplicationGroupDescription", "Test group for no-auth default member")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath()
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port");
try {
// Create user "default" with NO_AUTH
given()
.formParam("Action", "CreateUser")
.formParam("UserId", defUserId)
.formParam("UserName", "default")
.formParam("Engine", "redis")
.formParam("AuthenticationMode.Type", "no-password-required")
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Create password user
given()
.formParam("Action", "CreateUser")
.formParam("UserId", passUserId)
.formParam("UserName", passUserName)
.formParam("Engine", "redis")
.formParam("AuthenticationMode.Type", "password")
.formParam("AuthenticationMode.Passwords.member.1", password)
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Associate both users with the replication group
given()
.formParam("Action", "ModifyReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("UserGroupIdsToAdd.member.1", defUserId)
.formParam("UserGroupIdsToAdd.member.2", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// 1. Passwordless client sends PING directly without AUTH and reaches the cache
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
// 2. Client authenticating as custom user with wrong password is rejected
String wrongPassReply = sendCommand(proxyPort, respArray("AUTH", passUserName, "wrong-password"));
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", wrongPassReply);
// 3. Client authenticating as custom user with correct password succeeds
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("AUTH", passUserName, password));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
// 4. Client authenticating via HELLO with wrong password is rejected
String wrongHelloReply = sendCommand(proxyPort, respArray("HELLO", "3", "AUTH", passUserName, "wrong-password"));
assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n", wrongHelloReply);
// 5. Client authenticating via HELLO with correct password succeeds
String helloReply = sendCommand(proxyPort, respArray("HELLO", "3", "AUTH", passUserName, password));
assertTrue(helloReply.startsWith("%") || helloReply.startsWith("*") || helloReply.startsWith("+"),
"HELLO response must be returned from backend");
} finally {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", defUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
}
}
@Test
@Order(18)
void replicationGroupWithMembersWithoutDefaultMemberRequiresAuth() throws Exception {
String groupId = "it-ec-nodef-members";
String passUserId = "it-nodef-pass-uid";
String passUserName = "nodef-user";
String password = "secret-pass-456";
// Create replication group with AuthMode.NO_AUTH
int proxyPort =
given()
.formParam("Action", "CreateReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("ReplicationGroupDescription", "Test group with members but no default member")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath()
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port");
try {
// Create password user (NOT named default)
given()
.formParam("Action", "CreateUser")
.formParam("UserId", passUserId)
.formParam("UserName", passUserName)
.formParam("Engine", "redis")
.formParam("AuthenticationMode.Type", "password")
.formParam("AuthenticationMode.Passwords.member.1", password)
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Associate only this password user with the replication group (no default user)
given()
.formParam("Action", "ModifyReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("UserGroupIdsToAdd.member.1", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// 1. Unauthenticated client sends PING directly without AUTH and is rejected with NOAUTH
String noAuthReply = sendCommand(proxyPort, respArray("PING"));
assertEquals("-NOAUTH Authentication required.\r\n", noAuthReply);
// 2. Client authenticating with correct password succeeds
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("AUTH", passUserName, password));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
} finally {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
}
}
@Test
@Order(19)
void replicationGroupWithDisabledDefaultUserRequiresAuth() throws Exception {
String groupId = "it-ec-disabled-def";
String defUserId = "it-disabled-def-uid";
String passUserId = "it-pass-member-uid";
String passUserName = "member-user";
String password = "secret-pass-789";
// Create replication group with AuthMode.NO_AUTH
int proxyPort =
given()
.formParam("Action", "CreateReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("ReplicationGroupDescription", "Test group with disabled default user")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.xmlPath()
.getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port");
try {
// Create user "default" with no-password-required and access string "off -@all" (per ElastiCache guide)
given()
.formParam("Action", "CreateUser")
.formParam("UserId", defUserId)
.formParam("UserName", "default")
.formParam("Engine", "redis")
.formParam("AuthenticationMode.Type", "no-password-required")
.formParam("AccessString", "off -@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Create password user
given()
.formParam("Action", "CreateUser")
.formParam("UserId", passUserId)
.formParam("UserName", passUserName)
.formParam("Engine", "redis")
.formParam("AuthenticationMode.Type", "password")
.formParam("AuthenticationMode.Passwords.member.1", password)
.formParam("AccessString", "on ~* +@all")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// Associate both users with the replication group
given()
.formParam("Action", "ModifyReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.formParam("UserGroupIdsToAdd.member.1", defUserId)
.formParam("UserGroupIdsToAdd.member.2", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
// 1. Unauthenticated client sends PING directly without AUTH and is rejected with NOAUTH
String noAuthReply = sendCommand(proxyPort, respArray("PING"));
assertEquals("-NOAUTH Authentication required.\r\n", noAuthReply);
// 2. Client authenticating as disabled default user is rejected
String disabledAuthReply = sendCommand(proxyPort, respArray("AUTH", "default", "any-password"));
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", disabledAuthReply);
// 3. Single-arg AUTH targeting disabled default user is rejected
String singleArgReply = sendCommand(proxyPort, respArray("AUTH", "any-password"));
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", singleArgReply);
// 4. Password user with wrong password is rejected
String wrongPassReply = sendCommand(proxyPort, respArray("AUTH", passUserName, "wrong-pass"));
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", wrongPassReply);
// 5. Password user with correct password succeeds
try (Socket socket = openSocket(proxyPort)) {
write(socket, respArray("AUTH", passUserName, password));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
assertEquals("+PONG\r\n", readLine(socket));
}
} finally {
given()
.formParam("Action", "DeleteReplicationGroup")
.formParam("ReplicationGroupId", groupId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", defUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
given()
.formParam("Action", "DeleteUser")
.formParam("UserId", passUserId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/");
}
}
static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
@@ -193,6 +193,107 @@ class ElastiCacheServiceTest {
assertFalse(service.validatePassword("grp", null, "wrong-token"));
}
@Test
void validatePasswordAdmitsNoAuthUserWithAnyPassword() {
service.createReplicationGroup("grp-nopass", "test", AuthMode.IAM, null, "us-east-1");
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);
assertTrue(service.hasMembers("grp-nopass"));
assertEquals(AuthMode.NO_AUTH, service.memberAuthMode("grp-nopass", "nopass-user"));
assertTrue(service.validatePassword("grp-nopass", "nopass-user", "any-password"));
assertTrue(service.validatePassword("grp-nopass", "nopass-user", ""));
}
@Test
void memberAuthModeResolvesPasswordIamAndNoAuthUsers() {
service.createReplicationGroup("grp-mixed", "test", AuthMode.IAM, null, "us-east-1");
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("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);
assertTrue(service.hasMembers("grp-mixed"));
assertEquals(AuthMode.PASSWORD, service.memberAuthMode("grp-mixed", "default"));
assertEquals(AuthMode.PASSWORD, service.memberAuthMode("grp-mixed", null));
assertEquals(AuthMode.IAM, service.memberAuthMode("grp-mixed", "iam-user"));
assertEquals(AuthMode.NO_AUTH, service.memberAuthMode("grp-mixed", "nopass-user"));
assertNull(service.memberAuthMode("grp-mixed", "unknown-user"));
}
@Test
void disabledUserCannotAuthenticateAndHasNoMemberAuthMode() {
service.createReplicationGroup("grp-disabled", "test", AuthMode.IAM, null, "us-east-1");
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("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);
assertTrue(service.hasMembers("grp-disabled"));
// Disabled users have no effective memberAuthMode
assertNull(service.memberAuthMode("grp-disabled", "default"));
assertNull(service.memberAuthMode("grp-disabled", null));
assertNull(service.memberAuthMode("grp-disabled", "disabled-pass"));
assertNull(service.memberAuthMode("grp-disabled", "disabled-iam"));
// Enabled user resolves normally
assertEquals(AuthMode.PASSWORD, service.memberAuthMode("grp-disabled", "enabled-pass"));
// Disabled users cannot validate password
assertFalse(service.validatePassword("grp-disabled", "default", "any-password"));
assertFalse(service.validatePassword("grp-disabled", null, "any-password"));
assertFalse(service.validatePassword("grp-disabled", "disabled-pass", "secret"));
// Enabled user validates password successfully
assertTrue(service.validatePassword("grp-disabled", "enabled-pass", "secret"));
}
@Test
void deleteUserCleansUpGroupAssociationAndHasMembers() {
service.createReplicationGroup("grp-stale", "test", AuthMode.NO_AUTH, null, "us-east-1");
service.createUser("uid-stale", "user-stale", AuthMode.PASSWORD, List.of("pass123"), "on ~* +@all", null);
service.modifyReplicationGroup("grp-stale", List.of("uid-stale"), null);
assertTrue(service.hasMembers("grp-stale"));
assertTrue(service.getReplicationGroup("grp-stale").getAssociatedUserIds().contains("uid-stale"));
service.deleteUser("uid-stale");
assertFalse(service.hasMembers("grp-stale"));
assertFalse(service.getReplicationGroup("grp-stale").getAssociatedUserIds().contains("uid-stale"));
}
@Test
void modifyReplicationGroupRejectsDuplicateUserNames() {
service.createReplicationGroup("grp-dup", "test", AuthMode.NO_AUTH, null, "us-east-1");
service.createUser("uid-1", "same-name", AuthMode.PASSWORD, List.of("pass1"), "on ~* +@all", null);
service.createUser("uid-2", "same-name", AuthMode.NO_AUTH, List.of(), "on ~* +@all", null);
// Attempting to associate both users in the same call must fail with DuplicateUserNameFault
AwsException ex = assertThrows(AwsException.class,
() -> service.modifyReplicationGroup("grp-dup", List.of("uid-1", "uid-2"), null));
assertEquals("DuplicateUserNameFault", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
// Associate uid-1 first
service.modifyReplicationGroup("grp-dup", List.of("uid-1"), null);
assertTrue(service.getReplicationGroup("grp-dup").getAssociatedUserIds().contains("uid-1"));
// Attempting to add uid-2 with the same username must also fail
AwsException ex2 = assertThrows(AwsException.class,
() -> service.modifyReplicationGroup("grp-dup", List.of("uid-2"), null));
assertEquals("DuplicateUserNameFault", ex2.getErrorCode());
assertEquals(400, ex2.getHttpStatus());
// Validate password must not allow bypassing password check
assertTrue(service.validatePassword("grp-dup", "same-name", "pass1"));
assertFalse(service.validatePassword("grp-dup", "same-name", "wrong-pass"));
}
@Test
void failedProvisioningRollsBackContainerAndReleasesProxyPort() {
ElastiCacheContainerHandle handle =
@@ -6,6 +6,8 @@ import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Users persisted before the engine field existed must deserialize with the redis
@@ -26,4 +28,31 @@ class ElastiCacheUserModelTest {
ElastiCacheUser.class);
assertEquals("redis", user.getEngine());
}
@Test
void isAccessStringOnEvaluatesTokensCorrectly() {
assertTrue(ElastiCacheUser.isAccessStringOn("on ~* +@all"));
assertTrue(ElastiCacheUser.isAccessStringOn("on"));
assertTrue(ElastiCacheUser.isAccessStringOn("+@all on ~*"));
assertTrue(ElastiCacheUser.isAccessStringOn("off +@all on"));
assertFalse(ElastiCacheUser.isAccessStringOn("off -@all"));
assertFalse(ElastiCacheUser.isAccessStringOn("off"));
assertFalse(ElastiCacheUser.isAccessStringOn("on ~* off"));
assertFalse(ElastiCacheUser.isAccessStringOn("~* +@all"));
assertFalse(ElastiCacheUser.isAccessStringOn(null));
assertFalse(ElastiCacheUser.isAccessStringOn(""));
assertFalse(ElastiCacheUser.isAccessStringOn(" "));
}
@Test
void userIsEnabledReflectsAccessString() {
ElastiCacheUser enabledUser = new ElastiCacheUser();
enabledUser.setAccessString("on ~* +@all");
assertTrue(enabledUser.isEnabled());
ElastiCacheUser disabledUser = new ElastiCacheUser();
disabledUser.setAccessString("off -@all");
assertFalse(disabledUser.isEnabled());
}
}
@@ -232,7 +232,7 @@ class AbstractRedisAuthProxyHandshakeTest {
try (ServerSocket backendServer = new ServerSocket(0)) {
TestProxy proxy = startProxy(backendServer, false, USERNAME, PASSWORD);
try (Socket client = openClient(proxy.proxyPort())) {
byte[] command = respArray("HELLO", "3", "AUTH", "unused", "unused");
byte[] command = respArray("HELLO", "3", "SETNAME", "test-client");
write(client, command);
try (Socket backend = acceptBackend(backendServer)) {
@@ -248,6 +248,42 @@ class AbstractRedisAuthProxyHandshakeTest {
}
}
@Test
void helloWithAuthOnOpenCacheAuthenticatesAndStripsCredentials() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0)) {
TestProxy proxy = startProxy(backendServer, false, USERNAME, PASSWORD);
try (Socket client = openClient(proxy.proxyPort())) {
write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD));
try (Socket backend = acceptBackend(backendServer)) {
byte[] expected = respArray("HELLO", "3");
assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));
write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));
assertEquals("+HELLO\r\n", readLine(client));
}
assertEquals(1, proxy.authenticationAttempts());
} finally {
proxy.stop();
}
}
}
@Test
void helloWithWrongAuthOnOpenCacheRejectsWithWrongPass() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0)) {
TestProxy proxy = startProxy(backendServer, false, USERNAME, PASSWORD);
try (Socket client = openClient(proxy.proxyPort())) {
write(client, respArray("HELLO", "3", "AUTH", USERNAME, "wrong"));
assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n",
readLine(client));
assertEquals(1, proxy.authenticationAttempts());
} finally {
proxy.stop();
}
}
}
private static TestProxy startProxy(ServerSocket backendServer, boolean authRequired,
String username, String password) throws IOException {
return startProxy(backendServer, authRequired, username, password,
@@ -0,0 +1,399 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ElastiCacheAuthProxyTest {
@Test
void groupWithIamAuthModeAuthenticatesPasswordUserWhenAssociated() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "app-user".equals(username) && "app-pass".equals(password);
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "app-user".equals(username) ? AuthMode.PASSWORD : null;
}
};
// Replication group created with TransitEncryptionEnabled and no AuthToken -> AuthMode.IAM
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-1", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate("app-user", "app-pass"),
"password user must authenticate even if replication group mode is IAM");
assertFalse(proxy.authenticate("app-user", "wrong-pass"));
assertFalse(proxy.authenticate("outsider", "any-pass"));
}
@Test
void groupWithPasswordAuthModeAuthenticatesIamUserWhenAssociated() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
when(sigV4Validator.validate("valid-sigv4", "grp-2", "iam-user")).thenReturn(true);
when(sigV4Validator.validate("bad-sigv4", "grp-2", "iam-user")).thenReturn(false);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "iam-user".equals(username) ? AuthMode.IAM : null;
}
};
// Replication group created with AuthToken -> AuthMode.PASSWORD
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-2", AuthMode.PASSWORD, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate("iam-user", "valid-sigv4"),
"IAM user must authenticate with SigV4 token even if replication group mode is PASSWORD");
assertFalse(proxy.authenticate("iam-user", "bad-sigv4"));
}
@Test
void groupWithIamAuthModeAuthenticatesNoAuthUserWhenAssociated() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "nopass-user".equals(username);
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "nopass-user".equals(username) ? AuthMode.NO_AUTH : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-nopass", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate("nopass-user", "any-password"));
assertTrue(proxy.authenticate("nopass-user", ""));
}
@Test
void singleArgAuthFallsBackToDefaultMemberOrAuthToken() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
if (username == null && "token123".equals(password)) {
return true;
}
return (username == null || "default".equals(username)) && "def-pass".equals(password);
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return (username == null || "default".equals(username)) ? AuthMode.PASSWORD : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-3", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate(null, "def-pass"), "single-arg AUTH matches member named default");
assertFalse(proxy.authenticate(null, "wrong-pass"));
}
@Test
void groupWithMembersNormalizesEmptyUsernameToDefaultForIamValidation() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
when(sigV4Validator.validate("valid-sigv4", "grp-empty", "default")).thenReturn(true);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return (username == null || username.isEmpty()) ? AuthMode.IAM : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-empty", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate("", "valid-sigv4"),
"AUTH \"\" <token> must validate against the default member's IAM token, not an empty username");
}
@Test
void groupWithNoMembersRequiresDefaultUserForSingleArgIamAuth() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
when(sigV4Validator.validate("valid-sigv4", "grp-legacy-iam", "default")).thenReturn(true);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return false;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-legacy-iam", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(proxy.authenticate(null, "valid-sigv4"),
"single-arg AUTH on an unassociated IAM cache must validate the token's User against default");
}
@Test
void groupWithNoMembersPreservesLegacyIamAndAuthTokenBehaviour() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
when(sigV4Validator.validate("valid-sigv4", "grp-4", "anyone")).thenReturn(true);
ElastiCacheAuthProxy.PasswordValidator passwordValidator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "group-token".equals(password);
}
@Override
public boolean hasMembers() {
return false;
}
};
ElastiCacheAuthProxy iamProxy = new ElastiCacheAuthProxy("grp-4", AuthMode.IAM, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(iamProxy.authenticate("anyone", "valid-sigv4"),
"unassociated IAM cache admits any valid IAM user");
ElastiCacheAuthProxy passProxy = new ElastiCacheAuthProxy("grp-5", AuthMode.PASSWORD, "127.0.0.1", 6379,
passwordValidator, sigV4Validator);
assertTrue(passProxy.authenticate(null, "group-token"),
"unassociated password cache admits group auth token");
}
@Test
void authRequiredDependsOnDefaultMemberAuthModeWhenClusterHasMembers() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator validatorNoAuthDefault = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "default".equals(username) ? AuthMode.NO_AUTH : AuthMode.PASSWORD;
}
};
ElastiCacheAuthProxy.PasswordValidator validatorPasswordDefault = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "default".equals(username) ? AuthMode.PASSWORD : null;
}
};
ElastiCacheAuthProxy.PasswordValidator validatorIamDefault = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "default".equals(username) ? AuthMode.IAM : null;
}
};
ElastiCacheAuthProxy.PasswordValidator validatorWithoutMembers = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return false;
}
};
ElastiCacheAuthProxy proxyNoAuth = new ElastiCacheAuthProxy("grp-noauth", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorNoAuthDefault, sigV4Validator);
assertFalse(proxyNoAuth.authRequired(), "authRequired must be false when default member is NO_AUTH");
ElastiCacheAuthProxy proxyPassword = new ElastiCacheAuthProxy("grp-pass", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorPasswordDefault, sigV4Validator);
assertTrue(proxyPassword.authRequired(), "authRequired must be true when default member is PASSWORD");
ElastiCacheAuthProxy proxyIam = new ElastiCacheAuthProxy("grp-iam", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorIamDefault, sigV4Validator);
assertTrue(proxyIam.authRequired(), "authRequired must be true when default member is IAM");
ElastiCacheAuthProxy proxyNoMembersNoAuth = new ElastiCacheAuthProxy("grp-plain-noauth", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorWithoutMembers, sigV4Validator);
assertFalse(proxyNoMembersNoAuth.authRequired(), "authRequired must be false if NO_AUTH and no members");
ElastiCacheAuthProxy proxyNoMembersPass = new ElastiCacheAuthProxy("grp-plain-pass", AuthMode.PASSWORD,
"127.0.0.1", 6379, validatorWithoutMembers, sigV4Validator);
assertTrue(proxyNoMembersPass.authRequired(), "authRequired must be true if PASSWORD and no members");
}
@Test
void explicitDefaultUserAuthenticatesWithGroupAuthTokenWhenGroupHasMembers() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator validator = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
boolean isDefault = (username == null || username.isEmpty() || "default".equals(username));
return isDefault && "group-secret-token".equals(password);
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
// Group has members (e.g. app-user), but no member is named "default"
return "app-user".equals(username) ? AuthMode.PASSWORD : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-token-members", AuthMode.PASSWORD,
"127.0.0.1", 6379, validator, sigV4Validator);
assertTrue(proxy.authenticate("default", "group-secret-token"),
"AUTH default <token> must authenticate with group auth token even when group has members");
assertTrue(proxy.authenticate("", "group-secret-token"),
"AUTH \"\" <token> must authenticate with group auth token");
assertTrue(proxy.authenticate(null, "group-secret-token"),
"AUTH <token> must authenticate with group auth token");
assertFalse(proxy.authenticate("default", "wrong-token"));
}
@Test
void authRequiredIsTrueWhenGroupHasMembersWithoutDefaultMember() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator validatorWithoutDefault = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
return "app-user".equals(username) ? AuthMode.PASSWORD : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-no-default", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorWithoutDefault, sigV4Validator);
assertTrue(proxy.authRequired(),
"authRequired must be true when group has members but no default member, even if replication group is NO_AUTH");
}
@Test
void authRequiredIsTrueWhenDefaultMemberIsDisabled() {
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
ElastiCacheAuthProxy.PasswordValidator validatorWithDisabledDefault = new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
if ("app-user".equals(username) && "secret-123".equals(password)) {
return true;
}
return false;
}
@Override
public boolean hasMembers() {
return true;
}
@Override
public AuthMode memberAuthMode(String username) {
// Disabled default user returns null mode; active password user returns PASSWORD
return "app-user".equals(username) ? AuthMode.PASSWORD : null;
}
};
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-disabled-default", AuthMode.NO_AUTH,
"127.0.0.1", 6379, validatorWithDisabledDefault, sigV4Validator);
assertTrue(proxy.authRequired(),
"authRequired must be true when default member is disabled, keeping auth required");
assertFalse(proxy.authenticate("default", "any-pass"),
"AUTH default <pass> must fail when default user is disabled");
assertFalse(proxy.authenticate(null, "any-pass"),
"AUTH <pass> must fail when default user is disabled");
assertFalse(proxy.authenticate("", "any-pass"),
"AUTH \"\" <pass> must fail when default user is disabled");
assertTrue(proxy.authenticate("app-user", "secret-123"),
"Configured password user must be able to authenticate");
}
}