fix(elasticache,memorydb): check AUTH sent after sign-in and close IAM connections after 12 hours (#8704)

Once a client had signed in, the auth proxy relayed its bytes blind, so a later AUTH or HELLO reached
the backend with the client's own credentials, which the backend refuses. A client refreshing its IAM
token or switching user got WRONGPASS where AWS signs it in. Where the proxy checks credentials, it now
keeps reading the client's commands and checks a later AUTH or HELLO as at sign-in. Accepted
credentials are relayed as their user's private backend credentials and refused ones as credentials
the backend refuses, so the backend still answers every command and the replies keep their order. The
client's password or token never reaches the backend, and every other command passes byte for byte.

A connection signed in with an IAM token is now closed 12 hours after it signed in, and a new token
gives it another 12 hours, as AWS documents for ElastiCache and MemoryDB. An IAM user's AUTH or HELLO
inside MULTI is refused, since AWS does not support IAM re-authentication inside a transaction.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 05:06:39 -04:00
1 parent da8cc6fb1b
commit 8b2d21498b
15 files changed
+1914 -33

No files matched your search

@@ -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<String, List<String>> 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<String> 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<String> 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<String> 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<String> 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<String> 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.
}
}
}
}
@@ -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<String> flushedBeforeEachRead = new ArrayList<>();
InputStream chunks = new InputStream() {
private final List<byte[]> 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<List<String>> rewrite;
private final List<String> asked = new ArrayList<>();
private final List<List<String>> rewritten = new ArrayList<>();
private Recording(UnaryOperator<List<String>> 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<String> rewrite(List<String> command) {
rewritten.add(List.copyOf(command));
return rewrite.apply(command);
}
@Override
public List<String> 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);
}
}
}
@@ -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 {
@@ -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 <password> 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<AuthMode> cacheAuthMode = new AtomicReference<>();
@@ -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<String> credentials = acl.credentials("localhost", server.port(), "reader",
() -> "on ~reports:* -@all +get");
assertEquals(connections + 1, server.connections());
assertEquals(List.of("reader", passwordOf("reader")), credentials);
List<List<String>> 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<String> 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<String> 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<String> 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");
@@ -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<MemoryDbAuthProxy.AuthValidator> validator =
ArgumentCaptor.forClass(MemoryDbAuthProxy.AuthValidator.class);
@@ -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<String> credentials = proxy.backendCredentials("reader");
List<String> 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);