mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user