Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ecs): launch a container with its linuxParameters, checked as RegisterTaskDefinition does (#5951)
Alessandro Lattao98b2429e5870
diff --git a/Makefile b/Makefileindex d4082aed84..cff745ceb8 100644--- a/Makefile+++ b/Makefile@@ -19,6 +19,8 @@# API Gateway integration types come from the public service model via tools/aws/regen_apigateway_types.py.# src/main/resources/aws/sesv2-request-shapes.json is generated from botocore's SES v2 model# by tools/aws/regen_sesv2_shapes.py.+# src/main/resources/aws/ecs-request-shapes.json is generated from botocore's ECS model+# by tools/aws/regen_ecs_shapes.py.PYTHON ?= python3@@ -212,6 +214,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py$(PYTHON) tools/aws/regen_apigateway_types.py$(PYTHON) tools/aws/regen_sesv2_shapes.py+ $(PYTHON) tools/aws/regen_ecs_shapes.py$(PYTHON) tools/aws/regen_query_services.py$(PYTHON) tools/aws/regen_managed_policies.py@@ -250,6 +253,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generationecho " Run 'make aws-data-sync' and commit the result."; \exit 1; \}+ @$(PYTHON) tools/aws/regen_ecs_shapes.py --check || { \+ echo ""; \+ echo "error: src/main/resources/aws/ecs-request-shapes.json is out of date."; \+ echo " Run 'make aws-data-sync' and commit the result."; \+ exit 1; \+ }@$(PYTHON) tools/aws/regen_query_services.py --check || { \echo ""; \echo "error: src/main/resources/aws/query-services.json is out of date."; \diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsLinuxParametersRegistrationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsLinuxParametersRegistrationTest.javanew file mode 100644index 0000000000..fe30b4595a--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsLinuxParametersRegistrationTest.java@@ -0,0 +1,118 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.ecs.EcsClient;+import software.amazon.awssdk.services.ecs.model.Compatibility;+import software.amazon.awssdk.services.ecs.model.ContainerDefinition;+import software.amazon.awssdk.services.ecs.model.EcsException;+import software.amazon.awssdk.services.ecs.model.LinuxParameters;+import software.amazon.awssdk.services.ecs.model.NetworkMode;+import software.amazon.awssdk.services.ecs.model.TaskDefinition;++import java.util.ArrayList;+import java.util.List;+import java.util.function.Consumer;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * A container's {@code linuxParameters} through RegisterTaskDefinition, with the refusals and the+ * stored form measured on AWS (eu-west-1, 2026-10-03 and 2026-10-16).+ */+@DisplayName("ECS linuxParameters on RegisterTaskDefinition")+class EcsLinuxParametersRegistrationTest {++ private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";++ private static final List<String> REGISTERED = new ArrayList<>();++ private static EcsClient ecs;++ @BeforeAll+ static void setup() {+ ecs = TestFixtures.ecsClient();+ }++ @AfterAll+ static void cleanup() {+ if (ecs == null) {+ return;+ }+ for (String arn : REGISTERED) {+ ecs.deregisterTaskDefinition(request -> request.taskDefinition(arn));+ }+ if (!REGISTERED.isEmpty()) {+ ecs.deleteTaskDefinitions(request -> request.taskDefinitions(REGISTERED));+ }+ ecs.close();+ }++ @Test+ @DisplayName("refuses what RegisterTaskDefinition refuses, whatever the launch type")+ void refusesWhatRegistrationRefuses() {+ assertRefused(false, linux -> linux.capabilities(caps -> caps.add("CAP_NET_ADMIN")),+ "Unrecognized Linux capabilities in add: [CAP_NET_ADMIN]");+ assertRefused(false, linux -> linux.devices(device -> device.hostPath("/dev/null")+ .permissionsWithStrings("READ")),+ "Invalid permission: READ for device /dev/null");+ assertRefused(false, linux -> linux.tmpfs(mount -> mount.containerPath("/scratch").size(16)+ .mountOptions("NOEXEC")),+ "The NOEXEC tmpfs mount option specified is invalid.");+ assertRefused(false, linux -> linux.maxSwap(256),+ "When a container has a swap memory, it must also specify a swappiness value.");+ }++ @Test+ @DisplayName("refuses on Fargate the parameters Fargate cannot honour")+ void refusesOnFargateWhatFargateCannotHonour() {+ assertRefused(true, linux -> linux.devices(device -> device.hostPath("/dev/null")),+ "Fargate compatible task definitions do not support devices");+ assertRefused(true, linux -> linux.capabilities(caps -> caps.add("NET_ADMIN")),+ "NET_ADMIN is not allowed on Fargate.");+ }++ @Test+ @DisplayName("stores a swappiness without swap as dropped, and both capability lists")+ void storesTheParametersAsRegistrationDoes() {+ TaskDefinition registered = register(false, linux -> linux.swappiness(10)+ .capabilities(caps -> caps.add("SYS_PTRACE")));++ LinuxParameters stored = ecs.describeTaskDefinition(request -> request+ .taskDefinition(registered.taskDefinitionArn())).taskDefinition()+ .containerDefinitions().get(0).linuxParameters();+ assertThat(stored.swappiness()).isNull();+ assertThat(stored.capabilities().add()).containsExactly("SYS_PTRACE");+ assertThat(stored.capabilities().hasDrop()).isTrue();+ assertThat(stored.capabilities().drop()).isEmpty();+ }++ private static void assertRefused(boolean fargate, Consumer<LinuxParameters.Builder> linux, String message) {+ assertThatThrownBy(() -> register(fargate, linux))+ .isInstanceOfSatisfying(EcsException.class, refusal -> {+ assertThat(refusal.awsErrorDetails().errorCode()).isEqualTo("ClientException");+ assertThat(refusal.awsErrorDetails().errorMessage()).isEqualTo(message);+ });+ }++ private static TaskDefinition register(boolean fargate, Consumer<LinuxParameters.Builder> linux) {+ ContainerDefinition container = ContainerDefinition.builder()+ .name("app")+ .image(IMAGE)+ .memory(128)+ .linuxParameters(linux)+ .build();+ TaskDefinition registered = ecs.registerTaskDefinition(request -> {+ request.family(TestFixtures.uniqueName("compat-ecs-linux")).containerDefinitions(container);+ if (fargate) {+ request.requiresCompatibilities(Compatibility.FARGATE).networkMode(NetworkMode.AWSVPC)+ .cpu("256").memory("512");+ }+ }).taskDefinition();+ REGISTERED.add(registered.taskDefinitionArn());+ return registered;+ }+}diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.mdindex fa7b19d984..df8952e0d3 100644--- a/docs/configuration/advanced/application-yml.md+++ b/docs/configuration/advanced/application-yml.md@@ -356,7 +356,7 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for ECS task containers || `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when task definition omits it || `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when task definition omits it |-| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Comma-separated allowlist of parent directories for host volume bind mounts; by default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` is rejected |+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Comma-separated allowlist of parent directories for host volume bind mounts and container devices; by default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` and device `hostPath` is rejected || `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing the host-volume-roots allowlist (traversal, bare root, and the Docker socket or an ancestor directory of it are still always rejected) || `FLOCI_SERVICES_ECS_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the ECS containers a previous run of this Floci left on the daemon before replacement tasks start || `FLOCI_SERVICES_ECS_IMAGE_PULL_BEHAVIOR` | `default` | How task images are pulled at launch, as the ECS agent's `ECS_IMAGE_PULL_BEHAVIOR`: `default`, `always`, `once` or `prefer-cached` |diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex eaa86478aa..61b25d8244 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -522,7 +522,7 @@ These services spawn Docker containers. They require access to the Docker socket| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default task memory when not specified in the task definition || `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default task CPU units when not specified in the task definition || `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | _(none)_ | Docker network for ECS task containers |-| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | _(none)_ | Comma-separated allowlist of parent directories host volume `sourcePath`s must resolve under. By default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` is rejected |+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | _(none)_ | Comma-separated allowlist of parent directories host volume `sourcePath`s and container device `hostPath`s must resolve under. By default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` and device `hostPath` is rejected || `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing `HOST_VOLUME_ROOTS`; traversal, the bare root, and the Docker socket (or an ancestor directory of it, e.g. `/var/run`) are still always rejected || `FLOCI_SERVICES_ECS_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | On startup, in Docker mode, remove the ECS containers a previous run of this Floci left on the daemon (matched by resource namespace and API port) before replacement tasks start || `FLOCI_SERVICES_ECS_IMAGE_PULL_BEHAVIOR` | `default` | How task images are pulled at launch, with the values and semantics of the ECS agent's `ECS_IMAGE_PULL_BEHAVIOR`: `default` pulls every launch and falls back to the cached image, `always` fails the task when the pull fails, `once` pulls once per Floci process, `prefer-cached` pulls only when nothing is cached |diff --git a/docs/services/ecs.md b/docs/services/ecs.mdindex ececc10029..4e9fbc1c18 100644--- a/docs/services/ecs.md+++ b/docs/services/ecs.md@@ -65,8 +65,8 @@ instances and stop the tasks first, as on AWS.A task definition round-trips whole. Members Floci acts on are modelled(`ephemeralStorage`, `pidMode`, `ipcMode`, `runtimePlatform`, and at container level `dependsOn`,`startTimeout`, `stopTimeout`, `user`, `workingDirectory`, `readonlyRootFilesystem`,-`environmentFiles`, `dockerLabels`, `repositoryCredentials` and the rest); everything else it does-not act on, such as `proxyConfiguration`, `linuxParameters`, `ulimits`, `resourceRequirements`,+`environmentFiles`, `dockerLabels`, `repositoryCredentials` and the rest); everything else,+such as `proxyConfiguration`, `ulimits`, `resourceRequirements`,`systemControls` and placement constraints, is kept verbatim and returned as registered. A clientthat reads back what it wrote (Terraform, or a deploy tool verifying its own`RegisterTaskDefinition`) sees no drift. `runtimePlatform` does not change where a local task@@ -124,6 +124,33 @@ on teardown; a container that does not ask for one gets 5 seconds rather than AW`StopTask` here answers synchronously and most containers ignore SIGTERM as PID 1. A containerstill running when its grace period is up is killed, so its exit code is always reported.+A container's `linuxParameters` reach Docker as ECS documents them. `initProcessEnabled` runs an+init process as PID 1 (`docker run --init`) that forwards signals and reaps orphaned processes;+`capabilities` are added and dropped (`--cap-add`, `--cap-drop`); each of `devices` is exposed+(`--device`), with read, write and mknod when it names no `permissions` and at its `hostPath` when+it names no `containerPath`; `sharedMemorySize` sizes `/dev/shm` in MiB (`--shm-size`); each of+`tmpfs` is mounted at its `containerPath` with its `mountOptions` and `size` in MiB (`--tmpfs`);+`maxSwap` caps memory plus swap at the container's hard limit plus that many MiB (`--memory-swap`,+so `0` means no swap), and `swappiness` (`--memory-swappiness`) goes with it: as on ECS,+`RegisterTaskDefinition` refuses a `maxSwap` without a `swappiness`, and drops a `swappiness`+without `maxSwap` from the definition it stores. A container with no hard limit, neither its own+`memory` nor the task's, gets no swap limit, because Docker cannot limit swap without one, but+still its `swappiness`. A daemon on cgroup v2 discards+`swappiness`, as Amazon Linux 2023 does. Inside a task behind a security group, `NET_ADMIN` and+`NET_RAW` stay dropped whatever `capabilities` adds, because the group is enforced in the network+namespace the task's containers share.++A device hands the container the host's hardware, so Floci refuses one as it refuses a host volume:+by default, unless its `hostPath` is under `floci.services.ecs.host-volume-roots`+(`FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS`) or `floci.services.ecs.allow-unsafe-host-volumes` is set,+at `RegisterTaskDefinition` after AWS's own checks and again at launch. `RegisterTaskDefinition`+reads the members as AWS does: a member of the wrong JSON type is refused with the deserializer's+message (`STRING_VALUE cannot be converted to Integer`, `Unexpected value type in payload`, ...) before+any other check, walking the shapes vendored in `src/main/resources/aws/ecs-request-shapes.json`+(generated by `tools/aws/regen_ecs_shapes.py` from the botocore release pinned in+`tools/aws/requirements.txt`), a number is stored as an integer with its fraction dropped and its range capped to+32 bits, a boolean may come as text in any case, and a null member is left out.+`firelensConfiguration` is stored and returned the same way. `RegisterTaskDefinition` rejects amissing or unsupported `type` (`fluentd` and `fluentbit` only), and a task using `awsfirelens`must name exactly one router: a task definition with two FireLens routers, or a router publishing@@ -214,8 +241,19 @@ at registration:- None of the parameters that are not valid in a Fargate task: `disableNetworking`,`dnsSearchDomains`, `dnsServers`, `dockerSecurityOptions`, `extraHosts`, a `GPU``resourceRequirements` entry, `ipcMode`, `links`, `placementConstraints`, `privileged`,- `linuxParameters.maxSwap`, `linuxParameters.swappiness`, a `pidMode` other than `task`, or a- host volume with a `sourcePath`. All of them are accepted on an EC2-compatible definition.+ `linuxParameters.devices` (an empty list passes), `linuxParameters.sharedMemorySize`,+ `linuxParameters.maxSwap`, `linuxParameters.swappiness`, a `linuxParameters.capabilities.add`+ entry other than `SYS_PTRACE` as written (`sys_ptrace` is refused by name), a `pidMode` other+ than `task`, or a host volume with a `sourcePath`. All of them are accepted on an EC2-compatible+ definition. The `linuxParameters` among them are checked in that order, with AWS's messages.+- Whatever the launch type, in this order and with AWS's messages: every `capabilities` entry one+ of the names the KernelCapabilities reference lists, in any case and without a `CAP_` prefix+ (`Unrecognized Linux capabilities in add: [CAP_NET_ADMIN]`); every device with a `hostPath`, and+ only `read`, `write` and `mknod` as `permissions`, as written; every `tmpfs` mount with a+ `containerPath`, a `size` above zero and `mountOptions` the Tmpfs reference lists, as written and+ with any `=value`; a `sharedMemorySize` above zero; and a `maxSwap` only with a `swappiness`, of+ zero or more, with a `swappiness` from 0 to 100. These come before the Fargate rules. The stored+ `capabilities` always carry both an `add` and a `drop` list, as on AWS.- A `dependsOn` graph that names only containers of the same task definition and has no cycle.A launched Fargate task reports what AWS reports: `platformVersion` (with `LATEST` resolved to a@@ -781,7 +819,7 @@ Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for task containers || `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when the task definition omits it || `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when the task definition omits it |-| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Approved parent directories for host volume bind mounts (`volumes[].host.sourcePath`) |+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Approved parent directories for host volume bind mounts (`volumes[].host.sourcePath`) and container devices (`linuxParameters.devices[].hostPath`) || `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing the `HOST_VOLUME_ROOTS` allowlist; traversal, the bare root, and the Docker socket are still always rejected || `FLOCI_SERVICES_ECS_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | On startup, in Docker mode, remove the ECS containers a previous run of this Floci left on the daemon before the scheduler starts replacement tasks (see [Restarts](#restarts)) || `FLOCI_SERVICES_ECS_IMAGE_PULL_BEHAVIOR` | `default` | How task images are pulled at launch, as the ECS agent's `ECS_IMAGE_PULL_BEHAVIOR`: `default`, `always`, `once` or `prefer-cached` (see [Image pulls](#image-pulls)) |@@ -910,7 +948,9 @@ Always rejected, regardless of configuration:- `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES=true`: allow any host path (for local development where any host path should be mountable). The traversal, bare-root, and Docker socket blocks above are never bypassed by this flag.-A rejected `sourcePath` fails `RegisterTaskDefinition` with `InvalidParameterException`; a rejection caught again at `RunTask` time (e.g. a task definition registered before this policy existed) stops the task with that message as its `stoppedReason`. Named Docker volumes, EFS volumes, and host volumes with no `sourcePath` (ephemeral storage shared within a task) are unaffected by these checks.+A container device's `hostPath` (`linuxParameters.devices`) goes through the same checks and the same allowlist, since a device hands the container the host's hardware.++A rejected `sourcePath` or device `hostPath` fails `RegisterTaskDefinition` with `InvalidParameterException`; a rejection caught again at `RunTask` time (e.g. a task definition registered before this policy existed) stops the task with that message as its `stoppedReason`. Named Docker volumes, EFS volumes, and host volumes with no `sourcePath` (ephemeral storage shared within a task) are unaffected by these checks.### EFS volume ownershipdiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 49d1fc9982..507134d347 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2219,15 +2219,16 @@ public interface EmulatorConfig {/*** Approved parent directories for task definition host volume bind mounts- * (volumes[].host.sourcePath). A sourcePath must resolve under one of these roots.- * Empty (the default) rejects every host volume sourcePath unless+ * (volumes[].host.sourcePath) and container devices (linuxParameters.devices[].hostPath).+ * A host path must resolve under one of these roots. Empty (the default) rejects every+ * host volume sourcePath and device hostPath unless* {@link #allowUnsafeHostVolumes()} is set, subject to the always-on traversal,* bare-root, and Docker socket blocks below.*/Optional<List<String>> hostVolumeRoots();/**- * When true, bypasses the {@link #hostVolumeRoots()} allowlist check for host volumes,+ * When true, bypasses the {@link #hostVolumeRoots()} allowlist check for host volumes and devices,* allowing any absolute path. Traversal segments, the bare root "/", and the Docker* socket (or any ancestor directory that contains it) are still always rejected.*/diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeCheck.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeCheck.javanew file mode 100644index 0000000000..9d5bc6c5d9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeCheck.java@@ -0,0 +1,188 @@+package io.github.hectorvent.floci.core.common;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;++import java.util.Map;+import java.util.Set;++/**+ * Walks a request value against a {@link RequestShapeModel} as AWS's JSON deserializers read a body,+ * before an operation validates anything, and refuses the first member of the wrong JSON type. The+ * walk is the same for every service: a JSON null is an absent member (a null list element is left+ * to the operation), a member the model does not know is skipped, a structure's values are read as+ * members and a list's or a map's as elements, a boolean also reads from "true" or "false" in any+ * case, and a scalar of the wrong kind is named by its JSON token ({@code NUMBER_VALUE},+ * {@code TRUE_VALUE}, ...). What a service's deserializer says at each point is its {@link Messages}.+ */+public final class RequestShapeCheck {++ /** A message that depends on whether the value was read as a member or as an element. */+ public record ByPosition(String member, String element) {++ public static ByPosition same(String message) {+ return new ByPosition(message, message);+ }++ String at(boolean asMember) {+ return asMember ? member : element;+ }+ }++ /**+ * One deserializer's wording, as measured on its service. A null message is answered with the+ * error code alone.+ *+ * @param errorCode the exception every mismatch answers with, as HTTP 400+ * @param objectNotExpected an object where a list or a scalar is expected+ * @param listNotExpected a list where a structure, a map or a scalar is expected+ * @param scalarForStructure a scalar where a structure is expected+ * @param scalarForList a scalar where a list is expected+ * @param scalarForMap a scalar where a map is expected+ * @param conversion a scalar of the wrong kind, formatted with its token and the target+ * type ({@code String}, {@code Integer}, {@code Long}, {@code Double},+ * {@code Date}, {@code Boolean}, {@code Blob})+ * @param decimalToken whether a non-integral number is {@code DECIMAL_VALUE} rather than+ * {@code NUMBER_VALUE}+ * @param invalidBoolean text other than true or false where a boolean is expected+ * @param blobNotText a scalar that is not text where a blob is expected, or null to word+ * it as {@code conversion} does+ * @param scalarTypes the scalar shape types the service was measured on; a value of any+ * other scalar type passes unchecked+ */+ public record Messages(String errorCode, String objectNotExpected, String listNotExpected,+ ByPosition scalarForStructure, ByPosition scalarForList, ByPosition scalarForMap,+ String conversion, boolean decimalToken, String invalidBoolean, String blobNotText,+ Set<String> scalarTypes) {+ }++ private static final Map<String, String> TARGETS = Map.of("string", "String", "integer", "Integer",+ "long", "Long", "double", "Double", "timestamp", "Date", "boolean", "Boolean", "blob", "Blob");++ private RequestShapeCheck() {+ }++ /** Checks {@code value}, read as a member, against the shape {@code shapeName} of {@code model}. */+ public static void check(RequestShapeModel model, String shapeName, JsonNode value, Messages messages) {+ checkValue(model, model.shapes().get(shapeName), value, true, messages);+ }++ private static void checkValue(RequestShapeModel model, Shape shape, JsonNode value, boolean member,+ Messages messages) {+ if (value == null || value.isNull()) {+ return;+ }+ switch (shape.type()) {+ case "structure" -> checkStructure(model, shape, value, member, messages);+ case "list" -> checkList(model, shape, value, member, messages);+ case "map" -> checkMap(model, shape, value, member, messages);+ default -> checkScalar(shape.type(), value, messages);+ }+ }++ private static void checkStructure(RequestShapeModel model, Shape shape, JsonNode value, boolean member,+ Messages messages) {+ if (value.isArray()) {+ throw refusal(messages, messages.listNotExpected());+ }+ if (!value.isObject()) {+ throw refusal(messages, messages.scalarForStructure().at(member));+ }+ for (Map.Entry<String, JsonNode> field : value.properties()) {+ String memberShape = shape.members().get(field.getKey());+ if (memberShape != null) {+ checkValue(model, model.shapes().get(memberShape), field.getValue(), true, messages);+ }+ }+ }++ private static void checkList(RequestShapeModel model, Shape shape, JsonNode value, boolean member,+ Messages messages) {+ if (value.isObject()) {+ throw refusal(messages, messages.objectNotExpected());+ }+ if (!value.isArray()) {+ throw refusal(messages, messages.scalarForList().at(member));+ }+ checkElements(model, shape, value, messages);+ }++ private static void checkMap(RequestShapeModel model, Shape shape, JsonNode value, boolean member,+ Messages messages) {+ if (value.isArray()) {+ throw refusal(messages, messages.listNotExpected());+ }+ if (!value.isObject()) {+ throw refusal(messages, messages.scalarForMap().at(member));+ }+ checkElements(model, shape, value, messages);+ }++ private static void checkElements(RequestShapeModel model, Shape shape, JsonNode value, Messages messages) {+ Shape element = model.shapes().get(shape.element());+ for (JsonNode item : value) {+ checkValue(model, element, item, false, messages);+ }+ }++ private static void checkScalar(String type, JsonNode value, Messages messages) {+ if (!messages.scalarTypes().contains(type)) {+ return;+ }+ if (value.isObject()) {+ throw refusal(messages, messages.objectNotExpected());+ }+ if (value.isArray()) {+ throw refusal(messages, messages.listNotExpected());+ }+ switch (type) {+ case "string" -> requireToken(value.isTextual(), value, type, messages);+ case "integer", "long", "double", "timestamp" -> requireToken(value.isNumber(), value, type, messages);+ case "boolean" -> checkBoolean(value, messages);+ case "blob" -> checkBlob(value, messages);+ default -> {+ }+ }+ }++ private static void checkBoolean(JsonNode value, Messages messages) {+ if (value.isTextual()) {+ String text = value.textValue();+ if (!"true".equalsIgnoreCase(text) && !"false".equalsIgnoreCase(text)) {+ throw refusal(messages, messages.invalidBoolean());+ }+ return;+ }+ requireToken(value.isBoolean(), value, "boolean", messages);+ }++ private static void checkBlob(JsonNode value, Messages messages) {+ if (value.isTextual() || value.isBinary()) {+ return;+ }+ if (messages.blobNotText() != null) {+ throw refusal(messages, messages.blobNotText());+ }+ requireToken(false, value, "blob", messages);+ }++ private static void requireToken(boolean accepted, JsonNode value, String type, Messages messages) {+ if (!accepted) {+ throw refusal(messages, messages.conversion().formatted(token(value, messages), TARGETS.get(type)));+ }+ }++ private static String token(JsonNode value, Messages messages) {+ if (value.isNumber()) {+ return messages.decimalToken() && !value.isIntegralNumber() ? "DECIMAL_VALUE" : "NUMBER_VALUE";+ }+ if (value.isBoolean()) {+ return value.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";+ }+ return "STRING_VALUE";+ }++ private static AwsException refusal(Messages messages, String message) {+ return new AwsException(messages.errorCode(), message, 400);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeModel.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeModel.javaindex 52b74e0a30..838434b549 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeModel.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestShapeModel.java@@ -12,7 +12,7 @@ import java.util.Map;* The input shapes of a service's operations, as a {@code tools/aws/regen_*_shapes.py} generator* vendors them from botocore: each operation's input shape, and for every shape reachable from one* its type and the shapes of its structure members, list elements or map values. A service's- * request check walks a body against it with its own protocol's messages.+ * request check walks a body against it with {@link RequestShapeCheck} and its own messages.*/public record RequestShapeModel(Map<String, String> operations, Map<String, Shape> shapes) {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.javaindex efe554d759..9197f06349 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@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common.docker;import com.github.dockerjava.api.model.AccessMode;import com.github.dockerjava.api.model.Bind;+import com.github.dockerjava.api.model.Device;import com.github.dockerjava.api.model.DeviceRequest;import com.github.dockerjava.api.model.LogConfig;import com.github.dockerjava.api.model.Mount;@@ -170,6 +171,13 @@ public class ContainerBuilder {private final List<String> dnsServers = new ArrayList<>();private final List<String> linkLocalIps = new ArrayList<>();private final List<DeviceRequest> deviceRequests = new ArrayList<>();+ private final List<String> capAdd = new ArrayList<>();+ private final List<String> capDrop = new ArrayList<>();+ private final List<Device> devices = new ArrayList<>();+ private Long shmSizeBytes;+ private final Map<String, String> tmpfs = new HashMap<>();+ private Long memorySwapBytes;+ private Long memorySwappiness;Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,EmbeddedDnsServer embeddedDnsServer,@@ -621,6 +629,68 @@ public class ContainerBuilder {return this;}+ /**+ * Adds a capability to the daemon's default set ({@code --cap-add}), named without the+ * {@code CAP_} prefix, or {@code ALL}.+ */+ public Builder withCapAdd(String capability) {+ this.capAdd.add(capability);+ return this;+ }++ /**+ * Drops a capability from the daemon's default set ({@code --cap-drop}), named without the+ * {@code CAP_} prefix, or {@code ALL}.+ */+ public Builder withCapDrop(String capability) {+ this.capDrop.add(capability);+ return this;+ }++ /**+ * Exposes a host device inside the container ({@code --device}).+ *+ * @param cgroupPermissions any of {@code r}, {@code w} and {@code m}, as Docker takes them+ */+ public Builder withDevice(String hostPath, String containerPath, String cgroupPermissions) {+ this.devices.add(new Device(cgroupPermissions, containerPath, hostPath));+ return this;+ }++ /**+ * Sets the size of {@code /dev/shm} ({@code --shm-size}).+ */+ public Builder withShmSizeBytes(long shmSizeBytes) {+ this.shmSizeBytes = shmSizeBytes;+ return this;+ }++ /**+ * Mounts a tmpfs at {@code containerPath} ({@code --tmpfs}), with Docker's option string,+ * such as {@code "noexec,size=64m"}.+ */+ public Builder withTmpfs(String containerPath, String options) {+ this.tmpfs.put(containerPath, options);+ return this;+ }++ /**+ * Caps memory plus swap ({@code --memory-swap}); a value equal to the memory limit means+ * the container does not swap.+ */+ public Builder withMemorySwapBytes(long memorySwapBytes) {+ this.memorySwapBytes = memorySwapBytes;+ return this;+ }++ /**+ * Sets the container's swappiness, 0 to 100 ({@code --memory-swappiness}).+ */+ public Builder withMemorySwappiness(long memorySwappiness) {+ this.memorySwappiness = memorySwappiness;+ return this;+ }+private void requireNoExistingDeviceRequest() {if (!deviceRequests.isEmpty()) {throw new IllegalStateException(@@ -707,7 +777,9 @@ public class ContainerBuilder {readonlyRootfs,List.copyOf(linkLocalIps),Map.copyOf(portBindingHostIps),- init+ init,+ new LinuxOptions(List.copyOf(capAdd), List.copyOf(capDrop), List.copyOf(devices),+ shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness));}}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.javaindex ca4b409d2d..a646a7cf44 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@@ -35,8 +35,10 @@ import org.jboss.logging.Logger;import java.io.Closeable;import java.nio.file.Files;import java.nio.file.Path;+import java.util.ArrayList;import java.util.HashMap;import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.Optional;import java.util.OptionalInt;@@ -1209,6 +1211,30 @@ public class ContainerLifecycleManager {}}+ /**+ * Capability names as a task definition or a caller gives them, with or without the+ * {@code CAP_} prefix and in any case. A name Docker does not know fails the create, as+ * {@code docker run --cap-add} does.+ */+ private static List<Capability> capabilities(List<String> names) {+ List<Capability> result = new ArrayList<>();+ for (String name : names) {+ String normalized = name.trim().toUpperCase(Locale.ROOT);+ if (normalized.startsWith("CAP_")) {+ normalized = normalized.substring("CAP_".length());+ }+ try {+ Capability capability = Capability.valueOf(normalized);+ if (!result.contains(capability)) {+ result.add(capability);+ }+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException("Unknown Linux capability: " + name, e);+ }+ }+ return result;+ }+private HostConfig buildHostConfig(ContainerSpec spec) {HostConfig hostConfig = HostConfig.newHostConfig();@@ -1216,15 +1242,45 @@ public class ContainerLifecycleManager {if (spec.privileged()) {hostConfig.withPrivileged(true);}+ LinuxOptions linux = spec.linuxOptions();+ List<Capability> capDrop = new ArrayList<>();+ List<Capability> capAdd = capabilities(linux.capAdd());if ("true".equals(ContainerStorageHelper.labelValue(spec.labels(), ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL))) {- hostConfig.withCapDrop(Capability.NET_ADMIN, Capability.NET_RAW);+ // The security group is enforced inside the namespace the workload shares, so the+ // workload must not be able to rewrite it, whatever capabilities it asks for. Docker+ // applies a named add over a drop, so the two are taken out of the adds as well; ALL+ // among the adds is every capability but the dropped ones, so it can stay.+ capDrop.add(Capability.NET_ADMIN);+ capDrop.add(Capability.NET_RAW);+ capAdd.removeAll(capDrop);+ }+ for (Capability capability : capabilities(linux.capDrop())) {+ if (!capDrop.contains(capability)) {+ capDrop.add(capability);+ }}// The firewall helper only has to program nftables in the namespace it already owns,// which needs CAP_NET_ADMIN and nothing else that privileged mode would also grant.if ("true".equals(ContainerStorageHelper.labelValue(- spec.labels(), ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL))) {- hostConfig.withCapAdd(Capability.NET_ADMIN);+ spec.labels(), ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL))+ && !capAdd.contains(Capability.NET_ADMIN)) {+ capAdd.add(Capability.NET_ADMIN);+ }+ if (!capDrop.isEmpty()) {+ hostConfig.withCapDrop(capDrop.toArray(new Capability[0]));+ }+ if (!capAdd.isEmpty()) {+ hostConfig.withCapAdd(capAdd.toArray(new Capability[0]));+ }+ if (!linux.devices().isEmpty()) {+ hostConfig.withDevices(linux.devices());+ }+ if (linux.shmSizeBytes() != null) {+ hostConfig.withShmSize(linux.shmSizeBytes());+ }+ if (!linux.tmpfs().isEmpty()) {+ hostConfig.withTmpFs(linux.tmpfs());}if (spec.cgroupnsMode() != null && !spec.cgroupnsMode().isBlank()) {@@ -1241,6 +1297,12 @@ public class ContainerLifecycleManager {if (spec.hasMemoryLimit()) {hostConfig.withMemory(spec.memoryBytes());}+ if (linux.memorySwapBytes() != null) {+ hostConfig.withMemorySwap(linux.memorySwapBytes());+ }+ if (linux.memorySwappiness() != null) {+ hostConfig.withMemorySwappiness(linux.memorySwappiness());+ }// CPU quota and weightif (spec.nanoCpus() != null && spec.nanoCpus() > 0) {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.javaindex 39c60fc731..8d324dfcf9 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@@ -47,6 +47,8 @@ import java.util.regex.Pattern;* 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+ * @param linuxOptions Capabilities, devices, shared memory, tmpfs and swap+ * ({@link LinuxOptions#NONE} = daemon defaults)*/public record ContainerSpec(String image,@@ -77,13 +79,17 @@ public record ContainerSpec(boolean readonlyRootfs,List<String> linkLocalIps,Map<Integer, String> portBindingHostIps,- boolean init+ boolean init,+ LinuxOptions linuxOptions) {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");private static final Set<String> NAMESPACE_NETWORK_MODES = Set.of("host", "none");public ContainerSpec {+ if (linuxOptions == null) {+ linuxOptions = LinuxOptions.NONE;+ }if (linkLocalIps != null && !linkLocalIps.isEmpty()) {requireUserDefinedNetwork(networkMode);linkLocalIps.forEach(ContainerSpec::requireLinkLocalIpv4);@@ -97,7 +103,48 @@ 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(), false);+ null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE);+ }++ /**+ * Backward-compatible constructor that leaves {@code linuxOptions} to the daemon, so callers+ * that predate the Linux process options keep their existing behaviour.+ */+ public ContainerSpec(+ String image,+ String name,+ List<String> env,+ List<String> cmd,+ List<String> entrypoint,+ Long memoryBytes,+ Map<Integer, Integer> portBindings,+ List<Integer> loopbackPortBindings,+ List<Integer> exposedPorts,+ String networkMode,+ List<Mount> mounts,+ List<Bind> binds,+ List<VolumesFrom> volumesFrom,+ List<String> extraHosts,+ Map<String, String> labels,+ LogConfig logConfig,+ boolean privileged,+ String cgroupnsMode,+ List<String> dnsServers,+ String workingDir,+ String user,+ List<String> groupAdd,+ List<DeviceRequest> deviceRequests,+ Long nanoCpus,+ Integer cpuShares,+ boolean readonlyRootfs,+ List<String> linkLocalIps,+ Map<Integer, String> portBindingHostIps,+ boolean init+ ) {+ this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,+ exposedPorts, networkMode, mounts, binds, volumesFrom, extraHosts, labels, logConfig,+ privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests,+ nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, LinuxOptions.NONE);}/**@@ -129,7 +176,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(), false);+ List.of(), Map.of(), false, LinuxOptions.NONE);}/**@@ -163,7 +210,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(), false);+ null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE);}/**@@ -197,7 +244,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(), false);+ null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE);}/**diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/LinuxOptions.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/LinuxOptions.javanew file mode 100644index 0000000000..b19b1d12ed--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/LinuxOptions.java@@ -0,0 +1,35 @@+package io.github.hectorvent.floci.core.common.docker;++import com.github.dockerjava.api.model.Device;++import java.util.List;+import java.util.Map;++/**+ * The Linux process options a container is created with, as {@code docker run} names them:+ * {@code --cap-add}, {@code --cap-drop}, {@code --device}, {@code --shm-size}, {@code --tmpfs},+ * {@code --memory-swap} and {@code --memory-swappiness}; {@code --init} is+ * {@link ContainerSpec#init()}. {@link #NONE} leaves every one of them to the daemon.+ *+ * @param capAdd capabilities added to the daemon's default set, named without {@code CAP_}+ * @param capDrop capabilities dropped from the daemon's default set, named without {@code CAP_}+ * @param devices host devices exposed inside the container+ * @param shmSizeBytes size of {@code /dev/shm} in bytes (null = daemon default)+ * @param tmpfs tmpfs mounts, keyed by container path, each with Docker's option string+ * (for example {@code "noexec,size=64m"})+ * @param memorySwapBytes memory plus swap the container may use, in bytes; equal to the memory+ * limit means no swap (null = daemon default)+ * @param memorySwappiness swappiness from 0 to 100 (null = daemon default)+ */+public record LinuxOptions(+ List<String> capAdd,+ List<String> capDrop,+ List<Device> devices,+ Long shmSizeBytes,+ Map<String, String> tmpfs,+ Long memorySwapBytes,+ Long memorySwappiness+) {+ public static final LinuxOptions NONE =+ new LinuxOptions(List.of(), List.of(), List.of(), null, Map.of(), null, null);+}diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbRequestShapes.javaindex 9127a56396..9eaa2bee29 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbRequestShapes.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbRequestShapes.java@@ -1,30 +1,39 @@package io.github.hectorvent.floci.services.dynamodb;import com.fasterxml.jackson.databind.JsonNode;-import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RequestShapeCheck;+import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;import io.github.hectorvent.floci.core.common.RequestShapeModel;-import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;-import java.util.Iterator;-import java.util.Map;+import java.util.Set;/*** Rejects a DynamoDB request member of the wrong JSON type with the SerializationException* DynamoDB answers before it runs the operation. The input shapes come from the vendored* {@code aws/dynamodb-request-shapes.json}, generated from botocore's DynamoDB model by- * {@code tools/aws/regen_dynamodb_shapes.py}.+ * {@code tools/aws/regen_dynamodb_shapes.py}, and are walked by {@link RequestShapeCheck}.*- * <p>AWS reads the body in order and reports the first bad member, without naming it. A JSON- * null counts as an absent member, and a member the model does not know is ignored.+ * <p>AWS reads the body in order and reports the first bad member, without naming it.*/public final class DynamoDbRequestShapes {static final String RESOURCE_NAME = "aws/dynamodb-request-shapes.json";- private static final String OBJECT_NOT_EXPECTED = "Start of structure or map found where not expected";private static final String UNKNOWN_ERROR = "UnknownError";- private static final String UNEXPECTED_FIELD_TYPE = "Unexpected field type";- private static final String UNEXPECTED_VALUE_TYPE = "Unexpected value type in payload";+ private static final ByPosition SCALAR_FOR_CONTAINER = new ByPosition("Unexpected field type", UNKNOWN_ERROR);++ private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages(+ "SerializationException",+ "Start of structure or map found where not expected",+ UNKNOWN_ERROR,+ new ByPosition("Unexpected field type", "Unexpected value type in payload"),+ SCALAR_FOR_CONTAINER,+ SCALAR_FOR_CONTAINER,+ "%s cannot be converted to %s",+ true,+ "Unexpected token received from parser",+ "only base-64-encoded strings are convertible to bytes",+ Set.of("string", "integer", "long", "double", "timestamp", "boolean", "blob"));private static final class Holder {static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "DynamoDB request shapes");@@ -41,120 +50,7 @@ public final class DynamoDbRequestShapes {static void check(RequestShapeModel model, String action, JsonNode request) {String input = model.operations().get(action);if (input != null) {- checkValue(model, model.shapes().get(input), request, true);+ RequestShapeCheck.check(model, input, request, MESSAGES);}}-- private static void checkValue(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {- if (value.isNull()) {- return;- }- switch (shape.type()) {- case "structure" -> checkStructure(model, shape, value, member);- case "list" -> checkList(model, shape, value, member);- case "map" -> checkMap(model, shape, value, member);- default -> checkScalar(shape.type(), value);- }- }-- private static void checkStructure(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {- if (value.isArray()) {- throw serialization(UNKNOWN_ERROR);- }- if (!value.isObject()) {- throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNEXPECTED_VALUE_TYPE);- }- Iterator<Map.Entry<String, JsonNode>> fields = value.fields();- while (fields.hasNext()) {- Map.Entry<String, JsonNode> field = fields.next();- String memberShape = shape.members().get(field.getKey());- if (memberShape != null) {- checkValue(model, model.shapes().get(memberShape), field.getValue(), true);- }- }- }-- private static void checkList(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {- if (value.isObject()) {- throw serialization(OBJECT_NOT_EXPECTED);- }- if (!value.isArray()) {- throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNKNOWN_ERROR);- }- Shape element = model.shapes().get(shape.element());- for (JsonNode item : value) {- checkValue(model, element, item, false);- }- }-- private static void checkMap(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {- if (value.isArray()) {- throw serialization(UNKNOWN_ERROR);- }- if (!value.isObject()) {- throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNKNOWN_ERROR);- }- Shape element = model.shapes().get(shape.element());- for (JsonNode item : value) {- checkValue(model, element, item, false);- }- }-- private static void checkScalar(String type, JsonNode value) {- if (value.isObject()) {- throw serialization(OBJECT_NOT_EXPECTED);- }- if (value.isArray()) {- throw serialization(UNKNOWN_ERROR);- }- switch (type) {- case "string" -> requireToken(value.isTextual(), value, "String");- case "integer" -> requireToken(value.isNumber(), value, "Integer");- case "long" -> requireToken(value.isNumber(), value, "Long");- case "double" -> requireToken(value.isNumber(), value, "Double");- case "timestamp" -> requireToken(value.isNumber(), value, "Date");- case "boolean" -> checkBoolean(value);- case "blob" -> {- if (!value.isTextual() && !value.isBinary()) {- throw serialization("only base-64-encoded strings are convertible to bytes");- }- }- default -> {- }- }- }-- private static void checkBoolean(JsonNode value) {- if (value.isTextual()) {- String text = value.asText();- if (!"true".equalsIgnoreCase(text) && !"false".equalsIgnoreCase(text)) {- throw serialization("Unexpected token received from parser");- }- return;- }- requireToken(value.isBoolean(), value, "Boolean");- }-- private static void requireToken(boolean accepted, JsonNode value, String target) {- if (!accepted) {- throw serialization(token(value) + " cannot be converted to " + target);- }- }-- private static String token(JsonNode value) {- if (value.isIntegralNumber()) {- return "NUMBER_VALUE";- }- if (value.isNumber()) {- return "DECIMAL_VALUE";- }- if (value.isBoolean()) {- return value.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";- }- return "STRING_VALUE";- }-- private static AwsException serialization(String message) {- return new AwsException("SerializationException", message, 400);- }}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.javaindex 837b7b9b2b..8a1ff47548 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;+import io.github.hectorvent.floci.services.ecs.container.EcsLinuxParameters;import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;import io.github.hectorvent.floci.services.ecs.container.EcsTaskLaunchException;import io.github.hectorvent.floci.services.ecs.exec.EcsExecChannelHandler;@@ -872,9 +873,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, ResettabvalidateEphemeralStorage(request.getEphemeralStorage());validateContainerDependencies(containerDefs);validateFirelensS3Config(containerDefs, fargate);+ EcsLinuxParameters.validate(containerDefs);if (fargate) {validateFargateUnsupportedParameters(request);}+ if (containerDefs != null) {+ containerDefs.forEach(containerManager::checkDeviceHostPaths);+ }+ EcsLinuxParameters.normalize(containerDefs);String family = request.getFamily();int revision = latestRevisions.compute(familyKey(region, family),(key, latest) -> (latest != null ? latest : latestRevision(region, family)) + 1);@@ -1138,7 +1144,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, ResettabrejectOnFargate(def.getDockerSecurityOptions() != null && !def.getDockerSecurityOptions().isEmpty(),"dockerSecurityOptions");rejectOnFargate(notEmpty(def.getUnparsed(), "extraHosts"), "extraHosts");- validateFargateLinuxParameters(def);+ EcsLinuxParameters.validateFargate(def);validateFargateResourceRequirements(def);}}@@ -1150,17 +1156,6 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab}}- /** {@code maxSwap} and {@code swappiness} have no meaning on Fargate's managed kernel. */- @SuppressWarnings("unchecked")- private static void validateFargateLinuxParameters(ContainerDefinition def) {- Object linuxParameters = def.getUnparsed() == null ? null : def.getUnparsed().get("linuxParameters");- if (!(linuxParameters instanceof Map<?, ?> parameters)) {- return;- }- rejectOnFargate(parameters.get("maxSwap") != null, "maxSwap");- rejectOnFargate(parameters.get("swappiness") != null, "swappiness");- }-/** A Fargate task cannot ask for a GPU; only {@code InferenceAccelerator} requirements remain. */private static void validateFargateResourceRequirements(ContainerDefinition def) {Object requirements = def.getUnparsed() == null ? null : def.getUnparsed().get("resourceRequirements");diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.javaindex 7be5e6f09d..674f9389a2 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java@@ -435,6 +435,11 @@ public class EcsContainerManager {if (Boolean.TRUE.equals(def.getReadonlyRootFilesystem())) {specBuilder.withReadonlyRootfs();}+ // Checked at registration too; again here, as for a host volume, for a definition+ // persisted before the policy covered devices.+ checkDeviceHostPaths(def);+ EcsLinuxParameters.apply(specBuilder, def,+ def.getMemory() != null ? def.getMemory() : parseTaskMemoryMb(task.getMemory()));// Add port mappings. In bridge/host mode an explicit hostPort is// published to the Docker host literally, matching AWS bridge mode@@ -2437,6 +2442,18 @@ public class EcsContainerManager {return collapsed.startsWith("/") ? collapsed : "/" + collapsed;}+ /**+ * Refuses a device whose host path {@link HostVolumePolicy} does not allow, as it refuses a host+ * volume: by default, unless {@code floci.services.ecs.host-volume-roots} holds it or+ * {@code floci.services.ecs.allow-unsafe-host-volumes} is set. A device hands the container the+ * host's hardware directly, so it is no less exposed than a bind mount.+ */+ public void checkDeviceHostPaths(ContainerDefinition def) {+ for (String hostPath : EcsLinuxParameters.deviceHostPaths(def)) {+ hostVolumePolicy.validate(hostPath, HostVolumePolicy.DEVICE_HOST_PATH);+ }+ }+// Inner enum to avoid import cycle — mirrors model.TaskStatus for readabilityprivate enum TaskStatus {RUNNING}}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParameters.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParameters.javanew file mode 100644index 0000000000..0b03fe4286--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParameters.java@@ -0,0 +1,384 @@+package io.github.hectorvent.floci.services.ecs.container;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;++import java.math.BigDecimal;+import java.math.RoundingMode;+import java.util.ArrayList;+import java.util.Collection;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;++/**+ * A container definition's {@code linuxParameters}: checked and stored as RegisterTaskDefinition+ * does, and applied to the container it launches as ECS documents each member:+ * {@code initProcessEnabled} is {@code --init}, {@code capabilities} are {@code --cap-add} and+ * {@code --cap-drop}, {@code devices} are {@code --device} (read, write and mknod when no+ * permissions are given), {@code sharedMemorySize} is {@code --shm-size} in MiB, each+ * {@code tmpfs} entry is a {@code --tmpfs} of its size in MiB with its mount options,+ * {@code maxSwap} is {@code --memory-swap} as the container's memory plus that many MiB (a+ * container with only a soft limit gets none), and {@code swappiness} is {@code --memory-swappiness},+ * which registration requires with {@code maxSwap} and drops without it, as ECS does.+ *+ * <p>RegisterTaskDefinition keeps the members among the definition's unparsed members, which is+ * where they are read from, whether the definition came from the API or a template.+ */+public final class EcsLinuxParameters {++ private static final long MIB = 1024L * 1024L;++ /** The one capability a Fargate container may add (KernelCapabilities, "add"). */+ private static final String FARGATE_CAPABILITY = "SYS_PTRACE";++ /** The values KernelCapabilities lists for {@code add} and {@code drop}. */+ private static final Set<String> KERNEL_CAPABILITIES = Set.of(+ "ALL", "AUDIT_CONTROL", "AUDIT_WRITE", "BLOCK_SUSPEND", "CHOWN", "DAC_OVERRIDE",+ "DAC_READ_SEARCH", "FOWNER", "FSETID", "IPC_LOCK", "IPC_OWNER", "KILL", "LEASE",+ "LINUX_IMMUTABLE", "MAC_ADMIN", "MAC_OVERRIDE", "MKNOD", "NET_ADMIN", "NET_BIND_SERVICE",+ "NET_BROADCAST", "NET_RAW", "SETFCAP", "SETGID", "SETPCAP", "SETUID", "SYS_ADMIN",+ "SYS_BOOT", "SYS_CHROOT", "SYS_MODULE", "SYS_NICE", "SYS_PACCT", "SYS_PTRACE", "SYS_RAWIO",+ "SYS_RESOURCE", "SYS_TIME", "SYS_TTY_CONFIG", "SYSLOG", "WAKE_ALARM");++ /** The tmpfs mount options the Tmpfs reference lists, matched as written, before any {@code =value}. */+ private static final Set<String> TMPFS_MOUNT_OPTIONS = Set.of(+ "defaults", "ro", "rw", "suid", "nosuid", "dev", "nodev", "exec", "noexec", "sync", "async",+ "dirsync", "remount", "mand", "nomand", "atime", "noatime", "diratime", "nodiratime", "bind",+ "rbind", "unbindable", "runbindable", "private", "rprivate", "shared", "rshared", "slave",+ "rslave", "relatime", "norelatime", "strictatime", "nostrictatime", "mode", "uid", "gid",+ "nr_inodes", "nr_blocks", "mpol");++ private static final Set<String> DEVICE_PERMISSIONS = Set.of("read", "write", "mknod");++ private static final Set<String> INTEGER_MEMBERS = Set.of("sharedMemorySize", "maxSwap", "swappiness");++ private EcsLinuxParameters() {+ }++ /**+ * The {@code linuxParameters} rules RegisterTaskDefinition applies whatever the launch type,+ * before Fargate's own, with the messages and in the order measured on AWS (eu-west-1,+ * 2026-10-03, 2026-10-16 and 2026-10-18). First, for every container, the JSON type of every+ * member, against ECS's model (see {@link EcsRequestShapes}); then every capability one the KernelCapabilities reference+ * lists, in any case and without the {@code CAP_} prefix; every device with a host path and only+ * read, write and mknod as permissions, as written; every tmpfs mount with a container path, a+ * size above zero and options the reference lists; a shared memory size above zero; and swap+ * with a swappiness, a swap size of zero or more and a swappiness from 0 to 100. A number is+ * read as the integer AWS stores, its fraction dropped and its range capped.+ */+ public static void validate(List<ContainerDefinition> containerDefs) {+ if (containerDefs == null) {+ return;+ }+ for (ContainerDefinition def : containerDefs) {+ EcsRequestShapes.check("LinuxParameters",+ def.getUnparsed() == null ? null : def.getUnparsed().get("linuxParameters"));+ }+ for (ContainerDefinition def : containerDefs) {+ Map<?, ?> parameters = of(def);+ if (parameters == null) {+ continue;+ }+ for (String list : List.of("add", "drop")) {+ List<String> unrecognized = new ArrayList<>();+ for (String capability : capabilities(parameters, list)) {+ if (!KERNEL_CAPABILITIES.contains(capability.toUpperCase(Locale.ROOT))) {+ unrecognized.add(capability);+ }+ }+ if (!unrecognized.isEmpty()) {+ throw new AwsException("ClientException",+ "Unrecognized Linux capabilities in " + list + ": " + unrecognized, 400);+ }+ }+ for (Map<?, ?> device : entries(parameters.get("devices"))) {+ if (!(device.get("hostPath") instanceof String hostPath) || hostPath.isBlank()) {+ throw new AwsException("ClientException", "Device cannot have empty hostPath", 400);+ }+ for (String permission : strings(device.get("permissions"))) {+ if (!DEVICE_PERMISSIONS.contains(permission)) {+ throw new AwsException("ClientException",+ "Invalid permission: " + permission + " for device " + hostPath, 400);+ }+ }+ }+ for (Map<?, ?> mount : entries(parameters.get("tmpfs"))) {+ if (!(mount.get("containerPath") instanceof String containerPath) || containerPath.isBlank()) {+ throw new AwsException("ClientException",+ "All tmpfs mounts must have a specified containerPath value.", 400);+ }+ Integer size = integer(mount.get("size"));+ if (size == null || size <= 0) {+ throw new AwsException("ClientException", "The container has an invalid tmpfs size value"+ + " specified. It must be a non-zero, non-negative integer.", 400);+ }+ for (String option : strings(mount.get("mountOptions"))) {+ String name = option.contains("=") ? option.substring(0, option.indexOf('=')) : option;+ if (!TMPFS_MOUNT_OPTIONS.contains(name)) {+ throw new AwsException("ClientException",+ "The " + option + " tmpfs mount option specified is invalid.", 400);+ }+ }+ }+ Integer sharedMemorySize = integer(parameters.get("sharedMemorySize"));+ if (sharedMemorySize != null && sharedMemorySize <= 0) {+ throw new AwsException("ClientException", "The container has an invalid shared memory volume"+ + " size. It must be a non-zero, non-negative integer.", 400);+ }+ if (parameters.get("maxSwap") != null && parameters.get("swappiness") == null) {+ throw new AwsException("ClientException",+ "When a container has a swap memory, it must also specify a swappiness value.", 400);+ }+ Integer maxSwap = integer(parameters.get("maxSwap"));+ if (maxSwap != null) {+ if (maxSwap < 0) {+ throw new AwsException("ClientException",+ "The container has an invalid swap memory size. It must be non-negative integer.", 400);+ }+ Integer swappiness = integer(parameters.get("swappiness"));+ if (swappiness != null && (swappiness < 0 || swappiness > 100)) {+ throw new AwsException("ClientException",+ "The container has an invalid swappiness value. It must be between 0 and 100.", 400);+ }+ }+ }+ }++ /**+ * The {@code linuxParameters} Fargate cannot honour, in the order RegisterTaskDefinition+ * checks them on AWS: host devices, the shared memory size, swap, then any capability but+ * {@code SYS_PTRACE}, the only one Fargate adds, matched as written. AWS words these without+ * the trailing period its other Fargate refusals carry.+ */+ public static void validateFargate(ContainerDefinition def) {+ Map<?, ?> parameters = of(def);+ if (parameters == null) {+ return;+ }+ rejectOnFargate(parameters.get("devices") instanceof Collection<?> devices && !devices.isEmpty(),+ "devices");+ rejectOnFargate(parameters.get("sharedMemorySize") != null, "sharedMemorySize");+ rejectOnFargate(parameters.get("maxSwap") != null, "maxSwap");+ rejectOnFargate(parameters.get("swappiness") != null, "swappiness");+ for (String capability : capabilities(parameters, "add")) {+ if (!FARGATE_CAPABILITY.equals(capability)) {+ throw new AwsException("ClientException", capability + " is not allowed on Fargate.", 400);+ }+ }+ }++ /**+ * The {@code linuxParameters} as RegisterTaskDefinition stores them (measured): a member that+ * is null is left out, numbers are the integers {@link #integer} reads and booleans the ones+ * {@link #bool} reads, a swappiness without a swap size is dropped, whatever its value, and+ * capabilities always carry both an {@code add} and a {@code drop} list, without null entries.+ */+ public static void normalize(List<ContainerDefinition> containerDefs) {+ if (containerDefs == null) {+ return;+ }+ for (ContainerDefinition def : containerDefs) {+ Map<?, ?> parameters = of(def);+ if (parameters == null) {+ continue;+ }+ Map<Object, Object> stored = new LinkedHashMap<>();+ parameters.forEach((member, value) -> {+ if (value != null) {+ stored.put(member, value);+ }+ });+ for (String member : INTEGER_MEMBERS) {+ if (stored.containsKey(member)) {+ stored.put(member, integer(stored.get(member)));+ }+ }+ if (stored.containsKey("initProcessEnabled")) {+ stored.put("initProcessEnabled", bool(stored.get("initProcessEnabled")));+ }+ if (stored.get("maxSwap") == null) {+ stored.remove("swappiness");+ }+ if (stored.get("capabilities") instanceof Map<?, ?> capabilities) {+ Map<Object, Object> lists = new LinkedHashMap<>();+ lists.put("add", strings(capabilities.get("add")));+ lists.put("drop", strings(capabilities.get("drop")));+ stored.put("capabilities", lists);+ }+ if (stored.get("tmpfs") instanceof Collection<?> mounts) {+ List<Map<Object, Object>> storedMounts = new ArrayList<>();+ for (Map<?, ?> mount : entries(mounts)) {+ Map<Object, Object> storedMount = new LinkedHashMap<>(mount);+ storedMount.put("size", integer(mount.get("size")));+ storedMounts.add(storedMount);+ }+ stored.put("tmpfs", storedMounts);+ }+ Map<String, Object> unparsed = new LinkedHashMap<>(def.getUnparsed());+ unparsed.put("linuxParameters", stored);+ def.setUnparsed(unparsed);+ }+ }++ /** The host path of each device the definition asks for, which {@link HostVolumePolicy} checks. */+ public static List<String> deviceHostPaths(ContainerDefinition def) {+ Map<?, ?> parameters = of(def);+ List<String> hostPaths = new ArrayList<>();+ if (parameters != null) {+ for (Map<?, ?> device : entries(parameters.get("devices"))) {+ if (device.get("hostPath") instanceof String hostPath) {+ hostPaths.add(hostPath);+ }+ }+ }+ return hostPaths;+ }++ /**+ * @param memoryLimitMb the hard memory limit the container runs under, which {@code maxSwap}+ * is added to; without one Docker cannot limit swap, so {@code maxSwap} is not applied+ */+ static void apply(ContainerBuilder.Builder spec, ContainerDefinition def, Integer memoryLimitMb) {+ Map<?, ?> parameters = of(def);+ if (parameters == null) {+ return;+ }+ if (Boolean.TRUE.equals(bool(parameters.get("initProcessEnabled")))) {+ spec.withInit();+ }+ capabilities(parameters, "add").forEach(spec::withCapAdd);+ capabilities(parameters, "drop").forEach(spec::withCapDrop);+ for (Map<?, ?> device : entries(parameters.get("devices"))) {+ if (device.get("hostPath") instanceof String hostPath) {+ String containerPath = device.get("containerPath") instanceof String path && !path.isBlank()+ ? path : hostPath;+ spec.withDevice(hostPath, containerPath, cgroupPermissions(strings(device.get("permissions"))));+ }+ }+ Integer sharedMemorySize = integer(parameters.get("sharedMemorySize"));+ if (sharedMemorySize != null) {+ spec.withShmSizeBytes(sharedMemorySize * MIB);+ }+ for (Map<?, ?> mount : entries(parameters.get("tmpfs"))) {+ Integer size = integer(mount.get("size"));+ if (mount.get("containerPath") instanceof String containerPath && size != null) {+ List<String> options = new ArrayList<>(strings(mount.get("mountOptions")));+ options.add("size=" + size + "m");+ spec.withTmpfs(containerPath, String.join(",", options));+ }+ }+ Integer maxSwap = integer(parameters.get("maxSwap"));+ if (maxSwap != null) {+ if (memoryLimitMb != null) {+ spec.withMemorySwapBytes((memoryLimitMb + (long) maxSwap) * MIB);+ }+ // Docker takes a swappiness without a swap limit; registration keeps one only with maxSwap.+ Integer swappiness = integer(parameters.get("swappiness"));+ if (swappiness != null) {+ spec.withMemorySwappiness(swappiness.longValue());+ }+ }+ }++ private static void rejectOnFargate(boolean present, String parameter) {+ if (present) {+ throw new AwsException("ClientException",+ "Fargate compatible task definitions do not support " + parameter, 400);+ }+ }++ /** ECS's {@code read}, {@code write} and {@code mknod} as Docker's cgroup permission letters. */+ private static String cgroupPermissions(List<String> permissions) {+ if (permissions.isEmpty()) {+ return "rwm";+ }+ StringBuilder letters = new StringBuilder();+ if (permissions.contains("read")) {+ letters.append('r');+ }+ if (permissions.contains("write")) {+ letters.append('w');+ }+ if (permissions.contains("mknod")) {+ letters.append('m');+ }+ return letters.toString();+ }++ private static Map<?, ?> of(ContainerDefinition def) {+ Object linuxParameters = def.getUnparsed() == null ? null : def.getUnparsed().get("linuxParameters");+ return linuxParameters instanceof Map<?, ?> parameters ? parameters : null;+ }++ private static List<String> capabilities(Map<?, ?> parameters, String list) {+ return parameters.get("capabilities") instanceof Map<?, ?> capabilities+ ? strings(capabilities.get(list)) : List.of();+ }++ /** The members of a list as written, null ones left out; empty when it is not a list. */+ private static List<String> strings(Object list) {+ List<String> result = new ArrayList<>();+ if (list instanceof Collection<?> items) {+ for (Object item : items) {+ if (item != null) {+ result.add(String.valueOf(item));+ }+ }+ }+ return result;+ }++ /** The objects of a list, a null one read as empty, as RegisterTaskDefinition reads it. */+ private static List<Map<?, ?>> entries(Object list) {+ List<Map<?, ?>> entries = new ArrayList<>();+ if (list instanceof Collection<?> items) {+ for (Object item : items) {+ if (item == null) {+ entries.add(Map.of());+ } else if (item instanceof Map<?, ?> entry) {+ entries.add(entry);+ }+ }+ }+ return entries;+ }++ /**+ * The integer RegisterTaskDefinition reads from a number (measured): its fraction dropped+ * toward zero (1.9 is 1, -0.5 is 0) and its value capped to the 32-bit range (3000000000 is+ * 2147483647); null when it is not a number.+ */+ private static Integer integer(Object value) {+ if (!(value instanceof Number number)) {+ return null;+ }+ BigDecimal whole = new BigDecimal(number.toString()).setScale(0, RoundingMode.DOWN);+ if (whole.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) {+ return Integer.MAX_VALUE;+ }+ if (whole.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) {+ return Integer.MIN_VALUE;+ }+ return whole.intValue();+ }++ /** A boolean, or a string that reads as one in any case (measured); null otherwise. */+ private static Boolean bool(Object value) {+ if (value instanceof Boolean flag) {+ return flag;+ }+ if (value instanceof String text) {+ if ("true".equalsIgnoreCase(text)) {+ return true;+ }+ if ("false".equalsIgnoreCase(text)) {+ return false;+ }+ }+ return null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapes.javanew file mode 100644index 0000000000..569c5d3e31--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapes.java@@ -0,0 +1,59 @@+package io.github.hectorvent.floci.services.ecs.container;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.RequestShapeCheck;+import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;+import io.github.hectorvent.floci.core.common.RequestShapeModel;++import java.util.Set;++/**+ * Rejects an ECS request member of the wrong JSON type with the InvalidParameterException ECS's+ * deserializer answers before it validates anything (measured with raw requests on+ * RegisterTaskDefinition, eu-west-1, 2026-10-18). The shapes come from the vendored+ * {@code aws/ecs-request-shapes.json}, generated from botocore's ECS model by+ * {@code tools/aws/regen_ecs_shapes.py}, and are walked by {@link RequestShapeCheck}.+ *+ * <p>It checks the members Floci keeps unparsed, a container's {@code linuxParameters}, whose+ * scalars are strings, integers and booleans. A list where none is expected is refused with no+ * message at all.+ */+final class EcsRequestShapes {++ static final String RESOURCE_NAME = "aws/ecs-request-shapes.json";++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static final String UNEXPECTED_FIELD_TYPE = "Unexpected field type";+ private static final ByPosition SCALAR_FOR_STRUCTURE =+ new ByPosition(UNEXPECTED_FIELD_TYPE, "Unexpected value type in payload");++ private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages(+ "InvalidParameterException",+ "Start of structure or map found where not expected",+ null,+ SCALAR_FOR_STRUCTURE,+ ByPosition.same(UNEXPECTED_FIELD_TYPE),+ SCALAR_FOR_STRUCTURE,+ "%s cannot be converted to %s",+ false,+ "Unexpected token received from parser",+ null,+ Set.of("string", "integer", "boolean"));++ private static final class Holder {+ static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "ECS request shapes");+ }++ private EcsRequestShapes() {+ }++ /** Checks {@code value}, a structure member, against the shape {@code shapeName}. */+ static void check(String shapeName, Object value) {+ check(Holder.MODEL, shapeName, value);+ }++ static void check(RequestShapeModel model, String shapeName, Object value) {+ RequestShapeCheck.check(model, shapeName, MAPPER.valueToTree(value), MESSAGES);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.javaindex 983aba6b56..175bf3d31b 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java@@ -16,7 +16,8 @@ import java.util.List;import java.util.function.Function;/**- * Guards task-definition {@code volumes[].host.sourcePath} against the unsafe bind mounts a+ * Guards task-definition {@code volumes[].host.sourcePath}, and the host path of each of a+ * container's {@code linuxParameters.devices}, against the unsafe host access a* caller-controlled task definition could otherwise request: relative/traversal paths, the bare* filesystem root, anything that reaches the Docker daemon socket, and (unless* {@code floci.services.ecs.allow-unsafe-host-volumes} is set) paths outside the configured@@ -35,6 +36,12 @@ import java.util.function.Function;@ApplicationScopedpublic class HostVolumePolicy {+ /** The field {@link #validate(String)} names. */+ public static final String VOLUME_SOURCE_PATH = "volumes[].host.sourcePath";++ /** The field a container's devices are checked as. */+ public static final String DEVICE_HOST_PATH = "containerDefinitions[].linuxParameters.devices[].hostPath";+private static final List<String> LITERAL_DOCKER_SOCKET_PATHS = List.of("/var/run/docker.sock","/run/docker.sock");@@ -60,33 +67,38 @@ public class HostVolumePolicy {}public void validate(String sourcePath) {+ validate(sourcePath, VOLUME_SOURCE_PATH);+ }++ /** As {@link #validate(String)}, for the host path {@code field} names in its refusals. */+ public void validate(String sourcePath, String field) {Path rawPath;try {rawPath = Path.of(sourcePath);} catch (InvalidPathException e) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath is not a valid filesystem path: " + sourcePath, 400);+ field + " is not a valid filesystem path: " + sourcePath, 400);}if (!rawPath.isAbsolute()) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath must be an absolute path: " + sourcePath, 400);+ field + " must be an absolute path: " + sourcePath, 400);}for (Path segment : rawPath) {if ("..".equals(segment.toString())) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath must not contain '..' segments: " + sourcePath, 400);+ field + " must not contain '..' segments: " + sourcePath, 400);}}Path normalized = rawPath.normalize();if (normalized.getNameCount() == 0) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath must not be the filesystem root: " + sourcePath, 400);+ field + " must not be the filesystem root: " + sourcePath, 400);}Path canonical = canonicalizeForContainment(normalized);if (exposesDockerSocket(normalized, canonical)) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath must not target or contain the Docker socket: "+ field + " must not target or contain the Docker socket: "+ sourcePath, 400);}@@ -97,7 +109,7 @@ public class HostVolumePolicy {List<String> roots = ecsConfig.hostVolumeRoots().orElse(List.of());if (roots.isEmpty()) {throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath is rejected by default: " + sourcePath+ field + " is rejected by default: " + sourcePath+ ". Configure floci.services.ecs.host-volume-roots"+ " (FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS) with approved parent"+ " directories, or set floci.services.ecs.allow-unsafe-host-volumes"@@ -111,7 +123,7 @@ public class HostVolumePolicy {}}throw new AwsException("InvalidParameterException",- "volumes[].host.sourcePath is not within an approved host-volume root: " + sourcePath, 400);+ field + " is not within an approved host-volume root: " + sourcePath, 400);}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.javaindex 1e671c7765..b8b36cfa88 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java@@ -24,6 +24,14 @@ import java.util.Map;*/final class SesV2Json {+ /** The deserializer's wording, which {@link SesV2RequestShapes}' walk of the body shapes shares. */+ static final String SERIALIZATION_EXCEPTION = "SerializationException";+ static final String CONVERSION = "%s can not be converted to a %s";+ static final String EXPECTED_NULL = "Expected null";+ static final String EXPECTED_LIST = "Expected list or null";+ static final String LIST_NOT_EXPECTED = "Start of list found where not expected";+ static final String OBJECT_NOT_EXPECTED = "Start of structure or map found where not expected.";+private SesV2Json() {}@@ -79,7 +87,7 @@ final class SesV2Json {// error (AWS returns SerializationException for a scalar/array element; it returns a 500// InternalFailure for a null element, a server-side bug we normalize to the same 400).if (!t.isObject()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}JsonNode key = t.path("Key");JsonNode value = t.path("Value");@@ -88,7 +96,7 @@ final class SesV2Json {// SerializationException rather than turning 123 into "123". A missing/null member is left// to the downstream service validation, matching AWS.if (nonStringMember(key) || nonStringMember(value)) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}out.add(new Tag(key.asText(null), value.asText(null)));}@@ -134,12 +142,12 @@ final class SesV2Json {return switch (node.textValue().toLowerCase(Locale.ROOT)) {case "true", "yes", "y", "t", "1" -> true;case "false", "no", "n", "f", "0" -> false;- default -> throw new AwsException("SerializationException",+ default -> throw new AwsException(SERIALIZATION_EXCEPTION,"STRING_VALUE can not be converted to an Boolean", 400);};}if (node.isNull()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}throw scalarTypeError(node, "Boolean");}@@ -223,34 +231,30 @@ final class SesV2Json {*/static AwsException scalarTypeError(JsonNode node, String target) {if (node.isNumber()) {- return new AwsException("SerializationException",- "NUMBER_VALUE can not be converted to a " + target, 400);+ return new AwsException(SERIALIZATION_EXCEPTION, CONVERSION.formatted("NUMBER_VALUE", target), 400);}if (node.isBoolean()) {- return new AwsException("SerializationException",- (node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") + " can not be converted to a " + target,- 400);+ return new AwsException(SERIALIZATION_EXCEPTION,+ CONVERSION.formatted(node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE", target), 400);}return unexpectedStartError(node);}/** The deserializer's message for a structure or map member given a scalar. */static AwsException expectedNullError() {- return new AwsException("SerializationException", "Expected null", 400);+ return new AwsException(SERIALIZATION_EXCEPTION, EXPECTED_NULL, 400);}/** The deserializer's message for a list member given a scalar. */static AwsException expectedListError() {- return new AwsException("SerializationException", "Expected list or null", 400);+ return new AwsException(SERIALIZATION_EXCEPTION, EXPECTED_LIST, 400);}static AwsException unexpectedStartError(JsonNode node) {if (node.isArray()) {- return new AwsException("SerializationException",- "Start of list found where not expected", 400);+ return new AwsException(SERIALIZATION_EXCEPTION, LIST_NOT_EXPECTED, 400);}- return new AwsException("SerializationException",- "Start of structure or map found where not expected.", 400);+ return new AwsException(SERIALIZATION_EXCEPTION, OBJECT_NOT_EXPECTED, 400);}// Read a typed string member: absent/null returns null, but a present value of the wrong JSON type@@ -261,7 +265,7 @@ final class SesV2Json {return null;}if (!n.isTextual()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}return n.textValue();}@@ -275,12 +279,12 @@ final class SesV2Json {return null;}if (!n.isArray()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}List<String> values = new ArrayList<>();for (JsonNode item : n) {if (!item.isTextual()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}values.add(item.textValue());}@@ -296,7 +300,7 @@ final class SesV2Json {return null;}if (!n.isIntegralNumber() || !n.canConvertToInt()) {- throw new AwsException("SerializationException", null, 400);+ throw new AwsException(SERIALIZATION_EXCEPTION, null, 400);}return n.intValue();}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.javaindex 82ba815124..aec5b6115a 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java@@ -2,29 +2,28 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.databind.JsonNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RequestShapeCheck;+import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;import io.github.hectorvent.floci.core.common.RequestShapeModel;-import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;import org.jboss.logging.Logger;-import java.util.Map;+import java.util.Set;/*** Rejects an SES v2 request body member of the wrong JSON type with the SerializationException* SES answers before it validates anything. The body shapes come from the vendored* {@code aws/sesv2-request-shapes.json}, generated from botocore's SES v2 model by- * {@code tools/aws/regen_sesv2_shapes.py}.+ * {@code tools/aws/regen_sesv2_shapes.py}, and are walked by {@link RequestShapeCheck}.** <p>An operation calls this when its body nests a structure in a structure or holds a list of* structures, where member-by-member checks drift apart. A flat body, a {@code Tags}-only body and* a list operation's map {@code Filter} keep the {@link SesV2Json} member helpers.*- * <p>AWS reads the body in order and reports the first bad member, without naming it. A JSON null- * counts as an absent member, a null list element is left to the operation's own validation, and- * a member the model does not know is ignored. A map container answers like a structure, as the- * list operations' {@code Filter} already does. Only the string, blob, list and structure messages- * have been probed, so a number, boolean or timestamp member is still checked by its controller.- * The probes sent integers only: a non-integral number is reported as {@code NUMBER_VALUE} too,- * although AWS may name it differently.+ * <p>AWS reads the body in order and reports the first bad member, without naming it. A map+ * container answers like a structure, as the list operations' {@code Filter} already does. Only the+ * string, blob, list and structure messages have been probed, so a number, boolean or timestamp+ * member is still checked by its controller. The probes sent integers only: a non-integral number+ * is reported as {@code NUMBER_VALUE} too, although AWS may name it differently.*/final class SesV2RequestShapes {@@ -32,6 +31,21 @@ final class SesV2RequestShapes {private static final Logger LOG = Logger.getLogger(SesV2RequestShapes.class);+ private static final ByPosition EXPECTED_NULL = ByPosition.same(SesV2Json.EXPECTED_NULL);++ private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages(+ SesV2Json.SERIALIZATION_EXCEPTION,+ SesV2Json.OBJECT_NOT_EXPECTED,+ SesV2Json.LIST_NOT_EXPECTED,+ EXPECTED_NULL,+ ByPosition.same(SesV2Json.EXPECTED_LIST),+ EXPECTED_NULL,+ SesV2Json.CONVERSION,+ false,+ null,+ null,+ Set.of("string", "blob"));+private static final class Holder {static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "SES v2 request shapes");}@@ -51,67 +65,6 @@ final class SesV2RequestShapes {throw new AwsException("InternalFailure","The request processing has failed because of an unknown error.", 500);}- checkValue(model, model.shapes().get(input), request);- }-- private static void checkValue(RequestShapeModel model, Shape shape, JsonNode value) {- if (value.isNull()) {- return;- }- switch (shape.type()) {- case "structure" -> checkStructure(model, shape, value);- case "map" -> checkMap(model, shape, value);- case "list" -> checkList(model, shape, value);- case "string" -> checkScalar(value, "String");- case "blob" -> checkScalar(value, "Blob");- default -> {- }- }- }-- private static void checkStructure(RequestShapeModel model, Shape shape, JsonNode value) {- requireObject(value);- for (Map.Entry<String, JsonNode> field : value.properties()) {- String memberShape = shape.members().get(field.getKey());- if (memberShape != null) {- checkValue(model, model.shapes().get(memberShape), field.getValue());- }- }- }-- private static void checkMap(RequestShapeModel model, Shape shape, JsonNode value) {- requireObject(value);- Shape element = model.shapes().get(shape.element());- for (JsonNode item : value) {- checkValue(model, element, item);- }- }-- private static void checkList(RequestShapeModel model, Shape shape, JsonNode value) {- if (value.isObject()) {- throw SesV2Json.unexpectedStartError(value);- }- if (!value.isArray()) {- throw SesV2Json.expectedListError();- }- Shape element = model.shapes().get(shape.element());- for (JsonNode item : value) {- checkValue(model, element, item);- }- }-- private static void requireObject(JsonNode value) {- if (value.isArray()) {- throw SesV2Json.unexpectedStartError(value);- }- if (!value.isObject()) {- throw SesV2Json.expectedNullError();- }- }-- private static void checkScalar(JsonNode value, String target) {- if (!value.isTextual()) {- throw SesV2Json.scalarTypeError(value, target);- }+ RequestShapeCheck.check(model, input, request, MESSAGES);}}diff --git a/src/main/resources/aws/ecs-request-shapes.json b/src/main/resources/aws/ecs-request-shapes.jsonnew file mode 100644index 0000000000..8b9e25e9ef--- /dev/null+++ b/src/main/resources/aws/ecs-request-shapes.json@@ -0,0 +1,2616 @@+{+ "_source": {+ "generator": "tools/aws/regen_ecs_shapes.py",+ "botocore": "botocore 1.43.113 (installed package)"+ },+ "operations": {+ "ContinueServiceDeployment": "ContinueServiceDeploymentRequest",+ "CreateCapacityProvider": "CreateCapacityProviderRequest",+ "CreateCluster": "CreateClusterRequest",+ "CreateDaemon": "CreateDaemonRequest",+ "CreateExpressGatewayService": "CreateExpressGatewayServiceRequest",+ "CreateService": "CreateServiceRequest",+ "CreateTaskSet": "CreateTaskSetRequest",+ "DeleteAccountSetting": "DeleteAccountSettingRequest",+ "DeleteAttributes": "DeleteAttributesRequest",+ "DeleteCapacityProvider": "DeleteCapacityProviderRequest",+ "DeleteCluster": "DeleteClusterRequest",+ "DeleteDaemon": "DeleteDaemonRequest",+ "DeleteDaemonTaskDefinition": "DeleteDaemonTaskDefinitionRequest",+ "DeleteExpressGatewayService": "DeleteExpressGatewayServiceRequest",+ "DeleteService": "DeleteServiceRequest",+ "DeleteTaskDefinitions": "DeleteTaskDefinitionsRequest",+ "DeleteTaskSet": "DeleteTaskSetRequest",+ "DeregisterContainerInstance": "DeregisterContainerInstanceRequest",+ "DeregisterTaskDefinition": "DeregisterTaskDefinitionRequest",+ "DescribeCapacityProviders": "DescribeCapacityProvidersRequest",+ "DescribeClusters": "DescribeClustersRequest",+ "DescribeContainerInstances": "DescribeContainerInstancesRequest",+ "DescribeDaemon": "DescribeDaemonRequest",+ "DescribeDaemonDeployments": "DescribeDaemonDeploymentsRequest",+ "DescribeDaemonRevisions": "DescribeDaemonRevisionsRequest",+ "DescribeDaemonTaskDefinition": "DescribeDaemonTaskDefinitionRequest",+ "DescribeExpressGatewayService": "DescribeExpressGatewayServiceRequest",+ "DescribeServiceDeployments": "DescribeServiceDeploymentsRequest",+ "DescribeServiceRevisions": "DescribeServiceRevisionsRequest",+ "DescribeServices": "DescribeServicesRequest",+ "DescribeTaskDefinition": "DescribeTaskDefinitionRequest",+ "DescribeTaskSets": "DescribeTaskSetsRequest",+ "DescribeTasks": "DescribeTasksRequest",+ "DiscoverPollEndpoint": "DiscoverPollEndpointRequest",+ "ExecuteCommand": "ExecuteCommandRequest",+ "GetTaskProtection": "GetTaskProtectionRequest",+ "ListAccountSettings": "ListAccountSettingsRequest",+ "ListAttributes": "ListAttributesRequest",+ "ListClusters": "ListClustersRequest",+ "ListContainerInstances": "ListContainerInstancesRequest",+ "ListDaemonDeployments": "ListDaemonDeploymentsRequest",+ "ListDaemonTaskDefinitions": "ListDaemonTaskDefinitionsRequest",+ "ListDaemons": "ListDaemonsRequest",+ "ListServiceDeployments": "ListServiceDeploymentsRequest",+ "ListServices": "ListServicesRequest",+ "ListServicesByNamespace": "ListServicesByNamespaceRequest",+ "ListTagsForResource": "ListTagsForResourceRequest",+ "ListTaskDefinitionFamilies": "ListTaskDefinitionFamiliesRequest",+ "ListTaskDefinitions": "ListTaskDefinitionsRequest",+ "ListTasks": "ListTasksRequest",+ "PutAccountSetting": "PutAccountSettingRequest",+ "PutAccountSettingDefault": "PutAccountSettingDefaultRequest",+ "PutAttributes": "PutAttributesRequest",+ "PutClusterCapacityProviders": "PutClusterCapacityProvidersRequest",+ "RegisterContainerInstance": "RegisterContainerInstanceRequest",+ "RegisterDaemonTaskDefinition": "RegisterDaemonTaskDefinitionRequest",+ "RegisterTaskDefinition": "RegisterTaskDefinitionRequest",+ "RunTask": "RunTaskRequest",+ "StartTask": "StartTaskRequest",+ "StopServiceDeployment": "StopServiceDeploymentRequest",+ "StopTask": "StopTaskRequest",+ "SubmitAttachmentStateChanges": "SubmitAttachmentStateChangesRequest",+ "SubmitContainerStateChange": "SubmitContainerStateChangeRequest",+ "SubmitTaskStateChange": "SubmitTaskStateChangeRequest",+ "TagResource": "TagResourceRequest",+ "UntagResource": "UntagResourceRequest",+ "UpdateCapacityProvider": "UpdateCapacityProviderRequest",+ "UpdateCluster": "UpdateClusterRequest",+ "UpdateClusterSettings": "UpdateClusterSettingsRequest",+ "UpdateContainerAgent": "UpdateContainerAgentRequest",+ "UpdateContainerInstancesState": "UpdateContainerInstancesStateRequest",+ "UpdateDaemon": "UpdateDaemonRequest",+ "UpdateExpressGatewayService": "UpdateExpressGatewayServiceRequest",+ "UpdateService": "UpdateServiceRequest",+ "UpdateServicePrimaryTaskSet": "UpdateServicePrimaryTaskSetRequest",+ "UpdateTaskProtection": "UpdateTaskProtectionRequest",+ "UpdateTaskSet": "UpdateTaskSetRequest"+ },+ "shapes": {+ "AcceleratorCountRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "AcceleratorManufacturer": {+ "type": "string"+ },+ "AcceleratorManufacturerSet": {+ "type": "list",+ "member": "AcceleratorManufacturer"+ },+ "AcceleratorName": {+ "type": "string"+ },+ "AcceleratorNameSet": {+ "type": "list",+ "member": "AcceleratorName"+ },+ "AcceleratorTotalMemoryMiBRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "AcceleratorType": {+ "type": "string"+ },+ "AcceleratorTypeSet": {+ "type": "list",+ "member": "AcceleratorType"+ },+ "AdvancedConfiguration": {+ "type": "structure",+ "members": {+ "alternateTargetGroupArn": "String",+ "productionListenerRule": "String",+ "testListenerRule": "String",+ "roleArn": "String"+ }+ },+ "AllowedInstanceType": {+ "type": "string"+ },+ "AllowedInstanceTypeSet": {+ "type": "list",+ "member": "AllowedInstanceType"+ },+ "ApplicationProtocol": {+ "type": "string"+ },+ "AssignPublicIp": {+ "type": "string"+ },+ "AttachmentStateChange": {+ "type": "structure",+ "members": {+ "attachmentArn": "String",+ "status": "String"+ }+ },+ "AttachmentStateChanges": {+ "type": "list",+ "member": "AttachmentStateChange"+ },+ "Attribute": {+ "type": "structure",+ "members": {+ "name": "String",+ "value": "String",+ "targetType": "TargetType",+ "targetId": "String"+ }+ },+ "Attributes": {+ "type": "list",+ "member": "Attribute"+ },+ "AutoRepairActionsStatus": {+ "type": "string"+ },+ "AutoRepairConfiguration": {+ "type": "structure",+ "members": {+ "actionsStatus": "AutoRepairActionsStatus"+ }+ },+ "AutoScalingGroupProvider": {+ "type": "structure",+ "members": {+ "autoScalingGroupArn": "String",+ "managedScaling": "ManagedScaling",+ "managedTerminationProtection": "ManagedTerminationProtection",+ "managedDraining": "ManagedDraining"+ }+ },+ "AutoScalingGroupProviderUpdate": {+ "type": "structure",+ "members": {+ "managedScaling": "ManagedScaling",+ "managedTerminationProtection": "ManagedTerminationProtection",+ "managedDraining": "ManagedDraining"+ }+ },+ "AvailabilityZoneRebalancing": {+ "type": "string"+ },+ "AwsVpcConfiguration": {+ "type": "structure",+ "members": {+ "subnets": "StringList",+ "securityGroups": "StringList",+ "assignPublicIp": "AssignPublicIp"+ }+ },+ "BareMetal": {+ "type": "string"+ },+ "BaselineEbsBandwidthMbpsRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "Boolean": {+ "type": "boolean"+ },+ "BoxedBoolean": {+ "type": "boolean"+ },+ "BoxedDouble": {+ "type": "double"+ },+ "BoxedInteger": {+ "type": "integer"+ },+ "BurstablePerformance": {+ "type": "string"+ },+ "CPUArchitecture": {+ "type": "string"+ },+ "CanaryConfiguration": {+ "type": "structure",+ "members": {+ "canaryPercent": "Double",+ "canaryBakeTimeInMinutes": "Integer"+ }+ },+ "CapacityOptionType": {+ "type": "string"+ },+ "CapacityProviderField": {+ "type": "string"+ },+ "CapacityProviderFieldList": {+ "type": "list",+ "member": "CapacityProviderField"+ },+ "CapacityProviderStrategy": {+ "type": "list",+ "member": "CapacityProviderStrategyItem"+ },+ "CapacityProviderStrategyItem": {+ "type": "structure",+ "members": {+ "capacityProvider": "String",+ "weight": "CapacityProviderStrategyItemWeight",+ "base": "CapacityProviderStrategyItemBase"+ }+ },+ "CapacityProviderStrategyItemBase": {+ "type": "integer"+ },+ "CapacityProviderStrategyItemWeight": {+ "type": "integer"+ },+ "CapacityReservationPreference": {+ "type": "string"+ },+ "CapacityReservationRequest": {+ "type": "structure",+ "members": {+ "reservationGroupArn": "String",+ "reservationPreference": "CapacityReservationPreference"+ }+ },+ "ClusterConfiguration": {+ "type": "structure",+ "members": {+ "executeCommandConfiguration": "ExecuteCommandConfiguration",+ "managedStorageConfiguration": "ManagedStorageConfiguration"+ }+ },+ "ClusterField": {+ "type": "string"+ },+ "ClusterFieldList": {+ "type": "list",+ "member": "ClusterField"+ },+ "ClusterServiceConnectDefaultsRequest": {+ "type": "structure",+ "members": {+ "namespace": "String"+ }+ },+ "ClusterSetting": {+ "type": "structure",+ "members": {+ "name": "ClusterSettingName",+ "value": "String"+ }+ },+ "ClusterSettingName": {+ "type": "string"+ },+ "ClusterSettings": {+ "type": "list",+ "member": "ClusterSetting"+ },+ "Compatibility": {+ "type": "string"+ },+ "CompatibilityList": {+ "type": "list",+ "member": "Compatibility"+ },+ "ContainerCondition": {+ "type": "string"+ },+ "ContainerDefinition": {+ "type": "structure",+ "members": {+ "name": "String",+ "image": "String",+ "repositoryCredentials": "RepositoryCredentials",+ "cpu": "Integer",+ "memory": "BoxedInteger",+ "memoryReservation": "BoxedInteger",+ "links": "StringList",+ "portMappings": "PortMappingList",+ "essential": "BoxedBoolean",+ "restartPolicy": "ContainerRestartPolicy",+ "entryPoint": "StringList",+ "command": "StringList",+ "environment": "EnvironmentVariables",+ "environmentFiles": "EnvironmentFiles",+ "mountPoints": "MountPointList",+ "volumesFrom": "VolumeFromList",+ "linuxParameters": "LinuxParameters",+ "secrets": "SecretList",+ "dependsOn": "ContainerDependencies",+ "startTimeout": "BoxedInteger",+ "stopTimeout": "BoxedInteger",+ "versionConsistency": "VersionConsistency",+ "hostname": "String",+ "user": "String",+ "workingDirectory": "String",+ "disableNetworking": "BoxedBoolean",+ "privileged": "BoxedBoolean",+ "readonlyRootFilesystem": "BoxedBoolean",+ "dnsServers": "StringList",+ "dnsSearchDomains": "StringList",+ "extraHosts": "HostEntryList",+ "dockerSecurityOptions": "StringList",+ "interactive": "BoxedBoolean",+ "pseudoTerminal": "BoxedBoolean",+ "dockerLabels": "DockerLabelsMap",+ "ulimits": "UlimitList",+ "logConfiguration": "LogConfiguration",+ "healthCheck": "HealthCheck",+ "systemControls": "SystemControls",+ "resourceRequirements": "ResourceRequirements",+ "firelensConfiguration": "FirelensConfiguration",+ "credentialSpecs": "StringList"+ }+ },+ "ContainerDefinitions": {+ "type": "list",+ "member": "ContainerDefinition"+ },+ "ContainerDependencies": {+ "type": "list",+ "member": "ContainerDependency"+ },+ "ContainerDependency": {+ "type": "structure",+ "members": {+ "containerName": "String",+ "condition": "ContainerCondition"+ }+ },+ "ContainerInstanceField": {+ "type": "string"+ },+ "ContainerInstanceFieldList": {+ "type": "list",+ "member": "ContainerInstanceField"+ },+ "ContainerInstanceStatus": {+ "type": "string"+ },+ "ContainerOverride": {+ "type": "structure",+ "members": {+ "name": "String",+ "command": "StringList",+ "environment": "EnvironmentVariables",+ "environmentFiles": "EnvironmentFiles",+ "cpu": "BoxedInteger",+ "memory": "BoxedInteger",+ "memoryReservation": "BoxedInteger",+ "resourceRequirements": "ResourceRequirements"+ }+ },+ "ContainerOverrides": {+ "type": "list",+ "member": "ContainerOverride"+ },+ "ContainerRestartPolicy": {+ "type": "structure",+ "members": {+ "enabled": "BoxedBoolean",+ "ignoredExitCodes": "IntegerList",+ "restartAttemptPeriod": "BoxedInteger"+ }+ },+ "ContainerStateChange": {+ "type": "structure",+ "members": {+ "containerName": "String",+ "imageDigest": "String",+ "runtimeId": "String",+ "exitCode": "BoxedInteger",+ "networkBindings": "NetworkBindings",+ "reason": "String",+ "status": "String"+ }+ },+ "ContainerStateChanges": {+ "type": "list",+ "member": "ContainerStateChange"+ },+ "ContinueServiceDeploymentRequest": {+ "type": "structure",+ "members": {+ "serviceDeploymentArn": "String",+ "hookId": "String",+ "action": "DeploymentLifecycleHookAction"+ }+ },+ "CpuManufacturer": {+ "type": "string"+ },+ "CpuManufacturerSet": {+ "type": "list",+ "member": "CpuManufacturer"+ },+ "CreateCapacityProviderRequest": {+ "type": "structure",+ "members": {+ "name": "String",+ "cluster": "String",+ "autoScalingGroupProvider": "AutoScalingGroupProvider",+ "managedInstancesProvider": "CreateManagedInstancesProviderConfiguration",+ "tags": "Tags"+ }+ },+ "CreateClusterRequest": {+ "type": "structure",+ "members": {+ "clusterName": "String",+ "tags": "Tags",+ "settings": "ClusterSettings",+ "configuration": "ClusterConfiguration",+ "capacityProviders": "StringList",+ "defaultCapacityProviderStrategy": "CapacityProviderStrategy",+ "serviceConnectDefaults": "ClusterServiceConnectDefaultsRequest"+ }+ },+ "CreateDaemonRequest": {+ "type": "structure",+ "members": {+ "daemonName": "String",+ "clusterArn": "String",+ "daemonTaskDefinitionArn": "String",+ "capacityProviderArns": "StringList",+ "deploymentConfiguration": "DaemonDeploymentConfiguration",+ "tags": "Tags",+ "propagateTags": "DaemonPropagateTags",+ "enableECSManagedTags": "Boolean",+ "enableExecuteCommand": "Boolean",+ "clientToken": "String",+ "critical": "BoxedBoolean"+ }+ },+ "CreateExpressGatewayServiceRequest": {+ "type": "structure",+ "members": {+ "executionRoleArn": "String",+ "infrastructureRoleArn": "String",+ "serviceName": "String",+ "cluster": "String",+ "healthCheckPath": "String",+ "primaryContainer": "ExpressGatewayContainer",+ "taskRoleArn": "String",+ "networkConfiguration": "ExpressGatewayServiceNetworkConfiguration",+ "cpu": "String",+ "memory": "String",+ "cpuArchitecture": "ExpressCpuArchitecture",+ "scalingTarget": "ExpressGatewayScalingTarget",+ "tags": "Tags",+ "taskDefinitionArn": "String"+ }+ },+ "CreateManagedInstancesProviderConfiguration": {+ "type": "structure",+ "members": {+ "infrastructureRoleArn": "String",+ "instanceLaunchTemplate": "InstanceLaunchTemplate",+ "propagateTags": "PropagateMITags",+ "infrastructureOptimization": "InfrastructureOptimization",+ "autoRepairConfiguration": "AutoRepairConfiguration"+ }+ },+ "CreateServiceRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "serviceName": "String",+ "taskDefinition": "String",+ "availabilityZoneRebalancing": "AvailabilityZoneRebalancing",+ "loadBalancers": "LoadBalancers",+ "serviceRegistries": "ServiceRegistries",+ "desiredCount": "BoxedInteger",+ "clientToken": "String",+ "launchType": "LaunchType",+ "capacityProviderStrategy": "CapacityProviderStrategy",+ "platformVersion": "String",+ "role": "String",+ "deploymentConfiguration": "DeploymentConfiguration",+ "placementConstraints": "PlacementConstraints",+ "placementStrategy": "PlacementStrategies",+ "networkConfiguration": "NetworkConfiguration",+ "healthCheckGracePeriodSeconds": "BoxedInteger",+ "schedulingStrategy": "SchedulingStrategy",+ "deploymentController": "DeploymentController",+ "tags": "Tags",+ "enableECSManagedTags": "Boolean",+ "propagateTags": "PropagateTags",+ "enableExecuteCommand": "Boolean",+ "serviceConnectConfiguration": "ServiceConnectConfiguration",+ "volumeConfigurations": "ServiceVolumeConfigurations",+ "vpcLatticeConfigurations": "VpcLatticeConfigurations",+ "monitoring": "MonitoringConfiguration"+ }+ },+ "CreateTaskSetRequest": {+ "type": "structure",+ "members": {+ "service": "String",+ "cluster": "String",+ "externalId": "String",+ "taskDefinition": "String",+ "networkConfiguration": "NetworkConfiguration",+ "loadBalancers": "LoadBalancers",+ "serviceRegistries": "ServiceRegistries",+ "launchType": "LaunchType",+ "capacityProviderStrategy": "CapacityProviderStrategy",+ "platformVersion": "String",+ "scale": "Scale",+ "clientToken": "String",+ "tags": "Tags"+ }+ },+ "CreatedAt": {+ "type": "structure",+ "members": {+ "before": "Timestamp",+ "after": "Timestamp"+ }+ },+ "DaemonAlarmConfiguration": {+ "type": "structure",+ "members": {+ "alarmNames": "StringList",+ "enable": "Boolean"+ }+ },+ "DaemonContainerDefinition": {+ "type": "structure",+ "members": {+ "name": "String",+ "image": "String",+ "memory": "BoxedInteger",+ "memoryReservation": "BoxedInteger",+ "repositoryCredentials": "RepositoryCredentials",+ "healthCheck": "HealthCheck",+ "cpu": "Integer",+ "essential": "BoxedBoolean",+ "entryPoint": "StringList",+ "command": "StringList",+ "workingDirectory": "String",+ "environmentFiles": "EnvironmentFiles",+ "environment": "EnvironmentVariables",+ "secrets": "SecretList",+ "readonlyRootFilesystem": "BoxedBoolean",+ "mountPoints": "MountPointList",+ "logConfiguration": "LogConfiguration",+ "firelensConfiguration": "FirelensConfiguration",+ "privileged": "BoxedBoolean",+ "user": "String",+ "ulimits": "UlimitList",+ "linuxParameters": "DaemonLinuxParameters",+ "dependsOn": "ContainerDependencies",+ "startTimeout": "BoxedInteger",+ "stopTimeout": "BoxedInteger",+ "systemControls": "SystemControls",+ "interactive": "BoxedBoolean",+ "pseudoTerminal": "BoxedBoolean",+ "restartPolicy": "ContainerRestartPolicy"+ }+ },+ "DaemonContainerDefinitionList": {+ "type": "list",+ "member": "DaemonContainerDefinition"+ },+ "DaemonDeploymentConfiguration": {+ "type": "structure",+ "members": {+ "drainPercent": "DaemonDrainPercent",+ "alarms": "DaemonAlarmConfiguration",+ "bakeTimeInMinutes": "Integer"+ }+ },+ "DaemonDeploymentStatus": {+ "type": "string"+ },+ "DaemonDeploymentStatusList": {+ "type": "list",+ "member": "DaemonDeploymentStatus"+ },+ "DaemonDrainPercent": {+ "type": "double"+ },+ "DaemonIpcMode": {+ "type": "string"+ },+ "DaemonLinuxParameters": {+ "type": "structure",+ "members": {+ "capabilities": "KernelCapabilities",+ "devices": "DevicesList",+ "initProcessEnabled": "BoxedBoolean",+ "tmpfs": "TmpfsList"+ }+ },+ "DaemonPidMode": {+ "type": "string"+ },+ "DaemonPropagateTags": {+ "type": "string"+ },+ "DaemonTaskDefinitionRevisionFilter": {+ "type": "string"+ },+ "DaemonTaskDefinitionStatusFilter": {+ "type": "string"+ },+ "DaemonVolume": {+ "type": "structure",+ "members": {+ "name": "String",+ "host": "HostVolumeProperties"+ }+ },+ "DaemonVolumeList": {+ "type": "list",+ "member": "DaemonVolume"+ },+ "DeleteAccountSettingRequest": {+ "type": "structure",+ "members": {+ "name": "SettingName",+ "principalArn": "String"+ }+ },+ "DeleteAttributesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "attributes": "Attributes"+ }+ },+ "DeleteCapacityProviderRequest": {+ "type": "structure",+ "members": {+ "capacityProvider": "String",+ "cluster": "String"+ }+ },+ "DeleteClusterRequest": {+ "type": "structure",+ "members": {+ "cluster": "String"+ }+ },+ "DeleteDaemonRequest": {+ "type": "structure",+ "members": {+ "daemonArn": "String"+ }+ },+ "DeleteDaemonTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "daemonTaskDefinition": "String"+ }+ },+ "DeleteExpressGatewayServiceRequest": {+ "type": "structure",+ "members": {+ "serviceArn": "String"+ }+ },+ "DeleteServiceRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "force": "BoxedBoolean"+ }+ },+ "DeleteTaskDefinitionsRequest": {+ "type": "structure",+ "members": {+ "taskDefinitions": "StringList"+ }+ },+ "DeleteTaskSetRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "taskSet": "String",+ "force": "BoxedBoolean"+ }+ },+ "DeploymentAlarms": {+ "type": "structure",+ "members": {+ "alarmNames": "StringList",+ "rollback": "Boolean",+ "enable": "Boolean"+ }+ },+ "DeploymentCircuitBreaker": {+ "type": "structure",+ "members": {+ "enable": "Boolean",+ "rollback": "Boolean",+ "resetOnHealthyTask": "BoxedBoolean",+ "thresholdConfiguration": "ThresholdConfiguration"+ }+ },+ "DeploymentConfiguration": {+ "type": "structure",+ "members": {+ "deploymentCircuitBreaker": "DeploymentCircuitBreaker",+ "maximumPercent": "BoxedInteger",+ "minimumHealthyPercent": "BoxedInteger",+ "alarms": "DeploymentAlarms",+ "strategy": "DeploymentStrategy",+ "bakeTimeInMinutes": "BoxedInteger",+ "lifecycleHooks": "DeploymentLifecycleHookList",+ "linearConfiguration": "LinearConfiguration",+ "canaryConfiguration": "CanaryConfiguration",+ "earlySuccessCriteria": "DeploymentEarlySuccessCriteria"+ }+ },+ "DeploymentController": {+ "type": "structure",+ "members": {+ "type": "DeploymentControllerType"+ }+ },+ "DeploymentControllerType": {+ "type": "string"+ },+ "DeploymentEarlySuccessCriteria": {+ "type": "structure",+ "members": {+ "enable": "Boolean",+ "healthyPercent": "HealthyPercentInteger",+ "sourceServiceRevisionCleanup": "ServiceRevisionCleanup"+ }+ },+ "DeploymentLifecycleHook": {+ "type": "structure",+ "members": {+ "targetType": "DeploymentLifecycleHookTargetType",+ "hookTargetArn": "String",+ "roleArn": "IAMRoleArn",+ "lifecycleStages": "DeploymentLifecycleHookStageList",+ "hookDetails": "HookDetails",+ "timeoutConfiguration": "DeploymentLifecycleHookTimeoutConfiguration"+ }+ },+ "DeploymentLifecycleHookAction": {+ "type": "string"+ },+ "DeploymentLifecycleHookDuration": {+ "type": "integer"+ },+ "DeploymentLifecycleHookList": {+ "type": "list",+ "member": "DeploymentLifecycleHook"+ },+ "DeploymentLifecycleHookStage": {+ "type": "string"+ },+ "DeploymentLifecycleHookStageList": {+ "type": "list",+ "member": "DeploymentLifecycleHookStage"+ },+ "DeploymentLifecycleHookTargetType": {+ "type": "string"+ },+ "DeploymentLifecycleHookTimeoutConfiguration": {+ "type": "structure",+ "members": {+ "timeoutInMinutes": "DeploymentLifecycleHookDuration",+ "action": "DeploymentLifecycleHookAction"+ }+ },+ "DeploymentStrategy": {+ "type": "string"+ },+ "DeregisterContainerInstanceRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstance": "String",+ "force": "BoxedBoolean"+ }+ },+ "DeregisterTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "taskDefinition": "String"+ }+ },+ "DescribeCapacityProvidersRequest": {+ "type": "structure",+ "members": {+ "capacityProviders": "StringList",+ "cluster": "String",+ "include": "CapacityProviderFieldList",+ "maxResults": "BoxedInteger",+ "nextToken": "String"+ }+ },+ "DescribeClustersRequest": {+ "type": "structure",+ "members": {+ "clusters": "StringList",+ "include": "ClusterFieldList"+ }+ },+ "DescribeContainerInstancesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstances": "StringList",+ "include": "ContainerInstanceFieldList"+ }+ },+ "DescribeDaemonDeploymentsRequest": {+ "type": "structure",+ "members": {+ "daemonDeploymentArns": "StringList"+ }+ },+ "DescribeDaemonRequest": {+ "type": "structure",+ "members": {+ "daemonArn": "String"+ }+ },+ "DescribeDaemonRevisionsRequest": {+ "type": "structure",+ "members": {+ "daemonRevisionArns": "StringList"+ }+ },+ "DescribeDaemonTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "daemonTaskDefinition": "String"+ }+ },+ "DescribeExpressGatewayServiceRequest": {+ "type": "structure",+ "members": {+ "serviceArn": "String",+ "include": "ExpressGatewayServiceIncludeList"+ }+ },+ "DescribeServiceDeploymentsRequest": {+ "type": "structure",+ "members": {+ "serviceDeploymentArns": "StringList"+ }+ },+ "DescribeServiceRevisionsRequest": {+ "type": "structure",+ "members": {+ "serviceRevisionArns": "StringList"+ }+ },+ "DescribeServicesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "services": "StringList",+ "include": "ServiceFieldList"+ }+ },+ "DescribeTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "taskDefinition": "String",+ "include": "TaskDefinitionFieldList"+ }+ },+ "DescribeTaskSetsRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "taskSets": "StringList",+ "include": "TaskSetFieldList"+ }+ },+ "DescribeTasksRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "tasks": "StringList",+ "include": "TaskFieldList"+ }+ },+ "DesiredStatus": {+ "type": "string"+ },+ "Device": {+ "type": "structure",+ "members": {+ "hostPath": "String",+ "containerPath": "String",+ "permissions": "DeviceCgroupPermissions"+ }+ },+ "DeviceCgroupPermission": {+ "type": "string"+ },+ "DeviceCgroupPermissions": {+ "type": "list",+ "member": "DeviceCgroupPermission"+ },+ "DevicesList": {+ "type": "list",+ "member": "Device"+ },+ "DiscoverPollEndpointRequest": {+ "type": "structure",+ "members": {+ "containerInstance": "String",+ "cluster": "String"+ }+ },+ "DockerLabelsMap": {+ "type": "map",+ "value": "String"+ },+ "DockerVolumeConfiguration": {+ "type": "structure",+ "members": {+ "scope": "Scope",+ "autoprovision": "BoxedBoolean",+ "driver": "String",+ "driverOpts": "StringMap",+ "labels": "StringMap"+ }+ },+ "Double": {+ "type": "double"+ },+ "Duration": {+ "type": "integer"+ },+ "EBSKMSKeyId": {+ "type": "string"+ },+ "EBSResourceType": {+ "type": "string"+ },+ "EBSSnapshotId": {+ "type": "string"+ },+ "EBSTagSpecification": {+ "type": "structure",+ "members": {+ "resourceType": "EBSResourceType",+ "tags": "Tags",+ "propagateTags": "PropagateTags"+ }+ },+ "EBSTagSpecifications": {+ "type": "list",+ "member": "EBSTagSpecification"+ },+ "EBSVolumeType": {+ "type": "string"+ },+ "ECSVolumeName": {+ "type": "string"+ },+ "EFSAuthorizationConfig": {+ "type": "structure",+ "members": {+ "accessPointId": "String",+ "iam": "EFSAuthorizationConfigIAM"+ }+ },+ "EFSAuthorizationConfigIAM": {+ "type": "string"+ },+ "EFSTransitEncryption": {+ "type": "string"+ },+ "EFSVolumeConfiguration": {+ "type": "structure",+ "members": {+ "fileSystemId": "String",+ "rootDirectory": "String",+ "transitEncryption": "EFSTransitEncryption",+ "transitEncryptionPort": "BoxedInteger",+ "authorizationConfig": "EFSAuthorizationConfig"+ }+ },+ "EnvironmentFile": {+ "type": "structure",+ "members": {+ "value": "String",+ "type": "EnvironmentFileType"+ }+ },+ "EnvironmentFileType": {+ "type": "string"+ },+ "EnvironmentFiles": {+ "type": "list",+ "member": "EnvironmentFile"+ },+ "EnvironmentVariables": {+ "type": "list",+ "member": "KeyValuePair"+ },+ "EphemeralStorage": {+ "type": "structure",+ "members": {+ "sizeInGiB": "Integer"+ }+ },+ "ExcludedInstanceType": {+ "type": "string"+ },+ "ExcludedInstanceTypeSet": {+ "type": "list",+ "member": "ExcludedInstanceType"+ },+ "ExecuteCommandConfiguration": {+ "type": "structure",+ "members": {+ "kmsKeyId": "String",+ "logging": "ExecuteCommandLogging",+ "logConfiguration": "ExecuteCommandLogConfiguration"+ }+ },+ "ExecuteCommandLogConfiguration": {+ "type": "structure",+ "members": {+ "cloudWatchLogGroupName": "String",+ "cloudWatchEncryptionEnabled": "Boolean",+ "s3BucketName": "String",+ "s3EncryptionEnabled": "Boolean",+ "s3KeyPrefix": "String"+ }+ },+ "ExecuteCommandLogging": {+ "type": "string"+ },+ "ExecuteCommandRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "container": "String",+ "command": "String",+ "interactive": "Boolean",+ "task": "String"+ }+ },+ "ExpressCpuArchitecture": {+ "type": "string"+ },+ "ExpressGatewayContainer": {+ "type": "structure",+ "members": {+ "image": "String",+ "containerPort": "BoxedInteger",+ "awsLogsConfiguration": "ExpressGatewayServiceAwsLogsConfiguration",+ "repositoryCredentials": "ExpressGatewayRepositoryCredentials",+ "command": "StringList",+ "environment": "EnvironmentVariables",+ "secrets": "SecretList"+ }+ },+ "ExpressGatewayRepositoryCredentials": {+ "type": "structure",+ "members": {+ "credentialsParameter": "String"+ }+ },+ "ExpressGatewayScalingTarget": {+ "type": "structure",+ "members": {+ "minTaskCount": "BoxedInteger",+ "maxTaskCount": "BoxedInteger",+ "autoScalingMetric": "ExpressGatewayServiceScalingMetric",+ "autoScalingTargetValue": "BoxedInteger"+ }+ },+ "ExpressGatewayServiceAwsLogsConfiguration": {+ "type": "structure",+ "members": {+ "logGroup": "String",+ "logStreamPrefix": "String"+ }+ },+ "ExpressGatewayServiceInclude": {+ "type": "string"+ },+ "ExpressGatewayServiceIncludeList": {+ "type": "list",+ "member": "ExpressGatewayServiceInclude"+ },+ "ExpressGatewayServiceNetworkConfiguration": {+ "type": "structure",+ "members": {+ "securityGroups": "StringList",+ "subnets": "StringList"+ }+ },+ "ExpressGatewayServiceScalingMetric": {+ "type": "string"+ },+ "FSxWindowsFileServerAuthorizationConfig": {+ "type": "structure",+ "members": {+ "credentialsParameter": "String",+ "domain": "String"+ }+ },+ "FSxWindowsFileServerVolumeConfiguration": {+ "type": "structure",+ "members": {+ "fileSystemId": "String",+ "rootDirectory": "String",+ "authorizationConfig": "FSxWindowsFileServerAuthorizationConfig"+ }+ },+ "FirelensConfiguration": {+ "type": "structure",+ "members": {+ "type": "FirelensConfigurationType",+ "options": "FirelensConfigurationOptionsMap"+ }+ },+ "FirelensConfigurationOptionsMap": {+ "type": "map",+ "value": "String"+ },+ "FirelensConfigurationType": {+ "type": "string"+ },+ "GetTaskProtectionRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "tasks": "StringList"+ }+ },+ "HealthCheck": {+ "type": "structure",+ "members": {+ "command": "StringList",+ "interval": "BoxedInteger",+ "timeout": "BoxedInteger",+ "retries": "BoxedInteger",+ "startPeriod": "BoxedInteger"+ }+ },+ "HealthyPercentInteger": {+ "type": "integer"+ },+ "HookDetails": {+ "type": "structure",+ "members": {}+ },+ "HostEntry": {+ "type": "structure",+ "members": {+ "hostname": "String",+ "ipAddress": "String"+ }+ },+ "HostEntryList": {+ "type": "list",+ "member": "HostEntry"+ },+ "HostVolumeProperties": {+ "type": "structure",+ "members": {+ "sourcePath": "String"+ }+ },+ "IAMRoleArn": {+ "type": "string"+ },+ "InferenceAccelerator": {+ "type": "structure",+ "members": {+ "deviceName": "String",+ "deviceType": "String"+ }+ },+ "InferenceAcceleratorOverride": {+ "type": "structure",+ "members": {+ "deviceName": "String",+ "deviceType": "String"+ }+ },+ "InferenceAcceleratorOverrides": {+ "type": "list",+ "member": "InferenceAcceleratorOverride"+ },+ "InferenceAccelerators": {+ "type": "list",+ "member": "InferenceAccelerator"+ },+ "InfrastructureOptimization": {+ "type": "structure",+ "members": {+ "scaleInAfter": "BoxedInteger"+ }+ },+ "InstanceGeneration": {+ "type": "string"+ },+ "InstanceGenerationSet": {+ "type": "list",+ "member": "InstanceGeneration"+ },+ "InstanceLaunchTemplate": {+ "type": "structure",+ "members": {+ "ec2InstanceProfileArn": "String",+ "networkConfiguration": "ManagedInstancesNetworkConfiguration",+ "storageConfiguration": "ManagedInstancesStorageConfiguration",+ "localStorageConfiguration": "ManagedInstancesLocalStorageConfiguration",+ "monitoring": "ManagedInstancesMonitoringOptions",+ "capacityOptionType": "CapacityOptionType",+ "instanceMetadataTagsPropagation": "BoxedBoolean",+ "instanceRequirements": "InstanceRequirementsRequest",+ "fipsEnabled": "BoxedBoolean",+ "capacityReservations": "CapacityReservationRequest"+ }+ },+ "InstanceLaunchTemplateUpdate": {+ "type": "structure",+ "members": {+ "ec2InstanceProfileArn": "String",+ "networkConfiguration": "ManagedInstancesNetworkConfiguration",+ "storageConfiguration": "ManagedInstancesStorageConfiguration",+ "instanceMetadataTagsPropagation": "BoxedBoolean",+ "localStorageConfiguration": "ManagedInstancesLocalStorageConfiguration",+ "monitoring": "ManagedInstancesMonitoringOptions",+ "instanceRequirements": "InstanceRequirementsRequest",+ "capacityReservations": "CapacityReservationRequest"+ }+ },+ "InstanceRequirementsRequest": {+ "type": "structure",+ "members": {+ "vCpuCount": "VCpuCountRangeRequest",+ "memoryMiB": "MemoryMiBRequest",+ "cpuManufacturers": "CpuManufacturerSet",+ "memoryGiBPerVCpu": "MemoryGiBPerVCpuRequest",+ "excludedInstanceTypes": "ExcludedInstanceTypeSet",+ "instanceGenerations": "InstanceGenerationSet",+ "spotMaxPricePercentageOverLowestPrice": "BoxedInteger",+ "onDemandMaxPricePercentageOverLowestPrice": "BoxedInteger",+ "bareMetal": "BareMetal",+ "burstablePerformance": "BurstablePerformance",+ "requireHibernateSupport": "BoxedBoolean",+ "networkInterfaceCount": "NetworkInterfaceCountRequest",+ "localStorage": "LocalStorage",+ "localStorageTypes": "LocalStorageTypeSet",+ "totalLocalStorageGB": "TotalLocalStorageGBRequest",+ "baselineEbsBandwidthMbps": "BaselineEbsBandwidthMbpsRequest",+ "acceleratorTypes": "AcceleratorTypeSet",+ "acceleratorCount": "AcceleratorCountRequest",+ "acceleratorManufacturers": "AcceleratorManufacturerSet",+ "acceleratorNames": "AcceleratorNameSet",+ "acceleratorTotalMemoryMiB": "AcceleratorTotalMemoryMiBRequest",+ "networkBandwidthGbps": "NetworkBandwidthGbpsRequest",+ "allowedInstanceTypes": "AllowedInstanceTypeSet",+ "maxSpotPriceAsPercentageOfOptimalOnDemandPrice": "BoxedInteger"+ }+ },+ "Integer": {+ "type": "integer"+ },+ "IntegerList": {+ "type": "list",+ "member": "BoxedInteger"+ },+ "IpcMode": {+ "type": "string"+ },+ "KernelCapabilities": {+ "type": "structure",+ "members": {+ "add": "StringList",+ "drop": "StringList"+ }+ },+ "KeyValuePair": {+ "type": "structure",+ "members": {+ "name": "String",+ "value": "String"+ }+ },+ "LaunchType": {+ "type": "string"+ },+ "LinearConfiguration": {+ "type": "structure",+ "members": {+ "stepPercent": "Double",+ "stepBakeTimeInMinutes": "Integer"+ }+ },+ "LinuxParameters": {+ "type": "structure",+ "members": {+ "capabilities": "KernelCapabilities",+ "devices": "DevicesList",+ "initProcessEnabled": "BoxedBoolean",+ "sharedMemorySize": "BoxedInteger",+ "tmpfs": "TmpfsList",+ "maxSwap": "BoxedInteger",+ "swappiness": "BoxedInteger"+ }+ },+ "ListAccountSettingsRequest": {+ "type": "structure",+ "members": {+ "name": "SettingName",+ "value": "String",+ "principalArn": "String",+ "effectiveSettings": "Boolean",+ "nextToken": "String",+ "maxResults": "Integer"+ }+ },+ "ListAttributesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "targetType": "TargetType",+ "attributeName": "String",+ "attributeValue": "String",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListClustersRequest": {+ "type": "structure",+ "members": {+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListContainerInstancesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "filter": "String",+ "nextToken": "String",+ "maxResults": "BoxedInteger",+ "status": "ContainerInstanceStatus"+ }+ },+ "ListDaemonDeploymentsRequest": {+ "type": "structure",+ "members": {+ "daemonArn": "String",+ "status": "DaemonDeploymentStatusList",+ "createdAt": "CreatedAt",+ "maxResults": "BoxedInteger",+ "nextToken": "String"+ }+ },+ "ListDaemonTaskDefinitionsRequest": {+ "type": "structure",+ "members": {+ "familyPrefix": "String",+ "family": "String",+ "revision": "DaemonTaskDefinitionRevisionFilter",+ "status": "DaemonTaskDefinitionStatusFilter",+ "sort": "SortOrder",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListDaemonsRequest": {+ "type": "structure",+ "members": {+ "clusterArn": "String",+ "capacityProviderArns": "StringList",+ "maxResults": "BoxedInteger",+ "nextToken": "String"+ }+ },+ "ListServiceDeploymentsRequest": {+ "type": "structure",+ "members": {+ "service": "String",+ "cluster": "String",+ "status": "ServiceDeploymentStatusList",+ "createdAt": "CreatedAt",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListServicesByNamespaceRequest": {+ "type": "structure",+ "members": {+ "namespace": "String",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListServicesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "nextToken": "String",+ "maxResults": "BoxedInteger",+ "launchType": "LaunchType",+ "schedulingStrategy": "SchedulingStrategy",+ "resourceManagementType": "ResourceManagementType"+ }+ },+ "ListTagsForResourceRequest": {+ "type": "structure",+ "members": {+ "resourceArn": "String"+ }+ },+ "ListTaskDefinitionFamiliesRequest": {+ "type": "structure",+ "members": {+ "familyPrefix": "String",+ "status": "TaskDefinitionFamilyStatus",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListTaskDefinitionsRequest": {+ "type": "structure",+ "members": {+ "familyPrefix": "String",+ "status": "TaskDefinitionStatus",+ "sort": "SortOrder",+ "nextToken": "String",+ "maxResults": "BoxedInteger"+ }+ },+ "ListTasksRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstance": "String",+ "family": "String",+ "nextToken": "String",+ "maxResults": "BoxedInteger",+ "startedBy": "String",+ "serviceName": "String",+ "desiredStatus": "DesiredStatus",+ "launchType": "LaunchType",+ "daemonName": "String"+ }+ },+ "LoadBalancer": {+ "type": "structure",+ "members": {+ "targetGroupArn": "String",+ "loadBalancerName": "String",+ "containerName": "String",+ "containerPort": "BoxedInteger",+ "advancedConfiguration": "AdvancedConfiguration"+ }+ },+ "LoadBalancers": {+ "type": "list",+ "member": "LoadBalancer"+ },+ "LocalStorage": {+ "type": "string"+ },+ "LocalStorageType": {+ "type": "string"+ },+ "LocalStorageTypeSet": {+ "type": "list",+ "member": "LocalStorageType"+ },+ "LogConfiguration": {+ "type": "structure",+ "members": {+ "logDriver": "LogDriver",+ "options": "LogConfigurationOptionsMap",+ "secretOptions": "SecretList"+ }+ },+ "LogConfigurationOptionsMap": {+ "type": "map",+ "value": "String"+ },+ "LogDriver": {+ "type": "string"+ },+ "Long": {+ "type": "long"+ },+ "ManagedAgentName": {+ "type": "string"+ },+ "ManagedAgentStateChange": {+ "type": "structure",+ "members": {+ "containerName": "String",+ "managedAgentName": "ManagedAgentName",+ "status": "String",+ "reason": "String"+ }+ },+ "ManagedAgentStateChanges": {+ "type": "list",+ "member": "ManagedAgentStateChange"+ },+ "ManagedDraining": {+ "type": "string"+ },+ "ManagedInstancesLocalStorageConfiguration": {+ "type": "structure",+ "members": {+ "useLocalStorage": "Boolean"+ }+ },+ "ManagedInstancesMonitoringOptions": {+ "type": "string"+ },+ "ManagedInstancesNetworkConfiguration": {+ "type": "structure",+ "members": {+ "subnets": "StringList",+ "securityGroups": "StringList"+ }+ },+ "ManagedInstancesStorageConfiguration": {+ "type": "structure",+ "members": {+ "storageSizeGiB": "TaskVolumeStorageGiB"+ }+ },+ "ManagedScaling": {+ "type": "structure",+ "members": {+ "status": "ManagedScalingStatus",+ "targetCapacity": "ManagedScalingTargetCapacity",+ "minimumScalingStepSize": "ManagedScalingStepSize",+ "maximumScalingStepSize": "ManagedScalingStepSize",+ "instanceWarmupPeriod": "ManagedScalingInstanceWarmupPeriod"+ }+ },+ "ManagedScalingInstanceWarmupPeriod": {+ "type": "integer"+ },+ "ManagedScalingStatus": {+ "type": "string"+ },+ "ManagedScalingStepSize": {+ "type": "integer"+ },+ "ManagedScalingTargetCapacity": {+ "type": "integer"+ },+ "ManagedStorageConfiguration": {+ "type": "structure",+ "members": {+ "kmsKeyId": "String",+ "fargateEphemeralStorageKmsKeyId": "String"+ }+ },+ "ManagedTerminationProtection": {+ "type": "string"+ },+ "MemoryGiBPerVCpuRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedDouble",+ "max": "BoxedDouble"+ }+ },+ "MemoryMiBRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "MetricConfiguration": {+ "type": "structure",+ "members": {+ "metricNames": "MetricNamesList",+ "resolutionSeconds": "MetricResolutionSeconds"+ }+ },+ "MetricConfigurationList": {+ "type": "list",+ "member": "MetricConfiguration"+ },+ "MetricName": {+ "type": "string"+ },+ "MetricNamesList": {+ "type": "list",+ "member": "MetricName"+ },+ "MetricResolutionSeconds": {+ "type": "integer"+ },+ "MonitoringConfiguration": {+ "type": "structure",+ "members": {+ "metricConfigurations": "MetricConfigurationList"+ }+ },+ "MountPoint": {+ "type": "structure",+ "members": {+ "sourceVolume": "String",+ "containerPath": "String",+ "readOnly": "BoxedBoolean"+ }+ },+ "MountPointList": {+ "type": "list",+ "member": "MountPoint"+ },+ "NetworkBandwidthGbpsRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedDouble",+ "max": "BoxedDouble"+ }+ },+ "NetworkBinding": {+ "type": "structure",+ "members": {+ "bindIP": "String",+ "containerPort": "BoxedInteger",+ "hostPort": "BoxedInteger",+ "protocol": "TransportProtocol",+ "containerPortRange": "String",+ "hostPortRange": "String"+ }+ },+ "NetworkBindings": {+ "type": "list",+ "member": "NetworkBinding"+ },+ "NetworkConfiguration": {+ "type": "structure",+ "members": {+ "awsvpcConfiguration": "AwsVpcConfiguration"+ }+ },+ "NetworkInterfaceCountRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "NetworkMode": {+ "type": "string"+ },+ "OSFamily": {+ "type": "string"+ },+ "PidMode": {+ "type": "string"+ },+ "PlacementConstraint": {+ "type": "structure",+ "members": {+ "type": "PlacementConstraintType",+ "expression": "String"+ }+ },+ "PlacementConstraintType": {+ "type": "string"+ },+ "PlacementConstraints": {+ "type": "list",+ "member": "PlacementConstraint"+ },+ "PlacementStrategies": {+ "type": "list",+ "member": "PlacementStrategy"+ },+ "PlacementStrategy": {+ "type": "structure",+ "members": {+ "type": "PlacementStrategyType",+ "field": "String"+ }+ },+ "PlacementStrategyType": {+ "type": "string"+ },+ "PlatformDevice": {+ "type": "structure",+ "members": {+ "id": "String",+ "type": "PlatformDeviceType"+ }+ },+ "PlatformDeviceType": {+ "type": "string"+ },+ "PlatformDevices": {+ "type": "list",+ "member": "PlatformDevice"+ },+ "PortMapping": {+ "type": "structure",+ "members": {+ "containerPort": "BoxedInteger",+ "hostPort": "BoxedInteger",+ "protocol": "TransportProtocol",+ "name": "String",+ "appProtocol": "ApplicationProtocol",+ "containerPortRange": "String"+ }+ },+ "PortMappingList": {+ "type": "list",+ "member": "PortMapping"+ },+ "PortNumber": {+ "type": "integer"+ },+ "PropagateMITags": {+ "type": "string"+ },+ "PropagateTags": {+ "type": "string"+ },+ "ProxyConfiguration": {+ "type": "structure",+ "members": {+ "type": "ProxyConfigurationType",+ "containerName": "String",+ "properties": "ProxyConfigurationProperties"+ }+ },+ "ProxyConfigurationProperties": {+ "type": "list",+ "member": "KeyValuePair"+ },+ "ProxyConfigurationType": {+ "type": "string"+ },+ "PutAccountSettingDefaultRequest": {+ "type": "structure",+ "members": {+ "name": "SettingName",+ "value": "String"+ }+ },+ "PutAccountSettingRequest": {+ "type": "structure",+ "members": {+ "name": "SettingName",+ "value": "String",+ "principalArn": "String"+ }+ },+ "PutAttributesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "attributes": "Attributes"+ }+ },+ "PutClusterCapacityProvidersRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "capacityProviders": "StringList",+ "defaultCapacityProviderStrategy": "CapacityProviderStrategy"+ }+ },+ "RegisterContainerInstanceRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "instanceIdentityDocument": "String",+ "instanceIdentityDocumentSignature": "String",+ "totalResources": "Resources",+ "versionInfo": "VersionInfo",+ "containerInstanceArn": "String",+ "attributes": "Attributes",+ "platformDevices": "PlatformDevices",+ "tags": "Tags"+ }+ },+ "RegisterDaemonTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "family": "String",+ "taskRoleArn": "String",+ "executionRoleArn": "String",+ "containerDefinitions": "DaemonContainerDefinitionList",+ "cpu": "String",+ "memory": "String",+ "volumes": "DaemonVolumeList",+ "tags": "Tags",+ "pidMode": "DaemonPidMode",+ "ipcMode": "DaemonIpcMode"+ }+ },+ "RegisterTaskDefinitionRequest": {+ "type": "structure",+ "members": {+ "family": "String",+ "taskRoleArn": "String",+ "executionRoleArn": "String",+ "networkMode": "NetworkMode",+ "containerDefinitions": "ContainerDefinitions",+ "volumes": "VolumeList",+ "placementConstraints": "TaskDefinitionPlacementConstraints",+ "requiresCompatibilities": "CompatibilityList",+ "cpu": "String",+ "memory": "String",+ "tags": "Tags",+ "pidMode": "PidMode",+ "ipcMode": "IpcMode",+ "proxyConfiguration": "ProxyConfiguration",+ "inferenceAccelerators": "InferenceAccelerators",+ "ephemeralStorage": "EphemeralStorage",+ "runtimePlatform": "RuntimePlatform",+ "enableFaultInjection": "BoxedBoolean"+ }+ },+ "RepositoryCredentials": {+ "type": "structure",+ "members": {+ "credentialsParameter": "String"+ }+ },+ "Resource": {+ "type": "structure",+ "members": {+ "name": "String",+ "type": "String",+ "doubleValue": "Double",+ "longValue": "Long",+ "integerValue": "Integer",+ "stringSetValue": "StringList"+ }+ },+ "ResourceManagementType": {+ "type": "string"+ },+ "ResourceRequirement": {+ "type": "structure",+ "members": {+ "value": "String",+ "type": "ResourceType"+ }+ },+ "ResourceRequirements": {+ "type": "list",+ "member": "ResourceRequirement"+ },+ "ResourceType": {+ "type": "string"+ },+ "Resources": {+ "type": "list",+ "member": "Resource"+ },+ "RunTaskRequest": {+ "type": "structure",+ "members": {+ "capacityProviderStrategy": "CapacityProviderStrategy",+ "cluster": "String",+ "count": "BoxedInteger",+ "enableECSManagedTags": "Boolean",+ "enableExecuteCommand": "Boolean",+ "group": "String",+ "launchType": "LaunchType",+ "networkConfiguration": "NetworkConfiguration",+ "overrides": "TaskOverride",+ "placementConstraints": "PlacementConstraints",+ "placementStrategy": "PlacementStrategies",+ "platformVersion": "String",+ "propagateTags": "PropagateTags",+ "referenceId": "String",+ "startedBy": "String",+ "tags": "Tags",+ "taskDefinition": "String",+ "clientToken": "String",+ "volumeConfigurations": "TaskVolumeConfigurations"+ }+ },+ "RuntimePlatform": {+ "type": "structure",+ "members": {+ "cpuArchitecture": "CPUArchitecture",+ "operatingSystemFamily": "OSFamily"+ }+ },+ "S3FilesVolumeConfiguration": {+ "type": "structure",+ "members": {+ "fileSystemArn": "String",+ "rootDirectory": "String",+ "transitEncryptionPort": "BoxedInteger",+ "accessPointArn": "String"+ }+ },+ "Scale": {+ "type": "structure",+ "members": {+ "value": "Double",+ "unit": "ScaleUnit"+ }+ },+ "ScaleUnit": {+ "type": "string"+ },+ "SchedulingStrategy": {+ "type": "string"+ },+ "Scope": {+ "type": "string"+ },+ "Secret": {+ "type": "structure",+ "members": {+ "name": "String",+ "valueFrom": "String"+ }+ },+ "SecretList": {+ "type": "list",+ "member": "Secret"+ },+ "ServiceConnectAccessLogConfiguration": {+ "type": "structure",+ "members": {+ "format": "ServiceConnectAccessLoggingFormat",+ "includeQueryParameters": "ServiceConnectIncludeQueryParameters"+ }+ },+ "ServiceConnectAccessLoggingFormat": {+ "type": "string"+ },+ "ServiceConnectClientAlias": {+ "type": "structure",+ "members": {+ "port": "PortNumber",+ "dnsName": "String",+ "testTrafficRules": "ServiceConnectTestTrafficRules"+ }+ },+ "ServiceConnectClientAliasList": {+ "type": "list",+ "member": "ServiceConnectClientAlias"+ },+ "ServiceConnectConfiguration": {+ "type": "structure",+ "members": {+ "enabled": "Boolean",+ "namespace": "String",+ "services": "ServiceConnectServiceList",+ "logConfiguration": "LogConfiguration",+ "accessLogConfiguration": "ServiceConnectAccessLogConfiguration"+ }+ },+ "ServiceConnectIncludeQueryParameters": {+ "type": "string"+ },+ "ServiceConnectService": {+ "type": "structure",+ "members": {+ "portName": "String",+ "discoveryName": "String",+ "clientAliases": "ServiceConnectClientAliasList",+ "ingressPortOverride": "PortNumber",+ "timeout": "TimeoutConfiguration",+ "tls": "ServiceConnectTlsConfiguration"+ }+ },+ "ServiceConnectServiceList": {+ "type": "list",+ "member": "ServiceConnectService"+ },+ "ServiceConnectTestTrafficHeaderMatchRules": {+ "type": "structure",+ "members": {+ "exact": "String"+ }+ },+ "ServiceConnectTestTrafficHeaderRules": {+ "type": "structure",+ "members": {+ "name": "String",+ "value": "ServiceConnectTestTrafficHeaderMatchRules"+ }+ },+ "ServiceConnectTestTrafficRules": {+ "type": "structure",+ "members": {+ "header": "ServiceConnectTestTrafficHeaderRules"+ }+ },+ "ServiceConnectTlsCertificateAuthority": {+ "type": "structure",+ "members": {+ "awsPcaAuthorityArn": "String"+ }+ },+ "ServiceConnectTlsConfiguration": {+ "type": "structure",+ "members": {+ "issuerCertificateAuthority": "ServiceConnectTlsCertificateAuthority",+ "kmsKey": "String",+ "roleArn": "String"+ }+ },+ "ServiceDeploymentStatus": {+ "type": "string"+ },+ "ServiceDeploymentStatusList": {+ "type": "list",+ "member": "ServiceDeploymentStatus"+ },+ "ServiceField": {+ "type": "string"+ },+ "ServiceFieldList": {+ "type": "list",+ "member": "ServiceField"+ },+ "ServiceManagedEBSVolumeConfiguration": {+ "type": "structure",+ "members": {+ "encrypted": "BoxedBoolean",+ "kmsKeyId": "EBSKMSKeyId",+ "volumeType": "EBSVolumeType",+ "sizeInGiB": "BoxedInteger",+ "snapshotId": "EBSSnapshotId",+ "volumeInitializationRate": "BoxedInteger",+ "iops": "BoxedInteger",+ "throughput": "BoxedInteger",+ "tagSpecifications": "EBSTagSpecifications",+ "roleArn": "IAMRoleArn",+ "filesystemType": "TaskFilesystemType"+ }+ },+ "ServiceRegistries": {+ "type": "list",+ "member": "ServiceRegistry"+ },+ "ServiceRegistry": {+ "type": "structure",+ "members": {+ "registryArn": "String",+ "port": "BoxedInteger",+ "containerName": "String",+ "containerPort": "BoxedInteger"+ }+ },+ "ServiceRevisionCleanup": {+ "type": "string"+ },+ "ServiceVolumeConfiguration": {+ "type": "structure",+ "members": {+ "name": "ECSVolumeName",+ "managedEBSVolume": "ServiceManagedEBSVolumeConfiguration"+ }+ },+ "ServiceVolumeConfigurations": {+ "type": "list",+ "member": "ServiceVolumeConfiguration"+ },+ "SettingName": {+ "type": "string"+ },+ "SortOrder": {+ "type": "string"+ },+ "StartTaskRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstances": "StringList",+ "enableECSManagedTags": "Boolean",+ "enableExecuteCommand": "Boolean",+ "group": "String",+ "networkConfiguration": "NetworkConfiguration",+ "overrides": "TaskOverride",+ "propagateTags": "PropagateTags",+ "referenceId": "String",+ "startedBy": "String",+ "tags": "Tags",+ "taskDefinition": "String",+ "volumeConfigurations": "TaskVolumeConfigurations"+ }+ },+ "StopServiceDeploymentRequest": {+ "type": "structure",+ "members": {+ "serviceDeploymentArn": "String",+ "stopType": "StopServiceDeploymentStopType"+ }+ },+ "StopServiceDeploymentStopType": {+ "type": "string"+ },+ "StopTaskRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "task": "String",+ "reason": "String"+ }+ },+ "String": {+ "type": "string"+ },+ "StringList": {+ "type": "list",+ "member": "String"+ },+ "StringMap": {+ "type": "map",+ "value": "String"+ },+ "SubmitAttachmentStateChangesRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "attachments": "AttachmentStateChanges"+ }+ },+ "SubmitContainerStateChangeRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "task": "String",+ "containerName": "String",+ "runtimeId": "String",+ "status": "String",+ "exitCode": "BoxedInteger",+ "reason": "String",+ "networkBindings": "NetworkBindings"+ }+ },+ "SubmitTaskStateChangeRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "task": "String",+ "status": "String",+ "reason": "String",+ "containers": "ContainerStateChanges",+ "attachments": "AttachmentStateChanges",+ "managedAgents": "ManagedAgentStateChanges",+ "pullStartedAt": "Timestamp",+ "pullStoppedAt": "Timestamp",+ "executionStoppedAt": "Timestamp"+ }+ },+ "SystemControl": {+ "type": "structure",+ "members": {+ "namespace": "String",+ "value": "String"+ }+ },+ "SystemControls": {+ "type": "list",+ "member": "SystemControl"+ },+ "Tag": {+ "type": "structure",+ "members": {+ "key": "TagKey",+ "value": "TagValue"+ }+ },+ "TagKey": {+ "type": "string"+ },+ "TagKeys": {+ "type": "list",+ "member": "TagKey"+ },+ "TagResourceRequest": {+ "type": "structure",+ "members": {+ "resourceArn": "String",+ "tags": "Tags"+ }+ },+ "TagValue": {+ "type": "string"+ },+ "Tags": {+ "type": "list",+ "member": "Tag"+ },+ "TargetType": {+ "type": "string"+ },+ "TaskDefinitionFamilyStatus": {+ "type": "string"+ },+ "TaskDefinitionField": {+ "type": "string"+ },+ "TaskDefinitionFieldList": {+ "type": "list",+ "member": "TaskDefinitionField"+ },+ "TaskDefinitionPlacementConstraint": {+ "type": "structure",+ "members": {+ "type": "TaskDefinitionPlacementConstraintType",+ "expression": "String"+ }+ },+ "TaskDefinitionPlacementConstraintType": {+ "type": "string"+ },+ "TaskDefinitionPlacementConstraints": {+ "type": "list",+ "member": "TaskDefinitionPlacementConstraint"+ },+ "TaskDefinitionStatus": {+ "type": "string"+ },+ "TaskField": {+ "type": "string"+ },+ "TaskFieldList": {+ "type": "list",+ "member": "TaskField"+ },+ "TaskFilesystemType": {+ "type": "string"+ },+ "TaskManagedEBSVolumeConfiguration": {+ "type": "structure",+ "members": {+ "encrypted": "BoxedBoolean",+ "kmsKeyId": "EBSKMSKeyId",+ "volumeType": "EBSVolumeType",+ "sizeInGiB": "BoxedInteger",+ "snapshotId": "EBSSnapshotId",+ "volumeInitializationRate": "BoxedInteger",+ "iops": "BoxedInteger",+ "throughput": "BoxedInteger",+ "tagSpecifications": "EBSTagSpecifications",+ "roleArn": "IAMRoleArn",+ "terminationPolicy": "TaskManagedEBSVolumeTerminationPolicy",+ "filesystemType": "TaskFilesystemType"+ }+ },+ "TaskManagedEBSVolumeTerminationPolicy": {+ "type": "structure",+ "members": {+ "deleteOnTermination": "BoxedBoolean"+ }+ },+ "TaskOverride": {+ "type": "structure",+ "members": {+ "containerOverrides": "ContainerOverrides",+ "cpu": "String",+ "inferenceAcceleratorOverrides": "InferenceAcceleratorOverrides",+ "executionRoleArn": "String",+ "memory": "String",+ "taskRoleArn": "String",+ "ephemeralStorage": "EphemeralStorage"+ }+ },+ "TaskSetField": {+ "type": "string"+ },+ "TaskSetFieldList": {+ "type": "list",+ "member": "TaskSetField"+ },+ "TaskVolumeConfiguration": {+ "type": "structure",+ "members": {+ "name": "ECSVolumeName",+ "managedEBSVolume": "TaskManagedEBSVolumeConfiguration"+ }+ },+ "TaskVolumeConfigurations": {+ "type": "list",+ "member": "TaskVolumeConfiguration"+ },+ "TaskVolumeStorageGiB": {+ "type": "integer"+ },+ "ThresholdConfiguration": {+ "type": "structure",+ "members": {+ "type": "ThresholdType",+ "value": "Integer"+ }+ },+ "ThresholdType": {+ "type": "string"+ },+ "TimeoutConfiguration": {+ "type": "structure",+ "members": {+ "idleTimeoutSeconds": "Duration",+ "perRequestTimeoutSeconds": "Duration"+ }+ },+ "Timestamp": {+ "type": "timestamp"+ },+ "Tmpfs": {+ "type": "structure",+ "members": {+ "containerPath": "String",+ "size": "Integer",+ "mountOptions": "StringList"+ }+ },+ "TmpfsList": {+ "type": "list",+ "member": "Tmpfs"+ },+ "TotalLocalStorageGBRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedDouble",+ "max": "BoxedDouble"+ }+ },+ "TransportProtocol": {+ "type": "string"+ },+ "Ulimit": {+ "type": "structure",+ "members": {+ "name": "UlimitName",+ "softLimit": "Integer",+ "hardLimit": "Integer"+ }+ },+ "UlimitList": {+ "type": "list",+ "member": "Ulimit"+ },+ "UlimitName": {+ "type": "string"+ },+ "UntagResourceRequest": {+ "type": "structure",+ "members": {+ "resourceArn": "String",+ "tagKeys": "TagKeys"+ }+ },+ "UpdateCapacityProviderRequest": {+ "type": "structure",+ "members": {+ "name": "String",+ "cluster": "String",+ "autoScalingGroupProvider": "AutoScalingGroupProviderUpdate",+ "managedInstancesProvider": "UpdateManagedInstancesProviderConfiguration"+ }+ },+ "UpdateClusterRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "settings": "ClusterSettings",+ "configuration": "ClusterConfiguration",+ "serviceConnectDefaults": "ClusterServiceConnectDefaultsRequest"+ }+ },+ "UpdateClusterSettingsRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "settings": "ClusterSettings"+ }+ },+ "UpdateContainerAgentRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstance": "String"+ }+ },+ "UpdateContainerInstancesStateRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "containerInstances": "StringList",+ "status": "ContainerInstanceStatus"+ }+ },+ "UpdateDaemonRequest": {+ "type": "structure",+ "members": {+ "daemonArn": "String",+ "daemonTaskDefinitionArn": "String",+ "capacityProviderArns": "StringList",+ "deploymentConfiguration": "DaemonDeploymentConfiguration",+ "propagateTags": "DaemonPropagateTags",+ "enableECSManagedTags": "Boolean",+ "enableExecuteCommand": "Boolean",+ "critical": "BoxedBoolean"+ }+ },+ "UpdateExpressGatewayServiceRequest": {+ "type": "structure",+ "members": {+ "serviceArn": "String",+ "executionRoleArn": "String",+ "healthCheckPath": "String",+ "primaryContainer": "ExpressGatewayContainer",+ "taskRoleArn": "String",+ "networkConfiguration": "ExpressGatewayServiceNetworkConfiguration",+ "cpu": "String",+ "memory": "String",+ "cpuArchitecture": "ExpressCpuArchitecture",+ "scalingTarget": "ExpressGatewayScalingTarget",+ "taskDefinitionArn": "String"+ }+ },+ "UpdateManagedInstancesProviderConfiguration": {+ "type": "structure",+ "members": {+ "infrastructureRoleArn": "String",+ "instanceLaunchTemplate": "InstanceLaunchTemplateUpdate",+ "propagateTags": "PropagateMITags",+ "infrastructureOptimization": "InfrastructureOptimization",+ "autoRepairConfiguration": "AutoRepairConfiguration"+ }+ },+ "UpdateServicePrimaryTaskSetRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "primaryTaskSet": "String"+ }+ },+ "UpdateServiceRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "desiredCount": "BoxedInteger",+ "taskDefinition": "String",+ "capacityProviderStrategy": "CapacityProviderStrategy",+ "deploymentConfiguration": "DeploymentConfiguration",+ "availabilityZoneRebalancing": "AvailabilityZoneRebalancing",+ "networkConfiguration": "NetworkConfiguration",+ "placementConstraints": "PlacementConstraints",+ "placementStrategy": "PlacementStrategies",+ "platformVersion": "String",+ "forceNewDeployment": "Boolean",+ "healthCheckGracePeriodSeconds": "BoxedInteger",+ "deploymentController": "DeploymentController",+ "enableExecuteCommand": "BoxedBoolean",+ "enableECSManagedTags": "BoxedBoolean",+ "loadBalancers": "LoadBalancers",+ "propagateTags": "PropagateTags",+ "serviceRegistries": "ServiceRegistries",+ "serviceConnectConfiguration": "ServiceConnectConfiguration",+ "volumeConfigurations": "ServiceVolumeConfigurations",+ "vpcLatticeConfigurations": "VpcLatticeConfigurations",+ "monitoring": "MonitoringConfiguration"+ }+ },+ "UpdateTaskProtectionRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "tasks": "StringList",+ "protectionEnabled": "Boolean",+ "expiresInMinutes": "BoxedInteger"+ }+ },+ "UpdateTaskSetRequest": {+ "type": "structure",+ "members": {+ "cluster": "String",+ "service": "String",+ "taskSet": "String",+ "scale": "Scale"+ }+ },+ "VCpuCountRangeRequest": {+ "type": "structure",+ "members": {+ "min": "BoxedInteger",+ "max": "BoxedInteger"+ }+ },+ "VersionConsistency": {+ "type": "string"+ },+ "VersionInfo": {+ "type": "structure",+ "members": {+ "agentVersion": "String",+ "agentHash": "String",+ "dockerVersion": "String"+ }+ },+ "Volume": {+ "type": "structure",+ "members": {+ "name": "String",+ "host": "HostVolumeProperties",+ "dockerVolumeConfiguration": "DockerVolumeConfiguration",+ "efsVolumeConfiguration": "EFSVolumeConfiguration",+ "s3filesVolumeConfiguration": "S3FilesVolumeConfiguration",+ "fsxWindowsFileServerVolumeConfiguration": "FSxWindowsFileServerVolumeConfiguration",+ "configuredAtLaunch": "BoxedBoolean"+ }+ },+ "VolumeFrom": {+ "type": "structure",+ "members": {+ "sourceContainer": "String",+ "readOnly": "BoxedBoolean"+ }+ },+ "VolumeFromList": {+ "type": "list",+ "member": "VolumeFrom"+ },+ "VolumeList": {+ "type": "list",+ "member": "Volume"+ },+ "VpcLatticeAdvancedConfiguration": {+ "type": "structure",+ "members": {+ "alternateTargetGroupArn": "String",+ "productionListenerRule": "String",+ "testListenerRule": "String"+ }+ },+ "VpcLatticeConfiguration": {+ "type": "structure",+ "members": {+ "roleArn": "IAMRoleArn",+ "targetGroupArn": "String",+ "portName": "String",+ "advancedConfiguration": "VpcLatticeAdvancedConfiguration"+ }+ },+ "VpcLatticeConfigurations": {+ "type": "list",+ "member": "VpcLatticeConfiguration"+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestShapeCheckTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestShapeCheckTest.javanew file mode 100644index 0000000000..6c0181b208--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestShapeCheckTest.java@@ -0,0 +1,120 @@+package io.github.hectorvent.floci.core.common;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;+import org.junit.jupiter.api.Test;++import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * The walk every service's request check shares, with a message per point so each test shows+ * where the walk refused. The services' own tests pin their measured wording.+ */+class RequestShapeCheckTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static final RequestShapeModel MODEL = parse("""+ {+ "operations": {},+ "shapes": {+ "Request": {"type": "structure", "members": {+ "Name": "Text", "Count": "Number", "On": "Flag", "Data": "Bytes", "When": "Time",+ "Nested": "Request", "Items": "Requests", "Names": "Texts", "Labels": "Labelled"}},+ "Requests": {"type": "list", "member": "Request"},+ "Texts": {"type": "list", "member": "Text"},+ "Labelled": {"type": "map", "value": "Request"},+ "Text": {"type": "string"},+ "Number": {"type": "integer"},+ "Flag": {"type": "boolean"},+ "Bytes": {"type": "blob"},+ "Time": {"type": "timestamp"}+ }+ }+ """);++ private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages("Refused",+ "object", "list", new ByPosition("structure member", "structure element"),+ new ByPosition("list member", "list element"), new ByPosition("map member", "map element"),+ "%s as %s", true, "boolean text", "blob", Set.of("string", "integer", "boolean", "blob"));++ @Test+ void nullsAndUnknownMembersPass() {+ assertAccepted("{\"Name\": null, \"Nested\": null, \"Items\": [null], \"Other\": [1, {}]}");+ }++ @Test+ void aContainerOfTheWrongKindNamesWhereItWasRead() {+ assertRefused("{\"Nested\": 5}", "structure member");+ assertRefused("{\"Items\": [5]}", "structure element");+ assertRefused("{\"Labels\": {\"a\": 5}}", "structure element");+ assertRefused("{\"Nested\": []}", "list");+ assertRefused("{\"Items\": 5}", "list member");+ assertRefused("{\"Items\": {}}", "object");+ assertRefused("{\"Labels\": 5}", "map member");+ assertRefused("{\"Labels\": []}", "list");+ }++ @Test+ void aScalarOfTheWrongKindIsNamedByItsToken() {+ assertRefused("{\"Name\": 5}", "NUMBER_VALUE as String");+ assertRefused("{\"Name\": 5.5}", "DECIMAL_VALUE as String");+ assertRefused("{\"Name\": true}", "TRUE_VALUE as String");+ assertRefused("{\"Count\": \"5\"}", "STRING_VALUE as Integer");+ assertRefused("{\"On\": 0}", "NUMBER_VALUE as Boolean");+ assertRefused("{\"Name\": {}}", "object");+ assertRefused("{\"Names\": [[\"a\"]]}", "list");+ assertRefused("{\"Data\": 5}", "blob");+ }++ @Test+ void aBooleanReadsTrueOrFalseTextInAnyCase() {+ assertAccepted("{\"On\": \"TRUE\", \"Nested\": {\"On\": \"false\"}}");+ assertRefused("{\"On\": \"yes\"}", "boolean text");+ }++ @Test+ void aScalarTypeTheServiceWasNotMeasuredOnPasses() {+ assertAccepted("{\"When\": \"not a number\", \"Nested\": {\"When\": {}}}");+ }++ @Test+ void aMessageLeftOutAnswersWithTheCodeAlone() {+ RequestShapeCheck.Messages silent = new RequestShapeCheck.Messages("Refused", "object", null,+ ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", false,+ "boolean text", null, Set.of("string", "blob"));+ AwsException e = assertThrows(AwsException.class,+ () -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree("{\"Nested\": []}"), silent));+ assertEquals("Refused", e.getErrorCode());+ assertNull(e.getMessage());+ AwsException blob = assertThrows(AwsException.class,+ () -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree("{\"Data\": 5}"), silent));+ assertEquals("NUMBER_VALUE as Blob", blob.getMessage());+ }++ private static void assertRefused(String body, String message) {+ AwsException e = assertThrows(AwsException.class,+ () -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);+ assertEquals("Refused", e.getErrorCode(), body);+ assertEquals(400, e.getHttpStatus(), body);+ assertEquals(message, e.getMessage(), body);+ }++ private static void assertAccepted(String body) {+ assertDoesNotThrow(() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);+ }++ private static RequestShapeModel parse(String json) {+ try {+ return RequestShapeModel.parse(MAPPER.readTree(json));+ } catch (JsonProcessingException e) {+ throw new IllegalArgumentException(json, e);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLinuxOptionsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLinuxOptionsTest.javanew file mode 100644index 0000000000..6745f39931--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLinuxOptionsTest.java@@ -0,0 +1,222 @@+package io.github.hectorvent.floci.core.common.docker;++import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.command.CreateContainerCmd;+import com.github.dockerjava.api.command.CreateContainerResponse;+import com.github.dockerjava.api.model.Capability;+import com.github.dockerjava.api.model.Device;+import com.github.dockerjava.api.model.HostConfig;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.util.Map;+import java.util.Optional;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+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_SELF;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * A spec's Linux options reach Docker's HostConfig as {@code docker run} would set them, a+ * container that asked for none gets the daemon's defaults, and a container behind a security+ * group keeps NET_ADMIN and NET_RAW dropped whatever it asks to add.+ */+@ExtendWith(MockitoExtension.class)+class ContainerLifecycleManagerLinuxOptionsTest {++ private static final long MIB = 1024L * 1024L;++ @Mock+ DockerClient dockerClient;++ @Mock+ ImageCacheService imageCacheService;++ @Mock+ ContainerDetector containerDetector;+++ @Mock+ EmulatorConfig config;++ @Mock+ EmulatorConfig.DockerConfig dockerConfig;++ @Mock+ EmulatorConfig.TlsConfig tlsConfig;++ @BeforeEach+ void setUp() {+ lenient().when(config.docker()).thenReturn(dockerConfig);+ lenient().when(config.tls()).thenReturn(tlsConfig);+ lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());+ lenient().when(imageCacheService.ensureImageExists(any()))+ .thenAnswer(invocation -> invocation.getArgument(0));+ }++ @Test+ void linuxOptionsReachTheHostConfig() {+ CreateContainerCmd createCmd = stubCreateContainer();+ ContainerSpec spec = builder()+ .withMemoryMb(512)+ .withInit()+ .withCapAdd("SYS_PTRACE")+ .withCapDrop("NET_RAW")+ .withDevice("/dev/fuse", "/dev/fuse", "rw")+ .withShmSizeBytes(256 * MIB)+ .withTmpfs("/scratch", "noexec,size=64m")+ .withMemorySwapBytes(1536 * MIB)+ .withMemorySwappiness(10)+ .build();++ manager().create(spec);++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertTrue(hostConfig.getInit());+ assertArrayEquals(new Capability[] {Capability.SYS_PTRACE}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.NET_RAW}, hostConfig.getCapDrop());+ assertArrayEquals(new Device[] {new Device("rw", "/dev/fuse", "/dev/fuse")}, hostConfig.getDevices());+ assertEquals(256 * MIB, hostConfig.getShmSize());+ assertEquals(Map.of("/scratch", "noexec,size=64m"), hostConfig.getTmpFs());+ assertEquals(512 * MIB, hostConfig.getMemory());+ assertEquals(1536 * MIB, hostConfig.getMemorySwap());+ assertEquals(10L, hostConfig.getMemorySwappiness());+ }++ @Test+ void aContainerThatAskedForNoneGetsTheDaemonDefaults() {+ CreateContainerCmd createCmd = stubCreateContainer();++ manager().create(new ContainerSpec("busybox:stable"));++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertNull(hostConfig.getInit());+ assertNull(hostConfig.getCapAdd());+ assertNull(hostConfig.getCapDrop());+ assertNull(hostConfig.getDevices());+ assertNull(hostConfig.getShmSize());+ assertNull(hostConfig.getTmpFs());+ assertNull(hostConfig.getMemorySwap());+ assertNull(hostConfig.getMemorySwappiness());+ }++ @Test+ void capabilityNamesAreReadWithOrWithoutThePrefixAndInAnyCase() {+ CreateContainerCmd createCmd = stubCreateContainer();++ manager().create(builder().withCapAdd("cap_sys_ptrace").withCapDrop("Mknod").build());++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertArrayEquals(new Capability[] {Capability.SYS_PTRACE}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.MKNOD}, hostConfig.getCapDrop());+ }++ @Test+ void anUnknownCapabilityFailsTheCreate() {+ IllegalArgumentException e = assertThrows(IllegalArgumentException.class,+ () -> manager().create(builder().withCapAdd("NOT_A_CAPABILITY").build()));++ assertEquals("Unknown Linux capability: NOT_A_CAPABILITY", e.getMessage());+ }++ @Test+ void aSecurityGroupWorkloadCannotAddBackWhatItsFirewallNeedsDropped() {+ CreateContainerCmd createCmd = stubCreateContainer();+ ContainerSpec spec = builder()+ .withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"))+ .withCapAdd("NET_ADMIN")+ .withCapAdd("SYS_PTRACE")+ .withCapAdd("NET_RAW")+ .withCapDrop("MKNOD")+ .build();++ manager().create(spec);++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertArrayEquals(new Capability[] {Capability.SYS_PTRACE}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.NET_ADMIN, Capability.NET_RAW, Capability.MKNOD},+ hostConfig.getCapDrop());+ }++ /**+ * ALL among the adds stays an add: Docker grants every capability but the ones dropped when+ * ALL is added (measured: docker run --cap-add ALL --cap-drop NET_ADMIN --cap-drop NET_RAW+ * reports CapEff 000001ffffffcfff, bits 12 and 13 clear), so the firewall's drops still hold.+ */+ @Test+ void aSecurityGroupWorkloadAskingForAllStillHasItsFirewallCapabilitiesDropped() {+ CreateContainerCmd createCmd = stubCreateContainer();++ manager().create(builder()+ .withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"))+ .withCapAdd("ALL")+ .build());++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertArrayEquals(new Capability[] {Capability.ALL}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.NET_ADMIN, Capability.NET_RAW}, hostConfig.getCapDrop());+ }++ /** KILL is one of the capabilities ECS accepts, and docker-java has it. */+ @Test+ void killIsAddedAndDroppedLikeAnyOtherCapability() {+ CreateContainerCmd createCmd = stubCreateContainer();++ manager().create(builder().withCapAdd("KILL").withCapDrop("CAP_KILL").build());++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertArrayEquals(new Capability[] {Capability.KILL}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.KILL}, hostConfig.getCapDrop());+ }++ @Test+ void aSecurityGroupWorkloadThatAskedForNothingKeepsItsDrops() {+ CreateContainerCmd createCmd = stubCreateContainer();++ manager().create(builder()+ .withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"))+ .build());++ HostConfig hostConfig = capturedHostConfig(createCmd);+ assertNull(hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.NET_ADMIN, Capability.NET_RAW}, hostConfig.getCapDrop());+ }++ private static ContainerBuilder.Builder builder() {+ return new ContainerBuilder(null, null, null).newContainer("busybox:stable");+ }++ private ContainerLifecycleManager manager() {+ return new ContainerLifecycleManager(+ dockerClient, imageCacheService, containerDetector, config);+ }++ private CreateContainerCmd stubCreateContainer() {+ CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);+ when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);+ CreateContainerResponse response = mock(CreateContainerResponse.class);+ when(response.getId()).thenReturn("container-id");+ when(createCmd.exec()).thenReturn(response);+ return createCmd;+ }++ private static HostConfig capturedHostConfig(CreateContainerCmd createCmd) {+ ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);+ verify(createCmd).withHostConfig(hostConfig.capture());+ return hostConfig.getValue();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.javaindex e176d8674d..60898aac47 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java@@ -140,7 +140,7 @@ class EcsFargateEdgeCaseIntegrationTest {container.formatted("gpu", "\"resourceRequirements\":[{\"type\":\"GPU\",\"value\":\"1\"}]"), 400).then().body("message", containsString("gpu"));call("RegisterTaskDefinition",- container.formatted("swap", "\"linuxParameters\":{\"maxSwap\":128}"), 400)+ container.formatted("swap", "\"linuxParameters\":{\"maxSwap\":128,\"swappiness\":10}"), 400).then().body("message", containsString("maxSwap"));call("RegisterTaskDefinition",container.formatted("swappiness", "\"linuxParameters\":{\"swappiness\":10}"), 400)@@ -154,6 +154,207 @@ class EcsFargateEdgeCaseIntegrationTest {.then().body("message", containsString("placementConstraints"));}+ // Each message below is what RegisterTaskDefinition answered on AWS (eu-west-1, 2026-10-03),+ // without a trailing period unless AWS writes one.+ @Test+ void fargateRefusesTheLinuxParametersItCannotHonour() {+ String body = "{\"family\":\"edge-linux-%s\","+ + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","+ + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":%s}]}";++ call("RegisterTaskDefinition", body.formatted("devices", "{\"devices\":[{\"hostPath\":\"/dev/null\"}]}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support devices"));+ call("RegisterTaskDefinition", body.formatted("shm", "{\"sharedMemorySize\":64}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support sharedMemorySize"));+ call("RegisterTaskDefinition", body.formatted("swap", "{\"maxSwap\":10,\"swappiness\":10}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support maxSwap"));+ call("RegisterTaskDefinition", body.formatted("swappiness", "{\"swappiness\":10}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support swappiness"));+ call("RegisterTaskDefinition", body.formatted("netadmin",+ "{\"capabilities\":{\"add\":[\"SYS_PTRACE\",\"NET_ADMIN\",\"SYS_ADMIN\"]}}"), 400)+ .then().body("message", equalTo("NET_ADMIN is not allowed on Fargate."));+ // Fargate's one capability is matched as written: in lower case it is refused by name.+ call("RegisterTaskDefinition", body.formatted("lowerptrace", "{\"capabilities\":{\"add\":[\"sys_ptrace\"]}}"), 400)+ .then().body("message", equalTo("sys_ptrace is not allowed on Fargate."));++ // The first rule a definition breaks is the one reported, in this order.+ call("RegisterTaskDefinition", body.formatted("order1", "{\"devices\":[{\"hostPath\":\"/dev/null\"}],"+ + "\"sharedMemorySize\":64,\"capabilities\":{\"add\":[\"NET_ADMIN\"]}}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support devices"));+ call("RegisterTaskDefinition", body.formatted("order2", "{\"swappiness\":10,\"sharedMemorySize\":64}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support sharedMemorySize"));+ call("RegisterTaskDefinition", body.formatted("order3",+ "{\"swappiness\":10,\"capabilities\":{\"add\":[\"NET_ADMIN\"]}}"), 400)+ .then().body("message", equalTo("Fargate compatible task definitions do not support swappiness"));++ call("RegisterTaskDefinition", body.formatted("nodevices", "{\"devices\":[]}"), 200);+ call("RegisterTaskDefinition", body.formatted("ptrace",+ "{\"capabilities\":{\"add\":[\"SYS_PTRACE\"],\"drop\":[\"net_raw\",\"ALL\"]}}"), 200);+ call("RegisterTaskDefinition", body.formatted("init",+ "{\"initProcessEnabled\":true,\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":16}]}"), 200);+ }++ @Test+ void linuxParametersAreCheckedWhateverTheLaunchType() {+ String body = "{\"family\":\"edge-linux-ec2-%s\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":%s}]}";++ call("RegisterTaskDefinition", body.formatted("swap", "{\"maxSwap\":10}"), 400)+ .then().body("message",+ equalTo("When a container has a swap memory, it must also specify a swappiness value."));+ call("RegisterTaskDefinition", body.formatted("capprefix", "{\"capabilities\":{\"add\":[\"CAP_NET_ADMIN\"]}}"), 400)+ .then().body("message", equalTo("Unrecognized Linux capabilities in add: [CAP_NET_ADMIN]"));+ call("RegisterTaskDefinition", body.formatted("unknowndrop", "{\"capabilities\":{\"drop\":[\"FOO\"]}}"), 400)+ .then().body("message", equalTo("Unrecognized Linux capabilities in drop: [FOO]"));+ call("RegisterTaskDefinition", body.formatted("lower", "{\"capabilities\":{\"add\":[\"net_admin\"]}}"), 200);++ // The swap rule comes before Fargate's own, which would otherwise name maxSwap.+ call("RegisterTaskDefinition", "{\"family\":\"edge-linux-fargate-swap\","+ + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","+ + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":{\"maxSwap\":10}}]}", 400)+ .then().body("message",+ equalTo("When a container has a swap memory, it must also specify a swappiness value."));+ }++ /** Measured on RegisterTaskDefinition (eu-west-1, 2026-10-16), each with AWS's message. */+ @Test+ void devicesTmpfsSharedMemoryAndSwapAreChecked() {+ String body = "{\"family\":\"edge-linux-values-%s\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":%s}]}";+ String[][] refused = {+ {"nohost", "{\"devices\":[{\"containerPath\":\"/dev/x\"}]}", "Device cannot have empty hostPath"},+ {"perm", "{\"devices\":[{\"hostPath\":\"/dev/null\",\"permissions\":[\"READ\"]}]}",+ "Invalid permission: READ for device /dev/null"},+ {"nopath", "{\"tmpfs\":[{\"size\":64}]}", "All tmpfs mounts must have a specified containerPath value."},+ {"nosize", "{\"tmpfs\":[{\"containerPath\":\"/t\"}]}",+ "The container has an invalid tmpfs size value specified. It must be a non-zero, non-negative integer."},+ {"zerosize", "{\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":0}]}",+ "The container has an invalid tmpfs size value specified. It must be a non-zero, non-negative integer."},+ {"option", "{\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":64,\"mountOptions\":[\"NOEXEC\"]}]}",+ "The NOEXEC tmpfs mount option specified is invalid."},+ {"shm", "{\"sharedMemorySize\":0}",+ "The container has an invalid shared memory volume size. It must be a non-zero, non-negative integer."},+ {"negswap", "{\"maxSwap\":-1,\"swappiness\":150}",+ "The container has an invalid swap memory size. It must be non-negative integer."},+ {"swappiness", "{\"maxSwap\":1024,\"swappiness\":150}",+ "The container has an invalid swappiness value. It must be between 0 and 100."},+ {"order", "{\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":0}],\"devices\":[{\"containerPath\":\"/x\"}]}",+ "Device cannot have empty hostPath"},+ };+ for (String[] c : refused) {+ call("RegisterTaskDefinition", body.formatted(c[0], c[1]), 400).then().body("message", equalTo(c[2]));+ }++ call("RegisterTaskDefinition", body.formatted("ok", "{\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":64,"+ + "\"mountOptions\":[\"mode=1777\",\"noexec\"]}],\"maxSwap\":0,\"swappiness\":0}"), 200);+ }++ /** Measured: a swappiness without maxSwap is dropped, and capabilities get both lists. */+ @Test+ void theStoredLinuxParametersAreTheOnesAwsKeeps() {+ String body = "{\"family\":\"edge-linux-stored\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":"+ + "{\"swappiness\":10,\"sharedMemorySize\":64,\"capabilities\":{\"drop\":[\"NET_RAW\"]}}}]}";++ call("RegisterTaskDefinition", body, 200).then()+ .body("taskDefinition.containerDefinitions[0].linuxParameters.swappiness", nullValue())+ .body("taskDefinition.containerDefinitions[0].linuxParameters.sharedMemorySize", equalTo(64))+ .body("taskDefinition.containerDefinitions[0].linuxParameters.capabilities.add", hasSize(0))+ .body("taskDefinition.containerDefinitions[0].linuxParameters.capabilities.drop[0]", equalTo("NET_RAW"));+ }++ /**+ * Measured with raw requests (eu-west-1, 2026-10-18): a member of the wrong JSON type is+ * refused by RegisterTaskDefinition's deserializer, with these messages, before any rule on the+ * values; a list where none is expected carries no message.+ */+ @Test+ void aLinuxParametersMemberOfTheWrongJsonTypeIsRefusedFirst() {+ String body = "{\"family\":\"edge-linux-types-%s\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":%s}]}";+ String[][] refused = {+ {"lp", "\"x\"", "Unexpected field type"},+ {"caps", "{\"capabilities\":\"x\"}", "Unexpected field type"},+ {"devices", "{\"devices\":\"x\"}", "Unexpected field type"},+ {"devobj", "{\"devices\":{\"hostPath\":\"/dev/null\"}}", "Start of structure or map found where not expected"},+ {"devitem", "{\"devices\":[\"not-a-device\"]}", "Unexpected value type in payload"},+ {"tmpfsitem", "{\"tmpfs\":[\"not-a-mount\"]}", "Unexpected value type in payload"},+ {"addnum", "{\"capabilities\":{\"add\":[5]}}", "NUMBER_VALUE cannot be converted to String"},+ {"hosttrue", "{\"devices\":[{\"hostPath\":true}]}", "TRUE_VALUE cannot be converted to String"},+ {"shmstring", "{\"sharedMemorySize\":\"64\"}", "STRING_VALUE cannot be converted to Integer"},+ {"shmfalse", "{\"sharedMemorySize\":false}", "FALSE_VALUE cannot be converted to Integer"},+ {"initnum", "{\"initProcessEnabled\":1}", "NUMBER_VALUE cannot be converted to Boolean"},+ {"inittext", "{\"initProcessEnabled\":\"abc\"}", "Unexpected token received from parser"},+ {"order", "{\"capabilities\":{\"add\":[\"CAP_X\"]},\"devices\":[\"x\"]}",+ "Unexpected value type in payload"},+ };+ for (String[] c : refused) {+ call("RegisterTaskDefinition", body.formatted(c[0], c[1]), 400).then()+ .body("__type", containsString("InvalidParameterException"))+ .body("message", equalTo(c[2]));+ }+ call("RegisterTaskDefinition", body.formatted("capslist", "{\"capabilities\":[]}"), 400).then()+ .body("__type", containsString("InvalidParameterException"))+ .body("message", nullValue());++ // Read as AWS reads them, then checked: a null device is an empty one, half a MiB is none.+ call("RegisterTaskDefinition", body.formatted("devnull", "{\"devices\":[null]}"), 400).then()+ .body("message", equalTo("Device cannot have empty hostPath"));+ call("RegisterTaskDefinition", body.formatted("shmhalf", "{\"sharedMemorySize\":0.5}"), 400).then()+ .body("message", equalTo(+ "The container has an invalid shared memory volume size. It must be a non-zero, non-negative integer."));+ }++ /**+ * Measured: numbers are stored as the integers AWS reads (the fraction dropped, the range+ * capped), a boolean as text is read in any case, and a null member or list entry is absent.+ */+ @Test+ void numbersBooleansAndNullsAreStoredAsAwsReadsThem() {+ String body = "{\"family\":\"edge-linux-read-%s\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\",\"linuxParameters\":%s}]}";+ String linux = "taskDefinition.containerDefinitions[0].linuxParameters.";++ call("RegisterTaskDefinition", body.formatted("fractions", "{\"sharedMemorySize\":1.9,\"maxSwap\":1.5,"+ + "\"swappiness\":10.5,\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":2.5}]}"), 200).then()+ .body(linux + "sharedMemorySize", equalTo(1))+ .body(linux + "maxSwap", equalTo(1))+ .body(linux + "swappiness", equalTo(10))+ .body(linux + "tmpfs[0].size", equalTo(2));+ call("RegisterTaskDefinition", body.formatted("capped", "{\"sharedMemorySize\":3000000000,"+ + "\"initProcessEnabled\":\"False\",\"capabilities\":{\"add\":[null]},\"devices\":null}"), 200).then()+ .body(linux + "sharedMemorySize", equalTo(Integer.MAX_VALUE))+ .body(linux + "initProcessEnabled", equalTo(false))+ .body(linux + "capabilities.add", hasSize(0))+ .body(linux + "capabilities.drop", hasSize(0))+ .body(linux + "devices", nullValue());+ }++ /**+ * A device hands the container the host's hardware, so Floci refuses one as it refuses a host+ * volume, by default and after AWS's own checks: floci.services.ecs.host-volume-roots or+ * allow-unsafe-host-volumes let it through.+ */+ @Test+ void aDeviceIsRefusedByDefaultLikeAHostVolume() {+ String body = "{\"family\":\"edge-linux-device\",\"requiresCompatibilities\":[\"EC2\"],"+ + "\"networkMode\":\"bridge\",\"memory\":\"512\",\"containerDefinitions\":"+ + "[{\"name\":\"app\",\"image\":\"nginx:latest\","+ + "\"linuxParameters\":{\"devices\":[{\"hostPath\":\"/dev/null\"}]}}]}";++ call("RegisterTaskDefinition", body, 400).then()+ .body("__type", containsString("InvalidParameterException"))+ .body("message", containsString(+ "containerDefinitions[].linuxParameters.devices[].hostPath is rejected by default: /dev/null"));+ }+@Testvoid pidModeTaskIsTheOnlyOneFargateAccepts() {String body = "{\"family\":\"edge-pidmode-%s\",\"requiresCompatibilities\":[\"FARGATE\"],"diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.javaindex 18d6945d33..28e890f253 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java@@ -62,8 +62,8 @@ class EcsFargateTaskDefinitionIntegrationTest {@Testvoid registerTaskDefinitionRoundTripsMembersFlociDoesNotActOn() {- // proxyConfiguration and the container's ulimits, linuxParameters and resourceRequirements- // have no local behaviour, but a client that wrote them reads them back or sees drift.+ // proxyConfiguration and the container's ulimits and resourceRequirements have no local+ // behaviour, but a client that wrote them, or linuxParameters, reads them back or sees drift.register("{\"family\":\"fargate-passthrough\",\"requiresCompatibilities\":[\"FARGATE\"],"+ "\"networkMode\":\"awsvpc\",\"cpu\":\"512\",\"memory\":\"1024\","+ "\"proxyConfiguration\":{\"type\":\"APPMESH\",\"containerName\":\"envoy\","diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLinuxParametersDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLinuxParametersDockerIntegrationTest.javanew file mode 100644index 0000000000..7ce4f3201e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLinuxParametersDockerIntegrationTest.java@@ -0,0 +1,140 @@+package io.github.hectorvent.floci.services.ecs;++import com.github.dockerjava.api.DockerClient;+import com.github.dockerjava.api.command.InspectContainerResponse;+import com.github.dockerjava.api.command.TopContainerResponse;+import com.github.dockerjava.api.model.Capability;+import com.github.dockerjava.api.model.Device;+import com.github.dockerjava.api.model.HostConfig;+import io.github.hectorvent.floci.services.ecs.model.EcsTask;+import io.github.hectorvent.floci.testing.DockerAvailability;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.github.hectorvent.floci.testing.TestImages;+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.AfterEach;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * A task definition registered through the API with {@code linuxParameters} runs a container+ * that has them: an init process as PID 1, the capabilities added and dropped, the device, the+ * size of {@code /dev/shm} and the tmpfs mount, as ECS hands each of them to Docker.+ */+@QuarkusTest+@TestProfile(EcsLinuxParametersDockerIntegrationTest.DockerEcsProfile.class)+class EcsLinuxParametersDockerIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String ECS_CT = "application/x-amz-json-1.1";+ private static final String ECS_TARGET = "AmazonEC2ContainerServiceV20141113.";+ private static final long MIB = 1024L * 1024L;++ /**+ * Real containers, with security-group enforcement back to its shipped default of off, and+ * {@code /dev/null} the one host path a device may take, since devices are refused by default.+ */+ public static final class DockerEcsProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.ecs.mock", "false",+ "floci.network.security-group-enforcement.enabled", "false",+ "floci.services.ecs.host-volume-roots", "/dev/null");+ }+ }++ @Inject+ EcsService ecsService;++ @Inject+ DockerClient dockerClient;++ private String clusterName;+ private String taskArn;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @BeforeEach+ void requireDocker() throws InterruptedException {+ Assumptions.assumeTrue(DockerAvailability.isAvailable(),+ "Docker daemon must be available for the ECS container test");+ }++ @AfterEach+ void stopTask() {+ if (taskArn != null) {+ ecsService.stopTask(clusterName, taskArn, "test teardown", REGION);+ }+ }++ @Test+ void theContainerRunsWithItsLinuxParameters() {+ String family = "linux-params-" + UUID.randomUUID().toString().substring(0, 8);+ String taskDefinitionArn = given().contentType(ECS_CT)+ .header("X-Amz-Target", ECS_TARGET + "RegisterTaskDefinition")+ .body("""+ {+ "family": "%s",+ "requiresCompatibilities": ["EC2"],+ "networkMode": "bridge",+ "containerDefinitions": [{+ "name": "worker",+ "image": "%s",+ "memory": 256,+ "command": ["sleep", "120"],+ "linuxParameters": {+ "initProcessEnabled": true,+ "capabilities": {"add": ["SYS_PTRACE"], "drop": ["NET_RAW"]},+ "devices": [{"hostPath": "/dev/null", "containerPath": "/dev/floci-null",+ "permissions": ["read"]}],+ "sharedMemorySize": 128,+ "tmpfs": [{"containerPath": "/scratch", "size": 16, "mountOptions": ["noexec"]}]+ }+ }]+ }+ """.formatted(family, TestImages.BUSYBOX))+ .when().post("/").then().statusCode(200)+ .extract().path("taskDefinition.taskDefinitionArn");++ clusterName = family;+ ecsService.createCluster(clusterName, REGION);+ EcsTask task = ecsService.runTask(clusterName, taskDefinitionArn, 1,+ null, null, null, null, null, REGION).getFirst();+ taskArn = task.getTaskArn();+ EcsTask described = ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst();+ assertEquals("RUNNING", described.getLastStatus(), "the container must be up: " + described.getStoppedReason());+ String containerId = described.getContainers().getFirst().getRuntimeId();++ InspectContainerResponse inspected = dockerClient.inspectContainerCmd(containerId).exec();+ HostConfig hostConfig = inspected.getHostConfig();+ assertEquals(Boolean.TRUE, hostConfig.getInit(), "initProcessEnabled is docker run --init");+ assertArrayEquals(new Capability[] {Capability.SYS_PTRACE}, hostConfig.getCapAdd());+ assertArrayEquals(new Capability[] {Capability.NET_RAW}, hostConfig.getCapDrop());+ assertArrayEquals(new Device[] {new Device("r", "/dev/floci-null", "/dev/null")}, hostConfig.getDevices());+ assertEquals(128 * MIB, hostConfig.getShmSize());+ assertEquals(Map.of("/scratch", "noexec,size=16m"), hostConfig.getTmpFs());++ TopContainerResponse top = dockerClient.topContainerCmd(containerId).exec();+ int command = Arrays.asList(top.getTitles()).indexOf("CMD");+ assertTrue(command >= 0, Arrays.toString(top.getTitles()));+ assertTrue(top.getProcesses()[0][command].contains("docker-init"),+ "PID 1 is the init process, with the command under it: " + Arrays.deepToString(top.getProcesses()));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParametersTest.javanew file mode 100644index 0000000000..d460c776b3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsLinuxParametersTest.java@@ -0,0 +1,108 @@+package io.github.hectorvent.floci.services.ecs.container;++import com.github.dockerjava.api.model.Device;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.LinuxOptions;+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * A container definition's {@code linuxParameters}, read where RegisterTaskDefinition keeps them,+ * become the Docker options ECS documents for each member.+ */+class EcsLinuxParametersTest {++ private static final long MIB = 1024L * 1024L;++ @Test+ void everyMemberBecomesTheDockerOptionEcsDocuments() {+ LinuxOptions options = apply(Map.of(+ "initProcessEnabled", true,+ "capabilities", Map.of("add", List.of("SYS_PTRACE"), "drop", List.of("NET_RAW", "MKNOD")),+ "devices", List.of(Map.of("hostPath", "/dev/fuse", "containerPath", "/dev/fuse0",+ "permissions", List.of("write", "read"))),+ "sharedMemorySize", 256,+ "tmpfs", List.of(Map.of("containerPath", "/scratch", "size", 64,+ "mountOptions", List.of("noexec", "nosuid"))),+ "maxSwap", 1024,+ "swappiness", 10), 512);++ assertEquals(List.of("SYS_PTRACE"), options.capAdd());+ assertEquals(List.of("NET_RAW", "MKNOD"), options.capDrop());+ assertEquals(List.of(new Device("rw", "/dev/fuse0", "/dev/fuse")), options.devices());+ assertEquals(256 * MIB, options.shmSizeBytes());+ assertEquals(Map.of("/scratch", "noexec,nosuid,size=64m"), options.tmpfs());+ assertEquals((512 + 1024) * MIB, options.memorySwapBytes(), "memory plus maxSwap");+ assertEquals(10L, options.memorySwappiness());+ }++ @Test+ void aDeviceWithoutPermissionsOrContainerPathGetsReadWriteMknodAtItsHostPath() {+ LinuxOptions options = apply(Map.of("devices", List.of(Map.of("hostPath", "/dev/null"))), null);++ assertEquals(List.of(new Device("rwm", "/dev/null", "/dev/null")), options.devices());+ }++ @Test+ void maxSwapZeroMeansNoSwap() {+ LinuxOptions options = apply(Map.of("maxSwap", 0, "swappiness", 0), 512);++ assertEquals(512 * MIB, options.memorySwapBytes(), "swap limit equal to the memory limit: no swap");+ assertEquals(0L, options.memorySwappiness());+ }++ @Test+ void swappinessWithoutMaxSwapIsIgnored() {+ LinuxOptions options = apply(Map.of("swappiness", 10), 512);++ assertNull(options.memorySwapBytes());+ assertNull(options.memorySwappiness());+ }++ @Test+ void maxSwapIsNotAppliedToAContainerWithNoMemoryLimitButItsSwappinessIs() {+ LinuxOptions options = apply(Map.of("maxSwap", 256, "swappiness", 10), null);++ assertNull(options.memorySwapBytes());+ assertEquals(10L, options.memorySwappiness());+ }++ @Test+ void initProcessDisabledOrAbsentLeavesTheDaemonDefault() {+ assertTrue(build(Map.of("initProcessEnabled", true), 512).init());+ assertFalse(build(Map.of("initProcessEnabled", false), 512).init());+ assertFalse(build(Map.of(), 512).init());+ assertEquals(LinuxOptions.NONE, apply(Map.of(), 512));+ }++ @Test+ void aContainerWithoutLinuxParametersGetsNone() {+ ContainerDefinition def = new ContainerDefinition();+ ContainerBuilder.Builder spec = new ContainerBuilder(null, null, null).newContainer("busybox:stable");++ EcsLinuxParameters.apply(spec, def, 512);++ assertEquals(LinuxOptions.NONE, spec.build().linuxOptions());+ }++ private static LinuxOptions apply(Map<String, Object> linuxParameters, Integer memoryLimitMb) {+ return build(linuxParameters, memoryLimitMb).linuxOptions();+ }++ private static ContainerSpec build(Map<String, Object> linuxParameters, Integer memoryLimitMb) {+ ContainerDefinition def = new ContainerDefinition();+ def.setUnparsed(Map.of("linuxParameters", linuxParameters));+ ContainerBuilder.Builder spec = new ContainerBuilder(null, null, null).newContainer("busybox:stable");+ EcsLinuxParameters.apply(spec, def, memoryLimitMb);+ return spec.build();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapesTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapesTest.javanew file mode 100644index 0000000000..0895480805--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsRequestShapesTest.java@@ -0,0 +1,104 @@+package io.github.hectorvent.floci.services.ecs.container;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * A container's {@code linuxParameters} walked against the vendored ECS model, with the+ * InvalidParameterException messages measured with raw RegisterTaskDefinition requests+ * (eu-west-1, 2026-10-18).+ */+class EcsRequestShapesTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final String STRUCTURE = "Start of structure or map found where not expected";++ @Test+ void aStructureTakesOnlyAnObject() {+ assertRejected("\"x\"", "Unexpected field type");+ assertRejected("{\"capabilities\":\"x\"}", "Unexpected field type");+ assertRejected("{\"devices\":[\"not-a-device\"]}", "Unexpected value type in payload");+ assertRejected("{\"tmpfs\":[\"not-a-mount\"]}", "Unexpected value type in payload");+ assertRejected("{\"devices\":[5]}", "Unexpected value type in payload");+ assertRejectedWithoutMessage("[]");+ assertRejectedWithoutMessage("{\"capabilities\":[]}");+ }++ @Test+ void aListTakesOnlyAnArray() {+ assertRejected("{\"devices\":\"x\"}", "Unexpected field type");+ assertRejected("{\"devices\":5}", "Unexpected field type");+ assertRejected("{\"capabilities\":{\"add\":\"SYS_PTRACE\"}}", "Unexpected field type");+ assertRejected("{\"devices\":{\"hostPath\":\"/dev/null\"}}", STRUCTURE);+ }++ @Test+ void aScalarNamesTheJsonTokenItGot() {+ assertRejected("{\"capabilities\":{\"add\":[5]}}", "NUMBER_VALUE cannot be converted to String");+ assertRejected("{\"capabilities\":{\"add\":[true]}}", "TRUE_VALUE cannot be converted to String");+ assertRejected("{\"capabilities\":{\"add\":[{\"a\":1}]}}", STRUCTURE);+ assertRejectedWithoutMessage("{\"capabilities\":{\"add\":[[\"x\"]]}}");+ assertRejected("{\"devices\":[{\"hostPath\":true}]}", "TRUE_VALUE cannot be converted to String");+ assertRejected("{\"devices\":[{\"hostPath\":\"/dev/null\",\"permissions\":[5]}]}",+ "NUMBER_VALUE cannot be converted to String");+ assertRejected("{\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":1,\"mountOptions\":[5]}]}",+ "NUMBER_VALUE cannot be converted to String");+ assertRejected("{\"sharedMemorySize\":\"64\"}", "STRING_VALUE cannot be converted to Integer");+ assertRejected("{\"sharedMemorySize\":true}", "TRUE_VALUE cannot be converted to Integer");+ assertRejected("{\"sharedMemorySize\":false}", "FALSE_VALUE cannot be converted to Integer");+ assertRejected("{\"sharedMemorySize\":{}}", STRUCTURE);+ assertRejectedWithoutMessage("{\"sharedMemorySize\":[]}");+ assertRejected("{\"initProcessEnabled\":1}", "NUMBER_VALUE cannot be converted to Boolean");+ assertRejected("{\"initProcessEnabled\":{}}", STRUCTURE);+ assertRejectedWithoutMessage("{\"initProcessEnabled\":[]}");+ }++ @Test+ void aBooleanReadsTrueOrFalseTextInAnyCase() {+ assertAccepted("{\"initProcessEnabled\":\"true\"}");+ assertAccepted("{\"initProcessEnabled\":\"False\"}");+ assertRejected("{\"initProcessEnabled\":\"abc\"}", "Unexpected token received from parser");+ assertRejected("{\"initProcessEnabled\":\"\"}", "Unexpected token received from parser");+ }++ @Test+ void nullsAndNumbersWithFractionsPass() {+ assertAccepted("{\"sharedMemorySize\":null,\"devices\":null,\"capabilities\":{\"add\":[null]}}");+ assertAccepted("{\"devices\":[null]}");+ assertAccepted("{\"sharedMemorySize\":1.9,\"maxSwap\":3000000000,\"swappiness\":10.5,"+ + "\"tmpfs\":[{\"containerPath\":\"/t\",\"size\":2.5}]}");+ }++ private static void assertRejected(String linuxParameters, String message) {+ AwsException e = assertThrows(AwsException.class,+ () -> EcsRequestShapes.check("LinuxParameters", parse(linuxParameters)), linuxParameters);+ assertEquals("InvalidParameterException", e.getErrorCode(), linuxParameters);+ assertEquals(message, e.getMessage(), linuxParameters);+ }++ private static void assertRejectedWithoutMessage(String linuxParameters) {+ AwsException e = assertThrows(AwsException.class,+ () -> EcsRequestShapes.check("LinuxParameters", parse(linuxParameters)), linuxParameters);+ assertEquals("InvalidParameterException", e.getErrorCode(), linuxParameters);+ assertNull(e.getMessage(), linuxParameters);+ }++ private static void assertAccepted(String linuxParameters) {+ assertDoesNotThrow(() -> EcsRequestShapes.check("LinuxParameters", parse(linuxParameters)), linuxParameters);+ }++ private static Object parse(String json) {+ try {+ return MAPPER.readValue(json, Object.class);+ } catch (JsonProcessingException e) {+ throw new IllegalArgumentException(json, e);+ }+ }+}diff --git a/tools/aws/regen_ecs_shapes.py b/tools/aws/regen_ecs_shapes.pynew file mode 100755index 0000000000..a684e3c463--- /dev/null+++ b/tools/aws/regen_ecs_shapes.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Regenerate src/main/resources/aws/ecs-request-shapes.json from botocore's ECS model.++ECS rejects a request body member of the wrong JSON type with an InvalidParameterException before+it validates anything. The Java side (`EcsRequestShapes`) needs the body shapes to do the same, so+this script keeps only what that check reads: the input shape of every operation and, for every+shape reachable from one, its type and the shapes of its members, list elements or map values.++The model is botocore's `ecs/2014-11-13/service-2.json` (Apache-2.0,+https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the+`local/aws/botocore` checkout, then the installed `botocore` package, which `requirements.txt`+pins so CI regenerates the same bytes.++Run from anywhere in the repo:+ python3 tools/aws/regen_ecs_shapes.py # rewrite the vendored file in place+ python3 tools/aws/regen_ecs_shapes.py --check # exit 1 when the vendored file is stale+"""+from __future__ import annotations++import sys+from pathlib import Path++import request_shapes++OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/ecs-request-shapes.json"+MODEL = Path("ecs/2014-11-13")+++def main(argv: list[str] | None = None) -> int:+ return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.pyindex 97a6a134ba..7bc92ba6c0 100644--- a/tools/aws/request_shapes.py+++ b/tools/aws/request_shapes.py@@ -1,7 +1,7 @@"""Shared generator for the vendored request shapes a service's request check reads.-`regen_dynamodb_shapes.py` and `regen_sesv2_shapes.py` each name a botocore model and an output-file and hand the rest to `main()`. The output keeps only what `RequestShapeModel` reads: the input+`regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py` and `regen_ecs_shapes.py` each name a botocore+model and an output file and hand the rest to `main()`. The output keeps only what `RequestShapeModel` reads: the inputshape of every operation, reduced to the members carried in the JSON body, and for every shapereachable from one, its type and the shapes of its members, list elements or map values.diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.pyindex ce8a49ea5b..d66d757f8f 100644--- a/tools/aws/test_request_shapes.py+++ b/tools/aws/test_request_shapes.py@@ -1,4 +1,4 @@-"""Tests for request_shapes, the generator behind regen_dynamodb_shapes and regen_sesv2_shapes.+"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes and regen_ecs_shapes.Run with: pytest tools/aws -q (or: make aws-data-test)"""@@ -11,6 +11,7 @@ from pathlib import Pathimport pytestimport regen_dynamodb_shapes+import regen_ecs_shapesimport regen_sesv2_shapesimport request_shapes as r@@ -140,6 +141,7 @@ def test_output_is_stable():def test_generator_name_is_the_scripts_path_from_the_repository_root():assert r.generator_name(regen_dynamodb_shapes.__file__) == "tools/aws/regen_dynamodb_shapes.py"assert r.generator_name(regen_sesv2_shapes.__file__) == "tools/aws/regen_sesv2_shapes.py"+ assert r.generator_name(regen_ecs_shapes.__file__) == "tools/aws/regen_ecs_shapes.py"def test_generator_name_outside_the_repository_is_the_file_name(tmp_path):@@ -163,6 +165,7 @@ def test_load_model_without_a_service_model_exits(tmp_path):@pytest.mark.parametrize("script, model, output", [(regen_dynamodb_shapes, "dynamodb/2012-08-10", "dynamodb-request-shapes.json"),(regen_sesv2_shapes, "sesv2/2019-09-27", "sesv2-request-shapes.json"),+ (regen_ecs_shapes, "ecs/2014-11-13", "ecs-request-shapes.json"),])def test_each_script_runs_the_shared_main_with_its_model_and_output(script, model, output, monkeypatch):calls = []