fix(ses): delete by id and filter by source in /_aws/ses (#5159)

* fix(ses): delete by id and filter by source in /_aws/ses

The inspection endpoint follows LocalStack's contract, as
docs/services/ses.md says, but differed from it in two ways. LocalStack
documents that "The query parameter id can be used to delete only a
specific message", and that "Query parameters id and email can be used
to filter by message ID and message source respectively".

- DELETE /_aws/ses?id=<id> cleared every message. It now deletes only
  that message, in whichever region it was sent. An unknown id deletes
  nothing.
- GET /_aws/ses?email=<address> matched the address against each
  message's ToAddresses. It now matches the message's Source, as
  LocalStack does.

GET also listed messages in storage hash order. It now lists them
oldest first by Timestamp, the order LocalStack keeps them in.

Floci's own tests read Cognito codes and other mail with
?email=<recipient>. They now list the mailbox and pick the recipient's
messages out of it, through a new SesMailbox test helper in src/test and
the same filtering in the Java and Node compatibility tests. A raw
send's mailbox entry shows RawData without its recipients, so the test
for recipients read from a raw message's headers checks the stored
record.

* fix(codeartifact): run the pypiserver sidecar under an init process so a stop ends it at once

The pypiserver image's entrypoint execs pypi-server, which installs no SIGTERM handler. The kernel
gives PID 1 no default signal actions, so the container ignored every stop request and went only
when Docker sent SIGKILL at the end of the 5-second timeout: each reset, repository delete and
shutdown waited that long for every pypi repository's container, one after another.

ContainerBuilder gains withInit(), carried on ContainerSpec as init and passed to Docker as
HostConfig.Init (docker run --init), and PypiserverSidecarManager uses it. Docker's init runs as
PID 1 and forwards the SIGTERM, so a stop now returns in a fraction of a second. Verdaccio already
handles the signal itself and is unchanged.

* fix(firehose): check buffers every second so delivery follows the buffering interval

AWS delivers a Firehose buffer once the first buffer condition is met. Floci checked for elapsed
buffering intervals on a 10-second tick, so a buffer was delivered up to 10 seconds after its
IntervalInSeconds ended: a 5-second interval landed anywhere from 5 to 15 seconds after the first
record. The default tick is now one second; the check is a scan of the in-memory buffers.

FirehoseFlushIntegrationTest's profile only set the same one-second tick, so it is removed and the
class shares the default test application. The compat tests that wait for a delivery checked S3
every 2 or 5 seconds; against Floci they now check every 250 ms, and keep their cadence against
real AWS.

* test: make subclass mocks the default so mocking stays cheap in a loaded test JVM

Mockito's default inline mock maker redefines every class it mocks in the running JVM. A
redefinition gets slow once the test JVM has loaded the Quarkus applications of the classes that
ran before, which in CI is most of the run: a unit class's first test spent seconds building its
mocks, and EmulatorLifecycleTest, which mocks some fifty types, spent 22 seconds. Subclass mocks
generate a subclass instead and redefine nothing. After twelve Quarkus applications in one JVM, the
fourteen Mockito classes whose first test was slowest in CI take 20.5 seconds instead of 41.9, and
their first tests 6.9 seconds instead of 27.8.

mockito-extensions/org.mockito.plugins.MockMaker makes the subclass mock maker the default. A
subclass cannot extend a final class, record or enum, so those mocks go through
InlineMocks.inlineMock and inlineSpy, or @Mock(mockMaker = MockMakers.INLINE), and
EmulatorLifecycleTest's static mock of Quarkus asks for the inline maker. The ContainerSpec mocks
a mocked ContainerBuilder.Builder returned were opaque values, so they are real specs now.

* fix(cloudformation): leave the last rollback's failed delete to ContinueUpdateRollback

#4949 refuses an update over UPDATE_ROLLBACK_FAILED until ContinueUpdateRollback finishes the
rollback, as AWS does. #4834, merged minutes earlier, had seven tests that update over that
status, and main has failed them since c4a809f47.

Six are in CloudFormationSchedulerScheduleIntegrationTest. They now reach their next update the
way AWS requires: ContinueUpdateRollback, which retries the schedule's own rollback, or, where the
replacement's delete has to keep failing, a skip of the schedule. The two whose update was meant to
be blocked by the pending rollback now check that the update is refused.

The seventh shows a real clash. #4949 made a second ReplacementCleanup.rollback retry the delete
the first one could not make, which is ContinueUpdateRollback's job. The Scheduler provisioner also
calls rollbackUpdate inside an update, to undo its own failed call, so after a skip a failed group
move deleted the earlier orphan there and then, and a failure of that delete would have failed the
move's restore. An update now ends that retry as it starts, through
ReplacementCleanup.endRollbackRetry, so the orphan stays owed for the next committed update or the
stack delete, as both changes document.

Three more provisioners roll an update back before ReplacementCleanup.record has cleared the retry,
and each returns as soon as the retry ran, skipping its own restore. CloudWatchDashboard and
IotAuthorizer unwind a failed in-place update that way, and CognitoResourceServer's failed attempt
is rolled back the same way, so after a skip the update's snapshot was never put back while the
resource was reported restored. They end the retry as an update starts too.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
jwoa95andPriamo authored and GitHub committed 2026-10-14 10:04:48 -04:00
1 parent f833ca9e12
commit 7c4d1c913a
75 files changed
+760 -251

No files matched your search

@@ -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();
/**
@@ -151,6 +151,7 @@ public class ContainerBuilder {
private Long nanoCpus;
private Integer cpuShares;
private boolean readonlyRootfs;
private boolean init;
private final Map<Integer, Integer> portBindings = new HashMap<>();
private final List<Integer> loopbackPortBindings = new ArrayList<>();
private final Map<Integer, String> 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
);
}
}
@@ -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
@@ -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<String> linkLocalIps,
Map<Integer, String> portBindingHostIps
Map<Integer, String> portBindingHostIps,
boolean init
) {
private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$");
private static final Set<String> 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);
}
/**
@@ -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<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String explicitName = ctx.resolveOptional(props, "DashboardName");
boolean hasExplicitName = explicitName != null && !explicitName.isBlank();
@@ -49,6 +49,11 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
validateString(name, "Name", 256, "[\\w\\s+=,.@-]+");
List<ResourceServerScope> 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);
@@ -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<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String functionArn = resolvePresent(props, "AuthorizerFunctionArn", ctx);
if (functionArn == null) {
@@ -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;
@@ -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);
@@ -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),
@@ -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<SentEmail> 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();
}
}
@@ -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<SentEmail> listAll() {
return emailStore.scan(k -> k.startsWith("email::"));
return emailStore.scan(k -> k.startsWith("email::")).stream()
.sorted(Comparator.comparing(SentEmail::getSentAt,
Comparator.nullsFirst(Comparator.<Instant>naturalOrder())))
.toList();
}
/** Removes the message with this id from whichever region holds it; an unknown id removes nothing. */
public void delete(String messageId) {
List<String> 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);
}
}