mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 17:58:05 -05:00
feat(redshift-serverless): export the audit logs of a namespace to CloudWatch Logs (#8333)
This commit is contained in:
1 parent
6fa18cc99e
commit
7a98f47742
9 files changed
+762
-15
No files matched your search
+182
@@ -0,0 +1,182 @@
|
||||
package io.floci.aws.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.floci.aws.services.redshift.RedshiftAuditTarget;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.secretsmanager.model.SecretVersion;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftDataServerlessAuditTest {
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String BACKEND_ID = "serverless_us-east-1_wg";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<String> groups = new CopyOnWriteArrayList<>();
|
||||
private final List<String> messages = new CopyOnWriteArrayList<>();
|
||||
private final RedshiftDataExecutor executor = new RedshiftDataExecutor(2, 8, 1);
|
||||
private RedshiftDataConnectionFactory factory;
|
||||
private RedshiftDataResourceResolver resolver;
|
||||
private RedshiftAuditLogPublisher publisher;
|
||||
private RedshiftDataService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
doAnswer(invocation -> {
|
||||
List<Map<String, Object>> records = invocation.getArgument(3);
|
||||
for (Map<String, Object> record : records) {
|
||||
groups.add(invocation.getArgument(1));
|
||||
messages.add(record.get("message").toString());
|
||||
}
|
||||
return null;
|
||||
}).when(logs).putLogEventsForAccount(anyString(), anyString(), anyString(), anyList(), anyString());
|
||||
publisher = new RedshiftAuditLogPublisher(logs);
|
||||
factory = mock(RedshiftDataConnectionFactory.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
when(connection.prepareStatement(anyString())).thenReturn(mock(PreparedStatement.class));
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":workgroup/abc", "localhost", 5439,
|
||||
"dev", "admin", "password", null, null, "analyst", "wg", null, ACCOUNT_ID + ":" + BACKEND_ID));
|
||||
service = new RedshiftDataService(resolver, factory, new RedshiftDataStatementStore(24, Clock.systemUTC()),
|
||||
mapper, null, executor, null, null, null,
|
||||
new RedshiftDataIdempotencyStore(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), Clock.systemUTC()),
|
||||
new RedshiftDataSessions(), publisher);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
service.clear();
|
||||
executor.close();
|
||||
}
|
||||
|
||||
private void execute(String sql) {
|
||||
ObjectNode request = mapper.createObjectNode().put("Sql", sql).put("WaitTimeSeconds", 5)
|
||||
.put("WorkgroupName", "wg").put("Database", "dev").put("DbUser", "analyst");
|
||||
service.executeStatement(request, "us-east-1");
|
||||
}
|
||||
|
||||
private static RedshiftAuditTarget namespaceTarget(List<String> exports) {
|
||||
return new RedshiftAuditTarget(BACKEND_ID, "serverless", "/aws/redshift/analytics",
|
||||
"namespace/analytics", !exports.isEmpty(), "cloudwatch", null, null, exports, true, 0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupStatementIsAuditedUnderItsNamespacesLogGroups() {
|
||||
publisher.register(ACCOUNT_ID, "us-east-1", namespaceTarget(List.of("connectionlog", "useractivitylog")));
|
||||
|
||||
execute("SELECT 1");
|
||||
|
||||
assertTrue(groups.contains("/aws/redshift/analytics/connectionlog"), groups.toString());
|
||||
assertTrue(groups.contains("/aws/redshift/analytics/useractivitylog"), groups.toString());
|
||||
assertTrue(messages.stream().anyMatch(line -> line.contains("SELECT 1")), messages.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheSelectedLogTypesAreWritten() {
|
||||
publisher.register(ACCOUNT_ID, "us-east-1", namespaceTarget(List.of("userlog")));
|
||||
|
||||
execute("SELECT 1");
|
||||
|
||||
assertEquals(List.of(), groups);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupWithoutARegisteredTargetWritesNothing() {
|
||||
execute("SELECT 1");
|
||||
publisher.register(ACCOUNT_ID, "us-east-1", namespaceTarget(List.of("useractivitylog")));
|
||||
publisher.unregister(ACCOUNT_ID, BACKEND_ID);
|
||||
execute("SELECT 2");
|
||||
|
||||
assertFalse(messages.stream().anyMatch(line -> line.contains("SELECT")), messages.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretArnWorkgroupTargetPublishesNamespaceAuditLogs() {
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:" + ACCOUNT_ID + ":secret:wg-secret";
|
||||
SecretVersion version = new SecretVersion();
|
||||
version.setSecretString("{\"username\":\"analyst\",\"password\":\"Secret123!\"}");
|
||||
when(secrets.getSecretValue(secretArn, null, null, "us-east-1")).thenReturn(version);
|
||||
RedshiftServerlessService serverless = mock(RedshiftServerlessService.class);
|
||||
when(serverless.getWorkgroupTarget("wg", "us-east-1")).thenReturn(
|
||||
new RedshiftServerlessService.WorkgroupTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":workgroup/abc",
|
||||
"wg", "localhost", 5439, "dev",
|
||||
"admin", "admin-pw", "admin", List.of(), null, null));
|
||||
RedshiftDataResourceResolver realResolver = new RedshiftDataResourceResolver(
|
||||
null, secrets, mapper, null, new RegionResolver("us-east-1", ACCOUNT_ID), serverless);
|
||||
|
||||
ObjectNode request = mapper.createObjectNode()
|
||||
.put("WorkgroupName", "wg")
|
||||
.put("Database", "dev")
|
||||
.put("SecretArn", secretArn)
|
||||
.put("Sql", "CREATE USER bob PASSWORD 'Secret123!'")
|
||||
.put("WaitTimeSeconds", 5);
|
||||
RedshiftDataResourceResolver.DatabaseTarget resolved = realResolver.resolve(request, "us-east-1");
|
||||
assertEquals(ACCOUNT_ID + ":" + BACKEND_ID, resolved.backendKey());
|
||||
assertNull(resolved.dbIdentity());
|
||||
|
||||
when(resolver.resolve(any(), any())).thenReturn(resolved);
|
||||
publisher.register(ACCOUNT_ID, "us-east-1",
|
||||
namespaceTarget(List.of("connectionlog", "useractivitylog", "userlog")));
|
||||
|
||||
service.executeStatement(request, "us-east-1");
|
||||
|
||||
assertTrue(groups.contains("/aws/redshift/analytics/connectionlog"), groups.toString());
|
||||
assertTrue(groups.contains("/aws/redshift/analytics/useractivitylog"), groups.toString());
|
||||
assertTrue(groups.contains("/aws/redshift/analytics/userlog"), groups.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterWithMalformedAuditSettingsDoesNotFailStatement() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("broken-cluster");
|
||||
cluster.setLoggingEnabled(true);
|
||||
cluster.setLoggingDestinationType("cloudwatch");
|
||||
cluster.setLoggingExports(Arrays.asList("connectionlog", null));
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:" + ACCOUNT_ID + ":cluster:broken-cluster",
|
||||
"localhost", 5439, "dev", "admin", "password", null, cluster, "admin"));
|
||||
|
||||
ObjectNode request = mapper.createObjectNode()
|
||||
.put("ClusterIdentifier", "broken-cluster")
|
||||
.put("Database", "dev")
|
||||
.put("DbUser", "admin")
|
||||
.put("Sql", "SELECT 1")
|
||||
.put("WaitTimeSeconds", 5);
|
||||
ObjectNode response = service.executeStatement(request, "us-east-1");
|
||||
String status = service.describeStatement(
|
||||
mapper.createObjectNode().put("Id", response.get("Id").asText())).get("Status").asText();
|
||||
assertEquals("FINISHED", status);
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package io.floci.aws.services.redshiftserverless;
|
||||
|
||||
import io.floci.aws.services.redshift.RedshiftConnections;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The audit logs of a running workgroup reach the CloudWatch Logs log groups of its namespace, for connections
|
||||
* through the wire proxy and for Data API statements, and stop when the namespace stops exporting them. Needs Docker.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class RedshiftServerlessAuditLogIntegrationTest {
|
||||
|
||||
private static final String NAMESPACE = "audit-it-ns";
|
||||
private static final String WORKGROUP = "audit-it-wg";
|
||||
private static final String ADMIN_PASSWORD = "Secret123";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String GROUP_PREFIX = "/aws/redshift/" + NAMESPACE + "/";
|
||||
private static final String STREAM = "serverless";
|
||||
|
||||
@Inject
|
||||
RedshiftServerlessService service;
|
||||
|
||||
private int endpointPort;
|
||||
private boolean created;
|
||||
|
||||
/** Creates the workgroup once, as {@code RedshiftServerlessRuntimeIntegrationTest} does. */
|
||||
@BeforeEach
|
||||
void ensureWorkgroup() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for Redshift Serverless audit log tests");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
if (created) {
|
||||
return;
|
||||
}
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """
|
||||
{"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"%s","dbName":"dev",
|
||||
"logExports":["connectionlog","userlog","useractivitylog"]}
|
||||
""".formatted(NAMESPACE, ADMIN_PASSWORD)).then().statusCode(200);
|
||||
created = true;
|
||||
ExtractableResponse<Response> workgroup = RestAssuredJsonUtils.awsAction("RedshiftServerless",
|
||||
"CreateWorkgroup", """
|
||||
{"workgroupName":"%s","namespaceName":"%s",
|
||||
"configParameters":[{"parameterKey":"enable_user_activity_logging","parameterValue":"true"}]}
|
||||
""".formatted(WORKGROUP, NAMESPACE)).then().statusCode(200).extract();
|
||||
endpointPort = workgroup.path("workgroup.endpoint.port");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
void deleteWorkgroup() {
|
||||
if (created) {
|
||||
service.deleteWorkgroup(WORKGROUP, REGION);
|
||||
service.deleteNamespace(NAMESPACE, REGION);
|
||||
}
|
||||
}
|
||||
|
||||
private Connection connect() throws SQLException {
|
||||
// 127.0.0.1 rather than the advertised address: CI sets floci.emulator.hostname to a name that does not
|
||||
// resolve from the test JVM.
|
||||
return RedshiftConnections.waitForConnection("127.0.0.1", endpointPort, "admin", ADMIN_PASSWORD);
|
||||
}
|
||||
|
||||
private void executeOnTheWire(String... statements) throws SQLException {
|
||||
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
|
||||
for (String sql : statements) {
|
||||
statement.execute(sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void executeThroughTheDataApi(String sql) {
|
||||
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql": "%s", "WorkgroupName": "%s", "Database": "dev"}
|
||||
""".formatted(sql, WORKGROUP)).then().statusCode(200).extract().path("Id");
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(250)).until(() -> {
|
||||
String status = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status");
|
||||
assertFalse("FAILED".equals(status) || "ABORTED".equals(status),
|
||||
() -> "statement " + id + " ended " + status);
|
||||
return "FINISHED".equals(status);
|
||||
});
|
||||
}
|
||||
|
||||
/** The messages of a log type's log group, or none while the group does not exist yet. */
|
||||
private List<String> messages(String logType) {
|
||||
Response response = RestAssuredJsonUtils.awsAction("Logs_20140328", "GetLogEvents", """
|
||||
{"logGroupName":"%s","logStreamName":"%s","startFromHead":true}
|
||||
""".formatted(GROUP_PREFIX + logType, STREAM));
|
||||
if (response.statusCode() != 200) {
|
||||
return List.of();
|
||||
}
|
||||
return response.jsonPath().getList("events.message", String.class);
|
||||
}
|
||||
|
||||
private void awaitMessage(String logType, String text) {
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).untilAsserted(
|
||||
() -> assertTrue(messages(logType).stream().anyMatch(line -> line.contains(text)),
|
||||
() -> logType + " has no record with " + text + ": " + messages(logType)));
|
||||
}
|
||||
|
||||
private void exportOnly(String... logTypes) {
|
||||
String exports = String.join("\",\"", logTypes);
|
||||
RestAssuredJsonUtils.awsAction("RedshiftServerless", "UpdateNamespace", """
|
||||
{"namespaceName":"%s","logExports":["%s"]}
|
||||
""".formatted(NAMESPACE, exports)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void wireConnectionsAndStatementsAreExportedToTheNamespaceLogGroups() throws Exception {
|
||||
executeOnTheWire("SELECT 'wire_marker_1'", "CREATE USER wire_user PASSWORD 'Hidden123'");
|
||||
|
||||
awaitMessage("connectionlog", "admin");
|
||||
awaitMessage("useractivitylog", "wire_marker_1");
|
||||
awaitMessage("userlog", "wire_user");
|
||||
assertTrue(messages("useractivitylog").stream().noneMatch(line -> line.contains("Hidden123")),
|
||||
"a password literal must be redacted: " + messages("useractivitylog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dataApiStatementsAreExportedToTheNamespaceLogGroups() {
|
||||
executeThroughTheDataApi("SELECT 'data_api_marker_1'");
|
||||
|
||||
awaitMessage("useractivitylog", "data_api_marker_1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRolledBackUserChangeIsNotLoggedAsCommitted() throws Exception {
|
||||
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
|
||||
connection.setAutoCommit(false);
|
||||
statement.execute("CREATE USER rolled_back_user PASSWORD 'Hidden123'");
|
||||
connection.rollback();
|
||||
statement.execute("SELECT 'after_rollback_marker'");
|
||||
connection.commit();
|
||||
}
|
||||
|
||||
awaitMessage("useractivitylog", "after_rollback_marker");
|
||||
assertTrue(messages("userlog").stream().noneMatch(line -> line.contains("rolled_back_user")),
|
||||
"a rolled back user must not reach the user log: " + messages("userlog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void turningAnExportOffStopsItsRecordsAndTurningItOnResumesThem() throws Exception {
|
||||
exportOnly("connectionlog", "userlog");
|
||||
try {
|
||||
executeOnTheWire("SELECT 'while_off_marker'");
|
||||
executeThroughTheDataApi("SELECT 'while_off_data_api_marker'");
|
||||
awaitMessage("connectionlog", "admin");
|
||||
Awaitility.await().during(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(10)).untilAsserted(() ->
|
||||
assertTrue(messages("useractivitylog").stream().noneMatch(line -> line.contains("while_off"))));
|
||||
} finally {
|
||||
exportOnly("connectionlog", "userlog", "useractivitylog");
|
||||
}
|
||||
|
||||
executeOnTheWire("SELECT 'while_on_marker'");
|
||||
awaitMessage("useractivitylog", "while_on_marker");
|
||||
assertEquals(List.of(), messages("useractivitylog").stream().filter(line -> line.contains("while_off"))
|
||||
.toList());
|
||||
}
|
||||
}
|
||||
+180
@@ -7,6 +7,8 @@ import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.floci.aws.services.redshift.RedshiftAuditTarget;
|
||||
import io.floci.aws.services.redshift.TempCredential;
|
||||
import io.floci.aws.services.redshift.model.Endpoint;
|
||||
import io.floci.aws.services.redshiftserverless.model.ConfigParameter;
|
||||
@@ -24,6 +26,7 @@ import org.mockito.Mockito;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -55,6 +58,7 @@ import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -1045,6 +1049,182 @@ class RedshiftServerlessServiceTest {
|
||||
assertEquals("ConflictException", conflict.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunningWorkgroupExportsTheLogTypesItsNamespaceSelects() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("audit-ns", "admin", null, null, null, null, List.of("connectionlog", "userlog"),
|
||||
Map.of(), REGION);
|
||||
|
||||
createWorkgroup("audit-wg", "audit-ns");
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
RedshiftAuditTarget target = registered.getValue();
|
||||
assertEquals("serverless_us-east-1_audit-wg", target.identifier());
|
||||
assertEquals("/aws/redshift/audit-ns", target.logGroupPrefix());
|
||||
assertEquals("serverless", target.name());
|
||||
assertEquals("cloudwatch", target.destinationType());
|
||||
assertEquals(List.of("connectionlog", "userlog"), target.exports());
|
||||
assertTrue(target.enabled());
|
||||
assertFalse(target.activityLoggingEnabled());
|
||||
|
||||
service.updateNamespace("audit-ns", null, null, null, null, List.of("useractivitylog"), REGION);
|
||||
service.updateNamespace("audit-ns", null, null, null, null, List.of(), REGION);
|
||||
service.deleteWorkgroup("audit-wg", REGION);
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> reregistered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher, times(3)).register(eq(ACCOUNT_ID), eq(REGION), reregistered.capture());
|
||||
assertEquals(List.of("useractivitylog"), reregistered.getAllValues().get(1).exports());
|
||||
assertFalse(reregistered.getAllValues().get(2).enabled());
|
||||
verify(publisher).unregister(ACCOUNT_ID, "serverless_us-east-1_audit-wg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingTheWorkgroupConfigParameterReregistersTheTarget() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("cfg-ns", "admin", null, null, null, null, List.of("useractivitylog"), Map.of(), REGION);
|
||||
createWorkgroup("cfg-wg", "cfg-ns");
|
||||
|
||||
service.updateWorkgroup("cfg-wg", new WorkgroupSettings(null, null, null, null, null,
|
||||
List.of(new ConfigParameter("enable_user_activity_logging", "true")), null, null, null, null, null,
|
||||
null), REGION);
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher, times(2)).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
assertFalse(registered.getAllValues().get(0).activityLoggingEnabled());
|
||||
assertTrue(registered.getAllValues().get(1).activityLoggingEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoringANamespaceUpdateReregistersThePreviousLogExports() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("rollback-ns", "admin", null, null, null, null, List.of("connectionlog"), Map.of(),
|
||||
REGION);
|
||||
createWorkgroup("rollback-wg", "rollback-ns");
|
||||
RedshiftServerlessService.NamespaceUpdateSnapshot snapshot =
|
||||
service.snapshotNamespaceUpdate("rollback-ns", REGION);
|
||||
service.updateNamespace("rollback-ns", null, null, null, null, List.of("userlog"), REGION);
|
||||
|
||||
service.restoreNamespaceUpdate(snapshot, REGION);
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher, times(3)).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
assertEquals(List.of("userlog"), registered.getAllValues().get(1).exports());
|
||||
assertEquals(List.of("connectionlog"), registered.getAllValues().get(2).exports());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestartRegistersTheTargetOfEveryRecoveredWorkgroup() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.createNamespace("boot-ns", "admin", null, null, null, null, List.of("connectionlog"), Map.of(), REGION);
|
||||
createWorkgroup("boot-wg", "boot-ns");
|
||||
when(endpoints.restore(any(Endpoint.class))).thenAnswer(call -> call.getArgument(0));
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
assertEquals("serverless_us-east-1_boot-wg", registered.getValue().identifier());
|
||||
assertEquals(List.of("connectionlog"), registered.getValue().exports());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupThatFailsToStartRegistersNothing() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("fail-ns", "admin", null, null, null, null, List.of("connectionlog"), Map.of(), REGION);
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenThrow(new IllegalStateException("container failed"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> createWorkgroup("fail-wg", "fail-ns"));
|
||||
|
||||
verify(publisher, never()).register(any(), any(), any(RedshiftAuditTarget.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUserActivityLogNeedsItsConfigParameterOnTheWorkgroup() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("activity-ns", "admin", null, null, null, null, List.of("useractivitylog"), Map.of(),
|
||||
REGION);
|
||||
|
||||
service.createWorkgroup("activity-wg", "activity-ns", new WorkgroupSettings(null, null, null, null, null,
|
||||
List.of(new ConfigParameter("enable_user_activity_logging", "true")), null, null, null, null, null,
|
||||
null), null, REGION);
|
||||
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
assertTrue(registered.getValue().activityLoggingEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryIgnoresNullLogExportsAndKeepsWorkgroupRuntime() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
Namespace namespace = service.createNamespace("null-export-ns", "admin", null, null, null, null,
|
||||
List.of("connectionlog"), Map.of(), REGION);
|
||||
namespace.setLogExports(Arrays.asList("connectionlog", null));
|
||||
store.put(REGION + "::null-export-ns", namespace);
|
||||
createWorkgroup("null-export-wg", "null-export-ns");
|
||||
when(endpoints.restore(any(Endpoint.class))).thenAnswer(call -> call.getArgument(0));
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
Workgroup recovered = service.getWorkgroup("null-export-wg", REGION);
|
||||
assertEquals("127.0.0.1", recovered.getRuntimeHost());
|
||||
assertEquals(55432, recovered.getRuntimePort());
|
||||
ArgumentCaptor<RedshiftAuditTarget> registered = ArgumentCaptor.forClass(RedshiftAuditTarget.class);
|
||||
verify(publisher).register(eq(ACCOUNT_ID), eq(REGION), registered.capture());
|
||||
assertEquals(List.of("connectionlog"), registered.getValue().exports());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryKeepsWorkgroupRuntimeWhenAuditRegistrationThrows() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
doThrow(new IllegalStateException("audit failure")).when(publisher)
|
||||
.register(eq(ACCOUNT_ID), eq(REGION), any(RedshiftAuditTarget.class));
|
||||
service.createNamespace("audit-err-ns", "admin", null, null, null, null, List.of("connectionlog"),
|
||||
Map.of(), REGION);
|
||||
createWorkgroup("audit-err-wg", "audit-err-ns");
|
||||
when(endpoints.restore(any(Endpoint.class))).thenAnswer(call -> call.getArgument(0));
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
Workgroup recovered = service.getWorkgroup("audit-err-wg", REGION);
|
||||
assertEquals("127.0.0.1", recovered.getRuntimeHost());
|
||||
assertEquals(55432, recovered.getRuntimePort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearUnregistersAuditTargetEvenWhenRuntimeStopFails() {
|
||||
RedshiftAuditLogPublisher publisher = mock(RedshiftAuditLogPublisher.class);
|
||||
service.auditPublisher = instanceOf(publisher);
|
||||
service.createNamespace("clear-err-ns", "admin", null, null, null, null, List.of("connectionlog"),
|
||||
Map.of(), REGION);
|
||||
Workgroup created = createWorkgroup("clear-err-wg", "clear-err-ns");
|
||||
doThrow(new RuntimeException("stop failed")).when(runtime).stop(ACCOUNT_ID, REGION, "clear-err-wg");
|
||||
|
||||
service.clear();
|
||||
|
||||
verify(publisher).unregister(ACCOUNT_ID, "serverless_us-east-1_clear-err-wg");
|
||||
verify(endpoints, never()).release(created.getEndpoint());
|
||||
assertTrue(service.listWorkgroups(REGION, null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Instance<RedshiftAuditLogPublisher> instanceOf(RedshiftAuditLogPublisher publisher) {
|
||||
Instance<RedshiftAuditLogPublisher> instance = mock(Instance.class);
|
||||
when(instance.isUnsatisfied()).thenReturn(false);
|
||||
when(instance.get()).thenReturn(publisher);
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreRequiresAnExistingNamespaceWorkgroupAndSnapshot() {
|
||||
create("restore-ns");
|
||||
|
||||
Reference in new issue
Block a user