diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java index b4f6d99072..77e448e147 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java @@ -68,10 +68,7 @@ public class RedshiftAuditLogPublisher { } } - private record Registration(String region, String identifier, boolean enabled, String destination, - String bucketName, String s3KeyPrefix, - List exports, boolean activityLoggingEnabled, - long loggingGeneration) { } + private record Registration(String region, RedshiftAuditTarget target) { } @Inject public RedshiftAuditLogPublisher(CloudWatchLogsService logs, S3Service s3, @@ -101,12 +98,11 @@ public class RedshiftAuditLogPublisher { } 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.getLoggingGeneration())); + register(accountId, region, RedshiftAuditTarget.of(cluster)); + } + + public void register(String accountId, String region, RedshiftAuditTarget target) { + registrations.put(registryKey(accountId, target.identifier()), new Registration(region, target)); } public void unregister(String accountId, String clusterIdentifier) { @@ -120,8 +116,7 @@ public class RedshiftAuditLogPublisher { if (registration == null) { return; } - Cluster cluster = registeredCluster(registration); - publish(cluster, accountId, registration.region(), logType, record); + publish(registration.target(), accountId, registration.region(), logType, record); } catch (Exception ex) { LOG.warnv(ex, "Failed to publish registered Redshift {0} audit event for cluster {1}", logType, clusterIdentifier); @@ -135,8 +130,7 @@ public class RedshiftAuditLogPublisher { if (registration == null) { return; } - Cluster cluster = registeredCluster(registration); - publishActivity(cluster, accountId, registration.region(), database, username, sql); + publishActivity(registration.target(), accountId, registration.region(), database, username, sql); } catch (Exception ex) { LOG.warnv(ex, "Failed to publish registered Redshift activity audit event for cluster {0}", clusterIdentifier); } @@ -149,24 +143,24 @@ public class RedshiftAuditLogPublisher { if (registration == null) { return; } - Cluster cluster = registeredCluster(registration); - publishUserChange(cluster, accountId, registration.region(), database, username, action, oldUsername); + publishUserChange(registration.target(), 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); } } - private static Cluster registeredCluster(Registration registration) { - Cluster cluster = new Cluster(); - 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; + /** + * Builds the target of a cluster for the publish overloads, which must never fail the statement being audited: + * a cluster whose stored logging settings are malformed is reported and treated as having no target. + */ + private static RedshiftAuditTarget targetOf(Cluster cluster) { + try { + return RedshiftAuditTarget.of(cluster); + } catch (RuntimeException ex) { + LOG.warnv(ex, "Failed to build the Redshift audit target for cluster {0}", + cluster.getClusterIdentifier()); + return null; + } } private static String registryKey(String accountId, String clusterIdentifier) { @@ -175,27 +169,38 @@ public class RedshiftAuditLogPublisher { public void publishActivity(Cluster cluster, String accountId, String region, String database, String username, String sql) { + publishActivity(targetOf(cluster), accountId, region, database, username, sql); + } + + public void publishActivity(RedshiftAuditTarget target, String accountId, String region, String database, String username, + String sql) { try { Map 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); + publish(target, 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"); + target != null ? target.identifier() : "unknown"); } } public void publishConnection(Cluster cluster, String accountId, String region, String database, String username, String event, String remoteAddress, String error) { + publishConnection(targetOf(cluster), accountId, region, database, username, event, remoteAddress, + error); + } + + public void publishConnection(RedshiftAuditTarget target, String accountId, String region, String database, String username, + String event, String remoteAddress, String error) { try { - publish(cluster, accountId, region, "connectionlog", + publish(target, 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"); + target != null ? target.identifier() : "unknown"); } } @@ -242,6 +247,11 @@ public class RedshiftAuditLogPublisher { public void publishUserChange(Cluster cluster, String accountId, String region, String database, String username, String action, String oldUsername) { + publishUserChange(targetOf(cluster), accountId, region, database, username, action, oldUsername); + } + + public void publishUserChange(RedshiftAuditTarget target, String accountId, String region, String database, + String username, String action, String oldUsername) { try { Map record = new LinkedHashMap<>(); record.put("recordtime", Instant.ofEpochMilli(clock.millis()).toString()); @@ -256,39 +266,44 @@ public class RedshiftAuditLogPublisher { record.put("valuntil", ""); record.put("pid", ""); record.put("xid", ""); - publish(cluster, accountId, region, "userlog", record); + publish(target, 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"); + target != null ? target.identifier() : "unknown"); } } public void publish(Cluster cluster, String accountId, String region, String logType, Map record) { + publish(targetOf(cluster), accountId, region, logType, record); + } + + public void publish(RedshiftAuditTarget target, String accountId, String region, String logType, + Map record) { try { - if (cluster == null || !cluster.isLoggingEnabled() - || "useractivitylog".equals(logType) && !cluster.isUserActivityLoggingEnabled() - || !LOG_TYPES.contains(logType) || !exports(cluster.getLoggingExports()).contains(logType)) { + if (target == null || !target.enabled() + || "useractivitylog".equals(logType) && !target.activityLoggingEnabled() + || !LOG_TYPES.contains(logType) || !exports(target.exports()).contains(logType)) { return; } - String destination = cluster.getLoggingDestinationType(); + String destination = target.destinationType(); if ("cloudwatch".equalsIgnoreCase(destination)) { - publishCloudWatch(cluster, accountId, region, logType, record); + publishCloudWatch(target, accountId, region, logType, record); } else if ("s3".equalsIgnoreCase(destination) - || (destination == null && cluster.getLoggingBucketName() != null)) { - publishS3(cluster, accountId, region, logType, record); + || (destination == null && target.bucketName() != null)) { + publishS3(target, accountId, region, logType, record); } } catch (Exception ex) { LOG.warnv(ex, "Failed to publish Redshift audit event for cluster {0}", - cluster != null ? cluster.getClusterIdentifier() : "unknown"); + target != null ? target.identifier() : "unknown"); } } - private void publishCloudWatch(Cluster cluster, String accountId, String region, String logType, + private void publishCloudWatch(RedshiftAuditTarget target, String accountId, String region, String logType, Map record) { - String group = "/aws/redshift/cluster/" + cluster.getClusterIdentifier() + "/" + logType; - String stream = cluster.getClusterIdentifier(); + String group = target.logGroupPrefix() + "/" + logType; + String stream = target.name(); try { createIfMissing(accountId, region, group, stream); Map event = Map.of( @@ -297,7 +312,7 @@ public class RedshiftAuditLogPublisher { logs.putLogEventsForAccount(accountId, group, stream, List.of(event), region); } catch (RuntimeException exception) { LOG.warnv(exception, "Failed to publish Redshift {0} audit event for cluster {1}", - logType, cluster.getClusterIdentifier()); + logType, target.identifier()); } } @@ -316,26 +331,26 @@ public class RedshiftAuditLogPublisher { return basePath + "AWSLogs/" + accountId + "/redshift/" + region + "/" + year + "/" + month + "/" + day + "/" + filename; } - private void publishS3(Cluster cluster, String accountId, String region, String logType, + private void publishS3(RedshiftAuditTarget target, String accountId, String region, String logType, Map record) { try { - String bucket = cluster.getLoggingBucketName(); + String bucket = target.bucketName(); 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 key = s3DeliveryKey(target.s3KeyPrefix(), accountId, region, + target.name(), logType, now); String partition = regionResolver != null ? regionResolver.partitionForRegion(region) : AwsRegions.partitionFor(region); String objectArn = S3ResourceArns.object(partition, bucket, key); - String clusterArn = AwsArnUtils.Arn.of("redshift", region, accountId, "cluster:" + cluster.getClusterIdentifier()).toString(); + String clusterArn = AwsArnUtils.Arn.of("redshift", region, accountId, target.arnResource()).toString(); Map> 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); + safeRecordOutcome(accountId, target.identifier(), target.loggingGeneration(), now, false, errorMsg); return; } @@ -347,20 +362,20 @@ public class RedshiftAuditLogPublisher { 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); + safeRecordOutcome(accountId, target.identifier(), target.loggingGeneration(), 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()); + logType, bucket, key, target.identifier()); String message = exception.getMessage() != null ? exception.getMessage() : "Failed to deliver log to S3"; - safeRecordOutcome(accountId, cluster.getClusterIdentifier(), cluster.getLoggingGeneration(), now, false, message); + safeRecordOutcome(accountId, target.identifier(), target.loggingGeneration(), 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()); + logType, bucket, key, target.identifier()); } } } catch (Exception unexpected) { LOG.errorv(unexpected, "Unexpected error delivering Redshift {0} audit event to S3 for cluster {1}", - logType, cluster.getClusterIdentifier()); + logType, target.identifier()); } } diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditTarget.java b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditTarget.java new file mode 100644 index 0000000000..5204bdb285 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditTarget.java @@ -0,0 +1,43 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.services.redshift.model.Cluster; + +import java.util.List; + +/** + * What the audit log publisher needs to know about the resource whose activity it records, so that it does not + * depend on the model of one kind of resource. + * + * @param identifier the identity the publisher registers the resource under and reports delivery outcomes for + * @param name the name used in log stream names and in the file names of delivered S3 objects + * @param logGroupPrefix the CloudWatch log group of a log type is {@code logGroupPrefix + "/" + logType} + * @param arnResource the resource part of the ARN a delivery to S3 is authorized as, after {@code redshift:::} + * @param enabled whether logging is on + * @param destinationType {@code cloudwatch} or {@code s3}; null with a bucket name means S3 + * @param bucketName the S3 bucket of an S3 delivery + * @param s3KeyPrefix the key prefix of an S3 delivery + * @param exports the log types delivered, or null for all of them + * @param activityLoggingEnabled whether the user activity log is on, which a log type of its own also needs + * @param loggingGeneration bumped whenever the logging configuration changes, so a late delivery outcome of an + * earlier configuration can be told apart + */ +public record RedshiftAuditTarget(String identifier, String name, String logGroupPrefix, String arnResource, + boolean enabled, String destinationType, String bucketName, String s3KeyPrefix, + List exports, boolean activityLoggingEnabled, long loggingGeneration) { + + public RedshiftAuditTarget { + exports = exports == null ? null : List.copyOf(exports); + } + + /** The target of a provisioned cluster, or null for no cluster. */ + public static RedshiftAuditTarget of(Cluster cluster) { + if (cluster == null) { + return null; + } + String identifier = cluster.getClusterIdentifier(); + return new RedshiftAuditTarget(identifier, identifier, "/aws/redshift/cluster/" + identifier, + "cluster:" + identifier, cluster.isLoggingEnabled(), cluster.getLoggingDestinationType(), + cluster.getLoggingBucketName(), cluster.getLoggingS3KeyPrefix(), cluster.getLoggingExports(), + cluster.isUserActivityLoggingEnabled(), cluster.getLoggingGeneration()); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisherTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisherTest.java index fe18ee0225..b7b63a3ce2 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisherTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisherTest.java @@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -54,6 +55,78 @@ import static org.mockito.Mockito.when; class RedshiftAuditLogPublisherTest { + private static RedshiftAuditTarget namespaceTarget(List exports) { + return new RedshiftAuditTarget("serverless_us-east-1_wg", "analytics", "/aws/redshift/analytics", + "namespace/analytics", true, "cloudwatch", null, null, exports, false, 1L); + } + + @Test + void aTargetNamesItsOwnLogGroupAndStream() { + CloudWatchLogsService logs = mock(CloudWatchLogsService.class); + RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs, + Clock.fixed(Instant.ofEpochMilli(1234), ZoneOffset.UTC)); + + publisher.publishConnection(namespaceTarget(null), "111111111111", "us-east-1", "dev", "admin", "authenticated", + "10.0.0.1", null); + + verify(logs).createLogGroupForAccount("111111111111", "/aws/redshift/analytics/connectionlog", null, Map.of(), + "us-east-1"); + verify(logs).createLogStreamForAccount("111111111111", "/aws/redshift/analytics/connectionlog", "analytics", + "us-east-1"); + verify(logs).putLogEventsForAccount(eq("111111111111"), eq("/aws/redshift/analytics/connectionlog"), + eq("analytics"), anyList(), eq("us-east-1")); + } + + @Test + void aRegisteredTargetPublishesOnlyItsSelectedExportsUnderItsIdentifier() { + CloudWatchLogsService logs = mock(CloudWatchLogsService.class); + RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs, Clock.systemUTC()); + publisher.register("111111111111", "us-east-1", namespaceTarget(List.of("userlog"))); + + publisher.publishRegisteredConnection("111111111111", "serverless_us-east-1_wg", "dev", "admin", "authenticated", + "10.0.0.1", 5439); + publisher.publishRegisteredUserChange("111111111111", "serverless_us-east-1_wg", "dev", "bob", "create", null); + publisher.unregister("111111111111", "serverless_us-east-1_wg"); + publisher.publishRegisteredUserChange("111111111111", "serverless_us-east-1_wg", "dev", "bob", "drop", null); + + verify(logs, never()).createLogGroupForAccount(anyString(), eq("/aws/redshift/analytics/connectionlog"), any(), + anyMap(), anyString()); + verify(logs, times(1)).putLogEventsForAccount(eq("111111111111"), eq("/aws/redshift/analytics/userlog"), + eq("analytics"), anyList(), eq("us-east-1")); + } + + @Test + void aClusterBecomesATargetWithTheClusterLogGroupAndArn() { + Cluster cluster = enabledCluster(List.of("userlog")); + cluster.setLoggingGeneration(7L); + + RedshiftAuditTarget target = RedshiftAuditTarget.of(cluster); + + assertEquals("analytics", target.identifier()); + assertEquals("analytics", target.name()); + assertEquals("/aws/redshift/cluster/analytics", target.logGroupPrefix()); + assertEquals("cluster:analytics", target.arnResource()); + assertEquals(List.of("userlog"), target.exports()); + assertEquals(7L, target.loggingGeneration()); + assertEquals(null, RedshiftAuditTarget.of(null)); + } + + @Test + void aClusterWithMalformedExportsNeverFailsThePublishOverloads() { + CloudWatchLogsService logs = mock(CloudWatchLogsService.class); + RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs); + Cluster cluster = enabledCluster(Arrays.asList("userlog", null)); + + assertDoesNotThrow(() -> { + publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "select 1"); + publisher.publishConnection(cluster, "111111111111", "us-east-1", "dev", "admin", "initiating session", + "127.0.0.1", null); + publisher.publishUserChange(cluster, "111111111111", "us-east-1", "dev", "admin", "create", null); + publisher.publish(cluster, "111111111111", "us-east-1", "userlog", Map.of()); + }); + verify(logs, never()).putLogEventsForAccount(anyString(), anyString(), anyString(), anyList(), anyString()); + } + @Test void createsAwsNamedResourcesAndWritesSelectedExport() { CloudWatchLogsService logs = mock(CloudWatchLogsService.class);