diff --git a/docs/services/elasticache.md b/docs/services/elasticache.md index a86a127601..8ccf68475b 100644 --- a/docs/services/elasticache.md +++ b/docs/services/elasticache.md @@ -52,9 +52,14 @@ 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). -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. +`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 +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 +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 diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java index 463e6f678b..eb7b57bbf6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java @@ -1654,7 +1654,7 @@ public class ElastiCacheService implements ResourceProvider { String id = original.getCacheClusterId(); String account = original.getOwnerAccountId(); return new ElastiCacheAuthProxy.PasswordValidator() { - private ElastiCacheUser member(String username) { + private ElastiCacheUser member(String username, boolean requireEnabled) { String name = username == null || username.isEmpty() ? "default" : username; synchronized (users) { CacheCluster cluster = cacheClusters.getForAccount(account, id).orElse(null); @@ -1666,14 +1666,14 @@ public class ElastiCacheService implements ResourceProvider { return null; } return group.getUserIds().stream().map(userId -> users.getForAccount(account, userId).orElse(null)) - .filter(user -> user != null && name.equals(user.getUserName()) && user.isEnabled()) + .filter(user -> user != null && name.equals(user.getUserName()) && (!requireEnabled || user.isEnabled())) .findFirst().orElse(null); } } @Override public boolean validatePassword(String username, String password) { - ElastiCacheUser user = member(username); + ElastiCacheUser user = member(username, true); return user != null && (user.getAuthMode() == AuthMode.NO_AUTH || user.getAuthMode() == AuthMode.PASSWORD && user.getPasswords().contains(password)); } @@ -1686,7 +1686,7 @@ public class ElastiCacheService implements ResourceProvider { @Override public AuthMode memberAuthMode(String username) { - ElastiCacheUser user = member(username); + ElastiCacheUser user = member(username, true); return user == null ? null : user.getAuthMode(); } @@ -1697,7 +1697,7 @@ public class ElastiCacheService implements ResourceProvider { @Override public String accessString(String username) { - ElastiCacheUser user = member(username); + ElastiCacheUser user = member(username, false); return user == null ? null : user.getAccessString(); } @@ -2141,6 +2141,36 @@ public class ElastiCacheService implements ResourceProvider { // Storage backends hand back the live stored object, so validate everything // before the first setter — a rejected request must not leave changes behind. String normalizedEngine = (engine == null || engine.isBlank()) ? null : normalizeEngine(engine); + ElastiCacheUser modified = applyUserModification(userId, user, authMode, passwords, accessString, + appendAccessString, normalizedEngine); + if (accessString != null || appendAccessString != null) { + reapplyAccessString(userId, modified); + } + return modified; + } + + /** Lets the open sessions of every cache the user can sign in to pick up its new access string. */ + private void reapplyAccessString(String userId, ElastiCacheUser user) { + for (ReplicationGroup group : groups.scan(k -> true)) { + if (effectiveUserIds(groups.accountId(), group).contains(userId)) { + proxyManager.refreshUser(group.getReplicationGroupId(), user.getUserName()); + } + } + for (CacheCluster cluster : cacheClusters.scan(k -> true)) { + if (cluster.getServerlessCacheName() != null && cluster.getUserGroupId() != null) { + String account = cluster.getOwnerAccountId() != null ? cluster.getOwnerAccountId() : cacheClusters.accountId(); + ElastiCacheUserGroup group = userGroups.getForAccount(account, + normalizeUserGroupId(cluster.getUserGroupId())).orElse(null); + if (group != null && group.getUserIds().contains(userId)) { + proxyManager.refreshUser(cluster.getCacheClusterId(), user.getUserName()); + } + } + } + } + + private ElastiCacheUser applyUserModification(String userId, ElastiCacheUser user, AuthMode authMode, + List passwords, String accessString, + String appendAccessString, String normalizedEngine) { synchronized (userGroupLock) { String nextEngine = normalizedEngine != null ? normalizedEngine : user.getEngine(); AuthMode nextAuthMode = authMode != null ? authMode : user.getAuthMode(); @@ -2563,7 +2593,7 @@ public class ElastiCacheService implements ResourceProvider { } return effectiveUserIds(accountId, group).stream() .map(id -> users.getForAccount(accountId, id).orElse(null)) - .filter(user -> user != null && user.isEnabled() && username.equals(user.getUserName())) + .filter(user -> user != null && username.equals(user.getUserName())) .map(ElastiCacheUser::getAccessString).findFirst().orElse(null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java index c764464558..a2c6097765 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java @@ -86,6 +86,14 @@ public abstract class AbstractRedisAuthProxy { this.handshakeTimeoutMillis = handshakeTimeoutMillis; } + protected final String backendHost() { + return backendHost; + } + + protected final int backendPort() { + return backendPort; + } + /** Whether the {@code AUTH} command is required before bridging to the backend. */ protected abstract boolean authRequired(); diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java index 2d24ef842b..8874550bd6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAuthProxy.java @@ -96,11 +96,22 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy { 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, + () -> members ? passwordValidator.accessString(name) : "on ~* &* +@all"); + } + + /** + * Applies the user's current access string to the backend user that its open sessions run as. A + * failure is logged and the sessions keep their old permissions until the user authenticates again. + */ + public void refreshUser(String username) { + String name = username == null || username.isEmpty() ? "default" : username; + try { + backendAcl.reapply(backendHost(), backendPort(), name, () -> passwordValidator.accessString(name)); + } catch (IOException e) { + LOG.warnv(e, "Could not apply the new permissions of user {0} to the open sessions of group {1}", + name, groupId); } - backendAcl.authenticate(backend, name, access); } @Override diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAcl.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAcl.java index d8ba9ccbf8..28c942e07a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAcl.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAcl.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.elasticache.proxy; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -10,9 +11,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.Supplier; /** Keeps frontend passwords and IAM tokens out of the backend's private ACL credentials. */ final class ElastiCacheBackendAcl { + private static final int CONNECT_TIMEOUT_MILLIS = 5000; + private static final int COMMAND_TIMEOUT_MILLIS = 10000; + private final String administrator = "floci-admin-" + UUID.randomUUID(); private final String administratorPassword = UUID.randomUUID().toString(); private final Map passwords = new LinkedHashMap<>(); @@ -22,13 +27,14 @@ final class ElastiCacheBackendAcl { return initialized; } - synchronized void authenticate(Socket backend, String username, String accessString) throws IOException { - List 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"); + synchronized void authenticate(Socket backend, String username, Supplier accessStringSupplier) + throws IOException { + String accessString = accessStringSupplier.get(); + if (accessString == null) { + throw new IOException("Cache user is no longer associated with this resource"); } - backend.setSoTimeout(10000); + List accessRules = accessRules(accessString); + backend.setSoTimeout(COMMAND_TIMEOUT_MILLIS); if (!initialized) { command(backend, List.of("ACL", "SETUSER", administrator, "reset", "on", ">" + administratorPassword, "~*", "&*", "+@all")); @@ -38,8 +44,64 @@ final class ElastiCacheBackendAcl { } else { command(backend, List.of("AUTH", administrator, administratorPassword)); } - String backendName = "default".equals(username) ? "floci-default-" + administrator : username; + String backendName = backendName(username); String password = passwords.computeIfAbsent(backendName, ignored -> UUID.randomUUID().toString()); + command(backend, userRules(backendName, accessRules, password)); + command(backend, List.of("AUTH", backendName, password)); + backend.setSoTimeout(0); + } + + void authenticate(Socket backend, String username, String accessString) throws IOException { + authenticate(backend, username, () -> accessString); + } + + /** + * Installs a changed access string on the backend user that sessions of {@code username} already run + * as, so it applies to their open connections and not only to the next login. Nothing is done while + * the backend has not been set up, or for a user nobody has authenticated as yet: the next login + * installs the current rules. + */ + synchronized void reapply(String backendHost, int backendPort, String username, + Supplier accessStringSupplier) throws IOException { + if (!initialized) { + return; + } + String backendName = backendName(username); + String password = passwords.get(backendName); + if (password == null) { + return; + } + String accessString = accessStringSupplier.get(); + if (accessString == null) { + return; + } + List accessRules = accessRules(accessString); + try (Socket backend = new Socket()) { + 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)); + } + } + + void reapply(String backendHost, int backendPort, String username, String accessString) throws IOException { + reapply(backendHost, backendPort, username, () -> accessString); + } + + private String backendName(String username) { + return "default".equals(username) ? "floci-default-" + administrator : username; + } + + private static List accessRules(String accessString) throws IOException { + List 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"); + } + return accessRules; + } + + private static List userRules(String backendName, List accessRules, String password) { List 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 @@ -47,9 +109,7 @@ final class ElastiCacheBackendAcl { 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); + return rules; } private static void command(Socket socket, List arguments) throws IOException { diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheProxyManager.java index 674e000d15..91b1d64877 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheProxyManager.java @@ -64,6 +64,14 @@ public class ElastiCacheProxyManager { } } + /** Applies a changed access string of {@code username} to the open sessions of the group's proxy. */ + public void refreshUser(String groupId, String username) { + ElastiCacheAuthProxy proxy = proxies.get(groupId); + if (proxy != null) { + proxy.refreshUser(username); + } + } + public void stopAll() { proxies.values().forEach(ElastiCacheAuthProxy::stop); proxies.clear(); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java index fa1df66e75..6a724bb874 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java @@ -202,6 +202,25 @@ class ElastiCacheServerlessServiceTest { assertFalse(validator.getValue().hasMembers()); } + @Test + void modifyUserAccessStringIsAppliedToOpenSessionsOfServerlessCache() { + ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team")); + ArgumentCaptor validator = ArgumentCaptor.forClass( + ElastiCacheAuthProxy.PasswordValidator.class); + verify(proxies).startProxy(eq(cache.getBackingCacheClusterId()), any(), anyInt(), anyString(), anyInt(), + validator.capture(), eq("cache")); + + runtime.modifyUser("alice", null, null, "on ~allowed:* -@all +get", null, null); + verify(proxies).refreshUser(cache.getBackingCacheClusterId(), "alice"); + assertEquals("on ~allowed:* -@all +get", validator.getValue().accessString("alice")); + + runtime.modifyUser("alice", null, null, "off -@all", null, null); + verify(proxies, times(2)).refreshUser(cache.getBackingCacheClusterId(), "alice"); + assertEquals("off -@all", validator.getValue().accessString("alice")); + assertFalse(validator.getValue().validatePassword("alice", "password-a")); + assertNull(validator.getValue().memberAuthMode("alice")); + } + @Test void validationAndFailedAllocationLeaveNoAssociationOrRecord() { error("UserGroupNotFound", () -> service.createServerlessCache(create("missing", "valkey", "absent"))); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java index e8d19c2428..cf8d8319b9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java @@ -1364,6 +1364,85 @@ class ElastiCacheServiceTest { 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")); + account.set("111111111111"); + svc.modifyUser("app-user-id", null, null, "off -@all", null, null); + account.set("000000000000"); + assertEquals("off -@all", validator.getValue().accessString("app")); + assertFalse(validator.getValue().validatePassword("app", "app-pass")); + assertNull(validator.getValue().memberAuthMode("app")); + } + + @Test + void modifyUserAccessStringIsAppliedToTheOpenSessionsOfTheGroupsThatHoldTheUser() { + service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"); + service.createReplicationGroup("other", "test", AuthMode.PASSWORD, null, "us-east-1"); + 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", "redis", List.of("default-user-id", "app-user-id"), "us-east-1"); + service.modifyReplicationGroup("grp", List.of("app-group"), null); + + service.modifyUser("app-user-id", null, null, "on ~allowed:* -@all +get", null, null); + + verify(proxyManager).refreshUser("grp", "app"); + verify(proxyManager, never()).refreshUser(eq("other"), anyString()); + } + + @Test + void modifyUserAppendedAccessStringIsAppliedToTheOpenSessions() { + service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"); + service.createUser("default-user-id", "default", AuthMode.PASSWORD, List.of("default-pass"), + "on ~* +@all", null); + service.createUserGroup("app-group", "redis", List.of("default-user-id"), "us-east-1"); + service.modifyReplicationGroup("grp", List.of("app-group"), null); + + service.modifyUser("default-user-id", null, null, null, "-flushall", null); + + verify(proxyManager).refreshUser("grp", "default"); + } + + @Test + void modifyUserWithoutAnAccessStringChangeLeavesTheOpenSessionsAlone() { + service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"); + service.createUser("default-user-id", "default", AuthMode.PASSWORD, List.of("default-pass"), + "on ~* +@all", null); + service.createUserGroup("app-group", "redis", List.of("default-user-id"), "us-east-1"); + service.modifyReplicationGroup("grp", List.of("app-group"), null); + + service.modifyUser("default-user-id", AuthMode.PASSWORD, List.of("new-pass"), null, null, null); + + verify(proxyManager, never()).refreshUser(anyString(), anyString()); + } + + @Test + void modifyUserDisablingUserAppliesToTheOpenSessions() { + service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"); + 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", "redis", List.of("default-user-id", "app-user-id"), "us-east-1"); + service.modifyReplicationGroup("grp", List.of("app-group"), null); + + service.modifyUser("app-user-id", null, null, "off -@all", null, null); + + verify(proxyManager).refreshUser("grp", "app"); + } + + @Test + void modifyUserAccessStringIsAppliedToAssociatedServerlessCaches() { + ElastiCacheService.CreateCacheClusterRequest req = new ElastiCacheService.CreateCacheClusterRequest( + "serverless-backing", "valkey", null, null, 1, null, AuthMode.NO_AUTH, null, null, null, + 0, null, null, null, null, null, null, false, "us-east-1", Map.of()); + service.createServerlessBacking(req, "my-serverless", "000000000000", "app-group"); + + 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.modifyUser("app-user-id", null, null, "on ~allowed:* -@all +get", null, null); + + verify(proxyManager).refreshUser("serverless-backing", "app"); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java index 361f549a8a..7f7a4f12d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java @@ -12,6 +12,7 @@ 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.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; @@ -190,6 +191,25 @@ class ElastiCacheAclProxyIntegrationTest { } } + @Test + void changedPermissionsApplyToAnAlreadyOpenSession() throws Exception { + memberMode.set(AuthMode.PASSWORD); + access.set("on ~allowed:* &* -@all +get +ping"); + try (Socket open = connect(proxy.localPort(), trust)) { + assertEquals("+OK", command(open, "AUTH", "subscriber", "synthetic-password")); + assertEquals("+PONG", command(open, "PING")); + assertTrue(command(open, "SET", "allowed:key", "value").startsWith("-NOPERM")); + + access.set("on ~allowed:* &* -@all +get +set +ping"); + proxy.refreshUser("subscriber"); + assertEquals("+OK", command(open, "SET", "allowed:key", "value")); + + access.set("on ~allowed:* &* -@all +get +ping"); + proxy.refreshUser("subscriber"); + assertTrue(command(open, "SET", "allowed:key", "value").startsWith("-NOPERM")); + } + } + @AfterAll void stopBackend() throws Exception { try { diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAclTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAclTest.java new file mode 100644 index 0000000000..f0f68a0ab5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/ElastiCacheBackendAclTest.java @@ -0,0 +1,228 @@ +package io.github.hectorvent.floci.services.elasticache.proxy; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +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; + +class ElastiCacheBackendAclTest { + + private static final int WAIT_MILLIS = 5000; + + private ServerSocket server; + private final List> commands = new CopyOnWriteArrayList<>(); + private final List accepted = new CopyOnWriteArrayList<>(); + private volatile boolean refuseNextCommands; + private ElastiCacheBackendAcl acl; + + @BeforeEach + void startBackend() throws IOException { + server = new ServerSocket(0); + 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 + void reapplyInstallsTheNewRulesOnTheBackendUserThatLoginCreated() throws Exception { + login("app", "on ~app:* -@all +get"); + int afterLogin = commands.size(); + String sessionPassword = passwordOf("app"); + + acl.reapply("localhost", server.getLocalPort(), "app", "on ~app:* -@all +get +set"); + + List> sent = commands.subList(afterLogin, commands.size()); + assertEquals(2, sent.size()); + assertEquals("AUTH", sent.get(0).get(0)); + assertTrue(sent.get(0).get(1).startsWith("floci-admin-")); + assertEquals(List.of("ACL", "SETUSER", "app", "reset", "on", "~app:*", "-@all", "+get", "+set", "resetpass", + ">" + sessionPassword), sent.get(1).subList(0, 11)); + assertTrue(sent.get(1).contains("-acl")); + assertTrue(sent.get(1).contains("-save")); + } + + @Test + void defaultUserIsReappliedToTheSameBackendUserLoginUsed() throws Exception { + login("default", "on ~* +@all"); + String backendUser = commands.stream() + .filter(c -> c.size() > 2 && "SETUSER".equals(c.get(1)) && c.get(2).startsWith("floci-default-")) + .findFirst().orElseThrow().get(2); + int afterLogin = commands.size(); + + acl.reapply("localhost", server.getLocalPort(), "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"); + + assertEquals(0, accepted.size()); + } + + @Test + void nothingIsSentForAUserNobodyHasAuthenticatedAs() throws Exception { + login("app", "on ~* +@all"); + int connections = accepted.size(); + + acl.reapply("localhost", server.getLocalPort(), "other", "on ~* +@all"); + + assertEquals(connections, accepted.size()); + } + + @Test + void selectorsAreRefusedWithoutTouchingTheBackend() throws Exception { + login("app", "on ~* +@all"); + int connections = accepted.size(); + + assertThrows(IOException.class, + () -> acl.reapply("localhost", server.getLocalPort(), "app", "on ~* -@all (+get ~*)")); + + assertEquals(connections, accepted.size()); + } + + @Test + void backendRefusalIsReportedWithoutExposingItsResponse() throws Exception { + login("app", "on ~* +@all"); + refuseNextCommands = true; + + IOException failure = assertThrows(IOException.class, + () -> acl.reapply("localhost", server.getLocalPort(), "app", "on ~* +@all")); + + assertEquals("Could not establish the backend cache user's permissions", failure.getMessage()); + } + + @Test + void rulesAreReadUnderTheLockSoStaleRulesCannotOverwriteNewerRules() throws Exception { + login("app", "on ~app:* -@all +get"); + int afterLogin = commands.size(); + + AtomicReference currentRules = new AtomicReference<>("on ~app:* -@all +get +set"); + acl.reapply("localhost", server.getLocalPort(), "app", currentRules::get); + + currentRules.set("on ~app:* -@all +get"); + acl.reapply("localhost", server.getLocalPort(), "app", currentRules::get); + + List> sent = commands.subList(afterLogin, commands.size()); + assertEquals(4, sent.size()); + assertTrue(sent.get(1).contains("+set")); + assertFalse(sent.get(3).contains("+set")); + } + + @Test + void disabledUserAccessStringIsReappliedToBackend() throws Exception { + login("app", "on ~app:* -@all +get"); + int afterLogin = commands.size(); + + acl.reapply("localhost", server.getLocalPort(), "app", "off -@all"); + + List> sent = commands.subList(afterLogin, commands.size()); + assertEquals(2, sent.size()); + assertEquals("ACL", sent.get(1).get(0)); + assertEquals("SETUSER", sent.get(1).get(1)); + assertEquals("app", sent.get(1).get(2)); + assertEquals("reset", sent.get(1).get(3)); + assertEquals("off", sent.get(1).get(4)); + assertEquals("-@all", sent.get(1).get(5)); + } + + private void login(String username, String accessString) throws IOException { + try (Socket backend = new Socket("localhost", server.getLocalPort())) { + 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 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 readCommand(InputStream in) throws IOException { + String header = readLine(in); + if (header == null) { + return null; + } + int count = Integer.parseInt(header.substring(1)); + List 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; + } +}