From 045c65ec49b9005cdf1ff9e9b175fc4d1c4b8c61 Mon Sep 17 00:00:00 2001 From: galsuchetzky-act Date: Fri, 30 Oct 2026 17:09:39 +0200 Subject: [PATCH] feat(ssm): add PutResourcePolicy, GetResourcePolicies and DeleteResourcePolicy for parameters (#6833) AWS lets an Advanced-tier parameter carry one resource-based policy, used to share it with other accounts. PutResourcePolicy returns a PolicyId and a PolicyHash, and updating or deleting the policy takes both: a hash that is no longer current is ResourcePolicyConflictException, an unknown id is ResourcePolicyNotFoundException, and an unknown parameter is ResourceNotFoundException. Floci answered all three actions with UnsupportedOperation. The parameter now stores its policy with an id and a hash of the document. PutResourcePolicy rejects a Standard-tier parameter, a policy over 1024 bytes and a document that is not a JSON object with the documented errors. GetResourcePolicies pages with MaxResults (1 to 50) and NextToken. An overwriting PutParameter keeps the policy and deleting the parameter removes it. The policy is not evaluated against callers, and no AWS RAM resource share is created. --- docs/services/ssm.md | 18 ++ .../services/iam/ResourceArnBuilder.java | 12 + .../floci/services/ssm/SsmJsonHandler.java | 84 +++++++ .../floci/services/ssm/SsmService.java | 134 ++++++++++ .../floci/services/ssm/model/Parameter.java | 6 + .../ssm/model/ParameterResourcePolicy.java | 14 ++ .../services/iam/ResourceArnBuilderTest.java | 17 ++ ...cePolicyIamEnforcementIntegrationTest.java | 98 ++++++++ .../ssm/SsmResourcePolicyIntegrationTest.java | 229 ++++++++++++++++++ 9 files changed, 612 insertions(+) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterResourcePolicy.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIamEnforcementIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIntegrationTest.java diff --git a/docs/services/ssm.md b/docs/services/ssm.md index 2b6889817f..790a8c5028 100644 --- a/docs/services/ssm.md +++ b/docs/services/ssm.md @@ -22,6 +22,9 @@ | `AddTagsToResource` | Tag a parameter | | `ListTagsForResource` | List tags on a parameter | | `RemoveTagsFromResource` | Remove tags from a parameter | +| `PutResourcePolicy` | Attach or update the resource policy of an Advanced-tier parameter | +| `GetResourcePolicies` | List the resource policy attached to a parameter | +| `DeleteResourcePolicy` | Remove a parameter's resource policy | | `DescribePatchBaselines` | List AWS-owned predefined patch baselines (filter by `OWNER`, `OPERATING_SYSTEM`, `NAME_PREFIX`) | | `GetDefaultPatchBaseline` | Get the default patch baseline id for an operating system | @@ -198,6 +201,21 @@ parameter. Cross-account shared parameters are not modeled. Secrets Manager references continue to use `/aws/reference/secretsmanager/`, not a parameter ARN. +## Parameter Resource Policies + +`PutResourcePolicy`, `GetResourcePolicies` and `DeleteResourcePolicy` take the parameter ARN as +`ResourceArn`. Only an Advanced-tier parameter can have a policy, and it has at most one; a +`SecureString` encrypted with the default `aws/ssm` key cannot have one. +`PutResourcePolicy` returns the policy's `PolicyId` and `PolicyHash`; updating or deleting the +policy takes both, and a hash that is no longer current fails with +`ResourcePolicyConflictException`. A policy over 1024 bytes fails with +`ResourcePolicyLimitExceededException`, and a document that is not a JSON object with +`MalformedResourcePolicyDocumentException`. An overwriting `PutParameter` keeps the policy, and +is refused with `ResourcePolicyInvalidParameterException` when it would leave the policy on a +parameter that could not take one; deleting the parameter removes it. With IAM enforcement on, the three actions are checked against +the parameter `ResourceArn` names. Floci stores the policy but does not evaluate it against callers +or create the AWS RAM resource share AWS makes for a shared parameter. + ## Parameter Types All AWS parameter types are accepted: `String`, `StringList`, `SecureString`. diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 76ff3a6da1..e845bf31cd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -78,6 +78,10 @@ public class ResourceArnBuilder { /** The segment a tagging route names before the ARN it tags, which it captures whole, slashes included. */ private static final String API_GATEWAY_TAGS_SEGMENT = "tags"; + /** The SSM actions whose {@code ResourceArn} names the parameter they act on, in place of {@code Name}. */ + private static final Set SSM_RESOURCE_POLICY_ACTIONS = + Set.of("PutResourcePolicy", "GetResourcePolicies", "DeleteResourcePolicy"); + private final ObjectMapper objectMapper; /** * Looked up lazily through a provider: this builder is constructed by the enforcement filter, @@ -1759,6 +1763,14 @@ public class ResourceArnBuilder { private String buildSsmArn(ContainerRequestContext ctx, String region, String accountId) { JsonNode json = readJsonBody(ctx); if (json != null && json.isObject()) { + String operation = IamActionRegistry.targetOperation(ctx); + if (operation != null && SSM_RESOURCE_POLICY_ACTIONS.contains(operation) + && json.hasNonNull("ResourceArn")) { + String resourceArn = json.get("ResourceArn").asText().trim(); + if (AwsArnUtils.isArnFor(resourceArn, "ssm")) { + return resourceArn; + } + } if (json.hasNonNull("Name")) { String name = json.get("Name").asText().trim(); if (!name.isEmpty()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java index c90def8a90..cd059b9f6c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java @@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ssm.model.CommandInvocation; import io.github.hectorvent.floci.services.ssm.model.InstanceInformation; import io.github.hectorvent.floci.services.ssm.model.Parameter; import io.github.hectorvent.floci.services.ssm.model.ParameterHistory; +import io.github.hectorvent.floci.services.ssm.model.ParameterResourcePolicy; import io.github.hectorvent.floci.services.ssm.model.ParameterStringFilter; import io.github.hectorvent.floci.services.ssm.model.PatchBaselineIdentity; import io.github.hectorvent.floci.services.ssm.model.ServiceSetting; @@ -74,6 +75,9 @@ public class SsmJsonHandler { case "AddTagsToResource" -> handleAddTagsToResource(request, region); case "ListTagsForResource" -> handleListTagsForResource(request, region); case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(request, region); + case "PutResourcePolicy" -> handlePutResourcePolicy(request, region); + case "GetResourcePolicies" -> handleGetResourcePolicies(request, region); + case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region); // Run Command (public API) case "SendCommand" -> handleSendCommand(request, region); case "GetCommandInvocation" -> handleGetCommandInvocation(request, region); @@ -1227,6 +1231,86 @@ public class SsmJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private static final int GET_RESOURCE_POLICIES_MAX_RESULTS = 50; + private static final String GET_RESOURCE_POLICIES_TOKEN = "GetResourcePolicies:"; + private static final String POLICY_PATTERN = "^(?!\\s*$).+"; + + private Response handlePutResourcePolicy(JsonNode request, String region) { + String resourceArn = optionalString(request, "ResourceArn"); + String policy = optionalString(request, "Policy"); + List violations = new ArrayList<>(); + addResourceArnViolation(violations, resourceArn); + if (policy == null) { + violations.add(SmithyValidationErrors.notNull("policy")); + } else if (policy.isBlank()) { + violations.add(SmithyValidationErrors.pattern("policy", policy, POLICY_PATTERN)); + } + if (!violations.isEmpty()) { + throw SsmService.validationErrors(violations); + } + + ParameterResourcePolicy stored = ssmService.putResourcePolicy(resourceArn, policy, + optionalText(request, "PolicyId"), optionalText(request, "PolicyHash"), region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("PolicyId", stored.policyId()); + response.put("PolicyHash", stored.policyHash()); + return Response.ok(response).build(); + } + + private Response handleGetResourcePolicies(JsonNode request, String region) { + String resourceArn = optionalString(request, "ResourceArn"); + List violations = new ArrayList<>(); + addResourceArnViolation(violations, resourceArn); + if (!violations.isEmpty()) { + throw SsmService.validationErrors(violations); + } + PageRequest pageRequest = pageRequest(request, GET_RESOURCE_POLICIES_MAX_RESULTS); + + PaginatedResult page = page(pageRequest, + ssmService.getResourcePolicies(resourceArn, region), ParameterResourcePolicy::policyId, + GET_RESOURCE_POLICIES_MAX_RESULTS, + GET_RESOURCE_POLICIES_TOKEN + ssmService.accountId() + ":" + region + ":" + resourceArn); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode policies = response.putArray("Policies"); + for (ParameterResourcePolicy p : page.items()) { + policies.addObject() + .put("PolicyId", p.policyId()) + .put("PolicyHash", p.policyHash()) + .put("Policy", p.policy()); + } + putNextToken(response, page); + return Response.ok(response).build(); + } + + private Response handleDeleteResourcePolicy(JsonNode request, String region) { + String resourceArn = optionalString(request, "ResourceArn"); + String policyId = optionalString(request, "PolicyId"); + String policyHash = optionalString(request, "PolicyHash"); + List violations = new ArrayList<>(); + addResourceArnViolation(violations, resourceArn); + if (policyId == null) { + violations.add(SmithyValidationErrors.notNull("policyId")); + } + if (policyHash == null) { + violations.add(SmithyValidationErrors.notNull("policyHash")); + } + if (!violations.isEmpty()) { + throw SsmService.validationErrors(violations); + } + + ssmService.deleteResourcePolicy(resourceArn, policyId, policyHash, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private static void addResourceArnViolation(List violations, String resourceArn) { + String violation = resourceArn == null + ? SmithyValidationErrors.notNull("resourceArn") + : SmithyValidationErrors.lengthOutOfRange("resourceArn", resourceArn, 20, 2048); + if (violation != null) { + violations.add(violation); + } + } + private ObjectNode parameterToNode(Parameter p) { ObjectNode node = objectMapper.createObjectNode(); node.put("Name", p.getName()); diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java index 8cb56c8f6c..66de904666 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java @@ -1,6 +1,8 @@ package io.github.hectorvent.floci.services.ssm; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -10,6 +12,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.DeadlineCharSequence; +import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.resource.ExplorerResource; @@ -24,6 +27,7 @@ import io.github.hectorvent.floci.services.secretsmanager.model.Secret; import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion; import io.github.hectorvent.floci.services.ssm.model.Parameter; import io.github.hectorvent.floci.services.ssm.model.ParameterHistory; +import io.github.hectorvent.floci.services.ssm.model.ParameterResourcePolicy; import io.github.hectorvent.floci.services.ssm.model.ParameterStringFilter; import io.github.hectorvent.floci.services.ssm.model.PatchBaselineIdentity; import io.github.hectorvent.floci.services.ssm.model.ServiceSetting; @@ -69,6 +73,9 @@ public class SsmService implements ResourceProvider { private static final String TAG_KEY_REGEX = "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$"; private static final Pattern TAG_KEY_PATTERN = Pattern.compile(TAG_KEY_REGEX); private static final int MAX_TAG_KEY_LENGTH = 128; + private static final int MAX_RESOURCE_POLICY_BYTES = 1024; + private static final ObjectMapper POLICY_JSON = new ObjectMapper() + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); /** The tail AWS appends to every rejected parameter name, whichever prefix the operation reserves. */ private static final String PARAMETER_NAME_FORMAT_RULE = "If formed as a path, it can consist of sub-paths " + "divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following " @@ -332,6 +339,10 @@ public class SsmService implements ResourceProvider { } else if (tags != null && !tags.isEmpty()) { parameter.setTags(new HashMap<>(tags)); } + if (existing != null && existing.getResourcePolicy() != null) { + requireResourcePolicyEligible(parameter); + parameter.setResourcePolicy(existing.getResourcePolicy()); + } parameterStore.put(storageKey, parameter); addHistory(storageKey, parameter); @@ -1104,6 +1115,129 @@ public class SsmService implements ResourceProvider { LOG.debugv("Removed tags from parameter: {0}", resourceId); } + /** + * Attaches or replaces the parameter's resource policy. A parameter holds one policy, so + * replacing it takes the current {@code policyId} and {@code policyHash}, which keeps two + * writers from overwriting each other. + */ + public synchronized ParameterResourcePolicy putResourcePolicy(String resourceArn, String policy, + String policyId, String policyHash, + String region) { + Parameter parameter = resourcePolicyParameter(resourceArn, region); + requireResourcePolicyEligible(parameter); + if (policy.getBytes(StandardCharsets.UTF_8).length > MAX_RESOURCE_POLICY_BYTES) { + throw new AwsException("ResourcePolicyLimitExceededException", + "A policy can't be greater than " + MAX_RESOURCE_POLICY_BYTES + " bytes in size.", 400); + } + if (!isJsonObject(policy)) { + throw new AwsException("MalformedResourcePolicyDocumentException", + "The specified policy document is malformed or invalid.", 400); + } + + ParameterResourcePolicy current = parameter.getResourcePolicy(); + String id; + if (current == null) { + if (policyId != null) { + throw resourcePolicyNotFound(); + } + id = UUID.randomUUID().toString(); + } else { + if (policyId == null) { + throw resourcePolicyConflict(); + } + requireCurrentPolicy(current, policyId, policyHash); + id = current.policyId(); + } + + ParameterResourcePolicy updated = new ParameterResourcePolicy(id, policyHash(policy), policy); + parameter.setResourcePolicy(updated); + parameterStore.put(regionKey(region, parameter.getName()), parameter); + LOG.debugv("Put resource policy {0} on parameter: {1}", id, parameter.getName()); + return updated; + } + + public List getResourcePolicies(String resourceArn, String region) { + ParameterResourcePolicy policy = resourcePolicyParameter(resourceArn, region).getResourcePolicy(); + return policy == null ? List.of() : List.of(policy); + } + + public synchronized void deleteResourcePolicy(String resourceArn, String policyId, String policyHash, + String region) { + Parameter parameter = resourcePolicyParameter(resourceArn, region); + ParameterResourcePolicy current = parameter.getResourcePolicy(); + if (current == null) { + throw resourcePolicyNotFound(); + } + requireCurrentPolicy(current, policyId, policyHash); + parameter.setResourcePolicy(null); + parameterStore.put(regionKey(region, parameter.getName()), parameter); + LOG.debugv("Deleted resource policy {0} from parameter: {1}", policyId, parameter.getName()); + } + + /** Only a parameter ARN in the caller's account and region addresses a parameter here. */ + private Parameter resourcePolicyParameter(String resourceArn, String region) { + Optional parameter = AwsArnUtils.isArnFor(resourceArn, "ssm") + ? parameterStore.get(regionKey(region, parameterReadName(resourceArn, region))) + : Optional.empty(); + return parameter.orElseThrow(() -> new AwsException("ResourceNotFoundException", + "The specified parameter to be shared could not be found.", 400)); + } + + /** + * Only an advanced-tier parameter, and not a SecureString under the default aws/ssm key, can have a + * resource policy, whether one is being attached or an overwrite would keep one. + */ + private static void requireResourcePolicyEligible(Parameter parameter) { + if (!"Advanced".equals(tierOf(parameter))) { + throw new AwsException("ResourcePolicyInvalidParameterException", + "Only parameters in the advanced tier can have a resource policy.", 400); + } + if (isDefaultSsmKey(keyIdOf(parameter))) { + throw new AwsException("ResourcePolicyInvalidParameterException", + "A SecureString parameter encrypted with the default aws/ssm key can't have a resource policy.", + 400); + } + } + + /** The AWS managed aws/ssm key, named by its alias or by the alias's ARN. */ + private static boolean isDefaultSsmKey(String keyId) { + return DEFAULT_SSM_KEY_ID.equals(keyId) + || keyId != null && AwsArnUtils.isArnFor(keyId, "kms") && keyId.endsWith(":" + DEFAULT_SSM_KEY_ID); + } + + private static void requireCurrentPolicy(ParameterResourcePolicy current, String policyId, String policyHash) { + if (!current.policyId().equals(policyId)) { + throw resourcePolicyNotFound(); + } + if (!current.policyHash().equals(policyHash)) { + throw resourcePolicyConflict(); + } + } + + private static AwsException resourcePolicyConflict() { + return new AwsException("ResourcePolicyConflictException", + "The hash provided in the call doesn't match the stored hash.", 400); + } + + private static AwsException resourcePolicyNotFound() { + return new AwsException("ResourcePolicyNotFoundException", + "No policies with the specified policy ID and hash could be found.", 400); + } + + private static boolean isJsonObject(String policy) { + try { + JsonNode document = POLICY_JSON.readTree(policy); + return document != null && document.isObject(); + } catch (JsonProcessingException e) { + return false; + } + } + + /** AWS documents the hash only as a value to send back; this one changes whenever the document does. */ + private static String policyHash(String policy) { + return Digests.sha256Hex(policy); + } + /** * The stored name a parameter name or ARN addresses. The ARN carries a leading slash the stored name may * lack, so {@code parameter/foo} falls back to {@code foo} when only {@code foo} is stored. A version or diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java index 464416ceab..d5b53353ff 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java @@ -53,6 +53,9 @@ public class Parameter { @JsonProperty("Policies") private List policies; + @JsonProperty("ResourcePolicy") + private ParameterResourcePolicy resourcePolicy; + @JsonProperty("Tags") @JsonAlias({"tags", "Tags"}) private Map tags = new HashMap<>(); @@ -111,6 +114,9 @@ public class Parameter { public List getPolicies() { return policies; } public void setPolicies(List policies) { this.policies = policies; } + public ParameterResourcePolicy getResourcePolicy() { return resourcePolicy; } + public void setResourcePolicy(ParameterResourcePolicy resourcePolicy) { this.resourcePolicy = resourcePolicy; } + public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterResourcePolicy.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterResourcePolicy.java new file mode 100644 index 0000000000..95944d02af --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterResourcePolicy.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.ssm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The resource-based policy PutResourcePolicy attaches to a parameter. A later update or delete + * must present the current {@code policyHash}. + */ +@RegisterForReflection +public record ParameterResourcePolicy(@JsonProperty("PolicyId") String policyId, + @JsonProperty("PolicyHash") String policyHash, + @JsonProperty("Policy") String policy) { +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 1146affbc7..9bcd860e87 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -1447,6 +1447,23 @@ class ResourceArnBuilderTest { assertEquals("arn:aws:ssm:us-east-1:000000000000:parameter/config-key", arn); } + @Test + void ssmResourcePolicyActionsActOnTheParameterTheirResourceArnNames() { + when(ctx.getHeaderString("X-Amz-Target")).thenReturn("AmazonSSM.PutResourcePolicy"); + setJsonBody("{\"ResourceArn\":\"arn:aws:ssm:us-east-1:000000000000:parameter/prod/db\",\"Policy\":\"{}\"}"); + assertEquals("arn:aws:ssm:us-east-1:000000000000:parameter/prod/db", + builder.build("ssm", ctx, "us-east-1", "000000000000")); + + // Any other action acts on the parameter its handler reads, its Name, whatever else the body carries. + when(ctx.getHeaderString("X-Amz-Target")).thenReturn("AmazonSSM.GetParameter"); + setJsonBody("{\"Name\":\"/prod/db\",\"ResourceArn\":\"arn:aws:ssm:us-east-1:000000000000:parameter/dev/db\"}"); + assertEquals("arn:aws:ssm:us-east-1:000000000000:parameter/prod/db", + builder.build("ssm", ctx, "us-east-1", "000000000000")); + when(ctx.getHeaderString("X-Amz-Target")).thenReturn(null); + assertEquals("arn:aws:ssm:us-east-1:000000000000:parameter/prod/db", + builder.build("ssm", ctx, "us-east-1", "000000000000")); + } + // ── SQS ───────────────────────────────────────────────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIamEnforcementIntegrationTest.java new file mode 100644 index 0000000000..de88af34ca --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIamEnforcementIntegrationTest.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.ssm; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ssm.SsmClient; +import software.amazon.awssdk.services.ssm.model.ParameterTier; +import software.amazon.awssdk.services.ssm.model.ParameterType; +import software.amazon.awssdk.services.ssm.model.SsmException; + +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** The resource policy actions are checked against the parameter their {@code ResourceArn} names. */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class SsmResourcePolicyIamEnforcementIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String POLICY = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::111122223333:root"},"Action":"ssm:GetParameter","Resource":"*"}]}"""; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aDenyOnAParameterPathRefusesThePolicyActionsOnIt() { + String prefix = "/iam-resource-policy-" + UUID.randomUUID(); + String denied = prefix + "/prod/db"; + String allowed = prefix + "/dev/db"; + try (SsmClient root = AwsTestClients.create(SsmClient.builder(), ACCOUNT, Region.US_EAST_1)) { + try { + String deniedArn = advancedParameter(root, denied); + String allowedArn = advancedParameter(root, allowed); + String userName = "ssm-policy-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(ACCOUNT, "iam"), userName); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(ACCOUNT, "iam"), userName, "p", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"ssm:*","Resource":"*"}, + {"Effect":"Deny","Action":["ssm:PutResourcePolicy","ssm:GetResourcePolicies", + "ssm:DeleteResourcePolicy","ssm:GetParameter"], + "Resource":"arn:aws:ssm:*:*:parameter%s/prod/*"}]}""" + .formatted(prefix)); + try (SsmClient user = AwsTestClients.create(SsmClient.builder(), credentials.accessKeyId(), + Region.US_EAST_1)) { + assertDoesNotThrow(() -> user.putResourcePolicy(r -> r.resourceArn(allowedArn).policy(POLICY))); + assertDoesNotThrow(() -> user.getResourcePolicies(r -> r.resourceArn(allowedArn))); + + SsmException put = assertThrows(SsmException.class, + () -> user.putResourcePolicy(r -> r.resourceArn(deniedArn).policy(POLICY))); + assertEquals("AccessDeniedException", put.awsErrorDetails().errorCode()); + SsmException get = assertThrows(SsmException.class, + () -> user.getResourcePolicies(r -> r.resourceArn(deniedArn))); + assertEquals("AccessDeniedException", get.awsErrorDetails().errorCode()); + } + + // Another action still acts on the parameter its handler reads, whatever ResourceArn it carries. + given() + .header("Authorization", auth(credentials.accessKeyId(), "ssm")) + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .contentType("application/x-amz-json-1.1") + .body("{\"Name\":\"" + denied + "\",\"ResourceArn\":\"" + allowedArn + "\"}") + .when().post("/") + .then().statusCode(400).body(containsString("AccessDeniedException")); + } finally { + root.deleteParameter(r -> r.name(denied)); + root.deleteParameter(r -> r.name(allowed)); + } + } + } + + private static String advancedParameter(SsmClient root, String name) { + root.putParameter(r -> r.name(name).type(ParameterType.STRING).value("v").tier(ParameterTier.ADVANCED)); + return root.getParameter(r -> r.name(name)).parameter().arn(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIntegrationTest.java new file mode 100644 index 0000000000..e875be52bb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmResourcePolicyIntegrationTest.java @@ -0,0 +1,229 @@ +package io.github.hectorvent.floci.services.ssm; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ssm.SsmClient; +import software.amazon.awssdk.services.ssm.model.GetResourcePoliciesResponse; +import software.amazon.awssdk.services.ssm.model.GetResourcePoliciesResponseEntry; +import software.amazon.awssdk.services.ssm.model.MalformedResourcePolicyDocumentException; +import software.amazon.awssdk.services.ssm.model.ParameterTier; +import software.amazon.awssdk.services.ssm.model.ParameterType; +import software.amazon.awssdk.services.ssm.model.PutResourcePolicyResponse; +import software.amazon.awssdk.services.ssm.model.ResourceNotFoundException; +import software.amazon.awssdk.services.ssm.model.ResourcePolicyConflictException; +import software.amazon.awssdk.services.ssm.model.ResourcePolicyInvalidParameterException; +import software.amazon.awssdk.services.ssm.model.ResourcePolicyLimitExceededException; +import software.amazon.awssdk.services.ssm.model.ResourcePolicyNotFoundException; +import software.amazon.awssdk.services.ssm.model.SsmException; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class SsmResourcePolicyIntegrationTest { + + private static final String POLICY = """ + {"Version":"2012-10-17","Statement":[{"Sid":"Share","Effect":"Allow",\ + "Principal":{"AWS":"arn:aws:iam::111122223333:root"},\ + "Action":["ssm:GetParameter"],"Resource":"*"}]}"""; + private static final String UPDATED_POLICY = POLICY.replace("\"Share\"", "\"ShareUpdated\""); + + private SsmClient ssm; + + @BeforeEach + void createClient() { + ssm = AwsTestClients.create(SsmClient.builder(), "000000000000", Region.US_EAST_1); + } + + @AfterEach + void closeClient() { + ssm.close(); + } + + @Test + void putGetUpdateAndDeleteTheParameterPolicy() { + String arn = parameter(ParameterTier.ADVANCED); + assertTrue(policies(arn).isEmpty()); + + PutResourcePolicyResponse created = ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY)); + assertFalse(created.policyId().isEmpty()); + assertFalse(created.policyHash().isEmpty()); + List attached = policies(arn); + assertEquals(1, attached.size()); + assertEquals(created.policyId(), attached.get(0).policyId()); + assertEquals(created.policyHash(), attached.get(0).policyHash()); + assertEquals(POLICY, attached.get(0).policy()); + + PutResourcePolicyResponse updated = ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(UPDATED_POLICY) + .policyId(created.policyId()).policyHash(created.policyHash())); + assertEquals(created.policyId(), updated.policyId()); + assertNotEquals(created.policyHash(), updated.policyHash()); + assertEquals(UPDATED_POLICY, policies(arn).get(0).policy()); + assertEquals(updated.policyHash(), policies(arn).get(0).policyHash()); + + ssm.deleteResourcePolicy(r -> r.resourceArn(arn) + .policyId(updated.policyId()).policyHash(updated.policyHash())); + assertTrue(policies(arn).isEmpty()); + } + + @Test + void aMissingOrStaleHashConflictsWithTheStoredPolicy() { + String arn = parameter(ParameterTier.ADVANCED); + PutResourcePolicyResponse created = ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY)); + PutResourcePolicyResponse updated = ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(UPDATED_POLICY) + .policyId(created.policyId()).policyHash(created.policyHash())); + + assertThrows(ResourcePolicyConflictException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY))); + assertThrows(ResourcePolicyConflictException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY) + .policyHash(updated.policyHash()))); + assertThrows(ResourcePolicyConflictException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY) + .policyId(created.policyId()).policyHash(created.policyHash()))); + assertThrows(ResourcePolicyConflictException.class, + () -> ssm.deleteResourcePolicy(r -> r.resourceArn(arn) + .policyId(created.policyId()).policyHash(created.policyHash()))); + assertThrows(ResourcePolicyNotFoundException.class, + () -> ssm.deleteResourcePolicy(r -> r.resourceArn(arn) + .policyId(UUID.randomUUID().toString()).policyHash(updated.policyHash()))); + + List attached = policies(arn); + assertEquals(1, attached.size()); + assertEquals(updated.policyHash(), attached.get(0).policyHash()); + assertEquals(UPDATED_POLICY, attached.get(0).policy()); + } + + @Test + void aPolicyIdIsNotFoundOnAParameterWithoutAPolicy() { + String arn = parameter(ParameterTier.ADVANCED); + + assertThrows(ResourcePolicyNotFoundException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY) + .policyId(UUID.randomUUID().toString()).policyHash("hash"))); + assertThrows(ResourcePolicyNotFoundException.class, + () -> ssm.deleteResourcePolicy(r -> r.resourceArn(arn) + .policyId(UUID.randomUUID().toString()).policyHash("hash"))); + assertTrue(policies(arn).isEmpty()); + } + + @Test + void anUnknownParameterIsResourceNotFound() { + String missing = parameter(ParameterTier.ADVANCED) + "-missing"; + + assertThrows(ResourceNotFoundException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(missing).policy(POLICY))); + assertThrows(ResourceNotFoundException.class, + () -> ssm.getResourcePolicies(r -> r.resourceArn(missing))); + assertThrows(ResourceNotFoundException.class, + () -> ssm.deleteResourcePolicy(r -> r.resourceArn(missing).policyId("id").policyHash("hash"))); + } + + @Test + void anOverwriteKeepsThePolicyAndADeleteRemovesIt() { + String name = "/resource-policy/" + UUID.randomUUID(); + String arn = parameter(name, ParameterTier.ADVANCED); + PutResourcePolicyResponse created = ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY)); + + ssm.putParameter(r -> r.name(name).value("v2").type(ParameterType.STRING).overwrite(true)); + List attached = policies(arn); + assertEquals(1, attached.size()); + assertEquals(created.policyId(), attached.get(0).policyId()); + + ssm.deleteParameter(r -> r.name(name)); + parameter(name, ParameterTier.ADVANCED); + assertTrue(policies(arn).isEmpty()); + } + + @Test + void onlyAnAdvancedParameterTakesAPolicy() { + String arn = parameter(ParameterTier.STANDARD); + + assertThrows(ResourcePolicyInvalidParameterException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY))); + assertTrue(policies(arn).isEmpty()); + } + + @Test + void anOverwriteThatWouldLeaveThePolicyOnAnIneligibleParameterIsRefused() { + String name = "/resource-policy/" + UUID.randomUUID(); + String arn = parameter(name, ParameterTier.ADVANCED); + ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY)); + + assertThrows(ResourcePolicyInvalidParameterException.class, () -> ssm.putParameter(r -> r.name(name) + .value("v2").type(ParameterType.STRING).tier(ParameterTier.STANDARD).overwrite(true))); + assertThrows(ResourcePolicyInvalidParameterException.class, () -> ssm.putParameter(r -> r.name(name) + .value("v2").type(ParameterType.SECURE_STRING).overwrite(true))); + assertEquals("v1", ssm.getParameter(r -> r.name(name)).parameter().value()); + assertEquals(1, policies(arn).size()); + } + + @Test + void aSecureStringUnderTheDefaultKeyTakesNoPolicy() { + for (String keyId : new String[] {null, "arn:aws:kms:us-east-1:000000000000:alias/aws/ssm"}) { + String name = "/resource-policy/" + UUID.randomUUID(); + ssm.putParameter(r -> r.name(name).value("secret").type(ParameterType.SECURE_STRING).keyId(keyId) + .tier(ParameterTier.ADVANCED)); + String arn = ssm.getParameter(r -> r.name(name)).parameter().arn(); + + assertThrows(ResourcePolicyInvalidParameterException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY))); + assertTrue(policies(arn).isEmpty()); + } + } + + @Test + void rejectsAnOversizedOrMalformedPolicy() { + String arn = parameter(ParameterTier.ADVANCED); + String oversized = "{\"Version\":\"2012-10-17\",\"Statement\":[],\"Sid\":\"" + "x".repeat(1024) + "\"}"; + + assertThrows(ResourcePolicyLimitExceededException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(oversized))); + assertThrows(MalformedResourcePolicyDocumentException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy("not-json"))); + assertThrows(MalformedResourcePolicyDocumentException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy("[]"))); + assertThrows(MalformedResourcePolicyDocumentException.class, + () -> ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY + " {}"))); + assertTrue(policies(arn).isEmpty()); + } + + @Test + void getResourcePoliciesValidatesMaxResults() { + String arn = parameter(ParameterTier.ADVANCED); + ssm.putResourcePolicy(r -> r.resourceArn(arn).policy(POLICY)); + + for (int maxResults : new int[] {0, 51}) { + SsmException e = assertThrows(SsmException.class, + () -> ssm.getResourcePolicies(r -> r.resourceArn(arn).maxResults(maxResults))); + assertEquals("ValidationException", e.awsErrorDetails().errorCode()); + } + GetResourcePoliciesResponse page = ssm.getResourcePolicies(r -> r.resourceArn(arn).maxResults(1)); + assertEquals(1, page.policies().size()); + assertNull(page.nextToken()); + } + + private String parameter(ParameterTier tier) { + return parameter("/resource-policy/" + UUID.randomUUID(), tier); + } + + private String parameter(String name, ParameterTier tier) { + ssm.putParameter(r -> r.name(name).value("v1").type(ParameterType.STRING).tier(tier)); + return ssm.getParameter(r -> r.name(name)).parameter().arn(); + } + + private List policies(String arn) { + return ssm.getResourcePolicies(r -> r.resourceArn(arn)).policies(); + } +}