mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
5f03ff975d
commit
b658720afe
26 files changed
+1658
-65
No files matched your search
@@ -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);
|
||||
|
||||
+70
-2
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+53
-10
@@ -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;
|
||||
|
||||
+1
-1
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user