feat: map Redshift IAM credentials to PostgreSQL roles (#8211)

* feat(redshift): map Redshift IAM credentials to PostgreSQL roles
* docs(redshift): document IAM database identity for Redshift services
* fix(redshift): harden Redshift IAM role handover and DbGroups lifecycle
* fix(redshift): grant public schema usage on auto-create and resolve latest credential
* fix(redshift): log in as the IAM-derived role so PostgreSQL blocks the switch back
* fix(redshift): restore the role's own password once the backend login completes
* chore(redshift): write the password tracker lock comment in English
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-14 01:06:59 -04:00
1 parent 5f03ff975d
commit b658720afe
26 files changed
+1658 -65

No files matched your search

+2 -2
View File
@@ -37,10 +37,10 @@ For the upstream API shape, see the AWS documentation:
A request identifies its target cluster or serverless workgroup one of three ways:
- **`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`.
- **`ClusterIdentifier` + `DbUser` + `Database`.** The `DbUser` is the cluster master, or the prefixed name returned by `GetClusterCredentials` / `GetClusterCredentialsWithIAM` (for example `IAM:analyst` or `IAMA:analyst`) while that credential is unexpired. For temporary credentials, Floci opens the session as the corresponding PostgreSQL role (honoring `AutoCreate` and session-scoped `DbGroups`), authenticated as that role so PostgreSQL refuses a switch to another user and applies the role's `ALTER USER ... SET` defaults, so `current_user`, `GRANT`, and object ownership match Redshift. 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` + `Database`, with or without `SecretArn`.** `WorkgroupName` is a workgroup name or workgroup ARN created through [Redshift Serverless](redshift-serverless.md). `Database` must be the namespace `dbName`. Without a `SecretArn`, Floci connects as the namespace admin; AWS derives the database user from the signing identity (`IAM:<name>`), and `DbUser` is not used. With a `SecretArn`, the secret must hold credentials the workgroup backend accepts. Sending `ClusterIdentifier` as well returns `ValidationException`, and so does a workgroup whose runtime is not running.
- **`WorkgroupName` + `Database`, with or without `SecretArn`.** `WorkgroupName` is a workgroup name or workgroup ARN created through [Redshift Serverless](redshift-serverless.md). `Database` must be the namespace `dbName`. Without a `SecretArn`, Floci derives the database user from the signing identity (`IAM:<user>` or `IAMR:<role>`, falling back to `IAMR:floci`), auto-creates that non-superuser PostgreSQL role if missing, and runs the session as that role; `DbUser` is not used. With a `SecretArn`, the secret must hold credentials the workgroup backend accepts. Sending `ClusterIdentifier` as well returns `ValidationException`, and so does a workgroup whose runtime is not running.
A statement run against a workgroup reports `WorkgroupName` and omits `ClusterIdentifier`, and the reverse holds for a cluster statement. `ListDatabases`, `ListSchemas`, `ListTables` and `DescribeTable` accept `WorkgroupName` the same way.
+1 -1
View File
@@ -75,7 +75,7 @@ Namespace and workgroup state is account and Region scoped and persisted through
- **A workgroup runs a real PostgreSQL container.** `CreateWorkgroup` starts the container (this needs Docker and uses `floci.services.redshift.image-version`) and an authenticating proxy on the `endpoint`, whose port comes from the same pool as provisioned Redshift clusters (`floci.services.redshift.proxy-base-port` to `proxy-max-port`). Connect with any PostgreSQL client or JDBC driver using the namespace admin user and password, to the namespace `dbName`. The Redshift Data API accepts `WorkgroupName` ([details](redshift-data.md)). Only the operations in the Supported Actions table are served. The rest of the Redshift Serverless API is not emulated and answers `UnknownOperationException`: snapshot restore access policies, recovery points, table restore and restore status, the Identity Center token, and lakehouse configuration.
- **Admin credentials come from the namespace.** The backend role is the namespace `adminUsername` (default `admin`) and the password is the `adminUserPassword` the namespace was created with. A namespace created without a password gets a generated one that is kept internally and never returned, so such a workgroup is reachable through `GetCredentials` and the Data API only unless managed credentials are enabled. Changing `adminUserPassword` with `UpdateNamespace` takes effect for new connections and is refused with `ValidationException` if the backend rejects it (AWS password rules: 8 to 64 characters with upper case, lower case and a digit, and none of `' " / @`). Changing `adminUsername` on a running workgroup does not rename the backend role; the new name is accepted at the proxy, which opens the backend as the original role.
- **`GetCredentials` returns a master-equivalent password.** `dbUser` is derived from the signing identity (`IAM:<user>` or `IAMR:<role>`, falling back to `IAMR:floci` when the caller cannot be resolved), `dbPassword` is random, and `expiration` and `nextRefreshTime` are epoch seconds (the same instant). `durationSeconds` defaults to 900 and must be 900 to 3600. `dbName`, when given, must be the namespace `dbName`. `customDomainName` can be used in place of `workgroupName` to resolve the associated workgroup. A returned credential stays valid until it expires or the workgroup is deleted.
- **`GetCredentials` maps the caller to a non-superuser PostgreSQL role.** `dbUser` is derived from the signing identity (`IAM:<user>` or `IAMR:<role>`, falling back to `IAMR:floci` when the caller cannot be resolved), `dbPassword` is random, and `expiration` and `nextRefreshTime` are epoch seconds (the same instant). `durationSeconds` defaults to 900 and must be 900 to 3600. `dbName`, when given, must be the namespace `dbName`. `customDomainName` can be used in place of `workgroupName` to resolve the associated workgroup. Connections using the returned credential auto-create and run as the `dbUser` PostgreSQL role rather than the namespace admin, and stay valid until expiration or workgroup deletion.
- **The runtime survives a restart when its container does.** On startup Floci re-attaches to the container and restarts the proxy on the same port, so the endpoint is stable. If the container is gone the workgroup comes back with an empty database; if neither can be started, the workgroup stays `AVAILABLE`, the Data API reports that its runtime is not available, and the failure is logged. Containers have no Docker volume, as for provisioned clusters.
- **Managed admin credentials use Secrets Manager.** `CreateNamespace` and `UpdateNamespace` accept `manageAdminPassword=true` to generate a password and create a service-owned secret. The namespace returns `adminPasswordSecretArn` and, when supplied, `adminPasswordSecretKmsKeyId`; the latter requires `manageAdminPassword=true`. The secret contains `engine`, `username`, `password`, `dbname`, and `namespaceName`. `GetNamespace` and `ListNamespaces` return the same references, and the Data API accepts the secret ARN with `WorkgroupName`. Passwords are never returned in namespace responses. Enabling management updates a running backend's password. While credentials are managed, an explicit `adminUserPassword` is rejected; switching to `manageAdminPassword=false` requires a replacement password, updates the backend, and removes the secret. Deleting the namespace also removes its managed secret. Credential changes compensate backend, secret, and namespace writes on failure. Snapshots retain the admin credentials captured at snapshot time. `RestoreFromSnapshot` with `manageAdminPassword=true` generates managed credentials and creates or refreshes the namespace secret; false or omitted restores the snapshot credentials and removes a currently managed secret. `AWS::RedshiftServerless::Namespace` supports `ManageAdminPassword` and `AdminPasswordSecretKmsKeyId` on create and update. Failed CloudFormation updates restore the previous namespace, backend password, secret ARN, and secret versions. If another secret has reused a deleted managed secret's name, rollback reports a conflict and preserves that secret. Concurrent creation and rollback cannot overwrite each other's secrets. As for other service-owned secrets in Floci, automatic rotation and `RotateSecret` password replacement are not executed; no successful rotation is reported.
- **Defaults follow AWS.** `dbName` defaults to `dev`, `kmsKeyId` to `AWS_OWNED_KMS_KEY`, `logExports` to an empty list, and `status` to `AVAILABLE` immediately: there is no `MODIFYING` or `CREATING` phase to poll through.
+1 -1
View File
@@ -1116,7 +1116,7 @@ runs the `COPY` over a connection to the cluster proxy. See [Firehose](firehose.
- 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.
- `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, and the session runs as the unprefixed PostgreSQL role (`<DbUser>`), creating it as a non-superuser login role when `AutoCreate` is true and failing when it is false and missing. The session authenticates to PostgreSQL as that role itself (Floci sets a random password on the role for the life of the session and restores the stored one afterwards), so PostgreSQL, not Floci, refuses any switch to another user, the role's own `ALTER USER ... SET` defaults apply, and a master or superuser `DbUser` runs with its own permissions. Every user gets `CREATE` and `USAGE` on the `public` schema, as in Redshift. A password login by that role is refused while a temporary credential session holds it. `GetClusterCredentialsWithIAM` runs as the `IAM:<user>` or `IAMR:<role>` PostgreSQL role (auto-created if missing). `DbGroups` grants temporary session-scoped membership in existing database groups (`GRANT ...` while the session is open, revoked on close) and fails if a named group does not exist.
### UNLOAD to S3
@@ -21,6 +21,7 @@ import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
@@ -72,6 +73,30 @@ public class PostgresProtocolHandler {
void onStartup(String username, String database, Map<String, String> parameters);
}
/**
* Optional callback used by Redshift proxies to provision/verify a database role and
* temporary group memberships before the backend session opens. The backend then
* authenticates as that role, so PostgreSQL itself keeps the session from becoming another user.
*/
@FunctionalInterface
public interface SessionRoleHandover {
HandoverOutcome prepare(String clientUsername, String clientPassword, String database) throws SQLException;
}
/**
* {@code backendPassword} is the password the backend session logs in as {@code databaseRole}
* with; {@code null} means the cluster master password, for the master user itself.
* {@code onBackendLogin} runs once that login has finished, whether it succeeded or not, so the
* role's own password can be restored while the session stays open; {@code onClose} runs when the
* session ends or the login is refused.
*/
public record HandoverOutcome(String databaseRole, String backendPassword,
Runnable onBackendLogin, Runnable onClose) {
public HandoverOutcome(String databaseRole, String backendPassword, Runnable onClose) {
this(databaseRole, backendPassword, null, onClose);
}
}
/** The username/password the proxy opens the backend PostgreSQL connection with. */
record BackendLogin(String user, String password) {}
@@ -176,6 +201,19 @@ public class PostgresProtocolHandler {
PasswordValidator passwordValidator, int handshakeTimeoutMillis,
boolean forwardStartupParameters, boolean databaseIamAuthentication,
StartupObserver startupObserver) throws IOException {
return authenticate(client, backendConnector, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, binding, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
forwardStartupParameters, databaseIamAuthentication, startupObserver, null);
}
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyBinding binding, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator, int handshakeTimeoutMillis,
boolean forwardStartupParameters, boolean databaseIamAuthentication,
StartupObserver startupObserver,
SessionRoleHandover roleHandover) throws IOException {
client.setSoTimeout(handshakeTimeoutMillis);
@@ -236,6 +274,40 @@ public class PostgresProtocolHandler {
}
}
// Phase 4b: A client the proxy vouched for through a role handover runs as the role the
// handover names, which the backend authenticates directly. Prepared before any backend
// session opens so a refused role never costs a connection.
boolean iamHandover = isIam && !isMaster;
boolean customHandover = !iamHandover && roleHandover != null
&& authResult == PasswordValidator.AuthResult.MASTER_EQUIVALENT && !isMaster;
String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName);
HandoverOutcome handoverOutcome = null;
if (customHandover) {
try {
handoverOutcome = roleHandover.prepare(clientUsername, clientPassword, effectiveDbName);
} catch (SQLException failure) {
String sqlState = failure.getSQLState() == null || failure.getSQLState().isBlank()
? "28000" : failure.getSQLState();
sendErrorResponse(clientOut, "FATAL", sqlState, failure.getMessage());
clientOut.flush();
closeQuietly(client);
return null;
}
if (handoverOutcome == null || handoverOutcome.databaseRole() == null
|| handoverOutcome.databaseRole().isBlank()) {
if (handoverOutcome != null && handoverOutcome.onClose() != null) {
handoverOutcome.onClose().run();
}
sendErrorResponse(clientOut, "FATAL", "28000",
"password authentication failed for user \"" + clientUsername + "\"");
clientOut.flush();
closeQuietly(client);
return null;
}
}
Runnable handoverClose = handoverOutcome == null || handoverOutcome.onClose() == null
? () -> { } : handoverOutcome.onClose();
// Phase 5: Connect to backend PostgreSQL, now that the client's startup message and
// credentials have been validated. IAM and master: use master credentials. The backend
// has the original container password and is never updated directly, so the proxy always
@@ -245,6 +317,7 @@ public class PostgresProtocolHandler {
try {
backend = backendConnector.connect();
} catch (IOException e) {
handoverClose.run();
sendErrorResponse(clientOut, "FATAL", "08006", "could not connect to backend database");
clientOut.flush();
closeQuietly(client);
@@ -260,18 +333,21 @@ public class PostgresProtocolHandler {
InputStream backendIn = backend.getInputStream();
OutputStream backendOut = backend.getOutputStream();
String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName);
BackendLogin backendLogin = resolveBackendLogin(isMaster, isIam, authResult,
masterUsername, masterPassword, clientUsername, clientPassword);
String backendUser = backendLogin.user();
String backendPass = backendLogin.password();
if (handoverOutcome != null) {
backendUser = handoverOutcome.databaseRole();
backendPass = handoverOutcome.backendPassword() != null
? handoverOutcome.backendPassword() : masterPassword;
}
// An IAM login for any role but the master runs on a session opened as the master and
// handed over below, so PostgreSQL would apply the client's parameters with the
// master's privileges: a "-c role=<master>" would outlive the handover and RESET ROLE
// would regain the master. Those logins open without them, and their parameters are
// applied once the session belongs to the role (Phase 5c). The proxy reads that
// session's results and sends it SQL of its own, so it fixes the encoding to UTF-8.
boolean iamHandover = isIam && !isMaster;
Map<String, String> backendParameters;
if (!forwardStartupParameters) {
backendParameters = Map.of();
@@ -280,9 +356,17 @@ public class PostgresProtocolHandler {
} else {
backendParameters = startup.parameters();
}
byte[] backendRejection = loginToBackend(backendIn, backendOut, backendUser, backendPass,
effectiveDbName, backendParameters);
byte[] backendRejection;
try {
backendRejection = loginToBackend(backendIn, backendOut, backendUser, backendPass,
effectiveDbName, backendParameters);
} finally {
if (handoverOutcome != null && handoverOutcome.onBackendLogin() != null) {
handoverOutcome.onBackendLogin().run();
}
}
if (backendRejection != null) {
handoverClose.run();
clientOut.write(backendRejection);
clientOut.flush();
closeQuietly(client);
@@ -486,8 +570,13 @@ public class PostgresProtocolHandler {
}
}
if (handoverOutcome != null) {
iamRole = handoverOutcome.databaseRole();
}
// Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge
if (endsWithErrorResponse(bufferedMessages)) {
handoverClose.run();
for (byte[] msg : bufferedMessages) {
clientOut.write(msg);
}
@@ -34,10 +34,17 @@ public class RedshiftCredentialBroker implements Resettable {
public TempCredential issue(String accountId, String clusterId, String dbUser,
List<String> dbGroups, int durationSeconds) {
return issue(accountId, clusterId, dbUser, dbGroups, durationSeconds, dbUser, true);
}
public TempCredential issue(String accountId, String clusterId, String dbUser,
List<String> dbGroups, int durationSeconds,
String databaseRole, boolean autoCreate) {
String password = randomPassword();
Instant expiresAt = Instant.now().plusSeconds(durationSeconds);
List<String> groups = dbGroups == null ? List.of() : List.copyOf(dbGroups);
TempCredential credential = new TempCredential(dbUser, password, expiresAt, groups);
TempCredential credential = new TempCredential(
dbUser, password, expiresAt, groups, databaseRole, autoCreate);
store.compute(key(accountId, clusterId, dbUser), (k, existing) -> {
CopyOnWriteArrayList<TempCredential> list =
existing == null ? new CopyOnWriteArrayList<>() : existing;
@@ -49,7 +56,18 @@ public class RedshiftCredentialBroker implements Resettable {
}
public Optional<TempCredential> resolve(String accountId, String clusterId, String dbUser) {
return liveCredentials(key(accountId, clusterId, dbUser)).stream().findFirst();
List<TempCredential> live = liveCredentials(key(accountId, clusterId, dbUser));
if (live.isEmpty()) {
return Optional.empty();
}
return Optional.of(live.get(live.size() - 1));
}
public Optional<TempCredential> authenticate(String accountId, String clusterId,
String username, String password) {
return liveCredentials(key(accountId, clusterId, username)).stream()
.filter(c -> c.password().equals(password))
.findFirst();
}
public Match classify(String accountId, String clusterId, String username, String password) {
@@ -0,0 +1,261 @@
package io.floci.aws.services.redshift;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Provisions or verifies the PostgreSQL role and temporary {@code DbGroups} memberships
* corresponding to an IAM-derived Redshift credential, and gives the session a password to log
* in as that role. Logging in as the role, rather than switching to it from the master, leaves
* the blocking of a switch to another user to PostgreSQL, which authorizes
* {@code SET SESSION AUTHORIZATION} against the authenticated user, and loads the role's own
* {@code ALTER USER ... SET} defaults as a direct login does.
*/
@ApplicationScoped
public class RedshiftDbIdentityProvisioner {
private static final Logger LOG = Logger.getLogger(RedshiftDbIdentityProvisioner.class);
/**
* {@code backendPassword} is the password to log in as {@code databaseRole}, or {@code null}
* when the role is the connection's own master user, which logs in with the master password.
* {@code restorePassword} puts the role's own password back and is called once the backend login
* has completed; {@code releaseLease} ends the whole identity (it restores the password too, if
* that has not happened yet) and is called when the session closes.
*/
public record PreparedIdentity(String databaseRole, String backendPassword,
Runnable restorePassword, Runnable releaseLease) { }
@FunctionalInterface
public interface ConnectionSupplier {
Connection open() throws SQLException;
}
private final TempGroupGrantTracker grantTracker;
private final TempRolePasswordTracker passwordTracker;
@Inject
public RedshiftDbIdentityProvisioner(TempGroupGrantTracker grantTracker,
TempRolePasswordTracker passwordTracker) {
this.grantTracker = grantTracker;
this.passwordTracker = passwordTracker;
}
/**
* Ensures {@code roleName} exists (creating it when {@code autoCreate} is true), validates
* every group in {@code dbGroups}, grants temporary membership for groups the role does
* not already belong to, and installs the temporary login password. Must be called on a
* master/admin connection.
*/
public PreparedIdentity prepare(Connection adminConnection, String backendKey,
String roleName, boolean autoCreate, List<String> dbGroups,
ConnectionSupplier adminConnectionFactory) throws SQLException {
if (roleName == null || roleName.isBlank()) {
throw new SQLException("Database role name must not be blank", "28000");
}
grantPublicSchemaAccess(adminConnection);
RoleInfo role = ensureLoginRole(adminConnection, roleName, autoCreate);
List<String> groupsToGrant = resolveTemporaryGroups(adminConnection, dbGroups);
TempGroupGrantTracker.Lease groupLease = grantTracker.acquire(
backendKey,
roleName,
groupsToGrant,
group -> executeSql(adminConnection,
"GRANT " + quoteIdentifier(group) + " TO " + quoteIdentifier(roleName)),
group -> executeSql(adminConnection,
"REVOKE " + quoteIdentifier(group) + " FROM " + quoteIdentifier(roleName)),
group -> isDirectMember(adminConnection, roleName, group));
TempRolePasswordTracker.Lease passwordLease = null;
if (!role.currentUser()) {
try {
passwordLease = passwordTracker.acquire(
backendKey,
roleName,
() -> readPasswordHash(adminConnection, roleName),
password -> setPassword(adminConnection, roleName, password));
} catch (SQLException | RuntimeException failure) {
releaseGroups(groupLease, roleName, adminConnectionFactory);
throw failure;
}
}
TempRolePasswordTracker.Lease heldPassword = passwordLease;
Runnable releaseHandle = () -> {
releaseGroups(groupLease, roleName, adminConnectionFactory);
releasePassword(heldPassword, roleName, adminConnectionFactory);
};
Runnable restorePassword = () -> releasePassword(heldPassword, roleName, adminConnectionFactory);
return new PreparedIdentity(roleName, heldPassword == null ? null : heldPassword.password(),
restorePassword, releaseHandle);
}
private record RoleInfo(boolean canLogin, boolean currentUser) { }
/**
* Redshift gives every user CREATE and USAGE on the public schema, whereas PostgreSQL 15+
* revokes CREATE on it from PUBLIC. The grant is per database, and to PUBLIC so that users
* created with CREATE USER are covered as well as auto-created IAM users.
*/
private static void grantPublicSchemaAccess(Connection connection) throws SQLException {
executeSql(connection, "GRANT USAGE, CREATE ON SCHEMA public TO PUBLIC");
}
private RoleInfo ensureLoginRole(Connection connection, String roleName, boolean autoCreate) throws SQLException {
if (roleName.startsWith("pg_")) {
throw new SQLException("role \"" + roleName + "\" is not permitted for IAM session handover", "28000");
}
RoleInfo info = queryRoleInfo(connection, roleName);
if (info == null) {
if (!autoCreate) {
throw new SQLException("role \"" + roleName + "\" does not exist", "28000");
}
createLoginRole(connection, roleName);
info = queryRoleInfo(connection, roleName);
if (info == null) {
throw new SQLException("role \"" + roleName + "\" could not be created", "28000");
}
}
if (!info.canLogin()) {
throw new SQLException("role \"" + roleName + "\" is not permitted to log in", "28000");
}
return info;
}
private void createLoginRole(Connection connection, String roleName) throws SQLException {
String sql = "CREATE ROLE " + quoteIdentifier(roleName)
+ " WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE";
try {
executeSql(connection, sql);
} catch (SQLException failure) {
// Two concurrent logins with AutoCreate=true may race on CREATE ROLE.
String state = failure.getSQLState();
if (!"42710".equals(state) && !"23505".equals(state)) {
throw failure;
}
}
}
private List<String> resolveTemporaryGroups(Connection connection, List<String> dbGroups) throws SQLException {
if (dbGroups == null || dbGroups.isEmpty()) {
return List.of();
}
Set<String> distinct = new LinkedHashSet<>();
for (String group : dbGroups) {
if (group != null && !group.isBlank()) {
distinct.add(group);
}
}
if (distinct.isEmpty()) {
return List.of();
}
List<String> validGroups = new ArrayList<>();
for (String group : distinct) {
if (!roleExists(connection, group)) {
throw new SQLException("role \"" + group + "\" does not exist", "42704");
}
validGroups.add(group);
}
return validGroups;
}
private static RoleInfo queryRoleInfo(Connection connection, String roleName) throws SQLException {
String sql = "SELECT rolcanlogin, rolname = current_user FROM pg_catalog.pg_roles WHERE rolname = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, roleName);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
return new RoleInfo(rs.getBoolean(1), rs.getBoolean(2));
}
}
}
private static boolean roleExists(Connection connection, String roleName) throws SQLException {
String sql = "SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, roleName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
private static boolean isDirectMember(Connection connection, String roleName,
String groupName) throws SQLException {
String sql = "SELECT 1 FROM pg_catalog.pg_auth_members m "
+ "JOIN pg_catalog.pg_roles r ON r.oid = m.roleid "
+ "JOIN pg_catalog.pg_roles u ON u.oid = m.member "
+ "WHERE r.rolname = ? AND u.rolname = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, groupName);
ps.setString(2, roleName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
private static String readPasswordHash(Connection connection, String roleName) throws SQLException {
String sql = "SELECT rolpassword FROM pg_catalog.pg_authid WHERE rolname = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, roleName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString(1) : null;
}
}
}
private static void setPassword(Connection connection, String roleName, String password) throws SQLException {
String literal = password == null ? "NULL" : "'" + password.replace("'", "''") + "'";
executeSql(connection, "ALTER ROLE " + quoteIdentifier(roleName) + " PASSWORD " + literal);
}
private static void releaseGroups(TempGroupGrantTracker.Lease lease, String roleName,
ConnectionSupplier adminConnectionFactory) {
try {
lease.release(group -> {
try (Connection admin = adminConnectionFactory.open()) {
executeSql(admin, "REVOKE " + quoteIdentifier(group) + " FROM " + quoteIdentifier(roleName));
}
});
} catch (SQLException | RuntimeException failure) {
LOG.warnv(failure, "Failed to revoke temporary DbGroups for Redshift role {0}", roleName);
}
}
private static void releasePassword(TempRolePasswordTracker.Lease lease, String roleName,
ConnectionSupplier adminConnectionFactory) {
if (lease == null) {
return;
}
lease.release(storedHash -> {
try (Connection admin = adminConnectionFactory.open()) {
setPassword(admin, roleName, storedHash);
}
});
}
private static void executeSql(Connection connection, String sql) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
}
}
public static String quoteIdentifier(String identifier) {
return "\"" + identifier.replace("\"", "\"\"") + "\"";
}
}
@@ -33,6 +33,10 @@ public class RedshiftIamDbUserResolver {
public String resolveDbUser(String authorizationHeader) {
String accessKeyId = accountResolver.extractAccessKeyId(authorizationHeader);
return resolveDbUserForAccessKey(accessKeyId);
}
public String resolveDbUserForAccessKey(String accessKeyId) {
Optional<String> arn = iamService.resolveCallerArn(accessKeyId);
if (arn.isEmpty()) {
LOG.warnv("GetClusterCredentialsWithIAM caller could not be resolved; using {0}", FALLBACK_DB_USER);
@@ -1067,7 +1067,8 @@ public class RedshiftQueryHandler {
int duration = resolveDurationSeconds(params);
TempCredential credential = credentialBroker.issue(
regionResolver.getAccountId(), clusterId, effectiveDbUser, dbGroups, duration);
regionResolver.getAccountId(), clusterId, effectiveDbUser, dbGroups, duration,
dbUser, autoCreate);
return Response.ok(getClusterCredentialsXml("GetClusterCredentials", credential))
.type(MediaType.APPLICATION_XML).build();
}
@@ -1076,10 +1077,10 @@ public class RedshiftQueryHandler {
service.describeClusters(clusterId);
String dbUser = iamDbUserResolver.resolveDbUser(authorizationHeader);
int duration = resolveDurationSeconds(params);
List<String> dbGroups = memberList(params, "DbGroups");
TempCredential credential = credentialBroker.issue(
regionResolver.getAccountId(), clusterId, dbUser, dbGroups, duration);
regionResolver.getAccountId(), clusterId, dbUser, List.of(), duration,
dbUser, true);
return Response.ok(getClusterCredentialsXml("GetClusterCredentialsWithIAM", credential))
.type(MediaType.APPLICATION_XML).build();
}
@@ -3,5 +3,14 @@ package io.floci.aws.services.redshift;
import java.time.Instant;
import java.util.List;
public record TempCredential(String dbUser, String password, Instant expiresAt, List<String> dbGroups) {
public record TempCredential(
String dbUser,
String password,
Instant expiresAt,
List<String> dbGroups,
String databaseRole,
boolean autoCreate) {
public TempCredential(String dbUser, String password, Instant expiresAt, List<String> dbGroups) {
this(dbUser, password, expiresAt, dbGroups, dbUser, true);
}
}
@@ -0,0 +1,189 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.Resettable;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Reference-counts temporary {@code DbGroups} memberships granted for active sessions so
* concurrent sessions sharing a role and group do not revoke each other's access prematurely,
* and pre-existing permanent memberships are left untouched.
*/
@ApplicationScoped
public class TempGroupGrantTracker implements Resettable {
private static final Logger LOG = Logger.getLogger(TempGroupGrantTracker.class);
@FunctionalInterface
public interface GroupAction {
void execute(String group) throws SQLException;
}
@FunctionalInterface
public interface MembershipCheck {
boolean isMember(String group) throws SQLException;
}
public static final class Lease {
private final TempGroupGrantTracker tracker;
private final String backendKey;
private final String roleName;
private final List<String> groups;
private final AtomicBoolean released = new AtomicBoolean(false);
private Lease(TempGroupGrantTracker tracker, String backendKey, String roleName, List<String> groups) {
this.tracker = tracker;
this.backendKey = backendKey;
this.roleName = roleName;
this.groups = List.copyOf(groups);
}
public void release(GroupAction revokeAction) throws SQLException {
if (!released.compareAndSet(false, true) || groups.isEmpty()) {
return;
}
tracker.releaseGroups(backendKey, roleName, groups, revokeAction);
}
}
private record Key(String backendKey, String roleName, String groupName) { }
private final ConcurrentHashMap<Key, Integer> activeCounts = new ConcurrentHashMap<>();
private final Set<Key> pendingRevokes = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<Key, Object> keyLocks = new ConcurrentHashMap<>();
public Lease acquire(String backendKey, String roleName, List<String> groupsToGrant,
GroupAction grantAction) throws SQLException {
return acquire(backendKey, roleName, groupsToGrant, grantAction, null, null);
}
public Lease acquire(String backendKey, String roleName, List<String> groupsToGrant,
GroupAction grantAction, GroupAction rollbackRevokeAction) throws SQLException {
return acquire(backendKey, roleName, groupsToGrant, grantAction, rollbackRevokeAction, null);
}
public Lease acquire(String backendKey, String roleName, List<String> groupsToGrant,
GroupAction grantAction, GroupAction rollbackRevokeAction,
MembershipCheck alreadyMemberCheck) throws SQLException {
if (groupsToGrant == null || groupsToGrant.isEmpty()) {
return new Lease(this, backendKey, roleName, List.of());
}
Set<String> distinct = new LinkedHashSet<>(groupsToGrant);
List<String> acquired = new ArrayList<>();
try {
for (String group : distinct) {
Key key = new Key(backendKey, roleName, group);
synchronized (lockFor(key)) {
int current = activeCounts.getOrDefault(key, 0);
boolean hasPendingRevoke = pendingRevokes.contains(key);
if (current == 0 && !hasPendingRevoke) {
if (alreadyMemberCheck != null && alreadyMemberCheck.isMember(group)) {
continue;
}
grantAction.execute(group);
} else if (hasPendingRevoke) {
pendingRevokes.remove(key);
}
activeCounts.put(key, current + 1);
acquired.add(group);
}
}
} catch (SQLException | RuntimeException failure) {
rollbackAcquired(backendKey, roleName, acquired, rollbackRevokeAction);
throw failure;
}
return new Lease(this, backendKey, roleName, acquired);
}
private void rollbackAcquired(String backendKey, String roleName, List<String> acquired,
GroupAction rollbackRevokeAction) {
for (int i = acquired.size() - 1; i >= 0; i--) {
String group = acquired.get(i);
Key key = new Key(backendKey, roleName, group);
synchronized (lockFor(key)) {
int current = activeCounts.getOrDefault(key, 0);
if (current <= 1) {
activeCounts.remove(key);
if (rollbackRevokeAction != null) {
try {
rollbackRevokeAction.execute(group);
pendingRevokes.remove(key);
} catch (SQLException | RuntimeException failure) {
pendingRevokes.add(key);
LOG.warnv(failure,
"Failed to revoke temporary DbGroup {0} for role {1} during rollback",
group, roleName);
}
}
} else {
activeCounts.put(key, current - 1);
}
}
}
}
private void releaseGroups(String backendKey, String roleName, List<String> groups,
GroupAction revokeAction) throws SQLException {
SQLException firstFailure = null;
for (String group : groups) {
Key key = new Key(backendKey, roleName, group);
synchronized (lockFor(key)) {
int current = activeCounts.getOrDefault(key, 0);
if (current <= 1) {
if (current == 1 && revokeAction != null) {
try {
revokeAction.execute(group);
activeCounts.remove(key);
pendingRevokes.remove(key);
} catch (SQLException failure) {
activeCounts.remove(key);
pendingRevokes.add(key);
if (firstFailure == null) {
firstFailure = failure;
} else {
firstFailure.addSuppressed(failure);
}
} catch (RuntimeException failure) {
activeCounts.remove(key);
pendingRevokes.add(key);
throw failure;
}
} else {
activeCounts.remove(key);
pendingRevokes.remove(key);
}
} else {
activeCounts.put(key, current - 1);
}
}
}
if (firstFailure != null) {
throw firstFailure;
}
}
private Object lockFor(Key key) {
return keyLocks.computeIfAbsent(key, ignored -> new Object());
}
public void revokeBackend(String backendKey) {
activeCounts.keySet().removeIf(k -> k.backendKey().equals(backendKey));
pendingRevokes.removeIf(k -> k.backendKey().equals(backendKey));
keyLocks.keySet().removeIf(k -> k.backendKey().equals(backendKey));
}
@Override
public void clear() {
activeCounts.clear();
pendingRevokes.clear();
keyLocks.clear();
}
}
@@ -0,0 +1,146 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.Resettable;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Reference-counts the temporary password an IAM-derived session logs in with, so PostgreSQL
* authenticates the session as the role itself. A session that authenticated as the role cannot
* switch to another user, whatever SQL it runs, because PostgreSQL authorizes
* {@code SET SESSION AUTHORIZATION} against the authenticated user.
*
* <p>The first login of a role stores the role's current password hash and installs a random
* password; logins in flight at the same time share it; the last one to finish restores the stored
* hash. Callers release the lease as soon as their backend login completes, so the role's own
* password works again while the session is open. A failed
* restore keeps the stored hash so the next session does not mistake the temporary password for
* the role's own.
*/
@ApplicationScoped
public class TempRolePasswordTracker implements Resettable {
private static final Logger LOG = Logger.getLogger(TempRolePasswordTracker.class);
private static final String PASSWORD_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final int PASSWORD_LENGTH = 32;
@FunctionalInterface
public interface PasswordReader {
/** Returns the role's stored password hash, or {@code null} when it has none. */
String read() throws SQLException;
}
@FunctionalInterface
public interface PasswordWriter {
/** Stores {@code password} (a pre-hashed value or plaintext); {@code null} removes it. */
void write(String password) throws SQLException;
}
public static final class Lease {
private final TempRolePasswordTracker tracker;
private final Key key;
private final String password;
private final AtomicBoolean released = new AtomicBoolean(false);
private Lease(TempRolePasswordTracker tracker, Key key, String password) {
this.tracker = tracker;
this.key = key;
this.password = password;
}
public String password() {
return password;
}
public void release(PasswordWriter restore) {
if (released.compareAndSet(false, true)) {
tracker.release(key, restore);
}
}
}
private record Key(String backendKey, String roleName) { }
private static final class Entry {
private int active;
private String temporaryPassword;
private String storedHash;
}
private final SecureRandom random = new SecureRandom();
private final ConcurrentHashMap<Key, Entry> entries = new ConcurrentHashMap<>();
// One lock per key that outlives its entry: acquire and release always take the same lock, so a
// login waiting on it cannot carry on with an entry the last release has already removed.
private final ConcurrentHashMap<Key, Object> keyLocks = new ConcurrentHashMap<>();
public Lease acquire(String backendKey, String roleName, PasswordReader reader,
PasswordWriter writer) throws SQLException {
Key key = new Key(backendKey, roleName);
synchronized (lockFor(key)) {
Entry entry = entries.computeIfAbsent(key, ignored -> new Entry());
if (entry.active == 0) {
if (entry.temporaryPassword == null) {
entry.storedHash = reader.read();
}
String temporary = randomPassword();
writer.write(temporary);
entry.temporaryPassword = temporary;
}
entry.active++;
return new Lease(this, key, entry.temporaryPassword);
}
}
private void release(Key key, PasswordWriter restore) {
synchronized (lockFor(key)) {
Entry entry = entries.get(key);
if (entry == null) {
return;
}
entry.active--;
if (entry.active > 0) {
return;
}
try {
restore.write(entry.storedHash);
entry.temporaryPassword = null;
entry.storedHash = null;
entries.remove(key);
} catch (SQLException | RuntimeException failure) {
// Keep the stored hash and temporary marker: the next acquire must restore the
// original, not store the temporary password as if it were the role's own.
LOG.warnv(failure, "Failed to restore the password of Redshift role {0}", key.roleName());
}
}
}
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 Object lockFor(Key key) {
return keyLocks.computeIfAbsent(key, ignored -> new Object());
}
public void revokeBackend(String backendKey) {
entries.keySet().removeIf(k -> k.backendKey().equals(backendKey));
keyLocks.keySet().removeIf(k -> k.backendKey().equals(backendKey));
}
@Override
public void clear() {
entries.clear();
keyLocks.clear();
}
}
@@ -7,6 +7,9 @@ import io.floci.aws.services.rds.proxy.PostgresProtocolHandler;
import io.floci.aws.services.rds.proxy.RdsProxyTlsCertificates;
import io.floci.aws.services.rds.proxy.RdsSigV4Validator;
import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
import io.floci.aws.services.redshift.RedshiftCredentialBroker;
import io.floci.aws.services.redshift.RedshiftDbIdentityProvisioner;
import io.floci.aws.services.redshift.TempCredential;
import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor;
import io.floci.aws.services.s3.S3Service;
import org.jboss.logging.Logger;
@@ -17,8 +20,12 @@ import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
/**
* TCP auth proxy for a single Redshift cluster's backing PostgreSQL container.
@@ -45,6 +52,8 @@ public class RedshiftAuthProxy {
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final RedshiftCredentialBroker credentialBroker;
private final RedshiftDbIdentityProvisioner identityProvisioner;
private final String clusterAccountId;
private volatile RoleConfiguration roleConfiguration;
@@ -112,6 +121,24 @@ public class RedshiftAuthProxy {
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor,
auditLogPublisher, parquetWriter, null, null);
}
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
S3Service s3Service, IamService iamService,
String clusterAccountId,
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter,
RedshiftCredentialBroker credentialBroker,
RedshiftDbIdentityProvisioner identityProvisioner) {
this.clusterKey = clusterKey;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -126,6 +153,8 @@ public class RedshiftAuthProxy {
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.auditLogPublisher = auditLogPublisher;
this.credentialBroker = credentialBroker;
this.identityProvisioner = identityProvisioner;
this.clusterAccountId = clusterAccountId;
this.roleConfiguration = new RoleConfiguration(iamRoleArns, null);
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
@@ -248,6 +277,7 @@ public class RedshiftAuthProxy {
private void handleConnection(Socket client) {
PostgresProtocolHandler.AuthenticatedSession session = null;
LoginAttempt login = new LoginAttempt();
AtomicReference<Runnable> leaseCloser = new AtomicReference<>();
try {
client.setTcpNoDelay(true);
PostgresProtocolHandler.BackendConnector connector = () -> {
@@ -263,6 +293,7 @@ public class RedshiftAuthProxy {
backendSocket.setTcpNoDelay(true);
return backendSocket;
};
PostgresProtocolHandler.SessionRoleHandover roleHandover = buildRoleHandover(leaseCloser);
// iamEnabled = false: the SigV4 branch inside authenticate is never taken, so no
// token binding is needed.
session = PostgresProtocolHandler.authenticate(
@@ -272,7 +303,7 @@ public class RedshiftAuthProxy {
login.username = user;
login.database = database;
login.dataApi = RedshiftInternalAuth.consumeDataApiToken(params.get("application_name"));
});
}, roleHandover);
if (session != null) {
publishConnection(client, login, "authenticated");
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
@@ -283,18 +314,7 @@ public class RedshiftAuthProxy {
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, roles.iamRoleArns(), bridgeSpectrum, clusterKey, login.database,
roles.defaultIamRoleArn(), bridgeAudit, login.username, parquetWriter);
try (CopyLoadErrorLog loadErrors = new CopyLoadErrorLog(() -> {
PGSimpleDataSource source = new PGSimpleDataSource();
source.setServerNames(new String[]{backendHost});
source.setPortNumbers(new int[]{backendPort});
source.setDatabaseName(login.database);
source.setUser(masterUsername);
source.setPassword(masterPassword);
source.setConnectTimeout(Math.max(1, backendConnectTimeoutMillis / 1000));
source.setSocketTimeout(10);
source.setSslMode("disable");
return source.getConnection();
})) {
try (CopyLoadErrorLog loadErrors = new CopyLoadErrorLog(() -> openAdminConnection(login.database))) {
bridge.loadErrorSink(loadErrors);
bridge.run();
}
@@ -306,6 +326,10 @@ public class RedshiftAuthProxy {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
publishConnection(client, login, "connection_error");
} finally {
Runnable release = leaseCloser.getAndSet(null);
if (release != null) {
release.run();
}
// authenticate's success path hands both sockets to the bridge, which closes both
// itself; every other path (early return on a bare probe, auth failure, thrown
// IOException) never had a backend connection to begin with. Closing here is
@@ -319,6 +343,49 @@ public class RedshiftAuthProxy {
}
}
private PostgresProtocolHandler.SessionRoleHandover buildRoleHandover(AtomicReference<Runnable> leaseCloser) {
if (credentialBroker == null || identityProvisioner == null) {
return null;
}
int colon = clusterKey.indexOf(':');
if (colon <= 0 || colon >= clusterKey.length() - 1) {
return (user, password, database) -> {
throw new SQLException("password authentication failed for user \"" + user + "\"", "28000");
};
}
String accountId = clusterKey.substring(0, colon);
String clusterId = clusterKey.substring(colon + 1);
return (user, password, database) -> {
Optional<TempCredential> credential = credentialBroker.authenticate(accountId, clusterId, user, password);
if (credential.isEmpty()) {
throw new SQLException("password authentication failed for user \"" + user + "\"", "28P01");
}
TempCredential cred = credential.get();
try (Connection admin = openAdminConnection(database)) {
RedshiftDbIdentityProvisioner.PreparedIdentity prepared = identityProvisioner.prepare(
admin, clusterKey, cred.databaseRole(), cred.autoCreate(), cred.dbGroups(),
() -> openAdminConnection(database));
leaseCloser.set(prepared.releaseLease());
return new PostgresProtocolHandler.HandoverOutcome(
prepared.databaseRole(), prepared.backendPassword(),
prepared.restorePassword(), prepared.releaseLease());
}
};
}
private Connection openAdminConnection(String database) throws SQLException {
PGSimpleDataSource source = new PGSimpleDataSource();
source.setServerNames(new String[]{backendHost});
source.setPortNumbers(new int[]{backendPort});
source.setDatabaseName(database);
source.setUser(masterUsername);
source.setPassword(masterPassword);
source.setConnectTimeout(Math.max(1, backendConnectTimeoutMillis / 1000));
source.setSocketTimeout(10);
source.setSslMode("disable");
return source.getConnection();
}
private static final class LoginAttempt {
private String username;
private String database;
@@ -6,6 +6,8 @@ import io.floci.aws.services.rds.proxy.PasswordValidator;
import io.floci.aws.services.rds.proxy.RdsProxyTlsCertificates;
import io.floci.aws.services.rds.proxy.RdsSigV4Validator;
import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
import io.floci.aws.services.redshift.RedshiftCredentialBroker;
import io.floci.aws.services.redshift.RedshiftDbIdentityProvisioner;
import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor;
import io.floci.aws.services.s3.S3Service;
import io.quarkus.runtime.ShutdownEvent;
@@ -37,6 +39,8 @@ public class RedshiftProxyManager {
private final EmulatorConfig config;
private final RedshiftParquetWriter parquetWriter;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final RedshiftCredentialBroker credentialBroker;
private final RedshiftDbIdentityProvisioner identityProvisioner;
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
/**
* Proxies whose listener could not be closed during a failed start or replace. The
@@ -57,11 +61,21 @@ public class RedshiftProxyManager {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor,
auditLogPublisher, parquetWriter, null, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter,
RedshiftCredentialBroker credentialBroker,
RedshiftDbIdentityProvisioner identityProvisioner) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
this.s3Service = s3Service;
@@ -70,6 +84,8 @@ public class RedshiftProxyManager {
this.config = config;
this.parquetWriter = parquetWriter;
this.auditLogPublisher = auditLogPublisher;
this.credentialBroker = credentialBroker;
this.identityProvisioner = identityProvisioner;
}
public synchronized void startProxy(String relayKey, int proxyPort,
@@ -107,7 +123,8 @@ public class RedshiftProxyManager {
clusterAccountId,
iamRoleArns,
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher, parquetWriter);
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher, parquetWriter,
credentialBroker, identityProvisioner);
proxy.updateIamRoles(iamRoleArns, defaultIamRoleArn);
try {
proxy.start(proxyPort);
@@ -1,9 +1,13 @@
package io.floci.aws.services.redshiftdata;
import io.floci.aws.services.redshift.RedshiftDbIdentityProvisioner;
import io.floci.aws.services.redshift.proxy.RedshiftInternalAuth;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.postgresql.Driver;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
@@ -12,8 +16,50 @@ import java.util.Properties;
class RedshiftDataConnectionFactory {
private final Driver driver = new Driver();
private final RedshiftDbIdentityProvisioner identityProvisioner;
RedshiftDataConnectionFactory() {
this(null);
}
@Inject
RedshiftDataConnectionFactory(RedshiftDbIdentityProvisioner identityProvisioner) {
this.identityProvisioner = identityProvisioner;
}
Connection open(RedshiftDataResourceResolver.DatabaseTarget target) throws SQLException {
RedshiftDataResourceResolver.DbIdentity dbIdentity = target.dbIdentity();
if (identityProvisioner == null || dbIdentity == null) {
return openRaw(target, target.user(), target.password());
}
String backendKey = target.backendKey() != null ? target.backendKey() : target.arn();
RedshiftDbIdentityProvisioner.PreparedIdentity prepared;
try (Connection admin = openRaw(target, target.user(), target.password())) {
prepared = identityProvisioner.prepare(
admin, backendKey, dbIdentity.role(), dbIdentity.autoCreate(),
dbIdentity.dbGroups(), () -> openRaw(target, target.user(), target.password()));
}
try {
// The session authenticates as the role itself, so PostgreSQL refuses any switch to
// another user and loads the role's own ALTER USER ... SET defaults.
String password = prepared.backendPassword() != null ? prepared.backendPassword() : target.password();
Connection connection;
try {
connection = openRaw(target, prepared.databaseRole(), password);
} finally {
// Redshift keeps a user's own password working beside temporary credentials, so
// put it back as soon as the login is done instead of when the session closes.
prepared.restorePassword().run();
}
return wrapWithRelease(connection, prepared.releaseLease());
} catch (SQLException | RuntimeException failure) {
prepared.releaseLease().run();
throw failure;
}
}
private Connection openRaw(RedshiftDataResourceResolver.DatabaseTarget target,
String user, String password) throws SQLException {
// stringtype=unspecified: Redshift Data API parameter values are always strings on the
// wire, so every bind goes through PreparedStatement.setString. With the default
// (varchar) the driver stamps an explicit type OID and the server refuses
@@ -23,10 +69,32 @@ class RedshiftDataConnectionFactory {
String url = "jdbc:postgresql://" + target.host() + ":" + target.port() + "/" + target.database()
+ "?sslmode=disable&stringtype=unspecified&ApplicationName=" + applicationName;
Properties props = new Properties();
props.setProperty("user", target.user());
props.setProperty("password", target.password());
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("ApplicationName", applicationName);
props.setProperty("connectTimeout", "5");
return driver.connect(url, props);
}
private static Connection wrapWithRelease(Connection delegate, Runnable releaseLease) {
return (Connection) Proxy.newProxyInstance(
Connection.class.getClassLoader(),
new Class<?>[]{Connection.class},
(proxy, method, args) -> {
if ("close".equals(method.getName()) && method.getParameterCount() == 0) {
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} finally {
releaseLease.run();
}
}
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
});
}
}
@@ -6,8 +6,11 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.DatabaseSecretCredentials;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.services.redshift.RedshiftCredentialBroker;
import io.floci.aws.services.redshift.RedshiftIamDbUserResolver;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.TempCredential;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.proxy.CopyStatementParser;
import io.floci.aws.services.redshift.spectrum.SpectrumSession;
@@ -35,6 +38,18 @@ class RedshiftDataResourceResolver {
private final RedshiftCredentialBroker credentialBroker;
private final RegionResolver regionResolver;
private final RedshiftServerlessService serverlessService;
private final RedshiftIamDbUserResolver iamDbUserResolver;
private final RequestContext requestContext;
RedshiftDataResourceResolver(RedshiftService redshiftService,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper,
RedshiftCredentialBroker credentialBroker,
RegionResolver regionResolver,
RedshiftServerlessService serverlessService) {
this(redshiftService, secretsManagerService, objectMapper, credentialBroker,
regionResolver, serverlessService, null, null);
}
@Inject
RedshiftDataResourceResolver(RedshiftService redshiftService,
@@ -42,13 +57,17 @@ class RedshiftDataResourceResolver {
ObjectMapper objectMapper,
RedshiftCredentialBroker credentialBroker,
RegionResolver regionResolver,
RedshiftServerlessService serverlessService) {
RedshiftServerlessService serverlessService,
RedshiftIamDbUserResolver iamDbUserResolver,
RequestContext requestContext) {
this.redshiftService = redshiftService;
this.secretsManagerService = secretsManagerService;
this.objectMapper = objectMapper;
this.credentialBroker = credentialBroker;
this.regionResolver = regionResolver;
this.serverlessService = serverlessService;
this.iamDbUserResolver = iamDbUserResolver;
this.requestContext = requestContext;
}
/** The ARN of the serverless workgroup a request names by its name or ARN, as {@link #resolve} reads it. */
@@ -96,9 +115,12 @@ class RedshiftDataResourceResolver {
String host = hasProxy ? "127.0.0.1" : workgroup.host();
int port = hasProxy ? proxyPort : workgroup.port();
if (!hasText(request, "SecretArn")) {
String iamUser = resolveIamDbUser();
String backendKey = accountId + ":" + RedshiftServerlessRuntime.backendId(region, workgroup.workgroupName());
DbIdentity identity = new DbIdentity(iamUser, true, List.of());
return new DatabaseTarget(workgroup.arn(), host, port, database,
workgroup.masterUsername(), workgroup.masterPassword(), spectrum, null,
workgroup.masterUsername(), workgroup.workgroupName());
iamUser, workgroup.workgroupName(), identity, backendKey);
}
String secretArn = request.get("SecretArn").asText();
DatabaseSecretCredentials creds = secretCredentials(secretArn, region);
@@ -110,6 +132,14 @@ class RedshiftDataResourceResolver {
user, creds.password(), spectrum, null, user, workgroup.workgroupName());
}
private String resolveIamDbUser() {
if (iamDbUserResolver == null) {
return "IAMR:floci";
}
String accessKeyId = requestContext == null ? null : requestContext.getAccessKeyId();
return iamDbUserResolver.resolveDbUserForAccessKey(accessKeyId);
}
private boolean isManagedAdminSecret(String secretArn, String managedSecretArn, String region) {
if (managedSecretArn == null) {
return false;
@@ -161,15 +191,16 @@ class RedshiftDataResourceResolver {
if (dbUser.equals(cluster.getMasterUsername())) {
return target(clusterArn(clusterId, region), cluster, database, dbUser, cluster.getMasterPassword(), needsProxy);
}
boolean liveCredential = credentialBroker
.resolve(regionResolver.getAccountId(), clusterId, dbUser)
.isPresent();
if (liveCredential) {
// The minted DbUser is nominal: connect as the cluster master.
Optional<TempCredential> liveCredential = credentialBroker
.resolve(regionResolver.getAccountId(), clusterId, dbUser);
if (liveCredential.isPresent()) {
TempCredential cred = liveCredential.get();
DatabaseTarget backend = target(clusterArn(clusterId, region), cluster, database,
cluster.getMasterUsername(), cluster.getMasterPassword(), needsProxy);
DbIdentity identity = new DbIdentity(cred.databaseRole(), cred.autoCreate(), cred.dbGroups());
String backendKey = regionResolver.getAccountId() + ":" + clusterId;
return new DatabaseTarget(backend.arn(), backend.host(), backend.port(), backend.database(), backend.user(),
backend.password(), backend.spectrum(), cluster, dbUser);
backend.password(), backend.spectrum(), cluster, dbUser, null, identity, backendKey);
}
throw validation("DbUser " + dbUser + " has no active credentials; call GetClusterCredentials first.");
}
@@ -252,11 +283,23 @@ class RedshiftDataResourceResolver {
return value == null || value.isNull() ? null : value.asText();
}
record DbIdentity(String role, boolean autoCreate, List<String> dbGroups) {
DbIdentity {
dbGroups = dbGroups == null ? List.of() : List.copyOf(dbGroups);
}
}
record DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster, String auditUser, String workgroupName) {
SpectrumSession spectrum, Cluster cluster, String auditUser, String workgroupName,
DbIdentity dbIdentity, String backendKey) {
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster, String auditUser, String workgroupName) {
this(arn, host, port, database, user, password, spectrum, cluster, auditUser, workgroupName, null, null);
}
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster, String auditUser) {
this(arn, host, port, database, user, password, spectrum, cluster, auditUser, null);
this(arn, host, port, database, user, password, spectrum, cluster, auditUser, null, null, null);
}
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
@@ -408,6 +408,12 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
if (stored.withEvent && requestContext != null && requestContext.getAccessKeyId() != null) {
stored.principal = iamService.resolveCallerArn(requestContext.getAccessKeyId()).orElse(null);
}
if (target.dbIdentity() != null) {
stored.dbGroups = target.dbIdentity().dbGroups();
if (stored.dbUser == null && target.workgroupName() != null) {
stored.dbUser = target.dbIdentity().role();
}
}
}
private PendingStatement prepareStatement(JsonNode request, String region, RedshiftDataSessions.Scope owner) {
@@ -423,7 +429,7 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
stored.sqls = List.of(sql);
stored.clusterIdentifier = clusterIdentifierOrNull(resolved.parameters());
stored.workgroupName = workgroupNameOrNull(resolved.parameters());
stored.dbUser = target.user();
stored.dbUser = target.auditUser() != null ? target.auditUser() : target.user();
stored.database = target.database();
stored.resultFormat = request.path("ResultFormat").asText("JSON");
stored.queryParameters = storedParameters(parameters);
@@ -731,7 +737,12 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
if (stored.dbUser != null) {
response.put("DbUser", stored.dbUser);
}
response.putArray("DbGroups");
ArrayNode dbGroups = response.putArray("DbGroups");
if (stored.dbGroups != null) {
for (String group : stored.dbGroups) {
dbGroups.add(group);
}
}
putWorkgroupName(response, stored);
response.put("HasResultSet", stored.hasResultSet);
if (stored.sessionId == null) {
@@ -909,7 +920,7 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
parent.sqls = sqls;
parent.clusterIdentifier = clusterIdentifierOrNull(resolved.parameters());
parent.workgroupName = workgroupNameOrNull(resolved.parameters());
parent.dbUser = target.user();
parent.dbUser = target.auditUser() != null ? target.auditUser() : target.user();
parent.database = target.database();
parent.resultFormat = request.path("ResultFormat").asText("JSON");
parent.subStatements = new ArrayList<>();
@@ -180,6 +180,7 @@ class RedshiftDataStatementStore {
String workgroupName;
String database;
String dbUser;
List<String> dbGroups = List.of();
String sessionId;
String resultFormat = "JSON";
Status status;
@@ -225,6 +226,7 @@ class RedshiftDataStatementStore {
copy.workgroupName = workgroupName;
copy.database = database;
copy.dbUser = dbUser;
copy.dbGroups = dbGroups;
copy.sessionId = sessionId;
copy.resultFormat = resultFormat;
copy.status = status;
@@ -199,7 +199,7 @@ public class RedshiftServerlessRuntime {
public TempCredential issueCredential(String accountId, String region, String workgroupName,
String dbUser, int durationSeconds) {
return credentialBroker.issue(accountId, backendId(region, workgroupName), dbUser, List.of(),
durationSeconds);
durationSeconds, dbUser, true);
}
public String generatePassword() {
@@ -63,6 +63,9 @@ class RedshiftCredentialBrokerTest {
broker.classify("acc", "clus", "analyst", first.password()));
assertEquals(RedshiftCredentialBroker.Match.MASTER_EQUIVALENT,
broker.classify("acc", "clus", "analyst", second.password()));
// Passwordless resolution (e.g. Data API DbUser) picks the most recently issued credential.
assertEquals(second.password(),
broker.resolve("acc", "clus", "analyst").orElseThrow().password());
}
@Test
@@ -121,4 +124,30 @@ class RedshiftCredentialBrokerTest {
broker.clear();
assertTrue(broker.resolve("acc", "clus", "analyst").isEmpty());
}
@Test
void issueStoresDatabaseRoleAndAutoCreateFlag() {
TempCredential cred = broker.issue("acc", "clus", "IAM:analyst", List.of("g1"), 900, "analyst", false);
assertEquals("IAM:analyst", cred.dbUser());
assertEquals("analyst", cred.databaseRole());
assertFalse(cred.autoCreate());
assertEquals(List.of("g1"), cred.dbGroups());
}
@Test
void authenticateReturnsExactMatchingCredentialForPassword() {
TempCredential first = broker.issue("acc", "clus", "IAM:analyst", List.of("g1"), 900, "analyst", false);
TempCredential second = broker.issue("acc", "clus", "IAM:analyst", List.of("g2"), 900, "analyst", false);
Optional<TempCredential> matchedFirst = broker.authenticate("acc", "clus", "IAM:analyst", first.password());
Optional<TempCredential> matchedSecond = broker.authenticate("acc", "clus", "IAM:analyst", second.password());
assertTrue(matchedFirst.isPresent());
assertEquals(List.of("g1"), matchedFirst.get().dbGroups());
assertTrue(matchedSecond.isPresent());
assertEquals(List.of("g2"), matchedSecond.get().dbGroups());
assertTrue(broker.authenticate("acc", "clus", "IAM:analyst", "wrong").isEmpty());
assertTrue(broker.authenticate("acc", "clus", "unknown", "whatever").isEmpty());
}
}
@@ -1,7 +1,10 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
@@ -9,17 +12,24 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
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.assertThrows;
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.
* End-to-end: IAM-derived Redshift credentials map to real non-superuser PostgreSQL roles
* with AutoCreate, session-scoped DbGroups, and consistent behavior across wire, Data API,
* and retained sessions.
*/
@QuarkusTest
class RedshiftGetClusterCredentialsIntegrationTest {
@@ -56,45 +66,229 @@ class RedshiftGetClusterCredentialsIntegrationTest {
}
}
private void awaitFinished(String id) {
private String awaitTerminal(String id) {
String[] terminal = new String[1];
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);
if ("FINISHED".equals(status) || "FAILED".equals(status) || "ABORTED".equals(status)) {
terminal[0] = status;
return true;
}
return false;
});
return terminal[0];
}
private void awaitFinished(String id) {
String status = awaitTerminal(id);
assertEquals("FINISHED", status, () -> "statement " + id + " ended " + status);
}
private String executeMaster(String sql) {
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "%s", "ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev"}
""".formatted(sql, clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(id);
return id;
}
@Test
void nonMasterDbUserWorksAfterGetClusterCredentials() {
clusterId = "it-gcc-" + System.currentTimeMillis();
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
void autoCreateTrueCreatesNonSuperuserRoleWithMatchingCurrentUserAndOwnership() throws SQLException {
clusterId = "it-gcc-auto-" + System.currentTimeMillis();
Cluster cluster = redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
given()
String xml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "analyst")
.formParam("AutoCreate", "true")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<DbUser>IAM:analyst</DbUser>"))
.body(containsString("<DbPassword>"))
.body(containsString("<Expiration>"));
.body(containsString("<DbUser>IAMA:analyst</DbUser>"))
.extract().asString();
// A client passes back the exact DbUser that GetClusterCredentials returned.
String dbPassword = xml.replaceAll("(?s).*<DbPassword>(.*?)</DbPassword>.*", "$1");
// Data API: current_user is "analyst" (without IAMA: prefix) and created table is owned by "analyst".
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT 1", "ClusterIdentifier": "%s", "DbUser": "IAM:analyst", "Database": "dev"}
{"Sql": "SELECT current_user", "ClusterIdentifier": "%s", "DbUser": "IAMA: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());
String currentUser = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Records[0][0].stringValue");
assertEquals("analyst", currentUser);
String createId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "CREATE TABLE analyst_tbl (id INT)", "ClusterIdentifier": "%s", "DbUser": "IAMA:analyst", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(createId);
String ownerId = executeMaster("SELECT tableowner FROM pg_tables WHERE tablename = 'analyst_tbl'");
String owner = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + ownerId + "\"}").then().statusCode(200).extract().path("Records[0][0].stringValue");
assertEquals("analyst", owner);
// Wire proxy: current_user is also "analyst".
String jdbcUrl = "jdbc:postgresql://127.0.0.1:" + cluster.getProxyPort() + "/dev?sslmode=disable";
try (Connection conn = DriverManager.getConnection(jdbcUrl, "IAMA:analyst", dbPassword);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT current_user")) {
assertTrue(rs.next());
assertEquals("analyst", rs.getString(1));
}
}
@Test
void autoCreateFalseFailsForMissingRoleAndSupportsDbGroupsAcrossSession() throws SQLException {
clusterId = "it-gcc-noauto-" + System.currentTimeMillis();
Cluster cluster = redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String xml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "restricted")
.formParam("AutoCreate", "false")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<DbUser>IAM:restricted</DbUser>"))
.extract().asString();
String noAutoPw = xml.replaceAll("(?s).*<DbPassword>(.*?)</DbPassword>.*", "$1");
// Missing role with AutoCreate=false must fail on both wire and Data API (never fall back to master).
String jdbcUrl = "jdbc:postgresql://127.0.0.1:" + cluster.getProxyPort() + "/dev?sslmode=disable";
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl, "IAM:restricted", noAutoPw));
String failId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT 1", "ClusterIdentifier": "%s", "DbUser": "IAM:restricted", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
assertEquals("FAILED", awaitTerminal(failId));
// Pre-create user and group, plus an admin-owned table granted only to the group.
executeMaster("CREATE USER restricted");
executeMaster("CREATE GROUP etl_readers");
executeMaster("CREATE TABLE secret_tbl (v INT)");
executeMaster("INSERT INTO secret_tbl VALUES (42)");
executeMaster("GRANT SELECT ON secret_tbl TO GROUP etl_readers");
// Without DbGroups, restricted cannot read secret_tbl.
String deniedId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT v FROM secret_tbl", "ClusterIdentifier": "%s", "DbUser": "IAM:restricted", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
assertEquals("FAILED", awaitTerminal(deniedId));
// With DbGroups=etl_readers, restricted can read secret_tbl in a retained Data API session.
String groupXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "restricted")
.formParam("AutoCreate", "false")
.formParam("DbGroups.member.1", "etl_readers")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
String groupPw = groupXml.replaceAll("(?s).*<DbPassword>(.*?)</DbPassword>.*", "$1");
ExtractableResponse<Response> groupResp = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT v FROM secret_tbl", "ClusterIdentifier": "%s", "DbUser": "IAM:restricted", "Database": "dev", "SessionKeepAliveSeconds": 60}
""".formatted(clusterId)).then().statusCode(200).extract();
String groupStmtId = groupResp.path("Id");
String sessionId = groupResp.path("SessionId");
List<String> respGroups = groupResp.path("DbGroups");
assertEquals(List.of("etl_readers"), respGroups);
awaitFinished(groupStmtId);
Object val = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + groupStmtId + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue");
assertEquals(42, ((Number) val).intValue());
// Subsequent statement in the same retained session preserves DbGroups.
String retainedId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT v FROM secret_tbl", "SessionId": "%s"}
""".formatted(sessionId)).then().statusCode(200).extract().path("Id");
awaitFinished(retainedId);
// Wire proxy also honors DbGroups and revokes temporary membership on disconnect.
try (Connection conn = DriverManager.getConnection(jdbcUrl, "IAM:restricted", groupPw);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT v FROM secret_tbl")) {
assertTrue(rs.next());
assertEquals(42, rs.getInt(1));
}
// Missing DbGroup must fail rather than silently running without the group.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "restricted")
.formParam("AutoCreate", "false")
.formParam("DbGroups.member.1", "nonexistent_group")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200);
String missingGroupPw = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentials")
.formParam("ClusterIdentifier", clusterId)
.formParam("DbUser", "restricted")
.formParam("AutoCreate", "false")
.formParam("DbGroups.member.1", "nonexistent_group")
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString().replaceAll("(?s).*<DbPassword>(.*?)</DbPassword>.*", "$1");
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl, "IAM:restricted", missingGroupPw));
}
@Test
void getClusterCredentialsWithIamMapsToIamrRole() {
clusterId = "it-gcc-iam-" + System.currentTimeMillis();
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String xml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "GetClusterCredentialsWithIAM")
.formParam("ClusterIdentifier", clusterId)
.formParam("DurationSeconds", "900")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<DbUser>IAMR:floci</DbUser>"))
.extract().asString();
assertTrue(xml.contains("<DbPassword>"));
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT current_user", "ClusterIdentifier": "%s", "DbUser": "IAMR:floci", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(id);
String currentUser = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Records[0][0].stringValue");
assertEquals("IAMR:floci", currentUser);
}
}
@@ -74,4 +74,12 @@ class RedshiftIamDbUserResolverTest {
assertEquals("IAMR:floci", resolver.resolveDbUser(null));
}
@Test
void resolveDbUserForAccessKeyMapsArnDirectly() {
when(iamService.resolveCallerArn("ASIA999"))
.thenReturn(Optional.of("arn:aws:sts::000000000000:assumed-role/AnalyticsRole/s1"));
assertEquals("IAMR:AnalyticsRole", resolver.resolveDbUserForAccessKey("ASIA999"));
}
}
@@ -0,0 +1,164 @@
package io.floci.aws.services.redshift;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class TempGroupGrantTrackerTest {
private TempGroupGrantTracker tracker;
@BeforeEach
void setUp() {
tracker = new TempGroupGrantTracker();
}
@Test
void refCountsConcurrentLeasesAndRevokesOnlyOnLastRelease() throws SQLException {
List<String> events = new ArrayList<>();
TempGroupGrantTracker.Lease first = tracker.acquire(
"acc:clus", "analyst", List.of("g1", "g2"),
group -> events.add("GRANT:" + group));
TempGroupGrantTracker.Lease second = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> events.add("GRANT:" + group));
assertEquals(List.of("GRANT:g1", "GRANT:g2"), events);
first.release(group -> events.add("REVOKE:" + group));
assertEquals(List.of("GRANT:g1", "GRANT:g2", "REVOKE:g2"), events);
// Releasing the same lease twice is a no-op.
first.release(group -> events.add("REVOKE:" + group));
assertEquals(List.of("GRANT:g1", "GRANT:g2", "REVOKE:g2"), events);
second.release(group -> events.add("REVOKE:" + group));
assertEquals(List.of("GRANT:g1", "GRANT:g2", "REVOKE:g2", "REVOKE:g1"), events);
}
@Test
void rollsBackAcquiredGrantsIfASubsequentGroupGrantFails() throws SQLException {
List<String> events = new ArrayList<>();
assertThrows(SQLException.class, () -> tracker.acquire(
"acc:clus", "analyst", List.of("g1", "bad"),
group -> {
if ("bad".equals(group)) {
throw new SQLException("boom");
}
events.add("GRANT:" + group);
}));
// After rollback, a new acquire for g1 must grant it again because ref-count returned to 0.
tracker.acquire("acc:clus", "analyst", List.of("g1"), group -> events.add("GRANT2:" + group));
assertEquals(List.of("GRANT:g1", "GRANT2:g1"), events);
}
@Test
void checksPermanentMembershipInsideLockSoConcurrentSessionAcquiresLease() throws SQLException {
List<String> events = new ArrayList<>();
AtomicBoolean pgHasMembership = new AtomicBoolean(false);
TempGroupGrantTracker.Lease first = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> {
pgHasMembership.set(true);
events.add("GRANT:" + group);
},
null,
group -> pgHasMembership.get());
// Even though PostgreSQL now reports analyst in g1, session 2 must still take a lease
// because session 1 holds an active temporary grant.
TempGroupGrantTracker.Lease second = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> events.add("GRANT2:" + group),
null,
group -> pgHasMembership.get());
first.release(group -> {
pgHasMembership.set(false);
events.add("REVOKE1:" + group);
});
assertEquals(List.of("GRANT:g1"), events);
second.release(group -> {
pgHasMembership.set(false);
events.add("REVOKE2:" + group);
});
assertEquals(List.of("GRANT:g1", "REVOKE2:g1"), events);
}
@Test
void preservesPendingRevokeStateWhenRevokeFailsAndRetriesOnNextSession() throws SQLException {
List<String> events = new ArrayList<>();
AtomicBoolean pgHasMembership = new AtomicBoolean(false);
TempGroupGrantTracker.Lease first = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> {
pgHasMembership.set(true);
events.add("GRANT1:" + group);
},
null,
group -> pgHasMembership.get());
assertThrows(SQLException.class, () -> first.release(group -> {
throw new SQLException("transient network error");
}));
// Because the previous REVOKE failed, the grant still exists in PostgreSQL.
// Next session must adopt it (not treat it as permanent) and revoke it on close.
TempGroupGrantTracker.Lease second = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> events.add("GRANT2:" + group),
null,
group -> pgHasMembership.get());
second.release(group -> {
pgHasMembership.set(false);
events.add("REVOKE2:" + group);
});
assertEquals(List.of("GRANT1:g1", "REVOKE2:g1"), events);
}
@Test
void toleratesRollbackRevokeFailureAndAdoptsLeftoverGrantOnRetry() throws SQLException {
List<String> events = new ArrayList<>();
AtomicBoolean pgHasMembership = new AtomicBoolean(false);
assertThrows(SQLException.class, () -> tracker.acquire(
"acc:clus", "analyst", List.of("g1", "bad"),
group -> {
if ("bad".equals(group)) {
throw new SQLException("grant failed");
}
pgHasMembership.set(true);
events.add("GRANT1:" + group);
},
group -> {
throw new SQLException("rollback revoke failed");
},
group -> "g1".equals(group) && pgHasMembership.get()));
TempGroupGrantTracker.Lease retry = tracker.acquire(
"acc:clus", "analyst", List.of("g1"),
group -> events.add("GRANT2:" + group),
null,
group -> pgHasMembership.get());
retry.release(group -> {
pgHasMembership.set(false);
events.add("REVOKE2:" + group);
});
assertEquals(List.of("GRANT1:g1", "REVOKE2:g1"), events);
}
}
@@ -0,0 +1,92 @@
package io.floci.aws.services.redshift;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class TempRolePasswordTrackerTest {
private final TempRolePasswordTracker tracker = new TempRolePasswordTracker();
private final List<String> writes = new ArrayList<>();
@Test
void concurrentSessionsShareOnePasswordAndLastReleaseRestoresTheStoredHash() throws Exception {
TempRolePasswordTracker.Lease first = tracker.acquire("k", "analyst", () -> "SCRAM-SHA-256$stored", writes::add);
TempRolePasswordTracker.Lease second = tracker.acquire("k", "analyst", () -> "SCRAM-SHA-256$stored", writes::add);
assertEquals(first.password(), second.password());
assertEquals(1, writes.size());
first.release(writes::add);
assertEquals(1, writes.size());
second.release(writes::add);
assertEquals(List.of(first.password(), "SCRAM-SHA-256$stored"), writes);
}
@Test
void roleWithoutPasswordIsRestoredToNull() throws Exception {
TempRolePasswordTracker.Lease lease = tracker.acquire("k", "analyst", () -> null, writes::add);
lease.release(writes::add);
lease.release(writes::add);
assertEquals(2, writes.size());
assertNull(writes.get(1));
}
@Test
void concurrentAcquireAndReleaseAlwaysEndWithTheStoredHashRestored() throws Exception {
List<String> log = Collections.synchronizedList(new ArrayList<>());
int threads = 8;
int rounds = 200;
ExecutorService pool = Executors.newFixedThreadPool(threads);
try {
List<Future<?>> futures = new ArrayList<>();
for (int t = 0; t < threads; t++) {
futures.add(pool.submit(() -> {
for (int i = 0; i < rounds; i++) {
TempRolePasswordTracker.Lease lease = tracker.acquire(
"k", "analyst", () -> "stored", log::add);
lease.release(log::add);
}
return null;
}));
}
for (Future<?> future : futures) {
future.get();
}
} finally {
pool.shutdownNow();
}
// The stored hash is only ever read from the role itself, never from a temporary password.
assertEquals("stored", log.get(log.size() - 1));
long restores = log.stream().filter("stored"::equals).count();
assertEquals(log.size() - restores, restores);
}
@Test
void failedRestoreKeepsTheStoredHashForTheNextSession() throws Exception {
TempRolePasswordTracker.Lease lease = tracker.acquire("k", "analyst", () -> "stored", writes::add);
lease.release(value -> {
throw new SQLException("backend down");
});
TempRolePasswordTracker.Lease next = tracker.acquire("k", "analyst", () -> lease.password(), writes::add);
assertNotEquals(lease.password(), next.password());
next.release(writes::add);
assertEquals("stored", writes.get(writes.size() - 1));
}
}
@@ -0,0 +1,146 @@
package io.floci.aws.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.services.redshift.RedshiftCredentialBroker;
import io.floci.aws.services.redshift.RedshiftIamDbUserResolver;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftDataResourceResolverIdentityTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private RedshiftService redshiftService;
private SecretsManagerService secretsManagerService;
private RedshiftCredentialBroker credentialBroker;
private RegionResolver regionResolver;
private RedshiftServerlessService serverlessService;
private RedshiftIamDbUserResolver iamDbUserResolver;
private RequestContext requestContext;
private RedshiftDataResourceResolver resolver;
@BeforeEach
void setUp() {
redshiftService = mock(RedshiftService.class);
secretsManagerService = mock(SecretsManagerService.class);
credentialBroker = new RedshiftCredentialBroker();
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
serverlessService = mock(RedshiftServerlessService.class);
iamDbUserResolver = mock(RedshiftIamDbUserResolver.class);
requestContext = new RequestContext();
requestContext.setAccessKeyId("ASIA123");
resolver = new RedshiftDataResourceResolver(
redshiftService, secretsManagerService, MAPPER,
credentialBroker, regionResolver, serverlessService,
iamDbUserResolver, requestContext);
}
@Test
void resolvesProvisionedGetClusterCredentialsWithoutAutoCreate() {
Cluster cluster = runningCluster("c1");
when(redshiftService.describeClusters("c1")).thenReturn(List.of(cluster));
credentialBroker.issue("000000000000", "c1", "IAM:analyst", List.of("g1"), 900, "analyst", false);
ObjectNode req = MAPPER.createObjectNode()
.put("ClusterIdentifier", "c1")
.put("Database", "dev")
.put("DbUser", "IAM:analyst");
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(req, "us-east-1");
assertNotNull(target.dbIdentity());
assertEquals("analyst", target.dbIdentity().role());
assertFalse(target.dbIdentity().autoCreate());
assertEquals(List.of("g1"), target.dbIdentity().dbGroups());
assertEquals("IAM:analyst", target.auditUser());
}
@Test
void resolvesProvisionedGetClusterCredentialsWithAutoCreateAndIam() {
Cluster cluster = runningCluster("c1");
when(redshiftService.describeClusters("c1")).thenReturn(List.of(cluster));
credentialBroker.issue("000000000000", "c1", "IAMA:alice", List.of("g1"), 900, "alice", true);
credentialBroker.issue("000000000000", "c1", "IAMR:MyRole", List.of("g2"), 900, "IAMR:MyRole", true);
ObjectNode autoReq = MAPPER.createObjectNode()
.put("ClusterIdentifier", "c1")
.put("Database", "dev")
.put("DbUser", "IAMA:alice");
RedshiftDataResourceResolver.DatabaseTarget autoTarget = resolver.resolve(autoReq, "us-east-1");
assertNotNull(autoTarget.dbIdentity());
assertEquals("alice", autoTarget.dbIdentity().role());
assertTrue(autoTarget.dbIdentity().autoCreate());
assertEquals(List.of("g1"), autoTarget.dbIdentity().dbGroups());
ObjectNode iamReq = MAPPER.createObjectNode()
.put("ClusterIdentifier", "c1")
.put("Database", "dev")
.put("DbUser", "IAMR:MyRole");
RedshiftDataResourceResolver.DatabaseTarget iamTarget = resolver.resolve(iamReq, "us-east-1");
assertNotNull(iamTarget.dbIdentity());
assertEquals("IAMR:MyRole", iamTarget.dbIdentity().role());
assertTrue(iamTarget.dbIdentity().autoCreate());
assertEquals(List.of("g2"), iamTarget.dbIdentity().dbGroups());
}
@Test
void resolvesServerlessIamWithoutSecretArnAndDirectSecretWithSecretArn() {
RedshiftServerlessService.WorkgroupTarget wg = new RedshiftServerlessService.WorkgroupTarget(
"arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/wg1",
"wg1", "127.0.0.1", 5439, "dev", "admin", "Secret123",
null, List.of(), null);
when(serverlessService.getWorkgroupTarget("wg1", "us-east-1")).thenReturn(wg);
when(iamDbUserResolver.resolveDbUserForAccessKey("ASIA123")).thenReturn("IAMR:MyRole");
ObjectNode iamReq = MAPPER.createObjectNode()
.put("WorkgroupName", "wg1")
.put("Database", "dev");
RedshiftDataResourceResolver.DatabaseTarget iamTarget = resolver.resolve(iamReq, "us-east-1");
assertNotNull(iamTarget.dbIdentity());
assertEquals("IAMR:MyRole", iamTarget.dbIdentity().role());
assertTrue(iamTarget.dbIdentity().autoCreate());
assertEquals("IAMR:MyRole", iamTarget.auditUser());
SecretVersion sv = new SecretVersion();
sv.setSecretString("{\"username\":\"admin\",\"password\":\"Secret123\"}");
when(secretsManagerService.getSecretValue(
"arn:aws:secretsmanager:us-east-1:000000000000:secret:my-secret",
null, null, "us-east-1")).thenReturn(sv);
ObjectNode secretReq = MAPPER.createObjectNode()
.put("WorkgroupName", "wg1")
.put("Database", "dev")
.put("SecretArn", "arn:aws:secretsmanager:us-east-1:000000000000:secret:my-secret");
RedshiftDataResourceResolver.DatabaseTarget secretTarget = resolver.resolve(secretReq, "us-east-1");
assertNull(secretTarget.dbIdentity());
}
private static Cluster runningCluster(String id) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(id);
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setContainerHost("127.0.0.1");
cluster.setContainerPort(5432);
return cluster;
}
}
@@ -225,12 +225,47 @@ class RedshiftServerlessRuntimeIntegrationTest {
assertNotNull(dbUser);
assertNotNull(dbPassword);
try (Connection connection = connect(dbUser, dbPassword)) {
try (Connection connection = connect(dbUser, dbPassword);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT current_user")) {
assertTrue(connection.isValid(5));
assertTrue(rs.next());
assertEquals(dbUser, rs.getString(1));
}
assertThrows(SQLException.class, () -> DriverManager.getConnection(jdbcUrl(), dbUser, "stale-password"));
}
@Test
void dataApiWithoutSecretArnRunsAsIamIdentityAcrossRetainedSession() {
ExtractableResponse<Response> first = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT current_user", "WorkgroupName": "%s", "Database": "dev", "SessionKeepAliveSeconds": 60}
""".formatted(WORKGROUP)).then().statusCode(200).extract();
String firstId = first.path("Id");
String sessionId = first.path("SessionId");
assertNotNull(sessionId);
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(250)).until(() -> "FINISHED".equals(
RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + firstId + "\"}").then().statusCode(200).extract().path("Status")));
String user1 = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + firstId + "\"}").then().statusCode(200).extract().path("Records[0][0].stringValue");
assertEquals("IAMR:floci", user1);
String secondId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT current_user", "SessionId": "%s"}
""".formatted(sessionId)).then().statusCode(200).extract().path("Id");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(250)).until(() -> "FINISHED".equals(
RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + secondId + "\"}").then().statusCode(200).extract().path("Status")));
String user2 = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + secondId + "\"}").then().statusCode(200).extract().path("Records[0][0].stringValue");
assertEquals("IAMR:floci", user2);
}
@Test
void anAdminPasswordChangeAppliesToNewConnections() throws SQLException {
RestAssuredJsonUtils.awsAction("RedshiftServerless", "UpdateNamespace",