diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessAuditLogTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessAuditLogTest.java new file mode 100644 index 0000000000..677c183ac3 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessAuditLogTest.java @@ -0,0 +1,104 @@ +package com.floci.test; + +import org.jboss.logging.Logger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse; +import software.amazon.awssdk.services.cloudwatchlogs.model.OutputLogEvent; +import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundException; +import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient; +import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementResponse; +import software.amazon.awssdk.services.redshiftdata.model.StatusString; +import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient; +import software.amazon.awssdk.services.redshiftserverless.model.ConfigParameter; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +@DisplayName("Redshift Serverless audit log export") +class RedshiftServerlessAuditLogTest { + + private static final Logger LOG = Logger.getLogger(RedshiftServerlessAuditLogTest.class); + private static final String STREAM = "serverless"; + + @Test + @DisplayName("A namespace exports the logs it selects to its CloudWatch log groups, and stops when it stops selecting them") + void namespaceExportsItsAuditLogsToCloudWatch() throws Exception { + assumeFalse(TestFixtures.isRealAws(), "Asserts emulator-local log delivery"); + + String suffix = UUID.randomUUID().toString().substring(0, 8); + String namespace = "audit-ns-" + suffix; + String workgroup = "audit-wg-" + suffix; + String activityGroup = "/aws/redshift/" + namespace + "/useractivitylog"; + String connectionGroup = "/aws/redshift/" + namespace + "/connectionlog"; + try (RedshiftServerlessClient serverless = TestFixtures.redshiftServerlessClient(); + RedshiftDataClient data = TestFixtures.redshiftDataClient(); + CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) { + try { + serverless.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin") + .adminUserPassword("Secret123!") + .logExportsWithStrings("connectionlog", "useractivitylog")); + serverless.createWorkgroup(request -> request.workgroupName(workgroup).namespaceName(namespace) + .configParameters(ConfigParameter.builder().parameterKey("enable_user_activity_logging") + .parameterValue("true").build())); + + execute(data, workgroup, "select 'sdk_audit_on_marker'"); + awaitMessage(logs, activityGroup, "sdk_audit_on_marker"); + awaitMessage(logs, connectionGroup, "authenticated"); + + serverless.updateNamespace(request -> request.namespaceName(namespace) + .logExportsWithStrings(new ArrayList<>(List.of("connectionlog")))); + execute(data, workgroup, "select 'sdk_audit_off_marker'"); + assertThat(messages(logs, activityGroup)).noneMatch(line -> line.contains("sdk_audit_off_marker")); + } finally { + try { + deleteBestEffort(() -> serverless.deleteWorkgroup(request -> request.workgroupName(workgroup)), + "workgroup " + workgroup); + } finally { + deleteBestEffort(() -> serverless.deleteNamespace(request -> request.namespaceName(namespace)), + "namespace " + namespace); + } + } + } + } + + private static void execute(RedshiftDataClient data, String workgroup, String sql) { + ExecuteStatementResponse executed = data.executeStatement(request -> request.workgroupName(workgroup).database("dev").sql(sql) + .waitTimeSeconds(30)); + assertThat(data.describeStatement(request -> request.id(executed.id())).status()) + .isEqualTo(StatusString.FINISHED); + } + + private static List messages(CloudWatchLogsClient logs, String group) { + try { + GetLogEventsResponse response = logs.getLogEvents(request -> request.logGroupName(group) + .logStreamName(STREAM).startFromHead(true)); + return response.events().stream().map(OutputLogEvent::message).toList(); + } catch (ResourceNotFoundException notYet) { + return List.of(); + } + } + + private static void awaitMessage(CloudWatchLogsClient logs, String group, String text) + throws InterruptedException { + TestFixtures.await(() -> messages(logs, group).stream().anyMatch(line -> line.contains(text)), + group, "a record containing " + text, Duration.ofSeconds(30).toNanos(), 500, + () -> ": " + messages(logs, group)); + } + + private static void deleteBestEffort(Runnable deletion, String resource) { + try { + deletion.run(); + } catch (software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException ignored) { + // Name clash with cloudwatchlogs ResourceNotFoundException; resource was not created or already deleted. + } catch (RuntimeException cleanupError) { + LOG.warnf(cleanupError, "Best-effort cleanup failed for %s", resource); + } + } +} diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.md index 0d0f854e92..aaa7a27511 100644 --- a/docs/services/redshift-serverless.md +++ b/docs/services/redshift-serverless.md @@ -91,6 +91,7 @@ Namespace and workgroup state is account and Region scoped and persisted through - **`namespaceId` is a generated UUID** and `namespaceArn` is `arn:aws:redshift-serverless:::namespace/`. - **`DeleteNamespace` returns the deleted namespace with `status` `DELETING`** and removes it in the same call, so the next `GetNamespace` returns `ResourceNotFoundException`. - **`UpdateNamespace` applies only the fields present in the request.** An omitted field keeps its stored value; an explicitly empty `iamRoles` or `logExports` array clears it. +- **`logExports` exports the audit logs of a running workgroup to CloudWatch Logs.** Each selected log type (`connectionlog`, `userlog`, `useractivitylog`) is written to `/aws/redshift//`, in the `serverless` log stream, for connections through the wire proxy and for Data API statements. `UpdateNamespace` takes effect at once: an emptied `logExports` stops the records. The user activity log also needs the workgroup's `enable_user_activity_logging` config parameter set to `true`, as on AWS. Passwords in statements are redacted, and a user change appears in `userlog` only once its transaction commits. A namespace whose workgroup is not running exports nothing, and the logs are not delivered to S3. - **A namespace has at most one workgroup, and a workgroup belongs to exactly one namespace.** A second `CreateWorkgroup` for a namespace returns `ConflictException`, and so does `DeleteNamespace` while the namespace still has a workgroup. AWS documents the one-to-one relationship; the `DeleteNamespace` refusal is the one rule here that is inferred rather than documented, because the API reference lists `ConflictException` for that call without naming its trigger. - **Workgroup defaults follow AWS.** `baseCapacity` defaults to 128 RPUs, `port` to 5439, `ipAddressType` to `ipv4`, `trackName` to `current`, `pricePerformanceTarget` to `{"status":"DISABLED"}`, and `enhancedVpcRouting`, `publiclyAccessible` and `extraComputeForAutomaticOptimization` to `false`. `status` is `AVAILABLE` as soon as the call returns; `DeleteWorkgroup` returns the workgroup with `DELETING` and removes it in the same call. - **Usage limits are stored and echoed, not enforced.** Floci does not meter RPU consumption, so no `breachAction` ever fires and `period` never resets a counter. A limit belongs to a workgroup: `resourceArn` must be a workgroup ARN (`ResourceNotFoundException` otherwise), and `amount` must be a positive integer. Deleting a workgroup removes its limits, and a workgroup recreated under the same name does not inherit them. `UpdateUsageLimit` changes only `amount` and `breachAction`. `CreateUsageLimit` takes no tags in the API model, so usage limits are not taggable here. diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java index 77e448e147..b049174971 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftAuditLogPublisher.java @@ -27,6 +27,7 @@ import java.time.format.DateTimeFormatter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -105,6 +106,11 @@ public class RedshiftAuditLogPublisher { registrations.put(registryKey(accountId, target.identifier()), new Registration(region, target)); } + /** The target registered under {@code identifier}, which a caller that only knows the backend publishes for. */ + public Optional registeredTarget(String accountId, String identifier) { + return Optional.ofNullable(registrations.get(registryKey(accountId, identifier))).map(Registration::target); + } + public void unregister(String accountId, String clusterIdentifier) { registrations.remove(registryKey(accountId, clusterIdentifier)); } @@ -153,7 +159,7 @@ public class RedshiftAuditLogPublisher { * Builds the target of a cluster for the publish overloads, which must never fail the statement being audited: * a cluster whose stored logging settings are malformed is reported and treated as having no target. */ - private static RedshiftAuditTarget targetOf(Cluster cluster) { + public static RedshiftAuditTarget targetOf(Cluster cluster) { try { return RedshiftAuditTarget.of(cluster); } catch (RuntimeException ex) { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolver.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolver.java index d2efca5bdd..fff8210816 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolver.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolver.java @@ -103,8 +103,9 @@ class RedshiftDataResourceResolver { RedshiftServerlessService.WorkgroupTarget workgroup = serverlessService.getWorkgroupTarget(request.get("WorkgroupName").asText(), region); String accountId = AwsArnUtils.parse(workgroup.arn()).accountId(); + String backendKey = accountId + ":" + RedshiftServerlessRuntime.backendId(region, workgroup.workgroupName()); SpectrumSession spectrum = new SpectrumSession(accountId, - accountId + ":" + RedshiftServerlessRuntime.backendId(region, workgroup.workgroupName()), database, + backendKey, database, workgroup.iamRoleArns(), false); if (!database.equals(workgroup.database())) { throw validation("Database " + database + " does not exist in workgroup " + workgroup.workgroupName() @@ -116,7 +117,6 @@ class RedshiftDataResourceResolver { int port = hasProxy ? proxyPort : workgroup.port(); if (!hasText(request, "SecretArn")) { String iamUser = resolveIamDbUser(); - String backendKey = accountId + ":" + RedshiftServerlessRuntime.backendId(region, workgroup.workgroupName()); DbIdentity identity = new DbIdentity(iamUser, true, List.of()); return new DatabaseTarget(workgroup.arn(), host, port, database, workgroup.masterUsername(), workgroup.masterPassword(), spectrum, null, @@ -129,7 +129,7 @@ class RedshiftDataResourceResolver { user = workgroup.masterUsername(); } return new DatabaseTarget(workgroup.arn(), host, port, database, - user, creds.password(), spectrum, null, user, workgroup.workgroupName()); + user, creds.password(), spectrum, null, user, workgroup.workgroupName(), null, backendKey); } private String resolveIamDbUser() { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java index 11234a1458..d601962fa1 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java @@ -17,6 +17,7 @@ import io.floci.aws.services.redshift.RedshiftAuditLogPublisher; import io.floci.aws.services.redshift.RedshiftAuditSql; import io.floci.aws.services.redshift.RedshiftAuditSql.UserChange; import io.floci.aws.services.redshift.RedshiftAuditSql.UserChanges; +import io.floci.aws.services.redshift.RedshiftAuditTarget; import io.floci.aws.services.redshift.proxy.CopyJobSql; import io.floci.aws.services.redshift.proxy.RedshiftSqlInterceptor; import io.floci.aws.services.redshift.spectrum.BackendSql; @@ -473,10 +474,28 @@ public class RedshiftDataService implements Resettable, StoredResourceArns { } } + /** + * What the audit logs of the target's cluster or workgroup take: a cluster's settings, or the target its + * workgroup's namespace registered, which is none while the namespace exports no logs. + */ + private RedshiftAuditTarget auditTarget(RedshiftDataResourceResolver.DatabaseTarget target) { + if (auditLogPublisher == null) { + return null; + } + if (target.cluster() != null) { + return RedshiftAuditLogPublisher.targetOf(target.cluster()); + } + String backendKey = target.backendKey(); + int separator = backendKey == null ? -1 : backendKey.indexOf(':'); + return separator < 0 ? null : auditLogPublisher.registeredTarget(backendKey.substring(0, separator), + backendKey.substring(separator + 1)).orElse(null); + } + private void publishConnection(RedshiftDataResourceResolver.DatabaseTarget target, String event, String error) { - if (auditLogPublisher != null && target.cluster() != null) { + RedshiftAuditTarget auditTarget = auditTarget(target); + if (auditTarget != null) { AwsArnUtils.Arn arn = AwsArnUtils.parse(target.arn()); - auditLogPublisher.publishConnection(target.cluster(), arn.accountId(), arn.region(), target.database(), + auditLogPublisher.publishConnection(auditTarget, arn.accountId(), arn.region(), target.database(), target.auditUser(), event, null, error); } } @@ -572,8 +591,9 @@ public class RedshiftDataService implements Resettable, StoredResourceArns { private void publishActivity(RedshiftDataStatementStore.StoredStatement stored, RedshiftDataResourceResolver.DatabaseTarget target, String sql) { - if (auditLogPublisher != null && target.cluster() != null) { - auditLogPublisher.publishActivity(target.cluster(), stored.accountId, stored.region, + RedshiftAuditTarget auditTarget = auditTarget(target); + if (auditTarget != null) { + auditLogPublisher.publishActivity(auditTarget, stored.accountId, stored.region, target.database(), target.auditUser(), sql); } } @@ -590,9 +610,10 @@ public class RedshiftDataService implements Resettable, StoredResourceArns { private void publishUserChanges(RedshiftDataStatementStore.StoredStatement stored, RedshiftDataResourceResolver.DatabaseTarget target, List changes) { - if (auditLogPublisher != null && target.cluster() != null) { + RedshiftAuditTarget auditTarget = auditTarget(target); + if (auditTarget != null) { for (UserChange change : changes) { - auditLogPublisher.publishUserChange(target.cluster(), stored.accountId, stored.region, + auditLogPublisher.publishUserChange(auditTarget, stored.accountId, stored.region, target.database(), change.username(), change.action(), change.oldUsername()); } } diff --git a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java index dd1f90fb33..5c499503c9 100644 --- a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java @@ -11,6 +11,8 @@ import io.floci.aws.core.common.Resettable; import io.floci.aws.core.common.StoredResourceArns; 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.SnapshotDumpCopier; import io.floci.aws.services.redshift.TempCredential; import io.floci.aws.services.redshift.model.Endpoint; @@ -128,6 +130,9 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns /** Looked up lazily: the endpoint service is built on this one. */ @Inject Instance endpointAccess; + /** Looked up lazily so a build without the publisher, and the unit tests that never wire one, still start. */ + @Inject + Instance auditPublisher; public RedshiftServerlessService(StorageFactory storageFactory, RegionResolver regionResolver, RedshiftServerlessEndpoints endpoints, RedshiftServerlessRuntime runtime, @@ -210,6 +215,63 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns workgroup.setMasterUsername(masterUsername); workgroup.setRuntimeHost(backend.host()); workgroup.setRuntimePort(backend.port()); + registerAudit(accountId, region, workgroup, namespace); + } + + /** Stops the workgroup's runtime, and with it the audit export of its namespace. */ + private void stopRuntime(String accountId, String region, String workgroupName) { + runtime.stop(accountId, region, workgroupName); + unregisterAudit(accountId, region, workgroupName); + } + + private void unregisterAudit(String accountId, String region, String workgroupName) { + publisher().ifPresent(publisher -> publisher.unregister(accountId, + RedshiftServerlessRuntime.backendId(region, workgroupName))); + } + + private Optional publisher() { + return auditPublisher == null || auditPublisher.isUnsatisfied() + ? Optional.empty() : Optional.of(auditPublisher.get()); + } + + /** Re-registers the audit export of the namespace's workgroup after the namespace's settings changed. */ + private void syncAudit(String accountId, String region, Namespace namespace) { + workgroupOf(namespace.getNamespaceName(), region) + .ifPresent(workgroup -> registerAudit(accountId, region, workgroup, namespace)); + } + + /** + * Registers what the workgroup's backend exports to CloudWatch Logs: the log types its namespace selects in + * {@code logExports}, under {@code /aws/redshift//}. A workgroup without a running + * backend has nothing to export. + */ + private void registerAudit(String accountId, String region, Workgroup workgroup, Namespace namespace) { + publisher().ifPresent(publisher -> { + String backendId = RedshiftServerlessRuntime.backendId(region, workgroup.getWorkgroupName()); + if (hasLiveRuntime(workgroup)) { + try { + publisher.register(accountId, region, auditTarget(backendId, workgroup, namespace)); + } catch (RuntimeException e) { + LOG.warnv(e, "Failed to register Redshift audit target for workgroup {0}", + workgroup.getWorkgroupName()); + } + } else { + publisher.unregister(accountId, backendId); + } + }); + } + + static RedshiftAuditTarget auditTarget(String backendId, Workgroup workgroup, Namespace namespace) { + List exports = namespace.getLogExports() == null ? List.of() : namespace.getLogExports().stream() + .filter(Objects::nonNull) + .toList(); + boolean activityLogging = workgroup.getConfigParameters() != null + && workgroup.getConfigParameters().stream() + .anyMatch(parameter -> "enable_user_activity_logging".equals(parameter.getParameterKey()) + && "true".equalsIgnoreCase(parameter.getParameterValue())); + return new RedshiftAuditTarget(backendId, "serverless", "/aws/redshift/" + namespace.getNamespaceName(), + "namespace/" + namespace.getNamespaceName(), !exports.isEmpty(), "cloudwatch", null, null, exports, + activityLogging, 0L); } private Supplier> adminSupplier( @@ -428,12 +490,16 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns } storeAttempted = true; namespaces.put(key, updated); + syncAudit(workgroups.accountId(), region, updated); if (wasManaged && !managed) { requireAdminSecrets().delete(current, region); } } catch (RuntimeException failure) { if (storeAttempted) { - compensate(() -> namespaces.put(key, current), failure, "restore namespace credentials"); + compensate(() -> { + namespaces.put(key, current); + syncAudit(workgroups.accountId(), region, current); + }, failure, "restore namespace credentials"); } if (backendChanged) { compensate(() -> restoreAdminPassword(current, region), failure, "restore backend admin password"); @@ -482,6 +548,7 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns } } namespaces.put(storageKey(region, previous.getNamespaceName()), previous); + syncAudit(workgroups.accountId(), region, previous); } public synchronized Namespace deleteNamespace(String namespaceName, String region) { @@ -1251,7 +1318,7 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns // The runtime may have started before the failure (a failed put), so tear it down; a // runtime that failed to start has already rolled itself back and this is then a no-op. try { - runtime.stop(workgroups.accountId(), region, workgroupName); + stopRuntime(workgroups.accountId(), region, workgroupName); } catch (RuntimeException stopFailure) { LOG.warnv(stopFailure, "Could not stop the runtime of workgroup {0} after a failed create", workgroupName); @@ -1325,6 +1392,8 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns } } workgroups.put(storageKey(region, workgroupName), updated); + namespaces.get(storageKey(region, updated.getNamespaceName())) + .ifPresent(namespace -> registerAudit(workgroups.accountId(), region, updated, namespace)); return updated; } @@ -1333,7 +1402,7 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns // The proxy goes first and its failure aborts the delete: a listener that could not be closed // keeps its port, so the workgroup must stay on record and the call can be retried. try { - runtime.stop(workgroups.accountId(), region, workgroupName); + stopRuntime(workgroups.accountId(), region, workgroupName); } catch (RuntimeException e) { LOG.warnv(e, "Failed to stop the runtime of workgroup {0}", workgroupName); throw new AwsException("InternalServerException", @@ -1623,14 +1692,18 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns @Override public void clear() { for (AccountAwareStorageBackend.AccountEntry entry : workgroups.scanAllAccountEntries(key -> true)) { + String region = regionOf(entry.key()); + String workgroupName = entry.value().getWorkgroupName(); try { - runtime.stop(entry.accountId(), regionOf(entry.key()), entry.value().getWorkgroupName()); + stopRuntime(entry.accountId(), region, workgroupName); endpoints.release(entry.value().getEndpoint()); } catch (RuntimeException e) { + // The workgroup record is about to be cleared, so drop its audit target even if shutdown failed. + unregisterAudit(entry.accountId(), region, workgroupName); // The listener may still be bound, so the endpoint stays reserved rather than being // handed to a later cluster or workgroup whose proxy could not bind it. LOG.warnv(e, "Could not stop the runtime of workgroup {0} while clearing state; " - + "its endpoint stays reserved", entry.value().getWorkgroupName()); + + "its endpoint stays reserved", workgroupName); } } namespaces.clear(); diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServerlessAuditTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServerlessAuditTest.java new file mode 100644 index 0000000000..6c6980d36e --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServerlessAuditTest.java @@ -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 groups = new CopyOnWriteArrayList<>(); + private final List 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> records = invocation.getArgument(3); + for (Map 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 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); + } +} diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAuditLogIntegrationTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAuditLogIntegrationTest.java new file mode 100644 index 0000000000..6d28d9781f --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAuditLogIntegrationTest.java @@ -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 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 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()); + } +} diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessServiceTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessServiceTest.java index 98d648f5a2..2ea69e03fc 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessServiceTest.java @@ -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 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 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 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 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 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 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 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 instanceOf(RedshiftAuditLogPublisher publisher) { + Instance instance = mock(Instance.class); + when(instance.isUnsatisfied()).thenReturn(false); + when(instance.get()).thenReturn(publisher); + return instance; + } + @Test void restoreRequiresAnExistingNamespaceWorkgroupAndSnapshot() { create("restore-ns");