fix(elasticache): enforce user permissions in backend ACL sessions (#6608)

* fix(elasticache): enforce user permissions in backend ACL sessions

* fix(elasticache): block replication commands for ACL users

* fix(elasticache): deny persistence and migration commands
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-27 10:36:05 -04:00
1 parent d58ce5c31c
commit 3890378728
8 files changed
+409 -7

No files matched your search

+32 -1
View File
@@ -32,7 +32,38 @@ valkey-cli --tls --cacert ./floci-root-ca.crt -h localhost -p "$CACHE_PORT" \
```
TLS terminates in Floci's cache proxy; the Docker backend hop retains its existing
transport. This does not add Memcached transit encryption or change cache-user ACL enforcement.
transport. This does not add Memcached transit encryption.
## User access strings
For non-cluster-mode Redis/Valkey replication groups 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
is disabled once RBAC is used, so another `AUTH` or `HELLO AUTH` cannot regain its
unrestricted permissions.
Backend passwords are generated in memory separately from frontend passwords and IAM
tokens. Even `+@all` users cannot manage ACLs or backend configuration, load modules,
reconfigure replication, shut down the engine, or observe administrative commands through
`MONITOR` or `SLOWLOG`. `SYNC` and `PSYNC` are also denied: replication streams can expose
keys outside a user's permitted key patterns. `SAVE`, `BGSAVE`, `BGREWRITEAOF`, and `MIGRATE`
are denied as well, preventing backend persistence operations and outbound key migrations.
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).
Access-string changes are installed on the next successful authentication; reconnect to
apply changes promptly. Re-authentication on an already relayed connection uses the
backend protocol directly, so reconnect through the proxy with frontend credentials.
Revoked members' existing sessions are not proactively disconnected by this change.
ACL selectors are rejected before backend changes: a selector can grant permissions
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
@@ -1695,6 +1695,12 @@ public class ElastiCacheService implements ResourceProvider {
return TransitEncryption.REQUIRED;
}
@Override
public String accessString(String username) {
ElastiCacheUser user = member(username);
return user == null ? null : user.getAccessString();
}
@Override
public String ownerAccountId() {
return account;
@@ -2549,6 +2555,23 @@ public class ElastiCacheService implements ResourceProvider {
.map(ReplicationGroup::transitEncryption).orElse(TransitEncryption.REQUIRED);
}
@Override
public String accessString(String username) {
ReplicationGroup group = groups.getForAccount(accountId, groupId).orElse(null);
if (group == null) {
return null;
}
return effectiveUserIds(accountId, group).stream()
.map(id -> users.getForAccount(accountId, id).orElse(null))
.filter(user -> user != null && user.isEnabled() && username.equals(user.getUserName()))
.map(ElastiCacheUser::getAccessString).findFirst().orElse(null);
}
@Override
public boolean clusterMode() {
return groups.getForAccount(accountId, groupId).map(ReplicationGroup::isClusterEnabled).orElse(false);
}
@Override
public String ownerAccountId() {
return accountId;
@@ -94,6 +94,10 @@ public abstract class AbstractRedisAuthProxy {
/** Closes a socket, tolerating errors. Implementations may add their own logging. */
protected abstract void closeQuietly(Socket socket);
/** Applies the validated frontend identity to a newly connected backend. */
protected void initializeBackend(Socket backend, String username) throws IOException {
}
/** Establishes the client transport before reading credentials. */
protected ClientTransport clientTransport(Socket client) throws IOException {
return ClientTransport.unencrypted(client);
@@ -205,7 +209,7 @@ public abstract class AbstractRedisAuthProxy {
}
continue;
}
bridgeCommand(client, input, cmd);
bridgeCommand(client, input, cmd, null);
return;
}
if (authRequired()) {
@@ -214,7 +218,7 @@ public abstract class AbstractRedisAuthProxy {
return;
}
bridgeCommand(client, input, cmd);
bridgeCommand(client, input, cmd, null);
return;
}
} catch (Exception e) {
@@ -252,8 +256,7 @@ public abstract class AbstractRedisAuthProxy {
return;
}
writeResponse(client, OK_RESPONSE);
bridgeCommand(client, input, null);
bridgeCommand(client, input, null, username);
}
private boolean handleHello(Socket client, InputStream input, String[] cmd) throws IOException {
@@ -318,7 +321,7 @@ public abstract class AbstractRedisAuthProxy {
return false;
}
bridgeCommand(client, input, forwarded.toArray(String[]::new));
bridgeCommand(client, input, forwarded.toArray(String[]::new), username);
return true;
}
@@ -339,12 +342,15 @@ public abstract class AbstractRedisAuthProxy {
return true;
}
private void bridgeCommand(Socket client, InputStream input, String[] command) throws IOException {
private void bridgeCommand(Socket client, InputStream input, String[] command, String username) throws IOException {
Socket backend = new Socket(backendHost, backendPort);
try {
backend.setTcpNoDelay(true);
initializeBackend(backend, username);
if (command != null) {
resendCommand(command, backend.getOutputStream());
} else {
writeResponse(client, OK_RESPONSE);
}
client.setSoTimeout(0);
handshakingClients.remove(client);
@@ -30,6 +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();
public ElastiCacheAuthProxy(String groupId, AuthMode authMode,
String backendHost, int backendPort,
@@ -83,6 +84,25 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
return encrypted;
}
@Override
protected void initializeBackend(Socket backend, String username) throws IOException {
boolean members = passwordValidator.hasMembers();
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");
}
String name = username == null || username.isEmpty() ? "default" : username;
String access = members ? passwordValidator.accessString(name) : "on ~* &* +@all";
if (access == null) {
throw new IOException("Cache user is no longer associated with this resource");
}
backendAcl.authenticate(backend, name, access);
}
@Override
protected boolean authRequired() {
if (passwordValidator.hasMembers()) {
@@ -168,6 +188,14 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
return TransitEncryption.NONE;
}
default String accessString(String username) {
return null;
}
default boolean clusterMode() {
return false;
}
default boolean hasMembers() {
return false;
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** Keeps frontend passwords and IAM tokens out of the backend's private ACL credentials. */
final class ElastiCacheBackendAcl {
private final String administrator = "floci-admin-" + UUID.randomUUID();
private final String administratorPassword = UUID.randomUUID().toString();
private final Map<String, String> passwords = new LinkedHashMap<>();
private volatile boolean initialized;
boolean initialized() {
return initialized;
}
synchronized void authenticate(Socket backend, String username, String accessString) throws IOException {
List<String> accessRules = List.of(accessString.trim().split("\\s+"));
if (accessRules.stream().anyMatch(rule -> rule.startsWith("("))) {
// Selectors can grant permissions independently of the root command restrictions below.
throw new IOException("Cache ACL selectors are not supported yet");
}
backend.setSoTimeout(10000);
if (!initialized) {
command(backend, List.of("ACL", "SETUSER", administrator, "reset", "on",
">" + administratorPassword, "~*", "&*", "+@all"));
command(backend, List.of("AUTH", administrator, administratorPassword));
command(backend, List.of("ACL", "SETUSER", "default", "reset", "off"));
initialized = true;
} else {
command(backend, List.of("AUTH", administrator, administratorPassword));
}
String backendName = "default".equals(username) ? "floci-default-" + administrator : username;
String password = passwords.computeIfAbsent(backendName, ignored -> UUID.randomUUID().toString());
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
// must never make an alternate backend identity publicly accessible.
rules.addAll(List.of("resetpass", ">" + password, "-acl", "-config", "-debug", "-module",
"-replicaof", "-slaveof", "-shutdown", "-monitor", "-slowlog", "-sync", "-psync",
"-save", "-bgsave", "-bgrewriteaof", "-migrate"));
command(backend, rules);
command(backend, List.of("AUTH", backendName, password));
backend.setSoTimeout(0);
}
private static void command(Socket socket, List<String> arguments) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(("*" + arguments.size() + "\r\n").getBytes(StandardCharsets.US_ASCII));
for (String argument : arguments) {
byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
out.write(("$" + bytes.length + "\r\n").getBytes(StandardCharsets.US_ASCII));
out.write(bytes);
out.write("\r\n".getBytes(StandardCharsets.US_ASCII));
}
out.flush();
InputStream in = socket.getInputStream();
StringBuilder response = new StringBuilder();
int value;
while ((value = in.read()) != -1 && value != '\r' && response.length() < 4096) {
response.append((char) value);
}
if (value != '\r' || in.read() != '\n' || !"+OK".contentEquals(response)) {
// Never include server responses, access strings or credentials in this error.
throw new IOException("Could not establish the backend cache user's permissions");
}
}
}
@@ -1358,6 +1358,12 @@ class ElastiCacheServiceTest {
// The proxy authenticates on its own thread, where the store falls back to the default account.
account.set("000000000000");
assertTrue(validator.getValue().validatePassword("app", "app-pass"));
assertEquals("on ~* +@all", validator.getValue().accessString("app"));
assertNull(validator.getValue().accessString("unknown"));
account.set("111111111111");
svc.modifyUser("app-user-id", null, null, "on ~allowed:* -@all +get", null, null);
account.set("000000000000");
assertEquals("on ~allowed:* -@all +get", validator.getValue().accessString("app"));
}
@Test
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.TransitEncryption;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.TlsTrust;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ElastiCacheAclProxyIntegrationTest {
@TempDir
static Path directory;
private final AtomicReference<AuthMode> memberMode = new AtomicReference<>();
private final AtomicReference<String> access = new AtomicReference<>();
private String name;
private ElastiCacheAuthProxy proxy;
private SSLContext trust;
private String docker(String... arguments) throws Exception {
List<String> command = new ArrayList<>(List.of("docker"));
command.addAll(List.of(arguments));
Path output = Files.createTempFile(directory, "docker-", ".log");
Process process = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()).start();
if (!process.waitFor(90, TimeUnit.SECONDS)) {
process.destroyForcibly();
throw new IllegalStateException("Docker command timed out");
}
assertEquals(0, process.exitValue(), () -> {
try {
return Files.readString(output);
} catch (Exception e) {
return "Docker command failed";
}
});
return Files.readString(output).trim();
}
private static String command(Socket socket, String... values) throws Exception {
StringBuilder request = new StringBuilder("*" + values.length + "\r\n");
for (String value : values) {
request.append('$').append(value.getBytes(StandardCharsets.UTF_8).length).append("\r\n")
.append(value).append("\r\n");
}
socket.getOutputStream().write(request.toString().getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
return new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)).readLine();
}
private static Socket connect(int port, SSLContext trust) throws Exception {
SSLSocket socket = (SSLSocket) trust.getSocketFactory().createSocket("127.0.0.1", port);
socket.setSoTimeout(5000);
SSLParameters parameters = socket.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(parameters);
socket.startHandshake();
return socket;
}
@BeforeAll
void startBackend() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
"Docker is required for actual Valkey ACL enforcement");
name = "floci-acl-test-" + UUID.randomUUID();
docker("run", "--detach", "--name", name, "--publish", "127.0.0.1::6379", "valkey/valkey:8",
"valkey-server", "--protected-mode", "no", "--save", "", "--appendonly", "no");
await().atMost(20, TimeUnit.SECONDS)
.untilAsserted(() -> assertEquals("PONG", docker("exec", name, "valkey-cli", "PING")));
int backendPort = Integer.parseInt(docker("inspect", "--format",
"{{(index (index .NetworkSettings.Ports \"6379/tcp\") 0).HostPort}}", name));
assertEquals("OK", docker("exec", name, "valkey-cli", "SET", "other:key", "private-example"));
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory.resolve("ca"));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config,
new CertificateGenerator());
trust = TlsTrust.trusting(authority.certificate());
SigV4Validator sigV4 = new SigV4Validator(
IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache"));
proxy = new ElastiCacheAuthProxy("acl-test", AuthMode.PASSWORD, "127.0.0.1", backendPort,
new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "subscriber".equals(username) && "synthetic-password".equals(password);
}
@Override
public boolean hasMembers() { return true; }
@Override
public AuthMode memberAuthMode(String username) {
return "subscriber".equals(username) ? memberMode.get() : null;
}
@Override
public String accessString(String username) { return access.get(); }
@Override
public TransitEncryption transitEncryption() { return TransitEncryption.REQUIRED; }
}, sigV4, certificates::sslContext);
proxy.start(0);
}
@ParameterizedTest
@EnumSource(value = AuthMode.class, names = {"PASSWORD", "IAM"})
void backendEnforcesCommandsKeysAndChannelsWithoutDefaultUserEscape(AuthMode mode) throws Exception {
memberMode.set(mode);
access.set("on ~* &allowed:* -@all +subscribe +psubscribe +ping");
String credential = mode == AuthMode.IAM ? SigV4TokenTestHelper.createElastiCacheToken(
"acl-test", "subscriber", "AKIDCACHE", "secret-cache", Instant.now().minusSeconds(60), 900)
: "synthetic-password";
int port = proxy.localPort();
try (Socket invalid = connect(port, trust)) {
assertTrue(command(invalid, "AUTH", "subscriber", "wrong-credential").startsWith("-ERR"));
}
try (Socket subscriber = connect(port, trust)) {
assertEquals("+OK", command(subscriber, "AUTH", "subscriber", credential));
assertEquals("+PONG", command(subscriber, "PING"));
assertTrue(command(subscriber, "SET", "key", "value").startsWith("-NOPERM"));
assertTrue(command(subscriber, "GET", "key").startsWith("-NOPERM"));
assertTrue(command(subscriber, "PUBLISH", "allowed:channel", "message").startsWith("-NOPERM"));
assertTrue(command(subscriber, "FLUSHALL").startsWith("-NOPERM"));
assertTrue(command(subscriber, "AUTH", "default", "anything").startsWith("-WRONGPASS"));
assertTrue(command(subscriber, "HELLO", "2", "AUTH", "default", "anything").startsWith("-WRONGPASS"));
assertTrue(command(subscriber, "SET", "key", "still-denied").startsWith("-NOPERM"));
assertTrue(command(subscriber, "SUBSCRIBE", "forbidden:channel").startsWith("-NOPERM"));
assertEquals("*3", command(subscriber, "SUBSCRIBE", "allowed:channel"));
}
// Permission updates are applied on the next successful authentication.
access.set("on ~allowed:* &* +@all");
try (Socket writer = connect(port, trust)) {
assertEquals("+OK", command(writer, "AUTH", "subscriber", credential));
assertEquals("+OK", command(writer, "SET", "allowed:key", "value"));
assertEquals(":1", command(writer, "EXISTS", "allowed:key"));
assertTrue(command(writer, "SET", "other:key", "value").startsWith("-NOPERM"));
assertTrue(command(writer, "GET", "other:key").startsWith("-NOPERM"));
assertTrue(command(writer, "ACL", "SETUSER", "default", "on", "nopass", "+@all").startsWith("-NOPERM"));
assertTrue(command(writer, "CONFIG", "SET", "requirepass", "").startsWith("-NOPERM"));
assertTrue(command(writer, "MONITOR").startsWith("-NOPERM"));
assertTrue(command(writer, "SLOWLOG", "GET").startsWith("-NOPERM"));
assertTrue(command(writer, "SYNC").startsWith("-NOPERM"),
"SYNC must not expose keys outside the user's allowed pattern");
assertTrue(command(writer, "PSYNC", "?", "-1").startsWith("-NOPERM"),
"PSYNC must not expose keys outside the user's allowed pattern");
assertAll(
() -> assertTrue(command(writer, "SAVE").startsWith("-NOPERM"), "SAVE must be denied"),
() -> assertTrue(command(writer, "BGSAVE").startsWith("-NOPERM"), "BGSAVE must be denied"),
() -> assertTrue(command(writer, "BGREWRITEAOF").startsWith("-NOPERM"), "BGREWRITEAOF must be denied"),
() -> assertTrue(command(writer, "MIGRATE", "127.0.0.1", "1", "allowed:key", "0", "100")
.startsWith("-NOPERM"), "MIGRATE must be denied even for an allowed key"));
assertEquals(":1", command(writer, "EXISTS", "allowed:key"));
assertEquals("+PONG", command(writer, "PING"));
}
access.set("on ~* &* -@all +ping");
try (Socket hello = connect(port, trust)) {
assertTrue(command(hello, "HELLO", "2", "AUTH", "subscriber", credential).startsWith("*"));
}
}
@AfterAll
void stopBackend() throws Exception {
try {
if (proxy != null) {
proxy.stop();
}
} finally {
if (name != null) {
docker("rm", "--force", "--volumes", name);
}
}
}
}
@@ -3,15 +3,42 @@ package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicReference;
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.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ElastiCacheAuthProxyTest {
@Test
void selectorsFailClosedBeforeChangingBackendCredentials() {
ElastiCacheBackendAcl acl = new ElastiCacheBackendAcl();
Socket backend = mock(Socket.class);
assertThrows(IOException.class, () -> acl.authenticate(backend, "subscriber",
"on -@all (+@all ~* &*)"));
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<>();