fix(ssm): return KeyId, AllowedPattern, Tier and Policies from DescribeParameters (#5263)

* fix(ssm): return KeyId, AllowedPattern, Tier and Policies from DescribeParameters

PutParameter accepted KeyId, AllowedPattern, Tier and Policies and dropped
them, so DescribeParameters never returned them and the Tier and KeyId
filters matched hardcoded defaults. Tools that read these attributes back,
such as Terraform's aws_ssm_parameter, saw a permanent diff.

PutParameter now stores the four attributes and DescribeParameters returns
them: KeyId for a SecureString (alias/aws/ssm when none was given), Tier
always, AllowedPattern and Policies when set. Intelligent-Tiering resolves
to Advanced when policies are present or the value exceeds 4 KB, an
overwrite that omits Tier keeps the existing tier, and a value that does
not match AllowedPattern is rejected with ParameterPatternMismatchException.

* fix(ssm): keep policies across overwrites and reject malformed patterns

An overwrite that omitted Policies cleared them; AWS keeps existing
policies until new policies or an empty list are sent. A malformed
AllowedPattern escaped as a 500 instead of InvalidAllowedPatternException,
and a Policies string that parsed to something other than a JSON array was
accepted as an empty list instead of rejected.

* fix(ssm): treat an empty AllowedPattern as no pattern

The Terraform AWS provider sends AllowedPattern="" on every PutParameter
when allowed_pattern is unset. An empty regex matches only the empty
string, so every aws_ssm_parameter apply failed with
ParameterPatternMismatchException (compat-terraform / compat-opentofu).

* fix(ssm): treat empty optional PutParameter fields as absent

The Terraform AWS provider sends every optional PutParameter field and
leaves unset ones as an empty string, which AWS reads as absent. Read
KeyId, AllowedPattern, Tier and Policies through one helper so a blank
value falls back to the default instead of being stored or validated.

* fix(ssm): bound AllowedPattern matching and cap its length

PutParameter matches a caller-supplied AllowedPattern against a
caller-supplied Value, so a pattern that backtracks catastrophically
could hold a request thread. Reject patterns over the 1024 characters
the SSM model allows, and match through a deadline-bounded subject that
aborts after one second with InvalidAllowedPatternException.

The deadline subject already lived inside CodePipelineService for
VariableCheck MATCHES; it moves to core.common so both use one copy.

Also cover the Intelligent-Tiering 4096-byte cutoff with ASCII and
multibyte values, and replace inline fully qualified test names with
imports.

* fix(ssm): keep Advanced on Intelligent-Tiering overwrite, validate Tier, serialize PutParameter

An Intelligent-Tiering overwrite with a small value no longer downgrades an
existing Advanced parameter to Standard. Tier outside Standard, Advanced and
Intelligent-Tiering is a ValidationException. putParameter is synchronized like
labelParameterVersion so concurrent overwrites cannot share a version.

* fix(ssm): validate PutParameter before taking the write lock

The tier, tag, name and AllowedPattern checks read only the request, so
they now run before the lock; only the stored-version read and the write
are synchronized. A pattern match running to its one-second deadline no
longer stalls other SSM writers.

The concurrency test now waits for the second overwrite's thread to reach
BLOCKED instead of waiting a fixed 300 ms for a timeout.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-08 20:18:29 -04:00
1 parent 3171b8a745
commit 80f25417b3
7 files changed
+532 -49

No files matched your search

@@ -2,14 +2,19 @@ package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
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 java.time.Duration;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -1637,6 +1642,243 @@ class SsmIntegrationTest {
describeParametersError("{ \"MaxResults\": 51 }", "ValidationException");
}
@Test
void describeParametersReturnsKeyIdAllowedPatternTierAndPolicies() {
String policy = "{\\\"Type\\\":\\\"Expiration\\\",\\\"Version\\\":\\\"1.0\\\","
+ "\\\"Attributes\\\":{\\\"Timestamp\\\":\\\"2099-01-01T00:00:00.000Z\\\"}}";
putFilterFixture("/attr/secure", "SecureString", ", \"KeyId\": \"alias/custom\", \"AllowedPattern\": \"^v$\","
+ " \"Tier\": \"Advanced\", \"Policies\": \"[" + policy + "]\"");
putFilterFixture("/attr/default-key", "SecureString", "");
putFilterFixture("/attr/plain", "String", "");
String policyText = describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr/secure"] }] }
""")
.body("Parameters[0].KeyId", equalTo("alias/custom"))
.body("Parameters[0].AllowedPattern", equalTo("^v$"))
.body("Parameters[0].Tier", equalTo("Advanced"))
.body("Parameters[0].Policies", hasSize(1))
.body("Parameters[0].Policies[0].PolicyType", equalTo("Expiration"))
.body("Parameters[0].Policies[0].PolicyStatus", equalTo("Pending"))
.extract().path("Parameters[0].Policies[0].PolicyText");
assertEquals("2099-01-01T00:00:00.000Z", JsonPath.from(policyText).getString("Attributes.Timestamp"));
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr/default-key"] }] }
""")
.body("Parameters[0].KeyId", equalTo("alias/aws/ssm"))
.body("Parameters[0].Tier", equalTo("Standard"))
.body("Parameters[0]", not(hasKey("AllowedPattern")))
.body("Parameters[0]", not(hasKey("Policies")));
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr/plain"] }] }
""")
.body("Parameters[0]", not(hasKey("KeyId")))
.body("Parameters[0].Tier", equalTo("Standard"));
// The stored tier and key, not the defaults, are what the filters see.
describeParameters("""
{ "ParameterFilters": [
{ "Key": "Name", "Option": "BeginsWith", "Values": ["/attr/"] },
{ "Key": "Tier", "Values": ["Advanced"] }
] }
""")
.body("Parameters.Name", contains("/attr/secure"));
describeParameters("""
{ "ParameterFilters": [
{ "Key": "Name", "Option": "BeginsWith", "Values": ["/attr/"] },
{ "Key": "KeyId", "Values": ["alias/custom"] }
] }
""")
.body("Parameters.Name", contains("/attr/secure"));
// An overwrite that omits Tier keeps the Advanced tier.
putFilterFixture("/attr/secure", "SecureString", ", \"Overwrite\": true");
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr/secure"] }] }
""")
.body("Parameters[0].Version", equalTo(2))
.body("Parameters[0].Tier", equalTo("Advanced"));
}
@Test
void putParameterIntelligentTieringResolvesToAdvancedOnlyWhenNeeded() {
putFilterFixture("/attr-it/small", "String", ", \"Tier\": \"Intelligent-Tiering\"");
putFilterFixture("/attr-it/policy", "String", ", \"Tier\": \"Intelligent-Tiering\", \"Policies\":"
+ " \"[{\\\"Type\\\":\\\"NoChangeNotification\\\",\\\"Version\\\":\\\"1.0\\\","
+ "\\\"Attributes\\\":{\\\"After\\\":\\\"30\\\",\\\"Unit\\\":\\\"Days\\\"}}]\"");
describeParameters("""
{ "ParameterFilters": [{ "Key": "Path", "Values": ["/attr-it"] }] }
""")
.body("Parameters.find { it.Name == '/attr-it/small' }.Tier", equalTo("Standard"))
.body("Parameters.find { it.Name == '/attr-it/policy' }.Tier", equalTo("Advanced"));
}
@Test
void putParameterIntelligentTieringCutsOverAbove4096Utf8Bytes() {
// An e-acute is one char but two UTF-8 bytes, so the multibyte values sit under 4096 chars.
putIntelligentTiering("/attr-it-size/ascii-4096", "a".repeat(4096));
putIntelligentTiering("/attr-it-size/ascii-4097", "a".repeat(4097));
putIntelligentTiering("/attr-it-size/utf8-4096", "\\u00e9".repeat(2048));
putIntelligentTiering("/attr-it-size/utf8-4098", "\\u00e9".repeat(2049));
describeParameters("""
{ "ParameterFilters": [{ "Key": "Path", "Values": ["/attr-it-size"] }] }
""")
.body("Parameters.find { it.Name == '/attr-it-size/ascii-4096' }.Tier", equalTo("Standard"))
.body("Parameters.find { it.Name == '/attr-it-size/ascii-4097' }.Tier", equalTo("Advanced"))
.body("Parameters.find { it.Name == '/attr-it-size/utf8-4096' }.Tier", equalTo("Standard"))
.body("Parameters.find { it.Name == '/attr-it-size/utf8-4098' }.Tier", equalTo("Advanced"));
}
@Test
void putParameterIntelligentTieringOverwriteKeepsAnAdvancedParameterAdvanced() {
putFilterFixture("/attr-it-keep/p", "String", ", \"Tier\": \"Advanced\"");
putFilterFixture("/attr-it-keep/p", "String", ", \"Tier\": \"Intelligent-Tiering\", \"Overwrite\": true");
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr-it-keep/p"] }] }
""")
.body("Parameters[0].Version", equalTo(2))
.body("Parameters[0].Tier", equalTo("Advanced"));
}
@Test
void putParameterRejectsATierOutsideTheEnumAndStoresNothing() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/attr-bad-tier/p", "Value": "v", "Type": "String", "Tier": "Premium" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("Value 'Premium' at 'tier'"));
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr-bad-tier/p"] }] }
""")
.body("Parameters", hasSize(0));
}
private void putIntelligentTiering(String name, String jsonEscapedValue) {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"" + name + "\", \"Value\": \"" + jsonEscapedValue
+ "\", \"Type\": \"String\", \"Tier\": \"Intelligent-Tiering\" }")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void putParameterRejectsAValueOutsideAllowedPattern() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Name": "/attr/pattern", "Value": "nope", "Type": "String", "AllowedPattern": "^v$" }
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterPatternMismatchException"));
}
@Test
void putParameterTreatsAnEmptyAllowedPatternAsNoPattern() {
putFilterFixture("/attr/empty-pattern", "String", ", \"AllowedPattern\": \"\"");
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/attr/empty-pattern"] }] }
""")
.body("Parameters[0].Version", equalTo(1))
.body("Parameters[0]", not(hasKey("AllowedPattern")));
}
@Test
void putParameterOverwriteKeepsPoliciesUntilNewOrEmptyPoliciesAreSent() {
putFilterFixture("/pol/keep", "String", ", \"Tier\": \"Advanced\", \"Policies\":"
+ " \"[{\\\"Type\\\":\\\"NoChangeNotification\\\",\\\"Version\\\":\\\"1.0\\\","
+ "\\\"Attributes\\\":{\\\"After\\\":\\\"30\\\",\\\"Unit\\\":\\\"Days\\\"}}]\"");
String byName = """
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/pol/keep"] }] }
""";
putFilterFixture("/pol/keep", "String", ", \"Overwrite\": true");
describeParameters(byName)
.body("Parameters[0].Version", equalTo(2))
.body("Parameters[0].Policies.PolicyType", contains("NoChangeNotification"));
putFilterFixture("/pol/keep", "String", ", \"Overwrite\": true, \"Policies\": \"[]\"");
describeParameters(byName)
.body("Parameters[0].Version", equalTo(3))
.body("Parameters[0]", not(hasKey("Policies")));
}
@Test
void putParameterRejectsMalformedAllowedPattern() {
putParameterError("""
{ "Name": "/pol/bad-pattern", "Value": "v", "Type": "String", "AllowedPattern": "[" }
""", "InvalidAllowedPatternException");
}
@Test
void putParameterBoundsCatastrophicAllowedPatternBacktracking() {
// Nested groups defeat the JDK's loop memoization; unbounded, this match runs for hours.
String body = "{ \"Name\": \"/pol/redos\", \"Value\": \"" + "a".repeat(40)
+ "!\", \"Type\": \"String\", \"AllowedPattern\": \"^((a+)+)+$\" }";
assertTimeoutPreemptively(Duration.ofSeconds(10),
() -> putParameterError(body, "InvalidAllowedPatternException"));
}
@Test
void putParameterRejectsAllowedPatternOver1024Chars() {
putParameterError("{ \"Name\": \"/pol/long-pattern\", \"Value\": \"a\", \"Type\": \"String\","
+ " \"AllowedPattern\": \"" + "a".repeat(1025) + "\" }", "ValidationException");
}
@Test
void putParameterRejectsPoliciesThatAreNotAJsonArray() {
putParameterError("""
{ "Name": "/pol/bad-policies", "Value": "v", "Type": "String", "Policies": "{}" }
""", "ValidationException");
}
@Test
void putParameterTreatsEmptyOptionalFieldsAsAbsent() {
// Terraform's aws_ssm_parameter sends every optional field, unset ones as "".
putFilterFixture("/empty/plain", "String",
", \"AllowedPattern\": \"\", \"Tier\": \"\", \"Policies\": \"\"");
putFilterFixture("/empty/secure", "SecureString", ", \"KeyId\": \"\", \"AllowedPattern\": \"\"");
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/empty/plain"] }] }
""")
.body("Parameters[0]", not(hasKey("AllowedPattern")))
.body("Parameters[0]", not(hasKey("Policies")))
.body("Parameters[0].Tier", equalTo("Standard"));
describeParameters("""
{ "ParameterFilters": [{ "Key": "Name", "Values": ["/empty/secure"] }] }
""")
.body("Parameters[0].KeyId", equalTo("alias/aws/ssm"))
.body("Parameters[0]", not(hasKey("AllowedPattern")));
}
private void putParameterError(String body, String errorType) {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo(errorType));
}
private void putFilterFixture(String name, String type, String extra) {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
@@ -23,6 +23,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -786,6 +787,76 @@ class SsmServiceTest {
+ "document's new share");
}
/**
* Two overwrites of one name must not both read the same current version. The parameter
* store's put blocks the first overwrite after it has read the version; a second overwrite
* must wait for it rather than compute the same next version.
*/
@Test
void concurrentOverwritesAreSerializedAndKeepEveryVersion() throws Exception {
String region = "us-east-1";
CountDownLatch firstPutStarted = new CountDownLatch(1);
CountDownLatch releaseFirstPut = new CountDownLatch(1);
Thread[] blocked = new Thread[1];
InMemoryStorage<String, Parameter> parameterStore = new InMemoryStorage<>() {
@Override
public void put(String key, Parameter value) {
if (value.getVersion() == 2 && blocked[0] == null) {
blocked[0] = Thread.currentThread();
firstPutStarted.countDown();
try {
releaseFirstPut.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
super.put(key, value);
}
};
SsmService service = new SsmService(parameterStore, new InMemoryStorage<>(), 50);
service.putParameter("/race/p", "v1", "String", null, false, region);
Thread first = new Thread(() -> service.putParameter("/race/p", "v2", "String", null, true, region));
Thread second = new Thread(() -> service.putParameter("/race/p", "v3", "String", null, true, region));
try {
first.start();
assertTrue(firstPutStarted.await(10, TimeUnit.SECONDS));
second.start();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (second.getState() != Thread.State.BLOCKED && second.isAlive() && System.nanoTime() < deadline) {
Thread.onSpinWait();
}
assertEquals(Thread.State.BLOCKED, second.getState(),
"a second overwrite must wait for the one in flight, not interleave with it");
} finally {
releaseFirstPut.countDown();
first.join(10_000);
second.join(10_000);
}
assertEquals(List.of(1L, 2L, 3L), service.getParameterHistory("/race/p", region).stream()
.map(ParameterHistory::getVersion).toList());
}
@Test
void allowedPatternIsCheckedWithoutHoldingTheWriteLock() throws Exception {
SsmService service = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(), 50);
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
// Hold the monitor putParameter writes under; an AllowedPattern check must still complete, since a
// slow match (up to the one-second deadline) inside the lock would stall every other SSM writer.
synchronized (service) {
Future<?> rejected = pool.submit(() -> service.putParameter("/lock/p", "abc", "String", null,
false, null, null, "^[0-9]+$", null, null, "us-east-1"));
ExecutionException e = assertThrows(ExecutionException.class,
() -> rejected.get(10, TimeUnit.SECONDS));
assertEquals("ParameterPatternMismatchException", ((AwsException) e.getCause()).getErrorCode());
}
} finally {
pool.shutdownNow();
}
}
@Test
void testListDocuments() {
ssmService.createDocument("Doc1", "{}", "Command", "us-east-1");