fix(rds): bind PostgreSQL IAM tokens to the published endpoint and authorize rds-db:connect (#4100)

* fix(rds): bind PostgreSQL IAM tokens to the published endpoint

The PostgreSQL proxy validated IAM auth tokens with the two-argument
validator, so a token generated for any host, port or region was
accepted as long as the signature and DBUser matched. The MySQL proxy
already checked the token against the endpoint it publishes. Thread the
same binding into the PostgreSQL handler and validate against it.

* fix(rds): carry account and resource ids in the proxy binding

RdsService now builds the proxy binding itself at every relay start
(instances, clusters, RDS Proxy relays and restart restores) from the
published endpoint, port, region, account and DbiResourceId or
DbClusterResourceId, so the auth proxy has everything rds-db:connect
is scoped to. The convenience startProxy overload that re-derived the
region from the relay key is gone along with it.

* feat(rds): authorize rds-db:connect when IAM enforcement is on

After the token signature checks out, the auth proxy now asks IAM whether
the token's principal may perform rds-db:connect on
arn:aws:rds-db:<region>:<account>:dbuser:<resource-id>/<db-user>, the
same check AWS runs. It only applies when services.iam.enforcement-enabled
is on; a caller IAM does not know keeps the filter's bypass. The client
still sees the engine's generic authentication failure, and the denial is
logged in AWS's wording so the cause is visible server-side.

* refactor(rds): rename RdsMysqlBinding to RdsProxyBinding

Both engines, Aurora clusters and RDS Proxy relays now validate IAM
tokens against it, so the MySQL-specific name was misleading.

* docs(rds): describe IAM token endpoint binding and rds-db:connect

* test(rds): cover a replayed IAM token in the JDBC compat suite

* fix(rds): accept IAM tokens generated for the loopback name of the endpoint

Floci advertises the name containers reach it by (host.docker.internal
natively, its own address in Docker), while a client on the host connects
to the same proxy over the loopback interface and generates its token for
localhost or 127.0.0.1. Binding tokens strictly to the advertised host
therefore refused every native client; the published port still has to
match, so a token for another instance on the same host is still refused.

The compatibility workflow sets FLOCI_SERVICES_RDS_ENDPOINT_HOST=floci as
it already does for Redshift, so the tests' tokens name what the
containerised Floci publishes.

* feat(rds): make the PostgreSQL IAM token endpoint binding opt-in

Refusing a PostgreSQL token generated for another hostname, port or
region matches RDS but breaks clients whose tokens name a different
host than the endpoint publishes, so the check now sits behind
services.rds.iam-token-endpoint-binding
(FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING), off by default.
MySQL and MariaDB keep requiring the endpoint as before, and the
rds-db:connect check still runs whenever IAM enforcement is on.
The compatibility workflow turns the flag on so the replayed-token
case stays covered.

* fix(rds): refuse an IAM token that reaches the validator without a binding

Every proxy publishes a binding, so a token without one has nothing to
be checked against; validating its signature alone was a fail-open
path. The signature-only validate(token, user) overload and the MySQL
handleAuth overloads that passed no binding are removed; production
only ever used the ones that pass it.

* fix(rds): sanitize the rds-db resource named in the refused connection warning

The database user is part of that resource and comes straight from the
client's startup message, so it is stripped of control characters like
the other client-controlled values in the warning.

* docs(rds): call a refused IAM token the engine's ordinary authentication failure

The exact message differs per engine, and RDS PostgreSQL words it
differently from Floci's handler today, so the docs no longer promise
one wording.

* docs(rds): move the IAM token binding row into the RDS variables table

The row had landed above the page heading, where it rendered as a
stray one-row table; it now follows FLOCI_SERVICES_RDS_ENDPOINT_HOST
as it does on the RDS page.

* fix(rds): bind PostgreSQL IAM tokens to the endpoint by default

A stock Floci still accepted a PostgreSQL token generated for another
endpoint, the replay this change set out to close, and PostgreSQL and
MySQL disagreed about it in a way RDS never has. The endpoint check is
now on for every engine. services.rds.iam-token-endpoint-binding
(FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING=false) stays as the
escape hatch for clients that generate tokens for a container name or
DNS alias the endpoint does not publish. The compatibility workflow no
longer needs to turn the check on.

* chore(ci): rerun after a Docker Hub rate limit failed shard 1
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-22 15:49:14 -04:00
1 parent f07b3fd3be
commit 4753428567
22 files changed
+677 -181

No files matched your search

@@ -1521,6 +1521,14 @@ public interface EmulatorConfig {
/** Hostname advertised for RDS endpoints. Uses published Docker ports when configured. */
Optional<String> endpointHost();
/** Whether a PostgreSQL IAM auth token must have been generated for the endpoint the
* instance publishes (hostname, port and region), as on RDS. On by default; turn it off
* when clients generate tokens for a container name or DNS alias the endpoint does not
* publish. MySQL and MariaDB always require it.
* Env: FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING */
@WithDefault("true")
boolean iamTokenEndpointBinding();
/** Docker network to attach DB containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
@@ -48,6 +48,7 @@ import io.github.hectorvent.floci.services.rds.model.GlobalCluster;
import io.github.hectorvent.floci.services.rds.model.GlobalClusterMember;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyBinding;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -757,7 +758,9 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEndpoint().address(),
masterUsername, masterPassword, dbName,
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw));
accountId, instanceRegion, id, user, pw),
proxyBinding(engine, instance.getEndpoint().address(), proxyPort,
instanceRegion, accountId, instance.getDbiResourceId()));
} catch (RuntimeException | Error e) {
try {
deleteInstanceForScope(accountId, effectiveRegion, id);
@@ -2733,7 +2736,9 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getProxyPort(), instance.getContainerHost(), instance.getContainerPort(),
instance.getEndpoint().address(),
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(accountId, instanceRegion, id, user, pw));
(user, pw) -> validateDbPasswordForScope(accountId, instanceRegion, id, user, pw),
proxyBinding(instance.getEngine(), instance.getEndpoint().address(), instance.getProxyPort(),
instanceRegion, accountId, instance.getDbiResourceId()));
}
}
@@ -2821,7 +2826,9 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getContainerHost(), cluster.getContainerPort(), member.getEndpoint().address(),
member.getMasterUsername() != null ? member.getMasterUsername() : "root",
member.getMasterPassword(), member.getDbName(),
(user, pw) -> validateDbPasswordForScope(accountId, memberRegion, memberId, user, pw));
(user, pw) -> validateDbPasswordForScope(accountId, memberRegion, memberId, user, pw),
proxyBinding(member.getEngine(), member.getEndpoint().address(), member.getProxyPort(),
memberRegion, accountId, member.getDbiResourceId()));
}
member.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, effectiveRegion, memberId, member);
@@ -2863,7 +2870,9 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getContainerHost(), cluster.getContainerPort(), member.getEndpoint().address(),
member.getMasterUsername() != null ? member.getMasterUsername() : "root",
member.getMasterPassword(), member.getDbName(),
(user, pw) -> validateDbPasswordForScope(accountId, memberRegion, memberId, user, pw));
(user, pw) -> validateDbPasswordForScope(accountId, memberRegion, memberId, user, pw),
proxyBinding(member.getEngine(), member.getEndpoint().address(), member.getProxyPort(),
memberRegion, accountId, member.getDbiResourceId()));
}
member.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, effectiveRegion, memberId, member);
@@ -2926,7 +2935,9 @@ public class RdsService implements Resettable, ResourceProvider {
handle.getHost(), handle.getPort(), cluster.getEndpoint().address(),
cluster.getMasterUsername() != null ? cluster.getMasterUsername() : "root",
cluster.getMasterPassword(), cluster.getDatabaseName(),
(user, pw) -> validateDbClusterPasswordForScope(accountId, clusterRegion, id, user, pw));
(user, pw) -> validateDbClusterPasswordForScope(accountId, clusterRegion, id, user, pw),
proxyBinding(cluster.getEngine(), cluster.getEndpoint().address(), cluster.getProxyPort(),
clusterRegion, accountId, cluster.getDbClusterResourceId()));
}
}
@@ -2990,7 +3001,9 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEndpoint().address(),
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw));
accountId, instanceRegion, id, user, pw),
proxyBinding(instance.getEngine(), instance.getEndpoint().address(),
instance.getProxyPort(), instanceRegion, accountId, instance.getDbiResourceId()));
} else {
// No backing container: created or last rebooted while no daemon was reachable.
instance = ensureInstanceBackend(id, effectiveRegion);
@@ -3001,6 +3014,20 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
/**
* The binding the proxy validates IAM auth tokens against. As on RDS a token is good for the
* endpoint it was generated for (hostname, port and region); MySQL and MariaDB proxies always
* require that, PostgreSQL proxies unless {@code services.rds.iam-token-endpoint-binding} is
* turned off for clients that generate tokens for a name the endpoint does not publish.
*/
private RdsProxyBinding proxyBinding(DatabaseEngine engine, String advertisedHost, int publishedPort,
String region, String accountId, String resourceId) {
boolean tokensBoundToEndpoint = engine != DatabaseEngine.POSTGRES
|| config.services().rds().iamTokenEndpointBinding();
return new RdsProxyBinding(advertisedHost, publishedPort, region, accountId, resourceId,
tokensBoundToEndpoint);
}
private static boolean hasBackend(String host, int port) {
return host != null && !host.isBlank() && port > 0;
}
@@ -3073,7 +3100,9 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEndpoint().address(),
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw));
accountId, instanceRegion, id, user, pw),
proxyBinding(instance.getEngine(), instance.getEndpoint().address(),
instance.getProxyPort(), instanceRegion, accountId, instance.getDbiResourceId()));
} catch (RuntimeException e) {
stopStartedBackend(started, e);
throw e;
@@ -3125,7 +3154,9 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getEndpoint().address(),
effectiveMasterUser, cluster.getMasterPassword(), cluster.getDatabaseName(),
(user, pw) -> validateDbClusterPasswordForScope(
accountId, clusterRegion, id, user, pw));
accountId, clusterRegion, id, user, pw),
proxyBinding(cluster.getEngine(), cluster.getEndpoint().address(),
cluster.getProxyPort(), clusterRegion, accountId, cluster.getDbClusterResourceId()));
} catch (RuntimeException e) {
stopStartedBackend(started, e);
throw e;
@@ -3405,7 +3436,9 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getEndpoint().address(),
effectiveMasterUser, masterPassword, databaseName,
(user, pw) -> validateDbClusterPasswordForScope(
accountId, clusterRegion, id, user, pw));
accountId, clusterRegion, id, user, pw),
proxyBinding(engine, cluster.getEndpoint().address(), proxyPort,
clusterRegion, accountId, cluster.getDbClusterResourceId()));
}
cluster.setServerlessV2MinCapacity(serverlessV2MinCapacity);
@@ -4648,7 +4681,9 @@ public class RdsService implements Resettable, ResourceProvider {
? validateDbClusterPasswordForScope(
proxyAccountId, targetRegion, targetId, user, pw)
: validateDbPasswordForScope(
proxyAccountId, targetRegion, targetId, user, pw));
proxyAccountId, targetRegion, targetId, user, pw),
proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(),
targetRegion, proxyAccountId, proxy.getDbProxyResourceId()));
}
putTargetGroupForAccount(proxyAccountId, proxyKey, updatedTargetGroup);
if (updatedProxy != null) {
@@ -6674,7 +6709,9 @@ public class RdsService implements Resettable, ResourceProvider {
? validateDbClusterPasswordForScope(
accountId, proxyRegion, targetId, user, password)
: validateDbPasswordForScope(
accountId, proxyRegion, targetId, user, password));
accountId, proxyRegion, targetId, user, password),
proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(),
proxyRegion, accountId, proxy.getDbProxyResourceId()));
}
private DbProxyTargetGroup copyProxyTargetGroup(DbProxyTargetGroup source) {
@@ -6778,7 +6815,9 @@ public class RdsService implements Resettable, ResourceProvider {
effectiveMasterUser, cluster.getMasterPassword(), cluster.getDatabaseName(),
(user, pw) -> validateDbClusterPasswordForScope(
accountId, clusterRegion,
cluster.getDbClusterIdentifier(), user, pw));
cluster.getDbClusterIdentifier(), user, pw),
proxyBinding(cluster.getEngine(), cluster.getEndpoint().address(), proxyPort,
clusterRegion, accountId, cluster.getDbClusterResourceId()));
}
cluster.setStatus(DbInstanceStatus.AVAILABLE);
putClusterForScope(accountId, clusterRegion,
@@ -6915,7 +6954,9 @@ public class RdsService implements Resettable, ResourceProvider {
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion,
instance.getDbInstanceIdentifier(), user, pw));
instance.getDbInstanceIdentifier(), user, pw),
proxyBinding(instance.getEngine(), instance.getEndpoint().address(), proxyPort,
instanceRegion, accountId, instance.getDbiResourceId()));
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, instanceRegion,
@@ -87,30 +87,6 @@ public class MySqlProtocolHandler {
private static final String IAM_AUTH_PLUGIN_REPLACEMENT =
"IDENTIFIED WITH mysql_native_password AS '" + NO_MATCHING_PASSWORD_HASH + "'";
public static void handleAuth(Socket client, Socket backend,
PostgresProtocolHandler.BackendConnector backendConnector,
String masterUsername, String masterPassword,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
int handshakeTimeoutMillis) throws IOException {
handleAuth(client, backend, backendConnector, masterUsername, masterPassword,
iamEnabled, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
username -> true, null);
}
public static void handleAuth(Socket client, Socket backend,
PostgresProtocolHandler.BackendConnector backendConnector,
String masterUsername, String masterPassword,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
int handshakeTimeoutMillis,
IamUserChecker iamUserChecker) throws IOException {
handleAuth(client, backend, backendConnector, masterUsername, masterPassword, iamEnabled,
sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis, iamUserChecker, null);
}
public static void handleAuth(Socket client, Socket backend,
PostgresProtocolHandler.BackendConnector backendConnector,
String masterUsername, String masterPassword,
@@ -119,7 +95,7 @@ public class MySqlProtocolHandler {
PasswordValidator passwordValidator,
int handshakeTimeoutMillis,
IamUserChecker iamUserChecker,
RdsMysqlBinding mysqlBinding) throws IOException {
RdsProxyBinding binding) throws IOException {
client.setSoTimeout(handshakeTimeoutMillis);
// The backend accepted the TCP connection but may never answer (or answer only
@@ -225,7 +201,7 @@ public class MySqlProtocolHandler {
&& isIamToken(clearPassword(parsed.authData())) && !tlsEstablished) {
valid = false;
} else if (iamLogin) {
valid = sigV4.validate(clearPassword(parsed.authData()), clientUsername, mysqlBinding);
valid = sigV4.validate(clearPassword(parsed.authData()), clientUsername, binding);
if (valid) {
clientResponseRaw = rewriteHandshakeCredentials(
clientResponseRaw, parsed, masterUsername,
@@ -278,7 +254,7 @@ public class MySqlProtocolHandler {
authenticateIamUserAfterAuthSwitch(
client, clientIn, clientOut, verdict[3] & 0xFF, clientResponseRaw, parsed,
backendNonce, backendConnector, masterUsername, masterPassword, sigV4,
handshakeTimeoutMillis, mysqlBinding);
handshakeTimeoutMillis, binding);
return;
}
clientOut.write(verdict);
@@ -357,7 +333,7 @@ public class MySqlProtocolHandler {
byte[] clientResponseRaw, ParsedHandshakeResponse parsed, byte[] nonce,
PostgresProtocolHandler.BackendConnector backendConnector,
String masterUsername, String masterPassword, RdsSigV4Validator sigV4,
int handshakeTimeoutMillis, RdsMysqlBinding mysqlBinding) throws IOException {
int handshakeTimeoutMillis, RdsProxyBinding binding) throws IOException {
if (!(client instanceof SSLSocket ssl) || !ssl.getSession().isValid()) {
closeQuietly(client);
return;
@@ -374,7 +350,7 @@ public class MySqlProtocolHandler {
String token = clearPassword(Arrays.copyOfRange(reply, 4, reply.length));
boolean valid;
try {
valid = isIamToken(token) && sigV4.validate(token, parsed.username(), mysqlBinding);
valid = isIamToken(token) && sigV4.validate(token, parsed.username(), binding);
} catch (Exception e) {
LOG.warnv("MySQL IAM auth error: {0}", e.getMessage());
valid = false;
@@ -88,6 +88,7 @@ public class PostgresProtocolHandler {
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyBinding binding,
RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
int handshakeTimeoutMillis) throws IOException {
@@ -128,7 +129,7 @@ public class PostgresProtocolHandler {
PasswordValidator.AuthResult authResult = PasswordValidator.AuthResult.PASSTHROUGH;
if (isIam) {
if (!sigV4.validate(clientPassword, clientUsername)) {
if (!sigV4.validate(clientPassword, clientUsername, binding)) {
sendErrorResponse(clientOut, "FATAL", "28P01",
"password authentication failed for user \"" + clientUsername + "\"");
clientOut.flush();
@@ -27,7 +27,7 @@ public class RdsAuthProxy {
private final String dbName;
private final DatabaseEngine engine;
private final RdsSigV4Validator sigV4;
private final RdsMysqlBinding mysqlBinding;
private final RdsProxyBinding binding;
private final MySqlProtocolHandler.IamUserChecker iamUserChecker;
private final RdsProxyTlsCertificates tlsCertificates;
private final MasterPasswordCheck passwordValidator;
@@ -56,11 +56,11 @@ public class RdsAuthProxy {
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, RdsMysqlBinding mysqlBinding) {
int maxConnections, RdsProxyBinding binding) {
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, mysqlBinding,
username -> mysqlBinding != null);
backendConnectTimeoutMillis, maxConnections, binding,
username -> binding != null);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
@@ -69,7 +69,7 @@ public class RdsAuthProxy {
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, RdsMysqlBinding mysqlBinding,
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker) {
this.instanceId = instanceId;
this.backendHost = backendHost;
@@ -80,7 +80,7 @@ public class RdsAuthProxy {
this.masterPassword = masterPassword;
this.dbName = dbName;
this.sigV4 = sigV4;
this.mysqlBinding = mysqlBinding;
this.binding = binding;
this.iamUserChecker = iamUserChecker;
this.tlsCertificates = tlsCertificates;
this.passwordValidator = passwordValidator;
@@ -177,7 +177,7 @@ public class RdsAuthProxy {
case POSTGRES -> {
session = PostgresProtocolHandler.authenticate(
client, connector, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, tlsCertificates, authAdapter,
iamEnabled, sigV4, binding, tlsCertificates, authAdapter,
handshakeTimeoutMillis);
if (session != null) {
PostgresProtocolHandler.bridge(session);
@@ -189,7 +189,7 @@ public class RdsAuthProxy {
client, backend, connector, masterUsername, masterPassword,
iamEnabled, sigV4, tlsCertificates, authAdapter,
handshakeTimeoutMillis,
iamUserChecker, mysqlBinding);
iamUserChecker, binding);
}
case SQLSERVER -> {
backend = connector.connect();
@@ -1,5 +0,0 @@
package io.github.hectorvent.floci.services.rds.proxy;
/** The published identity used when validating a MySQL RDS IAM token. */
public record RdsMysqlBinding(String advertisedHost, int publishedPort, String region) {
}
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.services.rds.proxy;
/**
* The identity a running RDS proxy publishes and that IAM auth tokens are validated against:
* the endpoint the token must have been generated for (host, port, region) and the scope of
* the {@code rds-db:connect} permission the token's principal needs
* ({@code arn:aws:rds-db:<region>:<accountId>:dbuser:<resourceId>/<DBUser>}).
*
* @param resourceId the instance's {@code DbiResourceId}, the cluster's
* {@code DbClusterResourceId} for an Aurora cluster endpoint, or the
* {@code prx-} id of an RDS Proxy
* @param tokensBoundToEndpoint whether a token has to name this endpoint (see
* {@link #acceptsHost}), its port and its region to be accepted.
* MySQL endpoints always require that; PostgreSQL endpoints unless
* {@code services.rds.iam-token-endpoint-binding} is turned off for
* tokens generated for a name the endpoint does not publish.
*/
public record RdsProxyBinding(String advertisedHost, int publishedPort, String region,
String accountId, String resourceId, boolean tokensBoundToEndpoint) {
/**
* Whether a token generated for {@code host} names this endpoint. Besides the advertised
* host, the loopback names count: Floci advertises the name containers reach it by
* ({@code host.docker.internal} natively, its own address in Docker) while a client on the
* host connects to the loopback interface, and both are the same proxy. The published port
* still has to match, so a token for a different instance on the same host is refused.
*/
public boolean acceptsHost(String host) {
return advertisedHost.equalsIgnoreCase(host)
|| "localhost".equalsIgnoreCase(host)
|| "127.0.0.1".equals(host);
}
}
@@ -30,29 +30,19 @@ public class RdsProxyManager {
this.config = config;
}
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String advertisedHost,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.MasterPasswordCheck passwordValidator) {
startProxy(instanceId, engine, iamEnabled, proxyPort, backendHost, backendPort,
advertisedHost, masterUsername, masterPassword, dbName, passwordValidator,
new RdsMysqlBinding(advertisedHost, proxyPort, regionFromRelayKey(instanceId)));
}
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String advertisedHost,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.MasterPasswordCheck passwordValidator,
RdsMysqlBinding mysqlBinding) {
RdsProxyBinding binding) {
tlsCertificates.ensureHost(advertisedHost);
EmulatorConfig.RdsServiceConfig rdsConfig = config.services().rds();
RdsAuthProxy proxy = new RdsAuthProxy(
instanceId, backendHost, backendPort, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator,
rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(),
rdsConfig.proxyMaxConnections(), mysqlBinding);
rdsConfig.proxyMaxConnections(), binding);
try {
proxy.start(proxyPort);
} catch (IOException e) {
@@ -91,17 +81,6 @@ public class RdsProxyManager {
}
}
private String regionFromRelayKey(String relayKey) {
int arnStart = relayKey.indexOf("arn:");
if (arnStart >= 0) {
String[] parts = relayKey.substring(arnStart).split(":", 6);
if (parts.length > 3 && !parts[3].isBlank()) {
return parts[3];
}
}
return config.defaultRegion();
}
public synchronized void updateMasterPassword(String instanceId, String newPassword) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
@@ -1,7 +1,11 @@
package io.github.hectorvent.floci.services.rds.proxy;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -9,6 +13,8 @@ import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.BooleanSupplier;
/**
* Validates RDS IAM auth tokens (SigV4 presigned URLs).
@@ -24,11 +30,26 @@ public class RdsSigV4Validator {
private static final Logger LOG = Logger.getLogger(RdsSigV4Validator.class);
private static final IamPolicyEvaluator POLICY_EVALUATOR = new IamPolicyEvaluator(new ObjectMapper());
private final IamService iamService;
private final SigV4RequestValidator requestValidator;
private final BooleanSupplier enforcementEnabled;
@Inject
public RdsSigV4Validator(IamService iamService, EmulatorConfig config) {
this(iamService, () -> config.services().iam().enforcementEnabled());
}
/** Signature-only validation, for callers that run without IAM enforcement. */
public RdsSigV4Validator(IamService iamService) {
this(iamService, () -> false);
}
RdsSigV4Validator(IamService iamService, BooleanSupplier enforcementEnabled) {
this.iamService = iamService;
this.requestValidator = new SigV4RequestValidator(iamService);
this.enforcementEnabled = enforcementEnabled;
}
/**
@@ -37,15 +58,19 @@ public class RdsSigV4Validator {
* {@code hostname:port/?Action=connect&DBUser=admin&X-Amz-Signature=...}
*
* @param token the presigned URL token
* @param clientUsername the username from the PostgreSQL startup message;
* @param clientUsername the username from the client's startup or handshake message;
* must match the {@code DBUser} in the token
* @return true if the token signature is valid, the DBUser matches, and the token is not expired
* @param binding what the proxy the token arrived at publishes; a token without one is
* refused, since there is nothing to check it against
* @return true if the token signature is valid, the DBUser matches, the token is not expired,
* it names the bound endpoint when the binding requires that, and with IAM
* enforcement on its principal is allowed {@code rds-db:connect} on the DBUser
*/
public boolean validate(String token, String clientUsername) {
return validate(token, clientUsername, null);
}
public boolean validate(String token, String clientUsername, RdsMysqlBinding binding) {
public boolean validate(String token, String clientUsername, RdsProxyBinding binding) {
if (binding == null) {
LOG.warn("Refusing an RDS IAM token that arrived without a proxy binding to validate it against");
return false;
}
try {
URI uri = URI.create("http://" + token);
String host = uri.getHost();
@@ -60,29 +85,68 @@ public class RdsSigV4Validator {
// RDS tokens sign host:port in the canonical host header
String authority = (port > 0) ? host + ":" + port : host;
if (binding != null && (!binding.advertisedHost().equalsIgnoreCase(host)
String[] credential = credentialScope(rawQuery);
if (credential == null) {
LOG.debugv("RDS IAM token missing its credential scope");
return false;
}
if (binding.tokensBoundToEndpoint() && (!binding.acceptsHost(host)
|| binding.publishedPort() != port
|| !credentialMatches(rawQuery, binding.region()))) {
|| !binding.region().equals(credential[2])
|| !"rds-db".equals(credential[3]))) {
return false;
}
return requestValidator.validate(rawQuery, authority, "DBUser", true, clientUsername, "RDS IAM token");
if (!requestValidator.validate(rawQuery, authority, "DBUser", true, clientUsername, "RDS IAM token")) {
return false;
}
return !enforcementEnabled.getAsBoolean()
|| isAllowedToConnect(credential[0], clientUsername, binding);
} catch (Exception e) {
LOG.debugv("RDS IAM token validation error: {0}", e.getMessage());
return false;
}
}
private static boolean credentialMatches(String rawQuery, String region) {
/**
* The {@code rds-db:connect} check AWS runs after the token signature is verified: the
* token's principal must be allowed to connect as {@code dbUser} to the bound database.
* An access key that IAM does not know is bypassed, as {@code IamEnforcementFilter} does.
*/
private boolean isAllowedToConnect(String accessKeyId, String dbUser, RdsProxyBinding binding) {
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
if (caller == null) {
return true;
}
String resource = "arn:aws:rds-db:" + binding.region() + ":" + binding.accountId()
+ ":dbuser:" + binding.resourceId() + "/" + dbUser;
IamPolicyEvaluator.SimulationDecision decision =
POLICY_EVALUATOR.simulatePrincipalPolicy(caller, "rds-db:connect", resource, Map.of());
if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
LOG.warnv("Failed to authorize the connection request for user {0} because the IAM policy "
+ "assumed by the caller ''{1}'' is not authorized to perform rds-db:connect on {2}",
sanitizeForLog(dbUser),
iamService.resolveCallerArn(accessKeyId).orElse(sanitizeForLog(accessKeyId)),
sanitizeForLog(resource));
return false;
}
return true;
}
/**
* The {@code X-Amz-Credential} scope split into its parts
* ({@code accessKeyId/date/region/service/aws4_request}), or {@code null} if absent or malformed.
*/
private static String[] credentialScope(String rawQuery) {
for (String pair : rawQuery.split("&")) {
int eq = pair.indexOf('=');
if (eq >= 0 && "X-Amz-Credential".equals(pair.substring(0, eq))) {
String[] parts = URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8)
.split("/");
return parts.length >= 5 && region.equals(parts[2]) && "rds-db".equals(parts[3]);
return parts.length >= 5 ? parts : null;
}
}
return false;
return null;
}
/**
@@ -195,10 +195,11 @@ public class RedshiftAuthProxy {
backendSocket.setTcpNoDelay(true);
return backendSocket;
};
// iamEnabled = false: the SigV4 branch inside authenticate is never taken.
// iamEnabled = false: the SigV4 branch inside authenticate is never taken, so no
// token binding is needed.
session = PostgresProtocolHandler.authenticate(
client, connector, masterUsername, masterPassword, dbName,
false, sigV4, tlsCertificates, passwordValidator,
false, sigV4, null, tlsCertificates, passwordValidator,
handshakeTimeoutMillis);
if (session != null) {
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain