diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java index 4e476f6a9d..6c510a6649 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -404,14 +404,16 @@ public class EcsContainerManager { // to the task region. String secretRegion = arnRegion(valueFrom, region); String value; + String jsonKey = null; 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); + // The valueFrom may carry the ECS selector suffix + // (:json-key:version-stage:version-id); the parser strips it so the base ARN + // reaches SecretsManagerService intact, keeping its partial-ARN fallback working. + var selector = SecretsManagerSelector.parse(valueFrom); + jsonKey = selector.jsonKey(); + var secret = secretsManagerService.getSecretValue(selector.secretId(), + selector.versionId(), selector.versionStage(), secretRegion); value = secret == null ? null : secret.getSecretString(); } else { String parameterName = ssmParameterName(valueFrom); @@ -425,9 +427,17 @@ public class EcsContainerManager { // 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". + // instead of emitting a literal "NAME=null". Checked before JSON extraction: the real + // agent nil-derefs on this input, so failing cleanly is a deliberate improvement. throw resourceInitializationError(valueFrom, "secret value is not a string", 400); } + if (jsonKey != null) { + try { + value = SecretsManagerSelector.extractJsonKey(value, jsonKey); + } catch (AwsException e) { + throw resourceInitializationError(valueFrom, e.getMessage(), e.getHttpStatus()); + } + } return value; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelector.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelector.java new file mode 100644 index 0000000000..bc0ed9a710 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelector.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; + +/** + * The ECS task-definition secret selector for Secrets Manager {@code valueFrom} values: + * {@code arn:aws:secretsmanager:region:account:secret:name:json-key:version-stage:version-id}. + * + *

Parsing mirrors the real ECS agent (amazon-ecs-agent, asmsecret.go): the ARN's resource + * segment is split on {@code :} and disambiguated purely by segment count, which is safe + * because a secret name can never contain a colon. Exactly two segments + * ({@code secret:name}) is a plain reference and the original string is used verbatim as the + * secret id, preserving partial-ARN lookups. Exactly five segments is a selector: the secret + * id is rebuilt from the first two segments, and empty selector segments mean "unset" — CDK + * routinely emits forms like {@code :field::}, {@code :::version-id} and + * {@code ::version-stage:}. Any other count is the agent's invalid-ARN error. + */ +record SecretsManagerSelector(String secretId, String jsonKey, String versionStage, String versionId) { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String INVALID_ARN_MESSAGE = + "an invalid ARN format for the AWS Secrets Manager secret was specified. " + + "Specify a valid ARN and try again."; + + static SecretsManagerSelector parse(String valueFrom) { + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(valueFrom); + } catch (IllegalArgumentException e) { + throw invalidArn(); + } + String[] segments = arn.resource().split(":", -1); + if (segments.length == 2) { + return new SecretsManagerSelector(valueFrom, null, null, null); + } + if (segments.length != 5) { + throw invalidArn(); + } + String baseArn = new AwsArnUtils.Arn(arn.partition(), arn.service(), arn.region(), + arn.accountId(), segments[0] + ":" + segments[1]).toString(); + return new SecretsManagerSelector(baseArn, + emptyToNull(segments[2]), emptyToNull(segments[3]), emptyToNull(segments[4])); + } + + /** + * Extracts a top-level JSON field from a secret string, mirroring the agent's behavior + * (asm.go): missing key and non-JSON secrets are errors. Scalar values are rendered with + * {@code asText()}, which keeps large numbers in plain notation where the Go agent's + * {@code %v} would print scientific notation. Object and array values deliberately serialize + * as JSON, another divergence: the agent's {@code %v} on the unmarshalled value would inject + * Go's native rendering ({@code map[a:1 b:2]}), which no consumer can parse back. + */ + static String extractJsonKey(String secretString, String jsonKey) { + JsonNode root; + try { + root = MAPPER.readTree(secretString); + } catch (Exception e) { + root = null; + } + if (root == null || !root.isObject()) { + throw new AwsException("InvalidParameterException", + "the secret value is not valid JSON, cannot extract json key " + jsonKey, 400); + } + JsonNode value = root.get(jsonKey); + if (value == null) { + throw new AwsException("ResourceNotFoundException", + "retrieved secret from Secrets Manager did not contain json key " + jsonKey, 400); + } + return value.isValueNode() ? value.asText() : value.toString(); + } + + private static String emptyToNull(String segment) { + return segment == null || segment.isEmpty() ? null : segment; + } + + private static AwsException invalidArn() { + return new AwsException("InvalidParameterException", INVALID_ARN_MESSAGE, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index 39a023eff7..5714af218f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java @@ -136,6 +136,13 @@ public class SecretsManagerService { throw new AwsException("ResourceNotFoundException", "Secrets Manager can't find the specified secret version.", 400); } + // When both selectors are supplied they must name the same version. + if (versionStage != null && !versionStage.isEmpty() + && (version.getVersionStages() == null + || !version.getVersionStages().contains(versionStage))) { + throw new AwsException("InvalidRequestException", + "You provided a VersionStage that is not associated to the provided VersionId.", 400); + } } else { String stage = (versionStage != null && !versionStage.isEmpty()) ? versionStage : AWSCURRENT; version = findVersionByStage(secret, stage); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java index e545784972..ff9690c28e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java @@ -363,21 +363,24 @@ class EcsIntegrationTest { "essential": true, "secrets": [ {"name": "DB_PASSWORD", "valueFrom": "%s"}, + {"name": "DB_TOKEN", "valueFrom": "%s:token::"}, {"name": "CONFIG_VALUE", "valueFrom": "/app/config"} ] } ] } - """.formatted(secretArn)) + """.formatted(secretArn, secretArn)) .when() .post("/") .then() .statusCode(200) - .body("taskDefinition.containerDefinitions[0].secrets", hasSize(2)) + .body("taskDefinition.containerDefinitions[0].secrets", hasSize(3)) .body("taskDefinition.containerDefinitions[0].secrets[0].name", equalTo("DB_PASSWORD")) .body("taskDefinition.containerDefinitions[0].secrets[0].valueFrom", equalTo(secretArn)) - .body("taskDefinition.containerDefinitions[0].secrets[1].name", equalTo("CONFIG_VALUE")) - .body("taskDefinition.containerDefinitions[0].secrets[1].valueFrom", equalTo("/app/config")) + .body("taskDefinition.containerDefinitions[0].secrets[1].name", equalTo("DB_TOKEN")) + .body("taskDefinition.containerDefinitions[0].secrets[1].valueFrom", equalTo(secretArn + ":token::")) + .body("taskDefinition.containerDefinitions[0].secrets[2].name", equalTo("CONFIG_VALUE")) + .body("taskDefinition.containerDefinitions[0].secrets[2].valueFrom", equalTo("/app/config")) .extract() .path("taskDefinition.taskDefinitionArn"); @@ -389,11 +392,13 @@ class EcsIntegrationTest { .post("/") .then() .statusCode(200) - .body("taskDefinition.containerDefinitions[0].secrets", hasSize(2)) + .body("taskDefinition.containerDefinitions[0].secrets", hasSize(3)) .body("taskDefinition.containerDefinitions[0].secrets[0].name", equalTo("DB_PASSWORD")) .body("taskDefinition.containerDefinitions[0].secrets[0].valueFrom", equalTo(secretArn)) - .body("taskDefinition.containerDefinitions[0].secrets[1].name", equalTo("CONFIG_VALUE")) - .body("taskDefinition.containerDefinitions[0].secrets[1].valueFrom", equalTo("/app/config")); + .body("taskDefinition.containerDefinitions[0].secrets[1].name", equalTo("DB_TOKEN")) + .body("taskDefinition.containerDefinitions[0].secrets[1].valueFrom", equalTo(secretArn + ":token::")) + .body("taskDefinition.containerDefinitions[0].secrets[2].name", equalTo("CONFIG_VALUE")) + .body("taskDefinition.containerDefinitions[0].secrets[2].valueFrom", equalTo("/app/config")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java index 359b5bbdb6..7f32b3894c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java @@ -166,6 +166,104 @@ class EcsContainerManagerSecretsTest { verify(lifecycleManager, never()).createAndStart(any()); } + @Test + void jsonKeySelectorExtractsFieldFromSecretString() { + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + when(secretsManagerService.getSecretValue(secretArn, null, null, "us-east-1")) + .thenReturn(secretVersion("{\"token\":\"expected-value\",\"other\":\"x\"}")); + + manager.startTask(task(), + taskDef(containerDef("app", List.of(new Secret("PROBE", secretArn + ":token::")))), + List.of(), "us-east-1"); + + @SuppressWarnings("unchecked") + ArgumentCaptor> envCaptor = ArgumentCaptor.forClass(List.class); + verify(builder).withEnv(envCaptor.capture()); + assertTrue(envCaptor.getValue().contains("PROBE=expected-value")); + // The service must see the base ARN, never the selector suffix. + verify(secretsManagerService).getSecretValue(secretArn, null, null, "us-east-1"); + } + + @Test + void emptyJsonKeySelectorInjectsWholeSecretAndPassesVersionArgs() { + // CDK's fromSecretsManagerVersion without a field emits ":::version-id". + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + when(secretsManagerService.getSecretValue(secretArn, "v123", null, "us-east-1")) + .thenReturn(secretVersion("whole-secret")); + + manager.startTask(task(), + taskDef(containerDef("app", List.of(new Secret("WHOLE", secretArn + ":::v123")))), + List.of(), "us-east-1"); + + @SuppressWarnings("unchecked") + ArgumentCaptor> envCaptor = ArgumentCaptor.forClass(List.class); + verify(builder).withEnv(envCaptor.capture()); + assertTrue(envCaptor.getValue().contains("WHOLE=whole-secret")); + verify(secretsManagerService).getSecretValue(secretArn, "v123", null, "us-east-1"); + } + + @Test + void fullSelectorPassesStageAndIdThrough() { + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + when(secretsManagerService.getSecretValue(secretArn, "v123", "AWSPREVIOUS", "us-east-1")) + .thenReturn(secretVersion("{\"token\":\"old-value\"}")); + + manager.startTask(task(), + taskDef(containerDef("app", + List.of(new Secret("PROBE", secretArn + ":token:AWSPREVIOUS:v123")))), + List.of(), "us-east-1"); + + verify(secretsManagerService).getSecretValue(secretArn, "v123", "AWSPREVIOUS", "us-east-1"); + } + + @Test + void missingJsonKeyFailsLaunchWithAgentMessage() { + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + when(secretsManagerService.getSecretValue(secretArn, null, null, "us-east-1")) + .thenReturn(secretVersion("{\"other\":\"x\"}")); + + AwsException thrown = assertThrows(AwsException.class, + () -> manager.startTask(task(), + taskDef(containerDef("app", List.of(new Secret("PROBE", secretArn + ":token::")))), + List.of(), "us-east-1")); + + assertTrue(thrown.getMessage().contains("ResourceInitializationError")); + assertTrue(thrown.getMessage().contains("did not contain json key token")); + verify(lifecycleManager, never()).createAndStart(any()); + } + + @Test + void nonJsonSecretWithJsonKeyFailsLaunch() { + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + when(secretsManagerService.getSecretValue(secretArn, null, null, "us-east-1")) + .thenReturn(secretVersion("plain-text")); + + AwsException thrown = assertThrows(AwsException.class, + () -> manager.startTask(task(), + taskDef(containerDef("app", List.of(new Secret("PROBE", secretArn + ":token::")))), + List.of(), "us-east-1")); + + assertTrue(thrown.getMessage().contains("ResourceInitializationError")); + assertTrue(thrown.getMessage().contains("not valid JSON")); + } + + @Test + void invalidSelectorFormFailsLaunchWithAgentSentence() { + // Three-segment form (":token" with no trailing "::") is not a valid selector; the + // real agent rejects it rather than guessing. + String secretArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app-AbCdEf"; + + AwsException thrown = assertThrows(AwsException.class, + () -> manager.startTask(task(), + taskDef(containerDef("app", List.of(new Secret("PROBE", secretArn + ":token")))), + List.of(), "us-east-1")); + + assertTrue(thrown.getMessage().contains("ResourceInitializationError")); + assertTrue(thrown.getMessage().contains( + "an invalid ARN format for the AWS Secrets Manager secret was specified")); + verify(lifecycleManager, never()).createAndStart(any()); + } + private static ContainerDefinition containerDef(String name, List secrets) { ContainerDefinition def = new ContainerDefinition(); def.setName(name); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelectorTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelectorTest.java new file mode 100644 index 0000000000..00727f3729 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/SecretsManagerSelectorTest.java @@ -0,0 +1,124 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import io.github.hectorvent.floci.core.common.AwsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SecretsManagerSelectorTest { + + private static final String BASE = + "arn:aws:secretsmanager:us-east-2:000000000000:secret:app/config-AbCdEf"; + + @Test + void plainArnPassesThroughVerbatim() { + var sel = SecretsManagerSelector.parse(BASE); + assertEquals(BASE, sel.secretId()); + assertNull(sel.jsonKey()); + assertNull(sel.versionStage()); + assertNull(sel.versionId()); + } + + @Test + void jsonKeyOnlySelector() { + // CDK Secret.fromSecretsManager(secret, 'token') emits ":token::". + var sel = SecretsManagerSelector.parse(BASE + ":token::"); + assertEquals(BASE, sel.secretId()); + assertEquals("token", sel.jsonKey()); + assertNull(sel.versionStage()); + assertNull(sel.versionId()); + } + + @Test + void emptyJsonKeyWithVersionIdMeansWholeSecret() { + // CDK fromSecretsManagerVersion(secret, {versionId}) with no field emits ":::id". + var sel = SecretsManagerSelector.parse(BASE + ":::v123"); + assertEquals(BASE, sel.secretId()); + assertNull(sel.jsonKey()); + assertNull(sel.versionStage()); + assertEquals("v123", sel.versionId()); + } + + @Test + void emptyJsonKeyWithVersionStage() { + var sel = SecretsManagerSelector.parse(BASE + "::AWSPREVIOUS:"); + assertNull(sel.jsonKey()); + assertEquals("AWSPREVIOUS", sel.versionStage()); + assertNull(sel.versionId()); + } + + @Test + void fullSelector() { + var sel = SecretsManagerSelector.parse(BASE + ":token:AWSPREVIOUS:v123"); + assertEquals(BASE, sel.secretId()); + assertEquals("token", sel.jsonKey()); + assertEquals("AWSPREVIOUS", sel.versionStage()); + assertEquals("v123", sel.versionId()); + } + + @Test + void partialArnBaseIsRebuiltWithoutSuffix() { + String partial = "arn:aws:secretsmanager:us-east-2:000000000000:secret:app/config"; + var sel = SecretsManagerSelector.parse(partial + ":token::"); + assertEquals(partial, sel.secretId()); + assertEquals("token", sel.jsonKey()); + } + + @ParameterizedTest + @ValueSource(strings = { + // 3 segments: the hand-written ":field" form CDK never emits; the agent rejects it. + BASE + ":token", + // 4 segments: also covers a CFN dynamic-reference style ":SecretString:key" mixup. + BASE + ":SecretString:token", + // 6 segments. + BASE + ":token:AWSPREVIOUS:v123:extra", + }) + void invalidSegmentCountsRejectedWithAgentMessage(String valueFrom) { + AwsException e = assertThrows(AwsException.class, () -> SecretsManagerSelector.parse(valueFrom)); + assertTrue(e.getMessage().contains( + "an invalid ARN format for the AWS Secrets Manager secret was specified")); + } + + @Test + void extractsTopLevelJsonKey() { + assertEquals("expected-value", + SecretsManagerSelector.extractJsonKey("{\"token\":\"expected-value\"}", "token")); + } + + @Test + void nonStringJsonValuesAreStringified() { + assertEquals("10000000", + SecretsManagerSelector.extractJsonKey("{\"port\":10000000}", "port")); + assertEquals("true", + SecretsManagerSelector.extractJsonKey("{\"enabled\":true}", "enabled")); + } + + @Test + void objectAndArrayValuesSerializeAsJson() { + // Third deliberate divergence from the real agent: Go's %v would inject + // "map[a:1 b:2]" for a nested object; JSON is parseable by the consumer. + assertEquals("{\"a\":1,\"b\":2}", + SecretsManagerSelector.extractJsonKey("{\"nested\":{\"a\":1,\"b\":2}}", "nested")); + assertEquals("[1,2,3]", + SecretsManagerSelector.extractJsonKey("{\"list\":[1,2,3]}", "list")); + } + + @Test + void missingJsonKeyIsAnError() { + AwsException e = assertThrows(AwsException.class, + () -> SecretsManagerSelector.extractJsonKey("{\"other\":\"x\"}", "token")); + assertTrue(e.getMessage().contains("did not contain json key token")); + } + + @Test + void nonJsonSecretWithKeyIsAnError() { + AwsException e = assertThrows(AwsException.class, + () -> SecretsManagerSelector.extractJsonKey("not-json", "token")); + assertTrue(e.getMessage().contains("not valid JSON")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java index 8b59428f95..c2b4b8a677 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java @@ -60,6 +60,30 @@ class SecretsManagerServiceTest { service.getSecretValue("missing", null, null, REGION)); } + @Test + void getSecretValueWithMatchingVersionIdAndStage() { + service.createSecret("paired", "v1", null, null, null, null, REGION); + SecretVersion current = service.getSecretValue("paired", null, null, REGION); + + SecretVersion fetched = service.getSecretValue("paired", + current.getVersionId(), "AWSCURRENT", REGION); + assertEquals("v1", fetched.getSecretString()); + } + + @Test + void getSecretValueWithMismatchedVersionIdAndStageThrows() { + // botocore: when both are supplied they must refer to the same version; moto and + // LocalStack both raise InvalidRequestException with this message. + service.createSecret("mismatched", "v1", null, null, null, null, REGION); + SecretVersion current = service.getSecretValue("mismatched", null, null, REGION); + + AwsException thrown = assertThrows(AwsException.class, () -> + service.getSecretValue("mismatched", current.getVersionId(), "AWSPREVIOUS", REGION)); + assertEquals("InvalidRequestException", thrown.getErrorCode()); + assertTrue(thrown.getMessage().contains( + "You provided a VersionStage that is not associated to the provided VersionId.")); + } + @Test void putSecretValueRotatesVersion() { service.createSecret("my-secret", "v1", null, null, null, null, REGION);