mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
da8cc6fb1b
commit
8b2d21498b
15 files changed
+1914
-33
No files matched your search
+373
-14
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<Socket> handshakingClients = ConcurrentHashMap.newKeySet();
|
||||
private final Set<Socket> unencryptedClients = ConcurrentHashMap.newKeySet();
|
||||
private final Set<Connection> 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 <password>} 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<String> 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.
|
||||
*
|
||||
* <p>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<String> 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<String> rewrite(List<String> 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<String> 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<String> inPlaceOfTooLarge(String name) {
|
||||
if (isSignIn(name)) {
|
||||
List<String> 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<String> 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<String> 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<String> arguments, List<Integer> credentials, boolean reachesSignIn) {
|
||||
|
||||
/** Null for an {@code AUTH} without arguments, which carries no credentials. */
|
||||
static SignIn auth(List<String> command) {
|
||||
return switch (command.size()) {
|
||||
case 1 -> null;
|
||||
// AUTH <password> 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<String> 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<String> command) {
|
||||
List<Integer> 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<String> relayed(List<String> replacement) {
|
||||
List<String> relayed = new ArrayList<>(arguments);
|
||||
for (int index : credentials) {
|
||||
relayed.set(index, replacement.get(0));
|
||||
relayed.set(index + 1, replacement.get(1));
|
||||
}
|
||||
return relayed;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> rewrite(List<String> command);
|
||||
|
||||
/** The command to pass on in place of a wanted one too large to hold, whose bytes are dropped. */
|
||||
List<String> 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<String> 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<String> 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<String> command, ByteArrayOutputStream held) throws IOException {
|
||||
List<String> 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<String> splitInline(byte[] line, int length) {
|
||||
List<String> 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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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)) {
|
||||
|
||||
@@ -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<String> credentials(String backendHost, int backendPort, String username,
|
||||
Supplier<String> 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
|
||||
|
||||
@@ -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<User> 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));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
*
|
||||
* <p>Whether authentication is required at all is decided up front from the cluster's
|
||||
* ACL: a cluster bound to {@code open-access} (or any ACL whose users require no
|
||||
* password) is created with {@code 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.
|
||||
*
|
||||
* <p>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<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user