mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+65
-3
@@ -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 weight
|
||||
if (spec.nanoCpus() != null && spec.nanoCpus() > 0) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+20
-124
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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, Resettab
|
||||
validateEphemeralStorage(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, Resettab
|
||||
rejectOnFargate(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");
|
||||
|
||||
+17
@@ -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 readability
|
||||
private enum TaskStatus {RUNNING}
|
||||
}
|
||||
+384
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+20
-8
@@ -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;
|
||||
@ApplicationScoped
|
||||
public 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user