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

+16 -9
View File
@@ -36,7 +36,7 @@ transport. This does not add Memcached transit encryption.
## User access strings
For non-cluster-mode Redis/Valkey replication groups and serverless caches, the auth
For Redis/Valkey replication groups, cluster-mode groups included, and serverless caches, the auth
proxy applies each associated user's `AccessString` to a private backend ACL identity.
Valkey enforces command, key and Pub/Sub channel permissions. Authenticating a
subscribe-only user does not grant `SET` or `FLUSHALL`. The backend default account
@@ -52,10 +52,22 @@ are denied as well, preventing backend persistence operations and outbound key m
These restrictions protect private backend credentials and key boundaries. AWS lists these among its
[restricted cache commands](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/SupportedCommands.html).
In a cluster-mode group, each node has a proxy of its own, which applies the access string on that
node when the user signs in there. A client that follows a `MOVED` redirect signs in to the other
node's proxy, as it does on AWS. Sessions on a cluster node also cannot run the `CLUSTER`
subcommands ElastiCache restricts, which change the cluster's topology, slots or failover state:
`ADDSLOTS`, `ADDSLOTSRANGE`, `BUMPEPOCH`, `DELSLOTS`, `DELSLOTSRANGE`, `FAILOVER`, `FLUSHSLOTS`,
`FORGET`, `LINKS`, `MEET`, `REPLICATE`, `RESET`, `SAVECONFIG`, `SET-CONFIG-EPOCH` and `SETSLOT`.
Before the first node disables its `default` account, Floci gives every node a private replication
user and sets `masteruser` and `masterauth` to it, so replication keeps authenticating. A
cluster-mode group nobody signs in to with a user never gets that password, which its unrestricted
sessions could otherwise read with `CONFIG GET masterauth`.
`ModifyUser` with `AccessString` or `AppendAccessString` is installed on the backend at once
for every replication group and serverless cache that holds the user, so it applies to connections
that are already open. A change that cannot be installed, such as one with a selector, is logged and
the open sessions keep their old permissions until the user authenticates again. Other
for every replication group, every node of a cluster-mode group and every serverless cache that
holds the user, so it applies to connections that are already open. A change that cannot be
installed, such as one with a selector, is logged and the open sessions keep their old permissions
until the user authenticates again. Other
changes, such as adding a user to a group or associating a user group with a cache, are
installed on the next successful authentication; reconnect to apply them promptly.
Re-authentication on an already relayed connection uses the backend protocol directly, so
@@ -65,11 +77,6 @@ ACL selectors are rejected before backend changes: a selector can grant permissi
independently of the root rules used to protect private backend credentials. Read-only
`ACL` commands are also unavailable through these sessions.
**Known limitation:** cluster-mode RBAC fails closed. Configuring replication credentials
across all nodes is still required before disabling their default accounts. Such connections
are rejected rather than being relayed with unrestricted permissions. Cluster-mode caches
without user associations retain their existing behavior.
## Supported Management Actions
<!-- floci:actions:start -->
+14
View File
@@ -10,6 +10,20 @@ Floci manages real Valkey/Redis Docker containers and proxies TCP connections to
Set `FLOCI_SERVICES_MEMORYDB_MOCK=true` to manage clusters as control-plane-only resources — no Redis container is started. The management API (`CreateCluster`, `DescribeClusters`, tagging, etc.) behaves normally and returns a `ClusterEndpoint` of `<hostname>:6379` (defaults to `localhost:6379`, controlled by `FLOCI_HOSTNAME`), but there is no live data plane to connect to. This is intended for Infrastructure-as-Code tools like Terraform and OpenTofu running in environments without a Docker socket, where you only need the AWS resources to exist and return consistent attributes.
## User access strings
A cluster bound to an ACL of its own runs each connection under the `AccessString` of the user it
signs in as. The proxy installs that access string on a private backend ACL user, and the backend
answers a command, key or channel outside it with `NOPERM`, as on AWS. A connection that does not
authenticate runs as the ACL's `default` user. Once the first connection is set up, the backend's
own `default` account is disabled, so an `AUTH` sent after the proxy has bridged the connection
cannot reach unrestricted permissions.
The backend user is the same kind ElastiCache uses, so the same commands are denied to every
session, and an access string with an ACL selector is refused. See
[User access strings](elasticache.md#user-access-strings) on the ElastiCache page.
Clusters on the `open-access` ACL are relayed without a backend ACL user, as before.
## Supported Management Actions
<!-- floci:actions:start -->
@@ -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;
}
}
}
@@ -0,0 +1,232 @@
package io.floci.aws.services.elasticache;
import io.floci.aws.services.elasticache.model.ClusterNode;
import io.floci.aws.services.elasticache.model.ReplicationGroup;
import io.floci.aws.testing.DockerAvailability;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.net.Socket;
import java.net.URI;
import java.util.List;
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.bulk;
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.command;
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.containerOf;
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.docker;
import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.openSocket;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A cluster-mode replication group with a user group: each node's proxy runs a session under the
* signed-in user's access string on that node, across MOVED redirects, ModifyUser reaches the open
* sessions of every node, and no session can change the cluster's topology.
*
* <p>Hash tags pin keys to a shard: {@code {bar}} hashes to slot 5061 (first shard of two) and
* {@code {foo}} to slot 12182 (second shard).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElastiCacheClusterAccessStringIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request";
private static final String GROUP_ID = "it-ecc-acl";
private static final String USER_GROUP = "it-ecc-acl-users";
private static final String DEFAULT_USER = "it-ecc-acl-default";
private static final String APP_USER = "it-ecc-acl-app";
private static final String OPS_USER = "it-ecc-acl-ops";
private static final String PASSWORD = "it-ecc-acl-password-0123";
private static int firstShardPort;
/** RestAssured's port is reset once the tests are done, so the cleanup names the server's own. */
@TestHTTPResource("/")
static URI baseUri;
@Inject
ElastiCacheService service;
@BeforeAll
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker must be available for cluster-mode access strings");
}
@AfterAll
static void cleanup() {
request("DeleteReplicationGroup").formParam("ReplicationGroupId", GROUP_ID).post("/");
request("DeleteUserGroup").formParam("UserGroupId", USER_GROUP).post("/");
for (String user : List.of(APP_USER, OPS_USER, DEFAULT_USER)) {
request("DeleteUser").formParam("UserId", user).post("/");
}
}
@Test
@Order(1)
void createAClusterModeGroupWithAUserGroup() {
createUser(DEFAULT_USER, "default", "on ~* &* +@all");
createUser(APP_USER, APP_USER, "on ~app:* -@all +get +set +ping");
createUser(OPS_USER, OPS_USER, "on ~* &* +@all");
request("CreateUserGroup")
.formParam("UserGroupId", USER_GROUP)
.formParam("Engine", "valkey")
.formParam("UserIds.member.1", DEFAULT_USER)
.formParam("UserIds.member.2", APP_USER)
.formParam("UserIds.member.3", OPS_USER)
.post("/").then().statusCode(200);
request("CreateReplicationGroup")
.formParam("ReplicationGroupId", GROUP_ID)
.formParam("ReplicationGroupDescription", "Cluster mode access strings")
.formParam("Engine", "valkey")
.formParam("EngineVersion", "8.2")
.formParam("CacheParameterGroupName", "default.valkey8.cluster.on")
.formParam("NumNodeGroups", "2")
.formParam("ReplicasPerNodeGroup", "1")
.formParam("AutomaticFailoverEnabled", "true")
.formParam("TransitEncryptionEnabled", "true")
.formParam("UserGroupIds.member.1", USER_GROUP)
.post("/").then().statusCode(200);
firstShardPort = group().getClusterNodes().stream()
.filter(node -> node.isPrimary() && "0001".equals(node.getNodeGroupId()))
.findFirst().orElseThrow().getProxyPort();
}
@Test
@Order(2)
void noNodeHoldsAReplicationPasswordBeforeAUserSignsIn() throws Exception {
for (ClusterNode node : group().getClusterNodes()) {
assertEquals("masterauth", nodeConfig(node, "masterauth"),
node.getMemberClusterId() + " must not hold a password its default sessions could read");
}
}
@Test
@Order(3)
void theFirstSignInGivesEveryNodeItsReplicationUser() throws Exception {
signIn(firstShardPort, APP_USER).close();
// The node signed in to has turned its default user off, so the CLI reads the others.
for (ClusterNode node : group().getClusterNodes()) {
if (node.getProxyPort() != firstShardPort) {
String reply = nodeConfig(node, "masteruser");
assertTrue(reply.lines().toList().getLast().startsWith("floci-replication-"),
node.getMemberClusterId() + " must sign in to its primary as the replication user: " + reply);
}
}
}
@Test
@Order(4)
void aSessionRunsUnderItsUsersAccessString() throws Exception {
try (Socket app = signIn(firstShardPort, APP_USER)) {
assertEquals("+OK", command(app, "SET", "app:{bar}", "first"));
assertEquals("first", bulk(app, "GET", "app:{bar}"));
assertTrue(command(app, "SET", "other:{bar}", "value").startsWith("-NOPERM"));
assertTrue(command(app, "FLUSHALL").startsWith("-NOPERM"));
assertTrue(command(app, "AUTH", "default", "anything").startsWith("-WRONGPASS"),
"AUTH sent past the proxy must not reach the node's unrestricted default user");
assertTrue(command(app, "SET", "other:{bar}", "value").startsWith("-NOPERM"));
}
}
@Test
@Order(5)
void aRedirectedSessionRunsUnderItsUsersAccessStringOnTheOtherShard() throws Exception {
int secondShardPort;
try (Socket app = signIn(firstShardPort, APP_USER)) {
String moved = command(app, "SET", "app:{foo}", "second");
assertTrue(moved.startsWith("-MOVED 12182 "), "the key lives on the second shard: " + moved);
secondShardPort = Integer.parseInt(moved.substring(moved.lastIndexOf(':') + 1));
}
try (Socket app = signIn(secondShardPort, APP_USER)) {
assertEquals("+OK", command(app, "SET", "app:{foo}", "second"));
assertTrue(command(app, "SET", "other:{foo}", "value").startsWith("-NOPERM"));
}
}
@Test
@Order(6)
void noSessionCanChangeTheClusterTopology() throws Exception {
try (Socket ops = signIn(firstShardPort, OPS_USER)) {
assertTrue(bulk(ops, "CLUSTER", "INFO").contains("cluster_state:ok"));
assertEquals("+OK", command(ops, "SET", "ops:{bar}", "value"));
assertTrue(command(ops, "CLUSTER", "MEET", "127.0.0.1", "7000").startsWith("-NOPERM"));
assertTrue(command(ops, "CLUSTER", "FAILOVER").startsWith("-NOPERM"));
assertTrue(command(ops, "CLUSTER", "FORGET", "0123456789abcdef").startsWith("-NOPERM"));
assertTrue(command(ops, "CLUSTER", "RESET").startsWith("-NOPERM"));
assertTrue(command(ops, "CONFIG", "GET", "masterauth").startsWith("-NOPERM"),
"the replication password must stay out of reach");
}
}
@Test
@Order(7)
void aChangedAccessStringReachesTheOpenSessionsOfEveryNode() throws Exception {
int secondShardPort = group().getClusterNodes().stream()
.filter(node -> node.isPrimary() && "0002".equals(node.getNodeGroupId()))
.findFirst().orElseThrow().getProxyPort();
try (Socket first = signIn(firstShardPort, APP_USER); Socket second = signIn(secondShardPort, APP_USER)) {
assertEquals("+OK", command(first, "SET", "app:{bar}", "writable"));
assertEquals("+OK", command(second, "SET", "app:{foo}", "writable"));
request("ModifyUser")
.formParam("UserId", APP_USER)
.formParam("AccessString", "on ~app:* -@all +get +ping")
.post("/").then().statusCode(200);
assertTrue(command(first, "SET", "app:{bar}", "read-only").startsWith("-NOPERM"));
assertTrue(command(second, "SET", "app:{foo}", "read-only").startsWith("-NOPERM"));
assertEquals("writable", bulk(second, "GET", "app:{foo}"));
}
}
private ReplicationGroup group() {
return service.listReplicationGroups(GROUP_ID).iterator().next();
}
/** The node's own value of a parameter, read with its CLI past the proxy: the parameter name, then the value. */
private static String nodeConfig(ClusterNode node, String parameter) throws Exception {
return docker("exec", containerOf(node.getMemberClusterId()), "valkey-cli", "CONFIG", "GET", parameter);
}
private static Socket signIn(int port, String user) throws Exception {
Socket socket = openSocket("localhost", port);
try {
assertEquals("+OK", command(socket, "AUTH", user, PASSWORD));
return socket;
} catch (Throwable failure) {
socket.close();
throw failure;
}
}
private static void createUser(String userId, String userName, String accessString) {
request("CreateUser")
.formParam("UserId", userId)
.formParam("UserName", userName)
.formParam("Engine", "valkey")
.formParam("AccessString", accessString)
.formParam("AuthenticationMode.Type", "password")
.formParam("AuthenticationMode.Passwords.member.1", PASSWORD)
.post("/").then().statusCode(200);
}
private static RequestSpecification request(String action) {
return given().port(baseUri.getPort()).formParam("Action", action).header("Authorization", AUTH_HEADER);
}
}
@@ -1062,6 +1062,25 @@ class ElastiCacheServiceTest {
verify(proxyManager, times(4)).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
}
@Test
void aClusterModeGroupGetsItsReplicationPasswordOnlyWhenAUserFirstSignsInToANode() {
stubPerNodeContainers();
service.createReplicationGroup(clusterRequest("grp", 2, 1));
// Until then every session is the node's unrestricted default user, which could read the password.
verify(clusterFormation, never()).secureReplication(anyString(), any());
ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validators =
ArgumentCaptor.forClass(ElastiCacheAuthProxy.PasswordValidator.class);
verify(proxyManager, times(4)).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(),
validators.capture());
validators.getAllValues().get(0).prepareClusterReplication();
validators.getAllValues().get(2).prepareClusterReplication();
Endpoint node = new Endpoint("localhost", 6379);
verify(clusterFormation, times(1)).secureReplication("grp", List.of(node, node, node, node));
}
@Test
void clusterOnParameterGroupEnablesClusterModeForSingleShard() {
stubPerNodeContainers();
@@ -1538,6 +1557,26 @@ class ElastiCacheServiceTest {
verify(proxyManager).refreshUser("serverless-backing", "app");
}
@Test
void modifyUserAccessStringIsAppliedOnEveryNodeOfAClusterModeGroup() {
stubPerNodeContainers();
service.createUser("default-user-id", "default", AuthMode.PASSWORD, List.of("default-pass"),
"on ~* +@all", null);
service.createUser("app-user-id", "app", AuthMode.PASSWORD, List.of("app-pass"), "on ~* +@all", null);
service.createUserGroup("app-group", "valkey", List.of("default-user-id", "app-user-id"), "us-east-1");
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest("grp", "test",
AuthMode.PASSWORD, null, "us-east-1", "valkey", "8.2", "cache.t4g.micro",
"default.valkey8.cluster.on", null, null, 2, 1,
null, true, null, null, ReplicationGroupSettings.defaults(), Map.of(), List.of("app-group"), null));
service.modifyUser("app-user-id", null, null, "on ~allowed:* -@all +get", null, null);
// Each node has a proxy and a backend ACL of its own, so each one installs the new rules.
for (String node : List.of("grp-0001-001", "grp-0001-002", "grp-0002-001", "grp-0002-002")) {
verify(proxyManager).refreshUser(node, "app");
}
}
@Test
void groupOfAnotherAccountDroppingItsLastUserGroupChangesTheProxyAuthModeOutsideTheRequest() {
AtomicReference<String> account = new AtomicReference<>("111111111111");
@@ -0,0 +1,116 @@
package io.floci.aws.services.elasticache.container;
import io.floci.aws.services.elasticache.model.Endpoint;
import io.floci.aws.testing.FakeRespServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ValkeyClusterFormationTest {
private final List<FakeRespServer> nodes = new ArrayList<>();
@AfterEach
void stopNodes() throws IOException {
for (FakeRespServer node : nodes) {
node.close();
}
}
@Test
void formingAClusterCreatesNoReplicationPasswordItsUnrestrictedSessionsCouldRead() {
FakeRespServer primary = node("primary-id", false);
FakeRespServer replica = node("replica-id", false);
new ValkeyClusterFormation().form("grp", List.of(member(primary, true), member(replica, false)), 1);
for (FakeRespServer node : List.of(primary, replica)) {
assertTrue(node.commands().stream().noneMatch(command -> "ACL".equals(command.getFirst())
|| "CONFIG".equals(command.getFirst())), "formation sent " + node.commands());
}
}
@Test
void everyNodeAcceptsTheReplicationUserAndSignsInWithIt() {
FakeRespServer primary = node("primary-id", false);
FakeRespServer replica = node("replica-id", false);
new ValkeyClusterFormation().secureReplication("grp", List.of(endpoint(primary), endpoint(replica)));
List<String> user = command(primary, "ACL", "SETUSER");
assertTrue(user.get(2).startsWith("floci-replication-"));
assertEquals(List.of("reset", "on"), user.subList(3, 5));
assertTrue(user.get(5).startsWith(">"));
assertEquals(List.of("+ping", "+sync", "+psync", "+replconf"), user.subList(6, 10));
String password = user.get(5).substring(1);
for (FakeRespServer node : List.of(primary, replica)) {
assertEquals(user, command(node, "ACL", "SETUSER"), "every node must accept the same user");
assertEquals(List.of("CONFIG", "SET", "masteruser", user.get(2)),
command(node, "CONFIG", "SET", "masteruser"));
assertEquals(List.of("CONFIG", "SET", "masterauth", password),
command(node, "CONFIG", "SET", "masterauth"));
}
}
@Test
void aRefusedReplicationUserFailsWithoutTheServersReply() {
FakeRespServer primary = node("primary-id", true);
RuntimeException failure = assertThrows(RuntimeException.class,
() -> new ValkeyClusterFormation().secureReplication("grp", List.of(endpoint(primary))));
String password = command(primary, "ACL", "SETUSER").get(5).substring(1);
for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
assertFalse(String.valueOf(cause.getMessage()).contains(password),
"the reply quotes the password and must stay out of the error: " + cause.getMessage());
}
}
/** A node that has met every other node and serves its slots, refusing ACL changes when told to. */
private FakeRespServer node(String id, boolean refuseAcl) {
try {
FakeRespServer node = new FakeRespServer(command -> switch (String.join(" ", command.subList(0, 2))) {
case "CLUSTER MYID" -> FakeRespServer.bulk(id);
case "CLUSTER INFO" -> FakeRespServer.bulk("cluster_state:ok\r\ncluster_known_nodes:" + nodes.size());
case "ACL SETUSER" -> refuseAcl
? "-ERR Error in ACL SETUSER: " + String.join(" ", command) + "\r\n" : "+OK\r\n";
default -> "+OK\r\n";
});
nodes.add(node);
return node;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static ValkeyClusterFormation.Node member(FakeRespServer node, boolean primary) {
return new ValkeyClusterFormation.Node("localhost", node.port(), "127.0.0.1", 0, primary);
}
private static Endpoint endpoint(FakeRespServer node) {
return new Endpoint("localhost", node.port());
}
private static List<String> command(FakeRespServer node, String... prefix) {
return node.commands().get(indexOf(node, prefix));
}
private static int indexOf(FakeRespServer node, String... prefix) {
List<List<String>> commands = node.commands();
for (int i = 0; i < commands.size(); i++) {
List<String> command = commands.get(i);
if (command.size() >= prefix.length && command.subList(0, prefix.length).equals(List.of(prefix))) {
return i;
}
}
throw new AssertionError("no " + String.join(" ", prefix) + " in " + commands);
}
}
@@ -26,19 +26,6 @@ class ElastiCacheAuthProxyTest {
verifyNoInteractions(backend);
}
@Test
void clusterModeFailsClosedBeforeChangingBackendReplicationCredentials() {
ElastiCacheAuthProxy.PasswordValidator validator = mock(ElastiCacheAuthProxy.PasswordValidator.class);
when(validator.hasMembers()).thenReturn(true);
when(validator.clusterMode()).thenReturn(true);
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("cluster", AuthMode.IAM, "127.0.0.1", 6379,
validator, mock(SigV4Validator.class));
Socket backend = mock(Socket.class);
assertThrows(IOException.class, () -> proxy.initializeBackend(backend, "subscriber"));
verifyNoInteractions(backend);
}
@Test
void authModeIsReadFromTheCacheOnEachConnection() {
AtomicReference<AuthMode> cacheAuthMode = new AtomicReference<>();
@@ -1,50 +1,47 @@
package io.floci.aws.services.elasticache.proxy;
import io.floci.aws.services.elasticache.model.AuthMode;
import io.floci.aws.testing.FakeRespServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheBackendAclTest {
private static final int WAIT_MILLIS = 5000;
private ServerSocket server;
private final List<List<String>> commands = new CopyOnWriteArrayList<>();
private final List<Socket> accepted = new CopyOnWriteArrayList<>();
private FakeRespServer server;
private List<List<String>> commands;
private volatile boolean refuseNextCommands;
private ElastiCacheBackendAcl acl;
@BeforeEach
void startBackend() throws IOException {
server = new ServerSocket(0);
server = new FakeRespServer(command -> refuseNextCommands ? "-ERR refused\r\n" : "+OK\r\n");
commands = server.commands();
acl = new ElastiCacheBackendAcl();
Thread acceptor = new Thread(this::acceptConnections, "fake-backend");
acceptor.setDaemon(true);
acceptor.start();
}
@AfterEach
void stopBackend() throws IOException {
server.close();
for (Socket socket : accepted) {
socket.close();
}
}
@Test
@@ -53,7 +50,7 @@ class ElastiCacheBackendAclTest {
int afterLogin = commands.size();
String sessionPassword = passwordOf("app");
acl.reapply("localhost", server.getLocalPort(), "app", "on ~app:* -@all +get +set");
acl.reapply("localhost", server.port(), "app", "on ~app:* -@all +get +set");
List<List<String>> sent = commands.subList(afterLogin, commands.size());
assertEquals(2, sent.size());
@@ -73,37 +70,37 @@ class ElastiCacheBackendAclTest {
.findFirst().orElseThrow().get(2);
int afterLogin = commands.size();
acl.reapply("localhost", server.getLocalPort(), "default", "on ~allowed:* +get");
acl.reapply("localhost", server.port(), "default", "on ~allowed:* +get");
assertEquals(backendUser, commands.get(afterLogin + 1).get(2));
}
@Test
void nothingIsSentBeforeTheBackendIsSetUp() throws Exception {
acl.reapply("localhost", server.getLocalPort(), "app", "on ~* +@all");
acl.reapply("localhost", server.port(), "app", "on ~* +@all");
assertEquals(0, accepted.size());
assertEquals(0, server.connections());
}
@Test
void nothingIsSentForAUserNobodyHasAuthenticatedAs() throws Exception {
login("app", "on ~* +@all");
int connections = accepted.size();
int connections = server.connections();
acl.reapply("localhost", server.getLocalPort(), "other", "on ~* +@all");
acl.reapply("localhost", server.port(), "other", "on ~* +@all");
assertEquals(connections, accepted.size());
assertEquals(connections, server.connections());
}
@Test
void selectorsAreRefusedWithoutTouchingTheBackend() throws Exception {
login("app", "on ~* +@all");
int connections = accepted.size();
int connections = server.connections();
assertThrows(IOException.class,
() -> acl.reapply("localhost", server.getLocalPort(), "app", "on ~* -@all (+get ~*)"));
() -> acl.reapply("localhost", server.port(), "app", "on ~* -@all (+get ~*)"));
assertEquals(connections, accepted.size());
assertEquals(connections, server.connections());
}
@Test
@@ -112,7 +109,7 @@ class ElastiCacheBackendAclTest {
refuseNextCommands = true;
IOException failure = assertThrows(IOException.class,
() -> acl.reapply("localhost", server.getLocalPort(), "app", "on ~* +@all"));
() -> acl.reapply("localhost", server.port(), "app", "on ~* +@all"));
assertEquals("Could not establish the backend cache user's permissions", failure.getMessage());
}
@@ -123,10 +120,10 @@ class ElastiCacheBackendAclTest {
int afterLogin = commands.size();
AtomicReference<String> currentRules = new AtomicReference<>("on ~app:* -@all +get +set");
acl.reapply("localhost", server.getLocalPort(), "app", currentRules::get);
acl.reapply("localhost", server.port(), "app", currentRules::get);
currentRules.set("on ~app:* -@all +get");
acl.reapply("localhost", server.getLocalPort(), "app", currentRules::get);
acl.reapply("localhost", server.port(), "app", currentRules::get);
List<List<String>> sent = commands.subList(afterLogin, commands.size());
assertEquals(4, sent.size());
@@ -139,7 +136,7 @@ class ElastiCacheBackendAclTest {
login("app", "on ~app:* -@all +get");
int afterLogin = commands.size();
acl.reapply("localhost", server.getLocalPort(), "app", "off -@all");
acl.reapply("localhost", server.port(), "app", "off -@all");
List<List<String>> sent = commands.subList(afterLogin, commands.size());
assertEquals(2, sent.size());
@@ -151,78 +148,116 @@ class ElastiCacheBackendAclTest {
assertEquals("-@all", sent.get(1).get(5));
}
@Test
void sessionsOnAClusterNodeCannotChangeTheClusterTopology() throws Exception {
acl = new ElastiCacheBackendAcl(() -> true);
login("ops", "on ~* &* +@all");
// The CLUSTER subcommands ElastiCache lists among its restricted commands.
List<String> rules = setUserOf("ops");
for (String subcommand : List.of("addslots", "addslotsrange", "bumpepoch", "delslots", "delslotsrange",
"failover", "flushslots", "forget", "links", "meet", "replicate", "reset", "saveconfig",
"set-config-epoch", "setslot")) {
assertTrue(rules.contains("-cluster|" + subcommand), "cluster " + subcommand + " must be denied");
}
assertTrue(rules.indexOf("-cluster|meet") > rules.indexOf("+@all"),
"the restrictions must follow the user's own rules so +@all cannot grant them back");
}
@Test
void aChangedAccessStringOnAClusterNodeKeepsTheClusterRestrictions() throws Exception {
acl = new ElastiCacheBackendAcl(() -> true);
login("ops", "on ~* &* +@all");
int afterLogin = commands.size();
acl.reapply("localhost", server.port(), "ops", "on ~* &* +@all -flushall");
assertTrue(commands.get(afterLogin + 1).contains("-cluster|failover"));
}
@Test
void sessionsOnAStandaloneBackendGetNoSubcommandRulesAnOlderEngineWouldRefuse() throws Exception {
login("ops", "on ~* &* +@all");
assertTrue(setUserOf("ops").stream().noneMatch(rule -> rule.startsWith("-cluster|")));
}
@Test
void aClusterModeCacheInstallsItsUserOnTheNodeItsProxyServes() throws Exception {
ElastiCacheAuthProxy.PasswordValidator validator = clusterValidator(true);
ElastiCacheAuthProxy proxy = clusterNodeProxy(validator);
initialize(proxy, "app");
initialize(proxy, "app");
List<String> rules = setUserOf("app");
assertEquals(List.of("ACL", "SETUSER", "app", "reset", "on", "~app:*", "-@all", "+get"), rules.subList(0, 8));
assertTrue(rules.contains("-cluster|failover"));
assertEquals(List.of("ACL", "SETUSER", "default", "reset", "off"), commands.get(2));
assertEquals(List.of("AUTH", "app", passwordOf("app")), commands.getLast());
InOrder order = inOrder(validator);
order.verify(validator).prepareClusterReplication();
order.verify(validator, atLeastOnce()).accessString("app");
verify(validator, times(1)).prepareClusterReplication();
}
@Test
void aClusterWhoseReplicationIsNotReadyRefusesTheSessionBeforeTurningDefaultOff() {
ElastiCacheAuthProxy.PasswordValidator validator = clusterValidator(true);
doThrow(new IllegalStateException("a node refused the replication credentials"))
.when(validator).prepareClusterReplication();
ElastiCacheAuthProxy proxy = clusterNodeProxy(validator);
assertThrows(IOException.class, () -> initialize(proxy, "app"));
assertEquals(List.of(), commands, "the node's default user must stay on for its replication");
}
@Test
void aClusterModeCacheWithoutUsersNeverGetsAReplicationPassword() throws Exception {
ElastiCacheAuthProxy.PasswordValidator validator = clusterValidator(false);
ElastiCacheAuthProxy proxy = clusterNodeProxy(validator);
initialize(proxy, null);
verify(validator, never()).prepareClusterReplication();
assertEquals(List.of(), commands);
}
private static ElastiCacheAuthProxy.PasswordValidator clusterValidator(boolean members) {
ElastiCacheAuthProxy.PasswordValidator validator = mock(ElastiCacheAuthProxy.PasswordValidator.class);
when(validator.hasMembers()).thenReturn(members);
when(validator.clusterMode()).thenReturn(true);
when(validator.accessString("app")).thenReturn("on ~app:* -@all +get");
return validator;
}
private ElastiCacheAuthProxy clusterNodeProxy(ElastiCacheAuthProxy.PasswordValidator validator) {
return new ElastiCacheAuthProxy("grp-0001-001", AuthMode.PASSWORD, "localhost", server.port(), validator,
mock(SigV4Validator.class));
}
private void initialize(ElastiCacheAuthProxy proxy, String username) throws IOException {
try (Socket backend = new Socket("localhost", server.port())) {
proxy.initializeBackend(backend, username);
}
}
private List<String> setUserOf(String backendUser) {
return commands.stream()
.filter(c -> c.size() > 2 && "SETUSER".equals(c.get(1)) && backendUser.equals(c.get(2)))
.reduce((first, second) -> second).orElseThrow();
}
private void login(String username, String accessString) throws IOException {
try (Socket backend = new Socket("localhost", server.getLocalPort())) {
try (Socket backend = new Socket("localhost", server.port())) {
acl.authenticate(backend, username, accessString);
}
}
private String passwordOf(String backendUser) {
return commands.stream()
.filter(c -> c.size() > 2 && "SETUSER".equals(c.get(1)) && backendUser.equals(c.get(2)))
.map(c -> c.get(c.indexOf("resetpass") + 1).substring(1))
.reduce((first, second) -> second).orElseThrow();
}
private void acceptConnections() {
while (!server.isClosed()) {
try {
Socket socket = server.accept();
accepted.add(socket);
Thread handler = new Thread(() -> serve(socket), "fake-backend-connection");
handler.setDaemon(true);
handler.start();
} catch (IOException e) {
return;
}
}
}
private void serve(Socket socket) {
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
while (true) {
List<String> command = readCommand(in);
if (command == null) {
return;
}
commands.add(command);
out.write((refuseNextCommands ? "-ERR refused\r\n" : "+OK\r\n").getBytes(StandardCharsets.US_ASCII));
out.flush();
}
} catch (IOException expected) {
// The test closed the connection, which is how every fake connection ends.
}
}
private static List<String> readCommand(InputStream in) throws IOException {
String header = readLine(in);
if (header == null) {
return null;
}
int count = Integer.parseInt(header.substring(1));
List<String> arguments = new ArrayList<>();
for (int i = 0; i < count; i++) {
int length = Integer.parseInt(readLine(in).substring(1));
byte[] bytes = in.readNBytes(length);
readLine(in);
arguments.add(new String(bytes, StandardCharsets.UTF_8));
}
return arguments;
}
private static String readLine(InputStream in) throws IOException {
StringBuilder line = new StringBuilder();
int value;
while ((value = in.read()) != -1) {
if (value == '\n') {
return line.toString();
}
if (value != '\r') {
line.append((char) value);
}
}
return null;
List<String> rules = setUserOf(backendUser);
return rules.get(rules.indexOf("resetpass") + 1).substring(1);
}
}
@@ -43,6 +43,8 @@ class MemoryDbIntegrationTest {
private static final String AUTH_USER = "it-mdb-user";
private static final String AUTH_ACL = "it-mdb-acl";
private static final String AUTH_PASSWORD = "it-mdb-password";
private static final String READER_USER = "it-mdb-reader";
private static final String READER_PASSWORD = "it-mdb-reader-password";
private static final int SOCKET_TIMEOUT_MS = 10_000;
private static final int READ_LINE_MAX_ATTEMPTS = 3;
@@ -71,10 +73,12 @@ class MemoryDbIntegrationTest {
} catch (Exception ignored) {
// best-effort
}
try {
memorydb("DeleteUser", "{\"UserName\":\"" + AUTH_USER + "\"}");
} catch (Exception ignored) {
// best-effort
for (String user : List.of(AUTH_USER, READER_USER)) {
try {
memorydb("DeleteUser", "{\"UserName\":\"" + user + "\"}");
} catch (Exception ignored) {
// best-effort
}
}
}
@@ -148,15 +152,21 @@ class MemoryDbIntegrationTest {
.statusCode(200)
.body("User.Name", equalTo(AUTH_USER))
.body("User.Authentication.Type", equalTo("password"));
memorydb("CreateUser", "{"
+ "\"UserName\":\"" + READER_USER + "\","
+ "\"AccessString\":\"on ~app:* -@all +get\","
+ "\"AuthenticationMode\":{\"Type\":\"password\",\"Passwords\":[\"" + READER_PASSWORD + "\"]}}")
.then()
.statusCode(200);
// An ACL must include the built-in "default" user (DefaultUserRequired otherwise).
memorydb("CreateACL", "{"
+ "\"ACLName\":\"" + AUTH_ACL + "\","
+ "\"UserNames\":[\"default\",\"" + AUTH_USER + "\"]}")
+ "\"UserNames\":[\"default\",\"" + AUTH_USER + "\",\"" + READER_USER + "\"]}")
.then()
.statusCode(200)
.body("ACL.Name", equalTo(AUTH_ACL))
.body("ACL.UserNames", hasItems("default", AUTH_USER));
.body("ACL.UserNames", hasItems("default", AUTH_USER, READER_USER));
}
@Test
@@ -206,6 +216,28 @@ class MemoryDbIntegrationTest {
}
}
@Test
@Order(12)
void aclUserRunsUnderItsAccessString() throws Exception {
try (Socket socket = openSocket(authPort)) {
write(socket, respArray("AUTH", READER_USER, READER_PASSWORD));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("GET", "app:key"));
assertEquals("$-1\r\n", readLine(socket));
write(socket, respArray("SET", "app:key", "value"));
assertTrue(readLine(socket).startsWith("-NOPERM"), "the reader may not write");
write(socket, respArray("GET", "other:key"));
assertTrue(readLine(socket).startsWith("-NOPERM"), "the reader may not read outside app:*");
write(socket, respArray("AUTH", "default", "anything"));
assertTrue(readLine(socket).startsWith("-WRONGPASS"),
"AUTH sent past the proxy must not reach an unrestricted backend user");
write(socket, respArray("SET", "app:key", "value"));
assertTrue(readLine(socket).startsWith("-NOPERM"));
}
}
@Test
@Order(10)
void wrongPasswordRejected() throws Exception {
@@ -14,10 +14,12 @@ import io.floci.aws.services.memorydb.model.AuthMode;
import io.floci.aws.services.memorydb.model.Cluster;
import io.floci.aws.services.memorydb.model.ClusterStatus;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.ArgumentCaptor;
import java.util.LinkedHashMap;
import java.util.List;
@@ -33,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -276,6 +279,50 @@ class MemoryDbServiceTest {
assertFalse(service.authenticate("secure", "unknown-user", "s3cret"));
}
@Test
void theProxyOfAClusterWithAnAclOfItsOwnGetsItsMembersAccessStrings() {
User userSpec = new User();
userSpec.setName("reader");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("s3cret"));
userSpec.setAccessString("on ~app:* -@all +get");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("reader-acl");
aclSpec.setUserNames(List.of("default", "reader"));
service.createAcl(aclSpec, "us-east-1");
Cluster spec = new Cluster();
spec.setName("reads");
spec.setAclName("reader-acl");
service.createCluster(spec, "us-east-1");
MemoryDbAuthProxy.AuthValidator validator = startedProxyValidator();
assertTrue(validator.enforcesAccessStrings());
assertEquals("on ~app:* -@all +get", validator.accessString("reader"));
assertEquals("on ~* &* +@all", validator.accessString("default"));
assertNull(validator.accessString("stranger"), "a user the ACL does not hold has no access string");
assertTrue(validator.authenticate("reader", "s3cret"));
}
@Test
void theProxyOfAnOpenAccessClusterLeavesItsSessionsUnrestricted() {
Cluster spec = new Cluster();
spec.setName("open");
spec.setAclName("open-access");
service.createCluster(spec, "us-east-1");
assertFalse(startedProxyValidator().enforcesAccessStrings());
}
private MemoryDbAuthProxy.AuthValidator startedProxyValidator() {
ArgumentCaptor<MemoryDbAuthProxy.AuthValidator> validator =
ArgumentCaptor.forClass(MemoryDbAuthProxy.AuthValidator.class);
verify(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), validator.capture());
return validator.getValue();
}
@Test
void iamAuthDelegatesToSigV4Validator() {
when(sigV4Validator.validate(anyString(), anyString(), anyString())).thenReturn(true);
@@ -0,0 +1,102 @@
package io.floci.aws.services.memorydb.proxy;
import io.floci.aws.testing.FakeRespServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class MemoryDbAuthProxyTest {
private FakeRespServer backend;
@BeforeEach
void startBackend() throws IOException {
backend = FakeRespServer.answeringOk();
}
@AfterEach
void stopBackend() throws IOException {
backend.close();
}
@Test
void aClusterWithAnAclOfItsOwnRunsEachSessionUnderItsUsersAccessString() throws Exception {
MemoryDbAuthProxy proxy = proxy(true, Map.of("reader", "on ~app:* -@all +get"));
initialize(proxy, "reader");
List<List<String>> commands = backend.commands();
assertEquals(List.of("ACL", "SETUSER", "default", "reset", "off"), commands.get(2),
"the backend's default user must not stay open to a client that sends AUTH again");
List<String> rules = commands.get(3);
assertEquals(List.of("ACL", "SETUSER", "reader", "reset", "on", "~app:*", "-@all", "+get"), rules.subList(0, 8));
assertTrue(rules.contains("-config"));
assertEquals(List.of("AUTH", "reader", rules.get(rules.indexOf("resetpass") + 1).substring(1)),
commands.get(4));
}
@Test
void aSessionWithoutAuthRunsAsTheAclsDefaultUser() throws Exception {
MemoryDbAuthProxy proxy = proxy(true, Map.of("default", "on ~* &* +@all"));
initialize(proxy, null);
List<String> rules = backend.commands().get(3);
assertTrue(rules.get(2).startsWith("floci-default-"), "default must not reopen the backend's own default user");
assertEquals(List.of("reset", "on", "~*", "&*", "+@all"), rules.subList(3, 8));
}
@Test
void aUserTheAclNoLongerHoldsIsRefused() {
MemoryDbAuthProxy proxy = proxy(true, Map.of());
assertThrows(IOException.class, () -> initialize(proxy, "gone"));
}
@Test
void anOpenAccessClusterRelaysWithoutTouchingTheBackend() throws Exception {
MemoryDbAuthProxy proxy = proxy(false, Map.of("default", "on ~* &* +@all"));
Socket socket = mock(Socket.class);
proxy.initializeBackend(socket, "default");
verifyNoInteractions(socket);
}
private void initialize(MemoryDbAuthProxy proxy, String username) throws IOException {
try (Socket socket = new Socket("localhost", backend.port())) {
proxy.initializeBackend(socket, username);
}
}
private MemoryDbAuthProxy proxy(boolean ownAcl, Map<String, String> accessStrings) {
return new MemoryDbAuthProxy("cluster", true, "localhost", backend.port(),
new MemoryDbAuthProxy.AuthValidator() {
@Override
public boolean authenticate(String username, String secret) {
return true;
}
@Override
public boolean enforcesAccessStrings() {
return ownAcl;
}
@Override
public String accessString(String username) {
return accessStrings.get(username);
}
});
}
}
@@ -0,0 +1,124 @@
package io.floci.aws.testing;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
/**
* A RESP server on a free local port that records every command array it is sent, in order across its
* connections, and answers each with the raw reply {@code replies} gives for it.
*/
public final class FakeRespServer implements AutoCloseable {
private final ServerSocket server;
private final Function<List<String>, String> replies;
private final List<List<String>> commands = new CopyOnWriteArrayList<>();
private final List<Socket> accepted = new CopyOnWriteArrayList<>();
public FakeRespServer(Function<List<String>, String> replies) throws IOException {
this.server = new ServerSocket(0);
this.replies = replies;
Thread acceptor = new Thread(this::acceptConnections, "fake-resp-server");
acceptor.setDaemon(true);
acceptor.start();
}
/** Answers {@code +OK} to everything. */
public static FakeRespServer answeringOk() throws IOException {
return new FakeRespServer(command -> "+OK\r\n");
}
public static String bulk(String value) {
return "$" + value.getBytes(StandardCharsets.UTF_8).length + "\r\n" + value + "\r\n";
}
public int port() {
return server.getLocalPort();
}
/** The commands received so far, a live view. */
public List<List<String>> commands() {
return commands;
}
public int connections() {
return accepted.size();
}
@Override
public void close() throws IOException {
server.close();
for (Socket socket : accepted) {
socket.close();
}
}
private void acceptConnections() {
while (!server.isClosed()) {
try {
Socket socket = server.accept();
accepted.add(socket);
Thread handler = new Thread(() -> serve(socket), "fake-resp-connection");
handler.setDaemon(true);
handler.start();
} catch (IOException e) {
return;
}
}
}
private void serve(Socket socket) {
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
while (true) {
List<String> command = readCommand(in);
if (command == null) {
return;
}
commands.add(command);
out.write(replies.apply(command).getBytes(StandardCharsets.UTF_8));
out.flush();
}
} catch (IOException expected) {
// The client or close() ended the connection, which is how every fake connection ends.
}
}
private static List<String> readCommand(InputStream in) throws IOException {
String header = readLine(in);
if (header == null) {
return null;
}
int count = Integer.parseInt(header.substring(1));
List<String> arguments = new ArrayList<>();
for (int i = 0; i < count; i++) {
int length = Integer.parseInt(readLine(in).substring(1));
byte[] bytes = in.readNBytes(length);
readLine(in);
arguments.add(new String(bytes, StandardCharsets.UTF_8));
}
return arguments;
}
private static String readLine(InputStream in) throws IOException {
StringBuilder line = new StringBuilder();
int value;
while ((value = in.read()) != -1) {
if (value == '\n') {
return line.toString();
}
if (value != '\r') {
line.append((char) value);
}
}
return null;
}
}