feat(ssm): document lifecycle, share permissions, and account-scoped service settings (#2629)

* feat(ssm): document share permissions for DescribeDocumentPermission and ModifyDocumentPermission

* feat(ssm): model documents with GetDocument, CreateDocument, and UpdateDocument

LZA's session-manager-settings custom resource reads SSM-SessionManagerRunShell
via GetDocument, creates it (DocumentType Session) when the InvalidDocument error
code comes back, and updates it otherwise, tolerating DuplicateDocumentContent.
Model documents region-scoped in a persistent store and serve all three ops with
those exact error codes so the AWS SDK maps them to its typed exceptions.

* feat(ssm): add DescribeDocument and DeleteDocument

Completes the document lifecycle alongside the existing Get/Create/Update
operations. DeleteDocument raises InvalidDocument for a name that was never
stored rather than succeeding silently.

* feat(ssm): account-scoped service settings (Get/Update/ResetServiceSetting)

LZA's ssm-block-public-document-sharing module assumes a role into every member account and reads/updates /ssm/documents/console/public-sharing-permission. Model the ServiceSetting API with per-account per-region state, account defaults (Enable for public sharing), and ServiceSettingNotFound for unknown ids, matching real AWS. Closes the gap reported upstream as floci-io/floci#2235.

* fix(ssm): raise InvalidDocument when a permission op names an unknown document

DescribeDocumentPermission returned an empty list and ModifyDocumentPermission
happily created share state for a document that does not exist. Botocore models
InvalidDocument on both operations, and this branch now has a real documentStore,
so the two halves of the service no longer need to disagree about whether a
document exists: both permission methods resolve the document first.

This also settles the ownership half. Only the document's owner may share a
document in AWS. Ownership here is the storage partition: documentStore is an
AccountAwareStorageBackend keyed by the caller's account from RequestContext,
the same resolution RegionResolver.getAccountId() performs, so getDocument can
only resolve a document in the caller's own partition and a non-owner gets
InvalidDocument. Deriving the guard from the partition rather than a second
stored owner field keeps check and storage scope from ever disagreeing.

* fix(ssm): validate Name and PermissionType on the document operations

Every new document handler read request.path("Name").asText(), which yields ""
— not null — for an absent field, so a request with Name omitted built the key
"<region>|" and surfaced "Document  does not exist." with a blank in the message.
Botocore constrains DocumentName to ^[a-zA-Z0-9_\-.]{3,128}$, making a blank name
a constraint violation, which AWS reports as ValidationException. No per-operation
error fits: InvalidDocument means "does not exist" rather than "malformed", and
CreateDocument does not model it at all — so unlike the ACM guards, a generic
ValidationException here is the modeled shape, not a substitute for one.

PermissionType was accepted and ignored on both document-permission operations.
Botocore models DocumentPermissionType as an enum whose only value is Share and
models InvalidPermissionType on both operations, so a present-but-unsupported
value now raises InvalidPermissionType. PermissionType is a required member, so
an absent one is treated as a missing required member (ValidationException), the
same as an absent Name.

Both guards run before the store lookup. The integration test for the permission
round-trip now creates the document it shares, and a two-account test asserts a
non-owner cannot share another account's document.

* fix(ssm): enforce the modelled DocumentType and AccountIds constraints

Two values the document operations read and store were never checked
against the model.

CreateDocument took DocumentType verbatim. Botocore models it as a
17-value enum; floci stored whatever arrived and echoed it back from
GetDocument, DescribeDocument and the create response, so a document
could sit in the store with a type neither AWS nor the emulator
recognises.

ModifyDocumentPermission wrote AccountIdsToAdd straight into the
document's share list. The model caps each list at 20 members and pins
the member pattern to (?i)all|[0-9]{12}; without either check a share
with "not-an-account" reported success and DescribeDocumentPermission
faithfully echoed it back.

Both are rejected with ValidationException, matching the treatment the
blank Name and the PermissionType enum already get.

* fix(ssm): enforce the DocumentName pattern instead of only rejecting blank names

requireDocumentName rejected an absent or blank Name but let any other
value through unvalidated, so a name violating botocore's
^[a-zA-Z0-9_\-.]{3,128}$ pattern (e.g. containing a slash) was accepted
and persisted instead of raising ValidationException. The lifecycle
integration test's document names started with "/", so they had to be
corrected to comply with the pattern now that it is actually enforced.

* fix(ssm): reject missing or non-string Content on CreateDocument/UpdateDocument

Content was read via JsonNode.asText(), which silently returns "" for
either an absent member or a non-textual node (e.g. a JSON object sent
instead of a JSON/YAML-encoded string). That let CreateDocument store
an empty document, and let UpdateDocument erase existing content while
still incrementing the version. Botocore models DocumentContent as a
required string with min length 1 on both operations, so this now
raises ValidationException before either service call is made.

* fix(ssm): clear share permissions when a document is deleted

deleteDocument removed only the document record, leaving its entry in
documentPermissionStore behind. A document recreated later under the
same account, region, and name inherited the deleted document's
account shares instead of starting unshared.

* fix(ssm): validate SettingId is present on service-setting operations

Get/Update/ResetServiceSetting read SettingId via JsonNode.asText(),
which yields "" for an absent member. That blank id was then treated
as an unknown setting (ServiceSettingNotFound) rather than a missing
required member (ValidationException) — the same distinction already
drawn for the document operations' Name field.

* fix(ssm): reject non-string document Name in CreateDocument

asText() silently coerces a numeric or boolean Name to its string form, so it can satisfy the DocumentName pattern and reach create/lookup instead of raising ValidationException for the wrong-typed member.

* fix(ssm): serialize document create/delete/share against each other

deleteDocument's trailing documentPermissionStore.delete ran unsynchronized against createDocument and modifyDocumentPermission, so a delete overlapping a same-name recreate-and-share could wipe out the recreated document's new shares.

* fix(ssm): widen GetDocument/DescribeDocument Name pattern for ARN reads

Botocore models a wider Name pattern (adds ':' and '/') on GetDocument
and DescribeDocument than on the other five document operations, since
DescribeDocument accepts the document's full ARN when reading a
document shared from another account. The shared DOCUMENT_NAME pattern
rejected that shape on both read operations, so an ARN naming a
caller's own document — an ordinary way to call GetDocument — failed
with ValidationException instead of resolving (or, for an unknown
document, InvalidDocument).
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 17:20:56 -04:00
1 parent 9b9e7f56a2
commit 7f6b875136
7 files changed
+1859 -1

No files matched your search

@@ -0,0 +1,115 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SsmDocumentLifecycleIntegrationTest {
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createAndDescribeDocument() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "floci-test-doc",
"DocumentType": "Command",
"Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("DocumentDescription.Name", equalTo("floci-test-doc"))
.body("DocumentDescription.DocumentType", equalTo("Command"));
given()
.header("X-Amz-Target", "AmazonSSM.DescribeDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "floci-test-doc"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Document.Name", equalTo("floci-test-doc"))
.body("Document.DocumentType", equalTo("Command"));
}
@Test
@Order(2)
void deleteDocument() {
given()
.header("X-Amz-Target", "AmazonSSM.DeleteDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "floci-test-doc"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(3)
void describeMissingDocument() {
given()
.header("X-Amz-Target", "AmazonSSM.DescribeDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "floci-nonexistent-doc"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
}
@Test
@Order(4)
void createDocumentRejectsNonStringName() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": 123,
"DocumentType": "Command",
"Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@@ -235,6 +235,109 @@ class SsmIntegrationTest {
.body("InvalidParameters", contains("/missing"));
}
// ── Service settings (LZA ssm-block-public-document-sharing) ──
@Test
@Order(11)
void getServiceSettingDefault() {
given()
.header("X-Amz-Target", "AmazonSSM.GetServiceSetting")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "SettingId": "/ssm/documents/console/public-sharing-permission" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ServiceSetting.SettingId", equalTo("/ssm/documents/console/public-sharing-permission"))
.body("ServiceSetting.SettingValue", equalTo("Enable"))
.body("ServiceSetting.Status", equalTo("Default"))
.body("ServiceSetting.ARN", endsWith(":servicesetting/ssm/documents/console/public-sharing-permission"))
.body("ServiceSetting.LastModifiedDate", notNullValue());
}
@Test
@Order(12)
void updateServiceSetting() {
given()
.header("X-Amz-Target", "AmazonSSM.UpdateServiceSetting")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"SettingId": "/ssm/documents/console/public-sharing-permission",
"SettingValue": "Disable"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.GetServiceSetting")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "SettingId": "/ssm/documents/console/public-sharing-permission" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ServiceSetting.SettingValue", equalTo("Disable"))
.body("ServiceSetting.Status", equalTo("Customized"));
}
@Test
@Order(13)
void resetServiceSetting() {
given()
.header("X-Amz-Target", "AmazonSSM.ResetServiceSetting")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "SettingId": "/ssm/documents/console/public-sharing-permission" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ServiceSetting.SettingValue", equalTo("Enable"))
.body("ServiceSetting.Status", equalTo("Default"));
}
@Test
@Order(14)
void getUnknownServiceSettingReturnsError() {
given()
.header("X-Amz-Target", "AmazonSSM.GetServiceSetting")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "SettingId": "/ssm/bogus/does-not-exist" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ServiceSettingNotFound"));
}
@Test
void serviceSettingOperations_missingSettingIdReturnsValidationException() {
for (String target : new String[]{"GetServiceSetting", "UpdateServiceSetting", "ResetServiceSetting"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "SettingValue": "Enable" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
// ── Issue #956: DescribePatchBaselines / GetDefaultPatchBaseline (AWS-owned predefined) ──
@Test
@@ -334,6 +437,56 @@ class SsmIntegrationTest {
.body("$", not(hasKey("NextToken")));
}
@Test
void documentPermission_modifyAndDescribeRoundTrip() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "AwsAccelerator-SessionManagerLogging",
"DocumentType": "Session",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "AwsAccelerator-SessionManagerLogging",
"PermissionType": "Share",
"AccountIdsToAdd": ["444444444444"]
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "AwsAccelerator-SessionManagerLogging",
"PermissionType": "Share"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("AccountIds", hasItem("444444444444"))
.body("AccountSharingInfoList[0].AccountId", equalTo("444444444444"))
.body("AccountSharingInfoList[0].SharedDocumentVersion", notNullValue());
}
@Test
void listAssociations_returnsEmptyList() {
given()
@@ -374,4 +527,631 @@ class SsmIntegrationTest {
.statusCode(400)
.body("__type", equalTo("UnsupportedOperation"));
}
@Test
void getDocument_unknownReturnsInvalidDocument() {
given()
.header("X-Amz-Target", "AmazonSSM.GetDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "No-Such-Document"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
}
@Test
void document_createGetUpdateRoundTrip() {
// Create — mirrors LZA's session-manager-settings Lambda (DocumentType Session)
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "SSM-SessionManagerRunShell",
"DocumentType": "Session",
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":false}}"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("DocumentDescription.Name", equalTo("SSM-SessionManagerRunShell"))
.body("DocumentDescription.DocumentType", equalTo("Session"))
.body("DocumentDescription.DocumentVersion", equalTo("1"))
.body("DocumentDescription.Status", equalTo("Active"));
given()
.header("X-Amz-Target", "AmazonSSM.GetDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "SSM-SessionManagerRunShell"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Name", equalTo("SSM-SessionManagerRunShell"))
.body("DocumentType", equalTo("Session"))
.body("DocumentVersion", equalTo("1"))
.body("Content", containsString("runAsEnabled"));
// Update with changed content bumps the version
given()
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "SSM-SessionManagerRunShell",
"DocumentVersion": "$LATEST",
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("DocumentDescription.DocumentVersion", equalTo("2"));
// Update with identical content fails DuplicateDocumentContent
given()
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "SSM-SessionManagerRunShell",
"DocumentVersion": "$LATEST",
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("DuplicateDocumentContent"));
}
// ── Document parameter validation (botocore: DocumentName ^[a-zA-Z0-9_\-.]{3,128}$) ──
@Test
void documentOperations_blankNameReturnsValidationException() {
for (String target : new String[]{
"GetDocument", "DescribeDocument", "DeleteDocument",
"CreateDocument", "UpdateDocument"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@Test
void documentOperations_nameViolatingPatternReturnsValidationException() {
for (String target : new String[]{"DeleteDocument", "CreateDocument", "UpdateDocument"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/floci/test-doc",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
// GetDocument/DescribeDocument model a wider Name pattern than the other five document
// operations (botocore: ^[a-zA-Z0-9_\-.:/]{3,128}$, vs ^[a-zA-Z0-9_\-.]{3,128}$ elsewhere) —
// DescribeDocument's own docs say Name is the document's ARN when reading a document shared
// from another account, so the read path must accept ARN shapes even though the other five
// reject them.
@Test
void getDocumentAndDescribeDocument_acceptArnShapedName() {
for (String target : new String[]{"GetDocument", "DescribeDocument"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "arn:aws:ssm:us-east-1:000000000000:document/No-Such-Document"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
}
}
@Test
void getDocumentAndDescribeDocument_stillRejectTrulyInvalidName() {
for (String target : new String[]{"GetDocument", "DescribeDocument"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "not a valid name!"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@Test
void documentPermissionOperations_blankNameReturnsValidationException() {
for (String target : new String[]{
"ModifyDocumentPermission", "DescribeDocumentPermission"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "PermissionType": "Share" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@Test
void createDocument_missingContentReturnsValidationException() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Floci-Missing-Content-Doc" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createDocument_nonTextContentReturnsValidationException() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Object-Content-Doc",
"Content": {"schemaVersion": "2.2", "mainSteps": []}
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void updateDocument_missingContentReturnsValidationExceptionWithoutErasingExistingContent() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Update-Missing-Content-Doc",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Floci-Update-Missing-Content-Doc" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
given()
.header("X-Amz-Target", "AmazonSSM.GetDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Floci-Update-Missing-Content-Doc" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Content", containsString("schemaVersion"));
}
// ── PermissionType (botocore: required, enum with the single value "Share") ──
@Test
void documentPermissionOperations_rejectUnsupportedPermissionType() {
for (String target : new String[]{
"ModifyDocumentPermission", "DescribeDocumentPermission"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Doc-That-Was-Never-Created",
"PermissionType": "Own"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidPermissionType"));
}
}
@Test
void documentPermissionOperations_missingPermissionTypeIsRejected() {
for (String target : new String[]{
"ModifyDocumentPermission", "DescribeDocumentPermission"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Doc-That-Was-Never-Created" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@Test
void deleteDocument_clearsSharePermissionsSoARecreatedDocumentStartsUnshared() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Recreated-Shared-Doc",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Recreated-Shared-Doc",
"PermissionType": "Share",
"AccountIdsToAdd": ["444444444444"]
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.DeleteDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Floci-Recreated-Shared-Doc" }
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Recreated-Shared-Doc",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Floci-Recreated-Shared-Doc",
"PermissionType": "Share"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("AccountIds", empty());
}
// ── Permission ops agree with the document store (botocore models InvalidDocument) ──
@Test
void documentPermissionOperations_unknownDocumentReturnsInvalidDocument() {
for (String target : new String[]{
"ModifyDocumentPermission", "DescribeDocumentPermission"}) {
given()
.header("X-Amz-Target", "AmazonSSM." + target)
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Doc-That-Was-Never-Created",
"PermissionType": "Share",
"AccountIdsToAdd": ["444444444444"]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
}
}
/**
* Only the document's owner may share it. Ownership is the storage partition:
* the document store is account-aware, so another account's ModifyDocumentPermission
* cannot resolve the document and gets InvalidDocument — AWS's own answer for a
* document the caller cannot see.
*/
@Test
void modifyDocumentPermission_otherAccountCannotShareOwnersDocument() {
String ownerAuth = "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/ssm/aws4_request,"
+ " SignedHeaders=host, Signature=abc";
String otherAuth = "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/ssm/aws4_request,"
+ " SignedHeaders=host, Signature=abc";
given()
.header("Authorization", ownerAuth)
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Owner-Only-Document",
"DocumentType": "Session",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("Authorization", otherAuth)
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Owner-Only-Document",
"PermissionType": "Share",
"AccountIdsToAdd": ["444444444444"]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
// …and the owner's own share state is untouched.
given()
.header("Authorization", ownerAuth)
.header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Owner-Only-Document",
"PermissionType": "Share"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("AccountIds", not(hasItem("444444444444")));
}
// ── DocumentType (botocore: enum, 17 values) ──
@Test
void createDocument_rejectsAnUnmodelledDocumentType() {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Bad-Document-Type",
"DocumentType": "NotADocumentType",
"Content": "{\\"schemaVersion\\":\\"1.0\\"}"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
// The rejected document must not have been stored.
given()
.header("X-Amz-Target", "AmazonSSM.GetDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Bad-Document-Type" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidDocument"));
}
@Test
void createDocument_acceptsEveryModelledDocumentType() {
String[] documentTypes = {
"Command", "Policy", "Automation", "Session", "Package",
"ApplicationConfiguration", "ApplicationConfigurationSchema", "DeploymentStrategy",
"ChangeCalendar", "Automation.ChangeTemplate", "ProblemAnalysis",
"ProblemAnalysisTemplate", "CloudFormation", "ConformancePackTemplate",
"QuickSetup", "ManualApprovalPolicy", "AutoApprovalPolicy"};
for (int i = 0; i < documentTypes.length; i++) {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Modelled-Type-%d",
"DocumentType": "%s",
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"n\\":%d}"
}
""".formatted(i, documentTypes[i], i))
.when()
.post("/")
.then()
.statusCode(200)
.body("DocumentDescription.DocumentType", equalTo(documentTypes[i]));
}
}
// ── AccountIdsToAdd/Remove (botocore: list max 20, member (?i)all|[0-9]{12}) ──
@Test
void modifyDocumentPermission_rejectsAnAccountIdThatIsNotAnAccountId() {
createSharableDocument("Bad-Account-Id-Document");
given()
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Bad-Account-Id-Document",
"PermissionType": "Share",
"AccountIdsToAdd": ["not-an-account"]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
// Nothing may have been shared.
given()
.header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "Bad-Account-Id-Document", "PermissionType": "Share" }
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("AccountIds", not(hasItem("not-an-account")));
}
/** The model spells the wildcard {@code (?i)all}, so "all" and "All" are both account ids. */
@Test
void modifyDocumentPermission_acceptsTheAllWildcard() {
createSharableDocument("All-Wildcard-Document");
given()
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "All-Wildcard-Document",
"PermissionType": "Share",
"AccountIdsToAdd": ["All"]
}
""")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void modifyDocumentPermission_rejectsMoreThanTwentyAccountIds() {
createSharableDocument("Too-Many-Accounts-Document");
StringBuilder ids = new StringBuilder();
for (int i = 0; i < 21; i++) {
ids.append(i == 0 ? "" : ",").append("\"%012d\"".formatted(100000000000L + i));
}
given()
.header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "Too-Many-Accounts-Document",
"PermissionType": "Share",
"AccountIdsToAdd": [%s]
}
""".formatted(ids))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
private static void createSharableDocument(String name) {
given()
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "%s",
"DocumentType": "Session",
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"doc\\":\\"%s\\"}"
}
""".formatted(name, name))
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -1,13 +1,26 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
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.ServiceSetting;
import io.github.hectorvent.floci.services.ssm.model.SsmDocument;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.*;
@@ -18,12 +31,63 @@ class SsmServiceTest {
@BeforeEach
void setUp() {
ssmService = new SsmService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
5
);
}
@Test
void describeDocumentPermissionEmptyByDefault() {
ssmService.createDocument("MyDoc", "{}", "Command", "us-east-1");
List<String> accountIds = ssmService.describeDocumentPermission("MyDoc", "us-east-1");
assertTrue(accountIds.isEmpty());
}
@Test
void describeDocumentPermissionUnknownDocumentThrowsInvalidDocument() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.describeDocumentPermission("NoSuchDoc", "us-east-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
@Test
void modifyDocumentPermissionUnknownDocumentThrowsInvalidDocument() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.modifyDocumentPermission("NoSuchDoc",
List.of("111111111111"), List.of(), "us-east-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
@Test
void modifyDocumentPermissionAddsAndRemovesAccounts() {
String region = "us-east-1";
ssmService.createDocument("ShareDoc", "{}", "Command", region);
ssmService.modifyDocumentPermission("ShareDoc",
List.of("111111111111", "222222222222"), List.of(), region);
assertEquals(List.of("111111111111", "222222222222"),
ssmService.describeDocumentPermission("ShareDoc", region));
ssmService.modifyDocumentPermission("ShareDoc",
List.of(), List.of("111111111111"), region);
assertEquals(List.of("222222222222"),
ssmService.describeDocumentPermission("ShareDoc", region));
}
@Test
void modifyDocumentPermissionIsIdempotentAndRegionScoped() {
String region = "us-east-1";
ssmService.createDocument("Doc", "{}", "Command", region);
ssmService.modifyDocumentPermission("Doc", List.of("333333333333"), List.of(), region);
ssmService.modifyDocumentPermission("Doc", List.of("333333333333"), List.of(), region);
assertEquals(List.of("333333333333"), ssmService.describeDocumentPermission("Doc", region));
// The document itself is region-scoped, so the other region has no document to describe.
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.describeDocumentPermission("Doc", "eu-west-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
@Test
void putAndGetParameter() {
String region = "eu-west-1";
@@ -146,4 +210,248 @@ class SsmServiceTest {
assertEquals("v3", history.get(0).getValue());
assertEquals("v7", history.get(4).getValue());
}
@Test
void getDocumentUnknownThrowsInvalidDocument() {
// The AWS SDK maps this code to its InvalidDocument exception class;
// LZA's session-manager-settings Lambda branches on it to create the doc.
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.getDocument("SSM-SessionManagerRunShell", "us-east-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
@Test
void createAndGetDocument() {
String region = "us-east-1";
String content = "{\"schemaVersion\":\"1.0\",\"inputs\":{\"runAsEnabled\":false}}";
ssmService.createDocument("SSM-SessionManagerRunShell", content, "Session", region);
SsmDocument doc = ssmService.getDocument("SSM-SessionManagerRunShell", region);
assertEquals("SSM-SessionManagerRunShell", doc.getName());
assertEquals(content, doc.getContent());
assertEquals("Session", doc.getDocumentType());
assertEquals(1, doc.getDocumentVersion());
assertEquals("Active", doc.getStatus());
}
@Test
void createDocumentTwiceThrowsAlreadyExists() {
String region = "us-east-1";
ssmService.createDocument("Doc", "{}", "Command", region);
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.createDocument("Doc", "{}", "Command", region));
assertEquals("DocumentAlreadyExists", ex.getErrorCode());
}
@Test
void updateDocumentBumpsVersion() {
String region = "us-east-1";
ssmService.createDocument("Doc", "{\"a\":1}", "Session", region);
SsmDocument updated = ssmService.updateDocument("Doc", "{\"a\":2}", region);
assertEquals(2, updated.getDocumentVersion());
assertEquals("{\"a\":2}", ssmService.getDocument("Doc", region).getContent());
}
@Test
void updateDocumentSameContentThrowsDuplicateDocumentContent() {
String region = "us-east-1";
ssmService.createDocument("Doc", "{\"a\":1}", "Session", region);
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.updateDocument("Doc", "{\"a\":1}", region));
assertEquals("DuplicateDocumentContent", ex.getErrorCode());
}
@Test
void updateDocumentUnknownThrowsInvalidDocument() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.updateDocument("Missing", "{}", "us-east-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
@Test
void documentsAreRegionScoped() {
ssmService.createDocument("Doc", "{}", "Session", "us-east-1");
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.getDocument("Doc", "eu-west-1"));
assertEquals("InvalidDocument", ex.getErrorCode());
}
// ── Service settings (LZA ssm-block-public-document-sharing) ──
private static final String PUBLIC_SHARING = "/ssm/documents/console/public-sharing-permission";
@Test
void getServiceSettingReturnsDefaultWhenNeverCustomized() {
ServiceSetting setting = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1");
assertEquals(PUBLIC_SHARING, setting.getSettingId());
assertEquals("Enable", setting.getSettingValue());
assertEquals("Default", setting.getStatus());
assertEquals("arn:aws:ssm:us-east-1:000000000000:servicesetting" + PUBLIC_SHARING,
setting.getArn());
assertNotNull(setting.getLastModifiedDate());
assertNotNull(setting.getLastModifiedUser());
}
@Test
void updateServiceSettingCustomizesValueAndStatus() {
ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1");
ServiceSetting setting = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1");
assertEquals("Disable", setting.getSettingValue());
assertEquals("Customized", setting.getStatus());
assertNotNull(setting.getLastModifiedDate());
}
@Test
void resetServiceSettingRestoresDefault() {
ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1");
ServiceSetting reset = ssmService.resetServiceSetting(PUBLIC_SHARING, "us-east-1");
assertEquals("Enable", reset.getSettingValue());
ServiceSetting after = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1");
assertEquals("Enable", after.getSettingValue());
assertEquals("Default", after.getStatus());
}
@Test
void unknownServiceSettingThrows() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.getServiceSetting("/ssm/bogus/does-not-exist", "us-east-1"));
assertEquals("ServiceSettingNotFound", ex.getErrorCode());
}
@Test
void updateUnknownServiceSettingThrows() {
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.updateServiceSetting("/ssm/bogus/does-not-exist", "x", "us-east-1"));
assertEquals("ServiceSettingNotFound", ex.getErrorCode());
}
@Test
void serviceSettingsAreRegionScoped() {
ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1");
ServiceSetting other = ssmService.getServiceSetting(PUBLIC_SHARING, "eu-west-1");
assertEquals("Enable", other.getSettingValue());
assertEquals("Default", other.getStatus());
}
@Test
void serviceSettingsAreAccountScoped() {
// LZA assumes a role into each member account and updates the setting
// there; a shared store must still keep per-account values separate.
InMemoryStorage<String, ServiceSetting> sharedSettings = new InMemoryStorage<>();
SsmService accountA = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
sharedSettings, 5, new RegionResolver("us-east-1", "111111111111"));
SsmService accountB = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
sharedSettings, 5, new RegionResolver("us-east-1", "222222222222"));
accountA.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1");
assertEquals("Disable", accountA.getServiceSetting(PUBLIC_SHARING, "us-east-1").getSettingValue());
ServiceSetting b = accountB.getServiceSetting(PUBLIC_SHARING, "us-east-1");
assertEquals("Enable", b.getSettingValue());
assertEquals("arn:aws:ssm:us-east-1:222222222222:servicesetting" + PUBLIC_SHARING, b.getArn());
}
/**
* A delete that overlaps a same-name recreate-and-share must not let the delete's
* trailing permission cleanup wipe out the recreated document's new shares.
* {@code documentStore.delete} is instrumented to signal once it starts and then
* block, giving a concurrent createDocument/modifyDocumentPermission call a window
* to run before deleteDocument reaches documentPermissionStore.delete.
*/
@Test
void deleteOverlappingRecreateAndShareDoesNotLoseNewPermission() throws Exception {
String region = "us-east-1";
String name = "RaceDoc";
CountDownLatch deleteStarted = new CountDownLatch(1);
CountDownLatch releaseDelete = new CountDownLatch(1);
InMemoryStorage<String, SsmDocument> realDocumentStore = new InMemoryStorage<>();
StorageBackend<String, SsmDocument> instrumentedDocumentStore =
new StorageBackend<>() {
@Override
public void put(String key, SsmDocument value) {
realDocumentStore.put(key, value);
}
@Override
public Optional<SsmDocument> get(String key) {
return realDocumentStore.get(key);
}
@Override
public void delete(String key) {
realDocumentStore.delete(key);
deleteStarted.countDown();
try {
releaseDelete.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public List<SsmDocument> scan(Predicate<String> keyFilter) {
return realDocumentStore.scan(keyFilter);
}
@Override
public Set<String> keys() {
return realDocumentStore.keys();
}
@Override
public void flush() {
realDocumentStore.flush();
}
@Override
public void load() {
realDocumentStore.load();
}
@Override
public void clear() {
realDocumentStore.clear();
}
};
SsmService service = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), instrumentedDocumentStore,
new InMemoryStorage<>(), 5, new RegionResolver(region, "000000000000"));
service.createDocument(name, "{}", "Command", region);
service.modifyDocumentPermission(name, List.of("111111111111"), List.of(), region);
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> deleteFuture = pool.submit(() -> service.deleteDocument(name, region));
assertTrue(deleteStarted.await(10, TimeUnit.SECONDS),
"delete must finish removing the document before this window opens");
Future<?> recreateFuture = pool.submit(() -> {
service.createDocument(name, "{}", "Command", region);
service.modifyDocumentPermission(name, List.of("222222222222"), List.of(), region);
return null;
});
assertThrows(TimeoutException.class, () -> recreateFuture.get(300, TimeUnit.MILLISECONDS),
"recreate-and-share must be serialized against the in-flight delete, "
+ "not interleaved with it");
releaseDelete.countDown();
deleteFuture.get(10, TimeUnit.SECONDS);
recreateFuture.get(10, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
assertEquals(List.of("222222222222"), service.describeDocumentPermission(name, region),
"the delete's trailing permission cleanup must not remove the recreated "
+ "document's new share");
}
}