mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(redshift): support audit logging to S3 (RS-14 / INT-08) (#7699)
This commit is contained in:
1 parent
9a88ebf830
commit
08be536e15
8 files changed
+1117
-73
No files matched your search
@@ -170,8 +170,8 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
|
||||
| `DescribeClusterVersions` | Return the single emulated engine version and its parameter group family |
|
||||
| `DescribeOrderableClusterOptions` | Return the static node types and cluster types, optionally filtered by `NodeType` or `ClusterVersion` |
|
||||
| `ModifyClusterIamRoles` | Add or remove associated IAM roles and set `DefaultIamRoleArn`; COPY and UNLOAD see the change on new connections |
|
||||
| `DescribeLoggingStatus` | Return a cluster's stored audit-logging configuration |
|
||||
| `EnableLogging` | Store audit-logging configuration and deliver the selected connection, user, and user-activity audit records to CloudWatch Logs for provisioned clusters |
|
||||
| `DescribeLoggingStatus` | Return a cluster's stored audit-logging configuration and delivery status |
|
||||
| `EnableLogging` | Store audit-logging configuration and deliver connection, user, and user-activity audit records to CloudWatch Logs or Amazon S3 for provisioned clusters |
|
||||
| `DisableLogging` | Clear a cluster's audit-logging configuration |
|
||||
| `PauseCluster` | Stop a provisioned cluster and its auth proxy while retaining the container and data |
|
||||
| `ResumeCluster` | Restart a paused cluster and restore its auth proxy on the same endpoint |
|
||||
@@ -180,7 +180,7 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
|
||||
| `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
CloudWatch audit events use the AWS log groups `/aws/redshift/cluster/<clusterIdentifier>/<logType>` and CSV log records. `connectionlog` and `userlog` follow the logging export selection. `useractivitylog` additionally requires `enable_user_activity_logging=true` in the cluster parameter group, which is false by default.
|
||||
CloudWatch audit events use the AWS log groups `/aws/redshift/cluster/<clusterIdentifier>/<logType>` and CSV log records. S3 audit events are compressed with gzip and delivered to `s3://<bucketName>/[<s3KeyPrefix>/]AWSLogs/<accountId>/redshift/<region>/<YYYY>/<MM>/<DD>/<accountId>_redshift_<region>_<clusterIdentifier>_<logType>_<timestamp>.gz` using pipe-delimited records for `connectionlog` and `userlog`, and standard formatted text for `useractivitylog`. `connectionlog` and `userlog` follow the logging export selection. `useractivitylog` additionally requires `enable_user_activity_logging=true` in the cluster parameter group, which is false by default.
|
||||
|
||||
Audit delivery covers PostgreSQL wire connections and Data API connections, including batch statements and retained sessions. Records identify the requested database user and database, even when temporary credentials use a master connection internally. User changes are published after commit and discarded on rollback, including rollback to a savepoint on the wire path. SQL password literals are redacted, including literals separated from `PASSWORD` by SQL comments.
|
||||
|
||||
|
||||
@@ -1,20 +1,35 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServiceCallAuthorizer;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
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;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftAuditLogPublisher {
|
||||
@@ -30,28 +45,67 @@ public class RedshiftAuditLogPublisher {
|
||||
"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());
|
||||
@FunctionalInterface
|
||||
public interface DeliveryStatusListener {
|
||||
void recordDeliveryOutcome(String accountId, String clusterIdentifier, long loggingGeneration,
|
||||
Instant timestamp, boolean success, String failureMessage);
|
||||
}
|
||||
|
||||
RedshiftAuditLogPublisher(CloudWatchLogsService logs, Clock clock) {
|
||||
private static final int STRIPE_COUNT = 64;
|
||||
private final CloudWatchLogsService logs;
|
||||
private final S3Service s3;
|
||||
private final ServiceCallAuthorizer authorizer;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Clock clock;
|
||||
private final Map<String, Registration> registrations = new ConcurrentHashMap<>();
|
||||
private final Object[] deliveryStripes = new Object[STRIPE_COUNT];
|
||||
private volatile DeliveryStatusListener statusListener;
|
||||
|
||||
{
|
||||
for (int i = 0; i < STRIPE_COUNT; i++) {
|
||||
deliveryStripes[i] = new Object();
|
||||
}
|
||||
}
|
||||
|
||||
private record Registration(String region, String identifier, boolean enabled, String destination,
|
||||
String bucketName, String s3KeyPrefix,
|
||||
List<String> exports, boolean activityLoggingEnabled,
|
||||
long loggingGeneration) { }
|
||||
|
||||
@Inject
|
||||
public RedshiftAuditLogPublisher(CloudWatchLogsService logs, S3Service s3,
|
||||
ServiceCallAuthorizer authorizer, RegionResolver regionResolver) {
|
||||
this(logs, s3, authorizer, regionResolver, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public RedshiftAuditLogPublisher(CloudWatchLogsService logs) {
|
||||
this(logs, null, null, null, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public RedshiftAuditLogPublisher(CloudWatchLogsService logs, Clock clock) {
|
||||
this(logs, null, null, null, clock);
|
||||
}
|
||||
|
||||
RedshiftAuditLogPublisher(CloudWatchLogsService logs, S3Service s3,
|
||||
ServiceCallAuthorizer authorizer, RegionResolver regionResolver, Clock clock) {
|
||||
this.logs = logs;
|
||||
this.s3 = s3;
|
||||
this.authorizer = authorizer;
|
||||
this.regionResolver = regionResolver;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public void setDeliveryStatusListener(DeliveryStatusListener statusListener) {
|
||||
this.statusListener = statusListener;
|
||||
}
|
||||
|
||||
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.getLoggingBucketName(), cluster.getLoggingS3KeyPrefix(),
|
||||
cluster.getLoggingExports() == null ? null : List.copyOf(cluster.getLoggingExports()),
|
||||
cluster.isUserActivityLoggingEnabled()));
|
||||
cluster.isUserActivityLoggingEnabled(),
|
||||
cluster.getLoggingGeneration()));
|
||||
}
|
||||
|
||||
public void unregister(String accountId, String clusterIdentifier) {
|
||||
@@ -60,32 +114,45 @@ public class RedshiftAuditLogPublisher {
|
||||
|
||||
public void publishRegistered(String accountId, String clusterIdentifier, String logType,
|
||||
Map<String, Object> record) {
|
||||
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
|
||||
if (registration == null) {
|
||||
return;
|
||||
try {
|
||||
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
|
||||
if (registration == null) {
|
||||
return;
|
||||
}
|
||||
Cluster cluster = registeredCluster(registration);
|
||||
publish(cluster, accountId, registration.region(), logType, record);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish registered Redshift {0} audit event for cluster {1}",
|
||||
logType, clusterIdentifier);
|
||||
}
|
||||
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;
|
||||
try {
|
||||
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
|
||||
if (registration == null) {
|
||||
return;
|
||||
}
|
||||
Cluster cluster = registeredCluster(registration);
|
||||
publishActivity(cluster, accountId, registration.region(), database, username, sql);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish registered Redshift activity audit event for cluster {0}", clusterIdentifier);
|
||||
}
|
||||
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;
|
||||
try {
|
||||
Registration registration = registrations.get(registryKey(accountId, clusterIdentifier));
|
||||
if (registration == null) {
|
||||
return;
|
||||
}
|
||||
Cluster cluster = registeredCluster(registration);
|
||||
publishUserChange(cluster, accountId, registration.region(), database, username, action, oldUsername);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish registered Redshift user change audit event for cluster {0}", clusterIdentifier);
|
||||
}
|
||||
Cluster cluster = registeredCluster(registration);
|
||||
publishUserChange(cluster, accountId, registration.region(), database, username, action, oldUsername);
|
||||
}
|
||||
|
||||
private static Cluster registeredCluster(Registration registration) {
|
||||
@@ -93,8 +160,11 @@ public class RedshiftAuditLogPublisher {
|
||||
cluster.setClusterIdentifier(registration.identifier());
|
||||
cluster.setLoggingEnabled(registration.enabled());
|
||||
cluster.setLoggingDestinationType(registration.destination());
|
||||
cluster.setLoggingBucketName(registration.bucketName());
|
||||
cluster.setLoggingS3KeyPrefix(registration.s3KeyPrefix());
|
||||
cluster.setLoggingExports(registration.exports());
|
||||
cluster.setUserActivityLoggingEnabled(registration.activityLoggingEnabled());
|
||||
cluster.setLoggingGeneration(registration.loggingGeneration());
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@@ -104,24 +174,38 @@ public class RedshiftAuditLogPublisher {
|
||||
|
||||
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);
|
||||
try {
|
||||
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);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish Redshift activity audit event for cluster {0}",
|
||||
cluster != null ? cluster.getClusterIdentifier() : "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
try {
|
||||
publish(cluster, accountId, region, "connectionlog",
|
||||
connectionRecord(database, username, event, remoteAddress, null, error));
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish Redshift connection audit event for cluster {0}",
|
||||
cluster != null ? cluster.getClusterIdentifier() : "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
try {
|
||||
publishRegistered(accountId, clusterIdentifier, "connectionlog",
|
||||
connectionRecord(database, username, event, remoteAddress, remotePort, null));
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish registered Redshift connection audit event for cluster {0}", clusterIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> connectionRecord(String database, String username, String event, String remoteAddress,
|
||||
@@ -157,31 +241,51 @@ public class RedshiftAuditLogPublisher {
|
||||
|
||||
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);
|
||||
try {
|
||||
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);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish Redshift user change audit event for cluster {0}",
|
||||
cluster != null ? cluster.getClusterIdentifier() : "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
try {
|
||||
if (cluster == null || !cluster.isLoggingEnabled()
|
||||
|| "useractivitylog".equals(logType) && !cluster.isUserActivityLoggingEnabled()
|
||||
|| !LOG_TYPES.contains(logType) || !exports(cluster.getLoggingExports()).contains(logType)) {
|
||||
return;
|
||||
}
|
||||
|
||||
String destination = cluster.getLoggingDestinationType();
|
||||
if ("cloudwatch".equalsIgnoreCase(destination)) {
|
||||
publishCloudWatch(cluster, accountId, region, logType, record);
|
||||
} else if ("s3".equalsIgnoreCase(destination)
|
||||
|| (destination == null && cluster.getLoggingBucketName() != null)) {
|
||||
publishS3(cluster, accountId, region, logType, record);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to publish Redshift audit event for cluster {0}",
|
||||
cluster != null ? cluster.getClusterIdentifier() : "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
private void publishCloudWatch(Cluster cluster, String accountId, String region, String logType,
|
||||
Map<String, Object> record) {
|
||||
String group = "/aws/redshift/cluster/" + cluster.getClusterIdentifier() + "/" + logType;
|
||||
String stream = cluster.getClusterIdentifier();
|
||||
try {
|
||||
@@ -196,6 +300,133 @@ public class RedshiftAuditLogPublisher {
|
||||
}
|
||||
}
|
||||
|
||||
public static String s3DeliveryKey(String s3KeyPrefix, String accountId, String region,
|
||||
String clusterIdentifier, String logType, Instant timestamp) {
|
||||
ZonedDateTime utc = timestamp.atZone(ZoneOffset.UTC);
|
||||
String year = String.format("%04d", utc.getYear());
|
||||
String month = String.format("%02d", utc.getMonthValue());
|
||||
String day = String.format("%02d", utc.getDayOfMonth());
|
||||
String timePart = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm").format(utc);
|
||||
String filename = accountId + "_redshift_" + region + "_" + clusterIdentifier
|
||||
+ "_" + logType + "_" + timePart + ".gz";
|
||||
String basePath = (s3KeyPrefix != null && !s3KeyPrefix.isBlank())
|
||||
? (s3KeyPrefix.endsWith("/") ? s3KeyPrefix : s3KeyPrefix + "/")
|
||||
: "";
|
||||
return basePath + "AWSLogs/" + accountId + "/redshift/" + region + "/" + year + "/" + month + "/" + day + "/" + filename;
|
||||
}
|
||||
|
||||
private void publishS3(Cluster cluster, String accountId, String region, String logType,
|
||||
Map<String, Object> record) {
|
||||
try {
|
||||
String bucket = cluster.getLoggingBucketName();
|
||||
if (bucket == null || bucket.isBlank() || s3 == null) {
|
||||
return;
|
||||
}
|
||||
Instant now = Instant.ofEpochMilli(clock.millis());
|
||||
String key = s3DeliveryKey(cluster.getLoggingS3KeyPrefix(), accountId, region,
|
||||
cluster.getClusterIdentifier(), logType, now);
|
||||
|
||||
String partition = regionResolver != null ? regionResolver.partitionForRegion(region) : AwsRegions.partitionFor(region);
|
||||
String objectArn = AwsArnUtils.Arn.global(partition, "s3", "", bucket + "/" + key).toString();
|
||||
String clusterArn = AwsArnUtils.Arn.of("redshift", region, accountId, "cluster:" + cluster.getClusterIdentifier()).toString();
|
||||
Map<String, List<String>> requestKeys = Map.of("aws:RequestedRegion", List.of(region));
|
||||
|
||||
if (authorizer != null && authorizer.authorize("redshift", "s3:PutObject", objectArn, clusterArn, accountId, requestKeys) != Decision.ALLOW) {
|
||||
String errorMsg = "Access Denied: The bucket policy does not allow Amazon Redshift to put objects.";
|
||||
LOG.warnv("Access Denied delivering Redshift audit log to s3://{0}/{1}", bucket, key);
|
||||
safeRecordOutcome(accountId, cluster.getClusterIdentifier(), cluster.getLoggingGeneration(), now, false, errorMsg);
|
||||
return;
|
||||
}
|
||||
|
||||
String line = formatS3Line(logType, record);
|
||||
byte[] newMember = compressGzipMember(line);
|
||||
int stripeIndex = Math.floorMod((bucket + "/" + key).hashCode(), STRIPE_COUNT);
|
||||
Object lock = deliveryStripes[stripeIndex];
|
||||
synchronized (lock) {
|
||||
try {
|
||||
byte[] gzipped = appendGzipMember(bucket, key, newMember);
|
||||
s3.putObject(bucket, key, gzipped, "application/x-gzip", Map.of());
|
||||
safeRecordOutcome(accountId, cluster.getClusterIdentifier(), cluster.getLoggingGeneration(), now, true, null);
|
||||
} catch (AwsException | IOException exception) {
|
||||
LOG.warnv(exception, "Failed to deliver Redshift {0} audit event to s3://{1}/{2} for cluster {3}",
|
||||
logType, bucket, key, cluster.getClusterIdentifier());
|
||||
String message = exception.getMessage() != null ? exception.getMessage() : "Failed to deliver log to S3";
|
||||
safeRecordOutcome(accountId, cluster.getClusterIdentifier(), cluster.getLoggingGeneration(), now, false, message);
|
||||
} catch (RuntimeException unexpected) {
|
||||
LOG.errorv(unexpected, "Unexpected runtime error delivering Redshift {0} audit event to s3://{1}/{2} for cluster {3}",
|
||||
logType, bucket, key, cluster.getClusterIdentifier());
|
||||
}
|
||||
}
|
||||
} catch (Exception unexpected) {
|
||||
LOG.errorv(unexpected, "Unexpected error delivering Redshift {0} audit event to S3 for cluster {1}",
|
||||
logType, cluster.getClusterIdentifier());
|
||||
}
|
||||
}
|
||||
|
||||
private void safeRecordOutcome(String accountId, String clusterIdentifier, long loggingGeneration,
|
||||
Instant timestamp, boolean success, String failureMessage) {
|
||||
DeliveryStatusListener listener = this.statusListener;
|
||||
if (listener != null) {
|
||||
try {
|
||||
listener.recordDeliveryOutcome(accountId, clusterIdentifier, loggingGeneration, timestamp, success, failureMessage);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Delivery status listener threw an exception for cluster {0}", clusterIdentifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] compressGzipMember(String newLine) throws IOException {
|
||||
ByteArrayOutputStream lineGz = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gos = new GZIPOutputStream(lineGz)) {
|
||||
gos.write(newLine.getBytes(StandardCharsets.UTF_8));
|
||||
gos.write('\n');
|
||||
}
|
||||
return lineGz.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] appendGzipMember(String bucket, String key, byte[] newMember) throws IOException {
|
||||
byte[] existingBytes = null;
|
||||
try {
|
||||
S3Object existingObj = s3.getObject(bucket, key);
|
||||
if (existingObj != null && existingObj.getData() != null && existingObj.getData().length > 0) {
|
||||
existingBytes = existingObj.getData();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
if (!"NoSuchKey".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
if (existingBytes == null || existingBytes.length == 0) {
|
||||
return newMember;
|
||||
}
|
||||
|
||||
byte[] combined = new byte[existingBytes.length + newMember.length];
|
||||
System.arraycopy(existingBytes, 0, combined, 0, existingBytes.length);
|
||||
System.arraycopy(newMember, 0, combined, existingBytes.length, newMember.length);
|
||||
return combined;
|
||||
}
|
||||
|
||||
private static String formatS3Line(String logType, Map<String, Object> record) {
|
||||
if ("useractivitylog".equals(logType)) {
|
||||
String recordTime = String.valueOf(record.getOrDefault("recordtime", ""));
|
||||
String db = String.valueOf(record.getOrDefault("db", ""));
|
||||
String user = String.valueOf(record.getOrDefault("user", ""));
|
||||
String pid = String.valueOf(record.getOrDefault("pid", ""));
|
||||
String userid = String.valueOf(record.getOrDefault("userid", ""));
|
||||
String xid = String.valueOf(record.getOrDefault("xid", ""));
|
||||
String query = String.valueOf(record.getOrDefault("query", ""));
|
||||
return "'" + recordTime + " UTC [ db=" + db + " user=" + user + " pid=" + pid
|
||||
+ " userid=" + userid + " xid=" + xid + " ]' " + query;
|
||||
}
|
||||
return LOG_COLUMNS.get(logType).stream()
|
||||
.map(col -> {
|
||||
Object val = record.get(col);
|
||||
return val == null ? "" : val.toString();
|
||||
})
|
||||
.collect(Collectors.joining("|"));
|
||||
}
|
||||
|
||||
private void createIfMissing(String accountId, String region, String group, String stream) {
|
||||
try {
|
||||
logs.createLogGroupForAccount(accountId, group, null, Map.of(), region);
|
||||
|
||||
@@ -1374,12 +1374,20 @@ public class RedshiftQueryHandler {
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
// No log delivery is emulated, so delivery timestamps and failure fields are omitted.
|
||||
private String buildLoggingStatusXml(Cluster cluster) {
|
||||
String lastSuccessful = cluster.getLastSuccessfulDeliveryTime() != null
|
||||
? DateTimeFormatter.ISO_INSTANT.format(cluster.getLastSuccessfulDeliveryTime())
|
||||
: null;
|
||||
String lastFailure = cluster.getLastFailureTime() != null
|
||||
? DateTimeFormatter.ISO_INSTANT.format(cluster.getLastFailureTime())
|
||||
: null;
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.elem("LoggingEnabled", cluster.isLoggingEnabled())
|
||||
.elem("BucketName", cluster.getLoggingBucketName())
|
||||
.elem("S3KeyPrefix", cluster.getLoggingS3KeyPrefix())
|
||||
.elem("LastSuccessfulDeliveryTime", lastSuccessful)
|
||||
.elem("LastFailureTime", lastFailure)
|
||||
.elem("LastFailureMessage", cluster.getLastFailureMessage())
|
||||
.elem("LogDestinationType", cluster.getLoggingDestinationType());
|
||||
if (cluster.getLoggingExports() != null) {
|
||||
builder.start("LogExports");
|
||||
|
||||
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServiceCallAuthorizer;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
@@ -16,6 +17,7 @@ import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.rds.proxy.PasswordValidator;
|
||||
import io.floci.aws.services.redshift.RedshiftEventCatalog.EventInfo;
|
||||
import io.floci.aws.services.redshift.container.RedshiftContainerHandle;
|
||||
@@ -34,6 +36,7 @@ import io.floci.aws.services.redshift.model.Snapshot;
|
||||
import io.floci.aws.services.redshift.model.SnapshotCopyGrant;
|
||||
import io.floci.aws.services.redshift.model.SnapshotSchedule;
|
||||
import io.floci.aws.services.redshift.proxy.RedshiftProxyManager;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.secretsmanager.ManagedSecretRotator;
|
||||
import io.floci.aws.services.secretsmanager.RandomPasswordGenerator;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
@@ -115,6 +118,8 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
private final RedshiftIntegrationEventPublisher integrationEvents;
|
||||
private final Ec2Service ec2Service;
|
||||
private final RedshiftZeroEtlEndpoints zeroEtlEndpoints;
|
||||
private final S3Service s3Service;
|
||||
private final ServiceCallAuthorizer serviceCallAuthorizer;
|
||||
// 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<>();
|
||||
@@ -131,7 +136,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
return withResourceLock(clusters.accountId(), kind, identifier, work);
|
||||
}
|
||||
|
||||
private <T> T withResourceLock(String accountId, String kind, String identifier, Supplier<T> work) {
|
||||
<T> T withResourceLock(String accountId, String kind, String identifier, Supplier<T> work) {
|
||||
ResourceKey key = new ResourceKey(accountId, kind, identifier);
|
||||
ResourceLock scoped = resourceLocks.compute(key, (ignored, existing) -> {
|
||||
ResourceLock selected = existing == null ? new ResourceLock() : existing;
|
||||
@@ -198,7 +203,8 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
|
||||
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
|
||||
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents,
|
||||
Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints) {
|
||||
Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints,
|
||||
S3Service s3Service, ServiceCallAuthorizer serviceCallAuthorizer) {
|
||||
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.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference<Map<String, Snapshot>>() {});
|
||||
@@ -223,6 +229,24 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
this.integrationEvents = integrationEvents;
|
||||
this.ec2Service = ec2Service;
|
||||
this.zeroEtlEndpoints = zeroEtlEndpoints;
|
||||
this.s3Service = s3Service;
|
||||
this.serviceCallAuthorizer = serviceCallAuthorizer;
|
||||
if (this.auditLogPublisher != null) {
|
||||
this.auditLogPublisher.setDeliveryStatusListener(this::recordAuditDeliveryOutcome);
|
||||
}
|
||||
}
|
||||
|
||||
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
|
||||
EmulatorConfig config, RegionResolver regionResolver,
|
||||
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver,
|
||||
RedshiftCredentialBroker credentialBroker,
|
||||
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
|
||||
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
|
||||
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents,
|
||||
Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints) {
|
||||
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
|
||||
credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events,
|
||||
integrationEvents, ec2Service, zeroEtlEndpoints, null, null);
|
||||
}
|
||||
|
||||
// Hand-built test constructions need not supply EC2; a null ec2Service skips subnet resolution.
|
||||
@@ -1480,8 +1504,18 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
String s3TableKmsKeyId, String s3TableGranularity) {
|
||||
Cluster cluster = clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
boolean cloudWatch = "cloudwatch".equalsIgnoreCase(logDestinationType);
|
||||
boolean s3Table = "s3table".equalsIgnoreCase(logDestinationType);
|
||||
|
||||
String destination = "s3";
|
||||
if (logDestinationType != null && !logDestinationType.isBlank()) {
|
||||
destination = logDestinationType.trim().toLowerCase();
|
||||
if (!List.of("cloudwatch", "s3", "s3table").contains(destination)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"LogDestinationType must be one of: cloudwatch, s3, s3table", 400);
|
||||
}
|
||||
}
|
||||
|
||||
boolean cloudWatch = "cloudwatch".equals(destination);
|
||||
boolean s3Table = "s3table".equals(destination);
|
||||
if (s3Table && s3TableGranularity != null
|
||||
&& !List.of("cluster", "account").contains(s3TableGranularity)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
@@ -1491,23 +1525,86 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"S3-table logging settings are valid only when LogDestinationType is s3table", 400);
|
||||
}
|
||||
if (!cloudWatch && !s3Table && (bucketName == null || bucketName.isBlank())) {
|
||||
throw new AwsException("InvalidParameterValue", "BucketName is required for an S3 log destination", 400);
|
||||
if (!cloudWatch && !s3Table) {
|
||||
if (bucketName == null || bucketName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "BucketName is required for an S3 log destination", 400);
|
||||
}
|
||||
if (s3KeyPrefix != null && s3KeyPrefix.startsWith("/")) {
|
||||
throw new AwsException("InvalidS3KeyPrefixFault",
|
||||
"The S3 key prefix cannot start with a forward slash (/)", 400);
|
||||
}
|
||||
validateS3BucketLogging(clusters.accountId(), cluster, bucketName, s3KeyPrefix, regionResolver.getRegion());
|
||||
}
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingBucketName(bucketName);
|
||||
cluster.setLoggingDestinationType(logDestinationType);
|
||||
cluster.setLoggingGeneration(cluster.getLoggingGeneration() + 1);
|
||||
cluster.setLoggingBucketName(cloudWatch || s3Table ? null : bucketName);
|
||||
cluster.setLoggingDestinationType(destination);
|
||||
cluster.setLoggingRegion(regionResolver.getRegion());
|
||||
cluster.setLoggingExports(logExports == null || logExports.isEmpty() ? null : List.copyOf(logExports));
|
||||
cluster.setLoggingS3KeyPrefix(s3KeyPrefix);
|
||||
cluster.setLoggingS3TableKmsKeyId(s3TableKmsKeyId);
|
||||
cluster.setLoggingS3TableGranularity(s3TableGranularity);
|
||||
cluster.setLoggingS3KeyPrefix(cloudWatch || s3Table ? null : s3KeyPrefix);
|
||||
cluster.setLoggingS3TableKmsKeyId(s3Table ? s3TableKmsKeyId : null);
|
||||
cluster.setLoggingS3TableGranularity(s3Table ? s3TableGranularity : null);
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
registerAuditLogging(clusters.accountId(), cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private void validateS3BucketLogging(String accountId, Cluster cluster, String bucketName,
|
||||
String s3KeyPrefix, String region) {
|
||||
if (s3Service == null) {
|
||||
return;
|
||||
}
|
||||
if (!s3Service.bucketExists(bucketName)) {
|
||||
throw new AwsException("BucketNotFoundFault",
|
||||
"Could not find the specified S3 bucket", 400);
|
||||
}
|
||||
if (serviceCallAuthorizer != null) {
|
||||
String partition = s3Service.bucketPartition(bucketName);
|
||||
String sampleKey = RedshiftAuditLogPublisher.s3DeliveryKey(s3KeyPrefix, accountId, region,
|
||||
cluster.getClusterIdentifier(), "connectionlog", Instant.now());
|
||||
String bucketArn = AwsArnUtils.Arn.global(partition, "s3", "", bucketName).toString();
|
||||
String objectArn = AwsArnUtils.Arn.global(partition, "s3", "", bucketName + "/" + sampleKey).toString();
|
||||
String clusterArn = AwsArnUtils.Arn.of("redshift", region, accountId,
|
||||
"cluster:" + cluster.getClusterIdentifier()).toString();
|
||||
Map<String, List<String>> requestKeys = Map.of("aws:RequestedRegion", List.of(region));
|
||||
|
||||
Decision getAcl = serviceCallAuthorizer.authorize("redshift", "s3:GetBucketAcl", bucketArn, clusterArn, accountId, requestKeys);
|
||||
Decision putObj = serviceCallAuthorizer.authorize("redshift", "s3:PutObject", objectArn, clusterArn, accountId, requestKeys);
|
||||
if (getAcl != Decision.ALLOW || putObj != Decision.ALLOW) {
|
||||
throw new AwsException("InsufficientS3BucketPolicyFault",
|
||||
"The cluster does not have read bucket or put object permissions on the S3 bucket specified when enabling logging.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void recordAuditDeliveryOutcome(String accountId, String clusterIdentifier, long generation,
|
||||
Instant timestamp, boolean success, String failureMessage) {
|
||||
try {
|
||||
withResourceLock(accountId, "cluster", clusterIdentifier, () -> mutate(() -> {
|
||||
Optional<Cluster> existing = clusters.getForAccount(accountId, clusterIdentifier);
|
||||
if (existing.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Cluster cluster = existing.get();
|
||||
if (!cluster.isLoggingEnabled() || cluster.getLoggingGeneration() != generation) {
|
||||
return null;
|
||||
}
|
||||
if (success) {
|
||||
cluster.setLastSuccessfulDeliveryTime(timestamp);
|
||||
} else {
|
||||
cluster.setLastFailureTime(timestamp);
|
||||
cluster.setLastFailureMessage(failureMessage);
|
||||
}
|
||||
clusters.putForAccount(accountId, clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
return null;
|
||||
}));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to record audit delivery outcome for cluster {0}", clusterIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
public Cluster disableLogging(String clusterIdentifier) {
|
||||
return mutateCluster(clusterIdentifier, () -> disableLoggingLocked(clusterIdentifier));
|
||||
}
|
||||
@@ -1516,6 +1613,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
Cluster cluster = clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
cluster.setLoggingEnabled(false);
|
||||
cluster.setLoggingGeneration(cluster.getLoggingGeneration() + 1);
|
||||
cluster.setLoggingBucketName(null);
|
||||
cluster.setLoggingS3KeyPrefix(null);
|
||||
cluster.setLoggingDestinationType(null);
|
||||
@@ -1523,6 +1621,9 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
cluster.setLoggingExports(null);
|
||||
cluster.setLoggingS3TableKmsKeyId(null);
|
||||
cluster.setLoggingS3TableGranularity(null);
|
||||
cluster.setLastSuccessfulDeliveryTime(null);
|
||||
cluster.setLastFailureTime(null);
|
||||
cluster.setLastFailureMessage(null);
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
registerAuditLogging(clusters.accountId(), cluster);
|
||||
|
||||
@@ -85,6 +85,24 @@ public class Cluster {
|
||||
public String getLoggingS3TableGranularity() { return loggingS3TableGranularity; }
|
||||
public void setLoggingS3TableGranularity(String loggingS3TableGranularity) { this.loggingS3TableGranularity = loggingS3TableGranularity; }
|
||||
|
||||
private Instant lastSuccessfulDeliveryTime;
|
||||
private Instant lastFailureTime;
|
||||
private String lastFailureMessage;
|
||||
|
||||
public Instant getLastSuccessfulDeliveryTime() { return lastSuccessfulDeliveryTime; }
|
||||
public void setLastSuccessfulDeliveryTime(Instant lastSuccessfulDeliveryTime) {
|
||||
this.lastSuccessfulDeliveryTime = lastSuccessfulDeliveryTime;
|
||||
}
|
||||
public Instant getLastFailureTime() { return lastFailureTime; }
|
||||
public void setLastFailureTime(Instant lastFailureTime) { this.lastFailureTime = lastFailureTime; }
|
||||
public String getLastFailureMessage() { return lastFailureMessage; }
|
||||
public void setLastFailureMessage(String lastFailureMessage) { this.lastFailureMessage = lastFailureMessage; }
|
||||
|
||||
private long loggingGeneration;
|
||||
|
||||
public long getLoggingGeneration() { return loggingGeneration; }
|
||||
public void setLoggingGeneration(long loggingGeneration) { this.loggingGeneration = loggingGeneration; }
|
||||
|
||||
// Cross-region snapshot copy (EnableSnapshotCopy). Enabled exactly when the destination is set.
|
||||
private String snapshotCopyDestinationRegion;
|
||||
private Integer snapshotCopyRetentionPeriod;
|
||||
|
||||
@@ -1,30 +1,56 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServiceCallAuthorizer;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftAuditLogPublisherTest {
|
||||
|
||||
@@ -177,6 +203,362 @@ class RedshiftAuditLogPublisherTest {
|
||||
assertEquals(sql, RedshiftAuditLogPublisher.sanitizeSql(sql));
|
||||
}
|
||||
|
||||
private static final Instant S3_TEST_TIME = Instant.parse("2026-11-06T15:30:00Z");
|
||||
|
||||
private final S3Service s3 = mock(S3Service.class);
|
||||
private final ServiceCallAuthorizer authorizer = mock(ServiceCallAuthorizer.class);
|
||||
private final RegionResolver regionResolver = new RegionResolver("us-east-1", "111111111111");
|
||||
|
||||
@BeforeEach
|
||||
void setUpAuthorizer() {
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any(), any())).thenReturn(Decision.ALLOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesConnectionLogToS3GzipWithPipeDelimiter() throws Exception {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
Cluster cluster = s3ClusterWithPrefix("cluster-logs", "connectionlog");
|
||||
publisher.register("111111111111", "us-east-1", cluster);
|
||||
|
||||
AtomicReference<Instant> deliveryTimestamp = new AtomicReference<>();
|
||||
AtomicBoolean deliverySuccess = new AtomicBoolean();
|
||||
publisher.setDeliveryStatusListener((acc, clId, gen, ts, success, msg) -> {
|
||||
deliveryTimestamp.set(ts);
|
||||
deliverySuccess.set(success);
|
||||
});
|
||||
|
||||
publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin", "authenticated",
|
||||
"192.0.2.1", 54321);
|
||||
|
||||
ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
ArgumentCaptor<Map<String, List<String>>> keysCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(s3).putObject(eq("audit-bucket"), keyCaptor.capture(), dataCaptor.capture(),
|
||||
eq("application/x-gzip"), eq(Map.of()));
|
||||
verify(authorizer).authorize(eq("redshift"), eq("s3:PutObject"), anyString(), anyString(),
|
||||
eq("111111111111"), keysCaptor.capture());
|
||||
assertEquals(List.of("us-east-1"), keysCaptor.getValue().get("aws:RequestedRegion"));
|
||||
|
||||
assertEquals("cluster-logs/AWSLogs/111111111111/redshift/us-east-1/2026/11/06/"
|
||||
+ "111111111111_redshift_us-east-1_analytics_connectionlog_2026-11-06T15:30.gz", keyCaptor.getValue());
|
||||
|
||||
String decompressed = decompressGzip(dataCaptor.getValue());
|
||||
String[] lines = decompressed.split("\n");
|
||||
assertEquals(1, lines.length);
|
||||
String[] columns = lines[0].split("\\|", -1);
|
||||
assertEquals(22, columns.length);
|
||||
assertEquals("authenticated", columns[0]);
|
||||
assertEquals("2026-11-06T15:30:00Z", columns[1]);
|
||||
assertEquals("192.0.2.1", columns[2]);
|
||||
assertEquals("54321", columns[3]);
|
||||
assertEquals("dev", columns[5]);
|
||||
assertEquals("admin", columns[6]);
|
||||
assertEquals("password", columns[7]);
|
||||
|
||||
assertTrue(deliverySuccess.get());
|
||||
assertEquals(S3_TEST_TIME, deliveryTimestamp.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesUserLogToS3GzipWithPipeDelimiter() throws Exception {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
Cluster cluster = s3Cluster("userlog");
|
||||
|
||||
publisher.publish(cluster, "111111111111", "us-east-1", "userlog", Map.of(
|
||||
"userid", "101",
|
||||
"username", "admin",
|
||||
"action", "create user alice",
|
||||
"usecreatedb", "true",
|
||||
"usesuper", "false",
|
||||
"usecatupd", "false",
|
||||
"valuntil", "infinity",
|
||||
"pid", "1234",
|
||||
"recordtime", "2026-11-06T15:30:00Z"
|
||||
));
|
||||
|
||||
ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3).putObject(eq("audit-bucket"), keyCaptor.capture(), dataCaptor.capture(),
|
||||
eq("application/x-gzip"), eq(Map.of()));
|
||||
|
||||
assertEquals("AWSLogs/111111111111/redshift/us-east-1/2026/11/06/"
|
||||
+ "111111111111_redshift_us-east-1_analytics_userlog_2026-11-06T15:30.gz", keyCaptor.getValue());
|
||||
|
||||
String decompressed = decompressGzip(dataCaptor.getValue());
|
||||
String[] columns = decompressed.strip().split("\\|", -1);
|
||||
assertEquals(11, columns.length);
|
||||
assertEquals("101", columns[0]);
|
||||
assertEquals("admin", columns[1]);
|
||||
assertEquals("", columns[2]);
|
||||
assertEquals("create user alice", columns[3]);
|
||||
assertEquals("true", columns[4]);
|
||||
assertEquals("false", columns[5]);
|
||||
assertEquals("false", columns[6]);
|
||||
assertEquals("infinity", columns[7]);
|
||||
assertEquals("1234", columns[8]);
|
||||
assertEquals("", columns[9]);
|
||||
assertEquals("2026-11-06T15:30:00Z", columns[10]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesUserActivityLogToS3GzipWithStandardFormatAndSanitizesSql() throws Exception {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
Cluster cluster = s3Cluster("useractivitylog");
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin",
|
||||
"ALTER USER alice PASSWORD 'secret123'");
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3).putObject(eq("audit-bucket"), anyString(), dataCaptor.capture(),
|
||||
eq("application/x-gzip"), eq(Map.of()));
|
||||
|
||||
String decompressed = decompressGzip(dataCaptor.getValue());
|
||||
assertEquals("'2026-11-06T15:30:00Z UTC [ db=dev user=admin pid= userid= xid= ]' "
|
||||
+ "LOG: ALTER USER alice PASSWORD '[REDACTED]'\n", decompressed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendsToExistingS3GzipObject() throws Exception {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
|
||||
String key = "AWSLogs/111111111111/redshift/us-east-1/2026/11/06/"
|
||||
+ "111111111111_redshift_us-east-1_analytics_useractivitylog_2026-11-06T15:30.gz";
|
||||
byte[] existingGzip = compressGzip("'2026-11-06T15:30:00Z UTC [ db=dev user=admin pid= userid= xid= ]' LOG: SELECT 1\n");
|
||||
S3Object existingObj = new S3Object("audit-bucket", key, existingGzip, "application/x-gzip");
|
||||
when(s3.getObject("audit-bucket", key)).thenReturn(existingObj);
|
||||
|
||||
Cluster cluster = s3Cluster("useractivitylog");
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "SELECT 2");
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3).putObject(eq("audit-bucket"), eq(key), dataCaptor.capture(),
|
||||
eq("application/x-gzip"), eq(Map.of()));
|
||||
|
||||
String decompressed = decompressGzip(dataCaptor.getValue());
|
||||
assertEquals("'2026-11-06T15:30:00Z UTC [ db=dev user=admin pid= userid= xid= ]' LOG: SELECT 1\n"
|
||||
+ "'2026-11-06T15:30:00Z UTC [ db=dev user=admin pid= userid= xid= ]' LOG: SELECT 2\n", decompressed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentAuditDeliveriesDoNotCorruptGzipOutput() throws Exception {
|
||||
ConcurrentHashMap<String, byte[]> bucket = new ConcurrentHashMap<>();
|
||||
doAnswer(inv -> {
|
||||
bucket.put(inv.getArgument(1, String.class), inv.getArgument(2, byte[].class));
|
||||
return null;
|
||||
}).when(s3).putObject(eq("audit-bucket"), anyString(), any(), anyString(), anyMap());
|
||||
when(s3.getObject(eq("audit-bucket"), anyString())).thenAnswer(inv -> {
|
||||
byte[] data = bucket.get(inv.getArgument(1, String.class));
|
||||
return data == null ? null : new S3Object("audit-bucket", inv.getArgument(1, String.class), data, "application/x-gzip");
|
||||
});
|
||||
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
Cluster cluster = s3Cluster("useractivitylog");
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
publisher.register("111111111111", "us-east-1", cluster);
|
||||
|
||||
int threadCount = 10;
|
||||
int recordsPerThread = 5;
|
||||
CountDownLatch startLatch = new CountDownLatch(1);
|
||||
CountDownLatch doneLatch = new CountDownLatch(threadCount);
|
||||
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(threadCount)) {
|
||||
for (int t = 0; t < threadCount; t++) {
|
||||
int threadId = t;
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
startLatch.await();
|
||||
for (int i = 0; i < recordsPerThread; i++) {
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin",
|
||||
"SELECT " + threadId + "_" + i);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
doneLatch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
startLatch.countDown();
|
||||
assertTrue(doneLatch.await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3, atLeastOnce()).putObject(eq("audit-bucket"), anyString(),
|
||||
dataCaptor.capture(), eq("application/x-gzip"), eq(Map.of()));
|
||||
|
||||
byte[] finalBytes = dataCaptor.getValue();
|
||||
String decompressed = decompressGzip(finalBytes);
|
||||
for (int t = 0; t < threadCount; t++) {
|
||||
for (int i = 0; i < recordsPerThread; i++) {
|
||||
assertTrue(decompressed.contains("SELECT " + t + "_" + i),
|
||||
"Missing record SELECT " + t + "_" + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyingBucketBetweenDeliveriesStartsFreshObject() throws Exception {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
Cluster cluster = s3Cluster("useractivitylog");
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
|
||||
String key = "AWSLogs/111111111111/redshift/us-east-1/2026/11/06/"
|
||||
+ "111111111111_redshift_us-east-1_analytics_useractivitylog_2026-11-06T15:30.gz";
|
||||
byte[] existingGzip = compressGzip("'2026-11-06T15:30:00Z UTC [ db=dev user=admin pid= userid= xid= ]' LOG: SELECT 1\n");
|
||||
when(s3.getObject("audit-bucket", key)).thenReturn(new S3Object("audit-bucket", key, existingGzip, "application/x-gzip"));
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "SELECT 2");
|
||||
|
||||
when(s3.getObject("audit-bucket", key)).thenReturn(null);
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "SELECT 3");
|
||||
|
||||
ArgumentCaptor<byte[]> dataCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3, times(2)).putObject(eq("audit-bucket"), eq(key), dataCaptor.capture(),
|
||||
eq("application/x-gzip"), eq(Map.of()));
|
||||
|
||||
byte[] secondPutBytes = dataCaptor.getAllValues().get(1);
|
||||
String decompressed = decompressGzip(secondPutBytes);
|
||||
assertFalse(decompressed.contains("SELECT 1"), "Must not resurrect deleted SELECT 1");
|
||||
assertFalse(decompressed.contains("SELECT 2"), "Must not resurrect deleted SELECT 2");
|
||||
assertTrue(decompressed.contains("SELECT 3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3AuthorizationDenialRecordsFailureAndDoesNotThrow() {
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any(), any())).thenReturn(Decision.DENY);
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher(Clock.systemUTC());
|
||||
publisher.register("111111111111", "us-east-1", s3Cluster("connectionlog"));
|
||||
|
||||
AtomicReference<String> failureMsg = new AtomicReference<>();
|
||||
AtomicBoolean deliverySuccess = new AtomicBoolean(true);
|
||||
publisher.setDeliveryStatusListener((acc, clId, gen, ts, success, msg) -> {
|
||||
deliverySuccess.set(success);
|
||||
failureMsg.set(msg);
|
||||
});
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin",
|
||||
"authenticated", "192.0.2.1", 54321));
|
||||
|
||||
verify(s3, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap());
|
||||
assertFalse(deliverySuccess.get());
|
||||
assertTrue(failureMsg.get().contains("Access Denied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3PutObjectFailureRecordsFailureAndDoesNotThrow() {
|
||||
doThrow(new AwsException("InternalError", "S3 connection timeout", 500)).when(s3)
|
||||
.putObject(anyString(), anyString(), any(), anyString(), anyMap());
|
||||
Cluster cluster = s3Cluster("connectionlog");
|
||||
cluster.setLoggingGeneration(5L);
|
||||
RedshiftAuditLogPublisher publisher = registeredS3Publisher(cluster);
|
||||
|
||||
AtomicReference<String> failureMsg = new AtomicReference<>();
|
||||
AtomicBoolean deliverySuccess = new AtomicBoolean(true);
|
||||
AtomicReference<Long> reportedGen = new AtomicReference<>();
|
||||
publisher.setDeliveryStatusListener((acc, clId, gen, ts, success, msg) -> {
|
||||
reportedGen.set(gen);
|
||||
deliverySuccess.set(success);
|
||||
failureMsg.set(msg);
|
||||
});
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin",
|
||||
"authenticated", "192.0.2.1", 54321));
|
||||
|
||||
assertFalse(deliverySuccess.get());
|
||||
assertEquals(5L, reportedGen.get());
|
||||
assertTrue(failureMsg.get().contains("S3 connection timeout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishS3DoesNotThrowOnUnexpectedRuntimeException() {
|
||||
doThrow(new IllegalStateException("Unexpected crash")).when(s3)
|
||||
.putObject(anyString(), anyString(), any(), anyString(), anyMap());
|
||||
RedshiftAuditLogPublisher publisher = registeredConnectionLogPublisher();
|
||||
|
||||
AtomicBoolean listenerCalled = new AtomicBoolean(false);
|
||||
publisher.setDeliveryStatusListener((acc, clId, gen, ts, success, msg) -> listenerCalled.set(true));
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin",
|
||||
"authenticated", "192.0.2.1", 54321));
|
||||
|
||||
assertFalse(listenerCalled.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishS3DoesNotThrowWhenAuthorizerThrows() {
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any(), any()))
|
||||
.thenThrow(new RuntimeException("Authorizer boom"));
|
||||
RedshiftAuditLogPublisher publisher = registeredConnectionLogPublisher();
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin",
|
||||
"authenticated", "192.0.2.1", 54321));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishS3DoesNotThrowWhenStatusListenerThrows() {
|
||||
RedshiftAuditLogPublisher publisher = registeredConnectionLogPublisher();
|
||||
publisher.setDeliveryStatusListener((acc, clId, gen, ts, success, msg) -> {
|
||||
throw new RuntimeException("Listener boom");
|
||||
});
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publishRegisteredConnection("111111111111", "analytics", "dev", "admin",
|
||||
"authenticated", "192.0.2.1", 54321));
|
||||
}
|
||||
|
||||
private RedshiftAuditLogPublisher registeredS3Publisher(Cluster cluster) {
|
||||
RedshiftAuditLogPublisher publisher = s3Publisher();
|
||||
publisher.register("111111111111", "us-east-1", cluster);
|
||||
return publisher;
|
||||
}
|
||||
|
||||
private RedshiftAuditLogPublisher registeredConnectionLogPublisher() {
|
||||
return registeredS3Publisher(s3Cluster("connectionlog"));
|
||||
}
|
||||
|
||||
private RedshiftAuditLogPublisher s3Publisher(Clock clock) {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
return new RedshiftAuditLogPublisher(logs, s3, authorizer, regionResolver, clock);
|
||||
}
|
||||
|
||||
private RedshiftAuditLogPublisher s3Publisher() {
|
||||
return s3Publisher(Clock.fixed(S3_TEST_TIME, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private static Cluster s3Cluster(String... exports) {
|
||||
return s3ClusterWithPrefix(null, exports);
|
||||
}
|
||||
|
||||
private static Cluster s3ClusterWithPrefix(String prefix, String... exports) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("analytics");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingDestinationType("s3");
|
||||
cluster.setLoggingBucketName("audit-bucket");
|
||||
cluster.setLoggingS3KeyPrefix(prefix);
|
||||
cluster.setLoggingExports(List.of(exports));
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private static String decompressGzip(byte[] gzipped) throws IOException {
|
||||
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gzipped));
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
in.transferTo(out);
|
||||
return out.toString(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] compressGzip(String text) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
|
||||
gzip.write(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static Cluster enabledCluster(List<String> exports) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("analytics");
|
||||
|
||||
@@ -1062,6 +1062,28 @@ class RedshiftQueryHandlerTest {
|
||||
assertTrue(xml.contains("<S3KeyPrefix>logs/</S3KeyPrefix>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeLoggingStatusIncludesDeliveryTimestampsAndFailureMessage() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("test-cluster");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingBucketName("my-bucket");
|
||||
cluster.setLastSuccessfulDeliveryTime(Instant.parse("2026-11-06T15:30:00Z"));
|
||||
cluster.setLastFailureTime(Instant.parse("2026-11-06T15:31:00Z"));
|
||||
cluster.setLastFailureMessage("Access Denied: The bucket policy does not allow Amazon Redshift to put objects.");
|
||||
when(service.describeLoggingStatus("test-cluster")).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("DescribeLoggingStatus", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<LastSuccessfulDeliveryTime>2026-11-06T15:30:00Z</LastSuccessfulDeliveryTime>"));
|
||||
assertTrue(xml.contains("<LastFailureTime>2026-11-06T15:31:00Z</LastFailureTime>"));
|
||||
assertTrue(xml.contains("<LastFailureMessage>Access Denied: The bucket policy does not allow Amazon Redshift to put objects.</LastFailureMessage>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeS3TableLoggingStatusIncludesEnabledAllWithoutGranularity() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServiceCallAuthorizer;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
@@ -17,6 +18,7 @@ import io.floci.aws.services.dynamodb.backend.DynamoDbOperations;
|
||||
import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.rds.proxy.PasswordValidator;
|
||||
import io.floci.aws.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
|
||||
@@ -48,6 +50,7 @@ import org.mockito.InOrder;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -67,6 +70,7 @@ import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.floci.aws.testing.InlineMocks.inlineMock;
|
||||
import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
@@ -890,6 +894,7 @@ class RedshiftServiceTest {
|
||||
private RedshiftIntegrationEventPublisher integrationEvents;
|
||||
private DynamoDbTableAccess zeroEtlTables;
|
||||
private RedshiftServerlessService zeroEtlServerless;
|
||||
private EmulatorConfig config;
|
||||
private S3Service zeroEtlS3;
|
||||
private RedshiftService service;
|
||||
|
||||
@@ -915,7 +920,7 @@ class RedshiftServiceTest {
|
||||
dockerHostResolver = mock(DockerHostResolver.class);
|
||||
when(dockerHostResolver.resolve()).thenReturn("localhost");
|
||||
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.StorageConfig storageConfig = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.storage()).thenReturn(storageConfig);
|
||||
when(storageConfig.persistentPath()).thenReturn("target/test-data");
|
||||
@@ -2481,6 +2486,264 @@ class RedshiftServiceTest {
|
||||
verify(clusterBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingRejectsPrefixStartingWithSlash() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.enableLogging("my-cluster", "my-bucket", "/logs", null, null));
|
||||
assertEquals("InvalidS3KeyPrefixFault", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingRejectsNonexistentS3Bucket() {
|
||||
S3Service mockS3 = mock(S3Service.class);
|
||||
when(mockS3.bucketExists("missing-bucket")).thenReturn(false);
|
||||
RedshiftService s3AwareService = s3Service(mockS3, null);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
s3AwareService.enableLogging("my-cluster", "missing-bucket", "logs", null, null));
|
||||
assertEquals("BucketNotFoundFault", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingRejectsInsufficientS3BucketPolicy() {
|
||||
S3Service mockS3 = mock(S3Service.class);
|
||||
when(mockS3.bucketExists("audit-bucket")).thenReturn(true);
|
||||
when(mockS3.bucketPartition("audit-bucket")).thenReturn("aws"); // partition-literal: mock test partition
|
||||
ServiceCallAuthorizer authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(eq("redshift"), eq("s3:GetBucketAcl"), anyString(), anyString(), anyString(), anyMap()))
|
||||
.thenReturn(Decision.DENY);
|
||||
|
||||
RedshiftService s3AwareService = s3Service(mockS3, authorizer);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
s3AwareService.enableLogging("my-cluster", "audit-bucket", "logs", null, null));
|
||||
assertEquals("InsufficientS3BucketPolicyFault", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingRejectsUnknownLogDestinationType() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.enableLogging("my-cluster", "my-bucket", "logs", "unsupported-dest", null));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertTrue(ex.getMessage().contains("LogDestinationType must be one of"));
|
||||
assertFalse(cluster.isLoggingEnabled());
|
||||
verify(clusterBackend, never()).put(anyString(), any());
|
||||
verify(clusterBackend, never()).putForAccount(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void enableLoggingAuthorizesBucketPolicyWithRequestedRegionCondition() {
|
||||
S3Service mockS3 = mock(S3Service.class);
|
||||
when(mockS3.bucketExists("audit-bucket")).thenReturn(true);
|
||||
when(mockS3.bucketPartition("audit-bucket")).thenReturn("aws"); // partition-literal: mock test partition
|
||||
ServiceCallAuthorizer authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(eq("redshift"), anyString(), anyString(), anyString(), anyString(), anyMap()))
|
||||
.thenAnswer(invocation -> {
|
||||
Map<String, List<String>> keys = invocation.getArgument(5);
|
||||
if (keys != null && List.of("us-east-1").equals(keys.get("aws:RequestedRegion"))) {
|
||||
return Decision.ALLOW;
|
||||
}
|
||||
return Decision.DENY;
|
||||
});
|
||||
|
||||
RedshiftService s3AwareService = s3Service(mockS3, authorizer);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Cluster result = s3AwareService.enableLogging("my-cluster", "audit-bucket", "cluster-logs", "s3", null);
|
||||
assertTrue(result.isLoggingEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void enableLoggingAuthorizesPutObjectWithRealDeliveryPathAndRequestedRegion() {
|
||||
S3Service mockS3 = mock(S3Service.class);
|
||||
when(mockS3.bucketExists("audit-bucket")).thenReturn(true);
|
||||
when(mockS3.bucketPartition("audit-bucket")).thenReturn("aws"); // partition-literal: mock test partition
|
||||
ServiceCallAuthorizer authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), anyString(), anyString(), anyMap()))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
|
||||
RedshiftService s3AwareService = s3Service(mockS3, authorizer);
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
s3AwareService.enableLogging("my-cluster", "audit-bucket", "cluster-logs", "s3", null);
|
||||
|
||||
ArgumentCaptor<String> objectArnCaptor = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<Map<String, List<String>>> keysCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(authorizer).authorize(eq("redshift"), eq("s3:PutObject"), objectArnCaptor.capture(),
|
||||
anyString(), anyString(), keysCaptor.capture());
|
||||
|
||||
assertTrue(objectArnCaptor.getValue().contains("audit-bucket/cluster-logs/AWSLogs/111111111111/redshift/"));
|
||||
assertEquals(List.of("us-east-1"), keysCaptor.getValue().get("aws:RequestedRegion"));
|
||||
}
|
||||
|
||||
private RedshiftService s3Service(S3Service s3, ServiceCallAuthorizer authorizer) {
|
||||
return new RedshiftService(sf, cm, config, regionResolver, proxyManager,
|
||||
dockerHostResolver, credentialBroker, secretsManagerService, new ObjectMapper(),
|
||||
null, null, events, integrationEvents, null, null, s3, authorizer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeDoesNotUpdateDisabledCluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setLoggingEnabled(false);
|
||||
when(clusterBackend.getForAccount("111111111111", "my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
service.recordAuditDeliveryOutcome("111111111111", "my-cluster", 1L, ts, true, null);
|
||||
assertNull(cluster.getLastSuccessfulDeliveryTime());
|
||||
assertNull(cluster.getLastFailureTime());
|
||||
verify(clusterBackend, never()).putForAccount(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeUpdatesClusterStatus() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingGeneration(1L);
|
||||
when(clusterBackend.getForAccount("111111111111", "my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
service.recordAuditDeliveryOutcome("111111111111", "my-cluster", 1L, ts, true, null);
|
||||
assertEquals(ts, cluster.getLastSuccessfulDeliveryTime());
|
||||
assertNull(cluster.getLastFailureTime());
|
||||
assertNull(cluster.getLastFailureMessage());
|
||||
|
||||
Instant failTs = Instant.parse("2026-11-06T15:31:00Z");
|
||||
service.recordAuditDeliveryOutcome("111111111111", "my-cluster", 1L, failTs, false, "timeout");
|
||||
assertEquals(ts, cluster.getLastSuccessfulDeliveryTime());
|
||||
assertEquals(failTs, cluster.getLastFailureTime());
|
||||
assertEquals("timeout", cluster.getLastFailureMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeIgnoresStaleGenerationOutcome() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingGeneration(2L);
|
||||
when(clusterBackend.getForAccount("111111111111", "my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
service.recordAuditDeliveryOutcome("111111111111", "my-cluster", 1L, ts, true, null);
|
||||
assertNull(cluster.getLastSuccessfulDeliveryTime());
|
||||
assertNull(cluster.getLastFailureTime());
|
||||
verify(clusterBackend, never()).putForAccount(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeSucceedsDuringPasswordRotation() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setClusterStatus("available");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingGeneration(1L);
|
||||
cluster.setMasterPasswordSecretArn("arn:aws:secretsmanager:us-east-1:111111111111:secret:redshift-pass");
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "my-cluster", cluster)));
|
||||
when(clusterBackend.getForAccount("111111111111", "my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
service.reserve("arn:aws:secretsmanager:us-east-1:111111111111:secret:redshift-pass", "us-east-1");
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
service.recordAuditDeliveryOutcome("111111111111", "my-cluster", 1L, ts, true, null);
|
||||
assertEquals(ts, cluster.getLastSuccessfulDeliveryTime());
|
||||
|
||||
service.release("arn:aws:secretsmanager:us-east-1:111111111111:secret:redshift-pass", "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeUsesSuppliedAccountIdRegardlessOfRequestContext() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingGeneration(1L);
|
||||
when(clusterBackend.getForAccount("999999999999", "my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
service.recordAuditDeliveryOutcome("999999999999", "my-cluster", 1L, ts, true, null);
|
||||
|
||||
assertEquals(ts, cluster.getLastSuccessfulDeliveryTime());
|
||||
verify(clusterBackend).putForAccount("999999999999", "my-cluster", cluster);
|
||||
verify(clusterBackend, never()).put(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAuditDeliveryOutcomeSerializesUnderAccountClusterLockWithoutDerivingAccountFromRequestContext() throws Exception {
|
||||
String accountId = "999999999999";
|
||||
String clusterId = "locked-cluster";
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier(clusterId);
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingGeneration(1L);
|
||||
|
||||
when(clusterBackend.getForAccount(accountId, clusterId)).thenReturn(Optional.of(cluster));
|
||||
|
||||
CountDownLatch inLock = new CountDownLatch(1);
|
||||
CountDownLatch releaseLock = new CountDownLatch(1);
|
||||
CountDownLatch outcomeStarted = new CountDownLatch(1);
|
||||
AtomicReference<Thread> outcomeThread = new AtomicReference<>();
|
||||
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> holdingLock = executor.submit(() -> {
|
||||
service.withResourceLock(accountId, "cluster", clusterId, () -> {
|
||||
inLock.countDown();
|
||||
try {
|
||||
assertTrue(releaseLock.await(5, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
assertTrue(inLock.await(2, TimeUnit.SECONDS));
|
||||
|
||||
Instant ts = Instant.parse("2026-11-06T15:30:00Z");
|
||||
Future<?> outcome = executor.submit(() -> {
|
||||
outcomeThread.set(Thread.currentThread());
|
||||
outcomeStarted.countDown();
|
||||
service.recordAuditDeliveryOutcome(accountId, clusterId, 1L, ts, true, null);
|
||||
});
|
||||
|
||||
assertTrue(outcomeStarted.await(2, TimeUnit.SECONDS));
|
||||
awaitBlockedOrDone(outcomeThread, outcome);
|
||||
assertFalse(outcome.isDone(), "outcome must wait while holding lock owns the cluster");
|
||||
|
||||
releaseLock.countDown();
|
||||
holdingLock.get(2, TimeUnit.SECONDS);
|
||||
outcome.get(2, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(ts, cluster.getLastSuccessfulDeliveryTime());
|
||||
verify(clusterBackend).putForAccount(accountId, clusterId, cluster);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyClusterIamRolesRejectsMalformedRoleArnWithoutChangingTheCluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
@@ -2539,6 +2802,19 @@ class RedshiftServiceTest {
|
||||
assertEquals(List.of("connectionlog"), result.getLoggingExports());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingDropsBucketNameWhenDestinationIsCloudWatch() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Cluster result = service.enableLogging("my-cluster", "my-bucket", "prefix", "cloudwatch", List.of("connectionlog"));
|
||||
assertTrue(result.isLoggingEnabled());
|
||||
assertEquals("cloudwatch", result.getLoggingDestinationType());
|
||||
assertNull(result.getLoggingBucketName());
|
||||
assertNull(result.getLoggingS3KeyPrefix());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableLoggingS3TableDoesNotRequireBucketName() {
|
||||
Cluster cluster = new Cluster();
|
||||
@@ -2637,6 +2913,9 @@ class RedshiftServiceTest {
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingBucketName("my-bucket");
|
||||
cluster.setLoggingS3KeyPrefix("logs/");
|
||||
cluster.setLastSuccessfulDeliveryTime(Instant.parse("2026-11-06T15:30:00Z"));
|
||||
cluster.setLastFailureTime(Instant.parse("2026-11-06T15:31:00Z"));
|
||||
cluster.setLastFailureMessage("failed");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Cluster result = service.disableLogging("my-cluster");
|
||||
@@ -2644,6 +2923,9 @@ class RedshiftServiceTest {
|
||||
assertFalse(result.isLoggingEnabled());
|
||||
assertNull(result.getLoggingBucketName());
|
||||
assertNull(result.getLoggingS3KeyPrefix());
|
||||
assertNull(result.getLastSuccessfulDeliveryTime());
|
||||
assertNull(result.getLastFailureTime());
|
||||
assertNull(result.getLastFailureMessage());
|
||||
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
|
||||
verify(clusterBackend).flush();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user