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;
}
}
}