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

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

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

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

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

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

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

* refactor(rds): rename RdsMysqlBinding to RdsProxyBinding

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

@@ -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());
@@ -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() {
@@ -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"));
}
@@ -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) {
@@ -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(