diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java index 0438282dbf..e6fbd95447 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoConfirmSignUpVerificationTest.java @@ -195,8 +195,9 @@ class CognitoConfirmSignUpVerificationTest { } private static String fetchVerificationCodeFromSes(String recipient) throws Exception { - URI uri = TestFixtures.endpoint() - .resolve("/_aws/ses?email=" + URLEncoder.encode(recipient, StandardCharsets.UTF_8)); + // The mailbox's email parameter filters by message source, so the message sent to the + // recipient is picked out of the full list. + URI uri = TestFixtures.endpoint().resolve("/_aws/ses"); HttpResponse resp = HTTP.send( HttpRequest.newBuilder() @@ -207,15 +208,26 @@ class CognitoConfirmSignUpVerificationTest { HttpResponse.BodyHandlers.ofString() ); - JsonNode messages = JSON.readTree(resp.body()).path("messages"); - assertThat(messages.isArray() && !messages.isEmpty()) + JsonNode message = firstMessageTo(JSON.readTree(resp.body()).path("messages"), recipient); + assertThat(message) .as("SES should have received a verification email for %s", recipient) - .isTrue(); + .isNotNull(); - String body = messages.get(0).path("Body").path("text_part").asText(); + String body = message.path("Body").path("text_part").asText(); return extractSixDigitCode(body); } + private static JsonNode firstMessageTo(JsonNode messages, String recipient) { + for (JsonNode message : messages) { + for (JsonNode to : message.path("Destination").path("ToAddresses")) { + if (recipient.equals(to.asText())) { + return message; + } + } + } + return null; + } + private static String fetchVerificationCodeFromSns(String phoneNumber) throws Exception { URI uri = TestFixtures.endpoint() .resolve("/_aws/sns?phone=" + URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8)); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoVerifyUserAttributeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoVerifyUserAttributeTest.java index 7ebc2dc987..0631c41416 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoVerifyUserAttributeTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoVerifyUserAttributeTest.java @@ -316,10 +316,17 @@ class CognitoVerifyUserAttributeTest { } private static String fetchLatestSesVerificationCode(String recipient) throws Exception { - URI uri = TestFixtures.endpoint() - .resolve("/_aws/ses?email=" + URLEncoder.encode(recipient, StandardCharsets.UTF_8)); - JsonNode messages = getInspectionMessages(uri); - return extractVerificationCode(messages.get(0).path("Body").path("text_part").asText()); + // The mailbox's email parameter filters by message source, so the message sent to the + // recipient is picked out of the full list. + JsonNode messages = getInspectionMessages(TestFixtures.endpoint().resolve("/_aws/ses")); + for (JsonNode message : messages) { + for (JsonNode to : message.path("Destination").path("ToAddresses")) { + if (recipient.equals(to.asText())) { + return extractVerificationCode(message.path("Body").path("text_part").asText()); + } + } + } + throw new AssertionError("SES should have received a verification email for " + recipient); } private static String fetchLatestSnsVerificationCode(String phoneNumber) throws Exception { diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DataLakeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DataLakeTest.java index ee730a3bd8..4fc03160c3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DataLakeTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DataLakeTest.java @@ -118,7 +118,7 @@ class DataLakeTest { // The bucket itself is only created on the first delivery. } if (!delivered) { - Thread.sleep(2_000); + Thread.sleep(TestFixtures.isRealAws() ? 2_000 : 250); } } assertThat(delivered) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseCompressionDeliveryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseCompressionDeliveryTest.java index 7e24816d51..5541c27a74 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseCompressionDeliveryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseCompressionDeliveryTest.java @@ -63,6 +63,7 @@ class FirehoseCompressionDeliveryTest { */ private static final int BUFFERING_INTERVAL_SECONDS = 5; private static final long POLL_TIMEOUT_MILLIS = 240_000L; + private static final long POLL_INTERVAL_MILLIS = TestFixtures.isRealAws() ? 5_000L : 250L; private static FirehoseClient firehose; private static S3Client s3; @@ -202,7 +203,7 @@ class FirehoseCompressionDeliveryTest { if (!contents.isEmpty()) { return contents.get(0).key(); } - Thread.sleep(5_000L); + Thread.sleep(POLL_INTERVAL_MILLIS); } throw new AssertionError("no object delivered under " + prefix + " within " + POLL_TIMEOUT_MILLIS / 1000 + "s"); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseLambdaTransformDeliveryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseLambdaTransformDeliveryTest.java index f76ce0756c..a10f9d70e2 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseLambdaTransformDeliveryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseLambdaTransformDeliveryTest.java @@ -61,6 +61,7 @@ class FirehoseLambdaTransformDeliveryTest { private static final int BUFFERING_INTERVAL_SECONDS = 5; private static final long POLL_TIMEOUT_MILLIS = 240_000L; + private static final long POLL_INTERVAL_MILLIS = TestFixtures.isRealAws() ? 5_000L : 250L; private static final String KEPT_RECORD = "keep-me\n"; private static final String DROPPED_RECORD = "DROP-me\n"; private static final String FAILED_RECORD = "FAIL-me\n"; @@ -178,7 +179,7 @@ class FirehoseLambdaTransformDeliveryTest { throw new AssertionError("no object under " + prefix + " in " + bucket + " after " + POLL_TIMEOUT_MILLIS / 1000 + "s"); } - Thread.sleep(5_000L); + Thread.sleep(POLL_INTERVAL_MILLIS); } } @@ -205,7 +206,7 @@ class FirehoseLambdaTransformDeliveryTest { throw new AssertionError("delivery stream stayed " + status + " for " + POLL_TIMEOUT_MILLIS / 1000 + "s"); } - Thread.sleep(5_000L); + Thread.sleep(POLL_INTERVAL_MILLIS); } } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseParquetDeliveryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseParquetDeliveryTest.java index 5452e2b193..94661811b0 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseParquetDeliveryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FirehoseParquetDeliveryTest.java @@ -80,6 +80,7 @@ class FirehoseParquetDeliveryTest { private static final int BUFFERING_INTERVAL_SECONDS = 5; private static final long POLL_TIMEOUT_MILLIS = 240_000L; + private static final long POLL_INTERVAL_MILLIS = TestFixtures.isRealAws() ? 5_000L : 250L; private static final byte[] PARQUET_MAGIC = "PAR1".getBytes(StandardCharsets.US_ASCII); private static final String VALID_RECORD_1 = @@ -221,7 +222,7 @@ class FirehoseParquetDeliveryTest { throw new AssertionError("delivery stream stayed " + status + " for " + POLL_TIMEOUT_MILLIS / 1000 + "s"); } - Thread.sleep(5_000L); + Thread.sleep(POLL_INTERVAL_MILLIS); } } @@ -470,7 +471,7 @@ class FirehoseParquetDeliveryTest { if (!contents.isEmpty()) { return contents.get(0).key(); } - Thread.sleep(5_000L); + Thread.sleep(POLL_INTERVAL_MILLIS); } throw new AssertionError("no object delivered under " + prefix + " within " + POLL_TIMEOUT_MILLIS / 1000 + "s"); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java index 5214654c40..2328052b3a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java @@ -510,7 +510,7 @@ class SesEventPublishingTest { if (!listed.contents().isEmpty()) { break; } - Thread.sleep(2_000); + Thread.sleep(TestFixtures.isRealAws() ? 2_000 : 250); } assertThat(listed.contents()) .as("Firehose should deliver the buffered events within IntervalInSeconds") diff --git a/compatibility-tests/sdk-test-node/tests/setup.ts b/compatibility-tests/sdk-test-node/tests/setup.ts index d25a88585b..6f325a2aef 100644 --- a/compatibility-tests/sdk-test-node/tests/setup.ts +++ b/compatibility-tests/sdk-test-node/tests/setup.ts @@ -41,17 +41,22 @@ export function sleep(ms: number): Promise { const SIX_DIGIT_CODE = /\b(\d{6})\b/; export async function fetchLatestSesVerificationCode(recipient: string): Promise { - const response = await fetch( - `${ENDPOINT}/_aws/ses?email=${encodeURIComponent(recipient)}` - ); + // The mailbox's email parameter filters by message source, so the message sent to the + // recipient is picked out of the full list. + const response = await fetch(`${ENDPOINT}/_aws/ses`); if (!response.ok) { throw new Error(`failed to fetch SES messages: ${response.status}`); } const payload = (await response.json()) as { - messages?: Array<{ Body?: { text_part?: string } }>; + messages?: Array<{ + Destination?: { ToAddresses?: string[] }; + Body?: { text_part?: string }; + }>; }; - const firstMessage = payload.messages?.[0]; + const firstMessage = payload.messages?.find((message) => + message.Destination?.ToAddresses?.includes(recipient) + ); const body = firstMessage?.Body?.text_part ?? (firstMessage?.Body as { html_part?: string } | undefined)?.html_part ?? diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 925048f8d9..f5f6cae2ba 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -298,7 +298,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_FIREHOSE_ENABLED` | `true` | Enable the Kinesis Data Firehose service | -| `FLOCI_SERVICES_FIREHOSE_TICK_INTERVAL_SECONDS` | `10` | How often (seconds) the buffer flusher checks for streams whose `BufferingHints.IntervalInSeconds` has elapsed | +| `FLOCI_SERVICES_FIREHOSE_TICK_INTERVAL_SECONDS` | `1` | How often (seconds) the buffer flusher checks for streams whose `BufferingHints.IntervalInSeconds` has elapsed | | `FLOCI_SERVICES_FIREHOSE_FLUSH_RECORD_COUNT` | `0` | Emulator-only: flush after this many buffered records (`0` = disabled, AWS-faithful; `1` = LocalStack-style record-at-a-time delivery) | | `FLOCI_SERVICES_FIREHOSE_STAGING_BUCKET` | `floci-firehose-staging` | S3 bucket used to stage NDJSON batches before DuckDB writes the Parquet object for format-converting streams | diff --git a/docs/services/firehose.md b/docs/services/firehose.md index ab664586c5..5f66dd3246 100644 --- a/docs/services/firehose.md +++ b/docs/services/firehose.md @@ -29,7 +29,7 @@ Floci emulates Amazon Data Firehose for streaming data ingestion and delivery to 1. **Buffering**: Incoming records are buffered in memory. 2. **Automatic Flush**: A buffer is delivered to S3 when either trigger of the stream's `BufferingHints` fires first, mirroring AWS's buffered delivery: - the buffered records reach `SizeInMBs` (default 5 MiB), or - - `IntervalInSeconds` (default 300 s) has elapsed since the first buffered record. A background flusher checks this every `floci.services.firehose.tick-interval-seconds` (default 10 s). + - `IntervalInSeconds` (default 300 s) has elapsed since the first buffered record. A background flusher checks this every `floci.services.firehose.tick-interval-seconds` (default 1 s). An emulator-only record-count trigger is also available for local dev: set `floci.services.firehose.flush-record-count` (env: `FLOCI_SERVICES_FIREHOSE_FLUSH_RECORD_COUNT`) to flush after that many buffered records — `1` gives LocalStack-style record-at-a-time delivery. Disabled by default (`0`) so delivery timing matches real AWS. diff --git a/docs/services/ses.md b/docs/services/ses.md index 89b90f9e77..4710dc79c6 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -220,9 +220,13 @@ the ones not listed here are not acted on. For test assertions and debugging, Floci exposes a LocalStack-compatible mailbox endpoint: -- `GET /_aws/ses` lists captured messages +- `GET /_aws/ses` lists captured messages, oldest first by `Timestamp` - `GET /_aws/ses?id=` returns a specific captured message +- `GET /_aws/ses?email=
` returns the messages whose `Source` equals that value exactly, so a sender given as `Name ` is matched in that form; with `id` as well, both filters apply - `DELETE /_aws/ses` clears the captured mailbox +- `DELETE /_aws/ses?id=` deletes only that message; an unknown id deletes nothing + +The `email` filter matches the sender, as on [LocalStack](https://docs.localstack.cloud/aws/services/ses/), not a recipient. Earlier Floci versions matched it against `ToAddresses`; to find the messages sent to an address, list them all and filter on `Destination.ToAddresses`. Messages are stored locally by Floci and can be persisted when SES storage is backed by persistent or hybrid storage. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index e20bc54072..f6351b4b12 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1887,9 +1887,11 @@ public interface EmulatorConfig { /** * How often the buffer flusher checks for streams whose buffering - * interval (BufferingHints.IntervalInSeconds) has elapsed. + * interval (BufferingHints.IntervalInSeconds) has elapsed. AWS delivers once + * the first buffer condition is met, so a buffer is delivered at most this + * long after its interval ends. */ - @WithDefault("10") + @WithDefault("1") long tickIntervalSeconds(); /** diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java index d291f7f418..d025e2911b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java @@ -151,6 +151,7 @@ public class ContainerBuilder { private Long nanoCpus; private Integer cpuShares; private boolean readonlyRootfs; + private boolean init; private final Map portBindings = new HashMap<>(); private final List loopbackPortBindings = new ArrayList<>(); private final Map portBindingHostIps = new HashMap<>(); @@ -276,6 +277,17 @@ public class ContainerBuilder { return this; } + /** + * Runs Docker's init process as PID 1, which forwards signals to the command (Docker + * {@code --init}). The kernel gives PID 1 no default signal actions, so a command that + * installs no SIGTERM handler of its own ignores the stop request and only goes when + * Docker sends SIGKILL at the end of the stop timeout. + */ + public Builder withInit() { + this.init = true; + return this; + } + /** * Adds a port binding from container port to a specific host port. */ @@ -690,7 +702,8 @@ public class ContainerBuilder { cpuShares, readonlyRootfs, List.copyOf(linkLocalIps), - Map.copyOf(portBindingHostIps) + Map.copyOf(portBindingHostIps), + init ); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java index 605d323bfe..2f23262dda 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java @@ -1146,6 +1146,9 @@ public class ContainerLifecycleManager { if (spec.readonlyRootfs()) { hostConfig.withReadonlyRootfs(true); } + if (spec.init()) { + hostConfig.withInit(true); + } // Port bindings — services decide whether to request them based on their // own in-container-vs-native logic. When Floci runs inside Docker, most diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java index d172e67f2d..39c60fc731 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java @@ -45,6 +45,8 @@ import java.util.regex.Pattern; * @param linkLocalIps Link-local IPv4 addresses assigned to the container's endpoint on the configured network * @param portBindingHostIps Host interface each published port binds to, keyed by container port. * A port with no entry here, and not in {@code loopbackPortBindings}, binds every interface + * @param init Whether Docker runs its init process as PID 1, forwarding signals to the command, for + * images whose command does not handle SIGTERM itself */ public record ContainerSpec( String image, @@ -74,7 +76,8 @@ public record ContainerSpec( Integer cpuShares, boolean readonlyRootfs, List linkLocalIps, - Map portBindingHostIps + Map portBindingHostIps, + boolean init ) { private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$"); private static final Set NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none"); @@ -94,7 +97,7 @@ public record ContainerSpec( public ContainerSpec(String image) { this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null, List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), - null, null, List.of(), List.of(), null, null, false, List.of(), Map.of()); + null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false); } /** @@ -126,7 +129,7 @@ public record ContainerSpec( this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, List.of(), exposedPorts, networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of(), null, null, false, - List.of(), Map.of()); + List.of(), Map.of(), false); } /** @@ -160,7 +163,7 @@ public record ContainerSpec( this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings, exposedPorts, networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of(), - null, null, false, List.of(), Map.of()); + null, null, false, List.of(), Map.of(), false); } /** @@ -194,7 +197,7 @@ public record ContainerSpec( this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings, exposedPorts, networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests, - null, null, false, List.of(), Map.of()); + null, null, false, List.of(), Map.of(), false); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java index 52e8d8012f..39b2186fd4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java @@ -63,6 +63,11 @@ public class CloudWatchDashboardCfnProvisioner implements CfnResourceProvisioner public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { // A snapshot describes the update in flight; one an earlier update left behind is stale. r.getAttributes().remove(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + // The unwind below undoes this update; only ContinueUpdateRollback retries the delete + // the last rollback could not make. + ReplacementCleanup.endRollbackRetry(r); + } Map attributesBefore = Map.copyOf(r.getAttributes()); String explicitName = ctx.resolveOptional(props, "DashboardName"); boolean hasExplicitName = explicitName != null && !explicitName.isBlank(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java index 0af5b6c954..5b4439e4df 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java @@ -49,6 +49,11 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision validateString(name, "Name", 256, "[\\w\\s+=,.@-]+"); List scopes = scopes(properties, ctx); + if (ctx.isUpdate()) { + // Rolling this update back undoes it alone; only ContinueUpdateRollback retries the + // delete the last rollback could not make. + ReplacementCleanup.endRollbackRetry(resource); + } if (ctx.isUpdate() && retainsFailedUpdateState(resource)) { try { rollbackUpdate(resource); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisioner.java index 68fc142c15..154b0c7574 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisioner.java @@ -68,6 +68,11 @@ public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner { public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { // A snapshot describes the update in flight; one an earlier update left behind is stale. r.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + // The unwind below undoes this update; only ContinueUpdateRollback retries the delete + // the last rollback could not make. + ReplacementCleanup.endRollbackRetry(r); + } Map attributesBefore = Map.copyOf(r.getAttributes()); String functionArn = resolvePresent(props, "AuthorizerFunctionArn", ctx); if (functionArn == null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java index 2437f92f07..af1804e528 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java @@ -164,6 +164,21 @@ public final class ReplacementCleanup { return true; } + /** + * Ends the retry a failed rollback left for the replacement it could not delete. Only + * ContinueUpdateRollback retries that delete, and a new update reaches the resource only once + * one skipped it, so a provisioner calls this as an update starts: otherwise rolling back an + * attempt that failed before {@link #record} would retry the earlier delete instead of undoing + * the attempt. The replacement stays listed, so the next committed update or the stack delete + * still removes it. + */ + static void endRollbackRetry(StackResource r) { + ObjectNode cleanup = read(r); + if (cleanup != null && cleanup.remove("undeletedReplacement") != null) { + write(r, cleanup); + } + } + static boolean hasReplacement(StackResource r) { ObjectNode cleanup = read(r); return cleanup != null && cleanup.path("displaced").size() > 0; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java index 5e8f6cbccf..620a1b9657 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java @@ -54,6 +54,11 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) { readCleanup(resource); + if (ctx.isUpdate()) { + // The rollbackUpdate calls below restore a snapshot; only ContinueUpdateRollback retries + // the delete the last rollback could not make. + ReplacementCleanup.endRollbackRetry(resource); + } if (ctx.isUpdate() && resource.getAttributes().containsKey(SNAPSHOT_ATTR)) { try { rollbackUpdate(resource); diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManager.java index 347e822ef6..617253639b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManager.java @@ -80,6 +80,10 @@ public class PypiserverSidecarManager implements ContainerTeardown { .withDockerNetwork(config.services().dockerNetwork()) .withEmbeddedDns() .withLogRotation() + // The image's entrypoint execs pypi-server, which installs no SIGTERM handler. As + // PID 1 it would ignore the stop request, and every reset, repository delete and + // shutdown would wait out the whole stop timeout for each repository's container. + .withInit() .withCmd(List.of( "run", "-p", String.valueOf(PYPISERVER_PORT), diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java index 8e75050197..00f40d18ee 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java @@ -18,7 +18,9 @@ import java.util.List; /** * LocalStack-compatible REST endpoint for inspecting sent SES emails. - * Provides GET /_aws/ses and DELETE /_aws/ses for test helpers. + * Provides GET /_aws/ses and DELETE /_aws/ses for test helpers. GET lists the messages oldest + * first and filters them by {@code id} (message id) and {@code email} (message source); DELETE + * removes the message named by {@code id}, or every message without it. */ @Path("/_aws/ses") @Produces(MediaType.APPLICATION_JSON) @@ -36,7 +38,7 @@ public class SesInspectionController { @GET public Response getEmails(@QueryParam("id") String messageId, - @QueryParam("email") String recipient) { + @QueryParam("email") String source) { List emails = sentEmailService.listAll(); ArrayNode messages = objectMapper.createArrayNode(); @@ -44,8 +46,7 @@ public class SesInspectionController { if (messageId != null && !messageId.equals(email.getMessageId())) { continue; } - if (recipient != null && (email.getToAddresses() == null - || !email.getToAddresses().contains(recipient))) { + if (source != null && !source.equals(email.getSource())) { continue; } ObjectNode node = objectMapper.createObjectNode(); @@ -144,8 +145,12 @@ public class SesInspectionController { } @DELETE - public Response clearEmails() { - sentEmailService.clear(); + public Response clearEmails(@QueryParam("id") String messageId) { + if (messageId != null) { + sentEmailService.delete(messageId); + } else { + sentEmailService.clear(); + } return Response.ok().build(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java index 72ae5ebec6..f9d8ca2fc0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java @@ -8,6 +8,8 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Instant; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; @@ -64,8 +66,21 @@ public class SesSentEmailService { return emailStore.scan(k -> k.startsWith(prefix)); } + /** Every stored message across regions, oldest first. */ public List listAll() { - return emailStore.scan(k -> k.startsWith("email::")); + return emailStore.scan(k -> k.startsWith("email::")).stream() + .sorted(Comparator.comparing(SentEmail::getSentAt, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .toList(); + } + + /** Removes the message with this id from whichever region holds it; an unknown id removes nothing. */ + public void delete(String messageId) { + List keys = emailStore.keys().stream() + .filter(key -> messageId.equals(messageIdOf(key))) + .toList(); + keys.forEach(emailStore::delete); + LOG.infov("Deleted SES email {0} ({1} record(s))", messageId, keys.size()); } public void clear() { @@ -76,4 +91,13 @@ public class SesSentEmailService { private static String emailKey(String region, String messageId) { return "email::" + region + "::" + messageId; } + + // The inverse of emailKey: a region never contains the separator, so the id follows the second. + private static String messageIdOf(String key) { + if (!key.startsWith("email::")) { + return null; + } + int separator = key.indexOf("::", "email::".length()); + return separator < 0 ? null : key.substring(separator + 2); + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d4c8c60bd5..45283ea2ad 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -538,7 +538,7 @@ floci: list-shards-next-token-ttl-millis: 300000 firehose: enabled: true - tick-interval-seconds: 10 + tick-interval-seconds: 1 flush-record-count: 0 staging-bucket: floci-firehose-staging kms: diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java index b36c31a9e4..67e60fac53 100644 --- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineSpy; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -31,7 +32,6 @@ import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; 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; @@ -284,7 +284,7 @@ class TlsCertificateManagerTest extends TlsCertificateManagerFixture { @Test void aFailedReissueLeavesTheServedFilesIntactAndDoesNotThrow() throws Exception { - FlociCertificateAuthority broken = spy(ca); + FlociCertificateAuthority broken = inlineSpy(ca); doThrow(new IllegalStateException("boom")).when(broken).issueServerCertificate(anyString(), anyList(), any(), any()); byte[] certBefore = servedCertificate(); String metadataBefore = Files.readString(tlsDir.resolve("floci-server.metadata.json")); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java index 422a4bb1a5..de22191292 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java @@ -4,6 +4,7 @@ import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerResponseContext; import org.junit.jupiter.api.Test; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -14,7 +15,7 @@ class AwsRestJsonErrorHeaderFilterTest { @Test void doesNotAddRestJsonHeaderToJsonProtocolErrorForDualProtocolService() { ResolvedServiceCatalog catalog = mock(ResolvedServiceCatalog.class); - ServiceDescriptor dualProtocolService = mock(ServiceDescriptor.class); + ServiceDescriptor dualProtocolService = inlineMock(ServiceDescriptor.class); when(dualProtocolService.supportsProtocol(ServiceProtocol.REST_JSON)).thenReturn(true); ContainerRequestContext request = mock(ContainerRequestContext.class); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCpuLimitTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCpuLimitTest.java index 51d837c31a..5e4ded9b1e 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCpuLimitTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCpuLimitTest.java @@ -75,6 +75,13 @@ class ContainerLifecycleManagerCpuLimitTest { assertTrue(hostConfig.getReadonlyRootfs()); } + @Test + void initReachesHostConfig() { + HostConfig hostConfig = createHostConfig(EIGHT_CPU_HOST, ContainerBuilder.Builder::withInit); + + assertTrue(hostConfig.getInit()); + } + @Test void containerThatAskedForNoCpuLimitGetsNone() { HostConfig hostConfig = createHostConfig(EIGHT_CPU_HOST, UnaryOperator.identity()); @@ -82,6 +89,7 @@ class ContainerLifecycleManagerCpuLimitTest { assertNull(hostConfig.getNanoCPUs()); assertNull(hostConfig.getCpuShares()); assertNull(hostConfig.getReadonlyRootfs()); + assertNull(hostConfig.getInit()); } /** diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java index 82839ecbf0..1878ece4d3 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java @@ -260,7 +260,7 @@ class ContainerLifecycleManagerNetworkTest { "busybox:stable", "probe", List.of(), null, null, null, portBindings, List.of(), exposedPorts, networkMode, List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of(), List.of(), null, null, false, - List.of(), Map.of()); + List.of(), Map.of(), false); } private static ContainerSpec specWithLinkLocalIp(Map portBindings) { @@ -268,6 +268,6 @@ class ContainerLifecycleManagerNetworkTest { "busybox:stable", null, List.of(), null, null, null, portBindings, List.of(), List.of(), "test-network", List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of(), List.of(), null, null, false, - List.of(LINK_LOCAL_IP), Map.of()); + List.of(LINK_LOCAL_IP), Map.of(), false); } } diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerTest.java index 5e583ed2c3..547b0423c9 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerTest.java @@ -14,6 +14,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; +import org.mockito.MockMakers; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; @@ -40,7 +41,7 @@ class EmulatorInfoControllerTest { @Mock private StorageFactory storageFactory; @Mock private Instance resettables; @Mock private Instance containerTeardowns; - @Mock private FlociCertificateAuthority certificateAuthority; + @Mock(mockMaker = MockMakers.INLINE) private FlociCertificateAuthority certificateAuthority; @Mock private EmulatorConfig config; @Mock private DynamoDbBackendSelector dynamoDbBackendSelector; @Mock private ContainerTeardown sageMakerTeardown; diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 2a94b0c135..3eed1f8c23 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -47,6 +47,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; +import org.mockito.MockMakers; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @@ -488,7 +489,8 @@ class EmulatorLifecycleTest { .when(initializationHooksRunner).run(InitializationHook.START); Thread.interrupted(); - try (MockedStatic quarkus = Mockito.mockStatic(Quarkus.class)) { + try (MockedStatic quarkus = Mockito.mockStatic(Quarkus.class, + Mockito.withSettings().mockMaker(MockMakers.INLINE))) { try { emulatorLifecycle.onHttpStart(new HttpServerStart(new HttpServerOptions().setPort(4566))); diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java index d124634f7e..3183f45de4 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java @@ -19,6 +19,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; + @ExtendWith(MockitoExtension.class) class InitializationHooksRunnerTest { @@ -165,7 +167,7 @@ class InitializationHooksRunnerTest { @DisplayName("hasHooks should return true when scripts exist in a primary directory") void hasHooksShouldReturnTrueWhenScriptsExist(@TempDir Path tempDir) throws IOException { Files.createFile(tempDir.resolve("01-setup.sh")); - InitializationHook hook = Mockito.mock(InitializationHook.class); + InitializationHook hook = inlineMock(InitializationHook.class); Mockito.when(hook.getName()).thenReturn("startup"); Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile())); Mockito.when(hook.getCompatPaths()).thenReturn(List.of()); @@ -177,7 +179,7 @@ class InitializationHooksRunnerTest { @DisplayName("hasHooks should return true when scripts exist only in a compat directory") void hasHooksShouldReturnTrueWhenScriptsExistInCompatDir(@TempDir Path tempDir) throws IOException { Files.createFile(tempDir.resolve("01-setup.sh")); - InitializationHook hook = Mockito.mock(InitializationHook.class); + InitializationHook hook = inlineMock(InitializationHook.class); Mockito.when(hook.getName()).thenReturn("startup"); Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of()); Mockito.when(hook.getCompatPaths()).thenReturn(List.of(tempDir.toFile())); @@ -188,7 +190,7 @@ class InitializationHooksRunnerTest { @Test @DisplayName("hasHooks should return false when all hook directories are empty") void hasHooksShouldReturnFalseWhenDirectoryIsEmpty(@TempDir Path tempDir) { - InitializationHook hook = Mockito.mock(InitializationHook.class); + InitializationHook hook = inlineMock(InitializationHook.class); Mockito.when(hook.getName()).thenReturn("startup"); Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile())); Mockito.when(hook.getCompatPaths()).thenReturn(List.of()); @@ -199,7 +201,7 @@ class InitializationHooksRunnerTest { @Test @DisplayName("hasHooks should return false when hook directories do not exist") void hasHooksShouldReturnFalseWhenDirectoryDoesNotExist() { - InitializationHook hook = Mockito.mock(InitializationHook.class); + InitializationHook hook = inlineMock(InitializationHook.class); Mockito.when(hook.getName()).thenReturn("startup"); Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(new File("/nonexistent/path"))); Mockito.when(hook.getCompatPaths()).thenReturn(List.of()); @@ -215,7 +217,7 @@ class InitializationHooksRunnerTest { Files.createFile(compatDir.resolve("01-seed.sh")); Files.createFile(compatDir.resolve("02-extra.sh")); - InitializationHook hook = Mockito.mock(InitializationHook.class); + InitializationHook hook = inlineMock(InitializationHook.class); Mockito.when(hook.getName()).thenReturn("ready"); Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(primaryDir.toFile())); Mockito.when(hook.getCompatPaths()).thenReturn(List.of(compatDir.toFile())); diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java index c2d7512732..b88ecbfd40 100644 --- a/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java @@ -71,7 +71,7 @@ class RabbitMqManagerTest { private static ContainerBuilder.Builder selfReturningBuilder(ContainerBuilder containerBuilder) { ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); return builder; } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java index b5ddacc92b..23f80b1ab3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java @@ -139,7 +139,7 @@ class NodeAppSyncJsRuntimeTest { ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(org.mockito.Answers.RETURNS_SELF)); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); Set created = ConcurrentHashMap.newKeySet(); Set stopped = ConcurrentHashMap.newKeySet(); diff --git a/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java index 92940e911b..5e681033ad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java @@ -89,7 +89,7 @@ class BatchDockerRunnerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), config, detector); @@ -144,7 +144,7 @@ class BatchDockerRunnerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class)); BatchJob job = job(); @@ -181,7 +181,7 @@ class BatchDockerRunnerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class)); @@ -228,7 +228,7 @@ class BatchDockerRunnerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class)); BatchJob job = job(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSchedulerScheduleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSchedulerScheduleIntegrationTest.java index 2d28008c68..473b64577f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSchedulerScheduleIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSchedulerScheduleIntegrationTest.java @@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Locale; @@ -31,7 +30,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import static io.restassured.RestAssured.given; -import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertAll; @@ -296,6 +294,8 @@ class CloudFormationSchedulerScheduleIntegrationTest { Queue queue = sqs.createQueue("external-" + suffix, Map.of(), "us-east-1"); prepareFailedRollback(stack, name, queue); allowOriginalRestore(name); + continueUpdateRollback(stack); + outputs(stack, "UPDATE_ROLLBACK_COMPLETE"); cloudFormation(stack, "UpdateStack", externalQueueTemplate(FAILURE, queue), Map.of("Name", name, "Expression", "rate(15 minutes)", "Payload", "third")); @@ -318,8 +318,9 @@ class CloudFormationSchedulerScheduleIntegrationTest { prepareFailedRollback(stack, name, queue); String snapshot = scheduleResource(stack).getAttributes().get("__FlociSchedulerUpdateSnapshot"); - cloudFormation(stack, "UpdateStack", externalQueueTemplate("", queue), + assertUpdateRefused(stack, externalQueueTemplate("", queue), Map.of("Name", name, "Expression", "rate(15 minutes)", "Payload", "third")); + continueUpdateRollback(stack); outputs(stack, "UPDATE_ROLLBACK_FAILED"); getSchedule(name, "default").then().statusCode(200) @@ -339,24 +340,13 @@ class CloudFormationSchedulerScheduleIntegrationTest { Queue queue = sqs.createQueue("external-" + suffix, Map.of(), "us-east-1"); prepareFailedRollback(stack, name, queue); String snapshot = scheduleResource(stack).getAttributes().get("__FlociSchedulerUpdateSnapshot"); - String unchanged = externalQueueTemplate("", queue); - cloudFormation(stack, "UpdateStack", unchanged, Map.of("Name", name)); - await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> - given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) - .formParam("Action", "DescribeStacks").formParam("StackName", stack).post("/") - .then().statusCode(200) - .body(containsString("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS")) - .body(containsString("Schedule rollback is still pending"))); + assertUpdateRefused(stack, externalQueueTemplate("", queue), Map.of("Name", name)); + outputs(stack, "UPDATE_ROLLBACK_FAILED"); assertEquals(snapshot, scheduleResource(stack).getAttributes().get("__FlociSchedulerUpdateSnapshot")); - assertEquals(unchanged, cloudFormation.describeStacks(stack, "us-east-1").getFirst().getOriginalTemplateBody()); getSchedule(name, "default").then().statusCode(200) .body("ScheduleExpression", equalTo("rate(10 minutes)")) .body("Target.Input", equalTo("payload:changed")); - given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) - .formParam("Action", "UpdateStack").formParam("StackName", stack) - .formParam("TemplateBody", unchanged).post("/").then().statusCode(400) - .body(containsString("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS")); deleteStack(stack); getSchedule(name, "default").then().statusCode(404); sqs.deleteQueue(queue.getQueueUrl(), "us-east-1"); @@ -510,6 +500,10 @@ class CloudFormationSchedulerScheduleIntegrationTest { given().delete("/schedules/" + replacementName).then().statusCode(200); doThrow(new AwsException("InternalServerException", "replacement deletion still unavailable", 500)) .when(scheduler).deleteSchedule(replacementName, "default", "us-east-1"); + // With its delete still failing, the rollback finishes only by skipping the schedule, which + // keeps the replacement owed when the next update recreates it at the same address. + continueUpdateRollback(stack, "Schedule"); + outputs(stack, "UPDATE_ROLLBACK_COMPLETE"); // Change both resources so the engine actually retries the replacement and its failing dependent. String repeatedFailure = FAILURE.replace("\"SecretString\":\"explicit\"", @@ -628,6 +622,11 @@ class CloudFormationSchedulerScheduleIntegrationTest { recreateScheduleViaApi(name, "default"); try { + continueUpdateRollback(stack); + outputs(stack, "UPDATE_ROLLBACK_COMPLETE"); + getSchedule(name, "default").then().statusCode(200) + .body("ScheduleExpression", equalTo("rate(5 minutes)")) + .body("Target.Input", equalTo("payload:first")); cloudFormation(stack, "UpdateStack", externalQueueTemplate("", queue), Map.of("Name", name, "Expression", "rate(15 minutes)", "Payload", "new")); outputs(stack, "UPDATE_COMPLETE"); @@ -683,6 +682,10 @@ class CloudFormationSchedulerScheduleIntegrationTest { && group.equals(request.getGroupName())), eq("us-east-1")); try { + continueUpdateRollback(stack); + outputs(stack, "UPDATE_ROLLBACK_COMPLETE"); + assertTrue(pausedRecreatedDestination.get()); + getSchedule(name, group).then().statusCode(404); cloudFormation(stack, "UpdateStack", externalQueueTemplate("", queue), Map.of("Name", name, "Expression", "rate(15 minutes)", "Payload", "new")); outputs(stack, "UPDATE_COMPLETE"); @@ -1030,6 +1033,11 @@ class CloudFormationSchedulerScheduleIntegrationTest { } private static void cloudFormation(String stack, String action, String template, Map parameters) { + cloudFormationRequest(stack, action, template, parameters).post("/").then().statusCode(200); + } + + private static RequestSpecification cloudFormationRequest(String stack, String action, String template, + Map parameters) { RequestSpecification request = given().contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH).formParam("Action", action).formParam("StackName", stack); if (template != null) { @@ -1041,6 +1049,20 @@ class CloudFormationSchedulerScheduleIntegrationTest { request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue()); index++; } + return request; + } + + // AWS refuses an update over UPDATE_ROLLBACK_FAILED: only ContinueUpdateRollback or DeleteStack proceeds. + private static void assertUpdateRefused(String stack, String template, Map parameters) { + cloudFormationRequest(stack, "UpdateStack", template, parameters).post("/").then().statusCode(400) + .body(containsString("is in UPDATE_ROLLBACK_FAILED state and can not be updated.")); + } + + private static void continueUpdateRollback(String stack, String... resourcesToSkip) { + RequestSpecification request = cloudFormationRequest(stack, "ContinueUpdateRollback", null, Map.of()); + for (int i = 0; i < resourcesToSkip.length; i++) { + request.formParam("ResourcesToSkip.member." + (i + 1), resourcesToSkip[i]); + } request.post("/").then().statusCode(200); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java index 5d2b62982f..1ebba9a746 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java @@ -30,6 +30,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -489,6 +490,39 @@ class CloudWatchDashboardCfnProvisionerTest { assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); } + /** + * A replacement whose rollback could not delete it stays owed. A later update reaches the + * dashboard only once ContinueUpdateRollback skipped it, and that update's own unwind restores + * its snapshot and leaves the orphan to the cleanup instead of retrying its delete. + */ + @Test + void anUnwindAfterASkippedRollbackRestoresTheBodyAndLeavesTheOrphanOwed() { + StackResource r = provision(""" + {"DashboardName": "ops-v2", "DashboardBody": "{}"} + """, "ops"); + doThrow(new AwsException("InternalServiceError", "delete unavailable", 500)).doNothing() + .when(dashboards).deleteDashboards(List.of("ops-v2"), REGION); + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + assertEquals("ops", r.getPhysicalId()); + assertEquals("ops-v2", provisioner.updateCleanupPhysicalId(r)); + Dashboard before = new Dashboard("ops", arn("ops"), OLD_BODY); + before.setTags(new HashMap<>(Map.of("team", "platform"))); + when(dashboards.getDashboard("ops", REGION)).thenReturn(before); + when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform")); + doThrow(new AwsException("InternalServiceError", "boom", 500)) + .when(dashboards).untagResource(arn("ops"), List.of("team"), REGION); + r.getAttributes().put("FlociDashboardNameMode", "explicit"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "env", "Value": "dev"}]} + """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops"))); + + verify(dashboards).putDashboard(eq("ops"), eq(OLD_BODY), anyMap(), eq(REGION)); + assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)); + verify(dashboards, times(1)).deleteDashboards(List.of("ops-v2"), REGION); + assertEquals("ops-v2", provisioner.updateCleanupPhysicalId(r)); + } + /** * An unwind that cannot put the body back keeps the snapshot and records the failure, so the * stack ends in UPDATE_ROLLBACK_FAILED instead of claiming the prior dashboard is live. diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java index db07f0d41a..86b01728a1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java @@ -498,6 +498,34 @@ class CognitoResourceServerCfnProvisionerTest { assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate")); } + /** + * A replacement whose rollback could not delete it stays owed. A later update reaches the + * resource server only once ContinueUpdateRollback skipped it, and rolling back that update's + * failed attempt restores its own snapshot instead of retrying the orphan's delete. + */ + @Test + void aFailedAttemptAfterASkippedRollbackRestoresItsSnapshotAndLeavesTheOrphanOwed() { + StackResource resource = resource(IDENTIFIER, POOL); + provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "Replacement API"), ctx(IDENTIFIER)); + doThrow(new AwsException("InternalErrorException", "delete failed", 500)).doNothing() + .when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER); + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource)); + assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId")); + assertTrue(provisioner.hasReplacementUpdate(resource)); + when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API")); + doThrow(new AwsException("InternalErrorException", "update failed", 500)) + .when(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("New API"), any()); + + assertThrows(AwsException.class, () -> provisioner.provision(resource, + properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER))); + assertTrue(provisioner.rollbackUpdate(resource)); + + verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any()); + assertFalse(provisioner.retainsFailedUpdateState(resource)); + verify(cognito, times(1)).deleteResourceServer(NEW_POOL, IDENTIFIER); + assertTrue(provisioner.hasReplacementUpdate(resource)); + } + @Test void aRecoveredReplacementUsesTheRestoredIdentityForTheNextAttempt() { String replacementIdentifier = "https://replacement.example.com"; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisionerTest.java index fec4430fa4..fdf3f17312 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IotAuthorizerCfnProvisionerTest.java @@ -41,6 +41,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -396,6 +397,32 @@ class IotAuthorizerCfnProvisionerTest { assertFalse(resource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)); } + /** + * A replacement whose rollback could not delete it stays owed. A later update reaches the + * authorizer only once ContinueUpdateRollback skipped it, and that update's own unwind restores + * its snapshot and leaves the orphan to the cleanup instead of retrying its delete. + */ + @Test + void anUnwindAfterASkippedRollbackRestoresTheAuthorizerAndLeavesTheOrphanOwed() { + StackResource resource = create(props("auth").put("SigningDisabled", true).put("Status", "ACTIVE")); + update(resource, props("auth-2").put("SigningDisabled", true)); + doThrow(new AwsException("InternalFailureException", "delete down", 500)).doNothing() + .when(service).deleteAuthorizer("auth-2", REGION); + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource)); + assertEquals("auth", resource.getPhysicalId()); + assertEquals("auth-2", provisioner.updateCleanupPhysicalId(resource)); + doThrow(new AwsException("InternalFailureException", "tags down", 500)) + .when(service).tagResource(anyString(), anyMap()); + + assertThrows(AwsException.class, () -> update(resource, props("auth") + .put("SigningDisabled", true).put("Status", "INACTIVE").set("Tags", tags("team", "a")))); + + assertEquals("ACTIVE", authorizers.get("auth").getStatus()); + assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)); + verify(service, times(1)).deleteAuthorizer("auth-2", REGION); + assertEquals("auth-2", provisioner.updateCleanupPhysicalId(resource)); + } + @Test void renamingTheAuthorizerReplacesItAndDeletesTheOldOneOnCommit() { StackResource resource = create(props("auth").put("SigningDisabled", true).put("Status", "ACTIVE")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java index 24ba4918bb..22e46853c6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventSourceMappingCfnProvisionerTest.java @@ -17,6 +17,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -78,7 +79,7 @@ class LambdaEventSourceMappingCfnProvisionerTest { }); when(engine.resolveNode(any())).thenAnswer(inv -> resolveMockNode((JsonNode) inv.getArgument(0), engine)); - ProvisionContext context = mock(ProvisionContext.class); + ProvisionContext context = inlineMock(ProvisionContext.class); when(context.engine()).thenReturn(engine); when(context.region()).thenReturn("us-east-1"); when(context.accountId()).thenReturn("000000000000"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java index ee560a4a61..4e89e3da62 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java @@ -526,6 +526,8 @@ class SchedulerScheduleCfnProvisionerTest { when(scheduler.createSchedule(argThat(r -> "c".equals(r.getGroupName())), eq(REGION))) .thenThrow(new AwsException("ConflictException", "destination owned elsewhere", 409)); + // The stack takes this update only after ContinueUpdateRollback skipped the schedule, so the + // orphan is still owed, and the failed move's own restore must not retry its delete. assertThrows(AwsException.class, () -> provisioner.provision(resource, properties("same", "c"), context("same"))); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManagerTest.java index cec938ae8c..47392f72c2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarManagerTest.java @@ -2,18 +2,28 @@ package io.github.hectorvent.floci.services.codeartifact; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.ContainerTeardown; +import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.lang.reflect.Field; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; /** * {@link PypiserverSidecarManager#stopManagedContainers()} is a thin delegation to @@ -46,6 +56,31 @@ class PypiserverSidecarManagerTest { verify(lifecycleManager).stopAndRemove("tracked-pypiserver-2", null); } + /** + * pypi-server installs no SIGTERM handler, so without an init process as PID 1 it ignores the + * stop request and every stop waits out the whole timeout. The start is failed right after the + * create, so the test needs neither Docker nor a health endpoint. + */ + @Test + void containerRunsUnderAnInitProcessSoAStopEndsItAtOnce() { + EmulatorConfig deepConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(deepConfig.services().codeartifact().pypiImage()).thenReturn("pypiserver/pypiserver:v2.4.2"); + when(deepConfig.services().dockerNetwork()).thenReturn(Optional.empty()); + when(deepConfig.docker().resourceNamespace()).thenReturn(Optional.empty()); + when(deepConfig.docker().logMaxSize()).thenReturn("10m"); + when(deepConfig.docker().logMaxFile()).thenReturn("3"); + ContainerBuilder realBuilder = new ContainerBuilder( + deepConfig, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)); + when(lifecycleManager.startCreated(any(), any())).thenThrow(new IllegalStateException("no Docker here")); + PypiserverSidecarManager manager = new PypiserverSidecarManager(realBuilder, lifecycleManager, deepConfig); + + assertThrows(IllegalStateException.class, () -> manager.ensureReady("pypi-repo-1", "http://localhost:4566")); + + ArgumentCaptor spec = ArgumentCaptor.forClass(ContainerSpec.class); + verify(lifecycleManager).create(spec.capture()); + assertTrue(spec.getValue().init()); + } + @Test void stopManagedContainersIsANoOpWhenNothingWasEverStarted() { PypiserverSidecarManager manager = manager(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationConcurrencyTest.java index 473a2e4849..cab89d66cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationConcurrencyTest.java @@ -26,6 +26,7 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -47,8 +48,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void concurrentUpdatesAreSerializedPerUser() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); AtomicInteger issues = new AtomicInteger(); AtomicReference latestCode = new AtomicReference<>(); @@ -108,8 +109,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void resendAndUpdateAreSerializedPerUser() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); AtomicInteger issues = new AtomicInteger(); AtomicReference latestCode = new AtomicReference<>(); @@ -164,8 +165,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void verifyAndUpdateAreSerializedPerUser() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); AtomicInteger issues = new AtomicInteger(); CountDownLatch consumeEntered = new CountDownLatch(1); @@ -212,8 +213,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void verificationFinishingAfterAdminUpdateDoesNotOverwriteAdminEmail() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); CountDownLatch consumeEntered = new CountDownLatch(1); CountDownLatch releaseConsume = new CountDownLatch(1); @@ -260,8 +261,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void verificationFinishingAfterAdminDeleteDoesNotRestoreDeletedEmail() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); CountDownLatch consumeEntered = new CountDownLatch(1); CountDownLatch releaseConsume = new CountDownLatch(1); @@ -308,8 +309,8 @@ class CognitoAttributeVerificationConcurrencyTest { @Test void verificationFinishingAfterAdminUserDeleteDoesNotResurrectTheUser() throws Exception { - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); CountDownLatch consumeEntered = new CountDownLatch(1); CountDownLatch releaseConsume = new CountDownLatch(1); @@ -360,8 +361,8 @@ class CognitoAttributeVerificationConcurrencyTest { // five: ChangePassword never touched pending-attribute state before this fix, so // nothing stopped it from racing VerifyUserAttribute's read-modify-write on the same // whole-object user record. - VerificationCodeService codes = mock(VerificationCodeService.class); - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService codes = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); Harness harness = harness(codes, dispatcher); CountDownLatch consumeEntered = new CountDownLatch(1); CountDownLatch releaseConsume = new CountDownLatch(1); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java index 7011e4e5a1..ce4268e1a9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testutil.SesMailbox; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; @@ -411,14 +412,7 @@ class CognitoAttributeVerificationIntegrationTest { } private static String fetchLatestSesVerificationCode(String recipient) throws Exception { - String response = given() - .queryParam("email", recipient) - .get("/_aws/ses") - .then() - .statusCode(200) - .extract() - .asString(); - JsonNode messages = JSON.readTree(response).path("messages"); + JsonNode messages = SesMailbox.messagesTo(recipient); assertTrue(messages.isArray() && !messages.isEmpty()); return extractVerificationCode(messages.get(0).path("Body").path("text_part").asText()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java index c0a2d0e9bf..bc7ab24417 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java @@ -1,8 +1,8 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testutil.SesMailbox; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; @@ -36,7 +36,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class CognitoGetUserAuthFactorsIntegrationTest { - private static final ObjectMapper JSON = new ObjectMapper(); private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b"); private static final String PASSWORD = "Factors1234!"; @@ -360,14 +359,7 @@ class CognitoGetUserAuthFactorsIntegrationTest { } private static String fetchLatestSesCode(String recipient) throws Exception { - String response = given() - .queryParam("email", recipient) - .get("/_aws/ses") - .then() - .statusCode(200) - .extract() - .asString(); - JsonNode messages = JSON.readTree(response).path("messages"); + JsonNode messages = SesMailbox.messagesTo(recipient); assertTrue(messages.isArray() && !messages.isEmpty(), "an EMAIL_OTP code should have been sent"); Matcher matcher = SIX_DIGIT_CODE.matcher(messages.get(0).path("Body").path("text_part").asText()); assertTrue(matcher.find(), "the EMAIL_OTP message should carry a six-digit code"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java index e54dd4ba65..e9d2401e1a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testutil.SesMailbox; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; import org.junit.jupiter.api.BeforeAll; @@ -1159,13 +1160,7 @@ class CognitoIntegrationTest { .body("__type", equalTo("NotAuthorizedException")) .body("message", equalTo("Contact administrator to reset password.")); - given() - .queryParam("email", email) - .when() - .get("/_aws/ses") - .then() - .statusCode(200) - .body("messages", hasSize(0)); + assertEquals(0, SesMailbox.messagesTo(email).size()); } @Test @@ -3601,16 +3596,7 @@ class CognitoIntegrationTest { } private static String fetchLatestSesVerificationCode(String recipient) throws Exception { - String response = given() - .queryParam("email", recipient) - .when() - .get("/_aws/ses") - .then() - .statusCode(200) - .extract() - .asString(); - JsonNode payload = OBJECT_MAPPER.readTree(response); - String body = payload.path("messages").get(0).path("Body").path("text_part").asText(); + String body = SesMailbox.messagesTo(recipient).get(0).path("Body").path("text_part").asText(); Matcher matcher = SIX_DIGIT_CODE.matcher(body); assertTrue(matcher.find(), "verification code email should contain a 6-digit code"); return matcher.group(1); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 5a6767aef7..210e26e0ba 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -51,6 +51,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -467,7 +468,7 @@ class CognitoLambdaTriggersTest { @Test void postConfirmationFiresOnConfirmForgotPassword() throws Exception { - VerificationCodeService verificationCodes = mock(VerificationCodeService.class); + VerificationCodeService verificationCodes = inlineMock(VerificationCodeService.class); CognitoService svc = createServiceWithMessaging( mock(SesService.class), mock(SnsService.class), verificationCodes); UserPool pool = svc.createUserPool(Map.of( @@ -2145,7 +2146,7 @@ class CognitoLambdaTriggersTest { @Test void customMessageOverridesSignUpVerificationEmail() { SesService ses = mock(SesService.class); - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("246962"); CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService); @@ -2170,7 +2171,7 @@ class CognitoLambdaTriggersTest { @Test @SuppressWarnings("unchecked") void customMessageSignUpTriggerReceivesCodeParameterAndUsername() throws Exception { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("246962"); CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class), @@ -2199,7 +2200,7 @@ class CognitoLambdaTriggersTest { @Test void customMessageLambdaErrorFallsBackToDefaultSignUpMessage() { SesService ses = mock(SesService.class); - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("246962"); CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService); @@ -2223,7 +2224,7 @@ class CognitoLambdaTriggersTest { @Test void customMessageDoesNotFireWhenNotConfigured() { SesService ses = mock(SesService.class); - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("246962"); CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService); @@ -2243,7 +2244,7 @@ class CognitoLambdaTriggersTest { @Test @SuppressWarnings("unchecked") void customMessageFiresWithResendCodeTriggerSourceOnResendConfirmationCode() throws Exception { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("111222"); CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class), @@ -2270,7 +2271,7 @@ class CognitoLambdaTriggersTest { @Test @SuppressWarnings("unchecked") void customMessageFiresWithForgotPasswordTriggerSourceOnForgotPassword() throws Exception { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.PASSWORD_RESET), any())) .thenReturn("333444"); CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class), @@ -2299,7 +2300,7 @@ class CognitoLambdaTriggersTest { void customMessageOverridesTheAdminCreateUserInvitation() { SesService ses = mock(SesService.class); CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), - mock(VerificationCodeService.class)); + inlineMock(VerificationCodeService.class)); UserPool pool = svc.createUserPool(Map.of( "PoolName", "trigger-pool", "LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1"); @@ -2319,7 +2320,7 @@ class CognitoLambdaTriggersTest { @SuppressWarnings("unchecked") void customMessageAdminCreateUserTriggerReceivesPlaceholdersAndClientMetadata() throws Exception { CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class), - mock(VerificationCodeService.class)); + inlineMock(VerificationCodeService.class)); UserPool pool = svc.createUserPool(Map.of( "PoolName", "trigger-pool", "LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1"); @@ -2343,7 +2344,7 @@ class CognitoLambdaTriggersTest { @Test void customMessageDoesNotFireForAnInvitationWithNowhereToGo() { CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class), - mock(VerificationCodeService.class)); + inlineMock(VerificationCodeService.class)); UserPool pool = svc.createUserPool(Map.of( "PoolName", "trigger-pool", "LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java index 3fa82c33a0..23f3641add 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testutil.SesMailbox; import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; @@ -1375,10 +1376,8 @@ class CognitoManagedLoginIntegrationTest { return matcher.group(1); } - private static JsonNode emailsTo(String email) throws Exception { - String body = given().queryParam("email", email).when().get("/_aws/ses") - .then().statusCode(200).extract().asString(); - return MAPPER.readTree(body).path("messages"); + private static JsonNode emailsTo(String email) { + return SesMailbox.messagesTo(email); } private static String differentCode(String code) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index 1d9605e4d4..d7a7cd702d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -61,6 +61,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -2080,8 +2081,8 @@ class CognitoServiceTest { @Test void signUpWithoutDeliveryTargetFailsBeforePersistingUser() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); CognitoService serviceWithVerification = new CognitoService( new InMemoryStorage<>(), new InMemoryStorage<>(), @@ -2116,8 +2117,8 @@ class CognitoServiceTest { @Test void signUpRollsBackUserWhenDispatchFails() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("123456"); doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher) @@ -2239,8 +2240,8 @@ class CognitoServiceTest { @Test @SuppressWarnings("unchecked") void expiredPendingEmailCodeLeavesActiveAttributeAndVerifiedFlagUnchanged() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any())) .thenReturn("123456"); @@ -2303,8 +2304,8 @@ class CognitoServiceTest { @Test @SuppressWarnings("unchecked") void verificationCodeForRequiredEmailUpdateUsesPendingDestination() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any())) .thenReturn("123456"); @@ -2364,8 +2365,8 @@ class CognitoServiceTest { @Test void adminContactUpdateClearsOnlyMatchingPendingValueAndVerificationCode() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); PendingContactFixture fixture = createPendingContactFixture( verificationCodeService, messageDispatcher); clearInvocations(verificationCodeService); @@ -2391,8 +2392,8 @@ class CognitoServiceTest { @Test void adminContactDeleteClearsOnlyMatchingPendingValueAndVerificationCode() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); PendingContactFixture fixture = createPendingContactFixture( verificationCodeService, messageDispatcher); clearInvocations(verificationCodeService); @@ -3405,8 +3406,8 @@ class CognitoServiceTest { @Test @SuppressWarnings("unchecked") void initiateAuthWithUserAuthOffersEmailOtpWhenVerificationIsConfiguredAndEmailVerified() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn("654321"); CognitoService serviceWithVerification = new CognitoService( @@ -3461,8 +3462,8 @@ class CognitoServiceTest { @Test @SuppressWarnings("unchecked") void initiateAuthWithUserAuthOffersSmsOtpWhenVerificationIsConfiguredAndPhoneVerified() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SMS_OTP), any())) .thenReturn("135790"); CognitoService serviceWithVerification = new CognitoService( @@ -3516,8 +3517,8 @@ class CognitoServiceTest { @Test void respondToEmailOtpChallengeRejectsWrongCode() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn("654321"); doThrow(new VerificationCodeException(VerificationCodeException.Kind.MISMATCH, "nope")) @@ -3657,7 +3658,7 @@ class CognitoServiceTest { @ParameterizedTest @CsvSource({"PASSWORD", "SMS_OTP", "WEB_AUTHN"}) void initiateAuthWithUserAuthOffersTheChoiceForAPreferredChallengeTheUserCannotTake(String preferred) { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); CognitoService serviceWithVerification = serviceWithVerification(verificationCodeService); UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP", "SMS_OTP"); UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false); @@ -3691,7 +3692,7 @@ class CognitoServiceTest { /** Managed login asks again after a wrong code, so the USER_AUTH session must outlive one. */ @Test void managedLoginEmailOtpKeepsTheSessionForAnotherTryAfterAWrongCode() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn("654321"); doThrow(new VerificationCodeException(VerificationCodeException.Kind.MISMATCH, "nope")) @@ -3839,7 +3840,7 @@ class CognitoServiceTest { @ParameterizedTest @CsvSource({"page", "api"}) void slowCodeRedemptionForOneUserDoesNotHoldUpAnotherUsersSignIn(String aliceAnswersThrough) throws Exception { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn("654321"); CountDownLatch aliceRedeeming = new CountDownLatch(1); @@ -3884,14 +3885,14 @@ class CognitoServiceTest { /** A service whose EMAIL_OTP code is always {@code code}, with delivery mocked out. */ private CognitoService serviceWithEmailOtpCode(String code) { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn(code); return serviceWithVerification(verificationCodeService); } private CognitoService serviceWithVerification(VerificationCodeService verificationCodeService) { - return serviceWithVerification(verificationCodeService, mock(CognitoMessageDispatcher.class)); + return serviceWithVerification(verificationCodeService, inlineMock(CognitoMessageDispatcher.class)); } private CognitoService serviceWithVerification(VerificationCodeService verificationCodeService, @@ -3921,7 +3922,7 @@ class CognitoServiceTest { * {@code clock}, that puts each code it sends in {@code sentCode}. */ private CognitoService serviceWithSlowCodeStore(Clock clock, AtomicReference sentCode) { - CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class); + CognitoMessageDispatcher dispatcher = inlineMock(CognitoMessageDispatcher.class); doAnswer(invocation -> { sentCode.set(invocation.getArgument(3)); return null; @@ -3958,8 +3959,8 @@ class CognitoServiceTest { @Test void issueOtpChallengeSurfacesRateLimitInsteadOfAGenericDeliveryFailure() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenThrow(new VerificationCodeException( VerificationCodeException.Kind.RATE_LIMIT, "Attempt limit exceeded")); @@ -3999,8 +4000,8 @@ class CognitoServiceTest { @Test void issueOtpChallengeInvalidatesTheIssuedCodeWhenDispatchFails() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any())) .thenReturn("777888"); doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher) @@ -5515,8 +5516,8 @@ class CognitoServiceTest { } private CognitoService createVerificationEnabledService() { - VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + VerificationCodeService verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any())) .thenReturn("123456"); return new CognitoService( @@ -5552,8 +5553,8 @@ class CognitoServiceTest { @BeforeEach void setUpVerification() { - verificationCodeService = mock(VerificationCodeService.class); - CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class); + verificationCodeService = inlineMock(VerificationCodeService.class); + CognitoMessageDispatcher messageDispatcher = inlineMock(CognitoMessageDispatcher.class); svc = new CognitoService( new InMemoryStorage<>(), new InMemoryStorage<>(), @@ -6585,7 +6586,7 @@ class CognitoServiceTest { @BeforeEach void setUpMessaging() { - messageDispatcher = mock(CognitoMessageDispatcher.class); + messageDispatcher = inlineMock(CognitoMessageDispatcher.class); svc = new CognitoService( new InMemoryStorage<>(), new InMemoryStorage<>(), @@ -6599,7 +6600,7 @@ class CognitoServiceTest { regionResolver, null, acmService, - mock(VerificationCodeService.class), + inlineMock(VerificationCodeService.class), messageDispatcher, mock(TlsCertificateManager.class) ); diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java index 1f87e67460..305e17952c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java @@ -122,7 +122,7 @@ class DocDbContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); @@ -153,7 +153,7 @@ class DocDbContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java index dfa88e4f5f..bed8bea6aa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.ArgumentMatchers.any; @@ -194,6 +195,6 @@ class DynamoDbFacadeTest { mock(IotMqttBrokerService.class), mock(SqsService.class), mock(SnsService.class), mock(S3Service.class), mock(KinesisService.class), facade, mock(LambdaService.class), mock(FirehoseService.class), mock(CloudWatchLogsService.class), - mock(FlociCertificateAuthority.class), new IamPolicyEvaluator(mapper)); + inlineMock(FlociCertificateAuthority.class), new IamPolicyEvaluator(mapper)); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java index 0ae905d60a..ce21f37c56 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java @@ -87,7 +87,7 @@ class EcrRegistryManagerTest { builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); when(containerBuilder.resolveImage(anyString())).thenAnswer(inv -> inv.getArgument(0)); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); when(lifecycleManager.findByName(anyString())).thenReturn(Optional.empty()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesFromTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesFromTest.java index 01ca2f8575..1f2e177555 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesFromTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesFromTest.java @@ -67,8 +67,8 @@ class EcsContainerManagerVolumesFromTest { appBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer("sidecar:latest")).thenReturn(sourceBuilder); when(containerBuilder.newContainer("app:latest")).thenReturn(appBuilder); - when(sourceBuilder.build()).thenReturn(mock(ContainerSpec.class)); - when(appBuilder.build()).thenReturn(mock(ContainerSpec.class)); + when(sourceBuilder.build()).thenReturn(new ContainerSpec("test-image")); + when(appBuilder.build()).thenReturn(new ContainerSpec("test-image")); lifecycleManager = mock(ContainerLifecycleManager.class); when(lifecycleManager.resolveImageForLaunch(any(), any())) @@ -126,7 +126,7 @@ class EcsContainerManagerVolumesFromTest { void firelensRouterAndApplicationStartAfterTheirVolumeSource() { ContainerBuilder.Builder routerBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer("router:latest")).thenReturn(routerBuilder); - when(routerBuilder.build()).thenReturn(mock(ContainerSpec.class)); + when(routerBuilder.build()).thenReturn(new ContainerSpec("test-image")); when(lifecycleManager.create(any())).thenReturn("router-id"); when(lifecycleManager.startCreated(eq("router-id"), any())) .thenReturn(new ContainerInfo("router-id", Map.of())); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index 796c5c53bb..8806b77bd5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -85,6 +85,7 @@ import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.LogRecord; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -382,7 +383,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); @@ -423,7 +424,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), @@ -455,7 +456,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), @@ -512,7 +513,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); portAllocator = Mockito.mock(PortAllocator.class); dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS); when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); @@ -2050,7 +2051,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); @@ -2879,7 +2880,7 @@ class EksClusterManagerTest { containerBuilder = Mockito.mock(ContainerBuilder.class); builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); portAllocator = Mockito.mock(PortAllocator.class); when(portAllocator.allocate(6500, 6599)).thenReturn(6500); @@ -3149,7 +3150,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class); when(dockerHostResolver.resolve()).thenReturn("host.docker.internal"); @@ -3160,7 +3161,7 @@ class EksClusterManagerTest { when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); - FlociCertificateAuthority certificateAuthority = Mockito.mock(FlociCertificateAuthority.class); + FlociCertificateAuthority certificateAuthority = inlineMock(FlociCertificateAuthority.class); when(certificateAuthority.caPem()).thenReturn(CA_PEM); manager = new EksClusterManager( @@ -3282,7 +3283,7 @@ class EksClusterManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); PortAllocator portAllocator = Mockito.mock(PortAllocator.class); when(portAllocator.allocate(6440, 6499)).thenReturn(6443); @@ -3712,7 +3713,7 @@ class EksClusterManagerTest { containerBuilder = Mockito.mock(ContainerBuilder.class); builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); @@ -3837,7 +3838,7 @@ class EksClusterManagerTest { Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000"), Mockito.mock(Ec2MetadataServer.class), Mockito.mock(EksOidcService.class), - Mockito.mock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class), + inlineMock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class), new InMemoryStorage<>())); } diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhookTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhookTest.java index a1a6a80ddf..002ae8ca28 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhookTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhookTest.java @@ -17,6 +17,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -48,10 +49,10 @@ class EksPodIdentityWebhookTest { cluster.setName(CLUSTER_NAME); when(eks.findAuthenticationCluster(ACCOUNT_ID, CLUSTER_NAME)).thenReturn(Optional.of(cluster)); when(addons.describe(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))) - .thenReturn(Mockito.mock(Addon.class)); + .thenReturn(inlineMock(Addon.class)); when(associations.list(any(), anyString(), anyString(), any(), any())) .thenReturn(new EksPodIdentityAssociationService.Page( - List.of(Mockito.mock(PodIdentityAssociationSummary.class)), null)); + List.of(inlineMock(PodIdentityAssociationSummary.class)), null)); } private Map admissionReview(Map pod) { diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManagerTest.java index 87cc62e23e..160b8515b8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheContainerManagerTest.java @@ -68,7 +68,7 @@ class ElastiCacheContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -112,7 +112,7 @@ class ElastiCacheContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java index 1c96f2b811..47eb579dbf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java @@ -54,7 +54,7 @@ class ElastiCacheMemcachedContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -96,7 +96,7 @@ class ElastiCacheMemcachedContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseFlushIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseFlushIntegrationTest.java index b0b2b9e7b4..ea802d46a6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseFlushIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseFlushIntegrationTest.java @@ -3,8 +3,6 @@ package io.github.hectorvent.floci.services.firehose; import io.github.hectorvent.floci.testing.MutableClock; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.quarkus.test.junit.QuarkusTestProfile; -import io.quarkus.test.junit.TestProfile; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -12,7 +10,6 @@ import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Base64; -import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,17 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * config override, and a Quarkus test profile applies to the whole class. */ @QuarkusTest -@TestProfile(FirehoseFlushIntegrationTest.FastTickProfile.class) class FirehoseFlushIntegrationTest { - public static class FastTickProfile implements QuarkusTestProfile { - @Override - public Map getConfigOverrides() { - // 1s flush tick so the interval test waits seconds, not the 10s default. - return Map.of("floci.services.firehose.tick-interval-seconds", "1"); - } - } - private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; private static final String TARGET_PREFIX = "Firehose_20150804."; private static final Pattern KEY_PATTERN = Pattern.compile("([^<]+)"); diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java index 58a6f52391..9f1a53210e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java @@ -36,6 +36,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -111,7 +112,7 @@ class IotServiceTest { lambda, firehose, logs, - mock(io.github.hectorvent.floci.config.FlociCertificateAuthority.class), + inlineMock(io.github.hectorvent.floci.config.FlociCertificateAuthority.class), new io.github.hectorvent.floci.services.iam.IamPolicyEvaluator(mapper)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java index 79359c865f..59ef6adea3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java @@ -189,7 +189,7 @@ class FlinkContainerManagerTest { ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java index bbeddbb1d8..37435ca663 100644 --- a/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java @@ -142,7 +142,7 @@ class MemoryDbContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -170,7 +170,7 @@ class MemoryDbContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java index 4b83fe405d..828d39092b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java @@ -147,7 +147,7 @@ class NeptuneContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -177,7 +177,7 @@ class NeptuneContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class); lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream"); diff --git a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java index 56581be374..b306e4e8a1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java @@ -58,7 +58,7 @@ class OpenSearchDomainManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); RegionResolver regionResolver = mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); @@ -119,7 +119,7 @@ class OpenSearchDomainManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); RegionResolver regionResolver = mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index 179224dc8b..e8e770d840 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -43,6 +43,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -357,7 +358,7 @@ class RedshiftServiceTest { persisted.setClusterStatus("available"); persisted.setProxyPort(7108); - AccountAwareStorageBackend.AccountEntry entry = mock(AccountAwareStorageBackend.AccountEntry.class); + AccountAwareStorageBackend.AccountEntry entry = inlineMock(AccountAwareStorageBackend.AccountEntry.class); when(entry.value()).thenReturn(persisted); when(entry.accountId()).thenReturn("111111111111"); when(entry.key()).thenReturn("c1"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridgeTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridgeTest.java index 83102a0d7f..ca5f687c62 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridgeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridgeTest.java @@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -329,7 +330,7 @@ class RedshiftInterceptingBridgeTest { @Test @Timeout(20) void locallyHandledQueryInsideTransactionKeepsTheTransactionStatus() throws Exception { - SpectrumInterceptor interceptor = Mockito.mock(SpectrumInterceptor.class); + SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class); Mockito.when(interceptor.intercept(Mockito.anyString(), Mockito.any(), Mockito.any(Socket.class))) .thenReturn(new SpectrumInterceptor.Decision.Forward(), new SpectrumInterceptor.Decision.Handled()); startBridge(interceptor); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java index bc397bf366..4e01d359bf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java @@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test; import java.net.Socket; import java.util.List; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.mockito.ArgumentMatchers.any; @@ -23,9 +24,9 @@ class SpectrumInterceptorTest { @BeforeEach void setUp() { catalog = mock(SpectrumCatalog.class); - materializer = mock(SpectrumMaterializer.class); + materializer = inlineMock(SpectrumMaterializer.class); interceptor = new SpectrumInterceptor(catalog, new SpectrumStatementParser(), new SpectrumQueryClassifier(), - null, mock(SpectrumS3Reader.class), materializer); + null, inlineMock(SpectrumS3Reader.class), materializer); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java index 20c7fc835a..5b49a4741c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java @@ -17,20 +17,20 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Stream; +import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class SpectrumMaterializerTest { @Test void materializesThroughBackendSqlWithoutBufferingRowsInTheCaller() throws Exception { - SpectrumS3Reader reader = mock(SpectrumS3Reader.class); + SpectrumS3Reader reader = inlineMock(SpectrumS3Reader.class); when(reader.read(any(SpectrumSession.class), any(SpectrumExternalSchema.class), any(SpectrumExternalTable.class))) @@ -56,7 +56,7 @@ class SpectrumMaterializerTest { @Test void copyFailureDropsTemporaryTableAndPreservesBackendSqlState() { - SpectrumS3Reader reader = mock(SpectrumS3Reader.class); + SpectrumS3Reader reader = inlineMock(SpectrumS3Reader.class); when(reader.read(any(SpectrumSession.class), any(SpectrumExternalSchema.class), any(SpectrumExternalTable.class))) @@ -77,7 +77,7 @@ class SpectrumMaterializerTest { @Test void rowReadFailurePreservesSqlStateAndDropsTemporaryTable() { - SpectrumS3Reader reader = mock(SpectrumS3Reader.class); + SpectrumS3Reader reader = inlineMock(SpectrumS3Reader.class); SpectrumReadException rowFailure = new SpectrumReadException("22000", "bad CSV row"); when(reader.read(any(SpectrumSession.class), any(SpectrumExternalSchema.class), @@ -103,7 +103,7 @@ class SpectrumMaterializerTest { try (ServerSocket listener = new ServerSocket(0); Socket backend = new Socket("localhost", listener.getLocalPort())) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future captured = executor.submit(() -> serve(listener)); - SpectrumS3Reader reader = mock(SpectrumS3Reader.class); + SpectrumS3Reader reader = inlineMock(SpectrumS3Reader.class); when(reader.read(any(), any())) .thenReturn(Stream.of(new SpectrumRow(Arrays.asList("1", null)), new SpectrumRow(List.of("two", "x")), diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesInspectionEndpointIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesInspectionEndpointIntegrationTest.java new file mode 100644 index 0000000000..0671a6fdbd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesInspectionEndpointIntegrationTest.java @@ -0,0 +1,178 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +/** + * The {@code /_aws/ses} inspection endpoint follows LocalStack's contract + * (LocalStack SES): "A {@code DELETE} + * call clears all messages from the memory. The query parameter {@code id} can be used to delete + * only a specific message", and "Query parameters {@code id} and {@code email} can be used to + * filter by message ID and message source respectively." Messages are listed oldest first. + */ +@QuarkusTest +class SesInspectionEndpointIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + private static final String SENDER = "inspection-a@floci.test"; + private static final String OTHER_SENDER = "inspection-b@floci.test"; + + @BeforeEach + void emptyMailbox() { + verify(SENDER); + verify(OTHER_SENDER); + given().delete("/_aws/ses").then().statusCode(200); + } + + private static void verify(String address) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", address) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String send(String source, String to, String subject) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "SendEmail") + .formParam("Source", source) + .formParam("Destination.ToAddresses.member.1", to) + .formParam("Message.Subject.Data", subject) + .formParam("Message.Body.Text.Data", "body") + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .xmlPath() + .getString("SendEmailResponse.SendEmailResult.MessageId"); + } + + @Test + void deleteWithId_removesOnlyThatMessage() { + String first = send(SENDER, "to1@example.com", "msg-1"); + String second = send(SENDER, "to2@example.com", "msg-2"); + String third = send(SENDER, "to3@example.com", "msg-3"); + + given().queryParam("id", second).when().delete("/_aws/ses").then().statusCode(200); + + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.Id", contains(first, third)); + } + + @Test + void deleteWithUnknownId_keepsEveryMessage() { + String first = send(SENDER, "to1@example.com", "msg-1"); + + given().queryParam("id", "no-such-message").when().delete("/_aws/ses").then().statusCode(200); + + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.Id", contains(first)); + } + + @Test + void deleteWithoutId_clearsEveryMessage() { + send(SENDER, "to1@example.com", "msg-1"); + send(OTHER_SENDER, "to2@example.com", "msg-2"); + + given().when().delete("/_aws/ses").then().statusCode(200); + + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages", empty()); + } + + @Test + void getWithEmail_filtersByMessageSource() { + String fromSender = send(SENDER, "to1@example.com", "msg-1"); + send(OTHER_SENDER, "to2@example.com", "msg-2"); + + given() + .queryParam("email", SENDER) + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.Id", contains(fromSender)) + .body("messages[0].Source", equalTo(SENDER)); + + // A recipient is not a message source. + given() + .queryParam("email", "to2@example.com") + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages", empty()); + } + + @Test + void getWithIdAndEmail_appliesBothFilters() { + String fromSender = send(SENDER, "to1@example.com", "msg-1"); + String fromOther = send(OTHER_SENDER, "to2@example.com", "msg-2"); + + given() + .queryParam("id", fromSender) + .queryParam("email", SENDER) + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.Id", contains(fromSender)); + + given() + .queryParam("id", fromOther) + .queryParam("email", SENDER) + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages", empty()); + } + + @Test + void get_listsMessagesOldestFirst() { + List sent = new ArrayList<>(); + for (int i = 1; i <= 8; i++) { + sent.add(send(SENDER, "to" + i + "@example.com", "msg-" + i)); + } + + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages", hasSize(8)) + .body("messages.Id", contains(sent.toArray())) + .body("messages.Subject", contains("msg-1", "msg-2", "msg-3", "msg-4", + "msg-5", "msg-6", "msg-7", "msg-8")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesListManagementOptionsV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesListManagementOptionsV2IntegrationTest.java index 372815c3a8..94bef1305c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesListManagementOptionsV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesListManagementOptionsV2IntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.ses; +import io.github.hectorvent.floci.testutil.SesMailbox; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -7,7 +8,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; /** * Integration tests for the SES V2 {@code SendEmail} {@code ListManagementOptions} wiring through the @@ -136,14 +140,13 @@ class SesListManagementOptionsV2IntegrationTest { .when().post("/v2/email/outbound-emails").then().statusCode(200); // The stored message body has the placeholder replaced with a functional Floci unsubscribe URL. - given().header("Authorization", AUTH).queryParam("email", recipient) - .when().get("/_aws/ses").then().statusCode(200) - .body(org.hamcrest.Matchers.containsString("/_aws/ses/unsubscribe?")) - .body(org.hamcrest.Matchers.containsString("contactList=" + LIST)) - .body(org.hamcrest.Matchers.containsString("topic=Sports")) - .body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("amazonSESUnsubscribeUrl"))) - // the stored message also carries the List-Unsubscribe header - .body(org.hamcrest.Matchers.containsString("List-Unsubscribe")); + String stored = SesMailbox.messagesTo(recipient).toString(); + assertThat(stored, containsString("/_aws/ses/unsubscribe?")); + assertThat(stored, containsString("contactList=" + LIST)); + assertThat(stored, containsString("topic=Sports")); + assertThat(stored, not(containsString("amazonSESUnsubscribeUrl"))); + // the stored message also carries the List-Unsubscribe header + assertThat(stored, containsString("List-Unsubscribe")); } @Test @@ -220,11 +223,10 @@ class SesListManagementOptionsV2IntegrationTest { """.formatted(FROM, recipient)) .when().post("/v2/email/outbound-emails").then().statusCode(200); - given().header("Authorization", AUTH).queryParam("email", recipient) - .when().get("/_aws/ses").then().statusCode(200) - .body(org.hamcrest.Matchers.containsString("X-Safe")) - .body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("X-Evil"))) - .body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("attacker@evil.com"))); + String stored = SesMailbox.messagesTo(recipient).toString(); + assertThat(stored, containsString("X-Safe")); + assertThat(stored, not(containsString("X-Evil"))); + assertThat(stored, not(containsString("attacker@evil.com"))); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java index e28bedef9e..8da5ee47c5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java @@ -63,9 +63,9 @@ class SesSendCustomVerificationEmailV2IntegrationTest { @Test @Order(2) void send_storesRenderedEmailInInspectionMailbox() { - given().header("Authorization", AUTH).queryParam("email", RECIPIENT) + given().header("Authorization", AUTH).queryParam("email", FROM) .when().get("/_aws/ses").then().statusCode(200) - .body(containsString(FROM)) + .body(containsString(RECIPIENT)) .body(containsString(SUBJECT)) // The template body is passed through verbatim (no placeholder substitution)... .body(containsString("verify")) diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java index db6f2ec3d5..f98eb2a0d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java @@ -1,12 +1,14 @@ package io.github.hectorvent.floci.services.ses; import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.Base64; import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; @@ -19,6 +21,11 @@ class SesSendRawNoDestinationIntegrationTest { private static final String TO = "success@simulator.amazonses.com"; private static final String VERIFIED_SENDER = "no-destination-sender@floci.test"; + // The mailbox shows a raw message as RawData only, without the recipients Floci read from its + // headers, so the stored record is checked directly. + @Inject + SesSentEmailService sentEmailService; + private static String rawData(String headers) { return Base64.getEncoder().encodeToString( (headers + "Subject: s\r\n\r\nb").getBytes(StandardCharsets.UTF_8)); @@ -52,14 +59,8 @@ class SesSendRawNoDestinationIntegrationTest { .body("MessageId", notNullValue()) .extract().path("MessageId"); - given() - .queryParam("id", messageId) - .queryParam("email", TO) - .when() - .get("/_aws/ses") - .then() - .statusCode(200) - .body("messages.Id", contains(messageId)); + assertThat(sentEmailService.find("us-east-1", messageId).orElseThrow().getToAddresses(), + contains(TO)); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java index 17d0f83d31..9704e5136b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java @@ -44,7 +44,7 @@ class TimestreamInfluxDbContainerManagerTest { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); - when(builder.build()).thenReturn(mock(ContainerSpec.class)); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); portAllocator = mock(PortAllocator.class); when(portAllocator.allocate(8086, 8185)).thenReturn(8090); diff --git a/src/test/java/io/github/hectorvent/floci/testing/InlineMocks.java b/src/test/java/io/github/hectorvent/floci/testing/InlineMocks.java new file mode 100644 index 0000000000..c145b63c8e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/InlineMocks.java @@ -0,0 +1,28 @@ +package io.github.hectorvent.floci.testing; + +import org.mockito.MockMakers; +import org.mockito.Mockito; + +/** + * Mocks and spies for the types the suite's default subclass mock maker cannot extend: final classes, + * records and enums. Each one redefines its class in the running JVM, the cost the default avoids, so a + * record is better built for real than mocked. + */ +public final class InlineMocks { + + private InlineMocks() { + } + + public static T inlineMock(Class type) { + return Mockito.mock(type, Mockito.withSettings().mockMaker(MockMakers.INLINE)); + } + + /** {@link Mockito#spy(Object)} for an instance of a final class. */ + @SuppressWarnings("unchecked") + public static T inlineSpy(T instance) { + return (T) Mockito.mock(instance.getClass(), Mockito.withSettings() + .spiedInstance(instance) + .defaultAnswer(Mockito.CALLS_REAL_METHODS) + .mockMaker(MockMakers.INLINE)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testutil/SesMailbox.java b/src/test/java/io/github/hectorvent/floci/testutil/SesMailbox.java new file mode 100644 index 0000000000..8115fffb21 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testutil/SesMailbox.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.testutil; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; + +import static io.restassured.RestAssured.given; + +/** + * Reads Floci's SES inspection mailbox, {@code GET /_aws/ses}, for one recipient. The endpoint's + * {@code email} parameter filters by message source, as on LocalStack, so the messages sent to an + * address are picked out here. + */ +public final class SesMailbox { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private SesMailbox() { + } + + /** The captured messages whose To addresses include {@code recipient}, oldest first. */ + public static ArrayNode messagesTo(String recipient) { + String body = given().when().get("/_aws/ses").then().statusCode(200).extract().asString(); + JsonNode messages; + try { + messages = MAPPER.readTree(body).path("messages"); + } catch (JsonProcessingException e) { + throw new IllegalStateException("GET /_aws/ses did not return JSON: " + body, e); + } + ArrayNode matching = MAPPER.createArrayNode(); + for (JsonNode message : messages) { + for (JsonNode to : message.path("Destination").path("ToAddresses")) { + if (recipient.equals(to.asText())) { + matching.add(message); + break; + } + } + } + return matching; + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index fa3e7fcbcf..48cb95f540 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -255,7 +255,7 @@ floci: list-shards-next-token-ttl-millis: 300000 firehose: enabled: true - tick-interval-seconds: 10 + tick-interval-seconds: 1 flush-record-count: 0 staging-bucket: floci-firehose-staging kms: diff --git a/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..451b4adb5f --- /dev/null +++ b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1,6 @@ +# Mocks are generated subclasses rather than Mockito's default inline mocks. An inline mock +# redefines its class in the running JVM, which gets slow once a test JVM has loaded the Quarkus +# applications of the classes that ran before. A final class, record or enum cannot be subclassed: +# mock one with InlineMocks.inlineMock(...) or @Mock(mockMaker = MockMakers.INLINE), and prefer a +# real instance of a record. +mock-maker-subclass