Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Ahmed khaleda8fde26d065f
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java
index 2dc859395e..613c884835 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandler.java
@@ -7,8 +7,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJson11Controller;
+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.User;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -44,6 +46,12 @@ public class MemoryDbHandler {
case "DescribeClusters" -> handleDescribeClusters(request);
case "UpdateCluster" -> handleUpdateCluster(request);
case "DeleteCluster" -> handleDeleteCluster(request);
+ case "CreateUser" -> handleCreateUser(request, region);
+ case "DescribeUsers" -> handleDescribeUsers(request, region);
+ case "DeleteUser" -> handleDeleteUser(request);
+ case "CreateACL" -> handleCreateAcl(request, region);
+ case "DescribeACLs" -> handleDescribeAcls(request, region);
+ case "DeleteACL" -> handleDeleteAcl(request);
case "ListTags" -> handleListTags(request);
case "TagResource" -> handleTagResource(request);
case "UntagResource" -> handleUntagResource(request);
@@ -76,8 +84,6 @@ public class MemoryDbHandler {
spec.setEngineVersion(text(request, "EngineVersion"));
spec.setAclName(text(request, "ACLName"));
spec.setTlsEnabled(request.path("TLSEnabled").asBoolean(false));
- spec.setAuthToken(text(request, "AuthToken"));
- spec.setAuthMode(resolveAuthMode(request));
spec.setTags(parseTags(request.path("Tags")));
Cluster created = service.createCluster(spec, region);
ObjectNode response = objectMapper.createObjectNode();
@@ -108,6 +114,61 @@ public class MemoryDbHandler {
return Response.ok(response).build();
}
+ private Response handleCreateUser(JsonNode request, String region) {
+ User spec = new User();
+ spec.setName(text(request, "UserName"));
+ spec.setAccessString(text(request, "AccessString"));
+ JsonNode authNode = request.path("AuthenticationMode");
+ spec.setAuthMode(parseAuthMode(authNode));
+ spec.setPasswords(parsePasswords(authNode.path("Passwords")));
+ User created = service.createUser(spec, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("User", userNode(created));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeUsers(JsonNode request, String region) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Users");
+ for (User user : service.describeUsers(text(request, "UserName"), region)) {
+ arr.add(userNode(user));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteUser(JsonNode request) {
+ User deleted = service.deleteUser(text(request, "UserName"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("User", userNode(deleted));
+ return Response.ok(response).build();
+ }
+
+ private Response handleCreateAcl(JsonNode request, String region) {
+ Acl spec = new Acl();
+ spec.setName(text(request, "ACLName"));
+ spec.setUserNames(parseStringList(request.path("UserNames")));
+ Acl created = service.createAcl(spec, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("ACL", aclNode(created));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeAcls(JsonNode request, String region) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("ACLs");
+ for (Acl acl : service.describeAcls(text(request, "ACLName"), region)) {
+ arr.add(aclNode(acl));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteAcl(JsonNode request) {
+ Acl deleted = service.deleteAcl(text(request, "ACLName"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("ACL", aclNode(deleted));
+ return Response.ok(response).build();
+ }
+
private Response handleListTags(JsonNode request) {
Map<String, String> tags = service.listTags(text(request, "ResourceArn"));
return Response.ok(tagListResponse(tags)).build();
@@ -150,6 +211,46 @@ public class MemoryDbHandler {
return node;
}
+ private ObjectNode userNode(User user) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Name", user.getName());
+ node.put("Status", user.getStatus());
+ if (user.getAccessString() != null) {
+ node.put("AccessString", user.getAccessString());
+ }
+ if (user.getMinimumEngineVersion() != null) {
+ node.put("MinimumEngineVersion", user.getMinimumEngineVersion());
+ }
+ ObjectNode authentication = node.putObject("Authentication");
+ authentication.put("Type", user.getAuthMode().wireValue());
+ if (user.getAuthMode() == AuthMode.PASSWORD) {
+ authentication.put("PasswordCount", user.getPasswords() != null ? user.getPasswords().size() : 0);
+ }
+ ArrayNode aclNames = node.putArray("ACLNames");
+ service.aclNamesForUser(user.getName()).forEach(aclNames::add);
+ if (user.getArn() != null) {
+ node.put("ARN", user.getArn());
+ }
+ return node;
+ }
+
+ private ObjectNode aclNode(Acl acl) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Name", acl.getName());
+ node.put("Status", acl.getStatus());
+ ArrayNode userNames = node.putArray("UserNames");
+ acl.getUserNames().forEach(userNames::add);
+ if (acl.getMinimumEngineVersion() != null) {
+ node.put("MinimumEngineVersion", acl.getMinimumEngineVersion());
+ }
+ ArrayNode clustersArr = node.putArray("Clusters");
+ service.clustersUsingAcl(acl.getName()).forEach(clustersArr::add);
+ if (acl.getArn() != null) {
+ node.put("ARN", acl.getArn());
+ }
+ return node;
+ }
+
private ObjectNode tagListResponse(Map<String, String> tags) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("TagList");
@@ -164,11 +265,33 @@ public class MemoryDbHandler {
// ──────────────────────────── Parsing ────────────────────────────
- private AuthMode resolveAuthMode(JsonNode request) {
- if (request.hasNonNull("AuthToken") && !request.get("AuthToken").asText().isBlank()) {
- return AuthMode.PASSWORD;
+ private AuthMode parseAuthMode(JsonNode authNode) {
+ String type = authNode.path("Type").asText(null);
+ if (type == null || type.isBlank()) {
+ return null;
+ }
+ try {
+ return AuthMode.fromWire(type);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterValueException", e.getMessage(), 400);
+ }
+ }
+
+ private List<String> parsePasswords(JsonNode passwordsNode) {
+ return parseStringList(passwordsNode);
+ }
+
+ private List<String> parseStringList(JsonNode node) {
+ List<String> values = new java.util.ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(n -> {
+ String value = n.asText(null);
+ if (value != null) {
+ values.add(value);
+ }
+ });
}
- return AuthMode.NO_AUTH;
+ return values;
}
private Map<String, String> parseTags(JsonNode tagsNode) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
index f3b887e3bd..23628d4ca5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
@@ -6,18 +6,22 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
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.Endpoint;
+import io.github.hectorvent.floci.services.memorydb.model.User;
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -25,20 +29,39 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
- * Core MemoryDB business logic — clusters and tags.
- * Creates a real Redis-compatible container plus an auth proxy on cluster creation.
+ * Core MemoryDB business logic — clusters, ACLs and users.
+ *
+ * <p>Authentication follows the real MemoryDB model: a {@link User} is created with a
+ * password or IAM auth mode, attached to an {@link Acl}, and a cluster references that
+ * ACL via {@code ACLName}. A cluster therefore has no auth mode of its own — its
+ * effective authentication is resolved from the users of the ACL it references.
+ *
+ * <p>The built-in {@code open-access} ACL and {@code default} user (which AWS provides
+ * out of the box and which cannot be created or deleted) are synthesized rather than
+ * stored, so they always exist for every account and map to the no-auth path.
*/
@ApplicationScoped
public class MemoryDbService {
private static final Logger LOG = Logger.getLogger(MemoryDbService.class);
private static final String DEFAULT_ENGINE = "redis";
+ private static final String DEFAULT_ENGINE_VERSION = "7.1";
private static final String DEFAULT_ACL = "open-access";
+ private static final String DEFAULT_USER = "default";
+ private static final String ACTIVE = "active";
private static final int REDIS_PORT = 6379;
+ // Per the MemoryDB API: a user name must start with a letter and contain only
+ // letters, digits and hyphens.
+ private static final java.util.regex.Pattern USER_NAME_PATTERN =
+ java.util.regex.Pattern.compile("[a-zA-Z][a-zA-Z0-9\\-]*");
+
private final StorageBackend<String, Cluster> clusters;
+ private final StorageBackend<String, User> users;
+ private final StorageBackend<String, Acl> acls;
private final MemoryDbContainerManager containerManager;
private final MemoryDbProxyManager proxyManager;
+ private final SigV4Validator sigV4Validator;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
@@ -46,17 +69,25 @@ public class MemoryDbService {
@Inject
public MemoryDbService(MemoryDbContainerManager containerManager,
MemoryDbProxyManager proxyManager,
+ SigV4Validator sigV4Validator,
StorageFactory storageFactory,
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
+ this.sigV4Validator = sigV4Validator;
this.config = config;
this.regionResolver = regionResolver;
this.clusters = storageFactory.create("memorydb", "memorydb-clusters.json",
new TypeReference<Map<String, Cluster>>() {});
+ this.users = storageFactory.create("memorydb", "memorydb-users.json",
+ new TypeReference<Map<String, User>>() {});
+ this.acls = storageFactory.create("memorydb", "memorydb-acls.json",
+ new TypeReference<Map<String, Acl>>() {});
}
+ // ──────────────────────────── Clusters ────────────────────────────
+
public Cluster createCluster(Cluster spec, String region) {
String name = spec.getName();
if (name == null || name.isBlank()) {
@@ -67,7 +98,12 @@ public class MemoryDbService {
"Cluster with specified name already exists.", 400);
}
- AuthMode authMode = spec.getAuthMode() != null ? spec.getAuthMode() : AuthMode.NO_AUTH;
+ String aclName = spec.getAclName();
+ if (aclName == null || aclName.isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "ACLName is required.", 400);
+ }
+ requireAclExists(aclName);
+ boolean authRequired = isAuthRequired(aclName);
Cluster cluster = new Cluster();
cluster.setName(name);
@@ -76,25 +112,23 @@ public class MemoryDbService {
cluster.setNodeType(spec.getNodeType() != null ? spec.getNodeType() : "db.t4g.small");
cluster.setNumberOfShards(spec.getNumberOfShards() > 0 ? spec.getNumberOfShards() : 1);
cluster.setEngine(spec.getEngine() != null ? spec.getEngine() : DEFAULT_ENGINE);
- cluster.setEngineVersion(spec.getEngineVersion() != null ? spec.getEngineVersion() : "7.1");
- cluster.setAclName(spec.getAclName() != null ? spec.getAclName() : DEFAULT_ACL);
+ cluster.setEngineVersion(spec.getEngineVersion() != null ? spec.getEngineVersion() : DEFAULT_ENGINE_VERSION);
+ cluster.setAclName(aclName);
cluster.setTlsEnabled(spec.isTlsEnabled());
- cluster.setAuthMode(authMode);
- cluster.setArn(buildArn(region, name));
+ cluster.setArn(buildArn(region, "cluster", name));
cluster.setCreatedAt(Instant.now());
- cluster.setAuthToken(spec.getAuthToken());
cluster.setTags(spec.getTags());
if (config.services().memorydb().mock()) {
LOG.infov("Creating MemoryDB cluster {0} in mock mode (no container)", name);
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), REDIS_PORT));
} else {
- startBackend(cluster, authMode);
+ startBackend(cluster, authRequired);
}
clusters.put(name, cluster);
- LOG.infov("MemoryDB cluster {0} created, endpoint={1}:{2}",
- name, cluster.getClusterEndpoint().address(),
+ LOG.infov("MemoryDB cluster {0} created (acl={1}, authRequired={2}), endpoint={3}:{4}",
+ name, aclName, String.valueOf(authRequired), cluster.getClusterEndpoint().address(),
String.valueOf(cluster.getClusterEndpoint().port()));
return cluster;
}
@@ -143,6 +177,176 @@ public class MemoryDbService {
return cluster;
}
+ // ──────────────────────────── Users ────────────────────────────
+
+ public User createUser(User spec, String region) {
+ String name = spec.getName();
+ if (name == null || name.isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "UserName is required.", 400);
+ }
+ if (!USER_NAME_PATTERN.matcher(name).matches()) {
+ throw new AwsException("InvalidParameterValueException",
+ "UserName must start with a letter and contain only letters, digits and hyphens.", 400);
+ }
+ if (DEFAULT_USER.equals(name) || users.get(name).isPresent()) {
+ throw new AwsException("UserAlreadyExistsFault",
+ "User with specified name already exists.", 400);
+ }
+ if (spec.getAuthMode() == null) {
+ throw new AwsException("InvalidParameterValueException",
+ "AuthenticationMode is required.", 400);
+ }
+ // AuthenticationMode.Type accepts "no-password" in the wire enum, but the service
+ // rejects it on create: per the API, all newly-created users must authenticate with
+ // a password or IAM. "no-password" is only ever the built-in default user.
+ if (spec.getAuthMode() == AuthMode.NO_PASSWORD) {
+ throw new AwsException("InvalidParameterValueException",
+ "AuthenticationMode Type must be 'password' or 'iam' for a new user.", 400);
+ }
+ if (spec.getAuthMode() == AuthMode.PASSWORD
+ && (spec.getPasswords() == null || spec.getPasswords().isEmpty())) {
+ throw new AwsException("InvalidParameterValueException",
+ "At least one password is required for password authentication.", 400);
+ }
+ if (spec.getAccessString() == null || spec.getAccessString().isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "AccessString is required.", 400);
+ }
+
+ User user = new User();
+ user.setName(name);
+ user.setStatus(ACTIVE);
+ user.setAuthMode(spec.getAuthMode());
+ user.setPasswords(spec.getPasswords());
+ user.setAccessString(spec.getAccessString());
+ user.setMinimumEngineVersion(DEFAULT_ENGINE_VERSION);
+ user.setArn(buildArn(region, "user", name));
+ user.setCreatedAt(Instant.now());
+
+ users.put(name, user);
+ LOG.infov("MemoryDB user {0} created with authMode={1}", name, user.getAuthMode());
+ return user;
+ }
+
+ public Collection<User> describeUsers(String filterName, String region) {
+ if (filterName != null && !filterName.isBlank()) {
+ return users.get(filterName)
+ .map(List::of)
+ .or(() -> DEFAULT_USER.equals(filterName)
+ ? java.util.Optional.of(List.of(builtinDefaultUser(region)))
+ : java.util.Optional.empty())
+ .orElseThrow(() -> new AwsException("UserNotFoundFault", "User not found.", 404));
+ }
+ List<User> all = new ArrayList<>();
+ all.add(builtinDefaultUser(region));
+ all.addAll(users.scan(k -> true));
+ return all;
+ }
+
+ public User deleteUser(String name) {
+ if (DEFAULT_USER.equals(name)) {
+ throw new AwsException("InvalidParameterValueException",
+ "The default user cannot be deleted.", 400);
+ }
+ User user = users.get(name).orElseThrow(() ->
+ new AwsException("UserNotFoundFault", "User not found.", 404));
+ users.delete(name);
+ LOG.infov("MemoryDB user {0} deleted", name);
+ return user;
+ }
+
+ // ──────────────────────────── ACLs ────────────────────────────
+
+ public Acl createAcl(Acl spec, String region) {
+ String name = spec.getName();
+ if (name == null || name.isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "ACLName is required.", 400);
+ }
+ if (DEFAULT_ACL.equals(name) || acls.get(name).isPresent()) {
+ throw new AwsException("ACLAlreadyExistsFault",
+ "ACL with specified name already exists.", 400);
+ }
+ if (!spec.getUserNames().contains(DEFAULT_USER)) {
+ throw new AwsException("DefaultUserRequired",
+ "A default user is required and must be specified.", 400);
+ }
+ java.util.Set<String> seen = new java.util.HashSet<>();
+ for (String userName : spec.getUserNames()) {
+ if (!seen.add(userName)) {
+ throw new AwsException("DuplicateUserNameFault",
+ "Duplicate user name " + userName + " in ACL.", 400);
+ }
+ if (!userExists(userName)) {
+ throw new AwsException("UserNotFoundFault", "User " + userName + " not found.", 404);
+ }
+ }
+
+ Acl acl = new Acl();
+ acl.setName(name);
+ acl.setStatus(ACTIVE);
+ acl.setUserNames(new ArrayList<>(spec.getUserNames()));
+ acl.setMinimumEngineVersion(DEFAULT_ENGINE_VERSION);
+ acl.setArn(buildArn(region, "acl", name));
+ acl.setCreatedAt(Instant.now());
+
+ acls.put(name, acl);
+ LOG.infov("MemoryDB ACL {0} created with users={1}", name, acl.getUserNames());
+ return acl;
+ }
+
+ public Collection<Acl> describeAcls(String filterName, String region) {
+ if (filterName != null && !filterName.isBlank()) {
+ return acls.get(filterName)
+ .map(List::of)
+ .or(() -> DEFAULT_ACL.equals(filterName)
+ ? java.util.Optional.of(List.of(builtinOpenAccessAcl(region)))
+ : java.util.Optional.empty())
+ .orElseThrow(() -> new AwsException("ACLNotFoundFault", "ACL not found.", 404));
+ }
+ List<Acl> all = new ArrayList<>();
+ all.add(builtinOpenAccessAcl(region));
+ all.addAll(acls.scan(k -> true));
+ return all;
+ }
+
+ public Acl deleteAcl(String name) {
+ if (DEFAULT_ACL.equals(name)) {
+ throw new AwsException("InvalidParameterValueException",
+ "The open-access ACL cannot be deleted.", 400);
+ }
+ Acl acl = acls.get(name).orElseThrow(() ->
+ new AwsException("ACLNotFoundFault", "ACL not found.", 404));
+ if (!clustersUsingAcl(name).isEmpty()) {
+ throw new AwsException("InvalidACLStateFault",
+ "ACL " + name + " is associated with one or more clusters.", 400);
+ }
+ acls.delete(name);
+ LOG.infov("MemoryDB ACL {0} deleted", name);
+ return acl;
+ }
+
+ /** Names of ACLs that include the given user; used to populate the user response. */
+ public List<String> aclNamesForUser(String userName) {
+ List<String> result = new ArrayList<>();
+ if (DEFAULT_USER.equals(userName)) {
+ result.add(DEFAULT_ACL);
+ }
+ acls.scan(k -> true).stream()
+ .filter(a -> a.getUserNames().contains(userName))
+ .map(Acl::getName)
+ .forEach(result::add);
+ return result;
+ }
+
+ /** Names of clusters currently referencing the given ACL; used to populate the ACL response. */
+ public List<String> clustersUsingAcl(String aclName) {
+ return clusters.scan(k -> true).stream()
+ .filter(c -> aclName.equals(c.getAclName()))
+ .map(Cluster::getName)
+ .toList();
+ }
+
+ // ──────────────────────────── Tags ────────────────────────────
+
public Map<String, String> listTags(String resourceArn) {
return clusterByArn(resourceArn).getTags();
}
@@ -161,17 +365,99 @@ public class MemoryDbService {
return cluster.getTags();
}
+ // ──────────────────────────── Authentication ────────────────────────────
+
/**
- * Validates a Redis AUTH password for the given cluster against its stored auth token.
+ * Validates a Redis AUTH attempt against the ACL the cluster references. A blank
+ * username corresponds to the single-argument {@code AUTH <secret>} form and targets
+ * the {@code default} user. The user's own auth mode decides how the secret is
+ * checked: a password is compared against the user's passwords, an IAM token is
+ * verified as a SigV4 presigned URL.
*/
- public boolean validatePassword(String clusterName, String username, String password) {
+ public boolean authenticate(String clusterName, String username, String secret) {
Cluster cluster = clusters.get(clusterName).orElse(null);
- if (cluster == null || cluster.getAuthToken() == null) {
+ if (cluster == null) {
+ return false;
+ }
+ String aclName = cluster.getAclName();
+ if (DEFAULT_ACL.equals(aclName)) {
+ return true;
+ }
+ Acl acl = acls.get(aclName).orElse(null);
+ if (acl == null) {
+ return false;
+ }
+ String target = (username == null || username.isEmpty()) ? DEFAULT_USER : username;
+ if (!acl.getUserNames().contains(target)) {
+ return false;
+ }
+ User user = resolveUser(target);
+ if (user == null) {
return false;
}
- return cluster.getAuthToken().equals(password);
+ return switch (user.getAuthMode()) {
+ case IAM -> sigV4Validator.validate(secret, clusterName, user.getName());
+ case PASSWORD -> user.getPasswords() != null && user.getPasswords().contains(secret);
+ case NO_PASSWORD -> true;
+ };
}
+ /** True if the ACL has at least one user that requires a credential (password or IAM). */
+ private boolean isAuthRequired(String aclName) {
+ if (DEFAULT_ACL.equals(aclName)) {
+ return false;
+ }
+ Acl acl = acls.get(aclName).orElse(null);
+ if (acl == null) {
+ return false;
+ }
+ return acl.getUserNames().stream()
+ .map(this::resolveUser)
+ .filter(java.util.Objects::nonNull)
+ .anyMatch(u -> u.getAuthMode() != AuthMode.NO_PASSWORD);
+ }
+
+ private void requireAclExists(String aclName) {
+ if (!DEFAULT_ACL.equals(aclName) && acls.get(aclName).isEmpty()) {
+ throw new AwsException("ACLNotFoundFault", "ACL " + aclName + " not found.", 404);
+ }
+ }
+
+ private boolean userExists(String name) {
+ return DEFAULT_USER.equals(name) || users.get(name).isPresent();
+ }
+
+ private User resolveUser(String name) {
+ return users.get(name).orElseGet(() -> DEFAULT_USER.equals(name) ? builtinDefaultUser(null) : null);
+ }
+
+ private User builtinDefaultUser(String region) {
+ User user = new User();
+ user.setName(DEFAULT_USER);
+ user.setStatus(ACTIVE);
+ user.setAuthMode(AuthMode.NO_PASSWORD);
+ user.setAccessString("on ~* &* +@all");
+ user.setMinimumEngineVersion(DEFAULT_ENGINE_VERSION);
+ if (region != null) {
+ user.setArn(buildArn(region, "user", DEFAULT_USER));
+ }
+ return user;
+ }
+
+ private Acl builtinOpenAccessAcl(String region) {
+ Acl acl = new Acl();
+ acl.setName(DEFAULT_ACL);
+ acl.setStatus(ACTIVE);
+ acl.setUserNames(new ArrayList<>(List.of(DEFAULT_USER)));
+ acl.setMinimumEngineVersion(DEFAULT_ENGINE_VERSION);
+ if (region != null) {
+ acl.setArn(buildArn(region, "acl", DEFAULT_ACL));
+ }
+ return acl;
+ }
+
+ // ──────────────────────────── Internals ────────────────────────────
+
private Cluster clusterByArn(String resourceArn) {
if (resourceArn == null) {
throw new AwsException("InvalidParameterValueException", "ResourceArn is required.", 400);
@@ -182,12 +468,12 @@ public class MemoryDbService {
.orElseThrow(() -> new AwsException("ClusterNotFoundFault", "Cluster not found.", 404));
}
- private void startBackend(Cluster cluster, AuthMode authMode) {
+ private void startBackend(Cluster cluster, boolean authRequired) {
String name = cluster.getName();
int proxyPort = allocateProxyPort();
String image = config.services().memorydb().defaultImage();
- LOG.infov("Creating MemoryDB cluster {0} with authMode={1} on proxy port {2}",
- name, authMode, String.valueOf(proxyPort));
+ LOG.infov("Creating MemoryDB cluster {0} with authRequired={1} on proxy port {2}",
+ name, String.valueOf(authRequired), String.valueOf(proxyPort));
MemoryDbContainerHandle handle = null;
try {
@@ -198,9 +484,9 @@ public class MemoryDbService {
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
- proxyManager.startProxy(name, authMode, proxyPort,
+ proxyManager.startProxy(name, authRequired, proxyPort,
handle.getHost(), handle.getPort(),
- (username, password) -> validatePassword(name, username, password));
+ (username, secret) -> authenticate(name, username, secret));
} catch (RuntimeException e) {
LOG.warnv("MemoryDB cluster {0} provisioning failed, rolling back: {1}", name, e.getMessage());
rollbackBackend(name, handle, proxyPort);
@@ -221,8 +507,9 @@ public class MemoryDbService {
}
}
- private String buildArn(String region, String name) {
- return "arn:aws:memorydb:" + region + ":" + regionResolver.getAccountId() + ":cluster/" + name;
+ private String buildArn(String region, String resourceType, String name) {
+ return "arn:aws:memorydb:" + region + ":" + regionResolver.getAccountId()
+ + ":" + resourceType + "/" + name;
}
private String resolveEndpointHost() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Acl.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Acl.java
new file mode 100644
index 0000000000..f419c8c531
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Acl.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.memorydb.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A MemoryDB Access Control List (ACL): a named collection of {@link User}s that a
+ * cluster references via {@code ACLName} to determine who may authenticate.
+ *
+ * <p>The list of clusters using an ACL is derived from the cluster store at read time
+ * rather than stored here, so it never drifts out of sync.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Acl {
+
+ private String name;
+ private String status;
+ private List<String> userNames = new ArrayList<>();
+ private String minimumEngineVersion;
+ private String arn;
+ private Instant createdAt;
+
+ public Acl() {}
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public List<String> getUserNames() { return userNames; }
+ public void setUserNames(List<String> userNames) {
+ this.userNames = userNames != null ? userNames : new ArrayList<>();
+ }
+
+ public String getMinimumEngineVersion() { return minimumEngineVersion; }
+ public void setMinimumEngineVersion(String minimumEngineVersion) {
+ this.minimumEngineVersion = minimumEngineVersion;
+ }
+
+ public String getArn() { return arn; }
+ public void setArn(String arn) { this.arn = arn; }
+
+ public Instant getCreatedAt() { return createdAt; }
+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java
index adef1d68b6..1d8e47e0c3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/AuthMode.java
@@ -1,5 +1,42 @@
package io.github.hectorvent.floci.services.memorydb.model;
+/**
+ * Authentication type of a MemoryDB {@link User}. Mirrors the {@code Type} field of the
+ * real API's {@code AuthenticationMode}/{@code Authentication} structures, whose wire
+ * values are lowercase (e.g. {@code password}).
+ *
+ * <p>A cluster does not carry an auth mode of its own — it references an ACL, and the
+ * effective authentication is determined by the auth modes of the users in that ACL.
+ */
public enum AuthMode {
- IAM, PASSWORD, NO_AUTH
+ PASSWORD("password"),
+ IAM("iam"),
+ NO_PASSWORD("no-password");
+
+ private final String wireValue;
+
+ AuthMode(String wireValue) {
+ this.wireValue = wireValue;
+ }
+
+ public String wireValue() {
+ return wireValue;
+ }
+
+ /**
+ * Parse the wire value from an {@code AuthenticationMode.Type} request field.
+ * Per the API, the valid input/output types are {@code password}, {@code iam} and
+ * {@code no-password}.
+ */
+ public static AuthMode fromWire(String value) {
+ if (value == null) {
+ return null;
+ }
+ for (AuthMode mode : values()) {
+ if (mode.wireValue.equalsIgnoreCase(value)) {
+ return mode;
+ }
+ }
+ throw new IllegalArgumentException("Unknown authentication type: " + value);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java
index e2cfcab725..04326b0105 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/Cluster.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.memorydb.model;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -7,6 +8,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Cluster {
private String name;
@@ -18,12 +20,10 @@ public class Cluster {
private String engineVersion;
private String aclName;
private boolean tlsEnabled;
- private AuthMode authMode;
private Endpoint clusterEndpoint;
private String arn;
private Instant createdAt;
private int proxyPort;
- private String authToken; // stored plain-text for PASSWORD auth validation in the proxy
private Map<String, String> tags = new LinkedHashMap<>();
// Transient fields — not persisted, restored on container restart
@@ -60,9 +60,6 @@ public class Cluster {
public boolean isTlsEnabled() { return tlsEnabled; }
public void setTlsEnabled(boolean tlsEnabled) { this.tlsEnabled = tlsEnabled; }
- public AuthMode getAuthMode() { return authMode; }
- public void setAuthMode(AuthMode authMode) { this.authMode = authMode; }
-
public Endpoint getClusterEndpoint() { return clusterEndpoint; }
public void setClusterEndpoint(Endpoint clusterEndpoint) { this.clusterEndpoint = clusterEndpoint; }
@@ -75,9 +72,6 @@ public class Cluster {
public int getProxyPort() { return proxyPort; }
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
- public String getAuthToken() { return authToken; }
- public void setAuthToken(String authToken) { this.authToken = authToken; }
-
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? tags : new LinkedHashMap<>();
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/model/User.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/User.java
new file mode 100644
index 0000000000..cca69606f6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/model/User.java
@@ -0,0 +1,57 @@
+package io.github.hectorvent.floci.services.memorydb.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A MemoryDB user. Users authenticate either with one or more passwords or with IAM,
+ * and are attached to one or more {@link Acl}s. A cluster's effective authentication is
+ * resolved from the users of the ACL it references.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class User {
+
+ private String name;
+ private String status;
+ private AuthMode authMode;
+ private List<String> passwords = new ArrayList<>();
+ private String accessString;
+ private String minimumEngineVersion;
+ private String arn;
+ private Instant createdAt;
+
+ public User() {}
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public AuthMode getAuthMode() { return authMode; }
+ public void setAuthMode(AuthMode authMode) { this.authMode = authMode; }
+
+ public List<String> getPasswords() { return passwords; }
+ public void setPasswords(List<String> passwords) {
+ this.passwords = passwords != null ? passwords : new ArrayList<>();
+ }
+
+ public String getAccessString() { return accessString; }
+ public void setAccessString(String accessString) { this.accessString = accessString; }
+
+ public String getMinimumEngineVersion() { return minimumEngineVersion; }
+ public void setMinimumEngineVersion(String minimumEngineVersion) {
+ this.minimumEngineVersion = minimumEngineVersion;
+ }
+
+ public String getArn() { return arn; }
+ public void setArn(String arn) { this.arn = arn; }
+
+ public Instant getCreatedAt() { return createdAt; }
+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java
index 5b20337ac2..6848aa1e54 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbAuthProxy.java
@@ -1,8 +1,6 @@
package io.github.hectorvent.floci.services.memorydb.proxy;
import io.github.hectorvent.floci.services.elasticache.proxy.RespReader;
-import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
-import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -14,12 +12,19 @@ import java.nio.charset.StandardCharsets;
/**
* TCP auth proxy for a single MemoryDB cluster.
- * Intercepts the Redis AUTH command, validates credentials (IAM or password),
- * then becomes a transparent byte relay to the backend Redis container.
+ * Intercepts the Redis AUTH command and delegates credential validation to an
+ * {@link AuthValidator}, which resolves the supplied user against the cluster's ACL
+ * (password or IAM). It then becomes a transparent byte relay to the backend Redis
+ * container.
+ *
+ * <p>Whether authentication is required at all is decided up front from the cluster's
+ * ACL: a cluster bound to {@code open-access} (or any ACL whose users require no
+ * password) is created with {@code authRequired = false}, in which case the proxy is a
+ * straight relay.
*
* <p>MemoryDB speaks the Redis wire protocol, so this reuses ElastiCache's
- * {@link RespReader} and {@link SigV4Validator}. A future refactor should lift
- * the shared Redis-auth pieces into a common package.
+ * {@link RespReader}. A future refactor should lift the shared Redis-auth pieces into a
+ * common package.
*/
public class MemoryDbAuthProxy {
@@ -36,25 +41,22 @@ public class MemoryDbAuthProxy {
.getBytes(StandardCharsets.UTF_8);
private final String clusterName;
- private final AuthMode authMode;
+ private final boolean authRequired;
private final String backendHost;
private final int backendPort;
- private final PasswordValidator passwordValidator;
- private final SigV4Validator sigV4Validator;
+ private final AuthValidator authValidator;
private volatile boolean running;
private ServerSocket serverSocket;
- public MemoryDbAuthProxy(String clusterName, AuthMode authMode,
+ public MemoryDbAuthProxy(String clusterName, boolean authRequired,
String backendHost, int backendPort,
- PasswordValidator passwordValidator,
- SigV4Validator sigV4Validator) {
+ AuthValidator authValidator) {
this.clusterName = clusterName;
- this.authMode = authMode;
+ this.authRequired = authRequired;
this.backendHost = backendHost;
this.backendPort = backendPort;
- this.passwordValidator = passwordValidator;
- this.sigV4Validator = sigV4Validator;
+ this.authValidator = authValidator;
}
public void start(int proxyPort) throws IOException {
@@ -102,7 +104,7 @@ public class MemoryDbAuthProxy {
if (cmd[0].equalsIgnoreCase("AUTH")) {
handleAuth(client, cmd);
- } else if (authMode != AuthMode.NO_AUTH) {
+ } else if (authRequired) {
client.getOutputStream().write(NOAUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
@@ -152,11 +154,10 @@ public class MemoryDbAuthProxy {
}
private boolean validate(String username, String password) {
- return switch (authMode) {
- case IAM -> sigV4Validator.validate(password, clusterName, username);
- case PASSWORD -> passwordValidator.validatePassword(username, password);
- case NO_AUTH -> true;
- };
+ if (!authRequired) {
+ return true;
+ }
+ return authValidator.authenticate(username, password);
}
private void bridge(Socket client, Socket backend) {
@@ -212,10 +213,13 @@ public class MemoryDbAuthProxy {
}
/**
- * Callback interface for password validation, provided by MemoryDbService.
+ * Callback interface for credential validation, provided by MemoryDbService.
+ * Resolves the supplied {@code username}/{@code secret} against the cluster's ACL,
+ * handling both password and IAM users. A {@code null} username corresponds to the
+ * single-argument {@code AUTH <password>} form (the {@code default} user).
*/
@FunctionalInterface
- public interface PasswordValidator {
- boolean validatePassword(String username, String password);
+ public interface AuthValidator {
+ boolean authenticate(String username, String secret);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java
index d4522ca821..e81d4f6f0e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/proxy/MemoryDbProxyManager.java
@@ -1,9 +1,6 @@
package io.github.hectorvent.floci.services.memorydb.proxy;
-import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
-import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
import jakarta.enterprise.context.ApplicationScoped;
-import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -17,20 +14,13 @@ public class MemoryDbProxyManager {
private static final Logger LOG = Logger.getLogger(MemoryDbProxyManager.class);
- private final SigV4Validator sigV4Validator;
private final ConcurrentHashMap<String, MemoryDbAuthProxy> proxies = new ConcurrentHashMap<>();
- @Inject
- public MemoryDbProxyManager(SigV4Validator sigV4Validator) {
- this.sigV4Validator = sigV4Validator;
- }
-
- public void startProxy(String clusterName, AuthMode authMode, int proxyPort,
+ public void startProxy(String clusterName, boolean authRequired, int proxyPort,
String backendHost, int backendPort,
- MemoryDbAuthProxy.PasswordValidator passwordValidator) {
+ MemoryDbAuthProxy.AuthValidator authValidator) {
MemoryDbAuthProxy proxy = new MemoryDbAuthProxy(
- clusterName, authMode, backendHost, backendPort,
- passwordValidator, sigV4Validator);
+ clusterName, authRequired, backendHost, backendPort, authValidator);
try {
proxy.start(proxyPort);
proxies.put(clusterName, proxy);
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java
index 7028019bd0..2deb53d216 100644
--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbHandlerTest.java
@@ -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");
+ verify(service).createCluster(captor.capture(), eq("us-east-1"));
+ assertEquals("app-acl", captor.getValue().getAclName());
+ }
+
+ @Test
+ 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\"]}}");
+
+ Response response = handler.handle("CreateUser", request, "us-east-1");
+ assertEquals(200, response.getStatus());
+
+ 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 createClusterWithoutAuthTokenDefaultsToNoAuth() throws Exception {
- JsonNode request = objectMapper.readTree("{\"ClusterName\":\"open\"}");
+ void createAclParsesUserNames() throws Exception {
+ when(service.createAcl(any(), any())).thenAnswer(inv -> inv.getArgument(0));
+ JsonNode request = objectMapper.readTree(
+ "{\"ACLName\":\"app-acl\",\"UserNames\":[\"app-user\"]}");
- handler.handle("CreateCluster", request, "us-east-1");
+ Response response = handler.handle("CreateACL", 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<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());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java
index 485d499500..5ad0a65f0c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java
@@ -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"))
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbPersistenceTest.java
new file mode 100644
index 0000000000..a9334ad2e4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbPersistenceTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
index 611d4cf072..3f64c251af 100644
--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
@@ -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("open");
+ spec.setAclName("open-access");
+ service.createCluster(spec, "us-east-1");
+
+ // 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.setAuthMode(AuthMode.PASSWORD);
- spec.setAuthToken("s3cret");
+ 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");
- assertTrue(service.validatePassword("secure", null, "s3cret"));
- assertFalse(service.validatePassword("secure", null, "wrong"));
+ 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());