feat(memorydb): model auth via ACLs and users (#1478)

* feat(memorydb): model auth via ACLs and users

* fix(memorydb): keep loading pre-existing cluster

* fix(memorydb): reject no-password CreateUser and validate UserName
This commit is contained in:
Ahmed khaled authored and GitHub committed 2026-06-25 19:48:45 -05:00
1 parent efacb37130
commit a8fde26d06
12 files changed
+960 -108

No files matched your search

@@ -2,20 +2,25 @@ package io.github.hectorvent.floci.services.memorydb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.memorydb.model.Acl;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
import io.github.hectorvent.floci.services.memorydb.model.Endpoint;
import io.github.hectorvent.floci.services.memorydb.model.User;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class MemoryDbHandlerTest {
@@ -35,31 +40,59 @@ class MemoryDbHandlerTest {
spec.setCreatedAt(Instant.now());
return spec;
});
when(service.clustersUsingAcl(any())).thenReturn(List.of());
when(service.aclNamesForUser(any())).thenReturn(List.of());
}
@Test
void createClusterPropagatesAuthTokenToSpec() throws Exception {
void createClusterPropagatesAclNameToSpec() throws Exception {
JsonNode request = objectMapper.readTree(
"{\"ClusterName\":\"secure\",\"AuthToken\":\"s3cret\"}");
"{\"ClusterName\":\"secure\",\"ACLName\":\"app-acl\"}");
handler.handle("CreateCluster", request, "us-east-1");
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
org.mockito.Mockito.verify(service).createCluster(captor.capture(), eq("us-east-1"));
Cluster spec = captor.getValue();
assertEquals("s3cret", spec.getAuthToken(),
"AuthToken must be copied onto the spec so PASSWORD auth can validate it");
assertEquals(AuthMode.PASSWORD, spec.getAuthMode());
verify(service).createCluster(captor.capture(), eq("us-east-1"));
assertEquals("app-acl", captor.getValue().getAclName());
}
@Test
void createClusterWithoutAuthTokenDefaultsToNoAuth() throws Exception {
JsonNode request = objectMapper.readTree("{\"ClusterName\":\"open\"}");
void createUserParsesAuthenticationMode() throws Exception {
when(service.createUser(any(), any())).thenAnswer(inv -> inv.getArgument(0));
JsonNode request = objectMapper.readTree(
"{\"UserName\":\"app-user\","
+ "\"AccessString\":\"on ~* +@all\","
+ "\"AuthenticationMode\":{\"Type\":\"password\",\"Passwords\":[\"s3cret\"]}}");
handler.handle("CreateCluster", request, "us-east-1");
Response response = handler.handle("CreateUser", request, "us-east-1");
assertEquals(200, response.getStatus());
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
org.mockito.Mockito.verify(service).createCluster(captor.capture(), eq("us-east-1"));
assertEquals(AuthMode.NO_AUTH, captor.getValue().getAuthMode());
ArgumentCaptor<User> captor = ArgumentCaptor.forClass(User.class);
verify(service).createUser(captor.capture(), eq("us-east-1"));
User spec = captor.getValue();
assertEquals("app-user", spec.getName());
assertEquals(AuthMode.PASSWORD, spec.getAuthMode());
assertEquals(List.of("s3cret"), spec.getPasswords());
}
@Test
void createAclParsesUserNames() throws Exception {
when(service.createAcl(any(), any())).thenAnswer(inv -> inv.getArgument(0));
JsonNode request = objectMapper.readTree(
"{\"ACLName\":\"app-acl\",\"UserNames\":[\"app-user\"]}");
Response response = handler.handle("CreateACL", request, "us-east-1");
assertEquals(200, response.getStatus());
ArgumentCaptor<Acl> captor = ArgumentCaptor.forClass(Acl.class);
verify(service).createAcl(captor.capture(), eq("us-east-1"));
assertEquals(List.of("app-user"), captor.getValue().getUserNames());
}
@Test
void unknownOperationReturns400() throws Exception {
JsonNode request = objectMapper.readTree("{}");
Response response = handler.handle("Bogus", request, "us-east-1");
assertEquals(400, response.getStatus());
}
}
@@ -21,6 +21,7 @@ import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -38,7 +39,9 @@ class MemoryDbIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String OPEN_CLUSTER = "it-mdb-open";
private static final String AUTH_CLUSTER = "it-mdb-auth";
private static final String AUTH_TOKEN = "it-mdb-token";
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 int SOCKET_TIMEOUT_MS = 10_000;
private static final int READ_LINE_MAX_ATTEMPTS = 3;
@@ -62,6 +65,16 @@ class MemoryDbIntegrationTest {
// best-effort
}
}
try {
memorydb("DeleteACL", "{\"ACLName\":\"" + AUTH_ACL + "\"}");
} catch (Exception ignored) {
// best-effort
}
try {
memorydb("DeleteUser", "{\"UserName\":\"" + AUTH_USER + "\"}");
} catch (Exception ignored) {
// best-effort
}
}
@Test
@@ -109,31 +122,56 @@ class MemoryDbIntegrationTest {
@Test
@Order(4)
void createClusterWithAuthToken() {
void createPasswordUserAndAcl() {
// A password user attached to an ACL is how real MemoryDB models auth — the
// cluster then references that ACL via ACLName.
memorydb("CreateUser", "{"
+ "\"UserName\":\"" + AUTH_USER + "\","
+ "\"AccessString\":\"on ~* +@all\","
+ "\"AuthenticationMode\":{\"Type\":\"password\",\"Passwords\":[\"" + AUTH_PASSWORD + "\"]}}")
.then()
.statusCode(200)
.body("User.Name", equalTo(AUTH_USER))
.body("User.Authentication.Type", equalTo("password"));
// An ACL must include the built-in "default" user (DefaultUserRequired otherwise).
memorydb("CreateACL", "{"
+ "\"ACLName\":\"" + AUTH_ACL + "\","
+ "\"UserNames\":[\"default\",\"" + AUTH_USER + "\"]}")
.then()
.statusCode(200)
.body("ACL.Name", equalTo(AUTH_ACL))
.body("ACL.UserNames", hasItems("default", AUTH_USER));
}
@Test
@Order(5)
void createClusterReferencingAcl() {
authPort = memorydb("CreateCluster", "{"
+ "\"ClusterName\":\"" + AUTH_CLUSTER + "\","
+ "\"AuthToken\":\"" + AUTH_TOKEN + "\"}")
+ "\"ACLName\":\"" + AUTH_ACL + "\"}")
.then()
.statusCode(200)
.body("Cluster.Name", equalTo(AUTH_CLUSTER))
.body("Cluster.Status", equalTo("available"))
.body("Cluster.ACLName", equalTo(AUTH_ACL))
.extract()
.path("Cluster.ClusterEndpoint.Port");
}
@Test
@Order(5)
void passwordClusterRejectsUnauthenticatedCommand() throws Exception {
@Order(6)
void aclClusterRejectsUnauthenticatedCommand() throws Exception {
assertEquals("-NOAUTH Authentication required.\r\n",
sendCommand(authPort, respArray("PING")));
}
@Test
@Order(6)
void authTokenAllowsAccess() throws Exception {
// Exercises end-to-end that CreateCluster propagated AuthToken to the proxy.
@Order(7)
void aclUserCredentialsAllowAccess() throws Exception {
// Exercises end-to-end that the proxy resolves auth through the ACL's user.
try (Socket socket = openSocket(authPort)) {
write(socket, respArray("AUTH", AUTH_TOKEN));
write(socket, respArray("AUTH", AUTH_USER, AUTH_PASSWORD));
assertEquals("+OK\r\n", readLine(socket));
write(socket, respArray("PING"));
@@ -142,14 +180,14 @@ class MemoryDbIntegrationTest {
}
@Test
@Order(7)
@Order(8)
void wrongPasswordRejected() throws Exception {
assertEquals("-ERR invalid username-password pair or user is disabled.\r\n",
sendCommand(authPort, respArray("AUTH", "wrong-token")));
sendCommand(authPort, respArray("AUTH", AUTH_USER, "wrong-password")));
}
@Test
@Order(8)
@Order(9)
void deleteClusterReleasesProxyPortForReuse() {
deleteCluster(OPEN_CLUSTER)
.then()
@@ -157,7 +195,7 @@ class MemoryDbIntegrationTest {
.body("Cluster.Name", equalTo(OPEN_CLUSTER));
int reusedPort = memorydb("CreateCluster",
"{\"ClusterName\":\"" + OPEN_CLUSTER + "-reused\"}")
"{\"ClusterName\":\"" + OPEN_CLUSTER + "-reused\",\"ACLName\":\"open-access\"}")
.then()
.statusCode(200)
.body("Cluster.ClusterEndpoint.Address", equalTo("localhost"))
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.memorydb;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Forward-compatibility guard: a {@code memorydb-clusters.json} snapshot written by an
* older build still carried the now-removed {@code authToken}/{@code authMode} fields.
* {@link PersistentStorage} uses a plain ObjectMapper (which fails on unknown properties
* by default), so without {@code @JsonIgnoreProperties(ignoreUnknown = true)} on
* {@link Cluster} the load would throw and the entire cluster store would start empty.
*/
class MemoryDbPersistenceTest {
@Test
void loadsLegacySnapshotContainingRemovedAuthFields(@TempDir Path dir) throws Exception {
Path file = dir.resolve("memorydb-clusters.json");
Files.writeString(file, """
{
"legacy-cluster": {
"name": "legacy-cluster",
"status": "AVAILABLE",
"nodeType": "db.t4g.small",
"aclName": "open-access",
"authMode": "PASSWORD",
"authToken": "old-plaintext-token",
"arn": "arn:aws:memorydb:us-east-1:000000000000:cluster/legacy-cluster"
}
}
""");
PersistentStorage<String, Cluster> storage =
new PersistentStorage<>(file, new TypeReference<Map<String, Cluster>>() {});
storage.load();
Optional<Cluster> loaded = storage.get("legacy-cluster");
assertTrue(loaded.isPresent(), "legacy cluster must survive the schema change");
assertEquals("legacy-cluster", loaded.get().getName());
assertEquals("open-access", loaded.get().getAclName());
}
}
@@ -5,11 +5,14 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerHandle;
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
import io.github.hectorvent.floci.services.memorydb.model.Acl;
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
import io.github.hectorvent.floci.services.memorydb.model.User;
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -23,6 +26,7 @@ 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.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
@@ -34,12 +38,14 @@ class MemoryDbServiceTest {
private MemoryDbService service;
private MemoryDbContainerManager containerManager;
private SigV4Validator sigV4Validator;
private EmulatorConfig.MemoryDbServiceConfig mdbConfig;
@BeforeEach
void setUp() {
containerManager = mock(MemoryDbContainerManager.class);
MemoryDbProxyManager proxyManager = mock(MemoryDbProxyManager.class);
sigV4Validator = mock(SigV4Validator.class);
StorageFactory storageFactory = mock(StorageFactory.class);
EmulatorConfig config = mock(EmulatorConfig.class);
RegionResolver regionResolver = mock(RegionResolver.class);
@@ -57,9 +63,10 @@ class MemoryDbServiceTest {
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>());
when(containerManager.start(anyString(), anyString()))
.thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
doNothing().when(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any());
service = new MemoryDbService(containerManager, proxyManager, storageFactory, config, regionResolver);
service = new MemoryDbService(containerManager, proxyManager, sigV4Validator,
storageFactory, config, regionResolver);
}
@Test
@@ -67,6 +74,7 @@ class MemoryDbServiceTest {
Cluster spec = new Cluster();
spec.setName("my-cluster");
spec.setNodeType("db.t4g.small");
spec.setAclName("open-access");
Cluster created = service.createCluster(spec, "us-east-1");
assertEquals("my-cluster", created.getName());
@@ -82,10 +90,12 @@ class MemoryDbServiceTest {
void duplicateClusterRejected() {
Cluster spec = new Cluster();
spec.setName("dupe");
spec.setAclName("open-access");
service.createCluster(spec, "us-east-1");
Cluster again = new Cluster();
again.setName("dupe");
again.setAclName("open-access");
assertThrows(AwsException.class, () -> service.createCluster(again, "us-east-1"));
}
@@ -93,6 +103,7 @@ class MemoryDbServiceTest {
void deleteClusterRemovesIt() {
Cluster spec = new Cluster();
spec.setName("temp");
spec.setAclName("open-access");
service.createCluster(spec, "us-east-1");
service.deleteCluster("temp");
@@ -104,6 +115,7 @@ class MemoryDbServiceTest {
void tagAndUntagResource() {
Cluster spec = new Cluster();
spec.setName("tagged");
spec.setAclName("open-access");
Cluster created = service.createCluster(spec, "us-east-1");
String arn = created.getArn();
@@ -115,15 +127,186 @@ class MemoryDbServiceTest {
}
@Test
void passwordValidationUsesAuthToken() {
void openAccessClusterRequiresNoAuth() {
Cluster spec = new Cluster();
spec.setName("secure");
spec.setAuthMode(AuthMode.PASSWORD);
spec.setAuthToken("s3cret");
spec.setName("open");
spec.setAclName("open-access");
service.createCluster(spec, "us-east-1");
assertTrue(service.validatePassword("secure", null, "s3cret"));
assertFalse(service.validatePassword("secure", null, "wrong"));
// open-access maps to the no-auth path: any AUTH attempt is accepted
assertTrue(service.authenticate("open", null, "anything"));
}
@Test
void passwordAuthResolvesThroughAclUser() {
User userSpec = new User();
userSpec.setName("app-user");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("s3cret"));
userSpec.setAccessString("on ~* +@all");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("app-acl");
aclSpec.setUserNames(List.of("default", "app-user"));
service.createAcl(aclSpec, "us-east-1");
Cluster spec = new Cluster();
spec.setName("secure");
spec.setAclName("app-acl");
service.createCluster(spec, "us-east-1");
assertTrue(service.authenticate("secure", "app-user", "s3cret"));
assertFalse(service.authenticate("secure", "app-user", "wrong"));
assertFalse(service.authenticate("secure", "unknown-user", "s3cret"));
}
@Test
void iamAuthDelegatesToSigV4Validator() {
when(sigV4Validator.validate(anyString(), anyString(), anyString())).thenReturn(true);
User userSpec = new User();
userSpec.setName("iam-user");
userSpec.setAuthMode(AuthMode.IAM);
userSpec.setAccessString("on ~* +@all");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("iam-acl");
aclSpec.setUserNames(List.of("default", "iam-user"));
service.createAcl(aclSpec, "us-east-1");
Cluster spec = new Cluster();
spec.setName("iam-cluster");
spec.setAclName("iam-acl");
service.createCluster(spec, "us-east-1");
assertTrue(service.authenticate("iam-cluster", "iam-user", "presigned-token"));
}
@Test
void createClusterWithUnknownAclRejected() {
Cluster spec = new Cluster();
spec.setName("bad");
spec.setAclName("does-not-exist");
assertThrows(AwsException.class, () -> service.createCluster(spec, "us-east-1"));
}
@Test
void passwordUserRequiresPassword() {
User userSpec = new User();
userSpec.setName("no-pass");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setAccessString("on ~* +@all");
assertThrows(AwsException.class, () -> service.createUser(userSpec, "us-east-1"));
}
@Test
void createClusterRequiresAclName() {
Cluster spec = new Cluster();
spec.setName("no-acl");
AwsException ex = assertThrows(AwsException.class, () -> service.createCluster(spec, "us-east-1"));
assertEquals(400, ex.getHttpStatus());
}
@Test
void createUserRequiresAccessString() {
User userSpec = new User();
userSpec.setName("no-access");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("p"));
assertThrows(AwsException.class, () -> service.createUser(userSpec, "us-east-1"));
}
@Test
void createUserRejectsNoPasswordType() {
// "no-password" is a valid wire enum value but is output-only: AWS rejects it on
// CreateUser ("all newly-created users require a password" / IAM).
User userSpec = new User();
userSpec.setName("npr");
userSpec.setAuthMode(AuthMode.NO_PASSWORD);
userSpec.setAccessString("on ~* +@all");
AwsException ex = assertThrows(AwsException.class, () -> service.createUser(userSpec, "us-east-1"));
assertEquals("InvalidParameterValueException", ex.jsonType());
}
@Test
void createUserRejectsInvalidUserName() {
User userSpec = new User();
userSpec.setName("1-bad-start"); // must start with a letter
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("p"));
userSpec.setAccessString("on ~* +@all");
AwsException ex = assertThrows(AwsException.class, () -> service.createUser(userSpec, "us-east-1"));
assertEquals("InvalidParameterValueException", ex.jsonType());
}
@Test
void createAclRequiresDefaultUser() {
User userSpec = new User();
userSpec.setName("solo");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("p"));
userSpec.setAccessString("on ~* +@all");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("no-default-acl");
aclSpec.setUserNames(List.of("solo")); // missing the required "default" user
AwsException ex = assertThrows(AwsException.class, () -> service.createAcl(aclSpec, "us-east-1"));
assertEquals("DefaultUserRequired", ex.jsonType());
}
@Test
void createAclRejectsDuplicateUserNames() {
User userSpec = new User();
userSpec.setName("dup");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("p"));
userSpec.setAccessString("on ~* +@all");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("dup-acl");
aclSpec.setUserNames(List.of("default", "dup", "dup"));
AwsException ex = assertThrows(AwsException.class, () -> service.createAcl(aclSpec, "us-east-1"));
assertEquals("DuplicateUserNameFault", ex.jsonType());
}
@Test
void describeIncludesBuiltinDefaults() {
assertTrue(service.describeUsers(null, "us-east-1").stream()
.anyMatch(u -> "default".equals(u.getName())));
assertTrue(service.describeAcls(null, "us-east-1").stream()
.anyMatch(a -> "open-access".equals(a.getName())));
}
@Test
void builtinDefaultsCannotBeDeleted() {
assertThrows(AwsException.class, () -> service.deleteUser("default"));
assertThrows(AwsException.class, () -> service.deleteAcl("open-access"));
}
@Test
void aclInUseCannotBeDeleted() {
User userSpec = new User();
userSpec.setName("u1");
userSpec.setAuthMode(AuthMode.PASSWORD);
userSpec.setPasswords(List.of("p"));
userSpec.setAccessString("on ~* +@all");
service.createUser(userSpec, "us-east-1");
Acl aclSpec = new Acl();
aclSpec.setName("in-use");
aclSpec.setUserNames(List.of("default", "u1"));
service.createAcl(aclSpec, "us-east-1");
Cluster spec = new Cluster();
spec.setName("c");
spec.setAclName("in-use");
service.createCluster(spec, "us-east-1");
assertThrows(AwsException.class, () -> service.deleteAcl("in-use"));
}
@Test
@@ -144,11 +327,13 @@ class MemoryDbServiceTest {
Cluster first = new Cluster();
first.setName("c1");
first.setAclName("open-access");
assertThrows(RuntimeException.class, () -> service.createCluster(first, "us-east-1"));
// The single port must have been released, so a second create still succeeds
Cluster second = new Cluster();
second.setName("c2");
second.setAclName("open-access");
Cluster created = service.createCluster(second, "us-east-1");
assertEquals(ClusterStatus.AVAILABLE, created.getStatus());
}
@@ -159,6 +344,7 @@ class MemoryDbServiceTest {
Cluster spec = new Cluster();
spec.setName("mock-cluster");
spec.setAclName("open-access");
Cluster created = service.createCluster(spec, "us-east-1");
assertEquals(ClusterStatus.AVAILABLE, created.getStatus());