mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
f07b3fd3be
commit
4753428567
22 files changed
+677
-181
No files matched your search
@@ -310,6 +310,7 @@ jobs:
|
||||
-e FLOCI_TLS_ENABLED=true \
|
||||
-e FLOCI_SERVICES_EC2_MOCK=true \
|
||||
-e FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci \
|
||||
-e FLOCI_SERVICES_RDS_ENDPOINT_HOST=floci \
|
||||
-e FLOCI_SERVICES_SSOOIDC_LOCAL_PRINCIPAL_ID=11111111-2222-3333-4444-555555555555 \
|
||||
floci:test-native
|
||||
|
||||
|
||||
+23
-2
@@ -146,6 +146,27 @@ class RdsJdbcCompatTest {
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
@DisplayName("IAM auth token generated for another host is rejected")
|
||||
void rejectsIamAuthTokenGeneratedForAnotherHost() {
|
||||
assumeInstanceCreated();
|
||||
|
||||
// Correctly signed, unexpired, same user: only the endpoint differs, as when a token
|
||||
// minted for one instance is replayed against another.
|
||||
String token = rds.utilities().generateAuthenticationToken(GenerateAuthenticationTokenRequest.builder()
|
||||
.hostname("other-instance.example.local")
|
||||
.port(proxyPort)
|
||||
.username(USERNAME)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build());
|
||||
|
||||
assertThatThrownBy(() -> openPostgresConnection(USERNAME, token))
|
||||
.isInstanceOf(SQLException.class)
|
||||
.hasMessageContaining("password authentication failed");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
@DisplayName("IAM auth rejected on instance created without IAM")
|
||||
void iamAuthRejectedWhenDisabledAtCreate() {
|
||||
assumeInstanceCreated();
|
||||
@@ -191,7 +212,7 @@ class RdsJdbcCompatTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
@Order(6)
|
||||
@DisplayName("Toggle IAM via modify on a running instance")
|
||||
void toggleIamViaModifyOnRunningInstance() throws Exception {
|
||||
assumeInstanceCreated();
|
||||
@@ -274,7 +295,7 @@ class RdsJdbcCompatTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
@Order(7)
|
||||
@DisplayName("Modify password keeps proxy reachable and delete releases port")
|
||||
void modifyKeepsProxyReachableAndDeleteReleasesPort() throws Exception {
|
||||
assumeInstanceCreated();
|
||||
|
||||
@@ -385,6 +385,7 @@ These services spawn Docker containers. They require access to the Docker socket
|
||||
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First port in the RDS proxy range |
|
||||
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last port in the RDS proxy range |
|
||||
| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port |
|
||||
| `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Default MySQL Docker image |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Default MariaDB Docker image |
|
||||
|
||||
@@ -144,6 +144,7 @@ checked against the instance's other window. Modifications apply immediately —
|
||||
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First host port in the RDS proxy range |
|
||||
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range |
|
||||
| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port |
|
||||
| `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Docker image for MySQL instances |
|
||||
| `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Docker image for MariaDB instances |
|
||||
@@ -454,6 +455,14 @@ The RDS auth proxy validates the master username and password at the proxy layer
|
||||
|
||||
IAM database authentication is also supported. Set `--enable-iam-database-authentication` at instance creation time and use `aws rds generate-db-auth-token` to obtain a token.
|
||||
|
||||
On RDS, a token is only good for the endpoint it was generated for: the hostname, port and region passed to `generate-db-auth-token` are the ones the instance (or cluster, or RDS Proxy) publishes. MySQL and MariaDB endpoints in Floci always refuse a token generated for another endpoint. PostgreSQL endpoints do the same by default; set `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING=false` to accept a token generated for another name, for clients that generate tokens for a container name or DNS alias the endpoint does not publish. Either way, the username must match the `DBUser` in the token exactly. Because clients on the host reach the same proxy over the loopback interface, a token generated for `localhost` or `127.0.0.1` on the published port is accepted as well. Clients on a Docker network connect by Floci's container name, so set `FLOCI_SERVICES_RDS_ENDPOINT_HOST` to that name (see [Docker Compose](#docker-compose)) so it is what the endpoint publishes and tokens are generated for. With [IAM enforcement](iam.md#iam-enforcement-mode) turned on, the token's principal must also be allowed `rds-db:connect` on the database user, scoped the way AWS scopes it:
|
||||
|
||||
```
|
||||
arn:aws:rds-db:<region>:<account-id>:dbuser:<DbiResourceId>/<db-user-name>
|
||||
```
|
||||
|
||||
Aurora clusters use the `DbClusterResourceId`, and connections through an RDS Proxy use the proxy's `prx-…` resource id. A token that fails any of these checks is refused with the engine's ordinary authentication failure; the reason is written to Floci's log.
|
||||
|
||||
On PostgreSQL, the token names a database role (`DBUser`) and the session runs as that role: `current_user` and `session_user` both report it, objects it creates are owned by it, and a token naming a role the database does not have is refused with `FATAL: role "..." does not exist`. Create the role first with `CREATE ROLE <name> WITH LOGIN` as the master user, and grant it whatever the application needs.
|
||||
|
||||
Underneath, the proxy reaches the container as the master user and hands the session over to the token's role, so an IAM session that talks its way back to the master role, via `RESET SESSION AUTHORIZATION` and its variants, is terminated with `FATAL: permission denied to set session authorization` rather than being allowed to regain superuser. `SET ROLE` is untouched: PostgreSQL still permission-checks it against the token's role, exactly as on RDS. One difference from RDS: the proxy learns of the switch from PostgreSQL's own report, so when several statements are batched into a single query after the switch, their results are returned before the session is closed.
|
||||
|
||||
@@ -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,
|
||||
|
||||
+5
-29
@@ -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;
|
||||
|
||||
+2
-1
@@ -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) {
|
||||
|
||||
+77
-13
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+3
-2
@@ -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
|
||||
|
||||
@@ -403,6 +403,7 @@ floci:
|
||||
proxy-base-port: 7001
|
||||
proxy-max-port: 7099
|
||||
# endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker
|
||||
# iam-token-endpoint-binding: true # FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING; false accepts PostgreSQL IAM tokens generated for another hostname or port
|
||||
# Omit image overrides to adapt Floci's built-in images to EngineVersion.
|
||||
# Uncomment an override to pin that engine to an exact image.
|
||||
# default-postgres-image: "registry.example.com/postgres:16-alpine"
|
||||
|
||||
@@ -100,4 +100,14 @@ class ApplicationDefaultsTest {
|
||||
assertNotNull(fallback, "allowPrivateJwtTargets should declare a fallback default");
|
||||
assertEquals("false", fallback.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void productionConfigBindsRdsIamTokensToTheEndpointByDefault() throws NoSuchMethodException {
|
||||
WithDefault fallback = EmulatorConfig.RdsServiceConfig.class
|
||||
.getMethod("iamTokenEndpointBinding")
|
||||
.getAnnotation(WithDefault.class);
|
||||
assertNotNull(fallback, "iamTokenEndpointBinding should declare a fallback default");
|
||||
assertEquals("true", fallback.value(),
|
||||
"a stock Floci should refuse a PostgreSQL IAM token generated for another endpoint, as RDS does");
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
|
||||
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
|
||||
import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyBinding;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
|
||||
@@ -143,6 +144,7 @@ class RdsServiceTest {
|
||||
when(servicesConfig.rds()).thenReturn(rdsConfig);
|
||||
when(rdsConfig.proxyBasePort()).thenReturn(7000);
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7099);
|
||||
when(rdsConfig.iamTokenEndpointBinding()).thenReturn(true);
|
||||
when(rdsConfig.defaultPostgresImage()).thenReturn(Optional.empty());
|
||||
when(rdsConfig.defaultMysqlImage()).thenReturn(Optional.empty());
|
||||
when(rdsConfig.defaultMariadbImage()).thenReturn(Optional.empty());
|
||||
@@ -218,7 +220,7 @@ class RdsServiceTest {
|
||||
assertFalse(passwordCheck.validate("admin", "wrong"));
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
|
||||
DbInstance instance = rdsService.createDbInstance("mypostgres", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
@@ -229,11 +231,54 @@ class RdsServiceTest {
|
||||
rdsService.getDbInstance("mypostgres").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstancePublishesTheBindingIamTokensAndConnectPoliciesAreCheckedAgainst() {
|
||||
DbInstance instance = rdsService.createDbInstance("mypostgres", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
|
||||
ArgumentCaptor<RdsProxyBinding> binding = ArgumentCaptor.forClass(RdsProxyBinding.class);
|
||||
verify(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), binding.capture());
|
||||
assertEquals(new RdsProxyBinding(instance.getEndpoint().address(), instance.getProxyPort(),
|
||||
"us-east-1", "123456789012", instance.getDbiResourceId(), true),
|
||||
binding.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstanceLeavesPostgresIamTokensUnboundWhenTheBindingIsTurnedOff() {
|
||||
when(rdsConfig.iamTokenEndpointBinding()).thenReturn(false);
|
||||
|
||||
rdsService.createDbInstance("mypostgres", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
|
||||
ArgumentCaptor<RdsProxyBinding> binding = ArgumentCaptor.forClass(RdsProxyBinding.class);
|
||||
verify(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), binding.capture());
|
||||
assertFalse(binding.getValue().tokensBoundToEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstanceAlwaysBindsMysqlIamTokensToTheEndpoint() {
|
||||
when(rdsConfig.iamTokenEndpointBinding()).thenReturn(false);
|
||||
|
||||
rdsService.createDbInstance("mymysql", "mysql", "8.0",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
|
||||
ArgumentCaptor<RdsProxyBinding> binding = ArgumentCaptor.forClass(RdsProxyBinding.class);
|
||||
verify(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), binding.capture());
|
||||
assertTrue(binding.getValue().tokensBoundToEndpoint(),
|
||||
"MySQL bound tokens to the endpoint before the setting existed and keeps doing so");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstanceRemovesVisibleRecordWhenProxyStartupFails() {
|
||||
doThrow(new IllegalStateException("proxy down"))
|
||||
.when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> rdsService.createDbInstance(
|
||||
"mypostgres", "postgres", "13",
|
||||
@@ -746,7 +791,7 @@ class RdsServiceTest {
|
||||
.thenReturn(secret);
|
||||
doThrow(new IllegalStateException("proxy down"))
|
||||
.when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
@@ -1401,7 +1446,7 @@ class RdsServiceTest {
|
||||
assertEquals("DBSubnetGroupNotFoundFault", exception.getErrorCode());
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1466,7 +1511,7 @@ class RdsServiceTest {
|
||||
assertNull(cluster.getContainerId());
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1699,7 +1744,7 @@ class RdsServiceTest {
|
||||
assertNull(instance.getDockerVolumeName());
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
@@ -1726,7 +1771,7 @@ class RdsServiceTest {
|
||||
assertEquals(0, instance.getContainerPort());
|
||||
assertNotNull(instance.getVolumeId());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1792,7 +1837,7 @@ class RdsServiceTest {
|
||||
assertEquals(DbInstanceStatus.AVAILABLE, member.getStatus());
|
||||
assertNull(member.getContainerId());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
|
||||
rdsService.deleteDbInstance("probe-member");
|
||||
rdsService.deleteDbCluster("probe-cluster");
|
||||
@@ -1830,7 +1875,7 @@ class RdsServiceTest {
|
||||
verify(proxyManager).startProxy(
|
||||
eq("rds-resource:" + created.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(created.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("password"), eq("dbname"), any());
|
||||
eq("admin"), eq("password"), eq("dbname"), any(), any());
|
||||
|
||||
// Already backed, so a further call is a no-op rather than a second container. Three
|
||||
// calls in total: the create, the retry that found no daemon, and the retry that started it.
|
||||
@@ -1852,7 +1897,7 @@ class RdsServiceTest {
|
||||
.thenReturn(late);
|
||||
doThrow(new IllegalStateException("port in use")).doNothing()
|
||||
.when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> rdsService.ensureInstanceBackend("probe-db", "us-east-1"));
|
||||
@@ -1892,10 +1937,10 @@ class RdsServiceTest {
|
||||
eq(DatabaseEngine.POSTGRES), any(), eq("admin"), eq("password"), eq("dbname"));
|
||||
verify(proxyManager).startProxy(
|
||||
eq("rds-resource:" + cluster.getDbClusterArn()), any(), anyBoolean(),
|
||||
eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any());
|
||||
eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager).startProxy(
|
||||
eq("rds-resource:" + member.getDbInstanceArn()), any(), anyBoolean(),
|
||||
eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any());
|
||||
eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1918,7 +1963,7 @@ class RdsServiceTest {
|
||||
verify(containerManager, never()).stop(any());
|
||||
verify(proxyManager).startProxy(
|
||||
eq("rds-resource:" + created.getDbInstanceArn()), any(), anyBoolean(),
|
||||
eq(created.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any());
|
||||
eq(created.getProxyPort()), eq("127.0.0.1"), eq(15432), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1947,7 +1992,7 @@ class RdsServiceTest {
|
||||
assertEquals(created.getProxyPort(), restored.getEndpoint().port());
|
||||
assertNull(restored.getContainerId());
|
||||
verify(daemonlessProxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1977,7 +2022,7 @@ class RdsServiceTest {
|
||||
assertEquals(DbInstanceStatus.AVAILABLE, restoredMember.getStatus());
|
||||
assertNull(restoredMember.getContainerId());
|
||||
verify(daemonlessProxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2061,7 +2106,7 @@ class RdsServiceTest {
|
||||
assertEquals(port, started.getEndpoint().port());
|
||||
verify(containerManager, times(2)).tryStart(any(), any(), any(), eq(volume), any(), any(), any(), any(), any());
|
||||
verify(proxyManager, times(2)).startProxy(any(), any(), anyBoolean(), eq(port), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
assertEquals("InvalidDBInstanceState", assertThrows(AwsException.class,
|
||||
() -> rdsService.startDbInstance("standalone")).getErrorCode());
|
||||
}
|
||||
@@ -2179,7 +2224,7 @@ class RdsServiceTest {
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(containerManager, never()).stop(any());
|
||||
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2837,7 +2882,7 @@ class RdsServiceTest {
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restored.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
eq("admin"), eq("secret"), eq("app"), any(), any());
|
||||
|
||||
restoredService.deleteDbInstance("mydb");
|
||||
verify(restoredContainerManager).removeVolume(
|
||||
@@ -2890,11 +2935,11 @@ class RdsServiceTest {
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restoredCluster.getDbClusterArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
eq("admin"), eq("secret"), eq("app"), any(), any());
|
||||
verify(restoredProxyManager).startProxy(
|
||||
eq("rds-resource:" + restoredMember.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
eq("admin"), eq("secret"), eq("app"), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -3375,7 +3420,7 @@ class RdsServiceTest {
|
||||
.doNothing()
|
||||
.when(restoredProxyManager).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("cleanup failed"))
|
||||
.doNothing()
|
||||
.doNothing()
|
||||
@@ -3500,7 +3545,7 @@ class RdsServiceTest {
|
||||
.doNothing()
|
||||
.when(restoredProxyManager).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("restore container cleanup failed"))
|
||||
.doThrow(new IllegalStateException("delete container cleanup failed"))
|
||||
.doNothing()
|
||||
@@ -4066,7 +4111,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
DbProxyAuth requiredAuth = new DbProxyAuth(
|
||||
@@ -4120,7 +4165,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
DbProxyAuth requiredAuth = new DbProxyAuth(
|
||||
@@ -4386,7 +4431,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
|
||||
@@ -4503,7 +4548,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
RdsService service = proxyStoreService(
|
||||
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
|
||||
|
||||
@@ -4573,7 +4618,7 @@ class RdsServiceTest {
|
||||
verify(proxyManager).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
|
||||
anyBoolean(), eq(3306), eq("localhost"), eq(3306), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
eq("admin"), eq("secret"), eq("app"), any(), any());
|
||||
verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
|
||||
}
|
||||
|
||||
@@ -4602,7 +4647,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
throw startupFailure;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
doAnswer(invocation -> {
|
||||
relayRunning.set(false);
|
||||
return null;
|
||||
@@ -5069,7 +5114,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
IllegalStateException deleteFailure =
|
||||
new IllegalStateException("simulated post-mutation target-group delete failure");
|
||||
doAnswer(invocation -> {
|
||||
@@ -5134,7 +5179,7 @@ class RdsServiceTest {
|
||||
relayRunning.set(true);
|
||||
return null;
|
||||
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
|
||||
anyInt(), any(), any(), any(), any(), any());
|
||||
anyInt(), any(), any(), any(), any(), any(), any());
|
||||
IllegalStateException deleteFailure =
|
||||
new IllegalStateException("simulated post-mutation proxy delete failure");
|
||||
doAnswer(invocation -> {
|
||||
@@ -5297,9 +5342,9 @@ class RdsServiceTest {
|
||||
String relayKeyB = "rds-resource:" + instanceB.getDbInstanceArn();
|
||||
|
||||
verify(proxyManager).startProxy(eq(relayKeyA), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager).startProxy(eq(relayKeyB), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
org.mockito.Mockito.clearInvocations(proxyManager);
|
||||
serviceA.deleteDbInstance("shared-db");
|
||||
@@ -5414,7 +5459,7 @@ class RdsServiceTest {
|
||||
assertTrue(rawClusters.get("cluster1").isPresent());
|
||||
assertTrue(rawClusters.get(currentAccount + "/cluster1").isEmpty());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -5520,7 +5565,7 @@ class RdsServiceTest {
|
||||
assertEquals("insufficient-resource-limits", failed.getStatus());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
DbProxy another = service.createDbProxy(
|
||||
"another-proxy", "MYSQL", true, false, "NONE", PROXY_ROLE_ARN,
|
||||
@@ -5540,7 +5585,7 @@ class RdsServiceTest {
|
||||
verify(proxyManager).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
|
||||
anyBoolean(), eq(failed.getProxyPort()), any(), anyInt(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -5566,7 +5611,7 @@ class RdsServiceTest {
|
||||
service.getDbProxy("app-proxy", "us-east-1").getStatus());
|
||||
verify(proxyManager, never()).startProxy(
|
||||
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
|
||||
any(), anyInt(), any(), any(), any(), any(), any());
|
||||
any(), anyInt(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -5631,7 +5676,7 @@ class RdsServiceTest {
|
||||
verify(restoredProxyManager).startProxy(eq("db-proxy:" + restored.getDbProxyArn()),
|
||||
eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), anyInt(), eq("127.0.0.1"), eq(15432), any(),
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
eq("admin"), eq("secret"), eq("app"), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -5703,7 +5748,7 @@ class RdsServiceTest {
|
||||
verify(restoredProxyManager).startProxy(eq("db-proxy:" + proxy.getDbProxyArn()),
|
||||
eq(DatabaseEngine.POSTGRES),
|
||||
eq(false), eq(5432), eq("127.0.0.1"), eq(15432), any(), eq("admin"),
|
||||
eq("target-secret"), eq("app"), validator.capture());
|
||||
eq("target-secret"), eq("app"), validator.capture(), any());
|
||||
assertTrue(validator.getValue().validate("admin", "target-secret"));
|
||||
assertFalse(validator.getValue().validate("admin", "default-secret"));
|
||||
assertTrue(rawProxies.get(targetAccount + "/us-east-1::app-proxy").isPresent());
|
||||
|
||||
+18
-6
@@ -95,7 +95,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, NO_RECONNECT, "admin", "secret",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -157,7 +158,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, NO_RECONNECT, "admin", "secret",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -213,7 +215,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, NO_RECONNECT, "admin", "secret",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -311,7 +314,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, NO_RECONNECT, "admin", "secret",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -372,7 +376,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, NO_RECONNECT, "admin", "secret",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 200);
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 200,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
authFailure.set(e);
|
||||
}
|
||||
@@ -675,7 +680,8 @@ class MySqlProtocolHandlerTest {
|
||||
MySqlProtocolHandler.handleAuth(
|
||||
proxyClient, backend, connector, "admin", "secret",
|
||||
iamEnabled, testSigV4Validator(), tlsCertificates,
|
||||
(user, pass) -> PasswordValidator.AuthResult.PASSTHROUGH, 5000);
|
||||
(user, pass) -> PasswordValidator.AuthResult.PASSTHROUGH, 5000,
|
||||
username -> true, testBinding());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -701,6 +707,12 @@ class MySqlProtocolHandlerTest {
|
||||
return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
|
||||
}
|
||||
|
||||
/** What the proxy publishes for the endpoint {@link #rdsToken} generates tokens for. */
|
||||
private static RdsProxyBinding testBinding() {
|
||||
return new RdsProxyBinding("mydb.abc123.us-east-1.rds.amazonaws.com", 3306, "us-east-1",
|
||||
"123456789012", "db-ABCDEFGHIJKL01234", true);
|
||||
}
|
||||
|
||||
private static SSLSocket trustedClientSocket(Socket socket) throws Exception {
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, new TrustManager[]{new X509TrustManager() {
|
||||
|
||||
+44
-15
@@ -65,7 +65,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL startup message length exceeds the 1048576 byte limit: 1048577",
|
||||
@@ -86,7 +86,7 @@ class PostgresProtocolHandlerTest {
|
||||
assertNull(PostgresProtocolHandler.authenticate(
|
||||
client, NEVER_CONNECT,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL startup message length is below the 8 byte minimum: -1",
|
||||
@@ -118,7 +118,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL password message length is below the 5 byte minimum: 4",
|
||||
@@ -135,7 +135,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL backend authentication message length exceeds the 1048576 byte limit: 1048577",
|
||||
@@ -155,7 +155,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL backend message length exceeds the 1048576 byte limit: 1048577",
|
||||
@@ -175,7 +175,7 @@ class PostgresProtocolHandlerTest {
|
||||
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
|
||||
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
assertEquals("PostgreSQL SASL continue message length exceeds the 1048576 byte limit: 1048577",
|
||||
@@ -222,7 +222,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -280,7 +280,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -338,7 +338,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -405,7 +405,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
false, testSigV4Validator(), testBinding(), tlsCertificates,
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -459,7 +459,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), tlsCertificates,
|
||||
false, testSigV4Validator(), testBinding(), tlsCertificates,
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -509,7 +509,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -636,6 +636,30 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionIsRejectedWhenTheTokenWasGeneratedForAnotherHost() throws Exception {
|
||||
ByteArrayOutputStream input = new ByteArrayOutputStream();
|
||||
DataOutputStream out = new DataOutputStream(input);
|
||||
writeStartup(out, "app_user", "postgres");
|
||||
writePassword(out, SigV4TokenTestHelper.createRdsToken("other.example.local", 7001, "app_user",
|
||||
"AKIATEST", "secret", Instant.now(), 900));
|
||||
MemorySocket client = new MemorySocket(input.toByteArray());
|
||||
|
||||
assertNull(PostgresProtocolHandler.authenticate(
|
||||
client, NEVER_CONNECT,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
true, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
|
||||
|
||||
DataInputStream clientIn = new DataInputStream(
|
||||
new ByteArrayInputStream(client.getOutputStream().toByteArray()));
|
||||
readCleartextPasswordChallenge(clientIn);
|
||||
Map<Character, String> error = readErrorResponse(clientIn);
|
||||
assertEquals("FATAL", error.get('S'));
|
||||
assertEquals("28P01", error.get('C'));
|
||||
assertEquals("password authentication failed for user \"app_user\"", error.get('M'));
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionForTheMasterUserKeepsTheMasterSession() throws Exception {
|
||||
AtomicReference<String> backendDatabase = new AtomicReference<>();
|
||||
@@ -872,7 +896,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, connector,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
false, testSigV4Validator(), testTlsCertificates(),
|
||||
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 200);
|
||||
} catch (IOException e) {
|
||||
authFailure.set(e);
|
||||
@@ -906,7 +930,7 @@ class PostgresProtocolHandlerTest {
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, () -> backend,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
true, testSigV4Validator(), testTlsCertificates(),
|
||||
true, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
@@ -1111,6 +1135,11 @@ class PostgresProtocolHandlerTest {
|
||||
return fields;
|
||||
}
|
||||
|
||||
/** The endpoint the test proxy publishes; {@link #rdsToken} signs tokens for exactly this endpoint. */
|
||||
private static RdsProxyBinding testBinding() {
|
||||
return new RdsProxyBinding("localhost", 7001, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true);
|
||||
}
|
||||
|
||||
private static RdsSigV4Validator testSigV4Validator() {
|
||||
return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
|
||||
}
|
||||
|
||||
+2
-1
@@ -178,7 +178,8 @@ class RdsProxyManagerTest {
|
||||
|
||||
private static void start(RdsProxyManager manager, String key, int proxyPort) {
|
||||
manager.startProxy(key, DatabaseEngine.POSTGRES, false, proxyPort,
|
||||
"localhost", 1, "localhost", "admin", "secret", "app", (user, password) -> true);
|
||||
"localhost", 1, "localhost", "admin", "secret", "app", (user, password) -> true,
|
||||
new RdsProxyBinding("localhost", proxyPort, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true));
|
||||
}
|
||||
|
||||
private static RdsAuthProxy authProxy(String key) {
|
||||
|
||||
+248
-25
@@ -4,9 +4,17 @@ import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.MessageFormat;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -14,6 +22,96 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RdsSigV4ValidatorTest {
|
||||
|
||||
private static final String S3_ONLY_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":[\"s3:GetObject\"],\"Resource\":[\"*\"]}]}";
|
||||
|
||||
private static RdsProxyBinding exampleBinding() {
|
||||
return new RdsProxyBinding("db.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a PostgreSQL proxy publishes when {@code services.rds.iam-token-endpoint-binding} is
|
||||
* turned off: the token's signature and DBUser are checked, the endpoint it was generated for
|
||||
* is not.
|
||||
*/
|
||||
private static RdsProxyBinding unboundBinding() {
|
||||
return new RdsProxyBinding("db.example.local", 5432, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every proxy publishes a binding; a token that shows up without one has nothing to be
|
||||
* checked against and is refused rather than waved through on its signature alone.
|
||||
*/
|
||||
@Test
|
||||
void validateRefusesTokenWithoutBinding() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "admin", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsCallerWithoutRdsDbConnectWhenEnforcementIsOn() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", S3_ONLY_POLICY);
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "jane_doe", exampleBinding()),
|
||||
"a valid token from a principal that is not allowed rds-db:connect must be rejected");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateAcceptsCallerAllowedRdsDbConnectOnTheBoundDbUser() throws Exception {
|
||||
// The example policy from the AWS "IAM database authentication" guide.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", connectPolicyFor(
|
||||
"arn:aws:rds-db:us-east-1:123456789012:dbuser:db-ABCDEFGHIJKL01234/jane_doe"));
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertTrue(validator.validate(token, "jane_doe", exampleBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsCallerWhoseConnectGrantIsForAnotherDbUser() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", connectPolicyFor(
|
||||
"arn:aws:rds-db:us-east-1:123456789012:dbuser:db-ABCDEFGHIJKL01234/someone_else"));
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "jane_doe", exampleBinding()),
|
||||
"rds-db:connect is granted per database user, not per database");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateSkipsTheConnectCheckWhenEnforcementIsOff() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", S3_ONLY_POLICY);
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertTrue(validator.validate(token, "jane_doe", exampleBinding()),
|
||||
"without IAM enforcement a well-formed token is enough, as before");
|
||||
}
|
||||
|
||||
private static String connectPolicyFor(String resourceArn) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":[\"rds-db:connect\"],\"Resource\":[\"" + resourceArn + "\"]}]}";
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateAcceptsTokenSignedByStandardSigV4() throws Exception {
|
||||
String accessKeyId = "AKIAORACLETEST";
|
||||
@@ -32,7 +130,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "testuser"),
|
||||
assertTrue(validator.validate(token, "testuser", unboundBinding()),
|
||||
"Validator must accept a well-formed SigV4 RDS authentication token");
|
||||
}
|
||||
|
||||
@@ -51,7 +149,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "admin"));
|
||||
assertTrue(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -70,7 +168,7 @@ class RdsSigV4ValidatorTest {
|
||||
);
|
||||
String brokenToken = validToken.replace("db.example.local:5432/?", "db.example.local/?");
|
||||
|
||||
assertFalse(validator.validate(brokenToken, "admin"));
|
||||
assertFalse(validator.validate(brokenToken, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,7 +186,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,7 +205,7 @@ class RdsSigV4ValidatorTest {
|
||||
);
|
||||
String tamperedToken = validToken.replace("DBUser=admin", "DBUser=attacker");
|
||||
|
||||
assertFalse(validator.validate(tamperedToken, "admin"));
|
||||
assertFalse(validator.validate(tamperedToken, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -125,7 +223,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,7 +248,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -169,7 +267,7 @@ class RdsSigV4ValidatorTest {
|
||||
);
|
||||
String withoutDbUser = validToken.replaceFirst("DBUser=admin&", "");
|
||||
|
||||
assertFalse(validator.validate(withoutDbUser, "admin"));
|
||||
assertFalse(validator.validate(withoutDbUser, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -187,7 +285,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "attacker"),
|
||||
assertFalse(validator.validate(token, "attacker", unboundBinding()),
|
||||
"Token signed for 'admin' must be rejected when client connects as 'attacker'");
|
||||
}
|
||||
|
||||
@@ -200,9 +298,9 @@ class RdsSigV4ValidatorTest {
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertTrue(validator.validate(token, "admin",
|
||||
new RdsMysqlBinding("db.example.local", 3307, "us-east-1")));
|
||||
new RdsProxyBinding("db.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
assertFalse(validator.validate(token, "admin",
|
||||
new RdsMysqlBinding("db.example.local", 3306, "us-east-1")));
|
||||
new RdsProxyBinding("db.example.local", 3306, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -214,7 +312,38 @@ class RdsSigV4ValidatorTest {
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin",
|
||||
new RdsMysqlBinding("other.example.local", 3307, "us-east-1")));
|
||||
new RdsProxyBinding("other.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Natively Floci advertises {@code host.docker.internal} (the name Lambda containers reach it
|
||||
* by) while host clients connect to the loopback interface; in Docker with published ports the
|
||||
* same split applies. A loopback name therefore names this same endpoint.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"localhost", "127.0.0.1"})
|
||||
void validateAcceptsTokenSignedForLoopbackWhenTheEndpointAdvertisesAnotherName(String loopbackHost)
|
||||
throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
loopbackHost, 3307, "admin", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertTrue(validator.validate(token, "admin",
|
||||
new RdsProxyBinding("host.docker.internal", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsLoopbackTokenSignedForAnotherPort() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"localhost", 3308, "admin", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin",
|
||||
new RdsProxyBinding("host.docker.internal", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -226,7 +355,7 @@ class RdsSigV4ValidatorTest {
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin",
|
||||
new RdsMysqlBinding("db.example.local", 3307, "eu-west-1")));
|
||||
new RdsProxyBinding("db.example.local", 3307, "eu-west-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,7 +367,38 @@ class RdsSigV4ValidatorTest {
|
||||
"us-east-1", "s3", Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin",
|
||||
new RdsMysqlBinding("db.example.local", 3307, "us-east-1")));
|
||||
new RdsProxyBinding("db.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", true)));
|
||||
}
|
||||
|
||||
/**
|
||||
* PostgreSQL endpoints publish their binding with the endpoint check off when
|
||||
* {@code services.rds.iam-token-endpoint-binding} is turned off: a well-signed token for any
|
||||
* host, port and region is accepted, as it was before the check existed.
|
||||
*/
|
||||
@Test
|
||||
void validateSkipsTheEndpointCheckWhenTokensAreNotBoundToTheEndpoint() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsTokenWithScope(
|
||||
"other.example.local", 3308, "admin", "AKIDRDS", "secret-rds",
|
||||
"eu-west-1", "rds-db", Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertTrue(validator.validate(token, "admin", new RdsProxyBinding(
|
||||
"db.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateStillRequiresRdsDbConnectWhenTokensAreNotBoundToTheEndpoint() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", S3_ONLY_POLICY);
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "jane_doe", new RdsProxyBinding(
|
||||
"db.example.local", 3307, "us-east-1", "123456789012", "db-ABCDEFGHIJKL01234", false)),
|
||||
"the endpoint check being off does not turn off the rds-db:connect check");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -256,7 +416,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, null),
|
||||
assertTrue(validator.validate(token, null, unboundBinding()),
|
||||
"Null clientUsername should skip the identity check (backwards compat)");
|
||||
}
|
||||
|
||||
@@ -277,7 +437,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "db+admin@example.com"));
|
||||
assertTrue(validator.validate(token, "db+admin@example.com", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -297,7 +457,7 @@ class RdsSigV4ValidatorTest {
|
||||
// Tampering with the region in the credential scope invalidates the signature
|
||||
String tamperedToken = token.replace("us-east-1", "eu-west-1");
|
||||
|
||||
assertFalse(validator.validate(tamperedToken, "admin"));
|
||||
assertFalse(validator.validate(tamperedToken, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -316,7 +476,7 @@ class RdsSigV4ValidatorTest {
|
||||
);
|
||||
String withoutSignature = validToken.replaceFirst("&X-Amz-Signature=[0-9a-f]+", "");
|
||||
|
||||
assertFalse(validator.validate(withoutSignature, "admin"));
|
||||
assertFalse(validator.validate(withoutSignature, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -337,7 +497,7 @@ class RdsSigV4ValidatorTest {
|
||||
"session-token"
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "admin"),
|
||||
assertTrue(validator.validate(token, "admin", unboundBinding()),
|
||||
"Validator must accept RDS IAM tokens signed with STS session credentials (ASIA… keys)");
|
||||
}
|
||||
|
||||
@@ -352,7 +512,7 @@ class RdsSigV4ValidatorTest {
|
||||
"db.example.local", 5432, "admin", accessKeyId, secretAccessKey,
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -366,7 +526,7 @@ class RdsSigV4ValidatorTest {
|
||||
"db.example.local", 5432, "admin", accessKeyId, secretAccessKey,
|
||||
Instant.now().minusSeconds(60), 900, "wrong-session-token");
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -381,7 +541,7 @@ class RdsSigV4ValidatorTest {
|
||||
"db.example.local", 5432, "admin", accessKeyId, secretAccessKey,
|
||||
Instant.now().minusSeconds(60), 900, "session-token");
|
||||
|
||||
assertFalse(validator.validate(token, "admin"));
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -400,7 +560,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"),
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()),
|
||||
"Validator must reject STS token signed with wrong secret");
|
||||
}
|
||||
|
||||
@@ -424,7 +584,7 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"),
|
||||
assertFalse(validator.validate(token, "admin", unboundBinding()),
|
||||
"A token self-signed with secret == accessKeyId for an unregistered access key "
|
||||
+ "must never validate; unregistered keys must fail closed");
|
||||
}
|
||||
@@ -450,10 +610,73 @@ class RdsSigV4ValidatorTest {
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "admin"),
|
||||
assertTrue(validator.validate(token, "admin", unboundBinding()),
|
||||
"The well-known \"test\"/\"test\" local-dev credential pair must still validate");
|
||||
}
|
||||
|
||||
/**
|
||||
* The database user comes straight from the client's startup message and ends up in the
|
||||
* {@code rds-db} resource the refusal names, so one carrying line breaks must not be able
|
||||
* to forge extra log lines through that warning.
|
||||
*/
|
||||
@Test
|
||||
void refusedConnectWarningStripsControlCharactersFromTheDbUser() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", S3_ONLY_POLICY);
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String dbUser = "jane\r\nINJECTED";
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local", 3307, dbUser, "AKIDRDS", "secret-rds",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
|
||||
List<LogRecord> records = captureLogs(
|
||||
() -> assertFalse(validator.validate(token, dbUser, exampleBinding())));
|
||||
|
||||
List<String> refusals = records.stream()
|
||||
.map(RdsSigV4ValidatorTest::render)
|
||||
.filter(message -> message.contains("rds-db:connect"))
|
||||
.toList();
|
||||
assertEquals(1, refusals.size(), "expected one refusal warning, got: " + records);
|
||||
assertTrue(refusals.get(0).contains("INJECTED"));
|
||||
assertFalse(refusals.get(0).contains("\r") || refusals.get(0).contains("\n"),
|
||||
"control characters must be stripped from the warning: " + refusals.get(0));
|
||||
}
|
||||
|
||||
private static String render(LogRecord record) {
|
||||
return record.getParameters() == null
|
||||
? record.getMessage()
|
||||
: MessageFormat.format(record.getMessage(), record.getParameters());
|
||||
}
|
||||
|
||||
private static List<LogRecord> captureLogs(Runnable action) {
|
||||
java.util.logging.Logger julLogger =
|
||||
java.util.logging.Logger.getLogger(RdsSigV4Validator.class.getName());
|
||||
julLogger.setLevel(Level.ALL);
|
||||
List<LogRecord> records = new ArrayList<>();
|
||||
Handler handler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
records.add(record);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
};
|
||||
handler.setLevel(Level.ALL);
|
||||
julLogger.addHandler(handler);
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
julLogger.removeHandler(handler);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitizeForLogStripsControlCharacters() throws Exception {
|
||||
// A forged accessKeyId containing CR/LF must not be able to inject fake log lines into
|
||||
|
||||
@@ -5,16 +5,61 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
public final class IamServiceTestHelper {
|
||||
|
||||
private IamServiceTestHelper() {
|
||||
}
|
||||
|
||||
/**
|
||||
* An IAM service holding one user whose only permissions are the given inline policy
|
||||
* document, plus an access key that belongs to that user.
|
||||
*/
|
||||
public static IamService iamServiceWithUserPolicy(String accessKeyId, String secretAccessKey,
|
||||
String userName, String inlinePolicyDocument) {
|
||||
try {
|
||||
Constructor<IamService> constructor = IamService.class.getDeclaredConstructor(
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
StorageBackend.class,
|
||||
RegionResolver.class
|
||||
);
|
||||
constructor.setAccessible(true);
|
||||
|
||||
InMemoryStorage<String, IamUser> users = new InMemoryStorage<>();
|
||||
IamUser user = new IamUser("AIDA" + userName.toUpperCase(), userName, "/",
|
||||
"arn:aws:iam::123456789012:user/" + userName);
|
||||
user.setInlinePolicies(Map.of("inline", inlinePolicyDocument));
|
||||
users.put(userName, user);
|
||||
|
||||
InMemoryStorage<String, AccessKey> accessKeys = new InMemoryStorage<>();
|
||||
accessKeys.put(accessKeyId, new AccessKey(accessKeyId, secretAccessKey, userName));
|
||||
|
||||
return constructor.newInstance(
|
||||
users,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
accessKeys,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "123456789012")
|
||||
);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException("Failed to construct IamService test fixture", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static IamService iamServiceWithAccessKey(String accessKeyId, String secretAccessKey) {
|
||||
try {
|
||||
Constructor<IamService> constructor = IamService.class.getDeclaredConstructor(
|
||||
|
||||
Reference in new issue
Block a user