mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ecs): resolve containerDefinitions[].secrets at task launch (#1687)
RegisterTaskDefinition now parses and stores containerDefinitions[].secrets (name + valueFrom) and round-trips them on register/describe as references, matching AWS (the resolved values are never returned). At RunTask launch, EcsContainerManager resolves each secret to an environment variable through the in-process SsmService / SecretsManagerService (the same local resolution CodeBuildRunner already uses, no extra HTTP hops): - SSM parameter by name or full ARN -> Parameter.value - Secrets Manager full ARN -> SecretString - a full ARN's own region is used, so cross-region references resolve correctly - env precedence: task-def environment < resolved secrets < RunTask container override environment (override still wins on a name collision) When a referenced secret/parameter cannot be resolved the launch fails the way AWS does: no container is started and the task goes STOPPED with a ResourceInitializationError stoppedReason, rather than silently starting the container without the variable. Deferred (noted in floci-io/floci#1624): the Secrets Manager valueFrom selector suffix (:json-key:version-stage:version-id) is not yet parsed; such a valueFrom is resolved as the plain secret. Adds handler round-trip tests, container-manager resolution / override / cross-region unit tests, a stopped-task failure test, and Java SDK compatibility coverage.
This commit is contained in:
13 files changed
+518
-23
No files matched your search
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ecs.model.PortMapping;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ProtectedTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ServiceRevision;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Secret;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskSet;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
|
||||
@@ -1023,6 +1024,17 @@ public class EcsJsonHandler {
|
||||
n.set("environment", envArr);
|
||||
}
|
||||
|
||||
if (def.getSecrets() != null && !def.getSecrets().isEmpty()) {
|
||||
ArrayNode secretsArr = objectMapper.createArrayNode();
|
||||
for (Secret secret : def.getSecrets()) {
|
||||
ObjectNode secretNode = objectMapper.createObjectNode();
|
||||
secretNode.put("name", secret.name());
|
||||
secretNode.put("valueFrom", secret.valueFrom());
|
||||
secretsArr.add(secretNode);
|
||||
}
|
||||
n.set("secrets", secretsArr);
|
||||
}
|
||||
|
||||
if (def.getMountPoints() != null && !def.getMountPoints().isEmpty()) {
|
||||
ArrayNode mps = objectMapper.createArrayNode();
|
||||
for (MountPoint mp : def.getMountPoints()) {
|
||||
@@ -1275,6 +1287,9 @@ public class EcsJsonHandler {
|
||||
|
||||
def.setPortMappings(parsePortMappings(item.path("portMappings")));
|
||||
def.setEnvironment(parseKeyValuePairs(item.path("environment")));
|
||||
if (item.has("secrets")) {
|
||||
def.setSecrets(parseSecrets(item.path("secrets")));
|
||||
}
|
||||
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
|
||||
|
||||
if (item.has("command") && item.path("command").isArray()) {
|
||||
@@ -1318,6 +1333,17 @@ public class EcsJsonHandler {
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Secret> parseSecrets(JsonNode node) {
|
||||
List<Secret> result = new ArrayList<>();
|
||||
if (!node.isArray()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode item : node) {
|
||||
result.add(new Secret(item.path("name").asText(), item.path("valueFrom").asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Volume> parseVolumes(JsonNode node) {
|
||||
List<Volume> result = new ArrayList<>();
|
||||
if (!node.isArray()) {
|
||||
|
||||
@@ -481,7 +481,14 @@ public class EcsService {
|
||||
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
|
||||
task.setLastStatus(TaskStatus.STOPPED.name());
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setStoppedReason("Failed to start: " + e.getMessage());
|
||||
// A ResourceInitializationError is already AWS's exact stopped-reason wording
|
||||
// (e.g. a secret that could not be resolved), so pass it through verbatim.
|
||||
// Other start failures keep the generic prefix.
|
||||
boolean resourceInitError = e instanceof AwsException ae
|
||||
&& "ResourceInitializationError".equals(ae.getErrorCode());
|
||||
task.setStoppedReason(resourceInitError
|
||||
? e.getMessage()
|
||||
: "Failed to start: " + e.getMessage());
|
||||
task.setStoppedAt(Instant.now());
|
||||
}
|
||||
} else {
|
||||
|
||||
+106
-14
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
@@ -19,8 +20,11 @@ import io.github.hectorvent.floci.services.ecs.model.MountPoint;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
|
||||
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Secret;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Volume;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
@@ -52,6 +56,8 @@ public class EcsContainerManager {
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final SsmService ssmService;
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
|
||||
@Inject
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -60,7 +66,9 @@ public class EcsContainerManager {
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver,
|
||||
LaunchedContainerAwsEnv awsEnv) {
|
||||
LaunchedContainerAwsEnv awsEnv,
|
||||
SsmService ssmService,
|
||||
SecretsManagerService secretsManagerService) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -68,6 +76,8 @@ public class EcsContainerManager {
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.awsEnv = awsEnv;
|
||||
this.ssmService = ssmService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,25 +110,23 @@ public class EcsContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, ContainerOverride> overridesByName = overridesByName(containerOverrides);
|
||||
Map<ContainerDefinition, List<String>> envVarsByContainer = new LinkedHashMap<>();
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region));
|
||||
}
|
||||
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
|
||||
|
||||
// RunTask containerOverrides matched by container name: command replaces
|
||||
// the task-def command; environment is merged over the task-def environment.
|
||||
ContainerOverride override = null;
|
||||
if (containerOverrides != null) {
|
||||
for (ContainerOverride co : containerOverrides) {
|
||||
if (def.getName() != null && def.getName().equals(co.getName())) {
|
||||
override = co;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ContainerOverride override = overridesByName.get(def.getName());
|
||||
|
||||
// Build container spec
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(def.getImage())
|
||||
.withName(containerName)
|
||||
.withEnv(buildEnvVars(def, override, region))
|
||||
.withEnv(envVarsByContainer.get(def))
|
||||
.withDockerNetwork(config.services().ecs().dockerNetwork())
|
||||
// Resolve Floci's endpoint from inside the task container the same way Lambda
|
||||
// containers do: host.docker.internal on Linux, plus Floci's embedded DNS so the
|
||||
@@ -344,9 +352,10 @@ public class EcsContainerManager {
|
||||
}
|
||||
|
||||
private List<String> buildEnvVars(ContainerDefinition def, ContainerOverride override, String region) {
|
||||
// AWS SDK baseline (endpoint + region + credentials) so the task can reach the emulator,
|
||||
// then the task-def environment, then the override environment — the task def and override
|
||||
// win on key conflict, so an explicit task-def value is never clobbered.
|
||||
// AWS SDK baseline (endpoint + region + credentials) first so the task can reach the
|
||||
// emulator, then the task-def environment, then task-def secrets, then the override
|
||||
// environment. Later entries win on key conflict, so an explicit task-def value or
|
||||
// secret is never clobbered by the baseline.
|
||||
Map<String, String> envMap = new LinkedHashMap<>();
|
||||
for (String kv : awsEnv.sdkBaselineEnv(region, Optional.empty())) {
|
||||
int eq = kv.indexOf('=');
|
||||
@@ -359,6 +368,11 @@ public class EcsContainerManager {
|
||||
envMap.put(kv.name(), kv.value());
|
||||
}
|
||||
}
|
||||
if (def.getSecrets() != null) {
|
||||
for (Secret secret : def.getSecrets()) {
|
||||
envMap.put(secret.name(), resolveSecretValue(secret.valueFrom(), region));
|
||||
}
|
||||
}
|
||||
if (override != null && override.getEnvironment() != null) {
|
||||
for (var kv : override.getEnvironment()) {
|
||||
envMap.put(kv.name(), kv.value());
|
||||
@@ -371,6 +385,84 @@ public class EcsContainerManager {
|
||||
return envVars;
|
||||
}
|
||||
|
||||
private Map<String, ContainerOverride> overridesByName(List<ContainerOverride> containerOverrides) {
|
||||
Map<String, ContainerOverride> overrides = new LinkedHashMap<>();
|
||||
if (containerOverrides == null) {
|
||||
return overrides;
|
||||
}
|
||||
for (ContainerOverride override : containerOverrides) {
|
||||
if (override.getName() != null) {
|
||||
overrides.put(override.getName(), override);
|
||||
}
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
|
||||
private String resolveSecretValue(String valueFrom, String region) {
|
||||
// A full ARN carries its own region; use it so cross-region references resolve
|
||||
// against the right store instead of the task's region. Bare SSM names fall back
|
||||
// to the task region.
|
||||
String secretRegion = arnRegion(valueFrom, region);
|
||||
String value;
|
||||
try {
|
||||
if (valueFrom != null && valueFrom.startsWith("arn:aws:secretsmanager:")) {
|
||||
// A plain secret ARN (or partial ARN) resolves to its full SecretString.
|
||||
// The ECS `:json-key:version-stage:version-id` selector suffix is not yet
|
||||
// supported: it is passed through unparsed, so a valueFrom carrying one fails
|
||||
// to resolve and stops the task with ResourceInitializationError rather than
|
||||
// silently returning the whole secret. See floci-io/floci#1624.
|
||||
var secret = secretsManagerService.getSecretValue(valueFrom, null, null, secretRegion);
|
||||
value = secret == null ? null : secret.getSecretString();
|
||||
} else {
|
||||
String parameterName = ssmParameterName(valueFrom);
|
||||
var parameter = ssmService.getParameter(parameterName, secretRegion);
|
||||
value = parameter == null ? null : parameter.getValue();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw resourceInitializationError(valueFrom, e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
if (value == null) {
|
||||
// A Secrets Manager secret stored as SecretBinary (no SecretString) has no string
|
||||
// value to inject as an env var. Real AWS fails the task launch rather than starting
|
||||
// the container with a missing value, so surface the same ResourceInitializationError
|
||||
// instead of emitting a literal "NAME=null".
|
||||
throw resourceInitializationError(valueFrom, "secret value is not a string", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// The error code is ResourceInitializationError, not the underlying store's code: this
|
||||
// exception never reaches a client (it is caught in EcsService and rendered as the task's
|
||||
// stoppedReason), and EcsService keys off this code to pass the reason through as AWS's
|
||||
// exact wording rather than wrapping it in the generic "Failed to start:" prefix.
|
||||
private AwsException resourceInitializationError(String valueFrom, String detail, int httpStatus) {
|
||||
return new AwsException("ResourceInitializationError",
|
||||
"ResourceInitializationError: unable to pull secrets or registry auth: "
|
||||
+ valueFrom + ": " + detail,
|
||||
httpStatus);
|
||||
}
|
||||
|
||||
/** The region embedded in an ARN {@code valueFrom} (4th segment), or {@code taskRegion} for a bare name. */
|
||||
private String arnRegion(String valueFrom, String taskRegion) {
|
||||
if (valueFrom != null && valueFrom.startsWith("arn:")) {
|
||||
String[] parts = valueFrom.split(":", 5);
|
||||
if (parts.length >= 4 && !parts[3].isBlank()) {
|
||||
return parts[3];
|
||||
}
|
||||
}
|
||||
return taskRegion;
|
||||
}
|
||||
|
||||
private String ssmParameterName(String valueFrom) {
|
||||
if (valueFrom != null && valueFrom.startsWith("arn:aws:ssm:")) {
|
||||
int parameterMarker = valueFrom.indexOf(":parameter");
|
||||
if (parameterMarker >= 0) {
|
||||
return valueFrom.substring(parameterMarker + ":parameter".length());
|
||||
}
|
||||
}
|
||||
return valueFrom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the host address at which a running task container is reachable from the
|
||||
* Floci process — used to register the container as an ELBv2 target.
|
||||
|
||||
@@ -15,6 +15,7 @@ public class ContainerDefinition {
|
||||
private boolean essential = true;
|
||||
private List<PortMapping> portMappings;
|
||||
private List<KeyValuePair> environment;
|
||||
private List<Secret> secrets;
|
||||
private List<String> command;
|
||||
private List<String> entryPoint;
|
||||
private List<MountPoint> mountPoints;
|
||||
@@ -43,6 +44,9 @@ public class ContainerDefinition {
|
||||
public List<KeyValuePair> getEnvironment() { return environment; }
|
||||
public void setEnvironment(List<KeyValuePair> environment) { this.environment = environment; }
|
||||
|
||||
public List<Secret> getSecrets() { return secrets; }
|
||||
public void setSecrets(List<Secret> secrets) { this.secrets = secrets; }
|
||||
|
||||
public List<String> getCommand() { return command; }
|
||||
public void setCommand(List<String> command) { this.command = command; }
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ecs.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public record Secret(String name, String valueFrom) {
|
||||
}
|
||||
Reference in new issue
Block a user