From 6b17ef2b1c13e66ce2101a732efd5fc2f47d316d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:58:33 +0700 Subject: [PATCH] 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:, an assumed role to IAMR:, 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. --- .../hectorvent/floci/compat/RedshiftTest.java | 35 ++++ docs/services/index.md | 2 +- docs/services/redshift-data.md | 2 +- docs/services/redshift.md | 7 +- .../floci/config/EmulatorConfig.java | 5 + .../floci/core/common/AwsQueryController.java | 5 +- .../services/rds/proxy/PasswordValidator.java | 17 +- .../rds/proxy/PostgresProtocolHandler.java | 43 +++- .../services/rds/proxy/RdsAuthProxy.java | 25 ++- .../services/rds/proxy/RdsProxyManager.java | 2 +- .../redshift/RedshiftCredentialBroker.java | 108 ++++++++++ .../redshift/RedshiftIamDbUserResolver.java | 53 +++++ .../redshift/RedshiftQueryHandler.java | 120 ++++++++++- .../services/redshift/RedshiftService.java | 58 +++++- .../services/redshift/TempCredential.java | 7 + .../redshift/proxy/RedshiftAuthProxy.java | 8 +- .../redshift/proxy/RedshiftProxyManager.java | 4 +- .../RedshiftDataResourceResolver.java | 26 ++- src/main/resources/application.yml | 1 + .../floci/services/rds/RdsServiceTest.java | 4 +- .../rds/proxy/MySqlProtocolHandlerTest.java | 8 +- ...PostgresProtocolHandlerAuthResultTest.java | 49 +++++ .../proxy/PostgresProtocolHandlerTest.java | 28 +-- .../RedshiftCredentialBrokerTest.java | 124 +++++++++++ ...tGetClusterCredentialsIntegrationTest.java | 100 +++++++++ .../RedshiftIamDbUserResolverTest.java | 68 ++++++ .../redshift/RedshiftQueryHandlerTest.java | 193 +++++++++++++++++- .../redshift/RedshiftServiceTest.java | 101 ++++++++- .../redshift/proxy/RedshiftAuthProxyTest.java | 9 +- .../proxy/RedshiftProxyManagerTest.java | 3 +- .../RedshiftDataResourceResolverTest.java | 26 ++- src/test/resources/application.yml | 1 + tools/docs/services.yaml | 7 +- 33 files changed, 1172 insertions(+), 77 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBroker.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolver.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshift/TempCredential.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerAuthResultTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBrokerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftGetClusterCredentialsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolverTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java index 69bd877dc2..a0da478d40 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java @@ -14,6 +14,8 @@ import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest; import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse; import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterResponse; +import software.amazon.awssdk.services.redshift.model.GetClusterCredentialsResponse; +import software.amazon.awssdk.services.redshift.model.GetClusterCredentialsWithIamResponse; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; @@ -152,6 +154,39 @@ public class RedshiftTest { @Test @Order(3) + public void testGetClusterCredentialsReturnsTemporaryCredentials() throws Exception { + RedshiftClient client = getClient(); + GetClusterCredentialsResponse res = withRetry(() -> client.getClusterCredentials(b -> b + .clusterIdentifier("test-cluster") + .dbUser("analyst") + .dbName("dev") + .durationSeconds(900))); + + assertNotNull(res.dbUser()); + assertTrue(res.dbUser().contains("analyst")); + assertNotNull(res.dbPassword()); + assertTrue(!res.dbPassword().isBlank()); + assertNotNull(res.expiration()); + } + + @Test + @Order(4) + public void testGetClusterCredentialsWithIamReturnsIamPrefixedUser() throws Exception { + RedshiftClient client = getClient(); + GetClusterCredentialsWithIamResponse res = withRetry(() -> client.getClusterCredentialsWithIAM(b -> b + .clusterIdentifier("test-cluster") + .dbName("dev") + .durationSeconds(900))); + + assertNotNull(res.dbUser()); + assertTrue(res.dbUser().startsWith("IAM")); + assertNotNull(res.dbPassword()); + assertTrue(!res.dbPassword().isBlank()); + assertNotNull(res.expiration()); + } + + @Test + @Order(5) public void testDeleteCluster() throws Exception { RedshiftClient client = getClient(); DeleteClusterResponse res = withRetry(() -> client.deleteCluster(DeleteClusterRequest.builder() diff --git a/docs/services/index.md b/docs/services/index.md index b171d81282..853e04ed74 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -68,7 +68,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Lake Formation](lakeformation.md) | `POST /` | REST JSON | 16 | | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 8 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire | 21 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire | 23 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 | | [EMR Serverless](emr-serverless.md) | `/applications/*` | REST JSON | 7 | diff --git a/docs/services/redshift-data.md b/docs/services/redshift-data.md index fa8b6a28d2..9d50bcfaab 100644 --- a/docs/services/redshift-data.md +++ b/docs/services/redshift-data.md @@ -36,7 +36,7 @@ For the upstream API shape, see the AWS documentation: A request identifies its target cluster one of two ways: -- **`ClusterIdentifier` + `DbUser` + `Database`.** The `DbUser` must be the cluster master user. Floci connects directly to the container, so a non-master `DbUser` needs a real PostgreSQL role; until `GetClusterCredentials` is emulated, a non-master `DbUser` returns `ValidationException`. +- **`ClusterIdentifier` + `DbUser` + `Database`.** The `DbUser` is the cluster master, or the prefixed name returned by `GetClusterCredentials` / `GetClusterCredentialsWithIAM` (for example `IAM:analyst`) while that credential is unexpired. Floci connects to the container as the cluster master in both cases. Any other `DbUser` returns `ValidationException`. - **`SecretArn` + `ClusterIdentifier` + `Database`.** The secret must be a local Secrets Manager secret holding JSON credentials (`username` or `user`, plus `password`). A cross-region `SecretArn` is rejected. `WorkgroupName` (Amazon Redshift Serverless) is rejected with `ValidationException`. Redshift Serverless is not emulated. diff --git a/docs/services/redshift.md b/docs/services/redshift.md index c74f9cbd6f..32c24ca77f 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -38,6 +38,8 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `DeleteClusterSubnetGroup` | Remove a subnet group | | `ModifyCluster` | Update node type, parameter group, security groups, or the master password | | `RebootCluster` | Restart a cluster's container | +| `GetClusterCredentials` | Issue a short-lived DbUser / DbPassword pair the auth proxy and Data API accept for a non-master user | +| `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity | ## Configuration @@ -177,6 +179,7 @@ order) through its own S3 service and streams the rows into the backing PostgreS - The rewrite is textual (regex-based). It masks single-quoted string literals first, so `DEFAULT` / `CHECK` string values are safe, but it is **not** comment-aware and does not recognize escape strings (`E'...'`): an apostrophe inside a `--` or `/* */` comment can make the rewrite skip a Redshift clause. That fails safe: the statement then reaches PostgreSQL, which returns its own syntax error, but avoid apostrophes-in-comments in `CREATE TABLE` / `ALTER TABLE`. - A `rewrite` failure or any statement the interceptor does not recognize is forwarded unmodified (fail-open); PostgreSQL then rejects the Redshift-only syntax itself. - Simple Query ('Q') messages larger than 16 MiB bypass the interceptor and stream through verbatim without heap buffering; non-query traffic also streams through with no size limit. +- `GetClusterCredentials` / `GetClusterCredentialsWithIAM` mint a short-lived password held in memory (lost on restart). As in AWS, `GetClusterCredentials` prefixes the returned `DbUser` with `IAM:` when `AutoCreate` is false and `IAMA:` when it is true; that prefixed name is what the auth proxy and Data API accept. The returned `DbUser` is nominal: the session runs as the cluster master, not a distinct PostgreSQL role, so `current_user`, `GRANT`, and object ownership are the master's. ### UNLOAD to S3 @@ -220,5 +223,5 @@ the result to S3 as one or more objects under ``. - Parameter groups apply no real engine settings; values are stored and echoed back only. - Subnet groups, VPC routing, and security groups are metadata only. - Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy. -- The auth proxy validates only the master user's password. Non-master users pass straight through to PostgreSQL, which remains the authority for their credentials. -- IAM database authentication (`GetClusterCredentials`), and `sslmode=verify-full` against the self-signed proxy certificate. +- The auth proxy validates the master user's password and any live `GetClusterCredentials` credential. Other non-master users pass straight through to PostgreSQL, which remains the authority for their credentials. +- IAM database authentication over the wire, and `sslmode=verify-full` against the self-signed proxy certificate. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 8e16db4c42..86d88ed727 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1312,6 +1312,11 @@ public interface EmulatorConfig { // Hostname clients use to reach a cluster endpoint. Empty -> resolved from // DockerHostResolver (falls back to "localhost"). Optional endpointHost(); + + // Default lifetime for GetClusterCredentials / GetClusterCredentialsWithIAM when + // DurationSeconds is omitted. AWS allows 900 to 3600. + @WithDefault("900") + int defaultCredentialDurationSeconds(); } interface RdsServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 0cb0bd9300..78241e481a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -356,7 +356,7 @@ public class AwsQueryController { : elbV2QueryHandler.handle(action, formParams, region); case "autoscaling" -> autoScalingQueryHandler.handle(action, formParams, region); case "elasticbeanstalk" -> elasticBeanstalkQueryHandler.handle(action, formParams, region); - case "redshift" -> redshiftQueryHandler.handle(action, formParams); + case "redshift" -> redshiftQueryHandler.handle(action, formParams, authorization); default -> xmlErrorResponse("UnknownService", "Unknown or unsupported service: " + service, 400); }; @@ -605,7 +605,8 @@ public class AwsQueryController { "CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup", "ModifyClusterParameterGroup", "CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup", - "CreateTags", "DeleteTags", "DescribeTags" + "CreateTags", "DeleteTags", "DescribeTags", + "GetClusterCredentials", "GetClusterCredentialsWithIAM" ); private String resolveService(String authorization, String action) { diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PasswordValidator.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PasswordValidator.java index bc4a36812f..87e228d39d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PasswordValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PasswordValidator.java @@ -1,6 +1,17 @@ package io.github.hectorvent.floci.services.rds.proxy; @FunctionalInterface - public interface PasswordValidator { - boolean validate(String username, String password); - } \ No newline at end of file +public interface PasswordValidator { + + AuthResult validate(String username, String password); + + /** + * REJECT : refuse the client. + * PASSTHROUGH : the proxy does not vouch for this user; forward the + * client's own credentials so the backend enforces them + * (legacy non-master behaviour). + * MASTER_EQUIVALENT: the proxy has validated the client; open the backend + * connection as the cluster master. + */ + enum AuthResult { REJECT, PASSTHROUGH, MASTER_EQUIVALENT } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java index 824d482298..60972bcbda 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java @@ -54,6 +54,26 @@ public class PostgresProtocolHandler { */ public record AuthenticatedSession(Socket client, String iamRole) {} + /** The username/password the proxy opens the backend PostgreSQL connection with. */ + record BackendLogin(String user, String password) {} + + /** + * Picks the backend login: the cluster master whenever the proxy is the authority for this + * connection (an IAM token, the master user itself, or a client the validator vouched for), + * otherwise the client's own credentials so the backend enforces its ACLs. + */ + static BackendLogin resolveBackendLogin(boolean isMaster, boolean isIam, + PasswordValidator.AuthResult result, + String masterUsername, String masterPassword, + String clientUsername, String clientPassword) { + boolean useMaster = isIam || isMaster + || result == PasswordValidator.AuthResult.MASTER_EQUIVALENT; + if (useMaster) { + return new BackendLogin(masterUsername, masterPassword); + } + return new BackendLogin(clientUsername, clientPassword); + } + public static AuthenticatedSession authenticate(Socket client, Socket backend, String masterUsername, String masterPassword, String dbName, boolean iamEnabled, RdsSigV4Validator sigV4, @@ -84,12 +104,15 @@ public class PostgresProtocolHandler { // Phase 4: Validate credentials. // - IAM tokens: validated locally via SigV4. - // - Master user (plain password): validated at the proxy via passwordValidator, which - // reads from RdsService and therefore reflects modifyDBInstance password changes. - // - Non-master users: pass through — the backend is the authority for their passwords. + // - Every non-IAM client: classified by passwordValidator into REJECT / PASSTHROUGH / + // MASTER_EQUIVALENT. PASSTHROUGH keeps the legacy non-master behaviour (the backend is + // the authority for the password); MASTER_EQUIVALENT means the proxy vouched for the + // client, so the backend leg runs as the cluster master. The RDS validator reads from + // RdsService, so a master login still reflects modifyDBInstance password changes. boolean isIam = iamEnabled && clientPassword.contains("X-Amz-Signature"); boolean isMaster = masterUsername.equals(clientUsername); + PasswordValidator.AuthResult authResult = PasswordValidator.AuthResult.PASSTHROUGH; if (isIam) { if (!sigV4.validate(clientPassword, clientUsername)) { sendErrorResponse(clientOut, "FATAL", "28P01", @@ -99,8 +122,9 @@ public class PostgresProtocolHandler { closeQuietly(backend); return null; } - } else if (isMaster) { - if (!passwordValidator.validate(clientUsername, clientPassword)) { + } else { + authResult = passwordValidator.validate(clientUsername, clientPassword); + if (authResult == PasswordValidator.AuthResult.REJECT) { sendErrorResponse(clientOut, "FATAL", "28P01", "password authentication failed for user \"" + clientUsername + "\""); clientOut.flush(); @@ -113,13 +137,16 @@ public class PostgresProtocolHandler { // Phase 5: Connect to backend PostgreSQL. // IAM and master: use master credentials — the backend has the original container password // and is never updated directly, so the proxy always authenticates as master. - // Non-master: forward the client's own credentials so the backend enforces its own ACLs. + // Non-master: forward the client's own credentials so the backend enforces its own ACLs, + // unless the proxy vouched for the client (MASTER_EQUIVALENT). InputStream backendIn = backend.getInputStream(); OutputStream backendOut = backend.getOutputStream(); String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName); - String backendUser = (isIam || isMaster) ? masterUsername : clientUsername; - String backendPass = (isIam || isMaster) ? masterPassword : clientPassword; + BackendLogin backendLogin = resolveBackendLogin(isMaster, isIam, authResult, + masterUsername, masterPassword, clientUsername, clientPassword); + String backendUser = backendLogin.user(); + String backendPass = backendLogin.password(); sendStartupToBackend(backendOut, backendUser, effectiveDbName); backendOut.flush(); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java index 96bf83430a..205ba02f70 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java @@ -27,7 +27,7 @@ public class RdsAuthProxy { private final DatabaseEngine engine; private final RdsSigV4Validator sigV4; private final RdsProxyTlsCertificates tlsCertificates; - private final PasswordValidator passwordValidator; + private final MasterPasswordCheck passwordValidator; private volatile boolean running; private ServerSocket serverSocket; @@ -36,7 +36,7 @@ public class RdsAuthProxy { DatabaseEngine engine, boolean iamEnabled, String masterUsername, String masterPassword, String dbName, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, - PasswordValidator passwordValidator) { + MasterPasswordCheck passwordValidator) { this.instanceId = instanceId; this.backendHost = backendHost; this.backendPort = backendPort; @@ -99,19 +99,30 @@ public class RdsAuthProxy { backend = new Socket(backendHost, backendPort); backend.setTcpNoDelay(true); + // RDS only proxy-validates the master user; a non-master user passes through so the + // backend enforces its own credentials. + PasswordValidator authAdapter = (user, pass) -> { + if (!masterUsername.equals(user)) { + return PasswordValidator.AuthResult.PASSTHROUGH; + } + return passwordValidator.validate(user, pass) + ? PasswordValidator.AuthResult.MASTER_EQUIVALENT + : PasswordValidator.AuthResult.REJECT; + }; + switch (engine) { case POSTGRES -> { PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate( client, backend, masterUsername, masterPassword, dbName, - iamEnabled, sigV4, tlsCertificates, passwordValidator::validate); + iamEnabled, sigV4, tlsCertificates, authAdapter); if (session != null) { PostgresProtocolHandler.bridge(session, backend); } } case MYSQL, MARIADB -> MySqlProtocolHandler.handleAuth( client, backend, masterUsername, masterPassword, - iamEnabled, sigV4, tlsCertificates, passwordValidator::validate); + iamEnabled, sigV4, tlsCertificates, authAdapter); } } catch (Exception e) { LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage()); @@ -135,10 +146,12 @@ public class RdsAuthProxy { } /** - * Callback for password validation — implemented by RdsService. + * Callback for master-password validation, implemented by RdsService. Returns true when the + * supplied master credentials are current. Non-master users are never asked here: the backend + * database is the authority for their passwords. */ @FunctionalInterface - public interface PasswordValidator { + public interface MasterPasswordCheck { boolean validate(String username, String password); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java index 75eb0f0ae3..778d1c35ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java @@ -30,7 +30,7 @@ public class RdsProxyManager { int proxyPort, String backendHost, int backendPort, String advertisedHost, String masterUsername, String masterPassword, String dbName, - RdsAuthProxy.PasswordValidator passwordValidator) { + RdsAuthProxy.MasterPasswordCheck passwordValidator) { tlsCertificates.ensureHost(advertisedHost); RdsAuthProxy proxy = new RdsAuthProxy( instanceId, backendHost, backendPort, engine, iamEnabled, diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBroker.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBroker.java new file mode 100644 index 0000000000..3ce5bf642e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBroker.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.redshift; + +import io.github.hectorvent.floci.core.common.Resettable; +import jakarta.enterprise.context.ApplicationScoped; + +import java.security.SecureRandom; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Holds the short-lived credentials minted by GetClusterCredentials / + * GetClusterCredentialsWithIAM. No real PostgreSQL role is created: a live + * credential is a signal to the auth proxy and the Data API resolver that the + * connection should run as the cluster master (the DbUser is nominal). + * + *

AWS keeps every issued credential valid until its own expiry, so a second + * call for the same DbUser does not invalidate the first: each key holds a list + * of unexpired credentials. + */ +@ApplicationScoped +public class RedshiftCredentialBroker implements Resettable { + + public enum Match { MASTER_EQUIVALENT, REJECT, PASSTHROUGH } + + private static final String PASSWORD_ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int PASSWORD_LENGTH = 32; + + private final SecureRandom random = new SecureRandom(); + private final ConcurrentHashMap> store = new ConcurrentHashMap<>(); + + public TempCredential issue(String accountId, String clusterId, String dbUser, + List dbGroups, int durationSeconds) { + String password = randomPassword(); + Instant expiresAt = Instant.now().plusSeconds(durationSeconds); + List groups = dbGroups == null ? List.of() : List.copyOf(dbGroups); + TempCredential credential = new TempCredential(dbUser, password, expiresAt, groups); + store.compute(key(accountId, clusterId, dbUser), (k, existing) -> { + CopyOnWriteArrayList list = + existing == null ? new CopyOnWriteArrayList<>() : existing; + list.removeIf(RedshiftCredentialBroker::isExpired); + list.add(credential); + return list; + }); + return credential; + } + + public Optional resolve(String accountId, String clusterId, String dbUser) { + return liveCredentials(key(accountId, clusterId, dbUser)).stream().findFirst(); + } + + public Match classify(String accountId, String clusterId, String username, String password) { + List live = liveCredentials(key(accountId, clusterId, username)); + if (live.isEmpty()) { + return Match.PASSTHROUGH; + } + return live.stream().anyMatch(c -> c.password().equals(password)) + ? Match.MASTER_EQUIVALENT + : Match.REJECT; + } + + /** + * Drops every credential minted for a cluster. Called when a cluster is deleted so a + * later cluster created with the same identifier does not inherit master-equivalent + * access from a stale credential. + */ + public void revokeCluster(String accountId, String clusterId) { + String prefix = accountId + ":" + clusterId + ":"; + store.keySet().removeIf(k -> k.startsWith(prefix)); + } + + @Override + public void clear() { + store.clear(); + } + + // Package-private hook for tests: number of unexpired credentials held for a DbUser. + int liveCredentialCountForTesting(String accountId, String clusterId, String dbUser) { + return liveCredentials(key(accountId, clusterId, dbUser)).size(); + } + + private List liveCredentials(String key) { + CopyOnWriteArrayList list = store.get(key); + if (list == null) { + return List.of(); + } + return list.stream().filter(c -> !isExpired(c)).toList(); + } + + private static boolean isExpired(TempCredential credential) { + return !credential.expiresAt().isAfter(Instant.now()); + } + + private String randomPassword() { + StringBuilder sb = new StringBuilder(PASSWORD_LENGTH); + for (int i = 0; i < PASSWORD_LENGTH; i++) { + sb.append(PASSWORD_ALPHABET.charAt(random.nextInt(PASSWORD_ALPHABET.length()))); + } + return sb.toString(); + } + + private static String key(String accountId, String clusterId, String dbUser) { + return accountId + ":" + clusterId + ":" + dbUser; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolver.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolver.java new file mode 100644 index 0000000000..b322fcbab6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolver.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.redshift; + +import io.github.hectorvent.floci.core.common.AccountResolver; +import io.github.hectorvent.floci.services.iam.IamService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Optional; + +/** + * Derives the Redshift Data API DbUser name for GetClusterCredentialsWithIAM from + * the caller's IAM identity: an IAM user becomes "IAM:", an assumed role + * becomes "IAMR:". When the caller cannot be resolved (for example a bare + * test key with no registered identity) the call still succeeds with a fixed + * fallback so local and CI flows are not blocked. + */ +@ApplicationScoped +public class RedshiftIamDbUserResolver { + + private static final Logger LOG = Logger.getLogger(RedshiftIamDbUserResolver.class); + private static final String FALLBACK_DB_USER = "IAMR:floci"; + + private final IamService iamService; + private final AccountResolver accountResolver; + + @Inject + public RedshiftIamDbUserResolver(IamService iamService, AccountResolver accountResolver) { + this.iamService = iamService; + this.accountResolver = accountResolver; + } + + public String resolveDbUser(String authorizationHeader) { + String accessKeyId = accountResolver.extractAccessKeyId(authorizationHeader); + Optional arn = iamService.resolveCallerArn(accessKeyId); + if (arn.isEmpty()) { + LOG.warnv("GetClusterCredentialsWithIAM caller could not be resolved; using {0}", FALLBACK_DB_USER); + return FALLBACK_DB_USER; + } + String resource = arn.get().substring(arn.get().lastIndexOf(':') + 1); + if (resource.startsWith("assumed-role/")) { + String[] parts = resource.split("/"); + return parts.length >= 2 ? "IAMR:" + parts[1] : FALLBACK_DB_USER; + } + if (resource.startsWith("user/")) { + // Drop any IAM path prefix (user/team/alice -> alice), matching how AWS names the DbUser. + return "IAM:" + resource.substring(resource.lastIndexOf('/') + 1); + } + LOG.warnv("GetClusterCredentialsWithIAM caller ARN {0} is not a user or role; using {1}", + arn.get(), FALLBACK_DB_USER); + return FALLBACK_DB_USER; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java index b974fa0729..3e236a8fdd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java @@ -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.core.common.XmlBuilder; import io.github.hectorvent.floci.services.redshift.model.Cluster; import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup; @@ -12,7 +14,9 @@ import jakarta.inject.Inject; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -22,14 +26,35 @@ import java.util.regex.Pattern; @ApplicationScoped public class RedshiftQueryHandler { + + private static final Logger LOG = Logger.getLogger(RedshiftQueryHandler.class); + + // GetClusterCredentials DurationSeconds bounds, inclusive (AWS: 900 to 3600). + private static final int MIN_CREDENTIAL_DURATION_SECONDS = 900; + private static final int MAX_CREDENTIAL_DURATION_SECONDS = 3600; + private final RedshiftService service; + private final RedshiftCredentialBroker credentialBroker; + private final EmulatorConfig config; + private final RedshiftIamDbUserResolver iamDbUserResolver; + private final RegionResolver regionResolver; @Inject - public RedshiftQueryHandler(RedshiftService service) { + public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker, + EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver, + RegionResolver regionResolver) { this.service = service; + this.credentialBroker = credentialBroker; + this.config = config; + this.iamDbUserResolver = iamDbUserResolver; + this.regionResolver = regionResolver; } public Response handle(String action, MultivaluedMap params) { + return handle(action, params, null); + } + + public Response handle(String action, MultivaluedMap params, String authorizationHeader) { switch (action) { case "CreateCluster" -> { String identifier = params.getFirst("ClusterIdentifier"); @@ -414,10 +439,102 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "GetClusterCredentials" -> { + String clusterId = requireParam(params, "ClusterIdentifier"); + String dbUser = requireParam(params, "DbUser"); + // describeClusters throws ClusterNotFound (404) for an unknown id. + service.describeClusters(clusterId); + // AWS prefixes the returned name IAMA: when AutoCreate is true, IAM: when it is false. + boolean autoCreate = Boolean.parseBoolean(params.getFirst("AutoCreate")); + String effectiveDbUser = (autoCreate ? "IAMA:" : "IAM:") + dbUser; + int duration = resolveDurationSeconds(params); + List dbGroups = memberList(params, "DbGroups"); + + TempCredential credential = credentialBroker.issue( + regionResolver.getAccountId(), clusterId, effectiveDbUser, dbGroups, duration); + return Response.ok(getClusterCredentialsXml("GetClusterCredentials", credential)) + .type(MediaType.APPLICATION_XML).build(); + } + case "GetClusterCredentialsWithIAM" -> { + String clusterId = requireParam(params, "ClusterIdentifier"); + service.describeClusters(clusterId); + String dbUser = iamDbUserResolver.resolveDbUser(authorizationHeader); + int duration = resolveDurationSeconds(params); + List dbGroups = memberList(params, "DbGroups"); + + TempCredential credential = credentialBroker.issue( + regionResolver.getAccountId(), clusterId, dbUser, dbGroups, duration); + return Response.ok(getClusterCredentialsXml("GetClusterCredentialsWithIAM", credential)) + .type(MediaType.APPLICATION_XML).build(); + } default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400); } } + private static String requireParam(MultivaluedMap params, String name) { + String value = params.getFirst(name); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidParameterValue", name + " is required", 400); + } + return value; + } + + private int resolveDurationSeconds(MultivaluedMap params) { + String raw = params.getFirst("DurationSeconds"); + if (raw == null || raw.isBlank()) { + return defaultDurationSeconds(); + } + int duration; + try { + duration = Integer.parseInt(raw); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", "DurationSeconds must be an integer", 400); + } + if (duration < MIN_CREDENTIAL_DURATION_SECONDS || duration > MAX_CREDENTIAL_DURATION_SECONDS) { + throw new AwsException("InvalidParameterValue", + "DurationSeconds must be between " + MIN_CREDENTIAL_DURATION_SECONDS + + " and " + MAX_CREDENTIAL_DURATION_SECONDS, 400); + } + return duration; + } + + // The YAML default is operator-supplied, so hold it to the same AWS bounds as a request + // value: an out-of-range override falls back to the AWS minimum rather than minting a + // credential that is already expired or outlives the documented range. + private int defaultDurationSeconds() { + int configured = config.services().redshift().defaultCredentialDurationSeconds(); + if (configured < MIN_CREDENTIAL_DURATION_SECONDS || configured > MAX_CREDENTIAL_DURATION_SECONDS) { + LOG.warnv("floci.services.redshift.default-credential-duration-seconds={0} is outside the " + + "AWS range {1} to {2}; using {1}", configured, + MIN_CREDENTIAL_DURATION_SECONDS, MAX_CREDENTIAL_DURATION_SECONDS); + return MIN_CREDENTIAL_DURATION_SECONDS; + } + return configured; + } + + private String getClusterCredentialsXml(String operation, TempCredential credential) { + XmlBuilder builder = new XmlBuilder() + .start(operation + "Response") + .start(operation + "Result") + .elem("DbUser", credential.dbUser()) + .elem("DbPassword", credential.password()) + .elem("Expiration", DateTimeFormatter.ISO_INSTANT.format(credential.expiresAt())); + if (!credential.dbGroups().isEmpty()) { + builder.start("DbGroups"); + for (String group : credential.dbGroups()) { + builder.elem("DbGroup", group); + } + builder.end("DbGroups"); + } + return builder + .end(operation + "Result") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(operation + "Response") + .build(); + } + private String buildClusterXml(Cluster cluster) { XmlBuilder builder = new XmlBuilder() .start("Cluster") @@ -549,6 +666,7 @@ public class RedshiftQueryHandler { case "SubnetIds" -> quoted + "(\\.member|\\.SubnetIdentifier)?\\.\\d+"; case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+"; case "TagKeys" -> quoted + "(\\.member|\\.TagKey)?\\.\\d+"; + case "DbGroups" -> quoted + "(\\.member|\\.DbGroup)?\\.\\d+"; default -> quoted + "(\\.member)?\\.\\d+"; }; } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index 997d381b65..570d101d80 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -6,7 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; -import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy; +import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle; @@ -51,13 +51,15 @@ public class RedshiftService { private final RegionResolver regionResolver; private final RedshiftProxyManager proxyManager; private final DockerHostResolver dockerHostResolver; + private final RedshiftCredentialBroker credentialBroker; // Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM. private final Set usedPorts = ConcurrentHashMap.newKeySet(); @Inject public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, EmulatorConfig config, RegionResolver regionResolver, - RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver) { + RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver, + RedshiftCredentialBroker credentialBroker) { this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference>() {}); this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference>() {}); this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference>() {}); @@ -67,6 +69,7 @@ public class RedshiftService { this.regionResolver = regionResolver; this.proxyManager = proxyManager; this.dockerHostResolver = dockerHostResolver; + this.credentialBroker = credentialBroker; } // Recreate Docker containers for persisted clusters on app restart (across every account, not just default) @@ -133,6 +136,9 @@ public class RedshiftService { if (clusters.get(identifier).isPresent()) { throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400); } + // A previous cluster with this identifier may have been deleted without its temp + // credentials being cleared; drop them so the new cluster starts with none. + credentialBroker.revokeCluster(clusters.accountId(), identifier); Cluster cluster = new Cluster(); cluster.setClusterIdentifier(identifier); @@ -168,6 +174,7 @@ public class RedshiftService { try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); } if (proxyStopped) { clusters.delete(identifier); + credentialBroker.revokeCluster(clusters.accountId(), identifier); } else { cluster.setClusterStatus("failed"); clusters.put(identifier, cluster); @@ -179,6 +186,7 @@ public class RedshiftService { try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); } if (proxyStopped) { clusters.delete(identifier); + credentialBroker.revokeCluster(clusters.accountId(), identifier); } else { cluster.setClusterStatus("failed"); clusters.put(identifier, cluster); @@ -220,7 +228,10 @@ public class RedshiftService { containerManager.stop(clusters.accountId(), identifier); clusters.delete(identifier); clusters.flush(); - + // Invalidate any GetClusterCredentials passwords so a cluster later recreated with this + // identifier does not accept them as master-equivalent. + credentialBroker.revokeCluster(clusters.accountId(), identifier); + cluster.setClusterStatus("deleting"); return cluster; } @@ -936,11 +947,40 @@ public class RedshiftService { return accountId + ":" + clusterIdentifier; } - // Validates the master password at the proxy against current cluster state, so a - // ModifyCluster password change is reflected for new connections without a proxy restart. - private RdsAuthProxy.PasswordValidator passwordValidatorFor(String accountId, String clusterIdentifier) { - return (user, password) -> clusters.getForAccount(accountId, clusterIdentifier) - .map(c -> user.equals(c.getMasterUsername()) && password.equals(c.getMasterPassword())) - .orElse(false); + // Classifies a proxy login against current cluster state: the master pair and any live + // GetClusterCredentials credential both run the backend leg as the cluster master, a known + // broker user with a stale password is rejected, everyone else passes through to the backend. + // Reading cluster state per call means a ModifyCluster password change takes effect for new + // connections without a proxy restart. + private PasswordValidator passwordValidatorFor(String accountId, String clusterIdentifier) { + return (user, password) -> { + Optional cluster = clusters.getForAccount(accountId, clusterIdentifier); + if (cluster.isEmpty()) { + // No cluster row to validate against: vouch for nothing. Falling through to the + // broker would classify an unknown user as PASSTHROUGH, and the wire proxy reads + // isMaster from its own start-time config, so a PASSTHROUGH there still opens the + // backend as master, authenticating any password for the master username. + return PasswordValidator.AuthResult.REJECT; + } + Cluster c = cluster.get(); + if (user.equals(c.getMasterUsername())) { + // The master username is authoritative here: a wrong password must be rejected, + // never handed to the broker (which only knows minted DbUsers) and never passed + // through as if the user were unknown. + return password.equals(c.getMasterPassword()) + ? PasswordValidator.AuthResult.MASTER_EQUIVALENT + : PasswordValidator.AuthResult.REJECT; + } + return switch (credentialBroker.classify(accountId, clusterIdentifier, user, password)) { + case MASTER_EQUIVALENT -> PasswordValidator.AuthResult.MASTER_EQUIVALENT; + case REJECT -> PasswordValidator.AuthResult.REJECT; + case PASSTHROUGH -> PasswordValidator.AuthResult.PASSTHROUGH; + }; + }; + } + + // Package-private hook for tests: passwordValidatorFor is otherwise private. + PasswordValidator passwordValidatorForTesting(String accountId, String clusterIdentifier) { + return passwordValidatorFor(accountId, clusterIdentifier); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/TempCredential.java b/src/main/java/io/github/hectorvent/floci/services/redshift/TempCredential.java new file mode 100644 index 0000000000..88ab85326f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/TempCredential.java @@ -0,0 +1,7 @@ +package io.github.hectorvent.floci.services.redshift; + +import java.time.Instant; +import java.util.List; + +public record TempCredential(String dbUser, String password, Instant expiresAt, List dbGroups) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java index a2591315c1..dec3429c19 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java @@ -1,7 +1,7 @@ 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.PostgresProtocolHandler; -import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy; 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; @@ -32,7 +32,7 @@ public class RedshiftAuthProxy { private final String dbName; private final RdsSigV4Validator sigV4; private final RdsProxyTlsCertificates tlsCertificates; - private final RdsAuthProxy.PasswordValidator passwordValidator; + private final PasswordValidator passwordValidator; private final S3Service s3Service; private volatile boolean running; @@ -41,7 +41,7 @@ public class RedshiftAuthProxy { public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort, String masterUsername, String masterPassword, String dbName, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, - RdsAuthProxy.PasswordValidator passwordValidator, + PasswordValidator passwordValidator, S3Service s3Service) { this.clusterKey = clusterKey; this.backendHost = backendHost; @@ -145,7 +145,7 @@ public class RedshiftAuthProxy { PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate( client, backend, masterUsername, masterPassword, dbName, - false, sigV4, tlsCertificates, passwordValidator::validate); + false, sigV4, tlsCertificates, passwordValidator); if (session != null) { // Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain // PostgreSQL backend on the way through; every other message is relayed verbatim. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java index aebaa1d340..630a91b4e7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.redshift.proxy; -import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy; +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; @@ -46,7 +46,7 @@ public class RedshiftProxyManager { public synchronized void startProxy(String relayKey, int proxyPort, String backendHost, int backendPort, String advertisedHost, String masterUsername, String masterPassword, String dbName, - RdsAuthProxy.PasswordValidator passwordValidator) { + PasswordValidator passwordValidator) { // A prior unclosable entry for this key is left in place: its listener may still // be bound, and only a successful stop (never a fresh start) may drop it. // Make sure the self-signed proxy certificate covers the host clients will connect to, diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java index e3181a5077..51c53273d2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; 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; @@ -20,14 +22,20 @@ class RedshiftDataResourceResolver { private final RedshiftService redshiftService; private final SecretsManagerService secretsManagerService; private final ObjectMapper objectMapper; + private final RedshiftCredentialBroker credentialBroker; + private final RegionResolver regionResolver; @Inject RedshiftDataResourceResolver(RedshiftService redshiftService, SecretsManagerService secretsManagerService, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, + RedshiftCredentialBroker credentialBroker, + RegionResolver regionResolver) { this.redshiftService = redshiftService; this.secretsManagerService = secretsManagerService; this.objectMapper = objectMapper; + this.credentialBroker = credentialBroker; + this.regionResolver = regionResolver; } DatabaseTarget resolve(JsonNode request, String region) { @@ -71,11 +79,19 @@ class RedshiftDataResourceResolver { String clusterId = requiredText(request, "ClusterIdentifier"); String dbUser = requiredText(request, "DbUser"); Cluster cluster = cluster(clusterId); - if (!dbUser.equals(cluster.getMasterUsername())) { - throw validation("DbUser " + dbUser + " is not the cluster master; create it first or use " - + "GetClusterCredentials (not yet emulated)."); + + if (dbUser.equals(cluster.getMasterUsername())) { + return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword()); } - return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword()); + boolean liveCredential = credentialBroker + .resolve(regionResolver.getAccountId(), clusterId, dbUser) + .isPresent(); + if (liveCredential) { + // The minted DbUser is nominal: connect as the cluster master. + return target(clusterArn(clusterId, null), cluster, database, + cluster.getMasterUsername(), cluster.getMasterPassword()); + } + throw validation("DbUser " + dbUser + " has no active credentials; call GetClusterCredentials first."); } private Cluster cluster(String clusterId) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index fc79e681c1..3b8c29f0e6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -353,6 +353,7 @@ floci: image-version: postgres:15-alpine proxy-base-port: 7100 proxy-max-port: 7199 + default-credential-duration-seconds: 900 # GetClusterCredentials default lifetime (900-3600) # endpoint-host: localhost # Hostname clients use; empty -> DockerHostResolver rds: enabled: true diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index ab32d820c6..899d9b9241 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -5044,8 +5044,8 @@ class RdsServiceTest { restoredService.restorePersistedRuntime(); - ArgumentCaptor validator = - ArgumentCaptor.forClass(RdsAuthProxy.PasswordValidator.class); + ArgumentCaptor 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"), diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java index 5b0bc0268c..05469b8680 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java @@ -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); } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerAuthResultTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerAuthResultTest.java new file mode 100644 index 0000000000..0bb8f79bd5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerAuthResultTest.java @@ -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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java index 0a806a4ef2..bb89291a49 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -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); } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBrokerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBrokerTest.java new file mode 100644 index 0000000000..669a69076f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftCredentialBrokerTest.java @@ -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 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftGetClusterCredentialsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftGetClusterCredentialsIntegrationTest.java new file mode 100644 index 0000000000..63d699c8a4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftGetClusterCredentialsIntegrationTest.java @@ -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("IAM:analyst")) + .body(containsString("")) + .body(containsString("")); + + // 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolverTest.java new file mode 100644 index 0000000000..2152a2ec43 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftIamDbUserResolverTest.java @@ -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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java index 1fb0e2bd0f..8fcb69fa50 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java @@ -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("env")); assertTrue(xml.contains("prod")); } + + // ── GetClusterCredentials ──────────────────────────────────────────────── + + @Test + void getClusterCredentialsReturnsUserPasswordAndExpiration() { + when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1"))); + MultivaluedMap 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("IAM:analyst")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + } + + @Test + void getClusterCredentialsStoresCredentialInBroker() { + when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1"))); + MultivaluedMap 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 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 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 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 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 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("IAMA:analyst")); + } + + @Test + void getClusterCredentialsAutoCreateFalsePrefixesIamOnDbUser() { + when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1"))); + MultivaluedMap 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("IAM:analyst")); + } + + @Test + void getClusterCredentialsEchoesDbGroups() { + when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1"))); + MultivaluedMap 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("etl")); + assertTrue(xml.contains("readonly")); + } + + @Test + void getClusterCredentialsPropagatesClusterNotFound() { + when(service.describeClusters("missing")) + .thenThrow(new AwsException("ClusterNotFound", "Cluster missing not found", 404)); + MultivaluedMap 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 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("IAMR:Deployer")); + assertTrue(xml.contains("")); + } + + @Test + void getClusterCredentialsWithIamIgnoresDbUserParam() { + when(service.describeClusters("c1")).thenReturn(List.of(availableCluster("c1"))); + when(iamDbUserResolver.resolveDbUser(any())).thenReturn("IAM:alice"); + MultivaluedMap 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("IAM:alice")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index 0c2cebe1e3..db33ae3fab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -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 /redshift-dumps/}. */ @@ -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")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java index 170dd4528c..fb52b55aee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java index dcbc75bd2c..b477fb201a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolverTest.java index 80332a0093..b24b8f8a72 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolverTest.java @@ -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); diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index f7873f59c7..c539b6b4bd 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -175,6 +175,7 @@ floci: image-version: postgres:15-alpine proxy-base-port: 7100 proxy-max-port: 7199 + default-credential-duration-seconds: 900 rds: enabled: true mock: false diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index e3e3dad2af..19202d5d42 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -250,9 +250,10 @@ services: doc: docs/services/redshift.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java, mode: switch } - # SubnetIds / VpcSecurityGroupIds / TagKeys are labels of an inner member-name - # switch (memberKeyRegex), not actions, same shape as the rds exclusions above. - exclude_actions: [SubnetIds, VpcSecurityGroupIds, TagKeys] + # SubnetIds / VpcSecurityGroupIds / TagKeys / DbGroups are labels of an inner + # member-name switch (memberKeyRegex), not actions, same shape as the rds + # exclusions above. + exclude_actions: [SubnetIds, VpcSecurityGroupIds, TagKeys, DbGroups] - service: redshiftdata doc: docs/services/redshift-data.md sources: