feat: deliver Redshift audit logs to CloudWatch Logs (#6432)

* feat: deliver Redshift audit logs to CloudWatch Logs

* fix: correct Redshift audit logging and account isolation

* docs: remove Redshift audit logging design document

* fix: reject transaction control in Redshift Data API batches

* fix: track Redshift batch audit changes through savepoints

* fix(redshift-data): guard explicit batch commits against cancellation

* fix(redshift): preserve audit regions and redact ambiguous passwords
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-25 07:42:48 -04:00
1 parent 8f3a6eafeb
commit b15bc708fa
25 files changed
+2014 -52

No files matched your search

@@ -31,6 +31,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
/**
* Handles the PostgreSQL wire protocol auth intercept.
@@ -140,6 +141,19 @@ public class PostgresProtocolHandler {
int handshakeTimeoutMillis, boolean forwardStartupParameters,
boolean databaseIamAuthentication) throws IOException {
return authenticate(client, backendConnector, masterUsername, masterPassword, dbName, iamEnabled, sigV4,
binding, tlsCertificates, passwordValidator, handshakeTimeoutMillis, forwardStartupParameters,
databaseIamAuthentication, (user, database) -> { });
}
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,
BiConsumer<String, String> startupObserver) throws IOException {
client.setSoTimeout(handshakeTimeoutMillis);
// Phase 1: Read client startup message (possibly preceded by SSL request)
@@ -151,6 +165,7 @@ public class PostgresProtocolHandler {
}
client = startup.socket();
String clientUsername = startup.username();
startupObserver.accept(clientUsername, resolveEffectiveDbName(startup.database(), dbName));
InputStream clientIn = client.getInputStream();
// PgBouncer rejects partial login packets; keep the challenge together until flush().
// https://github.com/pgbouncer/pgbouncer/blob/pgbouncer_1_24_0/src/server.c#L116-L119
@@ -0,0 +1,245 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@ApplicationScoped
public class RedshiftAuditLogPublisher {
private static final Logger LOG = Logger.getLogger(RedshiftAuditLogPublisher.class);
private static final Set<String> LOG_TYPES = Set.of("connectionlog", "userlog", "useractivitylog");
private static final Map<String, List<String>> LOG_COLUMNS = Map.of(
"connectionlog", List.of("event", "recordtime", "remotehost", "remoteport", "pid", "dbname",
"username", "authmethod", "duration", "sslversion", "sslcipher", "mtu", "sslcompression",
"sslexpansion", "iamauthguid", "application_name", "os_version", "driver_version",
"plugin_name", "protocol_version", "sessionid", "compression"),
"userlog", List.of("userid", "username", "oldusername", "action", "usecreatedb", "usesuper",
"usecatupd", "valuntil", "pid", "xid", "recordtime"),
"useractivitylog", List.of("recordtime", "db", "user", "pid", "userid", "xid", "query"));
private final CloudWatchLogsService logs;
private final Clock clock;
private final Map<String, Registration> registrations = new ConcurrentHashMap<>();
private record Registration(String region, String identifier, boolean enabled, String destination,
List<String> exports, boolean activityLoggingEnabled) { }
@Inject
public RedshiftAuditLogPublisher(CloudWatchLogsService logs) {
this(logs, Clock.systemUTC());
}
RedshiftAuditLogPublisher(CloudWatchLogsService logs, Clock clock) {
this.logs = logs;
this.clock = clock;
}
public void register(String accountId, String region, Cluster cluster) {
registrations.put(registryKey(accountId, cluster.getClusterIdentifier()), new Registration(region,
cluster.getClusterIdentifier(), cluster.isLoggingEnabled(), cluster.getLoggingDestinationType(),
cluster.getLoggingExports() == null ? null : List.copyOf(cluster.getLoggingExports()),
cluster.isUserActivityLoggingEnabled()));
}
public void unregister(String accountId, String clusterIdentifier) {
registrations.remove(registryKey(accountId, clusterIdentifier));
}
public void publishRegistered(String accountId, String clusterIdentifier, String logType,
Map<String, Object> record) {
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
if (registration == null) {
return;
}
Cluster cluster = registeredCluster(registration);
publish(cluster, accountId, registration.region(), logType, record);
}
public void publishRegisteredActivity(String accountId, String clusterIdentifier, String database,
String username, String sql) {
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
if (registration == null) {
return;
}
Cluster cluster = registeredCluster(registration);
publishActivity(cluster, accountId, registration.region(), database, username, sql);
}
public void publishRegisteredUserChange(String accountId, String clusterIdentifier, String database,
String username, String action, String oldUsername) {
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
if (registration == null) {
return;
}
Cluster cluster = registeredCluster(registration);
publishUserChange(cluster, accountId, registration.region(), database, username, action, oldUsername);
}
private static Cluster registeredCluster(Registration registration) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(registration.identifier());
cluster.setLoggingEnabled(registration.enabled());
cluster.setLoggingDestinationType(registration.destination());
cluster.setLoggingExports(registration.exports());
cluster.setUserActivityLoggingEnabled(registration.activityLoggingEnabled());
return cluster;
}
private static String registryKey(String accountId, String clusterIdentifier) {
return accountId + ":" + clusterIdentifier;
}
public void publishActivity(Cluster cluster, String accountId, String region, String database, String username,
String sql) {
Map<String, Object> record = new LinkedHashMap<>();
record.put("recordtime", Instant.ofEpochMilli(clock.millis()).toString());
record.put("db", database);
record.put("user", username);
record.put("query", "LOG: " + sanitizeSql(sql));
publish(cluster, accountId, region, "useractivitylog", record);
}
public void publishConnection(Cluster cluster, String accountId, String region, String database, String username,
String event, String remoteAddress, String error) {
publish(cluster, accountId, region, "connectionlog",
connectionRecord(database, username, event, remoteAddress, null, error));
}
public void publishRegisteredConnection(String accountId, String clusterIdentifier, String database, String username,
String event, String remoteAddress, int remotePort) {
publishRegistered(accountId, clusterIdentifier, "connectionlog",
connectionRecord(database, username, event, remoteAddress, remotePort, null));
}
private Map<String, Object> connectionRecord(String database, String username, String event, String remoteAddress,
Integer remotePort, String error) {
Map<String, Object> record = new LinkedHashMap<>();
record.put("recordtime", Instant.ofEpochMilli(clock.millis()).toString());
record.put("dbname", database);
record.put("username", username);
record.put("event", event);
record.put("remotehost", remoteAddress);
record.put("authmethod", "password");
record.put("remoteport", remotePort);
record.put("pid", "");
record.put("duration", "");
record.put("sslversion", "");
record.put("sslcipher", "");
record.put("mtu", "");
record.put("sslcompression", "");
record.put("sslexpansion", "");
record.put("iamauthguid", "");
record.put("application_name", "");
record.put("os_version", "");
record.put("driver_version", "");
record.put("plugin_name", "");
record.put("protocol_version", "");
record.put("sessionid", "");
record.put("compression", "");
if (error != null) {
record.put("event", "authentication failure");
}
return record;
}
public void publishUserChange(Cluster cluster, String accountId, String region, String database,
String username, String action, String oldUsername) {
Map<String, Object> record = new LinkedHashMap<>();
record.put("recordtime", Instant.ofEpochMilli(clock.millis()).toString());
record.put("userid", "");
record.put("db", database);
record.put("username", username);
record.put("oldusername", oldUsername == null ? "" : oldUsername);
record.put("action", action);
record.put("usecreatedb", "");
record.put("usesuper", "");
record.put("usecatupd", "");
record.put("valuntil", "");
record.put("pid", "");
record.put("xid", "");
publish(cluster, accountId, region, "userlog", record);
}
public void publish(Cluster cluster, String accountId, String region, String logType,
Map<String, Object> record) {
if (cluster == null || !cluster.isLoggingEnabled()
|| !"cloudwatch".equalsIgnoreCase(cluster.getLoggingDestinationType())
|| "useractivitylog".equals(logType) && !cluster.isUserActivityLoggingEnabled()
|| !LOG_TYPES.contains(logType) || !exports(cluster.getLoggingExports()).contains(logType)) {
return;
}
String group = "/aws/redshift/cluster/" + cluster.getClusterIdentifier() + "/" + logType;
String stream = cluster.getClusterIdentifier();
try {
createIfMissing(accountId, region, group, stream);
Map<String, Object> event = Map.of(
"timestamp", clock.millis(),
"message", csvLine(logType, record));
logs.putLogEventsForAccount(accountId, group, stream, List.of(event), region);
} catch (RuntimeException exception) {
LOG.warnv(exception, "Failed to publish Redshift {0} audit event for cluster {1}",
logType, cluster.getClusterIdentifier());
}
}
private void createIfMissing(String accountId, String region, String group, String stream) {
try {
logs.createLogGroupForAccount(accountId, group, null, Map.of(), region);
} catch (RuntimeException exception) {
if (!alreadyExists(exception)) {
throw exception;
}
}
try {
logs.createLogStreamForAccount(accountId, group, stream, region);
} catch (RuntimeException exception) {
if (!alreadyExists(exception)) {
throw exception;
}
}
}
private static Set<String> exports(List<String> configured) {
return configured == null ? LOG_TYPES : Set.copyOf(configured);
}
private static boolean alreadyExists(RuntimeException exception) {
return exception instanceof AwsException awsException
&& "ResourceAlreadyExistsException".equals(awsException.getErrorCode());
}
private static String csvLine(String logType, Map<String, Object> record) {
return LOG_COLUMNS.get(logType).stream()
.map(column -> csvValue(record.get(column)))
.collect(Collectors.joining(","));
}
private static String csvValue(Object value) {
if (value == null) {
return "";
}
String text = value.toString();
if (text.indexOf(',') >= 0 || text.indexOf('"') >= 0 || text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0) {
return "\"" + text.replace("\"", "\"\"") + "\"";
}
return text;
}
static String sanitizeSql(String sql) {
return RedshiftAuditSql.sanitize(sql);
}
}
@@ -0,0 +1,335 @@
package io.github.hectorvent.floci.services.redshift;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/** SQL inspection for audit records, preserving quoted text and skipping nested comments. */
public final class RedshiftAuditSql {
private RedshiftAuditSql() { }
public record UserChange(String username, String action, String oldUsername) { }
public record Savepoint(String operation, String name) { }
public static final class UserChanges {
private final List<UserChange> pending = new ArrayList<>();
private final List<UserChange> committed = new ArrayList<>();
private final ArrayDeque<Checkpoint> savepoints = new ArrayDeque<>();
private record Checkpoint(String name, int count) { }
public void complete(String sql) {
List<Token> tokens = tokens(sql);
String command = !tokens.isEmpty() && tokens.getFirst().kind() == Kind.WORD
? tokens.getFirst().text() : "";
complete(sql, command);
}
public void complete(String sql, String commandTag) {
Savepoint savepoint = savepoint(sql);
if (savepoint != null) {
completeSavepoint(savepoint);
return;
}
if ("COMMIT".equalsIgnoreCase(commandTag) || "END".equalsIgnoreCase(commandTag)) {
commit();
} else if ("ROLLBACK".equalsIgnoreCase(commandTag) || "ABORT".equalsIgnoreCase(commandTag)) {
rollback();
} else {
pending.addAll(userChanges(sql));
}
}
public void commit() {
committed.addAll(pending);
rollback();
}
public void rollback() {
pending.clear();
savepoints.clear();
}
public List<UserChange> drainCommitted() {
List<UserChange> changes = List.copyOf(committed);
committed.clear();
return changes;
}
private void completeSavepoint(Savepoint savepoint) {
if ("SAVEPOINT".equals(savepoint.operation())) {
savepoints.addLast(new Checkpoint(savepoint.name(), pending.size()));
return;
}
while (!savepoints.isEmpty()) {
Checkpoint checkpoint = savepoints.peekLast();
if (checkpoint.name().equals(savepoint.name())) {
if ("ROLLBACK".equals(savepoint.operation())) {
pending.subList(checkpoint.count(), pending.size()).clear();
} else {
savepoints.removeLast();
}
return;
}
savepoints.removeLast();
}
}
}
private enum Kind { WORD, IDENTIFIER, STRING, SYMBOL }
private record Token(String text, int start, int end, Kind kind) {
boolean keyword(String keyword) {
return kind == Kind.WORD && keyword.equalsIgnoreCase(text);
}
String identifier() {
return kind == Kind.IDENTIFIER
? text.substring(1, text.length() - 1).replace("\"\"", "\"") : text.toLowerCase(Locale.ROOT);
}
}
private record Redaction(int start, int end) { }
public static String sanitize(String sql) {
List<Redaction> redactions = new ArrayList<>();
collectPasswordRedactions(sql, tokens(sql), redactions);
collectPasswordRedactions(sql, tokens(sql, true), redactions);
redactions.sort(Comparator.comparingInt(Redaction::start));
StringBuilder sanitized = new StringBuilder(sql.length());
int copied = 0;
for (Redaction redaction : redactions) {
if (redaction.start() >= copied) {
sanitized.append(sql, copied, redaction.start()).append("'[REDACTED]'");
}
copied = Math.max(copied, redaction.end());
}
return sanitized.append(sql, copied, sql.length()).toString();
}
private static void collectPasswordRedactions(String sql, List<Token> tokens, List<Redaction> redactions) {
for (int i = 0; i + 1 < tokens.size(); i++) {
if (!tokens.get(i).keyword("PASSWORD")) {
continue;
}
Token value = tokens.get(++i);
if (value.kind() == Kind.SYMBOL) {
continue;
}
int end = value.end();
boolean uncertainBoundary = ambiguousPasswordString(value);
// PostgreSQL concatenates string literals separated by a newline, including comments.
while (value.kind() == Kind.STRING && i + 1 < tokens.size() && tokens.get(i + 1).kind() == Kind.STRING) {
Token continuation = tokens.get(++i);
end = continuation.end();
uncertainBoundary |= ambiguousPasswordString(continuation);
}
// A session may disable standard_conforming_strings, making the remaining password boundary uncertain.
redactions.add(new Redaction(value.start(), uncertainBoundary ? sql.length() : end));
}
}
private static boolean ambiguousPasswordString(Token token) {
String text = token.text();
return token.kind() == Kind.STRING && text.indexOf('\\') >= 0
&& (text.startsWith("'") || text.regionMatches(true, 0, "N'", 0, 2));
}
public static List<String> statements(String sql) {
List<String> statements = new ArrayList<>();
int start = 0;
boolean hasContent = false;
for (Token token : tokens(sql)) {
if (token.kind() == Kind.SYMBOL && ";".equals(token.text())) {
if (hasContent) {
statements.add(sql.substring(start, token.start()));
}
start = token.end();
hasContent = false;
} else {
hasContent = true;
}
}
if (hasContent) {
statements.add(sql.substring(start));
}
return statements;
}
public static boolean isCommit(String sql) {
List<Token> tokens = tokens(sql);
return !tokens.isEmpty() && (tokens.getFirst().keyword("COMMIT") || tokens.getFirst().keyword("END"));
}
public static List<UserChange> userChanges(String sql) {
List<Token> tokens = tokens(sql);
if (tokens.size() < 3 || !tokens.get(1).keyword("USER")) {
return List.of();
}
Token command = tokens.getFirst();
String action = command.keyword("CREATE") ? "Create"
: command.keyword("ALTER") ? "Alter" : command.keyword("DROP") ? "Drop" : null;
if (action == null) {
return List.of();
}
int name = 2;
if (tokens.get(name).keyword("IF")) {
name++;
if (name < tokens.size() && tokens.get(name).keyword("NOT")) {
name++;
}
if (name >= tokens.size() || !tokens.get(name++).keyword("EXISTS")) {
return List.of();
}
}
if (name >= tokens.size()) {
return List.of();
}
String username = tokens.get(name).identifier();
if ("Alter".equals(action) && name + 3 < tokens.size()
&& tokens.get(name + 1).keyword("RENAME") && tokens.get(name + 2).keyword("TO")) {
return List.of(new UserChange(tokens.get(name + 3).identifier(), "Rename", username));
}
List<UserChange> changes = new ArrayList<>();
changes.add(new UserChange(username, action, null));
if ("Drop".equals(action)) {
for (int i = name + 1; i + 1 < tokens.size() && ",".equals(tokens.get(i).text()); i += 2) {
changes.add(new UserChange(tokens.get(i + 1).identifier(), action, null));
}
}
return changes;
}
public static Savepoint savepoint(String sql) {
List<Token> tokens = tokens(sql);
if (tokens.size() < 2) {
return null;
}
int name = 1;
String operation;
if (tokens.getFirst().keyword("SAVEPOINT")) {
operation = "SAVEPOINT";
} else if (tokens.getFirst().keyword("RELEASE")) {
operation = "RELEASE";
if (tokens.get(name).keyword("SAVEPOINT")) {
name++;
}
} else if (tokens.getFirst().keyword("ROLLBACK")) {
operation = "ROLLBACK";
if (tokens.get(name).keyword("WORK") || tokens.get(name).keyword("TRANSACTION")) {
name++;
}
if (name >= tokens.size() || !tokens.get(name++).keyword("TO")) {
return null;
}
if (name < tokens.size() && tokens.get(name).keyword("SAVEPOINT")) {
name++;
}
} else {
return null;
}
return name < tokens.size() ? new Savepoint(operation, tokens.get(name).identifier()) : null;
}
private static List<Token> tokens(String sql) {
return tokens(sql, false);
}
private static List<Token> tokens(String sql, boolean ordinaryStringEscapes) {
List<Token> tokens = new ArrayList<>();
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (Character.isWhitespace(c)) {
i++;
} else if (sql.startsWith("--", i)) {
while (i < sql.length() && sql.charAt(i) != '\n' && sql.charAt(i) != '\r') {
i++;
}
} else if (sql.startsWith("/*", i)) {
i = skipComment(sql, i);
} else {
int start = i;
Kind kind;
if ("eEnNbBxX".indexOf(c) >= 0 && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
i = skipQuoted(sql, i + 1, '\'', c == 'e' || c == 'E'
|| ordinaryStringEscapes && (c == 'n' || c == 'N'));
kind = Kind.STRING;
} else if ((c == 'u' || c == 'U') && sql.startsWith("&'", i + 1)) {
i = skipQuoted(sql, i + 2, '\'', false);
kind = Kind.STRING;
} else if (c == '\'' || c == '"') {
i = skipQuoted(sql, i, c, c == '\'' && ordinaryStringEscapes);
kind = c == '\'' ? Kind.STRING : Kind.IDENTIFIER;
} else if (c == '$' && dollarDelimiter(sql, i) != null) {
String delimiter = dollarDelimiter(sql, i);
int end = sql.indexOf(delimiter, i + delimiter.length());
i = end < 0 ? sql.length() : end + delimiter.length();
kind = Kind.STRING;
} else if (Character.isLetterOrDigit(c) || c == '_') {
i++;
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i))
|| sql.charAt(i) == '_' || sql.charAt(i) == '$')) {
i++;
}
kind = Kind.WORD;
} else {
i++;
kind = Kind.SYMBOL;
}
tokens.add(new Token(sql.substring(start, i), start, i, kind));
}
}
return tokens;
}
private static int skipComment(String sql, int start) {
int depth = 1;
int i = start + 2;
while (i < sql.length() && depth > 0) {
if (sql.startsWith("/*", i)) {
depth++;
i += 2;
} else if (sql.startsWith("*/", i)) {
depth--;
i += 2;
} else {
i++;
}
}
return i;
}
private static int skipQuoted(String sql, int start, char quote, boolean escapes) {
int i = start + 1;
while (i < sql.length()) {
char c = sql.charAt(i++);
if (escapes && c == '\\' && i < sql.length()) {
i++;
} else if (c == quote) {
if (i >= sql.length() || sql.charAt(i) != quote) {
return i;
}
i++;
}
}
return i;
}
private static String dollarDelimiter(String sql, int start) {
int i = start + 1;
if (i < sql.length() && sql.charAt(i) == '$') {
return "$$";
}
if (i >= sql.length() || !(Character.isLetter(sql.charAt(i)) || sql.charAt(i) == '_')) {
return null;
}
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
i++;
}
return i < sql.length() && sql.charAt(i) == '$' ? sql.substring(start, i + 1) : null;
}
}
@@ -91,6 +91,7 @@ public class RedshiftService {
private final SecretsManagerService secretsManagerService;
private final ObjectMapper objectMapper;
private final DynamoDbStreamReader streamReader;
private final RedshiftAuditLogPublisher auditLogPublisher;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
@@ -133,7 +134,7 @@ public class RedshiftService {
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver,
RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader) {
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher) {
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>>() {});
@@ -150,6 +151,16 @@ public class RedshiftService {
this.secretsManagerService = secretsManagerService;
this.objectMapper = objectMapper;
this.streamReader = streamReader;
this.auditLogPublisher = auditLogPublisher;
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager,
DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, objectMapper, streamReader, null);
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -168,6 +179,7 @@ public class RedshiftService {
.toList();
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : availableClusters) {
Cluster cluster = entry.value();
registerAuditLogging(entry.accountId(), cluster);
if (containerManager.getContainer(entry.accountId(), cluster.getClusterIdentifier()).isPresent()) {
continue;
}
@@ -263,6 +275,7 @@ public class RedshiftService {
cluster.setDefaultIamRoleArn(defaultRole);
// A group named at create time is applied afterwards via modifyCluster.
cluster.setClusterParameterGroupName(DEFAULT_PARAMETER_GROUP_NAME);
cluster.setUserActivityLoggingEnabled(userActivityLoggingEnabled(DEFAULT_PARAMETER_GROUP_NAME));
cluster.setClusterStatus("creating");
clusters.put(identifier, cluster);
clusters.flush();
@@ -737,6 +750,9 @@ public class RedshiftService {
proxyManager.forgetSpectrumRuntime(relayKey(clusters.accountId(), identifier));
clusters.delete(identifier);
clusters.flush();
if (auditLogPublisher != null) {
auditLogPublisher.unregister(clusters.accountId(), identifier);
}
// Invalidate any GetClusterCredentials passwords so a cluster later recreated with this
// identifier does not accept them as master-equivalent.
credentialBroker.revokeCluster(clusters.accountId(), identifier);
@@ -794,6 +810,7 @@ public class RedshiftService {
}
if (clusterParameterGroupName != null && !clusterParameterGroupName.isBlank()) {
cluster.setClusterParameterGroupName(clusterParameterGroupName);
cluster.setUserActivityLoggingEnabled(userActivityLoggingEnabled(clusterParameterGroupName));
}
if (vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty()) {
cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds);
@@ -804,6 +821,7 @@ public class RedshiftService {
clusters.put(clusterIdentifier, cluster);
clusters.flush();
registerAuditLogging(clusters.accountId(), cluster);
return cluster;
}
@@ -841,6 +859,7 @@ public class RedshiftService {
proxyManager.updateIamRoles(relayKey(clusters.accountId(), clusterIdentifier), cluster.getIamRoleArns(), defaultRole);
clusters.put(clusterIdentifier, cluster);
clusters.flush();
registerAuditLogging(clusters.accountId(), cluster);
return cluster;
}
@@ -931,12 +950,14 @@ public class RedshiftService {
cluster.setLoggingEnabled(true);
cluster.setLoggingBucketName(bucketName);
cluster.setLoggingDestinationType(logDestinationType);
cluster.setLoggingRegion(regionResolver.getRegion());
cluster.setLoggingExports(logExports == null || logExports.isEmpty() ? null : List.copyOf(logExports));
cluster.setLoggingS3KeyPrefix(s3KeyPrefix);
cluster.setLoggingS3TableKmsKeyId(s3TableKmsKeyId);
cluster.setLoggingS3TableGranularity(s3TableGranularity);
clusters.put(clusterIdentifier, cluster);
clusters.flush();
registerAuditLogging(clusters.accountId(), cluster);
return cluster;
}
@@ -951,11 +972,13 @@ public class RedshiftService {
cluster.setLoggingBucketName(null);
cluster.setLoggingS3KeyPrefix(null);
cluster.setLoggingDestinationType(null);
cluster.setLoggingRegion(null);
cluster.setLoggingExports(null);
cluster.setLoggingS3TableKmsKeyId(null);
cluster.setLoggingS3TableGranularity(null);
clusters.put(clusterIdentifier, cluster);
clusters.flush();
registerAuditLogging(clusters.accountId(), cluster);
return cluster;
}
@@ -1305,6 +1328,7 @@ public class RedshiftService {
cluster.setMasterUsername(username);
cluster.setMasterPassword(password);
cluster.setClusterParameterGroupName(DEFAULT_PARAMETER_GROUP_NAME);
cluster.setUserActivityLoggingEnabled(userActivityLoggingEnabled(DEFAULT_PARAMETER_GROUP_NAME));
cluster.setClusterStatus("creating");
storeCluster(cluster);
@@ -1431,9 +1455,25 @@ public class RedshiftService {
group.setParameters(current);
parameterGroups.put(parameterGroupName, group);
parameterGroups.flush();
refreshClustersForActivityParameter(parameterGroupName, group);
return group;
}
private boolean userActivityLoggingEnabled(String parameterGroupName) {
ClusterParameterGroup group = parameterGroups.get(parameterGroupName)
.or(() -> DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName)
? Optional.of(defaultParameterGroup()) : Optional.empty())
.orElse(null);
return group != null && userActivityLoggingEnabled(group);
}
private static boolean userActivityLoggingEnabled(ClusterParameterGroup group) {
return group.getParameters().stream()
.filter(parameter -> "enable_user_activity_logging".equalsIgnoreCase(parameter.getParameterName()))
.map(Parameter::getParameterValue)
.anyMatch(value -> Boolean.parseBoolean(value));
}
public synchronized void resetClusterParameterGroup(String parameterGroupName, boolean resetAllParameters,
List<String> parameterNames) {
requireMutableParameterGroup(parameterGroupName);
@@ -1475,6 +1515,27 @@ public class RedshiftService {
group.setParameters(reset);
parameterGroups.put(parameterGroupName, group);
parameterGroups.flush();
refreshClustersForActivityParameter(parameterGroupName, group);
}
private void refreshClustersForActivityParameter(String parameterGroupName, ClusterParameterGroup group) {
boolean enabled = userActivityLoggingEnabled(group);
String accountId = clusters.accountId();
List<Cluster> affected = clusters.scan(key -> true).stream()
.filter(cluster -> parameterGroupName.equals(cluster.getClusterParameterGroupName())).toList();
for (Cluster cluster : affected) {
cluster.setUserActivityLoggingEnabled(enabled);
clusters.putForAccount(accountId, cluster.getClusterIdentifier(), cluster);
registerAuditLogging(accountId, cluster);
}
clusters.flush();
}
private void registerAuditLogging(String accountId, Cluster cluster) {
if (auditLogPublisher != null) {
String region = cluster.getLoggingRegion() != null ? cluster.getLoggingRegion() : regionResolver.getRegion();
auditLogPublisher.register(accountId, region, cluster);
}
}
private void requireMutableParameterGroup(String name) {
@@ -50,7 +50,7 @@ public class Cluster {
public String getDefaultIamRoleArn() { return defaultIamRoleArn; }
public void setDefaultIamRoleArn(String defaultIamRoleArn) { this.defaultIamRoleArn = defaultIamRoleArn; }
// Audit logging config as set by EnableLogging; no log delivery is emulated.
// Audit logging configuration set by EnableLogging.
private boolean loggingEnabled = false;
private String loggingBucketName;
private String loggingS3KeyPrefix;
@@ -63,14 +63,22 @@ public class Cluster {
public void setLoggingS3KeyPrefix(String loggingS3KeyPrefix) { this.loggingS3KeyPrefix = loggingS3KeyPrefix; }
private String loggingDestinationType;
private String loggingRegion;
private List<String> loggingExports;
private boolean userActivityLoggingEnabled;
private String loggingS3TableKmsKeyId;
private String loggingS3TableGranularity;
public String getLoggingDestinationType() { return loggingDestinationType; }
public void setLoggingDestinationType(String loggingDestinationType) { this.loggingDestinationType = loggingDestinationType; }
public String getLoggingRegion() { return loggingRegion; }
public void setLoggingRegion(String loggingRegion) { this.loggingRegion = loggingRegion; }
public List<String> getLoggingExports() { return loggingExports; }
public void setLoggingExports(List<String> loggingExports) { this.loggingExports = loggingExports; }
public boolean isUserActivityLoggingEnabled() { return userActivityLoggingEnabled; }
public void setUserActivityLoggingEnabled(boolean userActivityLoggingEnabled) {
this.userActivityLoggingEnabled = userActivityLoggingEnabled;
}
public String getLoggingS3TableKmsKeyId() { return loggingS3TableKmsKeyId; }
public void setLoggingS3TableKmsKeyId(String loggingS3TableKmsKeyId) { this.loggingS3TableKmsKeyId = loggingS3TableKmsKeyId; }
public String getLoggingS3TableGranularity() { return loggingS3TableGranularity; }
@@ -55,6 +55,7 @@ public class ClusterParameterGroup {
public static List<Parameter> defaultParameters() {
List<Parameter> defaults = new ArrayList<>(List.of(
new Parameter("max_cursor_result_set_size", "0", "Maximum cursor result set size", "integer"),
new Parameter("enable_user_activity_logging", "false", "Enable user activity audit logging", "boolean"),
new Parameter("wlm_json_configuration", "{}", "WLM configuration", "string")
));
defaults.forEach(parameter -> parameter.setSource("engine-default"));
@@ -7,6 +7,7 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
final class BackendResponseCoordinator {
@@ -25,6 +26,10 @@ final class BackendResponseCoordinator {
}
Ticket register(Operation operation, ExtendedQuerySession.Mutation mutation) {
return register(operation, mutation, null);
}
Ticket register(Operation operation, ExtendedQuerySession.Mutation mutation, BiConsumer<Character, byte[]> response) {
lock.lock();
try {
Ticket ticket = new Ticket(nextSequence++, operation);
@@ -36,7 +41,7 @@ final class BackendResponseCoordinator {
resolvedGates.put(ticket.sequence(), GateResult.SKIPPED_AFTER_ERROR);
}
} else {
pending.addLast(new PendingOperation(ticket, mutation));
pending.addLast(new PendingOperation(ticket, mutation, response));
}
changed.signalAll();
return ticket;
@@ -124,6 +129,9 @@ final class BackendResponseCoordinator {
}
Operation operation = head.ticket().operation();
if (head.response() != null) {
head.response().accept(type, body);
}
if (type == 'E') {
if (operation != Operation.SIMPLE_QUERY) {
pending.removeFirst();
@@ -316,6 +324,7 @@ final class BackendResponseCoordinator {
record Ticket(long sequence, Operation operation) {
}
private record PendingOperation(Ticket ticket, ExtendedQuerySession.Mutation mutation) {
private record PendingOperation(Ticket ticket, ExtendedQuerySession.Mutation mutation,
BiConsumer<Character, byte[]> response) {
}
}
@@ -11,25 +11,29 @@ import java.util.Set;
final class ExtendedQuerySession {
private final Map<String, CopyStatementParser.S3Statement> statements = new LinkedHashMap<>();
private final Map<String, PreparedSql> statements = new LinkedHashMap<>();
private final Map<String, String> portals = new LinkedHashMap<>();
private final List<JournalEntry> journal = new ArrayList<>();
private long nextMutationId = 1;
synchronized Mutation stageParse(String statementName, CopyStatementParser.S3Statement statement) {
Map<String, CopyStatementParser.S3Statement> statementsBefore = new LinkedHashMap<>(statements);
return stageParse(statementName, statement, null);
}
synchronized Mutation stageParse(String statementName, CopyStatementParser.S3Statement statement, String sql) {
Map<String, PreparedSql> statementsBefore = new LinkedHashMap<>(statements);
Map<String, String> portalsBefore = new LinkedHashMap<>(portals);
if (statement == null) {
if (statement == null && sql == null) {
statements.remove(statementName);
} else {
statements.put(statementName, statement);
statements.put(statementName, new PreparedSql(statement, sql));
}
portals.entrySet().removeIf(entry -> entry.getValue().equals(statementName));
return record(statementsBefore, portalsBefore);
}
synchronized Mutation stageBind(String portalName, String statementName) {
Map<String, CopyStatementParser.S3Statement> statementsBefore = new LinkedHashMap<>(statements);
Map<String, PreparedSql> statementsBefore = new LinkedHashMap<>(statements);
Map<String, String> portalsBefore = new LinkedHashMap<>(portals);
if (statements.containsKey(statementName)) {
portals.put(portalName, statementName);
@@ -44,7 +48,7 @@ final class ExtendedQuerySession {
throw new IllegalArgumentException("Close target type must be S or P");
}
Map<String, CopyStatementParser.S3Statement> statementsBefore = new LinkedHashMap<>(statements);
Map<String, PreparedSql> statementsBefore = new LinkedHashMap<>(statements);
Map<String, String> portalsBefore = new LinkedHashMap<>(portals);
if (targetType == 'S') {
statements.remove(name);
@@ -118,12 +122,16 @@ final class ExtendedQuerySession {
}
synchronized Optional<CopyStatementParser.S3Statement> statement(String statementName) {
return Optional.ofNullable(statements.get(statementName));
return Optional.ofNullable(statements.get(statementName)).map(PreparedSql::statement);
}
synchronized Optional<CopyStatementParser.S3Statement> portal(String portalName) {
String statementName = portals.get(portalName);
return Optional.ofNullable(statementName).map(statements::get);
return Optional.ofNullable(statementName).map(statements::get).map(PreparedSql::statement);
}
synchronized Optional<String> portalSql(String portalName) {
return Optional.ofNullable(portals.get(portalName)).map(statements::get).map(PreparedSql::sql);
}
synchronized void clearPortals() {
@@ -160,7 +168,7 @@ final class ExtendedQuerySession {
* entry's "before" or the live maps, keeps it a fixed historical fact: those two proxies go
* stale once an earlier {@link #rejectFrom} has already run its own cascading portal cleanup.
*/
private Mutation record(Map<String, CopyStatementParser.S3Statement> statementsBefore,
private Mutation record(Map<String, PreparedSql> statementsBefore,
Map<String, String> portalsBefore) {
Mutation mutation = new Mutation(nextMutationId++);
journal.add(new JournalEntry(
@@ -181,11 +189,13 @@ final class ExtendedQuerySession {
record Mutation(long id) {
}
private record PreparedSql(CopyStatementParser.S3Statement statement, String sql) { }
private record JournalEntry(
Mutation mutation,
Map<String, CopyStatementParser.S3Statement> statementsBefore,
Map<String, PreparedSql> statementsBefore,
Map<String, String> portalsBefore,
Map<String, CopyStatementParser.S3Statement> statementsAfter,
Map<String, PreparedSql> statementsAfter,
Map<String, String> portalsAfter) {
}
}
@@ -5,6 +5,7 @@ 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.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.jboss.logging.Logger;
@@ -40,6 +41,7 @@ public class RedshiftAuthProxy {
private final S3Service s3Service;
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final String clusterAccountId;
private volatile RoleConfiguration roleConfiguration;
@@ -91,6 +93,21 @@ public class RedshiftAuthProxy {
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, SpectrumInterceptor spectrumInterceptor) {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor, 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) {
this.clusterKey = clusterKey;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -103,6 +120,7 @@ public class RedshiftAuthProxy {
this.s3Service = s3Service;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.auditLogPublisher = auditLogPublisher;
this.clusterAccountId = clusterAccountId;
this.roleConfiguration = new RoleConfiguration(iamRoleArns, null);
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
@@ -217,12 +235,19 @@ public class RedshiftAuthProxy {
private void handleConnection(Socket client) {
PostgresProtocolHandler.AuthenticatedSession session = null;
LoginAttempt login = new LoginAttempt();
try {
client.setTcpNoDelay(true);
PostgresProtocolHandler.BackendConnector connector = () -> {
Socket backendSocket = new Socket();
backendSocket.connect(new InetSocketAddress(backendHost, backendPort),
backendConnectTimeoutMillis);
try {
backendSocket.connect(new InetSocketAddress(backendHost, backendPort),
backendConnectTimeoutMillis);
} catch (IOException failure) {
login.backendUnavailable = true;
closeQuietly(backendSocket);
throw failure;
}
backendSocket.setTcpNoDelay(true);
return backendSocket;
};
@@ -231,17 +256,25 @@ public class RedshiftAuthProxy {
session = PostgresProtocolHandler.authenticate(
client, connector, masterUsername, masterPassword, dbName,
false, sigV4, null, tlsCertificates, passwordValidator,
handshakeTimeoutMillis);
handshakeTimeoutMillis, false, true, (user, database) -> {
login.username = user;
login.database = database;
});
if (session != null) {
publishConnection(client, login, "authenticated");
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
RoleConfiguration roles = roleConfiguration;
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, roles.iamRoleArns(), spectrumInterceptor, clusterKey, dbName,
roles.defaultIamRoleArn()).run();
clusterAccountId, roles.iamRoleArns(), spectrumInterceptor, clusterKey, login.database,
roles.defaultIamRoleArn(), auditLogPublisher, login.username).run();
publishConnection(client, login, "disconnection");
} else {
publishConnection(client, login, login.backendUnavailable ? "connection_error" : "authentication failure");
}
} catch (Exception e) {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
publishConnection(client, login, "connection_error");
} finally {
// 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
@@ -256,6 +289,22 @@ public class RedshiftAuthProxy {
}
}
private static final class LoginAttempt {
private String username;
private String database;
private boolean backendUnavailable;
}
private void publishConnection(Socket client, LoginAttempt login, String event) {
if (auditLogPublisher == null || login.username == null) {
return;
}
String remoteAddress = client.getInetAddress() == null ? null : client.getInetAddress().getHostAddress();
String clusterIdentifier = clusterKey.substring(clusterKey.indexOf(':') + 1);
auditLogPublisher.publishRegisteredConnection(clusterAccountId, clusterIdentifier, login.database, login.username,
event, remoteAddress, client.getPort());
}
private static void closeQuietly(Socket s) {
if (s == null) {
return;
@@ -1,6 +1,10 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import io.github.hectorvent.floci.services.redshift.spectrum.PostgresExtendedBackendSession;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumColumn;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
@@ -18,6 +22,7 @@ import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@@ -26,6 +31,7 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
/**
* Replaces the transparent {@code bridge()} for Redshift connections so SQL in Simple and Extended
@@ -65,6 +71,9 @@ public class RedshiftInterceptingBridge {
private final SpectrumInterceptor spectrumInterceptor;
private final String clusterKey;
private final String databaseName;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final String databaseUser;
private final UserChanges auditUserChanges = new UserChanges();
private final PostgresExtendedBackendSession relationalBackend;
private final Map<String, PostgresWireDecoder.ParseMessage> relationalStatements = new HashMap<>();
private final ExtendedQuerySession session = new ExtendedQuerySession();
@@ -78,6 +87,7 @@ public class RedshiftInterceptingBridge {
private volatile boolean pumpFinished = false;
private boolean extendedSpectrumError;
private boolean rolledBackInCycle;
private boolean auditCycleFailed;
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) {
this(client, backend, s3Service, iamService, null);
@@ -105,6 +115,23 @@ public class RedshiftInterceptingBridge {
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
clusterKey, databaseName, defaultIamRoleArn, null, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher,
String databaseUser) {
this.client = client;
this.backend = backend;
this.s3Service = s3Service;
@@ -115,6 +142,8 @@ public class RedshiftInterceptingBridge {
this.spectrumInterceptor = spectrumInterceptor;
this.clusterKey = clusterKey;
this.databaseName = databaseName;
this.auditLogPublisher = auditLogPublisher;
this.databaseUser = databaseUser;
this.relationalBackend = new PostgresExtendedBackendSession(backend);
}
@@ -209,6 +238,7 @@ public class RedshiftInterceptingBridge {
private void handleSimpleQuery(PostgresWireDecoder.FrontendMessage message, OutputStream backendOut)
throws IOException {
String sql = message.getSql();
publishActivity(sql);
if (spectrumInterceptor != null) {
SpectrumInterceptor.Decision[] decision = new SpectrumInterceptor.Decision[1];
boolean intercepted;
@@ -268,7 +298,7 @@ public class RedshiftInterceptingBridge {
} catch (RuntimeException e) {
LOG.warnv("RedshiftSqlInterceptor failed, forwarding original query: {0}", e.getMessage());
}
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null, auditResponses(sql));
write(backendOut, packet);
}
@@ -288,6 +318,7 @@ public class RedshiftInterceptingBridge {
|| plan instanceof SpectrumInterceptor.Plan.ExternalDdl) {
awaitPriorBackendResponses();
spectrumStatements.put(parse.statementName(), plan);
session.confirm(session.stageParse(parse.statementName(), null, parse.sql()));
write(client.getOutputStream(), backendFrame('1', EMPTY_BODY));
return;
}
@@ -319,7 +350,7 @@ public class RedshiftInterceptingBridge {
}
CopyStatementParser.S3Statement statement = parse.parameterTypeOids().isEmpty()
? parseS3Statement(parse.sql()) : null;
ExtendedQuerySession.Mutation mutation = session.stageParse(parse.statementName(), statement);
ExtendedQuerySession.Mutation mutation = session.stageParse(parse.statementName(), statement, parse.sql());
coordinator.register(BackendResponseCoordinator.Operation.PARSE, mutation);
String rewritten = parse.sql();
@@ -364,6 +395,7 @@ public class RedshiftInterceptingBridge {
if (spectrumPlan != null) {
awaitPriorBackendResponses();
spectrumPortals.put(bind.portalName(), spectrumPlan);
session.confirm(session.stageBind(bind.portalName(), bind.statementName()));
write(client.getOutputStream(), backendFrame('2', EMPTY_BODY));
return;
}
@@ -442,6 +474,10 @@ public class RedshiftInterceptingBridge {
private void handleExecute(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.ExecuteMessage execute = decoder.decodeExecute(message);
String auditSql = session.portalSql(execute.portalName()).orElse(null);
if (auditSql != null) {
publishActivity(auditSql);
}
SpectrumInterceptor.Plan spectrumPlan = spectrumPortals.get(execute.portalName());
if (spectrumPlan != null) {
BackendResponseCoordinator.Ticket ticket = coordinator.register(
@@ -450,7 +486,8 @@ public class RedshiftInterceptingBridge {
return;
}
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
BackendResponseCoordinator.Operation.EXECUTE, null,
auditSql == null ? null : auditResponses(auditSql));
CopyStatementParser.S3Statement statement = session.portal(execute.portalName()).orElse(null);
if (statement == null) {
write(backendOut, message.toPacketBytes());
@@ -543,6 +580,7 @@ public class RedshiftInterceptingBridge {
// (they are synthesized locally, see handleParse/handleBind), so the backend has never
// heard of this name either: forwarding Close would draw a spurious "does not exist" error.
awaitPriorBackendResponses();
session.confirm(session.stageClose(close.targetType(), close.name()));
write(client.getOutputStream(), backendFrame('3', EMPTY_BODY));
return;
}
@@ -825,9 +863,13 @@ public class RedshiftInterceptingBridge {
if (type == 'E') {
relationalBackend.onBackendError();
}
if (type == 'E') {
auditCycleFailed = true;
}
coordinator.onBackendFrame(type, body);
if (type == 'Z') {
relationalBackend.onSync();
completeUserChanges(body);
}
});
try {
@@ -865,6 +907,54 @@ public class RedshiftInterceptingBridge {
}
}
private void publishActivity(String sql) {
if (auditLogPublisher == null) {
return;
}
auditLogPublisher.publishRegisteredActivity(clusterAccountId, clusterIdentifier(), databaseName,
databaseUser, sql);
}
private BiConsumer<Character, byte[]> auditResponses(String sql) {
ArrayDeque<String> commands = new ArrayDeque<>(RedshiftAuditSql.statements(sql));
return (type, body) -> {
if (type != 'C' || auditLogPublisher == null) {
return;
}
String command = commands.pollFirst();
if (command == null) {
return;
}
String tag = new String(body, StandardCharsets.UTF_8).replace("\0", "");
auditUserChanges.complete(command, tag);
publishCompletedUserChanges();
};
}
private void completeUserChanges(byte[] readyStatus) {
if (readyStatus.length > 0 && readyStatus[0] == 'I') {
if (auditCycleFailed) {
auditUserChanges.rollback();
} else {
auditUserChanges.commit();
}
publishCompletedUserChanges();
}
auditCycleFailed = false;
}
private void publishCompletedUserChanges() {
for (UserChange change : auditUserChanges.drainCommitted()) {
auditLogPublisher.publishRegisteredUserChange(clusterAccountId, clusterIdentifier(), databaseName,
change.username(), change.action(), change.oldUsername());
}
}
private String clusterIdentifier() {
int separator = clusterKey.indexOf(':');
return separator < 0 ? clusterKey : clusterKey.substring(separator + 1);
}
private void closeQuietly(Socket socket, String which) {
try {
if (socket != null && !socket.isClosed()) {
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.iam.IamService;
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.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.runtime.ShutdownEvent;
@@ -33,6 +34,7 @@ public class RedshiftProxyManager {
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final EmulatorConfig config;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
/**
* Proxies whose listener could not be closed during a failed start or replace. The
@@ -47,16 +49,24 @@ public class RedshiftProxyManager {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor) {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor,
RedshiftAuditLogPublisher auditLogPublisher) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
this.s3Service = s3Service;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.config = config;
this.auditLogPublisher = auditLogPublisher;
}
public synchronized void startProxy(String relayKey, int proxyPort,
@@ -94,7 +104,7 @@ public class RedshiftProxyManager {
clusterAccountId,
iamRoleArns,
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
redshiftConfig.proxyMaxConnections(), spectrumInterceptor);
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher);
proxy.updateIamRoles(iamRoleArns, defaultIamRoleArn);
try {
proxy.start(proxyPort);
@@ -54,7 +54,7 @@ class RedshiftDataResourceResolver {
if (hasText(request, "SecretArn")) {
return resolveViaSecret(request, region, database);
}
return resolveViaDbUser(request, database);
return resolveViaDbUser(request, region, database);
}
/**
@@ -117,21 +117,23 @@ class RedshiftDataResourceResolver {
return target(clusterArn(clusterId, region), cluster, database, creds.username(), creds.password());
}
private DatabaseTarget resolveViaDbUser(JsonNode request, String database) {
private DatabaseTarget resolveViaDbUser(JsonNode request, String region, String database) {
String clusterId = requiredText(request, "ClusterIdentifier");
String dbUser = requiredText(request, "DbUser");
Cluster cluster = cluster(clusterId);
if (dbUser.equals(cluster.getMasterUsername())) {
return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword());
return target(clusterArn(clusterId, region), 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,
DatabaseTarget backend = target(clusterArn(clusterId, region), cluster, database,
cluster.getMasterUsername(), cluster.getMasterPassword());
return new DatabaseTarget(backend.arn(), backend.host(), backend.port(), backend.database(), backend.user(),
backend.password(), backend.spectrum(), cluster, dbUser);
}
throw validation("DbUser " + dbUser + " has no active credentials; call GetClusterCredentials first.");
}
@@ -153,7 +155,7 @@ class RedshiftDataResourceResolver {
String accountId = AwsArnUtils.parse(arn).accountId();
SpectrumSession spectrum = new SpectrumSession(accountId, accountId + ":" + cluster.getClusterIdentifier(),
database, cluster.getIamRoleArns(), false);
return new DatabaseTarget(arn, host, port, database, user, password, spectrum);
return new DatabaseTarget(arn, host, port, database, user, password, spectrum, cluster);
}
private String clusterArn(String clusterId, String region) {
@@ -184,9 +186,18 @@ class RedshiftDataResourceResolver {
}
record DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum) {
SpectrumSession spectrum, Cluster cluster, String auditUser) {
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster) {
this(arn, host, port, database, user, password, spectrum, cluster, user);
}
DatabaseTarget(String arn, String host, int port, String database, String user, String password) {
this(arn, host, port, database, user, password, null);
this(arn, host, port, database, user, password, null, null);
}
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum) {
this(arn, host, port, database, user, password, spectrum, null);
}
}
@@ -11,6 +11,10 @@ import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
@@ -65,6 +69,7 @@ public class RedshiftDataService implements Resettable {
private final SpectrumQueryPreparation preparation;
private final RedshiftDataExecutor executor;
private final RedshiftDataEventPublisher publisher;
private final RedshiftAuditLogPublisher auditLogPublisher;
private final RequestContext requestContext;
private final IamService iamService;
private final RedshiftDataIdempotencyStore idempotency;
@@ -76,7 +81,16 @@ public class RedshiftDataService implements Resettable {
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher) {
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher, null,
null, new RedshiftDataIdempotencyStore(AccountAwareStorageBackend.inMemory("000000000000"),
Clock.systemUTC()));
Clock.systemUTC()), new RedshiftDataSessions(), null);
}
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency,
RedshiftDataSessions sessions) {
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher, requestContext,
iamService, idempotency, sessions, null);
}
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
@@ -84,7 +98,7 @@ public class RedshiftDataService implements Resettable {
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency) {
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher,
requestContext, iamService, idempotency, new RedshiftDataSessions());
requestContext, iamService, idempotency, new RedshiftDataSessions(), null);
}
@Inject
@@ -92,7 +106,7 @@ public class RedshiftDataService implements Resettable {
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency,
RedshiftDataSessions sessions) {
RedshiftDataSessions sessions, RedshiftAuditLogPublisher auditLogPublisher) {
this.resolver = resolver;
this.connectionFactory = connectionFactory;
this.store = store;
@@ -100,6 +114,7 @@ public class RedshiftDataService implements Resettable {
this.preparation = preparation;
this.executor = executor;
this.publisher = publisher;
this.auditLogPublisher = auditLogPublisher;
this.requestContext = requestContext;
this.iamService = iamService;
this.idempotency = idempotency;
@@ -406,14 +421,41 @@ public class RedshiftDataService implements Resettable {
private ConnectionUse connection(RedshiftDataResourceResolver.DatabaseTarget target,
RedshiftDataSessions.Reservation session) throws SQLException {
return new ConnectionUse(session == null ? connectionFactory.open(target) : session.connection(connectionFactory), session);
Runnable disconnected = () -> publishConnection(target, "disconnection", null);
try {
Connection connection;
if (session == null) {
connection = connectionFactory.open(target);
publishConnection(target, "authenticated", null);
} else {
connection = session.connection(connectionFactory,
() -> publishConnection(target, "authenticated", null), disconnected);
}
return new ConnectionUse(connection, session, disconnected);
} catch (SQLException failure) {
publishConnection(target, "authentication failure", failure.getSQLState());
throw failure;
}
}
private record ConnectionUse(Connection connection, RedshiftDataSessions.Reservation session) implements AutoCloseable {
private void publishConnection(RedshiftDataResourceResolver.DatabaseTarget target, String event, String error) {
if (auditLogPublisher != null && target.cluster() != null) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(target.arn());
auditLogPublisher.publishConnection(target.cluster(), arn.accountId(), arn.region(), target.database(),
target.auditUser(), event, null, error);
}
}
private record ConnectionUse(Connection connection, RedshiftDataSessions.Reservation session,
Runnable disconnected) implements AutoCloseable {
@Override
public void close() throws SQLException {
if (session == null) {
connection.close();
try {
connection.close();
} finally {
disconnected.run();
}
return;
}
try {
@@ -443,7 +485,8 @@ public class RedshiftDataService implements Resettable {
Connection connection = use.connection();
execution.track(connection);
try {
if (session != null && transactionControl(stored, sql, connection, session, execution)) {
publishActivity(stored, target, sql);
if (session != null && transactionControl(stored, target, sql, connection, session, execution)) {
return;
}
if (session != null && session.transactionFailed()) {
@@ -458,6 +501,7 @@ public class RedshiftDataService implements Resettable {
}
execution.commit(() -> runOnConnection(stored, connection, sql, parameters,
target.spectrum(), execution, true));
successfulUserChange(stored, target, sql, session);
} else {
runOnConnection(stored, connection, sql, parameters, target.spectrum(), execution, false);
execution.commit(() -> {
@@ -465,6 +509,7 @@ public class RedshiftDataService implements Resettable {
connection.commit();
}
});
successfulUserChange(stored, target, sql, session);
}
} catch (SQLException failure) {
if (session != null && failure.getSQLState() != null && failure.getSQLState().startsWith("08")) {
@@ -490,7 +535,36 @@ public class RedshiftDataService implements Resettable {
stored.updatedAt = Instant.now();
}
private boolean transactionControl(RedshiftDataStatementStore.StoredStatement stored, String sql,
private void publishActivity(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target, String sql) {
if (auditLogPublisher != null && target.cluster() != null) {
auditLogPublisher.publishActivity(target.cluster(), stored.accountId, stored.region,
target.database(), target.auditUser(), sql);
}
}
private void successfulUserChange(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target, String sql,
RedshiftDataSessions.Reservation session) {
if (session != null && session.inTransaction()) {
session.completeUserChanges(sql);
} else {
publishUserChanges(stored, target, RedshiftAuditSql.userChanges(sql));
}
}
private void publishUserChanges(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target, List<UserChange> changes) {
if (auditLogPublisher != null && target.cluster() != null) {
for (UserChange change : changes) {
auditLogPublisher.publishUserChange(target.cluster(), stored.accountId, stored.region,
target.database(), change.username(), change.action(), change.oldUsername());
}
}
}
private boolean transactionControl(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target, String sql,
Connection connection, RedshiftDataSessions.Reservation session,
RedshiftDataExecution execution) throws SQLException {
String normalized = TRANSACTION_COMMENTS.matcher(sql).replaceAll(" ").trim();
@@ -512,6 +586,7 @@ public class RedshiftDataService implements Resettable {
session.transaction(true);
}
case "COMMIT", "END" -> {
boolean rolledBack = session.transactionFailed();
if (!connection.getAutoCommit()) {
if (session.transactionFailed()) {
connection.rollback();
@@ -519,6 +594,10 @@ public class RedshiftDataService implements Resettable {
connection.commit();
}
}
List<UserChange> changes = session.takeUserChanges();
if (!rolledBack) {
publishUserChanges(stored, target, changes);
}
session.transaction(false);
connection.setAutoCommit(true);
}
@@ -526,6 +605,7 @@ public class RedshiftDataService implements Resettable {
if (!connection.getAutoCommit()) {
connection.rollback();
}
session.takeUserChanges();
session.transaction(false);
connection.setAutoCommit(true);
}
@@ -827,6 +907,7 @@ public class RedshiftDataService implements Resettable {
Connection connection = use.connection();
execution.track(connection);
BackendSql batchBackend = new RedshiftDataBackendSql(connection, execution);
UserChanges userChanges = session == null ? new UserChanges() : session.takeUserChangeState();
boolean committed = false;
try {
connection.setAutoCommit(false);
@@ -847,7 +928,8 @@ public class RedshiftDataService implements Resettable {
sub.updatedAt = now;
try {
execution.checkCancellation();
runOnConnection(sub, connection, sqls.get(n), parameters, target.spectrum(), execution, false);
publishActivity(parent, target, sqls.get(n));
runBatchEntry(sub, connection, sqls.get(n), parameters, target.spectrum(), execution, userChanges);
} catch (SQLException e) {
sub.status = RedshiftDataStatementStore.Status.FAILED;
sub.error = e.getMessage();
@@ -862,6 +944,9 @@ public class RedshiftDataService implements Resettable {
throw e;
}
connection.rollback();
if (session != null) {
session.takeUserChanges();
}
failed = true;
break;
}
@@ -876,9 +961,17 @@ public class RedshiftDataService implements Resettable {
if (!failed) {
execution.commit(connection::commit);
committed = true;
userChanges.commit();
parent.status = RedshiftDataStatementStore.Status.FINISHED;
}
} finally {
if (!committed) {
userChanges.rollback();
}
publishUserChanges(parent, target, userChanges.drainCommitted());
if (!committed && session != null) {
session.takeUserChanges();
}
if (preparation != null) {
if (committed) {
preparation.finishCycle(batchBackend, true);
@@ -907,6 +1000,34 @@ public class RedshiftDataService implements Resettable {
parent.updatedAt = Instant.now();
}
private void runBatchEntry(RedshiftDataStatementStore.StoredStatement sub, Connection connection, String sql,
Map<String, String> parameters, SpectrumSession context,
RedshiftDataExecution execution, UserChanges userChanges)
throws SQLException {
List<String> commands = RedshiftAuditSql.statements(sql);
if (commands.isEmpty()) {
runOnConnection(sub, connection, sql, parameters, context, execution, false);
return;
}
long duration = 0;
for (int i = 0; i < commands.size(); i++) {
// JDBC exposes the first result of an entry; later commands still affect transaction audit state.
RedshiftDataStatementStore.StoredStatement result = i == 0 ? sub : new RedshiftDataStatementStore.StoredStatement();
try {
String command = commands.get(i);
if (RedshiftAuditSql.isCommit(command)) {
execution.commit(() -> runOnConnection(result, connection, command, parameters, context, execution, false));
} else {
runOnConnection(result, connection, command, parameters, context, execution, false);
}
userChanges.complete(command);
} finally {
duration += result.durationNanos;
sub.durationNanos = duration;
}
}
}
// ── ListStatements ─────────────────────────────────────────────────────
public ObjectNode listStatements(JsonNode request) {
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -177,14 +179,16 @@ class RedshiftDataSessions implements AutoCloseable {
}
session.closed = true;
sessions.remove(session.id, session);
Retirement retirement = new Retirement(session.id, session.connection, cancel ? session.execution : null);
Retirement retirement = new Retirement(session.id, session.connection, cancel ? session.execution : null,
session.connectionClosed);
session.active = null;
session.execution = null;
session.connection = null;
session.userChanges.rollback();
return retirement;
}
private record Retirement(String id, Connection connection, RedshiftDataExecution execution) { }
private record Retirement(String id, Connection connection, RedshiftDataExecution execution, Runnable connectionClosed) { }
private static void cleanUp(Retirement retirement) {
if (retirement == null) {
@@ -196,7 +200,13 @@ class RedshiftDataSessions implements AutoCloseable {
retirement.execution().cancel();
}
} finally {
closeConnection(retirement.connection(), retirement.id());
try {
closeConnection(retirement.connection(), retirement.id());
} finally {
if (retirement.connection() != null && retirement.connectionClosed() != null) {
retirement.connectionClosed().run();
}
}
}
};
if (retirement.execution() == null) {
@@ -277,6 +287,8 @@ class RedshiftDataSessions implements AutoCloseable {
private Connection connection;
private RedshiftDataExecution execution;
private Reservation active;
private Runnable connectionClosed;
private UserChanges userChanges = new UserChanges();
private Session(Scope owner, RedshiftDataResourceResolver.DatabaseTarget target, JsonNode request, Instant createdAt) {
this.owner = owner;
@@ -338,6 +350,10 @@ class RedshiftDataSessions implements AutoCloseable {
}
Connection connection(RedshiftDataConnectionFactory factory) throws SQLException {
return connection(factory, () -> { }, () -> { });
}
Connection connection(RedshiftDataConnectionFactory factory, Runnable openedAudit, Runnable closedAudit) throws SQLException {
synchronized (session) {
if (session.closed) {
throw new SQLException("Session has expired", "08003");
@@ -347,13 +363,19 @@ class RedshiftDataSessions implements AutoCloseable {
}
}
Connection opened = factory.open(session.target);
openedAudit.run();
synchronized (session) {
if (!session.closed && !expired(session)) {
session.connection = opened;
session.connectionClosed = closedAudit;
return opened;
}
}
closeConnection(opened, session.id);
try {
closeConnection(opened, session.id);
} finally {
closedAudit.run();
}
throw new SQLException("Session has expired", "08003");
}
@@ -376,6 +398,28 @@ class RedshiftDataSessions implements AutoCloseable {
session.transactionFailed = true;
}
void completeUserChanges(String sql) {
synchronized (session) {
if (!session.closed) {
session.userChanges.complete(sql);
}
}
}
List<UserChange> takeUserChanges() {
UserChanges changes = takeUserChangeState();
changes.commit();
return changes.drainCommitted();
}
UserChanges takeUserChangeState() {
synchronized (session) {
UserChanges changes = session.userChanges;
session.userChanges = new UserChanges();
return changes;
}
}
void abort() {
release(false);
}