mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat: deliver Redshift audit logs to CloudWatch Logs (#6432)
* feat: deliver Redshift audit logs to CloudWatch Logs * fix: correct Redshift audit logging and account isolation * docs: remove Redshift audit logging design document * fix: reject transaction control in Redshift Data API batches * fix: track Redshift batch audit changes through savepoints * fix(redshift-data): guard explicit batch commits against cancellation * fix(redshift): preserve audit regions and redact ambiguous passwords
This commit is contained in:
1 parent
8f3a6eafeb
commit
b15bc708fa
25 files changed
+2014
-52
No files matched your search
+170
@@ -0,0 +1,170 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
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.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.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.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class RedshiftAuditLogPublisherTest {
|
||||
|
||||
@Test
|
||||
void createsAwsNamedResourcesAndWritesSelectedExport() {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs,
|
||||
Clock.fixed(Instant.ofEpochMilli(1234), ZoneOffset.UTC));
|
||||
Cluster cluster = enabledCluster(List.of("useractivitylog"));
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "select 1,2");
|
||||
|
||||
verify(logs).createLogGroupForAccount("111111111111",
|
||||
"/aws/redshift/cluster/analytics/useractivitylog", null, Map.of(), "us-east-1");
|
||||
verify(logs).createLogStreamForAccount("111111111111",
|
||||
"/aws/redshift/cluster/analytics/useractivitylog", "analytics", "us-east-1");
|
||||
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
|
||||
verify(logs).putLogEventsForAccount(eq("111111111111"),
|
||||
eq("/aws/redshift/cluster/analytics/useractivitylog"), eq("analytics"),
|
||||
events.capture(), eq("us-east-1"));
|
||||
assertEquals(1234L, events.getValue().get(0).get("timestamp"));
|
||||
assertEquals("1970-01-01T00:00:01.234Z,dev,admin,,,,\"LOG: select 1,2\"",
|
||||
events.getValue().get(0).get("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsUnselectedExportsAndNonCloudWatchDestinations() {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs, Clock.systemUTC());
|
||||
Cluster cluster = enabledCluster(List.of("connectionlog"));
|
||||
|
||||
publisher.publish(cluster, "111111111111", "us-east-1", "userlog", Map.of("action", "Create"));
|
||||
cluster.setLoggingDestinationType("s3");
|
||||
publisher.publish(cluster, "111111111111", "us-east-1", "connectionlog", Map.of("event", "connect"));
|
||||
|
||||
verify(logs, never()).putLogEventsForAccount(anyString(), anyString(), anyString(), anyList(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userActivityExportRequiresTheParameterGroupFlag() {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs, Clock.systemUTC());
|
||||
Cluster cluster = enabledCluster(List.of("useractivitylog"));
|
||||
|
||||
publisher.publishActivity(cluster, "111111111111", "us-east-1", "dev", "admin", "SELECT 1");
|
||||
|
||||
verify(logs, never()).putLogEventsForAccount(anyString(), anyString(), anyString(), anyList(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registeredConnectionsUseTheSharedCsvColumnLayout() {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs,
|
||||
Clock.fixed(Instant.ofEpochMilli(1234), ZoneOffset.UTC));
|
||||
publisher.register("111111111111", "us-west-2", enabledCluster(List.of("connectionlog")));
|
||||
|
||||
publisher.publishRegisteredConnection("111111111111", "analytics", "reports", "analyst", "authenticated",
|
||||
"192.0.2.1", 54321);
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
|
||||
verify(logs).putLogEventsForAccount(eq("111111111111"),
|
||||
eq("/aws/redshift/cluster/analytics/connectionlog"), eq("analytics"), events.capture(), eq("us-west-2"));
|
||||
String[] columns = events.getValue().getFirst().get("message").toString().split(",", -1);
|
||||
assertEquals(22, columns.length);
|
||||
assertEquals("authenticated", columns[0]);
|
||||
assertEquals("1970-01-01T00:00:01.234Z", columns[1]);
|
||||
assertEquals("192.0.2.1", columns[2]);
|
||||
assertEquals("54321", columns[3]);
|
||||
assertEquals("reports", columns[5]);
|
||||
assertEquals("analyst", columns[6]);
|
||||
assertEquals("password", columns[7]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudWatchFailureDoesNotEscapePublisher() {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
doThrow(new IllegalStateException("logs unavailable"))
|
||||
.when(logs).createLogGroupForAccount(anyString(), anyString(), isNull(), anyMap(), anyString());
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs, Clock.systemUTC());
|
||||
|
||||
assertDoesNotThrow(() -> publisher.publish(enabledCluster(List.of("userlog")),
|
||||
"111111111111", "us-east-1", "userlog", Map.of("action", "Create")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsSqlPasswordLiteralsFromActivityRecords() {
|
||||
assertEquals("ALTER USER alice PASSWORD '[REDACTED]'", RedshiftAuditLogPublisher.sanitizeSql(
|
||||
"ALTER USER alice PASSWORD 'top-secret'"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"ALTER USER alice PASSWORD /* rotation */ 'secret'",
|
||||
"ALTER USER alice PASSWORD -- rotation\n 'secret'",
|
||||
"ALTER USER alice PASSWORD /* outer /* nested */ comment */ 'secret'",
|
||||
"ALTER USER alice PASSWORD E'secret\\'suffix'",
|
||||
"ALTER USER alice PASSWORD $tag$secret$tag$",
|
||||
"ALTER USER alice PASSWORD 'first'\n 'secret'",
|
||||
"ALTER USER alice PASSWORD U&'secret'",
|
||||
"ALTER USER alice PASSWORD N'secret'"
|
||||
})
|
||||
void redactsCompletePasswordsAfterSqlComments(String sql) {
|
||||
String sanitized = RedshiftAuditLogPublisher.sanitizeSql(sql);
|
||||
assertFalse(sanitized.contains("secret"), sanitized);
|
||||
assertFalse(sanitized.contains("suffix"), sanitized);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"ALTER USER alice PASSWORD 'prefix\\'suffix'",
|
||||
"SET standard_conforming_strings=off; ALTER USER alice PASSWORD 'prefix\\'suffix'",
|
||||
"ALTER USER alice PASSWORD N'prefix\\'suffix'",
|
||||
"ALTER USER alice PASSWORD 'first'\n 'prefix\\'suffix'",
|
||||
"ALTER USER alice PASSWORD 'prefix\\'suffix'; ALTER USER bob PASSWORD 'anothersecret'",
|
||||
"SELECT 'path\\'tail'; ALTER USER alice PASSWORD 'anothersecret'",
|
||||
"SELECT 'path\\'; ALTER USER alice PASSWORD 'anothersecret'"
|
||||
})
|
||||
void redactsPasswordsWithUncertainBackslashBoundaries(String sql) {
|
||||
String sanitized = RedshiftAuditLogPublisher.sanitizeSql(sql);
|
||||
assertFalse(sanitized.contains("prefix"), sanitized);
|
||||
assertFalse(sanitized.contains("suffix"), sanitized);
|
||||
assertFalse(sanitized.contains("first"), sanitized);
|
||||
assertFalse(sanitized.contains("anothersecret"), sanitized);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitEscapeStringsRetainFollowingSqlAndOtherBackslashStringsRemainVisible() {
|
||||
assertEquals("ALTER USER alice PASSWORD '[REDACTED]'; SELECT 1", RedshiftAuditLogPublisher.sanitizeSql(
|
||||
"ALTER USER alice PASSWORD E'prefix\\'suffix'; SELECT 1"));
|
||||
String sql = "SELECT 'C:\\reports\\daily'";
|
||||
assertEquals(sql, RedshiftAuditLogPublisher.sanitizeSql(sql));
|
||||
}
|
||||
|
||||
private static Cluster enabledCluster(List<String> exports) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("analytics");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingDestinationType("cloudwatch");
|
||||
cluster.setLoggingExports(exports);
|
||||
return cluster;
|
||||
}
|
||||
}
|
||||
+73
-4
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbApiStreamReader;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
@@ -68,6 +69,72 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftServiceTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void loggingDestinationRegionSurvivesStorageAndRestart(boolean refresh) throws Exception {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("warehouse");
|
||||
cluster.setClusterStatus("available");
|
||||
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
RedshiftService original = new RedshiftService(sf, cm, config,
|
||||
new RegionResolver("us-west-2", "111111111111"), proxyManager, dockerHostResolver,
|
||||
credentialBroker, secretsManagerService, mapper, null, null);
|
||||
original.enableLogging("warehouse", null, null, "cloudwatch", List.of("connectionlog"));
|
||||
|
||||
Cluster restored = mapper.readValue(mapper.writeValueAsBytes(cluster), Cluster.class);
|
||||
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(restored));
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "warehouse", restored)));
|
||||
when(cm.getContainer("111111111111", "warehouse")).thenReturn(Optional.of(
|
||||
new RedshiftContainerHandle("container", "warehouse", "localhost", 5432)));
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
RedshiftAuditLogPublisher publisher = new RedshiftAuditLogPublisher(logs);
|
||||
RedshiftService restarted = new RedshiftService(sf, cm, config, regionResolver,
|
||||
proxyManager, dockerHostResolver, credentialBroker, secretsManagerService, mapper, null, publisher);
|
||||
|
||||
restarted.onStart(null);
|
||||
if (refresh) {
|
||||
restarted.modifyClusterIamRoles("warehouse", List.of(), List.of());
|
||||
}
|
||||
publisher.publishRegisteredConnection("111111111111", "warehouse", "dev", "alice",
|
||||
"authenticated", "192.0.2.1", 54321);
|
||||
|
||||
verify(logs).putLogEventsForAccount(eq("111111111111"),
|
||||
eq("/aws/redshift/cluster/warehouse/connectionlog"), eq("warehouse"), anyList(), eq("us-west-2"));
|
||||
verify(logs, never()).createLogGroupForAccount(anyString(), anyString(), any(), anyMap(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void activityParameterUpdatesStayWithinTheCallingAccount(boolean reset) {
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("shared", "redshift-1.0", "audit");
|
||||
when(parameterGroupBackend.get("shared")).thenReturn(Optional.of(group));
|
||||
Cluster owned = new Cluster();
|
||||
owned.setClusterIdentifier("owned");
|
||||
owned.setClusterParameterGroupName("shared");
|
||||
owned.setUserActivityLoggingEnabled(reset);
|
||||
Cluster foreign = new Cluster();
|
||||
foreign.setClusterIdentifier("foreign");
|
||||
foreign.setClusterParameterGroupName("shared");
|
||||
foreign.setUserActivityLoggingEnabled(reset);
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "owned", owned),
|
||||
new AccountAwareStorageBackend.AccountEntry<>("222222222222", "foreign", foreign)));
|
||||
when(clusterBackend.scan(any())).thenReturn(List.of(owned));
|
||||
|
||||
if (reset) {
|
||||
service.resetClusterParameterGroup("shared", true, List.of());
|
||||
} else {
|
||||
service.modifyClusterParameterGroup("shared", List.of(new Parameter("enable_user_activity_logging", "true")));
|
||||
}
|
||||
|
||||
assertEquals(!reset, owned.isUserActivityLoggingEnabled());
|
||||
assertEquals(reset, foreign.isUserActivityLoggingEnabled());
|
||||
verify(clusterBackend, never()).putForAccount(eq("222222222222"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryProxyFailureDoesNotDestructivelyStopAnAdoptedContainer() {
|
||||
Cluster cluster = new Cluster();
|
||||
@@ -1942,8 +2009,9 @@ class RedshiftServiceTest {
|
||||
assertEquals("0", parameters.get(0).getParameterValue());
|
||||
assertEquals("engine-default", parameters.get(0).getSource());
|
||||
assertEquals("integer", parameters.get(0).getDataType());
|
||||
assertEquals("custom", parameters.get(1).getParameterValue());
|
||||
assertEquals("user", parameters.get(1).getSource());
|
||||
assertEquals("false", parameters.get(1).getParameterValue());
|
||||
assertEquals("custom", parameters.get(2).getParameterValue());
|
||||
assertEquals("user", parameters.get(2).getSource());
|
||||
verify(parameterGroupBackend, times(2)).flush();
|
||||
}
|
||||
|
||||
@@ -1958,9 +2026,10 @@ class RedshiftServiceTest {
|
||||
service.resetClusterParameterGroup("reset-pg", true, List.of());
|
||||
|
||||
List<Parameter> parameters = service.describeClusterParameters("reset-pg");
|
||||
assertEquals(2, parameters.size());
|
||||
assertEquals(3, parameters.size());
|
||||
assertEquals("0", parameters.get(0).getParameterValue());
|
||||
assertEquals("{}", parameters.get(1).getParameterValue());
|
||||
assertEquals("false", parameters.get(1).getParameterValue());
|
||||
assertEquals("{}", parameters.get(2).getParameterValue());
|
||||
assertTrue(parameters.stream().allMatch(parameter -> "engine-default".equals(parameter.getSource())));
|
||||
assertEquals("analytics", group.getTags().get("owner"));
|
||||
assertEquals("description", group.getDescription());
|
||||
|
||||
+64
-1
@@ -1,11 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.PostgresWire;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testutil.FreePorts;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -22,6 +24,8 @@ import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -30,10 +34,69 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftAuthProxyTest {
|
||||
|
||||
@Test
|
||||
void failedLoginAuditsTheRequestedUserAndDatabase() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", 1, "admin", "password", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.REJECT,
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
|
||||
proxy.start(port);
|
||||
try (Socket client = new Socket("localhost", port)) {
|
||||
client.setSoTimeout(5000);
|
||||
client.getOutputStream().write(PostgresWire.startupMessage(Map.of("user", "analyst", "database", "analytics")));
|
||||
client.getOutputStream().flush();
|
||||
assertEquals(9, client.getInputStream().readNBytes(9).length);
|
||||
PostgresWire.write(client.getOutputStream(), 'p', "bad\0".getBytes(StandardCharsets.UTF_8));
|
||||
client.getOutputStream().flush();
|
||||
assertEquals('E', client.getInputStream().read());
|
||||
verify(audit, timeout(2000)).publishRegisteredConnection(eq("111111111111"), eq("c1"), eq("analytics"),
|
||||
eq("analyst"), eq("authentication failure"), anyString(), anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulLoginAndActivityUseTheRequestedIdentity() throws Exception {
|
||||
fakeBackend = new ServerSocket(0);
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try (Socket backend = fakeBackend.accept()) {
|
||||
PostgresWire.readStartup(backend.getInputStream(), 10000, "startup");
|
||||
PostgresWire.write(backend.getOutputStream(), 'R', new byte[4]);
|
||||
PostgresWire.write(backend.getOutputStream(), 'Z', new byte[]{'I'});
|
||||
backend.getOutputStream().flush();
|
||||
PostgresWire.read(backend.getInputStream(), 10000, "query");
|
||||
} catch (IOException expected) {
|
||||
// Closing the test sockets ends the fake server.
|
||||
}
|
||||
});
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "password", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
|
||||
proxy.start(port);
|
||||
try (Socket client = new Socket("localhost", port)) {
|
||||
client.setSoTimeout(5000);
|
||||
client.getOutputStream().write(PostgresWire.startupMessage(Map.of("user", "analyst", "database", "analytics")));
|
||||
client.getOutputStream().flush();
|
||||
assertEquals(9, client.getInputStream().readNBytes(9).length);
|
||||
PostgresWire.write(client.getOutputStream(), 'p', "password\0".getBytes(StandardCharsets.UTF_8));
|
||||
client.getOutputStream().flush();
|
||||
assertEquals('R', PostgresWire.read(client.getInputStream(), 10000, "authenticated").type());
|
||||
assertEquals('Z', PostgresWire.read(client.getInputStream(), 10000, "ready").type());
|
||||
PostgresWire.write(client.getOutputStream(), 'Q', "SELECT 1\0".getBytes(StandardCharsets.UTF_8));
|
||||
client.getOutputStream().flush();
|
||||
verify(audit, timeout(2000)).publishRegisteredActivity("111111111111", "c1", "analytics", "analyst", "SELECT 1");
|
||||
verify(audit, timeout(2000)).publishRegisteredConnection(eq("111111111111"), eq("c1"), eq("analytics"),
|
||||
eq("analyst"), eq("authenticated"), anyString(), anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
|
||||
+142
-1
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
|
||||
@@ -29,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftInterceptingBridgeTest {
|
||||
|
||||
@@ -61,6 +63,10 @@ class RedshiftInterceptingBridgeTest {
|
||||
}
|
||||
|
||||
private void startBridge(SpectrumInterceptor spectrumInterceptor) throws IOException {
|
||||
startBridge(spectrumInterceptor, null);
|
||||
}
|
||||
|
||||
private void startBridge(SpectrumInterceptor spectrumInterceptor, RedshiftAuditLogPublisher audit) throws IOException {
|
||||
clientListener = new ServerSocket(0);
|
||||
testClientEnd = new Socket("localhost", clientListener.getLocalPort());
|
||||
bridgeClientEnd = clientListener.accept();
|
||||
@@ -72,10 +78,145 @@ class RedshiftInterceptingBridgeTest {
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
|
||||
spectrumInterceptor, "000000000000:c", "dev");
|
||||
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst");
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void multiCommandQueryLogsEveryCommittedUserChange() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
sendAuditQuery("SELECT ';'; /* migration */ CREATE USER alice; ALTER USER alice RENAME TO bob",
|
||||
"SELECT 1", "CREATE ROLE", "ALTER ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "alice", "Create", null);
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "bob", "Rename", "alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void emptyAndFailedQueriesDoNotMislabelLaterUserChanges() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("; -- empty"));
|
||||
nextForwarded();
|
||||
testBackendEnd.getOutputStream().write(concat(frame('I', new byte[0]), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
sendAuditQuery("SELECT broken; CREATE USER skipped", new String[0]);
|
||||
sendAuditQuery("CREATE USER actual", "CREATE ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "actual", "Create", null);
|
||||
verify(audit, never()).publishRegisteredUserChange(anyString(), anyString(), anyString(), eq("skipped"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void implicitTransactionFailureDiscardsEarlierSuccessfulUserChanges() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("CREATE USER rolledback; SELECT broken"));
|
||||
nextForwarded();
|
||||
testBackendEnd.getOutputStream().write(concat(frame('C', cString("CREATE ROLE")),
|
||||
frame('E', cString("failed")), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
sendAuditQuery("CREATE USER actual", "CREATE ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "actual", "Create", null);
|
||||
verify(audit, never()).publishRegisteredUserChange(anyString(), anyString(), anyString(), eq("rolledback"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void rollbackInsideAMultiCommandQueryDoesNotPublishDiscardedChanges() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
sendAuditQuery("BEGIN; CREATE USER rolledback; ROLLBACK; CREATE USER actual",
|
||||
"BEGIN", "CREATE ROLE", "ROLLBACK", "CREATE ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "actual", "Create", null);
|
||||
verify(audit, never()).publishRegisteredUserChange(anyString(), anyString(), anyString(), eq("rolledback"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void rollbackToSavepointPreservesOnlyEarlierUserChanges() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
sendAuditQuery("BEGIN; CREATE USER kept; SAVEPOINT s; CREATE USER rolledback; ROLLBACK TO s; COMMIT",
|
||||
"BEGIN", "CREATE ROLE", "SAVEPOINT", "CREATE ROLE", "ROLLBACK", "COMMIT");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "kept", "Create", null);
|
||||
verify(audit, never()).publishRegisteredUserChange(anyString(), anyString(), anyString(), eq("rolledback"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void suspendedPortalsDoNotConsumeLaterUserChangeCompletions() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
|
||||
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage("select", "SELECT 1", List.of());
|
||||
pipeline.write(PostgresWireDecoder.encodeParse(parse, parse.sql()));
|
||||
pipeline.write(frame('B', concat(cString("portal"), cString("select"), new byte[6])));
|
||||
pipeline.write(frame('E', concat(cString("portal"), new byte[]{0, 0, 0, 1})));
|
||||
pipeline.write(frame('E', concat(cString("portal"), new byte[4])));
|
||||
pipeline.write(frame('S', new byte[0]));
|
||||
testClientEnd.getOutputStream().write(pipeline.toByteArray());
|
||||
testClientEnd.getOutputStream().flush();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
nextForwarded();
|
||||
}
|
||||
testBackendEnd.getOutputStream().write(concat(frame('1', new byte[0]), frame('2', new byte[0]),
|
||||
frame('s', new byte[0]), frame('C', cString("SELECT 1")), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
sendAuditQuery("CREATE USER actual", "CREATE ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "actual", "Create", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void rejectedNamedParseDoesNotReplaceTheSqlUsedForUserAudit() throws Exception {
|
||||
RedshiftAuditLogPublisher audit = mock(RedshiftAuditLogPublisher.class);
|
||||
startBridge(null, audit);
|
||||
PostgresWireDecoder.ParseMessage original = new PostgresWireDecoder.ParseMessage("s", "SELECT 1", List.of());
|
||||
testClientEnd.getOutputStream().write(concat(PostgresWireDecoder.encodeParse(original, original.sql()), frame('S', new byte[0])));
|
||||
nextForwarded();
|
||||
nextForwarded();
|
||||
testBackendEnd.getOutputStream().write(concat(frame('1', new byte[0]), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
PostgresWireDecoder replies = new PostgresWireDecoder(testClientEnd.getInputStream());
|
||||
assertEquals('1', replies.nextMessage().type());
|
||||
assertEquals('Z', replies.nextMessage().type());
|
||||
PostgresWireDecoder.ParseMessage rejected = new PostgresWireDecoder.ParseMessage("s", "CREATE USER phantom", List.of());
|
||||
testClientEnd.getOutputStream().write(concat(PostgresWireDecoder.encodeParse(rejected, rejected.sql()), frame('S', new byte[0])));
|
||||
nextForwarded();
|
||||
nextForwarded();
|
||||
testBackendEnd.getOutputStream().write(concat(frame('E', cString("duplicate name")), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
assertEquals('E', replies.nextMessage().type());
|
||||
assertEquals('Z', replies.nextMessage().type());
|
||||
testClientEnd.getOutputStream().write(concat(frame('B', concat(cString("p"), cString("s"), new byte[6])),
|
||||
frame('E', concat(cString("p"), new byte[4])), frame('S', new byte[0])));
|
||||
for (int i = 0; i < 3; i++) {
|
||||
nextForwarded();
|
||||
}
|
||||
testBackendEnd.getOutputStream().write(concat(frame('2', new byte[0]), frame('C', cString("SELECT 1")), frame('Z', new byte[]{'I'})));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
sendAuditQuery("CREATE USER actual", "CREATE ROLE");
|
||||
verify(audit, timeout(2000)).publishRegisteredUserChange("000000000000", "c", "dev", "actual", "Create", null);
|
||||
verify(audit, never()).publishRegisteredUserChange(anyString(), anyString(), anyString(), eq("phantom"), anyString(), any());
|
||||
}
|
||||
|
||||
private void sendAuditQuery(String sql, String... tags) throws IOException {
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery(sql));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
nextForwarded();
|
||||
for (String tag : tags) {
|
||||
testBackendEnd.getOutputStream().write(frame('C', cString(tag)));
|
||||
}
|
||||
if (tags.length == 0) {
|
||||
testBackendEnd.getOutputStream().write(frame('E', cString("failed")));
|
||||
}
|
||||
testBackendEnd.getOutputStream().write(frame('Z', new byte[]{'I'}));
|
||||
testBackendEnd.getOutputStream().flush();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
for (Socket s : new Socket[]{testClientEnd, bridgeClientEnd, bridgeBackendEnd, testBackendEnd}) {
|
||||
|
||||
+64
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -16,6 +17,8 @@ import org.junit.jupiter.api.TestInstance;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest;
|
||||
import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementResponse;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.ResourceNotFoundException;
|
||||
@@ -23,11 +26,13 @@ import software.amazon.awssdk.services.redshiftdata.model.ResourceNotFoundExcept
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -128,6 +133,65 @@ class RedshiftDataApiIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkExecuteStatementPublishesUserActivityToCloudWatchLogs() {
|
||||
String parameterGroup = "it-rs-audit-" + clusterId;
|
||||
redshift.createClusterParameterGroup(parameterGroup, "redshift-1.0", "Audit logging integration test");
|
||||
redshift.modifyClusterParameterGroup(parameterGroup,
|
||||
List.of(new Parameter("enable_user_activity_logging", "true")));
|
||||
redshift.modifyCluster(clusterId, null, null, null, parameterGroup, null);
|
||||
redshift.enableLogging(clusterId, null, null, "cloudwatch", List.of("useractivitylog"));
|
||||
String group = "/aws/redshift/cluster/" + clusterId + "/useractivitylog";
|
||||
|
||||
try (RedshiftDataClient data = RedshiftDataClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build();
|
||||
CloudWatchLogsClient logs = CloudWatchLogsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build()) {
|
||||
String statementId = data.executeStatement(request -> request.clusterIdentifier(clusterId)
|
||||
.dbUser("admin").database("dev").sql("SELECT 741")).id();
|
||||
awaitFinished(statementId);
|
||||
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).pollInterval(Duration.ofMillis(100)).until(() ->
|
||||
logs.getLogEvents(GetLogEventsRequest.builder().logGroupName(group).logStreamName(clusterId).build())
|
||||
.events().stream().anyMatch(event -> event.message().contains("LOG: SELECT 741")));
|
||||
} finally {
|
||||
redshift.disableLogging(clusterId);
|
||||
redshift.modifyCluster(clusterId, null, null, null,
|
||||
"default.redshift-1.0", null);
|
||||
redshift.deleteClusterParameterGroup(parameterGroup);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkBatchSavepointRollbackOmitsTheRolledBackUserFromCloudWatchLogs() {
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "");
|
||||
String kept = "audit_kept_" + suffix;
|
||||
String discarded = "audit_discarded_" + suffix;
|
||||
String group = "/aws/redshift/cluster/" + clusterId + "/userlog";
|
||||
redshift.enableLogging(clusterId, null, null, "cloudwatch", List.of("userlog"));
|
||||
try (RedshiftDataClient data = RedshiftDataClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build();
|
||||
CloudWatchLogsClient logs = CloudWatchLogsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build()) {
|
||||
String batch = data.batchExecuteStatement(request -> request.clusterIdentifier(clusterId)
|
||||
.dbUser("admin").database("dev").sqls("CREATE USER " + kept + " PASSWORD 'Secret123'",
|
||||
"SAVEPOINT s; CREATE USER " + discarded + " PASSWORD 'Secret123'; ROLLBACK TO s")).id();
|
||||
awaitFinished(batch);
|
||||
String query = data.executeStatement(request -> request.clusterIdentifier(clusterId).dbUser("admin")
|
||||
.database("dev").sql("SELECT COUNT(*) FROM pg_user WHERE usename = '" + discarded + "'")).id();
|
||||
awaitFinished(query);
|
||||
assertEquals(0L, data.getStatementResult(request -> request.id(query)).records().getFirst().getFirst().longValue());
|
||||
List<String> messages = logs.getLogEvents(GetLogEventsRequest.builder().logGroupName(group)
|
||||
.logStreamName(clusterId).build()).events().stream().map(event -> event.message()).toList();
|
||||
assertTrue(messages.stream().anyMatch(message -> message.contains("," + kept + ",,Create,")));
|
||||
assertFalse(messages.stream().anyMatch(message -> message.contains("," + discarded + ",")));
|
||||
} finally {
|
||||
redshift.disableLogging(clusterId);
|
||||
executeAndWait("DROP USER IF EXISTS " + kept);
|
||||
executeAndWait("DROP USER IF EXISTS " + discarded);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumPreservesAutoCommitExecution() {
|
||||
executeAndWait("VACUUM");
|
||||
|
||||
+384
@@ -0,0 +1,384 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.h2.Driver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataAuditTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"COMMIT,false", "END,false", "COMMIT,true", "END,true",
|
||||
"/* outer /* inner */ comment */ COMMIT WORK,true"})
|
||||
void explicitBatchCommitRejectsCancellationDuringAndAfterCommit(String command, boolean sameEntry) throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = fixture.mockSuccessfulBackend();
|
||||
PreparedStatement create = mock(PreparedStatement.class);
|
||||
PreparedStatement commit = mock(PreparedStatement.class);
|
||||
PreparedStatement tail = mock(PreparedStatement.class);
|
||||
CountDownLatch committing = new CountDownLatch(1);
|
||||
CountDownLatch releaseCommit = new CountDownLatch(1);
|
||||
CountDownLatch runningTail = new CountDownLatch(1);
|
||||
CountDownLatch releaseTail = new CountDownLatch(1);
|
||||
when(connection.prepareStatement(anyString())).thenAnswer(invocation -> {
|
||||
String sql = invocation.getArgument(0);
|
||||
return sql.contains("CREATE USER") ? create : sql.contains("SELECT") ? tail : commit;
|
||||
});
|
||||
when(commit.execute()).thenAnswer(invocation -> {
|
||||
committing.countDown();
|
||||
assertTrue(releaseCommit.await(5, TimeUnit.SECONDS));
|
||||
return false;
|
||||
});
|
||||
when(tail.execute()).thenAnswer(invocation -> {
|
||||
runningTail.countDown();
|
||||
assertTrue(releaseTail.await(5, TimeUnit.SECONDS));
|
||||
return false;
|
||||
});
|
||||
ObjectNode request = fixture.request("unused");
|
||||
request.remove("WaitTimeSeconds");
|
||||
ArrayNode sqls = request.putArray("Sqls").add("CREATE USER alice");
|
||||
if (sameEntry) {
|
||||
sqls.add(command + "; SELECT 1");
|
||||
} else {
|
||||
sqls.add(command).add("SELECT 1");
|
||||
}
|
||||
String id = fixture.service.batchExecuteStatement(request, "us-east-1").path("Id").asText();
|
||||
ObjectNode identifier = fixture.mapper.createObjectNode().put("Id", id);
|
||||
try {
|
||||
assertTrue(committing.await(5, TimeUnit.SECONDS));
|
||||
assertFalse(fixture.service.cancelStatement(identifier).path("Status").asBoolean(),
|
||||
"cancellation must be rejected while an explicit commit is running");
|
||||
releaseCommit.countDown();
|
||||
assertTrue(runningTail.await(5, TimeUnit.SECONDS));
|
||||
assertFalse(fixture.service.cancelStatement(identifier).path("Status").asBoolean(),
|
||||
"cancellation must be rejected after an explicit commit succeeds");
|
||||
} finally {
|
||||
releaseCommit.countDown();
|
||||
releaseTail.countDown();
|
||||
}
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
|
||||
assertEquals("FINISHED", fixture.service.describeStatement(identifier).path("Status").asText()));
|
||||
assertEquals(List.of("alice"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void commentedUserDdlProducesUserAndActivityRecords() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.execute("/* migration */ CREATE /* change */ USER alice PASSWORD 'secret'");
|
||||
assertTrue(fixture.records("userlog").stream().anyMatch(line -> line.contains(",alice,,Create,")),
|
||||
fixture.events.toString());
|
||||
assertTrue(fixture.records("useractivitylog").stream().allMatch(line -> !line.contains("secret")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchPublishesAttemptedSqlAndUserChangesOnlyAfterCommit() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.batch("CREATE USER alice PASSWORD 'secret'", "SELECT 1");
|
||||
assertEquals(2, fixture.records("useractivitylog").size());
|
||||
assertEquals(1, fixture.records("userlog").size());
|
||||
fixture.events.clear();
|
||||
|
||||
fixture.batch("CREATE USER bob PASSWORD 'secret'", "SELECT * FROM missing", "SELECT 3");
|
||||
assertEquals(2, fixture.records("useractivitylog").size());
|
||||
assertTrue(fixture.records("userlog").isEmpty(), fixture.events.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchSavepointRollbackDoesNotLogDiscardedUsers() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
fixture.assertFinished(fixture.batch("SAVEPOINT s", "CREATE USER bob PASSWORD 'secret'", "ROLLBACK TO s"));
|
||||
assertTrue(fixture.records("userlog").isEmpty());
|
||||
assertEquals(3, fixture.records("useractivitylog").size());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"ROLLBACK TO s", "ROLLBACK WORK TO SAVEPOINT s", "-- comment\r rOlLbAcK To s"
|
||||
})
|
||||
void batchSavepointRollbackPreservesEarlierChanges(String rollback) throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
fixture.assertFinished(fixture.batch("CREATE USER kept", "SAVEPOINT s", "CREATE USER discarded", rollback));
|
||||
assertEquals(List.of("kept"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchTracksNestedRepeatedAndReleasedSavepointsInsideOneEntry() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = fixture.mockSuccessfulBackend();
|
||||
String sql = "; CREATE USER kept; SAVEPOINT s; CREATE USER discarded; SAVEPOINT s; CREATE USER nested; "
|
||||
+ "ROLLBACK TO s; RELEASE SAVEPOINT s; ROLLBACK TO s; "
|
||||
+ "CREATE USER repeated; ROLLBACK TO s; CREATE USER after_rollback";
|
||||
ObjectNode response = fixture.batch(sql);
|
||||
fixture.assertFinished(response);
|
||||
assertEquals(List.of("kept", "after_rollback"), fixture.loggedUsers());
|
||||
verify(connection).prepareStatement(" CREATE USER kept");
|
||||
assertEquals(sql, fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", response.path("Id").asText())).path("SubStatements").get(0).path("QueryString").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasingSavepointRetainsChangesForTheFinalCommit() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
fixture.assertFinished(fixture.batch("SAVEPOINT s", "CREATE USER kept", "RELEASE s"));
|
||||
assertEquals(List.of("kept"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ROLLBACK", "ABORT"})
|
||||
void batchRollbackDiscardsOnlyChangesSinceTheLastCommit(String rollback) throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
fixture.assertFinished(fixture.batch("CREATE USER committed", "COMMIT", "CREATE USER discarded",
|
||||
rollback, "CREATE USER final_commit"));
|
||||
assertEquals(List.of("committed", "final_commit"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBatchStillLogsChangesCommittedByAnEarlierStatement() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = fixture.mockSuccessfulBackend();
|
||||
when(connection.prepareStatement("SELECT broken")).thenThrow(new SQLException("broken", "42P01"));
|
||||
ObjectNode response = fixture.batch("CREATE USER committed", "END", "CREATE USER discarded", "SELECT broken");
|
||||
assertEquals("FAILED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", response.path("Id").asText())).path("Status").asText());
|
||||
assertEquals(List.of("committed"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitBeforeAnErrorInsideTheSameEntryRetainsCommittedAuditRecords() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = fixture.mockSuccessfulBackend();
|
||||
when(connection.prepareStatement(" SELECT broken")).thenThrow(new SQLException("broken", "42P01"));
|
||||
ObjectNode response = fixture.batch("CREATE USER committed", "COMMIT; SELECT broken");
|
||||
assertEquals("FAILED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", response.path("Id").asText())).path("Status").asText());
|
||||
assertEquals(List.of("committed"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchSavepointRollbackRetainsPendingChangesFromTheSession() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
String session = fixture.service.executeStatement(fixture.request("BEGIN")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.reuse(session, "CREATE USER kept");
|
||||
ObjectNode request = fixture.mapper.createObjectNode().put("SessionId", session).put("WaitTimeSeconds", 5);
|
||||
request.putArray("Sqls").add("SAVEPOINT s").add("CREATE USER discarded").add("ROLLBACK TO s");
|
||||
fixture.assertFinished(fixture.service.batchExecuteStatement(request, "us-east-1"));
|
||||
assertEquals(List.of("kept"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchRollbackCanUseSavepointCreatedByAnEarlierSessionStatement() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.mockSuccessfulBackend();
|
||||
String session = fixture.service.executeStatement(fixture.request("BEGIN")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.reuse(session, "CREATE USER kept");
|
||||
fixture.reuse(session, "SAVEPOINT s");
|
||||
fixture.reuse(session, "CREATE USER discarded");
|
||||
ObjectNode request = fixture.mapper.createObjectNode().put("SessionId", session).put("WaitTimeSeconds", 5);
|
||||
request.putArray("Sqls").add("ROLLBACK TO s");
|
||||
fixture.assertFinished(fixture.service.batchExecuteStatement(request, "us-east-1"));
|
||||
assertEquals(List.of("kept"), fixture.loggedUsers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionKeywordsInsideCommentsAndLiteralsDoNotRejectBatch() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
ObjectNode response = fixture.batch("/* ROLLBACK */ SELECT 'SAVEPOINT s; COMMIT'", "SELECT 2");
|
||||
ObjectNode description = fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", response.path("Id").asText()));
|
||||
assertEquals("FINISHED", description.path("Status").asText(), description.toString());
|
||||
assertEquals(2, fixture.records("useractivitylog").size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedSessionPublishesUserChangesOnCommitAndDiscardsThemOnRollback() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("BEGIN")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.reuse(session, "CREATE USER alice PASSWORD 'secret'");
|
||||
assertTrue(fixture.records("userlog").isEmpty());
|
||||
fixture.reuse(session, "COMMIT");
|
||||
assertEquals(1, fixture.records("userlog").size(), fixture.events.toString());
|
||||
fixture.events.clear();
|
||||
fixture.reuse(session, "BEGIN");
|
||||
fixture.reuse(session, "CREATE USER bob PASSWORD 'secret'");
|
||||
fixture.reuse(session, "ROLLBACK");
|
||||
assertTrue(fixture.records("userlog").isEmpty());
|
||||
fixture.reuse(session, "BEGIN");
|
||||
fixture.reuse(session, "CREATE USER carol PASSWORD 'secret'");
|
||||
fixture.reuse(session, "SELECT * FROM missing");
|
||||
fixture.reuse(session, "COMMIT");
|
||||
assertTrue(fixture.records("userlog").isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedConnectionLogsAuthenticationOnceAndDisconnectionWhenRetired() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.reuse(session, "SELECT 2");
|
||||
assertEquals(1, fixture.records("connectionlog").size(), fixture.events.toString());
|
||||
assertTrue(fixture.records("connectionlog").getFirst().startsWith("authenticated,"));
|
||||
fixture.service.clear();
|
||||
assertEquals(2, fixture.records("connectionlog").size());
|
||||
assertTrue(fixture.records("connectionlog").getLast().startsWith("disconnection,"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackendAuthenticationProducesAConnectionRecord() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
when(fixture.factory.open(any())).thenThrow(new SQLException("bad password", "28P01"));
|
||||
fixture.execute("SELECT 1");
|
||||
assertEquals(1, fixture.records("connectionlog").size());
|
||||
assertTrue(fixture.records("connectionlog").getFirst().startsWith("authentication failure,"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void activityAndConnectionRecordsUseRequestedIdentityInsteadOfBackendCredentials() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
fixture.execute("SELECT 1");
|
||||
assertTrue(fixture.records("useractivitylog").getFirst().contains(",analytics,analyst,"));
|
||||
assertTrue(fixture.records("connectionlog").stream().allMatch(line -> line.contains(",analytics,analyst,")));
|
||||
}
|
||||
}
|
||||
|
||||
private record Event(String group, String message) { }
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<Event> events = new CopyOnWriteArrayList<>();
|
||||
private final RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
private final RedshiftDataExecutor executor = new RedshiftDataExecutor(2, 8, 1);
|
||||
private final RedshiftDataService service;
|
||||
private final Connection keeper;
|
||||
|
||||
private Fixture() throws Exception {
|
||||
Driver.load();
|
||||
String url = "jdbc:h2:mem:" + UUID.randomUUID();
|
||||
keeper = DriverManager.getConnection(url);
|
||||
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(url));
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("warehouse");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingDestinationType("cloudwatch");
|
||||
cluster.setUserActivityLoggingEnabled(true);
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:warehouse", "localhost", 5439,
|
||||
"analytics", "admin", "password", null, cluster, "analyst"));
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
doAnswer(invocation -> {
|
||||
List<Map<String, Object>> records = invocation.getArgument(3);
|
||||
for (Map<String, Object> record : records) {
|
||||
events.add(new Event(invocation.getArgument(1), record.get("message").toString()));
|
||||
}
|
||||
return null;
|
||||
}).when(logs).putLogEventsForAccount(anyString(), anyString(), anyString(), anyList(), anyString());
|
||||
service = new RedshiftDataService(resolver, factory, new RedshiftDataStatementStore(24, Clock.systemUTC()),
|
||||
mapper, null, executor, null, null, null,
|
||||
new RedshiftDataIdempotencyStore(AccountAwareStorageBackend.inMemory("000000000000"), Clock.systemUTC()),
|
||||
new RedshiftDataSessions(), new RedshiftAuditLogPublisher(logs));
|
||||
}
|
||||
|
||||
private List<String> records(String type) {
|
||||
return events.stream().filter(event -> event.group().endsWith("/" + type)).map(Event::message).toList();
|
||||
}
|
||||
|
||||
private List<String> loggedUsers() {
|
||||
return records("userlog").stream().map(line -> line.split(",", -1)[1]).toList();
|
||||
}
|
||||
|
||||
private Connection mockSuccessfulBackend() throws SQLException {
|
||||
// H2 user DDL implicitly commits; model successful PostgreSQL responses for transaction audit tests.
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
when(connection.prepareStatement(anyString())).thenReturn(statement);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
return connection;
|
||||
}
|
||||
|
||||
private void assertFinished(ObjectNode response) {
|
||||
ObjectNode described = service.describeStatement(mapper.createObjectNode().put("Id", response.path("Id").asText()));
|
||||
assertEquals("FINISHED", described.path("Status").asText(), described.toString());
|
||||
}
|
||||
|
||||
private ObjectNode request(String sql) {
|
||||
return mapper.createObjectNode().put("Sql", sql).put("WaitTimeSeconds", 5)
|
||||
.put("ClusterIdentifier", "warehouse").put("Database", "analytics").put("DbUser", "analyst");
|
||||
}
|
||||
|
||||
private void execute(String sql) {
|
||||
service.executeStatement(request(sql), "us-east-1");
|
||||
}
|
||||
|
||||
private void reuse(String session, String sql) {
|
||||
service.executeStatement(mapper.createObjectNode().put("Sql", sql).put("SessionId", session)
|
||||
.put("WaitTimeSeconds", 5), "us-east-1");
|
||||
}
|
||||
|
||||
private ObjectNode batch(String... sqls) {
|
||||
ObjectNode request = request("unused");
|
||||
request.remove("Sql");
|
||||
ArrayNode statements = request.putArray("Sqls");
|
||||
for (String sql : sqls) {
|
||||
statements.add(sql);
|
||||
}
|
||||
return service.batchExecuteStatement(request, "us-east-1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SQLException {
|
||||
service.clear();
|
||||
executor.close();
|
||||
keeper.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -82,6 +82,17 @@ class RedshiftDataResourceResolverTest {
|
||||
assertEquals("arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:wh", target.arn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dbUserTargetUsesTheRequestRegionForAuditDelivery() {
|
||||
RedshiftService redshift = mock(RedshiftService.class);
|
||||
when(redshift.describeClusters("wh")).thenReturn(List.of(cluster()));
|
||||
ObjectNode request = mapper.createObjectNode().put("ClusterIdentifier", "wh")
|
||||
.put("Database", "dev").put("DbUser", "admin");
|
||||
RedshiftDataResourceResolver.DatabaseTarget target =
|
||||
resolver(redshift, mock(SecretsManagerService.class)).resolve(request, "us-west-2");
|
||||
assertEquals("arn:aws:redshift:us-west-2:acc:cluster:wh", target.arn());
|
||||
}
|
||||
|
||||
private static RedshiftServerlessService.WorkgroupTarget workgroupTarget() {
|
||||
return new RedshiftServerlessService.WorkgroupTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:" + ACCOUNT + ":workgroup/wg-id", "wg-1",
|
||||
@@ -211,6 +222,7 @@ class RedshiftDataResourceResolverTest {
|
||||
resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION);
|
||||
|
||||
assertEquals("admin", target.user());
|
||||
assertEquals("analyst", target.auditUser());
|
||||
assertEquals("Secret123", target.password());
|
||||
}
|
||||
|
||||
|
||||
+18
@@ -310,6 +310,24 @@ class RedshiftDataServiceTest {
|
||||
assertEquals(parameters, service.listStatements(om.createObjectNode()).path("Statements").get(0).path("QueryParameters"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchParametersBindAcrossCommandsAndSavepointsInOneEntry() {
|
||||
service.executeStatement(req("CREATE TABLE batch_savepoint (id INT)"), REGION);
|
||||
ObjectNode request = batchReq("INSERT INTO batch_savepoint VALUES (:id); SAVEPOINT s; "
|
||||
+ "INSERT INTO batch_savepoint VALUES (:discarded); ROLLBACK TO SAVEPOINT s; COMMIT",
|
||||
"SELECT id FROM batch_savepoint WHERE id = :id");
|
||||
request.putArray("Parameters").addObject().put("name", "id").put("value", "42");
|
||||
request.withArray("Parameters").addObject().put("name", "discarded").put("value", "99");
|
||||
|
||||
String id = service.batchExecuteStatement(request, REGION).path("Id").asText();
|
||||
|
||||
ObjectNode description = service.describeStatement(idOf(id));
|
||||
assertEquals("FINISHED", description.path("Status").asText(), description.toString());
|
||||
assertEquals(42, service.getStatementResult(idOf(id)).path("Records").get(0).get(0).path("longValue").asInt());
|
||||
String count = service.executeStatement(req("SELECT COUNT(*) FROM batch_savepoint"), REGION).path("Id").asText();
|
||||
assertEquals(1, service.getStatementResult(idOf(count)).path("Records").get(0).get(0).path("longValue").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchParametersRollBackEarlierWritesWhenALaterStatementFails() {
|
||||
service.executeStatement(req("CREATE TABLE batch_rollback(id integer)"), REGION);
|
||||
|
||||
+21
@@ -171,6 +171,27 @@ class RedshiftDataSessionIntegrationTest {
|
||||
assertThrows(ResourceNotFoundException.class, () -> data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT 3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkBatchAcceptsSavepointsAndMultipleStatementsInAnEntry() {
|
||||
ExecuteStatementResponse created = data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse")
|
||||
.dbUser("admin").database("dev").sessionKeepAliveSeconds(60)
|
||||
.sql("CREATE LOCAL TEMPORARY TABLE batch_changes(id integer)"));
|
||||
finished(created.id());
|
||||
String batch = data.batchExecuteStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId())
|
||||
.sqls("SAVEPOINT s", "INSERT INTO batch_changes VALUES (1); ROLLBACK TO SAVEPOINT s",
|
||||
"INSERT INTO batch_changes VALUES (2)")).id();
|
||||
finished(batch);
|
||||
String query = data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId())
|
||||
.sql("SELECT id FROM batch_changes")).id();
|
||||
finished(query);
|
||||
assertEquals(1L, data.getStatementResult(r -> r.id(query)).totalNumRows());
|
||||
assertEquals(2L, data.getStatementResult(r -> r.id(query)).records().getFirst().getFirst().longValue());
|
||||
String multiResult = data.batchExecuteStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId())
|
||||
.sqls("SELECT 11; SELECT 22")).id();
|
||||
finished(multiResult);
|
||||
assertEquals(11L, data.getStatementResult(r -> r.id(multiResult)).records().getFirst().getFirst().longValue());
|
||||
}
|
||||
|
||||
private RedshiftDataClient client(String key, Region region) {
|
||||
return RedshiftDataClient.builder().endpointOverride(endpoint).region(region)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(key, "test"))).build();
|
||||
|
||||
Reference in new issue
Block a user