mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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,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