mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
bb57e63b8e
commit
7466c5c063
17 files changed
+1065
-153
No files matched your search
+232
@@ -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");
|
||||
|
||||
+116
@@ -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<>();
|
||||
|
||||
+134
-99
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user