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

@@ -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;
}
return AuthMode.NO_AUTH;
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 values;
}
private Map<String, String> parseTags(JsonNode tagsNode) {
@@ -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;
}
return cluster.getAuthToken().equals(password);
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 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() {
@@ -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; }
}
@@ -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);
}
}
@@ -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<>();
@@ -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; }
}
@@ -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);
}
}
@@ -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);