feat(redshift): emulate GetClusterCredentials and GetClusterCredentialsWithIAM (#3273)

* feat(redshift): add RedshiftCredentialBroker for short-lived Db credentials

* refactor(rds-proxy): widen PasswordValidator to a three-value AuthResult

The wire-level password check the PostgreSQL/MySQL proxy handlers take now
returns REJECT / PASSTHROUGH / MASTER_EQUIVALENT instead of a boolean, so a
caller can tell the proxy to open the backend leg as the cluster master for a
client it has vouched for. RdsAuthProxy keeps its own boolean master-password
callback, renamed MasterPasswordCheck to free the PasswordValidator name, and
adapts it at the handler boundary (non-master stays PASSTHROUGH).

* feat(redshift): auth proxy accepts live GetClusterCredentials credentials

passwordValidatorFor now returns AuthResult and consults RedshiftCredentialBroker:
the master pair and any live minted credential resolve to MASTER_EQUIVALENT, a
known broker user with a stale password is REJECTed, everyone else PASSTHROUGH.

* feat(redshift): add default-credential-duration-seconds config

* feat(redshift): implement GetClusterCredentials action

Mints a short-lived DbUser/DbPassword pair via RedshiftCredentialBroker and
returns it as Query-protocol XML. AutoCreate prefixes IAM: on the DbUser,
DbGroups are echoed, DurationSeconds is validated to 900-3600 (default from
the new config key), and an unknown ClusterIdentifier propagates ClusterNotFound.
The two credential actions are registered in AwsQueryController.REDSHIFT_ACTIONS
and the Query dispatch now forwards the Authorization header to the handler.

* feat(redshift): implement GetClusterCredentialsWithIAM action

Derives the DbUser from the caller's IAM identity resolved via the Authorization
header: an IAM user maps to IAM:<name>, an assumed role to IAMR:<role>, and an
unresolvable caller to the IAMR:floci fallback with a WARN so local and CI flows
are not blocked. Any DbUser request parameter is ignored.

* feat(redshift-data): resolve non-master DbUser via GetClusterCredentials

resolveViaDbUser now accepts a DbUser that has a live credential in
RedshiftCredentialBroker, connecting to the container as the cluster master
(the minted DbUser is nominal). An unknown non-master DbUser still fails with
ValidationException.

* test(redshift): end-to-end GetClusterCredentials + Data API non-master DbUser

Docker-gated: mints a credential for a non-master DbUser via GetClusterCredentials
then runs SELECT 1 through the Data API as that DbUser, asserting the result.

* test(compat): SDK coverage for Redshift GetClusterCredentials

Adds getClusterCredentials and getClusterCredentialsWithIAM assertions to the
AWS SDK Redshift compatibility test.

* docs(redshift): document GetClusterCredentials and GetClusterCredentialsWithIAM

Regenerates the redshift.md action table (excluding the DbGroups member-name
switch label), fills the two new descriptions, updates the wire-auth and
redshift-data.md DbUser notes, and bumps the Service Matrix count to 23.

* fix(redshift): reject a wrong master password instead of passing it through

passwordValidatorFor only treated the master pair as MASTER_EQUIVALENT and let
everything else fall to the broker. A request with the master username but a
wrong password is unknown to the broker, so it classified as PASSTHROUGH; the
wire proxy then opened the backend leg as master (isMaster is username-only) and
the client authenticated with the wrong password. Now the master username is
decided on its own password: match to MASTER_EQUIVALENT, mismatch to REJECT.

* fix(redshift): reject proxy logins when the cluster row is gone; strip IAM user path

passwordValidatorFor fell through to the broker when the cluster was absent from
the account partition, classifying an unknown user as PASSTHROUGH; the wire proxy
reads isMaster from its own start-time config, so that still opened the backend
as master for the master username with any password. Return REJECT when there is
no cluster row to validate against.

RedshiftIamDbUserResolver now strips an IAM path prefix from a user ARN
(user/team/alice -> alice), matching how AWS names the DbUser.

* fix(redshift): keep concurrent credentials, revoke on delete, bound the config default

Addresses PR review (greptile):
- RedshiftCredentialBroker now holds every unexpired credential per DbUser instead
  of one slot, so a reissue no longer invalidates a still-live password (matches
  AWS, which keeps each issued credential valid to its own expiry).
- Add revokeCluster(); RedshiftService calls it on deleteCluster and at the start
  of createCluster, so a cluster recreated with the same identifier does not
  inherit master-equivalent access from a stale credential.
- resolveDurationSeconds now holds the YAML default to the same 900-3600 bounds as
  a request value, falling back to 900 with a WARN instead of minting a credential
  that is already expired or over-range.

* fix(redshift): revoke temp credentials on createCluster rollback too

The greptile review asked for revocation on 'relevant rollback paths'. Both
createCluster failure branches that delete the cluster row now also call
credentialBroker.revokeCluster, so a credential issued by a concurrent
GetClusterCredentials while the row briefly existed cannot outlive it.

* fix(redshift): correct GetClusterCredentials AutoCreate prefix

AWS prefixes the returned DbUser with IAM: when AutoCreate is false and
IAMA: when it is true. The handler returned IAM: when true and no prefix
when false, so a client using the returned name could not authenticate
and the value diverged from GetClusterCredentialsWithIAM, which already
issues prefixed identities.

The broker keys on the returned name, so the proxy and Data API now
expect the prefixed DbUser. Tests and the redshift docs are updated to
match.

* test(redshift): give compat GetClusterCredentials tests distinct @Order

Three methods shared @Order(2), leaving their relative order undefined.
Number the two credential tests 3 and 4 and move testDeleteCluster to 5.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-10 23:58:33 -04:00
1 parent d9cc2a09d0
commit 6b17ef2b1c
33 files changed
+1172 -77

No files matched your search

@@ -5044,8 +5044,8 @@ class RdsServiceTest {
restoredService.restorePersistedRuntime();
ArgumentCaptor<RdsAuthProxy.PasswordValidator> validator =
ArgumentCaptor.forClass(RdsAuthProxy.PasswordValidator.class);
ArgumentCaptor<RdsAuthProxy.MasterPasswordCheck> validator =
ArgumentCaptor.forClass(RdsAuthProxy.MasterPasswordCheck.class);
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"),
@@ -66,7 +66,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -128,7 +128,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -184,7 +184,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -282,7 +282,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.services.rds.proxy;
import org.junit.jupiter.api.Test;
import static io.github.hectorvent.floci.services.rds.proxy.PasswordValidator.AuthResult;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PostgresProtocolHandlerAuthResultTest {
@Test
void masterAlwaysUsesMasterBackendCredentials() {
PostgresProtocolHandler.BackendLogin login = PostgresProtocolHandler.resolveBackendLogin(
true, false, AuthResult.MASTER_EQUIVALENT,
"master", "masterpass", "alice", "alicepass");
assertEquals("master", login.user());
assertEquals("masterpass", login.password());
}
@Test
void iamUsesMasterBackendCredentials() {
PostgresProtocolHandler.BackendLogin login = PostgresProtocolHandler.resolveBackendLogin(
false, true, AuthResult.PASSTHROUGH,
"master", "masterpass", "arn:role", "token");
assertEquals("master", login.user());
assertEquals("masterpass", login.password());
}
@Test
void nonMasterPassthroughForwardsClientCredentials() {
PostgresProtocolHandler.BackendLogin login = PostgresProtocolHandler.resolveBackendLogin(
false, false, AuthResult.PASSTHROUGH,
"master", "masterpass", "alice", "alicepass");
assertEquals("alice", login.user());
assertEquals("alicepass", login.password());
}
@Test
void nonMasterMasterEquivalentUsesMasterBackendCredentials() {
PostgresProtocolHandler.BackendLogin login = PostgresProtocolHandler.resolveBackendLogin(
false, false, AuthResult.MASTER_EQUIVALENT,
"master", "masterpass", "temp-user", "minted-pass");
assertEquals("master", login.user());
assertEquals("masterpass", login.password());
}
}
@@ -60,7 +60,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(input.toByteArray()), mock(Socket.class),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL startup message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -81,7 +81,7 @@ class PostgresProtocolHandlerTest {
client, new MemorySocket(new byte[0]),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
}
@Test
@@ -95,7 +95,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL startup message length is below the 8 byte minimum: -1",
error.getMessage());
@@ -113,7 +113,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL password message length is below the 5 byte minimum: 4",
error.getMessage());
@@ -130,7 +130,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL backend authentication message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -150,7 +150,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL backend message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -170,7 +170,7 @@ class PostgresProtocolHandlerTest {
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
assertEquals("PostgreSQL SASL continue message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -217,7 +217,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -275,7 +275,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -333,7 +333,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -400,7 +400,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -454,7 +454,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -504,7 +504,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -856,7 +856,7 @@ class PostgresProtocolHandlerTest {
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
true, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.redshift;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftCredentialBrokerTest {
private RedshiftCredentialBroker broker;
@BeforeEach
void setUp() {
broker = new RedshiftCredentialBroker();
}
@Test
void issueReturnsPopulatedCredentialWithFutureExpiry() {
TempCredential cred = broker.issue("acc", "clus", "analyst", List.of("etl"), 900);
assertEquals("analyst", cred.dbUser());
assertFalse(cred.password().isBlank());
assertTrue(cred.expiresAt().isAfter(Instant.now()));
assertEquals(List.of("etl"), cred.dbGroups());
}
@Test
void resolveReturnsLiveCredential() {
broker.issue("acc", "clus", "analyst", List.of(), 900);
Optional<TempCredential> found = broker.resolve("acc", "clus", "analyst");
assertTrue(found.isPresent());
assertEquals("analyst", found.get().dbUser());
}
@Test
void resolveMissesForUnknownUser() {
assertTrue(broker.resolve("acc", "clus", "nobody").isEmpty());
}
@Test
void resolveEvictsExpiredCredential() {
broker.issue("acc", "clus", "analyst", List.of(), 0);
assertTrue(broker.resolve("acc", "clus", "analyst").isEmpty());
}
@Test
void issueKeepsEveryUnexpiredCredentialForSameUser() {
TempCredential first = broker.issue("acc", "clus", "analyst", List.of(), 900);
TempCredential second = broker.issue("acc", "clus", "analyst", List.of(), 900);
// AWS keeps each issued password valid until its own expiry: a reissue must not
// invalidate a still-live credential.
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "clus", "analyst", first.password()));
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "clus", "analyst", second.password()));
}
@Test
void issuePrunesExpiredCredentialsForSameUser() {
broker.issue("acc", "clus", "analyst", List.of(), 0);
TempCredential live = broker.issue("acc", "clus", "analyst", List.of(), 900);
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "clus", "analyst", live.password()));
assertEquals(1, broker.liveCredentialCountForTesting("acc", "clus", "analyst"));
}
@Test
void revokeClusterDropsEveryCredentialForThatCluster() {
TempCredential a = broker.issue("acc", "clus", "analyst", List.of(), 900);
broker.issue("acc", "clus", "etl", List.of(), 900);
TempCredential other = broker.issue("acc", "other", "analyst", List.of(), 900);
broker.revokeCluster("acc", "clus");
assertTrue(broker.resolve("acc", "clus", "analyst").isEmpty());
assertEquals(RedshiftCredentialBroker.Match.PASSTHROUGH,
broker.classify("acc", "clus", "analyst", a.password()));
assertEquals(RedshiftCredentialBroker.Match.PASSTHROUGH,
broker.classify("acc", "clus", "etl", "anything"));
// A same-named DbUser on a different cluster is untouched.
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "other", "analyst", other.password()));
}
@Test
void classifyMatchesMasterEquivalentOnCorrectPassword() {
TempCredential cred = broker.issue("acc", "clus", "analyst", List.of(), 900);
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "clus", "analyst", cred.password()));
}
@Test
void classifyRejectsKnownUserWithWrongPassword() {
broker.issue("acc", "clus", "analyst", List.of(), 900);
assertEquals(RedshiftCredentialBroker.Match.REJECT,
broker.classify("acc", "clus", "analyst", "wrong"));
}
@Test
void classifyPassesThroughUnknownUser() {
assertEquals(RedshiftCredentialBroker.Match.PASSTHROUGH,
broker.classify("acc", "clus", "stranger", "whatever"));
}
@Test
void clearRemovesAllCredentials() {
broker.issue("acc", "clus", "analyst", List.of(), 900);
broker.clear();
assertTrue(broker.resolve("acc", "clus", "analyst").isEmpty());
}
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end: a non-master DbUser works for the Redshift Data API once
* GetClusterCredentials has minted a credential for it. The wire proxy and the
* Data API both connect to the container as the cluster master.
*/
@QuarkusTest
class RedshiftGetClusterCredentialsIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260822/us-east-1/redshift/aws4_request";
@Inject
RedshiftService redshift;
private String clusterId;
@BeforeAll
static void configure() {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for this integration test");
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static boolean dockerAvailable() {
try {
Process p = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true).start();
return p.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
redshift.deleteCluster(clusterId);
clusterId = null;
}
}
private void awaitFinished(String id) {
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(250)).until(() -> {
String status = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status");
assertTrue(!"FAILED".equals(status) && !"ABORTED".equals(status),
() -> "statement " + id + " ended " + status);
return "FINISHED".equals(status);
});
}
@Test
void nonMasterDbUserWorksAfterGetClusterCredentials() {
clusterId = "it-gcc-" + System.currentTimeMillis();
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "analyst")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<DbUser>IAM:analyst</DbUser>"))
.body(containsString("<DbPassword>"))
.body(containsString("<Expiration>"));
// A client passes back the exact DbUser that GetClusterCredentials returned.
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT 1", "ClusterIdentifier": "%s", "DbUser": "IAM:analyst", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(id);
Object value = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue");
assertEquals(1, ((Number) value).intValue());
}
}
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftIamDbUserResolverTest {
private IamService iamService;
private AccountResolver accountResolver;
private RedshiftIamDbUserResolver resolver;
@BeforeEach
void setUp() {
iamService = mock(IamService.class);
accountResolver = mock(AccountResolver.class);
resolver = new RedshiftIamDbUserResolver(iamService, accountResolver);
}
@Test
void mapsIamUserArnToIamPrefix() {
when(accountResolver.extractAccessKeyId("auth")).thenReturn("AKIA123");
when(iamService.resolveCallerArn("AKIA123"))
.thenReturn(Optional.of("arn:aws:iam::000000000000:user/alice"));
assertEquals("IAM:alice", resolver.resolveDbUser("auth"));
}
@Test
void stripsIamPathPrefixFromUserName() {
when(accountResolver.extractAccessKeyId("auth")).thenReturn("AKIA123");
when(iamService.resolveCallerArn("AKIA123"))
.thenReturn(Optional.of("arn:aws:iam::000000000000:user/team/lead/alice"));
assertEquals("IAM:alice", resolver.resolveDbUser("auth"));
}
@Test
void mapsAssumedRoleArnToIamrPrefix() {
when(accountResolver.extractAccessKeyId("auth")).thenReturn("ASIA123");
when(iamService.resolveCallerArn("ASIA123"))
.thenReturn(Optional.of("arn:aws:sts::000000000000:assumed-role/Deployer/session-1"));
assertEquals("IAMR:Deployer", resolver.resolveDbUser("auth"));
}
@Test
void fallsBackWhenCallerUnresolved() {
when(accountResolver.extractAccessKeyId("auth")).thenReturn("AKIA123");
when(iamService.resolveCallerArn("AKIA123")).thenReturn(Optional.empty());
assertEquals("IAMR:floci", resolver.resolveDbUser("auth"));
}
@Test
void fallsBackWhenHeaderMissing() {
when(accountResolver.extractAccessKeyId(null)).thenReturn(null);
assertEquals("IAMR:floci", resolver.resolveDbUser(null));
}
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
@@ -26,11 +28,30 @@ class RedshiftQueryHandlerTest {
private RedshiftQueryHandler handler;
private RedshiftService service;
private RedshiftCredentialBroker credentialBroker;
private EmulatorConfig config;
private RedshiftIamDbUserResolver iamDbUserResolver;
private RegionResolver regionResolver;
@BeforeEach
void setUp() {
service = mock(RedshiftService.class);
handler = new RedshiftQueryHandler(service);
credentialBroker = new RedshiftCredentialBroker();
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().redshift().defaultCredentialDurationSeconds()).thenReturn(900);
iamDbUserResolver = mock(RedshiftIamDbUserResolver.class);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("acc");
handler = new RedshiftQueryHandler(service, credentialBroker, config, iamDbUserResolver, regionResolver);
}
private Cluster availableCluster(String id) {
Cluster c = new Cluster();
c.setClusterIdentifier(id);
c.setMasterUsername("admin");
c.setMasterPassword("SecretPass1");
c.setClusterStatus("available");
return c;
}
@Test
@@ -374,4 +395,174 @@ class RedshiftQueryHandlerTest {
assertTrue(xml.contains("<Key>env</Key>"));
assertTrue(xml.contains("<Value>prod</Value>"));
}
// ── GetClusterCredentials ────────────────────────────────────────────────
@Test
void getClusterCredentialsReturnsUserPasswordAndExpiration() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
Response response = handler.handle("GetClusterCredentials", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAM:analyst</DbUser>"));
assertTrue(xml.contains("<DbPassword>"));
assertTrue(xml.contains("<Expiration>"));
assertTrue(xml.contains("<GetClusterCredentialsResult>"));
}
@Test
void getClusterCredentialsStoresCredentialInBroker() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
handler.handle("GetClusterCredentials", params);
assertTrue(credentialBroker.resolve("acc", "c1", "IAM:analyst").isPresent());
}
@Test
void getClusterCredentialsRejectsMissingDbUser() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("GetClusterCredentials", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void getClusterCredentialsClampsAnOutOfRangeConfigDefault() {
when(config.services().redshift().defaultCredentialDurationSeconds()).thenReturn(5);
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
handler.handle("GetClusterCredentials", params);
java.time.Instant expiresAt = credentialBroker.resolve("acc", "c1", "IAM:analyst").orElseThrow().expiresAt();
assertTrue(expiresAt.isAfter(java.time.Instant.now().plusSeconds(800)),
"an out-of-range config default must fall back to the AWS minimum, not be used as-is");
}
@Test
void getClusterCredentialsRejectsDurationBelowMinimum() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
params.putSingle("DurationSeconds", "899");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("GetClusterCredentials", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void getClusterCredentialsRejectsDurationAboveMaximum() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
params.putSingle("DurationSeconds", "3601");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("GetClusterCredentials", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void getClusterCredentialsAutoCreateTruePrefixesIamaOnDbUser() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
params.putSingle("AutoCreate", "true");
Response response = handler.handle("GetClusterCredentials", params);
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAMA:analyst</DbUser>"));
}
@Test
void getClusterCredentialsAutoCreateFalsePrefixesIamOnDbUser() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
Response response = handler.handle("GetClusterCredentials", params);
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAM:analyst</DbUser>"));
}
@Test
void getClusterCredentialsEchoesDbGroups() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "analyst");
params.putSingle("DbGroups.member.1", "etl");
params.putSingle("DbGroups.member.2", "readonly");
Response response = handler.handle("GetClusterCredentials", params);
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbGroup>etl</DbGroup>"));
assertTrue(xml.contains("<DbGroup>readonly</DbGroup>"));
}
@Test
void getClusterCredentialsPropagatesClusterNotFound() {
when(service.describeClusters("missing"))
.thenThrow(new AwsException("ClusterNotFound", "Cluster missing not found", 404));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "missing");
params.putSingle("DbUser", "analyst");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("GetClusterCredentials", params));
assertEquals("ClusterNotFound", ex.getErrorCode());
}
// ── GetClusterCredentialsWithIAM ─────────────────────────────────────────
@Test
void getClusterCredentialsWithIamDerivesDbUserFromCaller() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
when(iamDbUserResolver.resolveDbUser(any())).thenReturn("IAMR:Deployer");
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
Response response = handler.handle("GetClusterCredentialsWithIAM", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAMR:Deployer</DbUser>"));
assertTrue(xml.contains("<GetClusterCredentialsWithIAMResult>"));
}
@Test
void getClusterCredentialsWithIamIgnoresDbUserParam() {
when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1")));
when(iamDbUserResolver.resolveDbUser(any())).thenReturn("IAM:alice");
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("DbUser", "ignored");
Response response = handler.handle("GetClusterCredentialsWithIAM", params);
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAM:alice</DbUser>"));
}
}
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,6 +47,7 @@ class RedshiftServiceTest {
private RegionResolver regionResolver;
private RedshiftProxyManager proxyManager;
private DockerHostResolver dockerHostResolver;
private RedshiftCredentialBroker credentialBroker;
private RedshiftService service;
@BeforeEach
@@ -85,7 +87,10 @@ class RedshiftServiceTest {
regionResolver = new RegionResolver("us-east-1", "111111111111");
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver);
credentialBroker = new RedshiftCredentialBroker();
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker);
}
/** Absolute dump path as {@code createSnapshot} now stores it: under {@code <persistentPath>/redshift-dumps/<accountId>}. */
@@ -250,14 +255,21 @@ class RedshiftServiceTest {
void createClusterRemovesMetadataOnFailure() {
when(clusterBackend.accountId()).thenReturn("111111111111");
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
// Simulate a concurrent GetClusterCredentials landing while the row exists, then fail
// container startup so the rollback path runs.
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("password123")))
.thenThrow(new RuntimeException("startup failed"));
.thenAnswer(inv -> {
credentialBroker.issue("111111111111", "c1", "analyst", List.of(), 900);
throw new RuntimeException("startup failed");
});
assertThrows(AwsException.class, () ->
service.createCluster("c1", "dc2.large", "admin", "password123"));
verify(clusterBackend).delete("c1");
verify(clusterBackend, atLeastOnce()).flush();
// The rollback that removes the cluster row must also drop that credential.
assertTrue(credentialBroker.resolve("111111111111", "c1", "analyst").isEmpty());
}
@Test
@@ -347,6 +359,18 @@ class RedshiftServiceTest {
verify(clusterBackend).delete("test-c");
}
@Test
void deleteClusterRevokesItsGetClusterCredentialsCredentials() {
Cluster c = new Cluster();
c.setClusterIdentifier("test-c");
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
credentialBroker.issue("111111111111", "test-c", "analyst", List.of(), 900);
service.deleteCluster("test-c");
assertTrue(credentialBroker.resolve("111111111111", "test-c", "analyst").isEmpty());
}
@Test
void deleteClusterAbortsAndKeepsMetadataWhenTheProxyWontStop() {
Cluster c = new Cluster();
@@ -1101,4 +1125,77 @@ class RedshiftServiceTest {
String resource = arn.substring(arn.lastIndexOf(':') + 1);
return resource.contains("/") ? resource.substring(resource.lastIndexOf('/') + 1) : resource;
}
// ── passwordValidatorFor / GetClusterCredentials broker wiring ─────────────
private void seedCluster(String accountId, String clusterId) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(clusterId);
cluster.setMasterUsername("admin");
cluster.setMasterPassword("SecretPass1");
when(clusterBackend.getForAccount(accountId, clusterId)).thenReturn(Optional.of(cluster));
}
@Test
void passwordValidatorAcceptsMasterPair() {
seedCluster("acc", "c1");
PasswordValidator validator =
service.passwordValidatorForTesting("acc", "c1");
assertEquals(PasswordValidator.AuthResult.MASTER_EQUIVALENT,
validator.validate("admin", "SecretPass1"));
}
@Test
void passwordValidatorRejectsEverythingWhenClusterRowIsAbsent() {
when(clusterBackend.getForAccount("acc", "gone")).thenReturn(Optional.empty());
PasswordValidator validator = service.passwordValidatorForTesting("acc", "gone");
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("admin", "SecretPass1"));
assertEquals(PasswordValidator.AuthResult.REJECT, validator.validate("analyst", "anything"));
}
@Test
void passwordValidatorRejectsMasterUserWithWrongPassword() {
seedCluster("acc", "c1");
PasswordValidator validator = service.passwordValidatorForTesting("acc", "c1");
assertEquals(PasswordValidator.AuthResult.REJECT,
validator.validate("admin", "not-the-master-password"));
}
@Test
void passwordValidatorAcceptsLiveBrokerCredentialAsMasterEquivalent() {
seedCluster("acc", "c1");
TempCredential cred = credentialBroker.issue("acc", "c1", "analyst", List.of(), 900);
PasswordValidator validator =
service.passwordValidatorForTesting("acc", "c1");
assertEquals(PasswordValidator.AuthResult.MASTER_EQUIVALENT,
validator.validate("analyst", cred.password()));
}
@Test
void passwordValidatorRejectsKnownBrokerUserWithWrongPassword() {
seedCluster("acc", "c1");
credentialBroker.issue("acc", "c1", "analyst", List.of(), 900);
PasswordValidator validator =
service.passwordValidatorForTesting("acc", "c1");
assertEquals(PasswordValidator.AuthResult.REJECT,
validator.validate("analyst", "nope"));
}
@Test
void passwordValidatorPassesThroughUnknownUser() {
seedCluster("acc", "c1");
PasswordValidator validator =
service.passwordValidatorForTesting("acc", "c1");
assertEquals(PasswordValidator.AuthResult.PASSTHROUGH,
validator.validate("someone-else", "whatever"));
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -69,7 +70,7 @@ class RedshiftAuthProxyTest {
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
proxy.start(proxyPort);
@@ -123,7 +124,7 @@ class RedshiftAuthProxyTest {
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
proxy.start(proxyPort);
@@ -154,7 +155,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
proxy.start(proxyPort); // must not throw despite the port being busy at first
@@ -167,7 +168,7 @@ class RedshiftAuthProxyTest {
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "old", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
proxy.start(proxyPort);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -34,7 +35,7 @@ class RedshiftProxyManagerTest {
private static void start(RedshiftProxyManager manager, String key, int proxyPort) {
manager.startProxy(key, proxyPort, "localhost", 1, "localhost",
"admin", "secret", "dev", (user, password) -> true);
"admin", "secret", "dev", (user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
}
@Test
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -21,7 +23,9 @@ import static org.mockito.Mockito.when;
class RedshiftDataResourceResolverTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "acc";
private final ObjectMapper mapper = new ObjectMapper();
private final RedshiftCredentialBroker broker = new RedshiftCredentialBroker();
private static Cluster cluster() {
Cluster c = new Cluster();
@@ -34,7 +38,9 @@ class RedshiftDataResourceResolverTest {
}
private RedshiftDataResourceResolver resolver(RedshiftService redshift, SecretsManagerService secrets) {
return new RedshiftDataResourceResolver(redshift, secrets, mapper);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
return new RedshiftDataResourceResolver(redshift, secrets, mapper, broker, regionResolver);
}
@Test
@@ -94,6 +100,24 @@ class RedshiftDataResourceResolverTest {
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void resolvesLiveMintedDbUserAsMaster() {
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(cluster()));
broker.issue(ACCOUNT, "wh", "analyst", List.of(), 900);
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "wh");
req.put("DbUser", "analyst");
req.put("Database", "dev");
RedshiftDataResourceResolver.DatabaseTarget target =
resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION);
assertEquals("admin", target.user());
assertEquals("Secret123", target.password());
}
@Test
void resolvesSecretArn() {
RedshiftService redshift = mock(RedshiftService.class);