diff --git a/docs/services/elasticache.md b/docs/services/elasticache.md index 48d9fb9999..2cdd69a44a 100644 --- a/docs/services/elasticache.md +++ b/docs/services/elasticache.md @@ -70,13 +70,22 @@ installed, such as one with a selector, is logged and the open sessions keep the until the user authenticates again. Other changes, such as adding a user to a group or associating a user group with a cache, are installed on the next successful authentication; reconnect to apply them promptly. -Re-authentication on an already relayed connection uses the backend protocol directly, so -reconnect through the proxy with frontend credentials. Revoked members' existing sessions are not proactively disconnected by this change. ACL selectors are rejected before backend changes: a selector can grant permissions independently of the root rules used to protect private backend credentials. Read-only `ACL` commands are also unavailable through these sessions. +## Signing in again + +A connection can send `AUTH`, or `HELLO` with `AUTH`, again after it has signed in, to refresh an +IAM token or to switch to another user. The proxy checks those credentials as it does at sign-in, +for caches with users and for caches with an AUTH token. Accepted credentials switch the +connection to that user and its access string. Refused credentials get `WRONGPASS` and leave the +connection signed in as before, as Valkey does. An `AUTH` or `HELLO` over 64 KiB, too large to +check, is refused the same way. The client's password or token never reaches the backend: the proxy +relays the command with the backend user's private credentials instead. A cache +without authentication relays these commands to the engine as sent. + ## Supported Management Actions @@ -536,6 +545,21 @@ aws elasticache create-user \ --endpoint-url $AWS_ENDPOINT_URL ``` +### IAM connection lifetime and transactions + +As on AWS, a connection signed in with an IAM token is closed 12 hours after it signed in. Sending +`AUTH` or `HELLO` with a new token gives it another 12 hours, and signing in again as a user +without IAM ends the limit. + +IAM re-authentication is not supported inside `MULTI`/`EXEC`. An `AUTH` or `HELLO` for an IAM user +inside a transaction is refused with `ERR Command not allowed inside a transaction`, and `EXEC` then +aborts the transaction with `EXECABORT`. AWS does not document its reply, so this one is Floci's +reading. An image older than Valkey 8 refuses it with `ERR MULTI calls can not be nested` instead, +and runs the rest of the transaction. Another user's `AUTH` inside a transaction is queued and runs +with `EXEC`, as in Valkey. It leaves the 12 hours as they were, since Floci cannot see whether +`EXEC` runs it. Lua scripts cannot send `AUTH` or `HELLO` at all: the engine refuses both from a +script. + ### Transit encryption mode metadata An explicit `TransitEncryptionMode` (`preferred` or `required`) on a replication group is diff --git a/docs/services/memorydb.md b/docs/services/memorydb.md index 79e149bee4..2c9d415b04 100644 --- a/docs/services/memorydb.md +++ b/docs/services/memorydb.md @@ -15,7 +15,8 @@ Set `FLOCI_SERVICES_MEMORYDB_MOCK=true` to manage clusters as control-plane-only A cluster bound to an ACL of its own runs each connection under the `AccessString` of the user it signs in as. The proxy installs that access string on a private backend ACL user, and the backend answers a command, key or channel outside it with `NOPERM`, as on AWS. A connection that does not -authenticate runs as the ACL's `default` user. Once the first connection is set up, the backend's +authenticate runs as the ACL's `default` user, but signing in as `default` is refused: AWS lets the +built-in `default` user belong only to the `open-access` ACL. Once the first connection is set up, the backend's own `default` account is disabled, so an `AUTH` sent after the proxy has bridged the connection cannot reach unrestricted permissions. @@ -24,6 +25,13 @@ session, and an access string with an ACL selector is refused. See [User access strings](elasticache.md#user-access-strings) on the ElastiCache page. Clusters on the `open-access` ACL are relayed without a backend ACL user, as before. +A connection that sends `AUTH` or `HELLO` with `AUTH` again after it has signed in is checked by the +proxy as at sign-in, and switches to the new user's access string, as described in +[Signing in again](elasticache.md#signing-in-again). As on AWS, a connection signed in with an IAM +token is closed 12 hours after it signed in unless it sends a new token, and IAM authentication is +refused inside `MULTI`/`EXEC`, with the same reply as ElastiCache (see +[IAM connection lifetime and transactions](elasticache.md#iam-connection-lifetime-and-transactions)). + ## Supported Management Actions diff --git a/src/main/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxy.java b/src/main/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxy.java index 8e9d9bd46f..81d400699c 100644 --- a/src/main/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxy.java +++ b/src/main/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxy.java @@ -3,6 +3,7 @@ package io.floci.aws.services.elasticache.proxy; import io.floci.aws.core.common.ListenBacklog; import org.jboss.logging.Logger; +import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -10,24 +11,37 @@ import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.LongSupplier; /** * Shared TCP auth-proxy skeleton for the Redis (RESP) wire protocol. Intercepts the * {@code AUTH} command or the {@code AUTH} option in {@code HELLO}, validates credentials - * through the subclass, then becomes a transparent byte relay to the backend container. + * through the subclass, then relays the connection to the backend container. * Used by both the ElastiCache and MemoryDB proxies, since MemoryDB's real AWS design is * explicitly modeled on ElastiCache: same Redis-compatible wire protocol, same IAM-auth * mechanism. * + *

Where the proxy checks credentials, it keeps reading the client's commands after sign-in, so a + * later {@code AUTH} or {@code HELLO} is checked the same way, and a connection signed in with an IAM + * token is closed 12 hours after its last sign-in, as on AWS. Everything else is relayed byte for + * byte. + * *

Uses Java virtual threads to accept connections and run the AUTH handshake. */ public abstract class AbstractRedisAuthProxy { private static final int HANDSHAKE_TIMEOUT_MILLIS = 10_000; private static final long RELAY_JOIN_TIMEOUT_MILLIS = 1_000; + /** How long a connection signed in with an IAM token lasts, unless it signs in again. */ + private static final long IAM_CONNECTION_LIFETIME_NANOS = TimeUnit.HOURS.toNanos(12); private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8); private static final byte[] NOAUTH_RESPONSE = @@ -62,8 +76,10 @@ public abstract class AbstractRedisAuthProxy { private final String backendHost; private final int backendPort; private final int handshakeTimeoutMillis; + private final LongSupplier nanoTime; private final Set handshakingClients = ConcurrentHashMap.newKeySet(); private final Set unencryptedClients = ConcurrentHashMap.newKeySet(); + private final Set connections = ConcurrentHashMap.newKeySet(); private volatile boolean running; private ServerSocket serverSocket; @@ -77,6 +93,14 @@ public abstract class AbstractRedisAuthProxy { protected AbstractRedisAuthProxy(Logger log, String serviceName, String threadPrefix, String resourceId, String backendHost, int backendPort, int handshakeTimeoutMillis) { + this(log, serviceName, threadPrefix, resourceId, backendHost, backendPort, handshakeTimeoutMillis, + System::nanoTime); + } + + /** @param nanoTime the time IAM connection lifetimes are measured on, a seam for tests */ + AbstractRedisAuthProxy(Logger log, String serviceName, String threadPrefix, String resourceId, + String backendHost, int backendPort, int handshakeTimeoutMillis, + LongSupplier nanoTime) { this.log = log; this.serviceName = serviceName; this.threadPrefix = threadPrefix; @@ -84,6 +108,7 @@ public abstract class AbstractRedisAuthProxy { this.backendHost = backendHost; this.backendPort = backendPort; this.handshakeTimeoutMillis = handshakeTimeoutMillis; + this.nanoTime = nanoTime; } protected final String backendHost() { @@ -103,10 +128,40 @@ public abstract class AbstractRedisAuthProxy { /** Closes a socket, tolerating errors. Implementations may add their own logging. */ protected abstract void closeQuietly(Socket socket); + /** The user a username names: a blank one, as {@code AUTH } sends, names {@code default}. */ + protected static String userOrDefault(String username) { + return username == null || username.isEmpty() ? "default" : username; + } + /** Applies the validated frontend identity to a newly connected backend. */ protected void initializeBackend(Socket backend, String username) throws IOException { } + /** + * Whether {@code username} signs in with an IAM token. Such a connection is closed 12 hours after + * its last sign-in, and cannot sign in again inside a transaction. + */ + protected boolean signsInWithIam(String username) { + return false; + } + + /** + * Whether the proxy checks the credentials of an {@code AUTH} or {@code HELLO} sent after sign-in, + * as it does at sign-in. When it does not, they reach the backend as sent. + */ + protected boolean checksCredentials() { + return authRequired(); + } + + /** + * The username and password a relayed connection sends its backend to run as {@code username} from + * then on, once the proxy has accepted that user's own credentials. The default suits a backend + * without access control, whose default user takes any password. + */ + protected List backendCredentials(String username) throws IOException { + return List.of("default", UUID.randomUUID().toString()); + } + /** Establishes the client transport before reading credentials. */ protected ClientTransport clientTransport(Socket client) throws IOException { return ClientTransport.unencrypted(client); @@ -226,7 +281,7 @@ public abstract class AbstractRedisAuthProxy { } continue; } - bridgeCommand(client, input, cmd, null); + bridgeCommand(client, input, cmd, null, false); return; } if (authRequired()) { @@ -235,7 +290,7 @@ public abstract class AbstractRedisAuthProxy { return; } - bridgeCommand(client, input, cmd, null); + bridgeCommand(client, input, cmd, null, false); return; } } catch (Exception e) { @@ -273,7 +328,7 @@ public abstract class AbstractRedisAuthProxy { return; } - bridgeCommand(client, input, null, username); + bridgeCommand(client, input, null, username, true); } private boolean handleHello(Socket client, InputStream input, String[] cmd) throws IOException { @@ -338,7 +393,7 @@ public abstract class AbstractRedisAuthProxy { return false; } - bridgeCommand(client, input, forwarded.toArray(String[]::new), username); + bridgeCommand(client, input, forwarded.toArray(String[]::new), username, authProvided); return true; } @@ -359,7 +414,8 @@ public abstract class AbstractRedisAuthProxy { return true; } - private void bridgeCommand(Socket client, InputStream input, String[] command, String username) throws IOException { + private void bridgeCommand(Socket client, InputStream input, String[] command, String username, + boolean signedIn) throws IOException { Socket backend = new Socket(backendHost, backendPort); try { backend.setTcpNoDelay(true); @@ -371,7 +427,7 @@ public abstract class AbstractRedisAuthProxy { } client.setSoTimeout(0); handshakingClients.remove(client); - bridge(client, input, backend); + bridge(new Connection(client, backend, signedIn && signsInWithIam(username)), input); } catch (IOException e) { closeQuietly(backend); throw e; @@ -388,15 +444,22 @@ public abstract class AbstractRedisAuthProxy { * from {@code handleConnection} blocks in {@code join} here; scheduling nested virtual-thread * relays under load can stall delivery of backend responses (e.g. PING/PONG) to the client. */ - private void bridge(Socket client, InputStream clientInput, Socket backend) throws IOException { + private void bridge(Connection connection, InputStream clientInput) throws IOException { + Socket client = connection.client; + Socket backend = connection.backend; InputStream backendInput = backend.getInputStream(); - CountDownLatch firstRelayDone = new CountDownLatch(1); + boolean checkCredentials = checksCredentials(); + connections.add(connection); Thread t1 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-c2b-" + resourceId) .start(() -> { try { - relay(clientInput, backend); + if (checkCredentials) { + relayCommands(clientInput, connection); + } else { + relay(clientInput, backend); + } } finally { - firstRelayDone.countDown(); + connection.relayFinished(); } }); Thread t2 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-b2c-" + resourceId) @@ -404,21 +467,55 @@ public abstract class AbstractRedisAuthProxy { try { relay(backendInput, client); } finally { - firstRelayDone.countDown(); + connection.relayFinished(); } }); try { - firstRelayDone.await(); + if (connection.awaitEnd()) { + closeExpired(connection); + } t1.join(RELAY_JOIN_TIMEOUT_MILLIS); t2.join(RELAY_JOIN_TIMEOUT_MILLIS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { + connections.remove(connection); closeQuietly(client); closeQuietly(backend); } } + /** + * Closes every connection whose IAM sign-in is 12 hours old by {@code nanoTime}, as each + * connection's own wait does once that time has passed. A seam for tests that move the time on. + */ + void closeExpiredConnections() { + for (Connection connection : connections) { + if (connection.expire()) { + closeExpired(connection); + } + } + } + + private void closeExpired(Connection connection) { + log.infov("Closing a connection to {0} 12 hours after it signed in with an IAM token", resourceId); + closeQuietly(connection.client); + closeQuietly(connection.backend); + } + + private void relayCommands(InputStream clientInput, Connection connection) { + try { + OutputStream backendOutput = new BufferedOutputStream(connection.backend.getOutputStream()); + new ClientCommandRelay(clientInput, backendOutput, new SignedInCommands(connection)).run(); + } catch (IOException ignored) { + // Normal when either side closes the connection + } catch (RuntimeException e) { + log.warnv(e, "Closing a connection to {0} after a failure checking its commands", resourceId); + } finally { + shutdownOutput(connection.backend); + } + } + private static void relay(InputStream in, Socket to) { byte[] buf = new byte[8192]; try { @@ -468,4 +565,266 @@ public abstract class AbstractRedisAuthProxy { } return false; } + + /** + * A relayed connection. It ends when either side closes it, or, while the client is signed in with + * an IAM token, 12 hours after that sign-in. + */ + private final class Connection { + private final Socket client; + private final Socket backend; + private final ReentrantLock lock = new ReentrantLock(); + private final Condition changed = lock.newCondition(); + private boolean relayFinished; + private boolean expired; + private boolean iam; + private long signedInAt; + + private Connection(Socket client, Socket backend, boolean iam) { + this.client = client; + this.backend = backend; + this.iam = iam; + this.signedInAt = nanoTime.getAsLong(); + } + + /** + * Restarts the lifetime of a connection that signs in again, which lasts only after an IAM sign-in. + * Once the connection has expired, it is being closed, and signing in no longer renews it. + */ + void signedIn(boolean iamUser) { + lock.lock(); + try { + if (expired) { + return; + } + iam = iamUser; + signedInAt = nanoTime.getAsLong(); + changed.signalAll(); + } finally { + lock.unlock(); + } + } + + void relayFinished() { + lock.lock(); + try { + relayFinished = true; + changed.signalAll(); + } finally { + lock.unlock(); + } + } + + /** + * Marks the connection expired once its IAM sign-in has run out, which the caller then closes. True + * only for the call that marks it, and decided under the same lock as a renewing sign-in. + */ + boolean expire() { + lock.lock(); + try { + if (expired || !iam || remainingNanos() > 0) { + return false; + } + expired = true; + return true; + } finally { + lock.unlock(); + } + } + + /** Waits until a relay direction finishes, or until this wait expires the connection, which returns true. */ + boolean awaitEnd() throws InterruptedException { + lock.lock(); + try { + while (!relayFinished) { + if (expire()) { + return true; + } + if (iam && !expired) { + changed.awaitNanos(remainingNanos()); + } else { + changed.await(); + } + } + return false; + } finally { + lock.unlock(); + } + } + + private long remainingNanos() { + return IAM_CONNECTION_LIFETIME_NANOS - (nanoTime.getAsLong() - signedInAt); + } + } + + /** + * Follows a signed-in client's commands: it checks the credentials of each {@code AUTH} and + * {@code HELLO}, and tracks transactions, since IAM re-authentication is not supported inside one. + * A sign-in queued in a transaction leaves the connection's lifetime as it was: the proxy cannot see + * whether {@code EXEC} runs it, and an aborted transaction never does. + * + *

The backend answers every command, so its replies keep their order: accepted credentials are + * relayed as the backend credentials of their user, and refused ones as credentials the backend + * refuses with {@code WRONGPASS}, which leaves the connection signed in as before. The client's own + * password or token never reaches the backend. + */ + private final class SignedInCommands implements ClientCommandRelay.Commands { + /** The commands that begin or end a transaction, none of which takes an argument. */ + private static final List TRANSACTION_COMMANDS = List.of("MULTI", "EXEC", "DISCARD", "RESET"); + + private final Connection connection; + private boolean transaction; + + private SignedInCommands(Connection connection) { + this.connection = connection; + } + + @Override + public boolean wants(String name) { + return isSignIn(name) || TRANSACTION_COMMANDS.stream().anyMatch(name::equalsIgnoreCase); + } + + private static boolean isSignIn(String name) { + return name.equalsIgnoreCase("AUTH") || name.equalsIgnoreCase("HELLO"); + } + + @Override + public List rewrite(List command) { + String name = command.get(0); + if (!isSignIn(name)) { + // With an argument the backend refuses it for its arity, leaving the transaction as it was. + if (command.size() == 1) { + transaction = name.equalsIgnoreCase("MULTI"); + } + return command; + } + SignIn signIn = name.equalsIgnoreCase("AUTH") ? SignIn.auth(command) : SignIn.hello(command); + if (signIn == null) { + return command; + } + if (!signIn.reachesSignIn()) { + return signIn.relayed(refusedCredentials()); + } + String username = signIn.username(); + boolean iam = signsInWithIam(username); + if (transaction && iam) { + // Sends MULTI in its place: inside a transaction the backend refuses it as a command that + // cannot be queued, which also aborts the transaction, and the refusal keeps its place. + return List.of("MULTI"); + } + List credentials = authenticate(username, signIn.password()) ? switchTo(username) : null; + if (credentials == null) { + return signIn.relayed(refusedCredentials()); + } + if (!transaction) { + connection.signedIn(iam); + } + return signIn.relayed(credentials); + } + + @Override + public List inPlaceOfTooLarge(String name) { + if (isSignIn(name)) { + List refused = refusedCredentials(); + return List.of("AUTH", refused.get(0), refused.get(1)); + } + // A transaction command too large to hold has arguments, so the backend refuses this one too. + return List.of(name, ""); + } + + private List switchTo(String username) { + try { + return backendCredentials(username); + } catch (IOException e) { + log.warnv("Could not switch a connection to {0} over to another user: {1}", resourceId, + e.getMessage()); + return null; + } + } + + private static List refusedCredentials() { + return List.of("floci-refused-" + UUID.randomUUID(), UUID.randomUUID().toString()); + } + } + + /** + * The credentials in an {@code AUTH} or {@code HELLO} sent after sign-in. + * + * @param arguments what the backend reads of the command: all of it, or for a {@code HELLO} the + * backend refuses, the arguments up to the one it refuses + * @param credentials the index among them of each username and password pair + * @param reachesSignIn whether the backend gets as far as checking the credentials + */ + private record SignIn(List arguments, List credentials, boolean reachesSignIn) { + + /** Null for an {@code AUTH} without arguments, which carries no credentials. */ + static SignIn auth(List command) { + return switch (command.size()) { + case 1 -> null; + // AUTH signs in as the default user, which the proxy names null, as at sign-in. + case 2 -> new SignIn(Arrays.asList("AUTH", null, command.get(1)), List.of(1), true); + case 3 -> new SignIn(command, List.of(1), true); + // The backend refuses more arguments as a syntax error, before reading any of them. + default -> { + List blanks = new ArrayList<>(Collections.nCopies(command.size(), "")); + blanks.set(0, command.get(0)); + yield new SignIn(blanks, List.of(), false); + } + }; + } + + /** + * Reads the options as the backend does, which stops at the first it refuses. Null for a + * well-formed {@code HELLO} without an {@code AUTH} option. + */ + static SignIn hello(List command) { + List credentials = new ArrayList<>(); + if (command.size() > 1 && !supportedProtocol(command.get(1))) { + return new SignIn(command.subList(0, 2), credentials, false); + } + int index = 2; + while (index < command.size()) { + String option = command.get(index); + int remaining = command.size() - 1 - index; + if (option.equalsIgnoreCase("AUTH") && remaining >= 2) { + credentials.add(index + 1); + index += 3; + } else if (option.equalsIgnoreCase("SETNAME") && remaining >= 1 + && isValidClientName(command.get(index + 1))) { + index += 2; + } else { + int refused = option.equalsIgnoreCase("SETNAME") && remaining >= 1 ? index + 1 : index; + return new SignIn(command.subList(0, refused + 1), credentials, false); + } + } + return credentials.isEmpty() ? null : new SignIn(command, credentials, true); + } + + private static boolean supportedProtocol(String version) { + try { + long protocol = Long.parseLong(version); + return protocol >= 2 && protocol <= 3; + } catch (NumberFormatException e) { + return false; + } + } + + /** The last pair is the one the backend signs in with. */ + String username() { + return arguments.get(credentials.getLast()); + } + + String password() { + return arguments.get(credentials.getLast() + 1); + } + + List relayed(List replacement) { + List relayed = new ArrayList<>(arguments); + for (int index : credentials) { + relayed.set(index, replacement.get(0)); + relayed.set(index + 1, replacement.get(1)); + } + return relayed; + } + } } diff --git a/src/main/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelay.java b/src/main/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelay.java new file mode 100644 index 0000000000..a38f120fbd --- /dev/null +++ b/src/main/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelay.java @@ -0,0 +1,471 @@ +package io.floci.aws.services.elasticache.proxy; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * Relays a signed-in client's commands to its backend one command at a time, so the proxy can answer + * for the credentials a later {@code AUTH} or {@code HELLO} carries, as it does at sign-in. Commands + * come as RESP arrays or as inline lines, which are split into arguments as Valkey splits them. Every + * command the proxy does not ask for is passed on byte for byte, the values of an array streamed + * rather than held. A wanted command too large to hold is dropped for one the proxy supplies. After a + * malformed array, which the backend cannot read, the rest of the connection is a plain relay, as the + * backend then reports the protocol error and closes it. + */ +final class ClientCommandRelay { + + /** Longest command name worth reading: anything longer is no command the proxy looks at. */ + private static final int NAME_LIMIT = 64; + /** + * Most bytes of one command the proxy holds to look at its arguments, which is also the longest + * inline line Valkey reads. + */ + private static final int HELD_LIMIT = 64 * 1024; + /** Longest array or bulk string header line, such as {@code $536870912}. */ + private static final int HEADER_LIMIT = 32; + private static final long MALFORMED = Long.MIN_VALUE; + + /** What the proxy does with the commands passing through. */ + interface Commands { + /** Whether the proxy wants commands named {@code name} handed to {@link #rewrite} whole. */ + boolean wants(String name); + + /** + * The command to pass on in place of {@code command}, or {@code command} itself to pass on the + * bytes the client sent. + */ + List rewrite(List command); + + /** The command to pass on in place of a wanted one too large to hold, whose bytes are dropped. */ + List inPlaceOfTooLarge(String name); + } + + private final InputStream in; + private final OutputStream out; + private final Commands commands; + private final byte[] buffer = new byte[8192]; + private int position; + private int limit; + + ClientCommandRelay(InputStream in, OutputStream out, Commands commands) { + this.in = in; + this.out = out; + this.commands = commands; + } + + /** Relays until the client closes its side. */ + void run() throws IOException { + while (fill()) { + if (buffer[position] != '*') { + relayInline(); + } else if (!relayArray()) { + copyRest(); + return; + } + } + out.flush(); + } + + /** Relays one array; false when it was malformed, its bytes so far having been passed on. */ + private boolean relayArray() throws IOException { + ByteArrayOutputStream held = new ByteArrayOutputStream(); + long count = header(held, '*'); + if (count == MALFORMED) { + held.writeTo(out); + return false; + } + if (count <= 0) { + held.writeTo(out); + return true; + } + long nameLength = header(held, '$'); + if (nameLength == MALFORMED) { + held.writeTo(out); + return false; + } + if (nameLength > NAME_LIMIT) { + held.writeTo(out); + copy(nameLength + 2); + return streamArguments(count - 1); + } + byte[] name = read((int) nameLength + 2, held); + if (name == null) { + held.writeTo(out); + return false; + } + String commandName = new String(name, 0, name.length - 2, StandardCharsets.UTF_8); + if (!commands.wants(commandName)) { + held.writeTo(out); + return streamArguments(count - 1); + } + List command = new ArrayList<>(); + command.add(commandName); + for (long index = 1; index < count; index++) { + long length = header(held, '$'); + if (length == MALFORMED) { + held.writeTo(out); + return false; + } + if (held.size() + length + 2 > HELD_LIMIT) { + // Dropped unread, so credentials too large to check never reach the backend. + skip(length + 2); + if (!skipArguments(count - index - 1)) { + return false; + } + out.write(encode(commands.inPlaceOfTooLarge(commandName))); + return true; + } + byte[] value = read((int) length + 2, held); + if (value == null) { + held.writeTo(out); + return false; + } + command.add(new String(value, 0, value.length - 2, StandardCharsets.UTF_8)); + } + relay(command, held); + return true; + } + + /** Relays one inline command and its line end. */ + private void relayInline() throws IOException { + ByteArrayOutputStream held = new ByteArrayOutputStream(); + boolean complete = false; + while (!complete && held.size() <= HELD_LIMIT) { + if (!fill()) { + held.writeTo(out); + return; + } + int end = position; + while (end < limit && buffer[end] != '\n') { + end++; + } + complete = end < limit; + int stop = complete ? end + 1 : end; + held.write(buffer, position, stop - position); + position = stop; + } + if (held.size() > HELD_LIMIT) { + relayLongLine(held, complete); + return; + } + byte[] line = held.toByteArray(); + int length = line.length - 1; + if (length > 0 && line[length - 1] == '\r') { + length--; + } + List command = splitInline(line, length); + if (command == null || command.isEmpty() || !commands.wants(command.get(0))) { + held.writeTo(out); + } else { + relay(command, held); + } + } + + /** + * An inline line too long to hold, named by its first word: a wanted command is dropped unread for the + * proxy's replacement, and any other is passed on. + */ + private void relayLongLine(ByteArrayOutputStream held, boolean complete) throws IOException { + String name = firstWord(held.toByteArray()); + if (!name.isEmpty() && commands.wants(name)) { + if (!complete) { + skipLine(); + } + out.write(encode(commands.inPlaceOfTooLarge(name))); + } else { + held.writeTo(out); + if (!complete) { + copyLine(); + } + } + } + + private static String firstWord(byte[] line) { + int start = 0; + while (start < line.length && isSpace(line[start] & 0xff)) { + start++; + } + int end = start; + while (end < line.length && !isSpace(line[end] & 0xff)) { + end++; + } + return new String(line, start, end - start, StandardCharsets.UTF_8); + } + + private void relay(List command, ByteArrayOutputStream held) throws IOException { + List relayed = commands.rewrite(command); + if (relayed == command) { + held.writeTo(out); + } else { + out.write(encode(relayed)); + } + } + + /** Drops the remaining bulk strings of an array; false when they are malformed. */ + private boolean skipArguments(long remaining) throws IOException { + for (long index = 0; index < remaining; index++) { + long length = header(new ByteArrayOutputStream(), '$'); + if (length == MALFORMED) { + return false; + } + skip(length + 2); + } + return true; + } + + /** Passes on the remaining bulk strings of an array the proxy does not look into. */ + private boolean streamArguments(long remaining) throws IOException { + for (long index = 0; index < remaining; index++) { + ByteArrayOutputStream header = new ByteArrayOutputStream(); + long length = header(header, '$'); + header.writeTo(out); + if (length == MALFORMED) { + return false; + } + copy(length + 2); + } + return true; + } + + /** + * Reads one header line such as {@code *3} or {@code $5}, keeping its bytes in {@code held}, and + * returns its length, or {@link #MALFORMED}, as a bulk string's negative length also is. + */ + private long header(ByteArrayOutputStream held, char type) throws IOException { + StringBuilder line = new StringBuilder(); + while (line.length() <= HEADER_LIMIT) { + if (!fill()) { + return MALFORMED; + } + byte value = buffer[position++]; + held.write(value); + if (value == '\n') { + return parseHeader(line, type); + } + line.append((char) value); + } + return MALFORMED; + } + + private static long parseHeader(StringBuilder line, char type) { + if (line.length() < 3 || line.charAt(0) != type || line.charAt(line.length() - 1) != '\r') { + return MALFORMED; + } + try { + long length = Long.parseLong(line, 1, line.length() - 1, 10); + return type == '$' && length < 0 ? MALFORMED : length; + } catch (NumberFormatException e) { + return MALFORMED; + } + } + + /** Reads {@code length} bytes that end with CRLF, keeping them in {@code held}; null if they do not. */ + private byte[] read(int length, ByteArrayOutputStream held) throws IOException { + byte[] value = new byte[length]; + int read = 0; + while (read < length) { + if (!fill()) { + held.write(value, 0, read); + return null; + } + int chunk = Math.min(length - read, limit - position); + System.arraycopy(buffer, position, value, read, chunk); + position += chunk; + read += chunk; + } + held.write(value, 0, length); + return value[length - 2] == '\r' && value[length - 1] == '\n' ? value : null; + } + + /** Passes on the next {@code length} bytes as they arrive. */ + private void copy(long length) throws IOException { + long remaining = length; + while (remaining > 0 && fill()) { + int chunk = (int) Math.min(remaining, limit - position); + out.write(buffer, position, chunk); + position += chunk; + remaining -= chunk; + } + } + + /** Passes on the rest of an inline line, up to and including its line feed. */ + private void copyLine() throws IOException { + while (fill()) { + int end = position; + while (end < limit && buffer[end] != '\n') { + end++; + } + boolean complete = end < limit; + int stop = complete ? end + 1 : end; + out.write(buffer, position, stop - position); + position = stop; + if (complete) { + return; + } + } + } + + private void skipLine() throws IOException { + while (fill()) { + int end = position; + while (end < limit && buffer[end] != '\n') { + end++; + } + boolean complete = end < limit; + position = complete ? end + 1 : end; + if (complete) { + return; + } + } + } + + private void skip(long length) throws IOException { + long remaining = length; + while (remaining > 0 && fill()) { + int chunk = (int) Math.min(remaining, limit - position); + position += chunk; + remaining -= chunk; + } + } + + /** + * Splits an inline command into its arguments as Valkey does: on blanks, with double quotes taking + * backslash escapes and single quotes taking only an escaped single quote. Null for unbalanced + * quotes, which the backend refuses as a protocol error. + */ + static List splitInline(byte[] line, int length) { + List arguments = new ArrayList<>(); + int index = 0; + while (true) { + while (byteAt(line, length, index) != 0 && isSpace(byteAt(line, length, index))) { + index++; + } + if (byteAt(line, length, index) == 0) { + return arguments; + } + ByteArrayOutputStream argument = new ByteArrayOutputStream(); + boolean doubleQuoted = false; + boolean singleQuoted = false; + boolean done = false; + while (!done) { + int current = byteAt(line, length, index); + int next = byteAt(line, length, index + 1); + if (doubleQuoted) { + if (current == '\\' && next == 'x' && isHex(byteAt(line, length, index + 2)) + && isHex(byteAt(line, length, index + 3))) { + argument.write(Character.digit(byteAt(line, length, index + 2), 16) * 16 + + Character.digit(byteAt(line, length, index + 3), 16)); + index += 3; + } else if (current == '\\' && next != 0) { + index++; + argument.write(unescape(next)); + } else if (current == '"') { + if (next != 0 && !isSpace(next)) { + return null; + } + done = true; + } else if (current == 0) { + return null; + } else { + argument.write(current); + } + } else if (singleQuoted) { + if (current == '\\' && next == '\'') { + index++; + argument.write('\''); + } else if (current == '\'') { + if (next != 0 && !isSpace(next)) { + return null; + } + done = true; + } else if (current == 0) { + return null; + } else { + argument.write(current); + } + } else { + switch (current) { + case ' ', '\n', '\r', '\t', 0 -> done = true; + case '"' -> doubleQuoted = true; + case '\'' -> singleQuoted = true; + default -> argument.write(current); + } + } + if (current != 0) { + index++; + } + } + arguments.add(argument.toString(StandardCharsets.UTF_8)); + } + } + + /** The byte at {@code index}, or 0 past the end, which ends the line as it does in Valkey. */ + private static int byteAt(byte[] line, int length, int index) { + return index < length ? line[index] & 0xff : 0; + } + + private static boolean isSpace(int value) { + return value == ' ' || value == '\t' || value == '\n' || value == 0x0b || value == '\f' || value == '\r'; + } + + private static boolean isHex(int value) { + return Character.digit(value, 16) >= 0; + } + + private static int unescape(int value) { + return switch (value) { + case 'n' -> '\n'; + case 'r' -> '\r'; + case 't' -> '\t'; + case 'b' -> '\b'; + case 'a' -> 0x07; + default -> value; + }; + } + + private void copyRest() throws IOException { + out.write(buffer, position, limit - position); + position = limit; + out.flush(); + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + out.flush(); + } + } + + /** + * Makes sure unread bytes are buffered, first passing on everything written so far, since reading + * may block until the client sends more. False once the client has closed its side. + */ + private boolean fill() throws IOException { + if (position < limit) { + return true; + } + out.flush(); + int read = in.read(buffer); + if (read == -1) { + return false; + } + position = 0; + limit = read; + return true; + } + + static byte[] encode(List arguments) { + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + encoded.writeBytes(("*" + arguments.size() + "\r\n").getBytes(StandardCharsets.US_ASCII)); + for (String argument : arguments) { + byte[] bytes = argument.getBytes(StandardCharsets.UTF_8); + encoded.writeBytes(("$" + bytes.length + "\r\n").getBytes(StandardCharsets.US_ASCII)); + encoded.writeBytes(bytes); + encoded.writeBytes("\r\n".getBytes(StandardCharsets.US_ASCII)); + } + return encoded.toByteArray(); + } +} diff --git a/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxy.java b/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxy.java index 9ce3bcfaef..a20c46916e 100644 --- a/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxy.java +++ b/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxy.java @@ -12,6 +12,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.net.Socket; +import java.util.List; import java.util.function.Supplier; /** @@ -87,10 +88,30 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy { @Override protected void initializeBackend(Socket backend, String username) throws IOException { - boolean members = passwordValidator.hasMembers(); - if (!members && !backendAcl.initialized()) { + if (!controlsBackendAccess()) { return; } + String name = userOrDefault(username); + backendAcl.authenticate(backend, name, accessString(name)); + } + + @Override + protected List backendCredentials(String username) throws IOException { + if (!controlsBackendAccess()) { + return super.backendCredentials(username); + } + String name = userOrDefault(username); + return backendAcl.credentials(backendHost(), backendPort(), name, accessString(name)); + } + + /** + * Whether sessions run as private backend users: once the cache has users, and for as long as the + * backend keeps its default user off. Readies a cluster's replication before its first such session. + */ + private boolean controlsBackendAccess() throws IOException { + if (!passwordValidator.hasMembers() && !backendAcl.initialized()) { + return false; + } if (!backendAcl.initialized() && passwordValidator.clusterMode()) { try { passwordValidator.prepareClusterReplication(); @@ -99,9 +120,11 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy { throw new IOException("Cluster replication is not ready for access strings", e); } } - String name = username == null || username.isEmpty() ? "default" : username; - backendAcl.authenticate(backend, name, - () -> members ? passwordValidator.accessString(name) : "on ~* &* +@all"); + return true; + } + + private Supplier accessString(String name) { + return () -> passwordValidator.hasMembers() ? passwordValidator.accessString(name) : "on ~* &* +@all"; } /** @@ -109,7 +132,7 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy { * failure is logged and the sessions keep their old permissions until the user authenticates again. */ public void refreshUser(String username) { - String name = username == null || username.isEmpty() ? "default" : username; + String name = userOrDefault(username); try { backendAcl.reapply(backendHost(), backendPort(), name, () -> passwordValidator.accessString(name)); } catch (IOException e) { @@ -130,9 +153,26 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy { return currentAuthMode() != AuthMode.NO_AUTH; } + @Override + protected boolean checksCredentials() { + return passwordValidator.hasMembers() || currentAuthMode() != AuthMode.NO_AUTH; + } + + @Override + protected boolean signsInWithIam(String username) { + if (!passwordValidator.hasMembers()) { + return currentAuthMode() == AuthMode.IAM; + } + AuthMode userMode = passwordValidator.memberAuthMode(userOrDefault(username)); + if (userMode == null && username != null) { + userMode = passwordValidator.memberAuthMode(username); + } + return userMode == AuthMode.IAM; + } + @Override protected boolean authenticate(String username, String password) { - String effectiveUser = (username == null || username.isEmpty()) ? "default" : username; + String effectiveUser = userOrDefault(username); if (passwordValidator.hasMembers()) { if ("default".equals(effectiveUser)) { if (passwordValidator.validatePassword(username, password)) { diff --git a/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAcl.java b/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAcl.java index c42f18a19a..96fb57b62f 100644 --- a/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAcl.java +++ b/src/main/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAcl.java @@ -80,6 +80,21 @@ public final class ElastiCacheBackendAcl { authenticate(backend, username, () -> accessString); } + /** + * Installs the access string of {@code username} over a connection of its own, as a sign-in does, and + * returns the backend username and password that a session already relayed sends with {@code AUTH} to + * run as that user from then on. + */ + public synchronized List credentials(String backendHost, int backendPort, String username, + Supplier accessStringSupplier) throws IOException { + try (Socket backend = new Socket()) { + backend.connect(new InetSocketAddress(backendHost, backendPort), CONNECT_TIMEOUT_MILLIS); + authenticate(backend, username, accessStringSupplier); + } + String backendName = backendName(username); + return List.of(backendName, passwords.get(backendName)); + } + /** * Installs a changed access string on the backend user that sessions of {@code username} already run * as, so it applies to their open connections and not only to the next login. Nothing is done while diff --git a/src/main/java/io/floci/aws/services/memorydb/MemoryDbService.java b/src/main/java/io/floci/aws/services/memorydb/MemoryDbService.java index 537cca87e7..f25209fc6e 100644 --- a/src/main/java/io/floci/aws/services/memorydb/MemoryDbService.java +++ b/src/main/java/io/floci/aws/services/memorydb/MemoryDbService.java @@ -753,7 +753,8 @@ public class MemoryDbService { return true; } User user = aclMember(cluster, username, region, accountId); - if (user == null) { + if (user == null || DEFAULT_USER.equals(user.getName())) { + // AWS lets the built-in default user belong only to the open-access ACL, so it signs in nowhere else. return false; } return switch (user.getAuthMode()) { @@ -800,10 +801,17 @@ public class MemoryDbService { @Override public String accessString(String username) { + return member(username).map(User::getAccessString).orElse(null); + } + + @Override + public boolean signsInWithIam(String username) { + return member(username).map(user -> user.getAuthMode() == AuthMode.IAM).orElse(false); + } + + private Optional member(String username) { return ownedResourceGet(clusters, accountId, name, region) - .map(current -> aclMember(current, username, region, accountId)) - .map(User::getAccessString) - .orElse(null); + .map(current -> aclMember(current, username, region, accountId)); } }; } diff --git a/src/main/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxy.java b/src/main/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxy.java index 8400c3eb91..b875929220 100644 --- a/src/main/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxy.java +++ b/src/main/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxy.java @@ -6,6 +6,7 @@ import org.jboss.logging.Logger; import java.io.IOException; import java.net.Socket; +import java.util.List; /** * TCP auth proxy for a single MemoryDB cluster. @@ -16,8 +17,8 @@ import java.net.Socket; * *

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 requireAuth = false}, in which case the proxy is a - * straight relay. + * password) is created with {@code requireAuth = false}, in which case a client need not + * sign in, and an {@code open-access} cluster is a straight relay. * *

A cluster bound to an ACL of its own runs each connection as a private backend ACL user * that carries the signed-in user's access string, as an ElastiCache cache with user groups does, @@ -54,10 +55,29 @@ public class MemoryDbAuthProxy extends AbstractRedisAuthProxy { if (!authValidator.enforcesAccessStrings()) { return; } - String name = username == null || username.isEmpty() ? "default" : username; + String name = userOrDefault(username); backendAcl.authenticate(backend, name, () -> authValidator.accessString(name)); } + @Override + protected boolean checksCredentials() { + return requireAuth || authValidator.enforcesAccessStrings(); + } + + @Override + protected boolean signsInWithIam(String username) { + return authValidator.signsInWithIam(username); + } + + @Override + protected List backendCredentials(String username) throws IOException { + if (!authValidator.enforcesAccessStrings()) { + return super.backendCredentials(username); + } + String name = userOrDefault(username); + return backendAcl.credentials(backendHost(), backendPort(), name, () -> authValidator.accessString(name)); + } + @Override protected void closeQuietly(Socket s) { try { @@ -86,5 +106,10 @@ public class MemoryDbAuthProxy extends AbstractRedisAuthProxy { default String accessString(String username) { return null; } + + /** Whether {@code username}, null for the {@code default} user, is an IAM user of the cluster's ACL. */ + default boolean signsInWithIam(String username) { + return false; + } } } diff --git a/src/test/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxyReauthenticationTest.java b/src/test/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxyReauthenticationTest.java new file mode 100644 index 0000000000..09c431db41 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/proxy/AbstractRedisAuthProxyReauthenticationTest.java @@ -0,0 +1,393 @@ +package io.floci.aws.services.elasticache.proxy; + +import org.jboss.logging.Logger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.LongSupplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AbstractRedisAuthProxyReauthenticationTest { + + private static final long HOUR = TimeUnit.HOURS.toNanos(1); + /** Each user's accepted secrets; the IAM user takes either of two tokens. */ + private static final Map> SECRETS = Map.of( + "app", List.of("app-secret"), + "reader", List.of("reader-secret"), + "iam-user", List.of("token-1", "token-2")); + + private final AtomicLong now = new AtomicLong(1_000 * HOUR); + private ServerSocket backendServer; + private TestProxy proxy; + + @AfterEach + void stop() throws IOException { + if (proxy != null) { + proxy.stop(); + } + if (backendServer != null) { + backendServer.close(); + } + } + + @Test + void aSecondAuthIsRelayedWithTheBackendCredentialsOfItsUser() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + send(client, "AUTH", "reader", "reader-secret"); + + assertEquals(List.of("AUTH", "backend-reader", "backend-password-reader"), received(backend)); + reply(backend, "+OK\r\n"); + assertEquals("+OK", line(client)); + } + } + + @Test + void refusedCredentialsReachTheBackendAsCredentialsItRefusesWithoutTheClientsSecret() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + send(client, "AUTH", "app", "wrong-secret"); + send(client, "AUTH", "unknown-secret"); + + for (int attempt = 0; attempt < 2; attempt++) { + List relayed = received(backend); + assertEquals("AUTH", relayed.get(0)); + assertEquals(3, relayed.size()); + assertTrue(relayed.get(1).startsWith("floci-refused-"), relayed.get(1)); + assertFalse(relayed.contains("wrong-secret") || relayed.contains("unknown-secret")); + } + } + } + + @Test + void aHelloThatSignsInAgainKeepsItsOtherOptions() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + send(client, "HELLO", "3", "AUTH", "reader", "reader-secret", "SETNAME", "worker"); + + assertEquals(List.of("HELLO", "3", "AUTH", "backend-reader", "backend-password-reader", + "SETNAME", "worker"), received(backend)); + } + } + + @Test + void aHelloTheBackendRefusesEndsAtTheRefusedArgumentWithoutTheClientsSecret() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + int attempts = proxy.authenticationAttempts.get(); + send(client, "HELLO", "3", "AUTH", "reader", "reader-secret", "BOGUS", "AUTH", "app", "app-secret"); + send(client, "HELLO", "4", "AUTH", "reader", "reader-secret"); + send(client, "HELLO", "3", "SETNAME", "bad name", "AUTH", "reader", "reader-secret"); + + List unknownOption = received(backend); + assertEquals(List.of("HELLO", "3", "AUTH"), unknownOption.subList(0, 3)); + assertTrue(unknownOption.get(3).startsWith("floci-refused-"), unknownOption.get(3)); + assertEquals("BOGUS", unknownOption.getLast()); + assertEquals(6, unknownOption.size()); + assertEquals(List.of("HELLO", "4"), received(backend)); + assertEquals(List.of("HELLO", "3", "SETNAME", "bad name"), received(backend)); + assertEquals(attempts, proxy.authenticationAttempts.get(), + "credentials the backend never reaches are not checked"); + } + } + + @Test + void anIamUserCannotSignInAgainInsideATransaction() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + int attempts = proxy.authenticationAttempts.get(); + send(client, "MULTI"); + send(client, "AUTH", "iam-user", "token-2"); + send(client, "HELLO", "3", "AUTH", "iam-user", "token-2"); + send(client, "EXEC"); + send(client, "AUTH", "iam-user", "token-2"); + + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("MULTI"), received(backend), "the backend refuses MULTI inside a transaction"); + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("EXEC"), received(backend)); + assertEquals(List.of("AUTH", "backend-iam-user", "backend-password-iam-user"), received(backend)); + assertEquals(attempts + 1, proxy.authenticationAttempts.get()); + } + } + + @Test + void aPasswordSignInInsideATransactionIsQueuedLikeAnyCommand() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + send(client, "MULTI"); + send(client, "AUTH", "reader", "reader-secret"); + + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("AUTH", "backend-reader", "backend-password-reader"), received(backend)); + } + } + + @Test + void anIamConnectionIsClosed12HoursAfterItSignedIn() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + now.addAndGet(12 * HOUR - 1); + proxy.closeExpiredConnections(); + assertOpen(client, backend); + + now.incrementAndGet(); + proxy.closeExpiredConnections(); + assertEquals(-1, client.getInputStream().read()); + } + } + + @Test + void aConnectionsOwnWaitClosesItOnceItsIamSignInRunsOut() throws Exception { + AtomicInteger readings = new AtomicInteger(); + // The connection reads the time when it signs in, and again when it starts waiting: 12 hours on. + start(true, () -> readings.getAndIncrement() == 0 ? 0 : 12 * HOUR); + try (Socket client = client()) { + send(client, "AUTH", "iam-user", "token-1"); + try (Socket backend = backendServer.accept()) { + assertEquals("+OK", line(client)); + assertEquals(-1, client.getInputStream().read(), "closed while the backend side is still open"); + assertEquals(-1, backend.getInputStream().read()); + } + } + } + + @Test + void signingInAgainWithAFreshTokenGivesTheConnectionAnother12Hours() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + now.addAndGet(11 * HOUR); + send(client, "AUTH", "iam-user", "token-2"); + assertEquals(List.of("AUTH", "backend-iam-user", "backend-password-iam-user"), received(backend)); + + now.addAndGet(2 * HOUR); + proxy.closeExpiredConnections(); + assertOpen(client, backend); + + now.addAndGet(10 * HOUR); + proxy.closeExpiredConnections(); + assertEquals(-1, client.getInputStream().read()); + } + } + + @Test + void aConnectionSignedInWithAPasswordIsNeverClosedForItsAge() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + now.addAndGet(100 * HOUR); + proxy.closeExpiredConnections(); + assertOpen(client, backend); + } + } + + @Test + void anIamConnectionThatSignsInAgainWithAPasswordIsNoLongerClosedForItsAge() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + send(client, "AUTH", "app", "app-secret"); + assertEquals(List.of("AUTH", "backend-app", "backend-password-app"), received(backend)); + + now.addAndGet(13 * HOUR); + proxy.closeExpiredConnections(); + assertOpen(client, backend); + } + } + + @Test + void aSignInInsideATransactionLeavesTheIamLifetimeAsItWas() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + send(client, "MULTI"); + send(client, "AUTH", "app", "app-secret"); + send(client, "AUTH", "iam-user", "token-2"); + send(client, "EXEC"); + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("AUTH", "backend-app", "backend-password-app"), received(backend), + "queued for the backend, which runs it only if EXEC does not abort"); + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("EXEC"), received(backend), "this EXEC aborts: the refused MULTI doomed it"); + + now.addAndGet(12 * HOUR); + proxy.closeExpiredConnections(); + assertEquals(-1, client.getInputStream().read()); + } + } + + @Test + void aTransactionCommandWithArgumentsLeavesTheTransactionAsItWas() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "iam-user", "token-1")) { + send(client, "MULTI", "extra"); + send(client, "AUTH", "iam-user", "token-2"); + assertEquals(List.of("MULTI", "extra"), received(backend)); + assertEquals(List.of("AUTH", "backend-iam-user", "backend-password-iam-user"), received(backend), + "the backend refuses MULTI with an argument, so no transaction began"); + + send(client, "MULTI"); + send(client, "EXEC", "extra"); + send(client, "DISCARD", "extra"); + send(client, "RESET", "extra"); + send(client, "AUTH", "iam-user", "token-2"); + assertEquals(List.of("MULTI"), received(backend)); + assertEquals(List.of("EXEC", "extra"), received(backend)); + assertEquals(List.of("DISCARD", "extra"), received(backend)); + assertEquals(List.of("RESET", "extra"), received(backend)); + assertEquals(List.of("MULTI"), received(backend), "the transaction is still open on the backend"); + } + } + + @Test + void anInlineSignInIsCheckedLikeAnyOther() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + client.getOutputStream().write("auth reader \"reader-secret\"\r\n".getBytes(StandardCharsets.US_ASCII)); + client.getOutputStream().flush(); + + assertEquals(List.of("auth", "backend-reader", "backend-password-reader"), received(backend)); + } + } + + @Test + void aSignInTooLargeToCheckReachesTheBackendAsCredentialsItRefuses() throws Exception { + start(true); + try (Socket client = client(); Socket backend = signIn(client, "app", "app-secret")) { + int attempts = proxy.authenticationAttempts.get(); + send(client, "AUTH", "app", "s".repeat(70_000)); + send(client, "PING"); + + List relayed = received(backend); + assertEquals(3, relayed.size()); + assertTrue(relayed.get(1).startsWith("floci-refused-"), relayed.get(1)); + assertEquals(List.of("PING"), received(backend)); + assertEquals(attempts, proxy.authenticationAttempts.get()); + } + } + + @Test + void aProxyThatDoesNotCheckCredentialsRelaysAuthAsSent() throws Exception { + start(false); + try (Socket client = client()) { + send(client, "PING"); + try (Socket backend = backendServer.accept()) { + backend.setSoTimeout(2_000); + assertEquals(List.of("PING"), received(backend)); + send(client, "AUTH", "app", "app-secret"); + assertEquals(List.of("AUTH", "app", "app-secret"), received(backend)); + } + } + } + + private void start(boolean authRequired) throws IOException { + start(authRequired, now::get); + } + + private void start(boolean authRequired, LongSupplier nanoTime) throws IOException { + backendServer = new ServerSocket(0); + backendServer.setSoTimeout(2_000); + proxy = new TestProxy(backendServer.getLocalPort(), authRequired, nanoTime); + proxy.start(0); + } + + private Socket client() throws IOException { + Socket client = new Socket("127.0.0.1", proxy.localPort()); + client.setSoTimeout(2_000); + return client; + } + + /** Signs the client in and returns the backend connection the proxy opened for it. */ + private Socket signIn(Socket client, String username, String secret) throws IOException { + send(client, "AUTH", username, secret); + Socket backend = backendServer.accept(); + backend.setSoTimeout(2_000); + assertEquals("+OK", line(client)); + return backend; + } + + /** A command and its reply both get through, so neither side has been closed. */ + private static void assertOpen(Socket client, Socket backend) throws IOException { + send(client, "PING"); + assertEquals(List.of("PING"), received(backend)); + reply(backend, "+PONG\r\n"); + assertEquals("+PONG", line(client)); + } + + private static void send(Socket socket, String... arguments) throws IOException { + socket.getOutputStream().write(ClientCommandRelay.encode(List.of(arguments))); + socket.getOutputStream().flush(); + } + + private static void reply(Socket backend, String reply) throws IOException { + backend.getOutputStream().write(reply.getBytes(StandardCharsets.US_ASCII)); + backend.getOutputStream().flush(); + } + + private static List received(Socket backend) throws IOException { + return List.of(new RespReader(backend.getInputStream()).readCommand()); + } + + private static String line(Socket client) throws IOException { + InputStream input = client.getInputStream(); + ByteArrayOutputStream line = new ByteArrayOutputStream(); + int value; + while ((value = input.read()) != -1 && value != '\r') { + line.write(value); + } + input.read(); + return line.toString(StandardCharsets.UTF_8); + } + + private static final class TestProxy extends AbstractRedisAuthProxy { + private final boolean authRequired; + private final AtomicInteger authenticationAttempts = new AtomicInteger(); + + private TestProxy(int backendPort, boolean authRequired, LongSupplier nanoTime) { + super(Logger.getLogger(TestProxy.class), "test", "test", "reauthentication", "127.0.0.1", + backendPort, 2_000, nanoTime); + this.authRequired = authRequired; + } + + @Override + protected boolean authRequired() { + return authRequired; + } + + @Override + protected boolean authenticate(String username, String password) { + authenticationAttempts.incrementAndGet(); + return SECRETS.getOrDefault(username == null ? "default" : username, List.of()).contains(password); + } + + @Override + protected boolean signsInWithIam(String username) { + return "iam-user".equals(username); + } + + @Override + protected List backendCredentials(String username) { + return List.of("backend-" + username, "backend-password-" + username); + } + + @Override + protected void closeQuietly(Socket socket) { + try { + socket.close(); + } catch (IOException ignored) { + // The peer may already have closed the socket. + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelayTest.java b/src/test/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelayTest.java new file mode 100644 index 0000000000..001a55c94f --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/proxy/ClientCommandRelayTest.java @@ -0,0 +1,247 @@ +package io.floci.aws.services.elasticache.proxy; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.function.UnaryOperator; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ClientCommandRelayTest { + + @Test + void ordinaryCommandsPassThroughByteForByte() throws Exception { + byte[] value = new byte[20_000]; + for (int index = 0; index < value.length; index++) { + value[index] = (byte) index; + } + byte[] input = concat(array("SET".getBytes(StandardCharsets.US_ASCII), + "binary".getBytes(StandardCharsets.US_ASCII), value), + bytes("PING\r\n"), bytes("*0\r\n"), command("GET", "binary")); + Recording commands = new Recording(command -> command); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(List.of("SET", "PING", "GET"), commands.asked); + assertEquals(List.of(), commands.rewritten); + } + + @Test + void aCommandTheProxyAsksForIsHandedOverAndRelayedAsRewritten() throws Exception { + Recording commands = new Recording(command -> List.of("AUTH", "backend-user", "backend-password")); + + byte[] relayed = relay(concat(command("AUTH", "app", "client-secret"), command("PING")), commands); + + assertArrayEquals(concat(command("AUTH", "backend-user", "backend-password"), command("PING")), relayed); + assertEquals(List.of(List.of("AUTH", "app", "client-secret")), commands.rewritten); + } + + @Test + void aCommandHandedBackUnchangedKeepsTheBytesTheClientSent() throws Exception { + byte[] input = array(bytes("HELLO"), bytes("3"), bytes("SETNAME"), new byte[]{(byte) 0xff, 'x'}); + Recording commands = new Recording(command -> command); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(1, commands.rewritten.size()); + } + + @Test + void aWantedCommandTooLargeToHoldIsDroppedForTheProxysReplacement() throws Exception { + byte[] input = concat(command("AUTH", "app", "x".repeat(70_000), "trailing"), command("PING")); + Recording commands = new Recording(command -> List.of("AUTH", "rewritten", "rewritten")); + + byte[] relayed = relay(input, commands); + + assertArrayEquals(concat(command("AUTH", "in-place-of", "AUTH"), command("PING")), relayed); + assertEquals(List.of(), commands.rewritten); + } + + @Test + void anInlineCommandTheProxyWantsIsHandedOverAsValkeySplitsIt() throws Exception { + byte[] input = concat(bytes("auth app \"client \\\"secret\\x21\" 'it\\'s'\r\n"), command("PING")); + Recording commands = new Recording(command -> List.of("AUTH", "backend-user", "backend-password")); + + byte[] relayed = relay(input, commands); + + assertEquals(List.of(List.of("auth", "app", "client \"secret!", "it's")), commands.rewritten); + assertArrayEquals(concat(command("AUTH", "backend-user", "backend-password"), command("PING")), relayed); + } + + @Test + void anInlineCommandHandedBackUnchangedKeepsItsLine() throws Exception { + byte[] input = concat(bytes("HELLO 3\n"), bytes("MULTI\r\n"), bytes("\r\n")); + Recording commands = new Recording(command -> command); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(List.of(List.of("HELLO", "3"), List.of("MULTI")), commands.rewritten); + } + + @Test + void anInlineLineTheBackendCannotSplitIsPassedOnAsItCame() throws Exception { + byte[] input = concat(bytes("AUTH app \"unbalanced\r\n"), bytes("AUTH app \"closed\"early\r\n")); + Recording commands = new Recording(command -> List.of("AUTH", "rewritten", "rewritten")); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(List.of(), commands.rewritten); + } + + @Test + void anInlineLineTooLongToHoldIsDroppedWhenWantedAndPassedOnOtherwise() throws Exception { + byte[] longSet = bytes("SET key " + "x".repeat(70_000) + "\r\n"); + byte[] input = concat(bytes("AUTH app " + "x".repeat(70_000) + "\r\n"), longSet, command("PING")); + Recording commands = new Recording(command -> List.of("AUTH", "rewritten", "rewritten")); + + byte[] relayed = relay(input, commands); + + assertArrayEquals(concat(command("AUTH", "in-place-of", "AUTH"), longSet, command("PING")), relayed); + assertEquals(List.of(), commands.rewritten); + } + + @Test + void aMalformedArrayLeavesTheRestOfTheConnectionToAPlainRelay() throws Exception { + byte[] input = concat(bytes("*1\r\n:5\r\n"), command("AUTH", "app", "client-secret")); + Recording commands = new Recording(command -> List.of("AUTH", "rewritten", "rewritten")); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(List.of(), commands.asked); + } + + @Test + void anArgumentWithoutItsLineEndIsPassedOnAsItCame() throws Exception { + byte[] input = concat(bytes("*2\r\n$4\r\nAUTH\r\n$2\r\npwXX"), command("AUTH", "app", "client-secret")); + Recording commands = new Recording(command -> List.of("AUTH", "rewritten", "rewritten")); + + assertArrayEquals(input, relay(input, commands)); + assertEquals(List.of("AUTH"), commands.asked); + assertEquals(List.of(), commands.rewritten); + } + + @Test + void aClientThatStopsMidCommandHasWhatItSentPassedOn() throws Exception { + byte[] input = bytes("*2\r\n$3\r\nGET\r\n$10\r\nabc"); + + assertArrayEquals(input, relay(input, new Recording(command -> command))); + } + + @Test + void everythingReadIsPassedOnBeforeWaitingForMore() throws Exception { + byte[] first = concat(command("GET", "a"), command("AUTH", "app", "client-secret")); + Recording commands = new Recording(command -> List.of("AUTH", "backend-user", "backend-password")); + RecordingOutput output = new RecordingOutput(); + List flushedBeforeEachRead = new ArrayList<>(); + InputStream chunks = new InputStream() { + private final List remaining = new ArrayList<>(List.of(first, command("PING"))); + + @Override + public int read() { + throw new UnsupportedOperationException(); + } + + @Override + public int read(byte[] buffer) { + flushedBeforeEachRead.add(output.flushed()); + if (remaining.isEmpty()) { + return -1; + } + byte[] chunk = remaining.removeFirst(); + System.arraycopy(chunk, 0, buffer, 0, chunk.length); + return chunk.length; + } + }; + + new ClientCommandRelay(chunks, output, commands).run(); + + assertEquals("", flushedBeforeEachRead.get(0)); + assertEquals(text(concat(command("GET", "a"), command("AUTH", "backend-user", "backend-password"))), + flushedBeforeEachRead.get(1), "a backend must not wait for commands the proxy already holds"); + assertTrue(flushedBeforeEachRead.get(2).endsWith(text(command("PING")))); + } + + private static byte[] relay(byte[] input, ClientCommandRelay.Commands commands) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + new ClientCommandRelay(new ByteArrayInputStream(input), output, commands).run(); + return output.toByteArray(); + } + + private static byte[] command(String... arguments) { + return array(Arrays.stream(arguments).map(ClientCommandRelayTest::bytes).toArray(byte[][]::new)); + } + + private static byte[] array(byte[]... arguments) { + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + encoded.writeBytes(bytes("*" + arguments.length + "\r\n")); + for (byte[] argument : arguments) { + encoded.writeBytes(bytes("$" + argument.length + "\r\n")); + encoded.writeBytes(argument); + encoded.writeBytes(bytes("\r\n")); + } + return encoded.toByteArray(); + } + + private static byte[] concat(byte[]... parts) { + ByteArrayOutputStream joined = new ByteArrayOutputStream(); + for (byte[] part : parts) { + joined.writeBytes(part); + } + return joined.toByteArray(); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + /** Wants AUTH, HELLO and MULTI, whatever their case, and records what it was asked. */ + private static final class Recording implements ClientCommandRelay.Commands { + private final UnaryOperator> rewrite; + private final List asked = new ArrayList<>(); + private final List> rewritten = new ArrayList<>(); + + private Recording(UnaryOperator> rewrite) { + this.rewrite = rewrite; + } + + @Override + public boolean wants(String name) { + asked.add(name); + return List.of("AUTH", "HELLO", "MULTI").contains(name.toUpperCase(Locale.ROOT)); + } + + @Override + public List rewrite(List command) { + rewritten.add(List.copyOf(command)); + return rewrite.apply(command); + } + + @Override + public List inPlaceOfTooLarge(String name) { + return List.of("AUTH", "in-place-of", name); + } + } + + /** Keeps apart what has been flushed from what is only written. */ + private static final class RecordingOutput extends ByteArrayOutputStream { + private int flushedLength; + + @Override + public void flush() { + flushedLength = size(); + } + + String flushed() { + return new String(toByteArray(), 0, flushedLength, StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java index db411218ef..04e3a65a4c 100644 --- a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAclProxyIntegrationTest.java @@ -43,6 +43,9 @@ import static org.mockito.Mockito.mock; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ElastiCacheAclProxyIntegrationTest { + /** A second user, whose rules let it check keys exist but not write them. */ + private static final String AUDITOR_ACCESS = "on ~* &* -@all +ping +exists"; + @TempDir static Path directory; @@ -115,7 +118,8 @@ class ElastiCacheAclProxyIntegrationTest { new ElastiCacheAuthProxy.PasswordValidator() { @Override public boolean validatePassword(String username, String password) { - return "subscriber".equals(username) && "synthetic-password".equals(password); + return "subscriber".equals(username) && "synthetic-password".equals(password) + || "auditor".equals(username) && "auditor-password".equals(password); } @Override @@ -123,11 +127,16 @@ class ElastiCacheAclProxyIntegrationTest { @Override public AuthMode memberAuthMode(String username) { + if ("auditor".equals(username)) { + return AuthMode.PASSWORD; + } return "subscriber".equals(username) ? memberMode.get() : null; } @Override - public String accessString(String username) { return access.get(); } + public String accessString(String username) { + return "auditor".equals(username) ? AUDITOR_ACCESS : access.get(); + } @Override public TransitEncryption transitEncryption() { return TransitEncryption.REQUIRED; } @@ -210,6 +219,52 @@ class ElastiCacheAclProxyIntegrationTest { } } + @Test + void aSessionThatSignsInAgainRunsAsItsNewUserAndKeepsItsUserWhenRefused() throws Exception { + memberMode.set(AuthMode.PASSWORD); + access.set("on ~* &* -@all +ping +set"); + try (Socket session = connect(proxy.localPort(), trust)) { + assertEquals("+OK", command(session, "AUTH", "subscriber", "synthetic-password")); + assertEquals("+OK", command(session, "SET", "shared:key", "written")); + assertTrue(command(session, "EXISTS", "shared:key").startsWith("-NOPERM")); + + assertEquals("+OK", command(session, "AUTH", "auditor", "auditor-password")); + assertEquals(":1", command(session, "EXISTS", "shared:key")); + assertTrue(command(session, "SET", "shared:key", "overwritten").startsWith("-NOPERM")); + + assertTrue(command(session, "AUTH", "subscriber", "wrong-password").startsWith("-WRONGPASS")); + assertEquals(":1", command(session, "EXISTS", "shared:key"), "a refused sign-in keeps the session's user"); + + assertEquals("+OK", command(session, "AUTH", "subscriber", "synthetic-password")); + assertEquals("+OK", command(session, "SET", "shared:key", "rewritten")); + assertTrue(command(session, "HELLO", "2", "AUTH", "auditor", "auditor-password").startsWith("*")); + } + } + + @Test + void anIamSessionCannotSignInAgainInsideATransaction() throws Exception { + memberMode.set(AuthMode.IAM); + access.set("on ~* &* +@all"); + String token = SigV4TokenTestHelper.createElastiCacheToken( + "acl-test", "subscriber", "AKIDCACHE", "secret-cache", Instant.now().minusSeconds(60), 900); + try (Socket session = connect(proxy.localPort(), trust)) { + assertEquals("+OK", command(session, "AUTH", "subscriber", token)); + assertEquals("+OK", command(session, "AUTH", "subscriber", token), "a fresh token is taken outside one"); + + assertEquals("+OK", command(session, "MULTI")); + assertTrue(command(session, "AUTH", "subscriber", token) + .startsWith("-ERR Command not allowed inside a transaction")); + assertEquals("+QUEUED", command(session, "SET", "transaction:key", "value")); + assertTrue(command(session, "EXEC").startsWith("-EXECABORT")); + assertEquals(":0", command(session, "EXISTS", "transaction:key")); + + assertEquals("+OK", command(session, "MULTI")); + assertEquals("+QUEUED", command(session, "AUTH", "auditor", "auditor-password"), + "a password sign-in is queued like any command"); + assertEquals("*1", command(session, "EXEC")); + } + } + @AfterAll void stopBackend() throws Exception { try { diff --git a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxyTest.java b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxyTest.java index da02f36c1a..2caedc9cdb 100644 --- a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxyTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheAuthProxyTest.java @@ -26,6 +26,46 @@ class ElastiCacheAuthProxyTest { verifyNoInteractions(backend); } + @Test + void aUserSignsInWithIamWhenItsAuthenticationModeIsIam() { + ElastiCacheAuthProxy.PasswordValidator members = mock(ElastiCacheAuthProxy.PasswordValidator.class); + when(members.hasMembers()).thenReturn(true); + when(members.memberAuthMode("iam-user")).thenReturn(AuthMode.IAM); + when(members.memberAuthMode("app")).thenReturn(AuthMode.PASSWORD); + when(members.memberAuthMode("default")).thenReturn(AuthMode.NO_AUTH); + ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-users", AuthMode.PASSWORD, "127.0.0.1", 6379, + members, mock(SigV4Validator.class)); + + assertTrue(proxy.signsInWithIam("iam-user")); + assertFalse(proxy.signsInWithIam("app")); + assertFalse(proxy.signsInWithIam(null), "AUTH signs in as the default user"); + assertFalse(proxy.signsInWithIam("stranger")); + + ElastiCacheAuthProxy.PasswordValidator withoutMembers = mock(ElastiCacheAuthProxy.PasswordValidator.class); + assertTrue(new ElastiCacheAuthProxy("grp-iam", AuthMode.IAM, "127.0.0.1", 6379, withoutMembers, + mock(SigV4Validator.class)).signsInWithIam(null)); + assertFalse(new ElastiCacheAuthProxy("grp-token", AuthMode.PASSWORD, "127.0.0.1", 6379, withoutMembers, + mock(SigV4Validator.class)).signsInWithIam(null)); + } + + @Test + void credentialsAreCheckedAfterSignInWheneverTheCacheHasUsersOrAnAuthToken() { + ElastiCacheAuthProxy.PasswordValidator openDefault = mock(ElastiCacheAuthProxy.PasswordValidator.class); + when(openDefault.hasMembers()).thenReturn(true); + when(openDefault.memberAuthMode("default")).thenReturn(AuthMode.NO_AUTH); + ElastiCacheAuthProxy usersWithOpenDefault = new ElastiCacheAuthProxy("grp-open-default", AuthMode.NO_AUTH, + "127.0.0.1", 6379, openDefault, mock(SigV4Validator.class)); + assertFalse(usersWithOpenDefault.authRequired()); + assertTrue(usersWithOpenDefault.checksCredentials(), + "a session of the open default user can still sign in as another user"); + + ElastiCacheAuthProxy.PasswordValidator withoutMembers = mock(ElastiCacheAuthProxy.PasswordValidator.class); + assertTrue(new ElastiCacheAuthProxy("grp-token", AuthMode.PASSWORD, "127.0.0.1", 6379, withoutMembers, + mock(SigV4Validator.class)).checksCredentials()); + assertFalse(new ElastiCacheAuthProxy("grp-open", AuthMode.NO_AUTH, "127.0.0.1", 6379, withoutMembers, + mock(SigV4Validator.class)).checksCredentials(), "a cache without auth answers AUTH itself"); + } + @Test void authModeIsReadFromTheCacheOnEachConnection() { AtomicReference cacheAuthMode = new AtomicReference<>(); diff --git a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAclTest.java b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAclTest.java index d4ce7292cb..1455fec7bb 100644 --- a/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAclTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/proxy/ElastiCacheBackendAclTest.java @@ -75,6 +75,83 @@ class ElastiCacheBackendAclTest { assertEquals(backendUser, commands.get(afterLogin + 1).get(2)); } + @Test + void aSessionThatSignsInAgainGetsItsNewUsersCredentialsOverAConnectionOfTheirOwn() throws Exception { + login("app", "on ~app:* -@all +get"); + int connections = server.connections(); + int afterLogin = commands.size(); + + List credentials = acl.credentials("localhost", server.port(), "reader", + () -> "on ~reports:* -@all +get"); + + assertEquals(connections + 1, server.connections()); + assertEquals(List.of("reader", passwordOf("reader")), credentials); + List> sent = commands.subList(afterLogin, commands.size()); + assertTrue(sent.get(0).get(1).startsWith("floci-admin-"), "the rules are installed as the administrator"); + assertEquals(List.of("ACL", "SETUSER", "reader", "reset", "on", "~reports:*", "-@all", "+get"), + sent.get(1).subList(0, 8)); + assertEquals(List.of("AUTH", "reader", passwordOf("reader")), sent.get(2)); + } + + @Test + void theDefaultUserSignsInAgainAsItsPrivateBackendUser() throws Exception { + login("app", "on ~app:* -@all +get"); + + List credentials = acl.credentials("localhost", server.port(), "default", () -> "on ~* +@all"); + + assertTrue(credentials.get(0).startsWith("floci-default-"), "never the backend's own default user"); + assertEquals(passwordOf(credentials.get(0)), credentials.get(1)); + } + + @Test + void aUserWhoseRulesTheBackendRefusesGetsNoCredentials() throws Exception { + login("app", "on ~app:* -@all +get"); + refuseNextCommands = true; + + assertThrows(IOException.class, () -> acl.credentials("localhost", server.port(), "reader", + () -> "on ~reports:* -@all +get")); + } + + @Test + void aCacheWithUsersSwitchesASessionToTheBackendUserOfItsNewUser() throws Exception { + ElastiCacheAuthProxy.PasswordValidator validator = mock(ElastiCacheAuthProxy.PasswordValidator.class); + when(validator.hasMembers()).thenReturn(true); + when(validator.accessString("reader")).thenReturn("on ~reports:* -@all +get"); + ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-0001", AuthMode.PASSWORD, "localhost", + server.port(), validator, mock(SigV4Validator.class)); + + List credentials = proxy.backendCredentials("reader"); + + assertEquals("reader", credentials.get(0)); + assertEquals(List.of("ACL", "SETUSER", "reader", "reset", "on", "~reports:*", "-@all", "+get"), + setUserOf("reader").subList(0, 8)); + assertEquals(passwordOf("reader"), credentials.get(1)); + } + + @Test + void aCacheWithoutUsersSwitchesASessionToTheBackendsOwnDefaultUser() throws Exception { + ElastiCacheAuthProxy.PasswordValidator validator = mock(ElastiCacheAuthProxy.PasswordValidator.class); + ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy("grp-0001", AuthMode.PASSWORD, "localhost", + server.port(), validator, mock(SigV4Validator.class)); + + List credentials = proxy.backendCredentials(null); + + assertEquals("default", credentials.get(0), "an auth-token cache's backend has no users of its own"); + assertEquals(List.of(), commands); + } + + @Test + void aClusterNodeReadiesItsReplicationBeforeASessionSwitchesUser() throws Exception { + ElastiCacheAuthProxy.PasswordValidator validator = clusterValidator(true); + ElastiCacheAuthProxy proxy = clusterNodeProxy(validator); + + proxy.backendCredentials("app"); + + InOrder order = inOrder(validator); + order.verify(validator).prepareClusterReplication(); + order.verify(validator, atLeastOnce()).accessString("app"); + } + @Test void nothingIsSentBeforeTheBackendIsSetUp() throws Exception { acl.reapply("localhost", server.port(), "app", "on ~* +@all"); diff --git a/src/test/java/io/floci/aws/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/floci/aws/services/memorydb/MemoryDbServiceTest.java index 9675d76117..201fe1f31f 100644 --- a/src/test/java/io/floci/aws/services/memorydb/MemoryDbServiceTest.java +++ b/src/test/java/io/floci/aws/services/memorydb/MemoryDbServiceTest.java @@ -316,6 +316,64 @@ class MemoryDbServiceTest { assertFalse(startedProxyValidator().enforcesAccessStrings()); } + @Test + void theProxyOfAClusterKnowsWhichOfItsAclUsersSignInWithIam() { + User iamSpec = new User(); + iamSpec.setName("iam-user"); + iamSpec.setAuthMode(AuthMode.IAM); + iamSpec.setAccessString("on ~* +@all"); + service.createUser(iamSpec, "us-east-1"); + User passwordSpec = new User(); + passwordSpec.setName("reader"); + passwordSpec.setAuthMode(AuthMode.PASSWORD); + passwordSpec.setPasswords(List.of("s3cret")); + passwordSpec.setAccessString("on ~app:* -@all +get"); + service.createUser(passwordSpec, "us-east-1"); + Acl aclSpec = new Acl(); + aclSpec.setName("mixed-acl"); + aclSpec.setUserNames(List.of("default", "iam-user", "reader")); + service.createAcl(aclSpec, "us-east-1"); + Cluster spec = new Cluster(); + spec.setName("mixed"); + spec.setAclName("mixed-acl"); + + service.createCluster(spec, "us-east-1"); + + MemoryDbAuthProxy.AuthValidator validator = startedProxyValidator(); + assertTrue(validator.signsInWithIam("iam-user")); + assertFalse(validator.signsInWithIam("reader")); + assertFalse(validator.signsInWithIam(null), "the default user signs in with a password or none"); + assertFalse(validator.signsInWithIam("stranger"), "a user the ACL does not hold is no IAM user of it"); + } + + @Test + void theBuiltInDefaultUserSignsInOnlyOnTheOpenAccessAcl() { + User userSpec = new User(); + userSpec.setName("reader"); + userSpec.setAuthMode(AuthMode.PASSWORD); + userSpec.setPasswords(List.of("s3cret")); + userSpec.setAccessString("on ~app:* -@all +get"); + service.createUser(userSpec, "us-east-1"); + Acl aclSpec = new Acl(); + aclSpec.setName("reader-acl"); + aclSpec.setUserNames(List.of("default", "reader")); + service.createAcl(aclSpec, "us-east-1"); + Cluster restricted = new Cluster(); + restricted.setName("restricted"); + restricted.setAclName("reader-acl"); + service.createCluster(restricted, "us-east-1"); + Cluster open = new Cluster(); + open.setName("open-default"); + open.setAclName("open-access"); + service.createCluster(open, "us-east-1"); + + assertFalse(service.authenticate("restricted", "default", "anything"), + "a client must not escape the ACL's access strings as the unrestricted default user"); + assertFalse(service.authenticate("restricted", null, "anything")); + assertTrue(service.authenticate("restricted", "reader", "s3cret")); + assertTrue(service.authenticate("open-default", "default", "anything")); + } + private MemoryDbAuthProxy.AuthValidator startedProxyValidator() { ArgumentCaptor validator = ArgumentCaptor.forClass(MemoryDbAuthProxy.AuthValidator.class); diff --git a/src/test/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxyTest.java b/src/test/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxyTest.java index 4e559fc72f..1cc66712dd 100644 --- a/src/test/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxyTest.java +++ b/src/test/java/io/floci/aws/services/memorydb/proxy/MemoryDbAuthProxyTest.java @@ -11,6 +11,7 @@ import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -74,6 +75,66 @@ class MemoryDbAuthProxyTest { verifyNoInteractions(socket); } + @Test + void aSessionOfAClusterWithAnAclOfItsOwnSignsInAgainAsItsNewUsersBackendUser() throws Exception { + MemoryDbAuthProxy proxy = proxy(true, Map.of("reader", "on ~app:* -@all +get")); + + List credentials = proxy.backendCredentials("reader"); + + List rules = backend.commands().get(3); + assertEquals(List.of("ACL", "SETUSER", "reader", "reset", "on", "~app:*", "-@all", "+get"), rules.subList(0, 8)); + assertEquals(List.of("reader", rules.get(rules.indexOf("resetpass") + 1).substring(1)), credentials); + } + + @Test + void aSessionOfAnOpenAccessClusterSignsInAgainAsTheBackendsOwnDefaultUser() throws Exception { + MemoryDbAuthProxy proxy = proxy(false, Map.of()); + + assertEquals("default", proxy.backendCredentials("reader").get(0)); + assertEquals(List.of(), backend.commands()); + } + + @Test + void credentialsAreCheckedAfterSignInUnlessTheClusterIsOpenAccess() { + assertTrue(proxy(true, Map.of()).checksCredentials()); + MemoryDbAuthProxy.AuthValidator passwordless = (username, secret) -> true; + assertFalse(new MemoryDbAuthProxy("open", false, "localhost", backend.port(), passwordless) + .checksCredentials()); + MemoryDbAuthProxy ownAclWithoutPasswords = new MemoryDbAuthProxy("own", false, "localhost", backend.port(), + new MemoryDbAuthProxy.AuthValidator() { + @Override + public boolean authenticate(String username, String secret) { + return true; + } + + @Override + public boolean enforcesAccessStrings() { + return true; + } + }); + assertTrue(ownAclWithoutPasswords.checksCredentials(), + "a user of an ACL without passwords can still sign in again as another user"); + } + + @Test + void theAclDecidesWhichUsersSignInWithIam() { + MemoryDbAuthProxy proxy = new MemoryDbAuthProxy("cluster", true, "localhost", backend.port(), + new MemoryDbAuthProxy.AuthValidator() { + @Override + public boolean authenticate(String username, String secret) { + return true; + } + + @Override + public boolean signsInWithIam(String username) { + return "iam-user".equals(username); + } + }); + + assertTrue(proxy.signsInWithIam("iam-user")); + assertFalse(proxy.signsInWithIam("reader")); + } + private void initialize(MemoryDbAuthProxy proxy, String username) throws IOException { try (Socket socket = new Socket("localhost", backend.port())) { proxy.initializeBackend(socket, username);