From aef8416c4b72e981d8d32b8c1f0faebae7398114 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:01:17 +0100 Subject: [PATCH] fix(ssm): associate a document another account shared with the caller (#8646) CreateAssociation now resolves a document ARN in another account to that account's document when its owner shared it with the caller through ModifyDocumentPermission, and answers InvalidDocument for one that is not shared, is of another partition or does not exist. UpdateAssociation checks a new DocumentVersion through the same lookup. With IAM enforcement on, reachedInItsAccount has the request checked on the owner's document ARN alone, so the caller's identity policy must allow that ARN. Closes #8364 --- docs/services/ssm.md | 4 + .../io/floci/aws/services/ssm/SsmService.java | 65 ++++++++++- .../aws/services/ssm/SsmServiceTest.java | 60 ++++++++++ ...redDocumentAssociationIntegrationTest.java | 103 ++++++++++++++++++ 4 files changed, 230 insertions(+), 2 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/ssm/SsmSharedDocumentAssociationIntegrationTest.java diff --git a/docs/services/ssm.md b/docs/services/ssm.md index 1dd665ca5a..c5e3671cc8 100644 --- a/docs/services/ssm.md +++ b/docs/services/ssm.md @@ -35,6 +35,10 @@ the `DocumentDescription` of `CreateDocument`, `UpdateDocument` and `DescribeDoc without its leading `/`. `CreateDocument` is checked against `document/`, and `CreateAssociation` against the association and the `document/` its `Name` gives. +`CreateAssociation` also runs a document another account shared with the caller through +`ModifyDocumentPermission`, given in `Name` by its ARN. With IAM enforcement on, the caller's policy must allow +that ARN. A document the owner did not share is `InvalidDocument`. + `GetParameters` returns successful parameters alphabetically by `Name`, preserving the selected versions and labels. diff --git a/src/main/java/io/floci/aws/services/ssm/SsmService.java b/src/main/java/io/floci/aws/services/ssm/SsmService.java index 30d8503305..2b7adb5dfe 100644 --- a/src/main/java/io/floci/aws/services/ssm/SsmService.java +++ b/src/main/java/io/floci/aws/services/ssm/SsmService.java @@ -19,6 +19,7 @@ import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -57,6 +58,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns { private static final Logger LOG = Logger.getLogger(SsmService.class); private static final String PUBLIC_PARAMETER_PREFIX = "/aws/service/"; + private static final String DOCUMENT_PREFIX = "document/"; private static final String ECS_AL2023_RECOMMENDED = "/aws/service/ecs/optimized-ami/amazon-linux-2023/recommended"; private static final String ECS_AL2023_ARM64_RECOMMENDED = @@ -1509,6 +1511,51 @@ public class SsmService implements ResourceProvider, StoredResourceArns { // raises InvalidDocument instead of silently minting or reporting share state for // a document that does not exist. + /** + * The accounts the document of that name in the owner's account and Region is shared with; empty when there is no + * such document. + */ + List documentSharedWith(String ownerAccountId, String name, String region) { + String key = regionKey(region, name); + if (AccountAwareStorageBackend.readInAccount(documentStore, ownerAccountId, key).isEmpty()) { + return List.of(); + } + return AccountAwareStorageBackend.readInAccount(documentPermissionStore, ownerAccountId, key) + .map(List::copyOf).orElse(List.of()); + } + + /** + * The document an association runs: the caller's by its name or ARN, or, by its ARN, one another account shared + * with the caller. A document of another account not shared with the caller does not exist for it. + */ + private SsmDocument associatedDocument(String nameOrArn, String region) { + if (!AwsArnUtils.looksLikeArn(nameOrArn)) { + return getDocument(nameOrArn, region); + } + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(nameOrArn); + } catch (IllegalArgumentException e) { + LOG.debugv("Failed to parse document name as ARN: {0}", nameOrArn); + return getDocument(nameOrArn, region); + } + if (!"ssm".equals(arn.service()) || !arn.resource().startsWith(DOCUMENT_PREFIX) + || !arn.region().equals(region) || !arn.partition().equals(regionResolver.partitionForRegion(region))) { + return getDocument(nameOrArn, region); + } + String name = arn.resource().substring(DOCUMENT_PREFIX.length()); + String caller = regionResolver.getAccountId(); + if (arn.accountId().equals(caller)) { + return getDocument(name, region); + } + if (!documentSharedWith(arn.accountId(), name, region).contains(caller)) { + throw new AwsException("InvalidDocument", "Document " + nameOrArn + " does not exist.", 400); + } + return AccountAwareStorageBackend.readInAccount(documentStore, arn.accountId(), regionKey(region, name)) + .orElseThrow(() -> new AwsException("InvalidDocument", "Document " + nameOrArn + " does not exist.", + 400)); + } + public SsmDocument getDocument(String name, String region) { SsmDocument document = documentStore.get(regionKey(region, name)) .orElseThrow(() -> new AwsException("InvalidDocument", @@ -1728,7 +1775,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns { Map tags, String region) { validateTagKeys(tags); - SsmDocument document = getDocument(name, region); + SsmDocument document = associatedDocument(name, region); validateDocumentVersion(document, documentVersion); if (instanceId != null && !instanceId.isBlank()) { @@ -1795,7 +1842,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns { "The specified association does not exist.", 400)); if (documentVersion != null) { - validateDocumentVersion(getDocument(association.getName(), region), documentVersion); + validateDocumentVersion(associatedDocument(association.getName(), region), documentVersion); } if (associationName != null) association.setAssociationName(associationName); @@ -2056,6 +2103,20 @@ public class SsmService implements ResourceProvider, StoredResourceArns { return "ssm"; } + /** A document another account owns, which {@code CreateAssociation} runs from that account when it is shared. */ + @Override + public boolean reachedInItsAccount(String arn, String accountId) { + if (!AwsArnUtils.isArnFor(arn, "ssm")) { + return false; + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + return !parsed.accountId().isEmpty() && !parsed.accountId().equals(accountId) + && parsed.resource().startsWith(DOCUMENT_PREFIX) + && parsed.partition().equals(regionResolver.partitionForRegion(parsed.region())) + && AccountAwareStorageBackend.readInAccount(documentStore, parsed.accountId(), + regionKey(parsed.region(), parsed.resource().substring(DOCUMENT_PREFIX.length()))).isPresent(); + } + /** * The {@code parameter/} ARN a legacy {@code parameter} ARN of the caller's partition, Region and * account names, which the tagging operations act on as {@link #parameterTagName} reads it; empty for any other diff --git a/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java b/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java index 9ea50c505e..129edd84f4 100644 --- a/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java +++ b/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.services.eventbridge.EventBridgeService; @@ -1965,4 +1966,63 @@ class SsmServiceTest { ssmService.describeParameters(List.of(filter), "us-east-1")); assertEquals(errorCode, ex.getErrorCode()); } + + private static final String CALLER = "000000000000"; + private static final String OWNER = "100000008364"; + + @Test + void anAssociationOnASharedDocumentGivenByItsArnTakesANewDocumentVersion() { + AccountAwareStorageBackend> permissions = AccountAwareStorageBackend.inMemory(CALLER); + AccountAwareStorageBackend documents = AccountAwareStorageBackend.inMemory(CALLER); + documents.putForAccount(OWNER, "us-east-1::shared", ownerDocument("shared")); + permissions.putForAccount(OWNER, "us-east-1::shared", List.of(CALLER)); + SsmService service = sharingService(permissions, documents); + SsmAssociation association = service.createAssociation("arn:aws:ssm:us-east-1:" + OWNER + ":document/shared", + null, null, "i-0123456789abcdef0", null, null, null, "us-east-1"); + + SsmAssociation updated = service.updateAssociation(association.getAssociationId(), null, "1", null, null, + null, null, null, null, "us-east-1"); + + assertEquals("1", updated.getDocumentVersion()); + } + + @Test + void aSharedDocumentGivenByAnArnOfAnotherPartitionDoesNotExist() { + AccountAwareStorageBackend> permissions = AccountAwareStorageBackend.inMemory(CALLER); + AccountAwareStorageBackend documents = AccountAwareStorageBackend.inMemory(CALLER); + documents.putForAccount(OWNER, "us-east-1::shared", ownerDocument("shared")); + permissions.putForAccount(OWNER, "us-east-1::shared", List.of(CALLER)); + SsmService service = sharingService(permissions, documents); + String otherPartition = "arn:aws-cn:ssm:us-east-1:" + OWNER + ":document/shared"; + + AwsException e = assertThrows(AwsException.class, () -> service.createAssociation(otherPartition, + null, null, "i-0123456789abcdef0", null, null, null, "us-east-1")); + assertEquals("InvalidDocument", e.getErrorCode()); + assertFalse(service.reachedInItsAccount(otherPartition, CALLER)); + } + + @Test + void aDocumentSharedBeforeStorageWasScopedByAccountIsStillShared() { + InMemoryStorage> permissions = new InMemoryStorage<>(); + InMemoryStorage documents = new InMemoryStorage<>(); + permissions.put("us-east-1::legacy", List.of(OWNER)); + documents.put("us-east-1::legacy", ownerDocument("legacy")); + SsmService service = sharingService(new AccountAwareStorageBackend<>(permissions, null, CALLER), + new AccountAwareStorageBackend<>(documents, null, CALLER)); + + assertEquals(List.of(OWNER), service.documentSharedWith(CALLER, "legacy", "us-east-1")); + } + + private static SsmService sharingService(StorageBackend> permissions, + StorageBackend documents) { + return new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(), permissions, documents, + new InMemoryStorage<>(), new InMemoryStorage<>(), 5, new RegionResolver("us-east-1", CALLER)); + } + + private static SsmDocument ownerDocument(String name) { + SsmDocument document = new SsmDocument(name, "{}", "Command"); + document.setDocumentVersion(1); + document.setVersions(new LinkedHashMap<>(Map.of("1", "{}"))); + return document; + } } diff --git a/src/test/java/io/floci/aws/services/ssm/SsmSharedDocumentAssociationIntegrationTest.java b/src/test/java/io/floci/aws/services/ssm/SsmSharedDocumentAssociationIntegrationTest.java new file mode 100644 index 0000000000..f8d2e25ce7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ssm/SsmSharedDocumentAssociationIntegrationTest.java @@ -0,0 +1,103 @@ +package io.floci.aws.services.ssm; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +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.DocumentType; +import software.amazon.awssdk.services.ssm.model.SsmException; + +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** An account associates a document another account shared with it by giving the document's ARN. */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class SsmSharedDocumentAssociationIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String OWNER = "100000008364"; + private static final String CONTENT = "{\"schemaVersion\":\"2.2\",\"description\":\"d\",\"mainSteps\":[{" + + "\"action\":\"aws:runShellScript\",\"name\":\"s\",\"inputs\":{\"runCommand\":[\"echo hi\"]}}]}"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aSharedDocumentIsAssociatedByItsArnAndAnUnsharedOneIsNot() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String shared = "shared-" + suffix; + String unshared = "unshared-" + suffix; + try (SsmClient owner = AwsTestClients.create(SsmClient.builder(), OWNER, Region.US_EAST_1)) { + try { + createDocument(owner, shared); + createDocument(owner, unshared); + owner.modifyDocumentPermission(r -> r.name(shared).permissionType("Share").accountIdsToAdd(ACCOUNT)); + String userName = "ssm-shared-" + suffix; + 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:CreateAssociation", + "Resource":["arn:aws:ssm:*:*:association/*","%s","%s"]}]}""" + .formatted(arn(shared), arn(unshared))); + try (SsmClient user = AwsTestClients.create(SsmClient.builder(), credentials.accessKeyId(), + Region.US_EAST_1)) { + assertDoesNotThrow(() -> associate(user, arn(shared))); + SsmException missing = assertThrows(SsmException.class, () -> associate(user, arn(unshared))); + assertEquals("InvalidDocument", missing.awsErrorDetails().errorCode()); + } + } finally { + owner.deleteDocument(r -> r.name(shared).force(true)); + owner.deleteDocument(r -> r.name(unshared).force(true)); + } + } + } + + @Test + void aSharedDocumentIsNotAssociatedWithoutAnIdentityPolicyNamingIt() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String shared = "shared-ungranted-" + suffix; + try (SsmClient owner = AwsTestClients.create(SsmClient.builder(), OWNER, Region.US_EAST_1)) { + try { + createDocument(owner, shared); + owner.modifyDocumentPermission(r -> r.name(shared).permissionType("Share").accountIdsToAdd(ACCOUNT)); + String userName = "ssm-ungranted-" + suffix; + 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:CreateAssociation", + "Resource":"arn:aws:ssm:*:*:association/*"}]}"""); + try (SsmClient user = AwsTestClients.create(SsmClient.builder(), credentials.accessKeyId(), + Region.US_EAST_1)) { + SsmException denied = assertThrows(SsmException.class, () -> associate(user, arn(shared))); + assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode()); + } + } finally { + owner.deleteDocument(r -> r.name(shared).force(true)); + } + } + } + + private static String arn(String document) { + return "arn:aws:ssm:us-east-1:" + OWNER + ":document/" + document; + } + + private static void createDocument(SsmClient owner, String name) { + owner.createDocument(r -> r.name(name).documentType(DocumentType.COMMAND).content(CONTENT)); + } + + private static void associate(SsmClient ssm, String document) { + ssm.createAssociation(r -> r.name(document).targets(t -> t.key("InstanceIds").values("i-0123456789abcdef0"))); + } +}