feat(elasticache,memorydb): enforce user access strings on cluster-mode nodes and MemoryDB clusters (#8686)

A cluster-mode replication group with a user group refused every connection, because turning a
node's default user off would have left replication without credentials. Before the first node turns
it off, every node now gets a private replication user with masteruser and masterauth pointing at it,
once per running cluster, so each node's proxy installs the signed-in user's access string on its
own node, as a standalone group does. A cluster nobody signs in to with a user never holds that
password, which its unrestricted default sessions could read. Sessions on a cluster node also lose
the CLUSTER subcommands ElastiCache restricts, and ModifyUser reaches the open sessions of every
node.

MemoryDB relayed every connection as the backend's unrestricted default user. A cluster bound to an
ACL of its own now runs each connection under its user's access string through the same backend
ACL, with the open-access ACL relayed as before.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 23:27:43 -04:00
1 parent bb57e63b8e
commit 7466c5c063
17 files changed
+1065 -153

No files matched your search

@@ -125,6 +125,9 @@ public class ElastiCacheService implements ResourceProvider {
*/
private final Set<String> recordsHoldingTheirPort = ConcurrentHashMap.newKeySet();
/** Running cluster-mode clusters whose nodes have replication credentials: see {@link #secureClusterReplication}. */
private final Set<String> securedClusterReplication = ConcurrentHashMap.newKeySet();
/**
* A record's entry in {@link #recordsHoldingTheirPort}: its owning account, then its id. Ids
* are unique only within an account, so two accounts' records of the same name each hold
@@ -2772,6 +2775,10 @@ public class ElastiCacheService implements ResourceProvider {
for (ReplicationGroup group : groups.scan(k -> true)) {
if (effectiveUserIds(groups.accountId(), group).contains(userId)) {
proxyManager.refreshUser(group.getReplicationGroupId(), user.getUserName());
// Each node of a cluster-mode group has a proxy and a backend ACL of its own.
for (ClusterNode node : group.getClusterNodes()) {
proxyManager.refreshUser(node.getMemberClusterId(), user.getUserName());
}
}
}
for (CacheCluster cluster : cacheClusters.scan(k -> true)) {
@@ -3310,6 +3317,11 @@ public class ElastiCacheService implements ResourceProvider {
return groups.getForAccount(accountId, groupId).map(ReplicationGroup::isClusterEnabled).orElse(false);
}
@Override
public void prepareClusterReplication() {
secureClusterReplication(accountId, groupId);
}
@Override
public String ownerAccountId() {
return accountId;
@@ -3317,6 +3329,28 @@ public class ElastiCacheService implements ResourceProvider {
};
}
/**
* Gives the nodes of a cluster-mode group their replication credentials the first time one of them
* is about to turn its default user off. The nodes' container ids name the running cluster, so a
* cluster restored with new containers is secured again.
*/
private void secureClusterReplication(String accountId, String groupId) {
ReplicationGroup group = groups.getForAccount(accountId, groupId).orElse(null);
if (group == null || group.getClusterNodes().isEmpty()) {
return;
}
List<ClusterNode> nodes = group.getClusterNodes();
String running = accountId + "/" + String.join(",", nodes.stream().map(ClusterNode::getContainerId).toList());
synchronized (lockFor("rg-replication:" + accountId + "/" + groupId)) {
if (securedClusterReplication.contains(running)) {
return;
}
clusterFormation.secureReplication(groupId, nodes.stream()
.map(node -> new Endpoint(node.getContainerHost(), node.getContainerPort())).toList());
securedClusterReplication.add(running);
}
}
// AWS allows only redis and valkey.
private static String normalizeEngine(String engine) {
String normalized = engine.toLowerCase(Locale.ROOT);
@@ -1,5 +1,6 @@
package io.floci.aws.services.elasticache.container;
import io.floci.aws.services.elasticache.model.Endpoint;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
@@ -12,6 +13,7 @@ import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
/**
@@ -22,6 +24,10 @@ import java.util.function.Predicate;
* <p>Commands are issued from the JVM over each node's Floci-reachable endpoint;
* the addresses handed to MEET are the nodes' Docker-network IPs, because that is
* where the nodes reach <em>each other</em>.
*
* <p>{@link #secureReplication} later gives every node a replication user to sign in to its
* primary with, once the auth proxy is about to turn a node's {@code default} user off to
* enforce access strings.
*/
@ApplicationScoped
public class ValkeyClusterFormation {
@@ -103,6 +109,41 @@ public class ValkeyClusterFormation {
}
}
/**
* Gives every node of a formed cluster a replication user and has it sign in to its primary with
* that user, so replication keeps authenticating once a node's {@code default} user is off. Any
* node can become a primary, so every node both accepts the user and signs in with it. Run only
* when the first node is about to turn {@code default} off: until then every session is that
* unrestricted user, which could read the password back with {@code CONFIG GET masterauth}.
*
* @param nodes the endpoints Floci reaches the nodes on
*/
public void secureReplication(String groupId, List<Endpoint> nodes) {
String user = "floci-replication-" + UUID.randomUUID();
String password = UUID.randomUUID().toString();
List<RespClient> clients = new ArrayList<>(nodes.size());
try {
for (Endpoint node : nodes) {
clients.add(new RespClient(node.address(), node.port()));
}
for (RespClient client : clients) {
try {
client.callString("ACL", "SETUSER", user, "reset", "on", ">" + password,
"+ping", "+sync", "+psync", "+replconf");
client.callString("CONFIG", "SET", "masteruser", user);
client.callString("CONFIG", "SET", "masterauth", password);
} catch (RespError e) {
// Left out: the server's reply can quote the password back.
throw new IOException("a node refused the replication credentials");
}
}
} catch (IOException e) {
throw new RuntimeException("Securing replication for group " + groupId + " failed: " + e.getMessage(), e);
} finally {
clients.forEach(RespClient::closeQuietly);
}
}
/** The contiguous slot range served by the given shard, covering all 16384 slots overall. */
public static int[] slotRange(int nodeGroup, int numNodeGroups) {
int start = nodeGroup * TOTAL_SLOTS / numNodeGroups;
@@ -30,7 +30,7 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
private final PasswordValidator passwordValidator;
private final SigV4Validator sigV4Validator;
private final Supplier<SSLContext> tlsContext;
private final ElastiCacheBackendAcl backendAcl = new ElastiCacheBackendAcl();
private final ElastiCacheBackendAcl backendAcl;
public ElastiCacheAuthProxy(String groupId, AuthMode authMode,
String backendHost, int backendPort,
@@ -49,6 +49,7 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
this.passwordValidator = passwordValidator;
this.sigV4Validator = sigV4Validator;
this.tlsContext = tlsContext;
this.backendAcl = new ElastiCacheBackendAcl(passwordValidator::clusterMode);
}
@Override
@@ -90,10 +91,13 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
if (!members && !backendAcl.initialized()) {
return;
}
// Disabling default without configuring replication credentials breaks cluster nodes.
// Until that path is implemented, fail closed rather than ignore the user's ACL.
if (passwordValidator.clusterMode()) {
throw new IOException("Cluster-mode user ACL transport is not supported yet");
if (!backendAcl.initialized() && passwordValidator.clusterMode()) {
try {
passwordValidator.prepareClusterReplication();
} catch (RuntimeException e) {
LOG.warnv(e, "Could not give the nodes of {0} their replication credentials", groupId);
throw new IOException("Cluster replication is not ready for access strings", e);
}
}
String name = username == null || username.isEmpty() ? "default" : username;
backendAcl.authenticate(backend, name,
@@ -207,6 +211,14 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
return false;
}
/**
* Readies every node of a cluster-mode cache for replication without the {@code default} user,
* before a node turns it off for its first session under an access string. Called again by
* every node's first such session, so it does its work once per cluster.
*/
default void prepareClusterReplication() {
}
default boolean hasMembers() {
return false;
}
@@ -11,23 +11,48 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
/** Keeps frontend passwords and IAM tokens out of the backend's private ACL credentials. */
final class ElastiCacheBackendAcl {
/**
* Keeps frontend passwords and IAM tokens out of the backend's private ACL credentials. Each
* ElastiCache and MemoryDB proxy owns one, for the one backend server it relays to.
*/
public final class ElastiCacheBackendAcl {
private static final int CONNECT_TIMEOUT_MILLIS = 5000;
private static final int COMMAND_TIMEOUT_MILLIS = 10000;
/**
* The {@code CLUSTER} subcommands ElastiCache lists among its restricted commands: they change the
* cluster's topology, slots or failover state, which only Floci manages.
*/
private static final List<String> RESTRICTED_CLUSTER_SUBCOMMANDS = List.of("addslots", "addslotsrange",
"bumpepoch", "delslots", "delslotsrange", "failover", "flushslots", "forget", "links", "meet",
"replicate", "reset", "saveconfig", "set-config-epoch", "setslot");
private final String administrator = "floci-admin-" + UUID.randomUUID();
private final String administratorPassword = UUID.randomUUID().toString();
private final Map<String, String> passwords = new LinkedHashMap<>();
private final BooleanSupplier clusterNode;
private volatile boolean initialized;
public ElastiCacheBackendAcl() {
this(() -> false);
}
/**
* @param clusterNode whether the backend is a node of a cluster-mode cache, read when rules are
* installed: its sessions also lose the cluster-management subcommands
*/
ElastiCacheBackendAcl(BooleanSupplier clusterNode) {
this.clusterNode = clusterNode;
}
boolean initialized() {
return initialized;
}
synchronized void authenticate(Socket backend, String username, Supplier<String> accessStringSupplier)
public synchronized void authenticate(Socket backend, String username, Supplier<String> accessStringSupplier)
throws IOException {
String accessString = accessStringSupplier.get();
if (accessString == null) {
@@ -46,7 +71,7 @@ final class ElastiCacheBackendAcl {
}
String backendName = backendName(username);
String password = passwords.computeIfAbsent(backendName, ignored -> UUID.randomUUID().toString());
command(backend, userRules(backendName, accessRules, password));
command(backend, userRules(backendName, accessRules, password, clusterNode.getAsBoolean()));
command(backend, List.of("AUTH", backendName, password));
backend.setSoTimeout(0);
}
@@ -80,7 +105,7 @@ final class ElastiCacheBackendAcl {
backend.connect(new InetSocketAddress(backendHost, backendPort), CONNECT_TIMEOUT_MILLIS);
backend.setSoTimeout(COMMAND_TIMEOUT_MILLIS);
command(backend, List.of("AUTH", administrator, administratorPassword));
command(backend, userRules(backendName, accessRules, password));
command(backend, userRules(backendName, accessRules, password, clusterNode.getAsBoolean()));
}
}
@@ -101,7 +126,8 @@ final class ElastiCacheBackendAcl {
return accessRules;
}
private static List<String> userRules(String backendName, List<String> accessRules, String password) {
private static List<String> userRules(String backendName, List<String> accessRules, String password,
boolean clusterNode) {
List<String> rules = new ArrayList<>(List.of("ACL", "SETUSER", backendName, "reset"));
rules.addAll(accessRules);
// Authentication rules are owned by the proxy. A supplied nopass or password token
@@ -109,6 +135,10 @@ final class ElastiCacheBackendAcl {
rules.addAll(List.of("resetpass", ">" + password, "-acl", "-config", "-debug", "-module",
"-replicaof", "-slaveof", "-shutdown", "-monitor", "-slowlog", "-sync", "-psync",
"-save", "-bgsave", "-bgrewriteaof", "-migrate"));
if (clusterNode) {
// Subcommand rules need Valkey 7+, which cluster mode's 8.1+ requirement already implies.
RESTRICTED_CLUSTER_SUBCOMMANDS.forEach(subcommand -> rules.add("-cluster|" + subcommand));
}
return rules;
}
@@ -19,6 +19,7 @@ import io.floci.aws.services.memorydb.model.Cluster;
import io.floci.aws.services.memorydb.model.ClusterStatus;
import io.floci.aws.services.memorydb.model.Endpoint;
import io.floci.aws.services.memorydb.model.User;
import io.floci.aws.services.memorydb.proxy.MemoryDbAuthProxy;
import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -420,8 +421,7 @@ public class MemoryDbService {
cluster.setContainerPort(handle.getPort());
proxyManager.startProxy(identity, authRequired, cluster.getProxyPort(),
handle.getHost(), handle.getPort(),
(username, secret) -> authenticate(cluster.getName(), username, secret,
cluster.getRegion(), entry.accountId()));
clusterAuthenticator(cluster, entry.accountId()));
} else {
LOG.warnv("MemoryDB cluster {0} restored as metadata only: no Docker daemon is reachable",
ownerKey);
@@ -749,19 +749,10 @@ public class MemoryDbService {
if (cluster == null) {
return false;
}
String aclName = cluster.getAclName();
if (DEFAULT_ACL.equals(aclName)) {
if (DEFAULT_ACL.equals(cluster.getAclName())) {
return true;
}
Acl acl = ownedResourceGet(acls, accountId, aclName, region).orElse(null);
if (acl == null) {
return false;
}
String target = (username == null || username.isEmpty()) ? DEFAULT_USER : username;
if (!acl.getUserNames().contains(target)) {
return false;
}
User user = resolveUser(target, region, accountId);
User user = aclMember(cluster, username, region, accountId);
if (user == null) {
return false;
}
@@ -772,6 +763,51 @@ public class MemoryDbService {
};
}
/**
* The user of the cluster's ACL that {@code username} names, the {@code default} user for a blank
* name, or null when the ACL does not hold it.
*/
private User aclMember(Cluster cluster, String username, String region, String accountId) {
Acl acl = ownedResourceGet(acls, accountId, cluster.getAclName(), region).orElse(null);
if (acl == null) {
return null;
}
String target = (username == null || username.isEmpty()) ? DEFAULT_USER : username;
if (!acl.getUserNames().contains(target)) {
return null;
}
return resolveUser(target, region, accountId);
}
/**
* Bound to the account that owns the cluster, since the proxy calls back on its own thread. A
* cluster cannot change its ACL, so whether access strings apply is fixed when the proxy starts.
*/
private MemoryDbAuthProxy.AuthValidator clusterAuthenticator(Cluster cluster, String accountId) {
String name = cluster.getName();
String region = cluster.getRegion();
boolean ownAcl = !DEFAULT_ACL.equals(cluster.getAclName());
return new MemoryDbAuthProxy.AuthValidator() {
@Override
public boolean authenticate(String username, String secret) {
return MemoryDbService.this.authenticate(name, username, secret, region, accountId);
}
@Override
public boolean enforcesAccessStrings() {
return ownAcl;
}
@Override
public String accessString(String username) {
return ownedResourceGet(clusters, accountId, name, region)
.map(current -> aclMember(current, username, region, accountId))
.map(User::getAccessString)
.orElse(null);
}
};
}
/** True if the ACL has at least one user that requires a credential (password or IAM). */
private boolean isAuthRequired(String aclName, String region) {
return isAuthRequired(aclName, region, regionResolver.getAccountId());
@@ -923,8 +959,7 @@ public class MemoryDbService {
proxyManager.startProxy(identity, authRequired, proxyPort,
handle.getHost(), handle.getPort(),
(username, secret) -> authenticate(name, username, secret, cluster.getRegion(),
cluster.getAccountId()));
clusterAuthenticator(cluster, cluster.getAccountId()));
} else {
LOG.warnv("MemoryDB cluster {0} created without a backing container: no Docker "
+ "daemon is reachable. Metadata operations work; connections to the "
@@ -1,6 +1,7 @@
package io.floci.aws.services.memorydb.proxy;
import io.floci.aws.services.elasticache.proxy.AbstractRedisAuthProxy;
import io.floci.aws.services.elasticache.proxy.ElastiCacheBackendAcl;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -17,6 +18,10 @@ import java.net.Socket;
* ACL: a cluster bound to {@code open-access} (or any ACL whose users require no
* password) is created with {@code requireAuth = false}, in which case the proxy is a
* straight relay.
*
* <p>A cluster bound to an ACL of its own runs each connection as a private backend ACL user
* that carries the signed-in user's access string, as an ElastiCache cache with user groups does,
* so the backend answers a command the user may not run with {@code NOPERM}.
*/
public class MemoryDbAuthProxy extends AbstractRedisAuthProxy {
@@ -24,6 +29,7 @@ public class MemoryDbAuthProxy extends AbstractRedisAuthProxy {
private final boolean requireAuth;
private final AuthValidator authValidator;
private final ElastiCacheBackendAcl backendAcl = new ElastiCacheBackendAcl();
public MemoryDbAuthProxy(String clusterName, boolean authRequired,
String backendHost, int backendPort,
@@ -43,6 +49,15 @@ public class MemoryDbAuthProxy extends AbstractRedisAuthProxy {
return authValidator.authenticate(username, password);
}
@Override
protected void initializeBackend(Socket backend, String username) throws IOException {
if (!authValidator.enforcesAccessStrings()) {
return;
}
String name = username == null || username.isEmpty() ? "default" : username;
backendAcl.authenticate(backend, name, () -> authValidator.accessString(name));
}
@Override
protected void closeQuietly(Socket s) {
try {
@@ -61,5 +76,15 @@ public class MemoryDbAuthProxy extends AbstractRedisAuthProxy {
@FunctionalInterface
public interface AuthValidator {
boolean authenticate(String username, String secret);
/** Whether sessions run with their user's access string, false for the open-access ACL. */
default boolean enforcesAccessStrings() {
return false;
}
/** The access string of {@code username} in the cluster's ACL, or null when the ACL does not hold it. */
default String accessString(String username) {
return null;
}
}
}