mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecs): launch a container with its linuxParameters, checked as RegisterTaskDefinition does (#5951)
* fix(ecs): launch a container with its linuxParameters, checked as RegisterTaskDefinition does
RegisterTaskDefinition kept a container's linuxParameters and
DescribeTaskDefinition returned them, but the container was launched
without any of them. A worker that set initProcessEnabled so its orphaned
browser processes would be reaped ran with its own command as PID 1, and
they stayed zombies until the container ended; capabilities, devices,
/dev/shm size, tmpfs mounts and swap limits were ignored the same way.
ECS documents each member as a docker run option, and the container is
now created with them: initProcessEnabled is --init (through
ContainerSpec.init, the flag main already has for it), capabilities are
--cap-add and --cap-drop, devices are --device (read, write and mknod when
no permissions are given, at the host path when no container path is),
sharedMemorySize is --shm-size in MiB, each tmpfs entry is a --tmpfs of
its size in MiB with its mount options, maxSwap is --memory-swap as the
container's hard limit plus that many MiB, and swappiness is
--memory-swappiness. ContainerSpec gains LinuxOptions for the rest,
applied in ContainerLifecycleManager's HostConfig; a constructor with the
former signature keeps every other caller unchanged.
A container behind a security group already had NET_ADMIN and NET_RAW
dropped, because the group is enforced by nftables in the namespace the
task's containers share. Docker applies a named --cap-add over a
--cap-drop, so those two are now also removed from what the container
asks to add; ALL can stay, since Docker grants every capability but the
dropped ones then (measured: docker run --cap-add ALL --cap-drop NET_ADMIN
--cap-drop NET_RAW reports CapEff 000001ffffffcfff, bits 12 and 13 clear).
Measured on RegisterTaskDefinition (eu-west-1, 2026-10-03 and 2026-10-16),
with the SDK's own validation off, and now checked the same way before
anything is stored:
- every capability must be one the KernelCapabilities reference lists, in
any case and without a CAP_ prefix ("Unrecognized Linux capabilities in
add: [CAP_NET_ADMIN]", likewise for drop);
- a device needs a hostPath ("Device cannot have empty hostPath") and only
read, write and mknod as permissions, as written ("Invalid permission:
READ for device /dev/null");
- a tmpfs mount needs a containerPath, a size above zero and options the
Tmpfs reference lists, as written ("The NOEXEC tmpfs mount option
specified is invalid.");
- sharedMemorySize must be above zero, maxSwap zero or more and needs a
swappiness ("When a container has a swap memory, it must also specify a
swappiness value."), from 0 to 100;
- the checks run capabilities, devices, tmpfs, then swap, all before the
Fargate rules;
- on Fargate a non-empty devices list, sharedMemorySize, maxSwap and
swappiness are refused in that order ("Fargate compatible task
definitions do not support devices", with no trailing period, unlike
AWS's other Fargate refusals), and any capability added but SYS_PTRACE
as written ("NET_ADMIN is not allowed on Fargate.");
- a swappiness without maxSwap is accepted and dropped, and capabilities
are stored with both an add and a drop list.
EcsLinuxParameters holds all of it, validation, the stored form and the
launch, and reads the members through one set of helpers, so EcsService
only calls it.
Not done: swap is not limited for a container with no hard memory limit,
since Docker cannot limit swap without one, and a daemon on cgroup v2
discards swappiness, as Amazon Linux 2023 does on ECS.
Tests: EcsLinuxParametersTest and ContainerLifecycleManagerLinuxOptionsTest
for what reaches Docker, EcsLinuxParametersDockerIntegrationTest for a
real container (PID 1, capabilities, device, /dev/shm, tmpfs),
EcsFargateEdgeCaseIntegrationTest for the measured refusals and the stored
form, and EcsLinuxParametersRegistrationTest in sdk-test-java for the
same through the SDK.
* fix(ecs): read linuxParameters as RegisterTaskDefinition does, and guard devices like host volumes
Review of #5951 (Qodo).
A device hands the container the host's hardware, and reached Docker with
no check, where a host volume at the same path is refused by default.
HostVolumePolicy now covers each device's hostPath too, naming the field
it checks: refused unless floci.services.ecs.host-volume-roots holds it or
allow-unsafe-host-volumes is set, at RegisterTaskDefinition after AWS's
own checks (so their messages still come first) and again at launch,
through EcsContainerManager.checkDeviceHostPaths. The registration check
sits in EcsService rather than beside the host volume one in
EcsJsonHandler, so a template's definition gets it too.
Measured with raw requests on RegisterTaskDefinition (eu-west-1,
2026-10-18):
- a member of the wrong JSON type is refused with an
InvalidParameterException from the deserializer, before any rule on the
values: "Unexpected field type" for a scalar where an object or a list
is expected, "Unexpected value type in payload" for a device or a tmpfs
mount that is not an object, "Start of structure or map found where not
expected" for an object where a list or a scalar is expected,
"NUMBER_VALUE cannot be converted to String", "STRING_VALUE cannot be
converted to Integer", "TRUE_VALUE ...", "NUMBER_VALUE cannot be
converted to Boolean", "Unexpected token received from parser" for text
that is not true or false, and no message at all for a list where none
is expected;
- numbers are read as integers, the fraction dropped (sharedMemorySize
1.9 is stored as 1, 0.5 as 0 and refused) and the range capped
(3000000000 is 2147483647); a boolean may come as text in any case; a
null member or list entry is absent, and a null device is an empty one.
Floci kept such values as written and silently skipped what it could not
read, so a definition stored one size and launched another. The stored
form now holds what AWS stores.
Tests: EcsFargateEdgeCaseIntegrationTest for every measured shape, the
stored numbers, booleans and nulls, and a device refused by default; the
Docker test allows /dev/null through host-volume-roots. All fail on the
previous head.
* refactor(ecs): check linuxParameters' JSON types against the vendored ECS model
Review of #5951. EcsLinuxParameters hand-wrote the deserializer's type
check member by member, where Floci already drives that check from
botocore for DynamoDB and SES v2 (RequestShapeModel, with the shapes
vendored by tools/aws/request_shapes.py).
tools/aws/regen_ecs_shapes.py vendors botocore's ECS model as
src/main/resources/aws/ecs-request-shapes.json (botocore 1.43.113, the
release requirements.txt pins), registered in make aws-data-sync and
aws-data-check and in the shared generator's tests. EcsRequestShapes
walks a container's linuxParameters against the LinuxParameters shape
with ECS's InvalidParameterException messages, the ones measured on
RegisterTaskDefinition; EcsLinuxParameters' own member list is gone.
The messages and their order are unchanged.
The device change named host volumes only in two more descriptions of
floci.services.ecs.host-volume-roots: docs/configuration/
environment-variables.md and the configuration table in
docs/services/ecs.md now name devices too, as does the host volume
section and the allow-unsafe-host-volumes Javadoc.
Tests: EcsRequestShapesTest for every measured message against the
vendored model; EcsFargateEdgeCaseIntegrationTest passes unchanged.
* refactor(core): walk request shapes once, with each service's messages
Review of #5951: EcsRequestShapes walked the vendored model the same way
DynamoDbRequestShapes and SesV2RequestShapes do (a null is absent, an
unknown member is skipped, a structure's values are read as members and a
list's or a map's as elements, a boolean reads from "true" or "false" in
any case, a scalar of the wrong kind is named by its JSON token), with only
the error code and a few messages apart. That walk is now
RequestShapeCheck, next to RequestShapeModel in core.common, and each
service hands it its deserializer's wording as RequestShapeCheck.Messages:
DynamoDB's SerializationException with DECIMAL_VALUE and the base-64
message for a blob, SES v2's SerializationException with its "can not be
converted to a" wording and only strings and blobs checked, as probed, and
ECS's InvalidParameterException with no message for a list where none is
expected.
The three services' tests pass unchanged. SES v2's wording becomes
constants in SesV2Json, which its member helpers and the walk share.
This commit is contained in:
1 parent
6e18bb0b95
commit
98b2429e58
31 files changed
+4702
-262
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+222
@@ -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();
|
||||
}
|
||||
}
|
||||
+202
-1
@@ -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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pidModeTaskIsTheOnlyOneFargateAccepts() {
|
||||
String body = "{\"family\":\"edge-pidmode-%s\",\"requiresCompatibilities\":[\"FARGATE\"],"
|
||||
|
||||
+2
-2
@@ -62,8 +62,8 @@ class EcsFargateTaskDefinitionIntegrationTest {
|
||||
|
||||
@Test
|
||||
void 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\","
|
||||
|
||||
+140
@@ -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()));
|
||||
}
|
||||
}
|
||||
+108
@@ -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();
|
||||
}
|
||||
}
|
||||
+104
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user