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

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

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

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

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

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

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

* feat(redshift): implement GetClusterCredentials action

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

* feat(redshift): implement GetClusterCredentialsWithIAM action

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

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

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

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

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

* test(compat): SDK coverage for Redshift GetClusterCredentials

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

* docs(redshift): document GetClusterCredentials and GetClusterCredentialsWithIAM

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

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

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

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

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

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

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

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

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

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

* fix(redshift): correct GetClusterCredentials AutoCreate prefix

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

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

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

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

No files matched your search

@@ -1312,6 +1312,11 @@ public interface EmulatorConfig {
// Hostname clients use to reach a cluster endpoint. Empty -> resolved from
// DockerHostResolver (falls back to "localhost").
Optional<String> endpointHost();
// Default lifetime for GetClusterCredentials / GetClusterCredentialsWithIAM when
// DurationSeconds is omitted. AWS allows 900 to 3600.
@WithDefault("900")
int defaultCredentialDurationSeconds();
}
interface RdsServiceConfig {
@@ -356,7 +356,7 @@ public class AwsQueryController {
: elbV2QueryHandler.handle(action, formParams, region);
case "autoscaling" -> autoScalingQueryHandler.handle(action, formParams, region);
case "elasticbeanstalk" -> elasticBeanstalkQueryHandler.handle(action, formParams, region);
case "redshift" -> redshiftQueryHandler.handle(action, formParams);
case "redshift" -> redshiftQueryHandler.handle(action, formParams, authorization);
default -> xmlErrorResponse("UnknownService",
"Unknown or unsupported service: " + service, 400);
};
@@ -605,7 +605,8 @@ public class AwsQueryController {
"CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup",
"ModifyClusterParameterGroup",
"CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup",
"CreateTags", "DeleteTags", "DescribeTags"
"CreateTags", "DeleteTags", "DescribeTags",
"GetClusterCredentials", "GetClusterCredentialsWithIAM"
);
private String resolveService(String authorization, String action) {
@@ -1,6 +1,17 @@
package io.github.hectorvent.floci.services.rds.proxy;
@FunctionalInterface
public interface PasswordValidator {
boolean validate(String username, String password);
}
public interface PasswordValidator {
AuthResult validate(String username, String password);
/**
* REJECT : refuse the client.
* PASSTHROUGH : the proxy does not vouch for this user; forward the
* client's own credentials so the backend enforces them
* (legacy non-master behaviour).
* MASTER_EQUIVALENT: the proxy has validated the client; open the backend
* connection as the cluster master.
*/
enum AuthResult { REJECT, PASSTHROUGH, MASTER_EQUIVALENT }
}
@@ -54,6 +54,26 @@ public class PostgresProtocolHandler {
*/
public record AuthenticatedSession(Socket client, String iamRole) {}
/** The username/password the proxy opens the backend PostgreSQL connection with. */
record BackendLogin(String user, String password) {}
/**
* Picks the backend login: the cluster master whenever the proxy is the authority for this
* connection (an IAM token, the master user itself, or a client the validator vouched for),
* otherwise the client's own credentials so the backend enforces its ACLs.
*/
static BackendLogin resolveBackendLogin(boolean isMaster, boolean isIam,
PasswordValidator.AuthResult result,
String masterUsername, String masterPassword,
String clientUsername, String clientPassword) {
boolean useMaster = isIam || isMaster
|| result == PasswordValidator.AuthResult.MASTER_EQUIVALENT;
if (useMaster) {
return new BackendLogin(masterUsername, masterPassword);
}
return new BackendLogin(clientUsername, clientPassword);
}
public static AuthenticatedSession authenticate(Socket client, Socket backend,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
@@ -84,12 +104,15 @@ public class PostgresProtocolHandler {
// Phase 4: Validate credentials.
// - IAM tokens: validated locally via SigV4.
// - Master user (plain password): validated at the proxy via passwordValidator, which
// reads from RdsService and therefore reflects modifyDBInstance password changes.
// - Non-master users: pass through — the backend is the authority for their passwords.
// - Every non-IAM client: classified by passwordValidator into REJECT / PASSTHROUGH /
// MASTER_EQUIVALENT. PASSTHROUGH keeps the legacy non-master behaviour (the backend is
// the authority for the password); MASTER_EQUIVALENT means the proxy vouched for the
// client, so the backend leg runs as the cluster master. The RDS validator reads from
// RdsService, so a master login still reflects modifyDBInstance password changes.
boolean isIam = iamEnabled && clientPassword.contains("X-Amz-Signature");
boolean isMaster = masterUsername.equals(clientUsername);
PasswordValidator.AuthResult authResult = PasswordValidator.AuthResult.PASSTHROUGH;
if (isIam) {
if (!sigV4.validate(clientPassword, clientUsername)) {
sendErrorResponse(clientOut, "FATAL", "28P01",
@@ -99,8 +122,9 @@ public class PostgresProtocolHandler {
closeQuietly(backend);
return null;
}
} else if (isMaster) {
if (!passwordValidator.validate(clientUsername, clientPassword)) {
} else {
authResult = passwordValidator.validate(clientUsername, clientPassword);
if (authResult == PasswordValidator.AuthResult.REJECT) {
sendErrorResponse(clientOut, "FATAL", "28P01",
"password authentication failed for user \"" + clientUsername + "\"");
clientOut.flush();
@@ -113,13 +137,16 @@ public class PostgresProtocolHandler {
// Phase 5: Connect to backend PostgreSQL.
// IAM and master: use master credentials — the backend has the original container password
// and is never updated directly, so the proxy always authenticates as master.
// Non-master: forward the client's own credentials so the backend enforces its own ACLs.
// Non-master: forward the client's own credentials so the backend enforces its own ACLs,
// unless the proxy vouched for the client (MASTER_EQUIVALENT).
InputStream backendIn = backend.getInputStream();
OutputStream backendOut = backend.getOutputStream();
String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName);
String backendUser = (isIam || isMaster) ? masterUsername : clientUsername;
String backendPass = (isIam || isMaster) ? masterPassword : clientPassword;
BackendLogin backendLogin = resolveBackendLogin(isMaster, isIam, authResult,
masterUsername, masterPassword, clientUsername, clientPassword);
String backendUser = backendLogin.user();
String backendPass = backendLogin.password();
sendStartupToBackend(backendOut, backendUser, effectiveDbName);
backendOut.flush();
@@ -27,7 +27,7 @@ public class RdsAuthProxy {
private final DatabaseEngine engine;
private final RdsSigV4Validator sigV4;
private final RdsProxyTlsCertificates tlsCertificates;
private final PasswordValidator passwordValidator;
private final MasterPasswordCheck passwordValidator;
private volatile boolean running;
private ServerSocket serverSocket;
@@ -36,7 +36,7 @@ public class RdsAuthProxy {
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator) {
MasterPasswordCheck passwordValidator) {
this.instanceId = instanceId;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -99,19 +99,30 @@ public class RdsAuthProxy {
backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
// RDS only proxy-validates the master user; a non-master user passes through so the
// backend enforces its own credentials.
PasswordValidator authAdapter = (user, pass) -> {
if (!masterUsername.equals(user)) {
return PasswordValidator.AuthResult.PASSTHROUGH;
}
return passwordValidator.validate(user, pass)
? PasswordValidator.AuthResult.MASTER_EQUIVALENT
: PasswordValidator.AuthResult.REJECT;
};
switch (engine) {
case POSTGRES -> {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
iamEnabled, sigV4, tlsCertificates, authAdapter);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
}
case MYSQL, MARIADB -> MySqlProtocolHandler.handleAuth(
client, backend, masterUsername, masterPassword,
iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
iamEnabled, sigV4, tlsCertificates, authAdapter);
}
} catch (Exception e) {
LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage());
@@ -135,10 +146,12 @@ public class RdsAuthProxy {
}
/**
* Callback for password validation — implemented by RdsService.
* Callback for master-password validation, implemented by RdsService. Returns true when the
* supplied master credentials are current. Non-master users are never asked here: the backend
* database is the authority for their passwords.
*/
@FunctionalInterface
public interface PasswordValidator {
public interface MasterPasswordCheck {
boolean validate(String username, String password);
}
}
@@ -30,7 +30,7 @@ public class RdsProxyManager {
int proxyPort, String backendHost, int backendPort,
String advertisedHost,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
RdsAuthProxy.MasterPasswordCheck passwordValidator) {
tlsCertificates.ensureHost(advertisedHost);
RdsAuthProxy proxy = new RdsAuthProxy(
instanceId, backendHost, backendPort, engine, iamEnabled,
@@ -0,0 +1,108 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.Resettable;
import jakarta.enterprise.context.ApplicationScoped;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Holds the short-lived credentials minted by GetClusterCredentials /
* GetClusterCredentialsWithIAM. No real PostgreSQL role is created: a live
* credential is a signal to the auth proxy and the Data API resolver that the
* connection should run as the cluster master (the DbUser is nominal).
*
* <p>AWS keeps every issued credential valid until its own expiry, so a second
* call for the same DbUser does not invalidate the first: each key holds a list
* of unexpired credentials.
*/
@ApplicationScoped
public class RedshiftCredentialBroker implements Resettable {
public enum Match { MASTER_EQUIVALENT, REJECT, PASSTHROUGH }
private static final String PASSWORD_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final int PASSWORD_LENGTH = 32;
private final SecureRandom random = new SecureRandom();
private final ConcurrentHashMap<String, CopyOnWriteArrayList<TempCredential>> store = new ConcurrentHashMap<>();
public TempCredential issue(String accountId, String clusterId, String dbUser,
List<String> dbGroups, int durationSeconds) {
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);
store.compute(key(accountId, clusterId, dbUser), (k, existing) -> {
CopyOnWriteArrayList<TempCredential> list =
existing == null ? new CopyOnWriteArrayList<>() : existing;
list.removeIf(RedshiftCredentialBroker::isExpired);
list.add(credential);
return list;
});
return credential;
}
public Optional<TempCredential> resolve(String accountId, String clusterId, String dbUser) {
return liveCredentials(key(accountId, clusterId, dbUser)).stream().findFirst();
}
public Match classify(String accountId, String clusterId, String username, String password) {
List<TempCredential> live = liveCredentials(key(accountId, clusterId, username));
if (live.isEmpty()) {
return Match.PASSTHROUGH;
}
return live.stream().anyMatch(c -> c.password().equals(password))
? Match.MASTER_EQUIVALENT
: Match.REJECT;
}
/**
* Drops every credential minted for a cluster. Called when a cluster is deleted so a
* later cluster created with the same identifier does not inherit master-equivalent
* access from a stale credential.
*/
public void revokeCluster(String accountId, String clusterId) {
String prefix = accountId + ":" + clusterId + ":";
store.keySet().removeIf(k -> k.startsWith(prefix));
}
@Override
public void clear() {
store.clear();
}
// Package-private hook for tests: number of unexpired credentials held for a DbUser.
int liveCredentialCountForTesting(String accountId, String clusterId, String dbUser) {
return liveCredentials(key(accountId, clusterId, dbUser)).size();
}
private List<TempCredential> liveCredentials(String key) {
CopyOnWriteArrayList<TempCredential> list = store.get(key);
if (list == null) {
return List.of();
}
return list.stream().filter(c -> !isExpired(c)).toList();
}
private static boolean isExpired(TempCredential credential) {
return !credential.expiresAt().isAfter(Instant.now());
}
private String randomPassword() {
StringBuilder sb = new StringBuilder(PASSWORD_LENGTH);
for (int i = 0; i < PASSWORD_LENGTH; i++) {
sb.append(PASSWORD_ALPHABET.charAt(random.nextInt(PASSWORD_ALPHABET.length())));
}
return sb.toString();
}
private static String key(String accountId, String clusterId, String dbUser) {
return accountId + ":" + clusterId + ":" + dbUser;
}
}
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Optional;
/**
* Derives the Redshift Data API DbUser name for GetClusterCredentialsWithIAM from
* the caller's IAM identity: an IAM user becomes "IAM:<name>", an assumed role
* becomes "IAMR:<role>". When the caller cannot be resolved (for example a bare
* test key with no registered identity) the call still succeeds with a fixed
* fallback so local and CI flows are not blocked.
*/
@ApplicationScoped
public class RedshiftIamDbUserResolver {
private static final Logger LOG = Logger.getLogger(RedshiftIamDbUserResolver.class);
private static final String FALLBACK_DB_USER = "IAMR:floci";
private final IamService iamService;
private final AccountResolver accountResolver;
@Inject
public RedshiftIamDbUserResolver(IamService iamService, AccountResolver accountResolver) {
this.iamService = iamService;
this.accountResolver = accountResolver;
}
public String resolveDbUser(String authorizationHeader) {
String accessKeyId = accountResolver.extractAccessKeyId(authorizationHeader);
Optional<String> arn = iamService.resolveCallerArn(accessKeyId);
if (arn.isEmpty()) {
LOG.warnv("GetClusterCredentialsWithIAM caller could not be resolved; using {0}", FALLBACK_DB_USER);
return FALLBACK_DB_USER;
}
String resource = arn.get().substring(arn.get().lastIndexOf(':') + 1);
if (resource.startsWith("assumed-role/")) {
String[] parts = resource.split("/");
return parts.length >= 2 ? "IAMR:" + parts[1] : FALLBACK_DB_USER;
}
if (resource.startsWith("user/")) {
// Drop any IAM path prefix (user/team/alice -> alice), matching how AWS names the DbUser.
return "IAM:" + resource.substring(resource.lastIndexOf('/') + 1);
}
LOG.warnv("GetClusterCredentialsWithIAM caller ARN {0} is not a user or role; using {1}",
arn.get(), FALLBACK_DB_USER);
return FALLBACK_DB_USER;
}
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
@@ -12,7 +14,9 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
@@ -22,14 +26,35 @@ import java.util.regex.Pattern;
@ApplicationScoped
public class RedshiftQueryHandler {
private static final Logger LOG = Logger.getLogger(RedshiftQueryHandler.class);
// GetClusterCredentials DurationSeconds bounds, inclusive (AWS: 900 to 3600).
private static final int MIN_CREDENTIAL_DURATION_SECONDS = 900;
private static final int MAX_CREDENTIAL_DURATION_SECONDS = 3600;
private final RedshiftService service;
private final RedshiftCredentialBroker credentialBroker;
private final EmulatorConfig config;
private final RedshiftIamDbUserResolver iamDbUserResolver;
private final RegionResolver regionResolver;
@Inject
public RedshiftQueryHandler(RedshiftService service) {
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) {
this.service = service;
this.credentialBroker = credentialBroker;
this.config = config;
this.iamDbUserResolver = iamDbUserResolver;
this.regionResolver = regionResolver;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
return handle(action, params, null);
}
public Response handle(String action, MultivaluedMap<String, String> params, String authorizationHeader) {
switch (action) {
case "CreateCluster" -> {
String identifier = params.getFirst("ClusterIdentifier");
@@ -414,10 +439,102 @@ public class RedshiftQueryHandler {
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "GetClusterCredentials" -> {
String clusterId = requireParam(params, "ClusterIdentifier");
String dbUser = requireParam(params, "DbUser");
// describeClusters throws ClusterNotFound (404) for an unknown id.
service.describeClusters(clusterId);
// AWS prefixes the returned name IAMA: when AutoCreate is true, IAM: when it is false.
boolean autoCreate = Boolean.parseBoolean(params.getFirst("AutoCreate"));
String effectiveDbUser = (autoCreate ? "IAMA:" : "IAM:") + dbUser;
int duration = resolveDurationSeconds(params);
List<String> dbGroups = memberList(params, "DbGroups");
TempCredential credential = credentialBroker.issue(
regionResolver.getAccountId(), clusterId, effectiveDbUser, dbGroups, duration);
return Response.ok(getClusterCredentialsXml("GetClusterCredentials", credential))
.type(MediaType.APPLICATION_XML).build();
}
case "GetClusterCredentialsWithIAM" -> {
String clusterId = requireParam(params, "ClusterIdentifier");
service.describeClusters(clusterId);
String dbUser = iamDbUserResolver.resolveDbUser(authorizationHeader);
int duration = resolveDurationSeconds(params);
List<String> dbGroups = memberList(params, "DbGroups");
TempCredential credential = credentialBroker.issue(
regionResolver.getAccountId(), clusterId, dbUser, dbGroups, duration);
return Response.ok(getClusterCredentialsXml("GetClusterCredentialsWithIAM", credential))
.type(MediaType.APPLICATION_XML).build();
}
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
}
}
private static String requireParam(MultivaluedMap<String, String> params, String name) {
String value = params.getFirst(name);
if (value == null || value.isBlank()) {
throw new AwsException("InvalidParameterValue", name + " is required", 400);
}
return value;
}
private int resolveDurationSeconds(MultivaluedMap<String, String> params) {
String raw = params.getFirst("DurationSeconds");
if (raw == null || raw.isBlank()) {
return defaultDurationSeconds();
}
int duration;
try {
duration = Integer.parseInt(raw);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", "DurationSeconds must be an integer", 400);
}
if (duration < MIN_CREDENTIAL_DURATION_SECONDS || duration > MAX_CREDENTIAL_DURATION_SECONDS) {
throw new AwsException("InvalidParameterValue",
"DurationSeconds must be between " + MIN_CREDENTIAL_DURATION_SECONDS
+ " and " + MAX_CREDENTIAL_DURATION_SECONDS, 400);
}
return duration;
}
// The YAML default is operator-supplied, so hold it to the same AWS bounds as a request
// value: an out-of-range override falls back to the AWS minimum rather than minting a
// credential that is already expired or outlives the documented range.
private int defaultDurationSeconds() {
int configured = config.services().redshift().defaultCredentialDurationSeconds();
if (configured < MIN_CREDENTIAL_DURATION_SECONDS || configured > MAX_CREDENTIAL_DURATION_SECONDS) {
LOG.warnv("floci.services.redshift.default-credential-duration-seconds={0} is outside the "
+ "AWS range {1} to {2}; using {1}", configured,
MIN_CREDENTIAL_DURATION_SECONDS, MAX_CREDENTIAL_DURATION_SECONDS);
return MIN_CREDENTIAL_DURATION_SECONDS;
}
return configured;
}
private String getClusterCredentialsXml(String operation, TempCredential credential) {
XmlBuilder builder = new XmlBuilder()
.start(operation + "Response")
.start(operation + "Result")
.elem("DbUser", credential.dbUser())
.elem("DbPassword", credential.password())
.elem("Expiration", DateTimeFormatter.ISO_INSTANT.format(credential.expiresAt()));
if (!credential.dbGroups().isEmpty()) {
builder.start("DbGroups");
for (String group : credential.dbGroups()) {
builder.elem("DbGroup", group);
}
builder.end("DbGroups");
}
return builder
.end(operation + "Result")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end(operation + "Response")
.build();
}
private String buildClusterXml(Cluster cluster) {
XmlBuilder builder = new XmlBuilder()
.start("Cluster")
@@ -549,6 +666,7 @@ public class RedshiftQueryHandler {
case "SubnetIds" -> quoted + "(\\.member|\\.SubnetIdentifier)?\\.\\d+";
case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+";
case "TagKeys" -> quoted + "(\\.member|\\.TagKey)?\\.\\d+";
case "DbGroups" -> quoted + "(\\.member|\\.DbGroup)?\\.\\d+";
default -> quoted + "(\\.member)?\\.\\d+";
};
}
@@ -6,7 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
@@ -51,13 +51,15 @@ public class RedshiftService {
private final RegionResolver regionResolver;
private final RedshiftProxyManager proxyManager;
private final DockerHostResolver dockerHostResolver;
private final RedshiftCredentialBroker credentialBroker;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
@Inject
public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
EmulatorConfig config, RegionResolver regionResolver,
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver) {
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver,
RedshiftCredentialBroker credentialBroker) {
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
@@ -67,6 +69,7 @@ public class RedshiftService {
this.regionResolver = regionResolver;
this.proxyManager = proxyManager;
this.dockerHostResolver = dockerHostResolver;
this.credentialBroker = credentialBroker;
}
// Recreate Docker containers for persisted clusters on app restart (across every account, not just default)
@@ -133,6 +136,9 @@ public class RedshiftService {
if (clusters.get(identifier).isPresent()) {
throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400);
}
// A previous cluster with this identifier may have been deleted without its temp
// credentials being cleared; drop them so the new cluster starts with none.
credentialBroker.revokeCluster(clusters.accountId(), identifier);
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(identifier);
@@ -168,6 +174,7 @@ public class RedshiftService {
try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); }
if (proxyStopped) {
clusters.delete(identifier);
credentialBroker.revokeCluster(clusters.accountId(), identifier);
} else {
cluster.setClusterStatus("failed");
clusters.put(identifier, cluster);
@@ -179,6 +186,7 @@ public class RedshiftService {
try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); }
if (proxyStopped) {
clusters.delete(identifier);
credentialBroker.revokeCluster(clusters.accountId(), identifier);
} else {
cluster.setClusterStatus("failed");
clusters.put(identifier, cluster);
@@ -220,7 +228,10 @@ public class RedshiftService {
containerManager.stop(clusters.accountId(), identifier);
clusters.delete(identifier);
clusters.flush();
// Invalidate any GetClusterCredentials passwords so a cluster later recreated with this
// identifier does not accept them as master-equivalent.
credentialBroker.revokeCluster(clusters.accountId(), identifier);
cluster.setClusterStatus("deleting");
return cluster;
}
@@ -936,11 +947,40 @@ public class RedshiftService {
return accountId + ":" + clusterIdentifier;
}
// Validates the master password at the proxy against current cluster state, so a
// ModifyCluster password change is reflected for new connections without a proxy restart.
private RdsAuthProxy.PasswordValidator passwordValidatorFor(String accountId, String clusterIdentifier) {
return (user, password) -> clusters.getForAccount(accountId, clusterIdentifier)
.map(c -> user.equals(c.getMasterUsername()) && password.equals(c.getMasterPassword()))
.orElse(false);
// Classifies a proxy login against current cluster state: the master pair and any live
// GetClusterCredentials credential both run the backend leg as the cluster master, a known
// broker user with a stale password is rejected, everyone else passes through to the backend.
// Reading cluster state per call means a ModifyCluster password change takes effect for new
// connections without a proxy restart.
private PasswordValidator passwordValidatorFor(String accountId, String clusterIdentifier) {
return (user, password) -> {
Optional<Cluster> cluster = clusters.getForAccount(accountId, clusterIdentifier);
if (cluster.isEmpty()) {
// No cluster row to validate against: vouch for nothing. Falling through to the
// broker would classify an unknown user as PASSTHROUGH, and the wire proxy reads
// isMaster from its own start-time config, so a PASSTHROUGH there still opens the
// backend as master, authenticating any password for the master username.
return PasswordValidator.AuthResult.REJECT;
}
Cluster c = cluster.get();
if (user.equals(c.getMasterUsername())) {
// The master username is authoritative here: a wrong password must be rejected,
// never handed to the broker (which only knows minted DbUsers) and never passed
// through as if the user were unknown.
return password.equals(c.getMasterPassword())
? PasswordValidator.AuthResult.MASTER_EQUIVALENT
: PasswordValidator.AuthResult.REJECT;
}
return switch (credentialBroker.classify(accountId, clusterIdentifier, user, password)) {
case MASTER_EQUIVALENT -> PasswordValidator.AuthResult.MASTER_EQUIVALENT;
case REJECT -> PasswordValidator.AuthResult.REJECT;
case PASSTHROUGH -> PasswordValidator.AuthResult.PASSTHROUGH;
};
};
}
// Package-private hook for tests: passwordValidatorFor is otherwise private.
PasswordValidator passwordValidatorForTesting(String accountId, String clusterIdentifier) {
return passwordValidatorFor(accountId, clusterIdentifier);
}
}
@@ -0,0 +1,7 @@
package io.github.hectorvent.floci.services.redshift;
import java.time.Instant;
import java.util.List;
public record TempCredential(String dbUser, String password, Instant expiresAt, List<String> dbGroups) {
}
@@ -1,7 +1,7 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -32,7 +32,7 @@ public class RedshiftAuthProxy {
private final String dbName;
private final RdsSigV4Validator sigV4;
private final RdsProxyTlsCertificates tlsCertificates;
private final RdsAuthProxy.PasswordValidator passwordValidator;
private final PasswordValidator passwordValidator;
private final S3Service s3Service;
private volatile boolean running;
@@ -41,7 +41,7 @@ public class RedshiftAuthProxy {
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
RdsAuthProxy.PasswordValidator passwordValidator,
PasswordValidator passwordValidator,
S3Service s3Service) {
this.clusterKey = clusterKey;
this.backendHost = backendHost;
@@ -145,7 +145,7 @@ public class RedshiftAuthProxy {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
false, sigV4, tlsCertificates, passwordValidator::validate);
false, sigV4, tlsCertificates, passwordValidator);
if (session != null) {
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
@@ -1,6 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -46,7 +46,7 @@ public class RedshiftProxyManager {
public synchronized void startProxy(String relayKey, int proxyPort,
String backendHost, int backendPort, String advertisedHost,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
PasswordValidator passwordValidator) {
// A prior unclosable entry for this key is left in place: its listener may still
// be bound, and only a successful stop (never a fresh start) may drop it.
// Make sure the self-signed proxy certificate covers the host clients will connect to,
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -20,14 +22,20 @@ class RedshiftDataResourceResolver {
private final RedshiftService redshiftService;
private final SecretsManagerService secretsManagerService;
private final ObjectMapper objectMapper;
private final RedshiftCredentialBroker credentialBroker;
private final RegionResolver regionResolver;
@Inject
RedshiftDataResourceResolver(RedshiftService redshiftService,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
RedshiftCredentialBroker credentialBroker,
RegionResolver regionResolver) {
this.redshiftService = redshiftService;
this.secretsManagerService = secretsManagerService;
this.objectMapper = objectMapper;
this.credentialBroker = credentialBroker;
this.regionResolver = regionResolver;
}
DatabaseTarget resolve(JsonNode request, String region) {
@@ -71,11 +79,19 @@ class RedshiftDataResourceResolver {
String clusterId = requiredText(request, "ClusterIdentifier");
String dbUser = requiredText(request, "DbUser");
Cluster cluster = cluster(clusterId);
if (!dbUser.equals(cluster.getMasterUsername())) {
throw validation("DbUser " + dbUser + " is not the cluster master; create it first or use "
+ "GetClusterCredentials (not yet emulated).");
if (dbUser.equals(cluster.getMasterUsername())) {
return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword());
}
return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword());
boolean liveCredential = credentialBroker
.resolve(regionResolver.getAccountId(), clusterId, dbUser)
.isPresent();
if (liveCredential) {
// The minted DbUser is nominal: connect as the cluster master.
return target(clusterArn(clusterId, null), cluster, database,
cluster.getMasterUsername(), cluster.getMasterPassword());
}
throw validation("DbUser " + dbUser + " has no active credentials; call GetClusterCredentials first.");
}
private Cluster cluster(String clusterId) {