Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Allen Sanborn80f25417b3b7
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/DeadlineCharSequence.java b/src/main/java/io/github/hectorvent/floci/core/common/DeadlineCharSequence.java
new file mode 100644
index 0000000000..93ce655fa1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/DeadlineCharSequence.java
@@ -0,0 +1,40 @@
+package io.github.hectorvent.floci.core.common;
+
+/**
+ * A regex subject whose {@code charAt} throws once the deadline passes, so a catastrophically
+ * backtracking caller-supplied pattern aborts instead of holding a request thread.
+ */
+public final class DeadlineCharSequence implements CharSequence {
+ private final CharSequence delegate;
+ private final long deadlineNanos;
+ private final String timeoutMessage;
+
+ public DeadlineCharSequence(CharSequence delegate, long deadlineNanos, String timeoutMessage) {
+ this.delegate = delegate;
+ this.deadlineNanos = deadlineNanos;
+ this.timeoutMessage = timeoutMessage;
+ }
+
+ @Override
+ public char charAt(int index) {
+ if (System.nanoTime() - deadlineNanos > 0) {
+ throw new IllegalStateException(timeoutMessage);
+ }
+ return delegate.charAt(index);
+ }
+
+ @Override
+ public int length() {
+ return delegate.length();
+ }
+
+ @Override
+ public CharSequence subSequence(int start, int end) {
+ return new DeadlineCharSequence(delegate.subSequence(start, end), deadlineNanos, timeoutMessage);
+ }
+
+ @Override
+ public String toString() {
+ return delegate.toString();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java
index a2dbbb0e0f..330d71fff1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
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.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -1758,41 +1759,6 @@ public class CodePipelineService {
private static final long MATCHES_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1);
- /** A regex subject whose {@code charAt} throws once the deadline passes, so a catastrophically
- * backtracking pattern aborts instead of holding the run forever. */
- private static final class DeadlineCharSequence implements CharSequence {
- private final CharSequence delegate;
- private final long deadlineNanos;
-
- DeadlineCharSequence(CharSequence delegate, long deadlineNanos) {
- this.delegate = delegate;
- this.deadlineNanos = deadlineNanos;
- }
-
- @Override
- public char charAt(int index) {
- if (System.nanoTime() - deadlineNanos > 0) {
- throw new IllegalStateException("MATCHES pattern evaluation timed out");
- }
- return delegate.charAt(index);
- }
-
- @Override
- public int length() {
- return delegate.length();
- }
-
- @Override
- public CharSequence subSequence(int start, int end) {
- return new DeadlineCharSequence(delegate.subSequence(start, end), deadlineNanos);
- }
-
- @Override
- public String toString() {
- return delegate.toString();
- }
- }
-
private boolean variableCheckPasses(CodePipelineExecution execution, JsonNode rule) {
JsonNode config = rule.path("configuration");
String variable = resolveVariableReference(execution, config.path("Variable").asText(""));
@@ -1809,7 +1775,7 @@ public class CodePipelineService {
+ MAX_VARIABLE_CHECK_MATCH_LENGTH + " characters", 400);
}
yield Pattern.compile(value).matcher(new DeadlineCharSequence(variable,
- System.nanoTime() + MATCHES_TIMEOUT_NANOS)).matches();
+ System.nanoTime() + MATCHES_TIMEOUT_NANOS, "MATCHES pattern evaluation timed out")).matches();
}
default -> throw new AwsException("ValidationException",
"Unknown VariableCheck operator", 400);
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 626bd74de5..894ecff71f 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
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ssm.model.ServiceSetting;
import io.github.hectorvent.floci.services.ssm.model.SsmAssociation;
import io.github.hectorvent.floci.services.ssm.model.SsmDocument;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -126,7 +127,26 @@ public class SsmJsonHandler {
}
}
- long version = ssmService.putParameter(name, value, type, description, overwrite, tags, region);
+ // Null when the request has no Policies, so an overwrite keeps the existing ones.
+ List<JsonNode> policies = null;
+ String policiesText = optionalText(request, "Policies");
+ if (policiesText != null) {
+ JsonNode parsed;
+ try {
+ parsed = objectMapper.readTree(policiesText);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("ValidationException", "Invalid policies input: " + e.getOriginalMessage(), 400);
+ }
+ if (!parsed.isArray()) {
+ throw new AwsException("ValidationException", "Invalid policies input: expected a JSON array.", 400);
+ }
+ policies = new ArrayList<>();
+ parsed.forEach(policies::add);
+ }
+
+ long version = ssmService.putParameter(name, value, type, description, overwrite, tags,
+ optionalText(request, "KeyId"), optionalText(request, "AllowedPattern"),
+ optionalText(request, "Tier"), policies, region);
return Response.ok(new PutParameterResponse(version)).build();
}
@@ -315,6 +335,22 @@ public class SsmJsonHandler {
node.put("Description", p.getDescription());
}
node.put("DataType", p.getDataType());
+ if (SsmService.keyIdOf(p) != null) {
+ node.put("KeyId", SsmService.keyIdOf(p));
+ }
+ if (p.getAllowedPattern() != null) {
+ node.put("AllowedPattern", p.getAllowedPattern());
+ }
+ node.put("Tier", SsmService.tierOf(p));
+ if (p.getPolicies() != null) {
+ ArrayNode policies = node.putArray("Policies");
+ for (JsonNode policy : p.getPolicies()) {
+ policies.addObject()
+ .put("PolicyText", policy.toString())
+ .put("PolicyType", policy.path("Type").asText(null))
+ .put("PolicyStatus", "Pending");
+ }
+ }
parametersArray.add(node);
}
response.set("Parameters", parametersArray);
@@ -324,6 +360,12 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
+ /** Terraform sends every optional field, unset ones as "", which AWS reads as absent. */
+ private static String optionalText(JsonNode request, String field) {
+ String text = request.path(field).asText("");
+ return text.isEmpty() ? null : text;
+ }
+
private static List<String> textValues(JsonNode values) {
List<String> result = new ArrayList<>();
values.forEach(v -> result.add(v.asText()));
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 57dc82d4ea..e6efa2a46d 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,12 +1,14 @@
package io.github.hectorvent.floci.services.ssm;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -29,13 +31,16 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.ArrayList;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
@ApplicationScoped
public class SsmService implements ResourceProvider {
@@ -50,6 +55,10 @@ public class SsmService implements ResourceProvider {
private static final Set<String> DESCRIBE_PARAMETERS_FILTER_KEYS =
Set.of("Name", "Type", "KeyId", "Path", "Tier", "DataType");
private static final String DEFAULT_SSM_KEY_ID = "alias/aws/ssm";
+ private static final int STANDARD_TIER_MAX_VALUE_BYTES = 4096;
+ private static final Set<String> PARAMETER_TIERS = Set.of("Standard", "Advanced", "Intelligent-Tiering");
+ private static final int MAX_ALLOWED_PATTERN_LENGTH = 1024;
+ private static final long ALLOWED_PATTERN_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1);
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;
@@ -183,16 +192,21 @@ public class SsmService implements ResourceProvider {
public long putParameter(String name, String value, String type, String description, boolean overwrite,
Map<String, String> tags, String region) {
- validateTagKeys(tags);
- rejectReservedName(name);
- String storageKey = regionKey(region, name);
- Parameter existing = parameterStore.get(storageKey).orElse(null);
+ return putParameter(name, value, type, description, overwrite, tags, null, null, null, null, region);
+ }
- if (existing != null && !overwrite) {
- throw new AwsException("ParameterAlreadyExists",
- "The parameter already exists. To overwrite this value, set the overwrite option in the request to true.",
- 400);
+ public long putParameter(String name, String value, String type, String description,
+ boolean overwrite, Map<String, String> tags, String keyId, String allowedPattern,
+ String tier, List<JsonNode> policies, String region) {
+ // Validation reads only the request, so it runs before the lock: an AllowedPattern match can take up
+ // to ALLOWED_PATTERN_TIMEOUT_NANOS and must not stall other SSM writers.
+ if (tier != null && !PARAMETER_TIERS.contains(tier)) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value '" + tier + "' at 'tier' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [Standard, Advanced, Intelligent-Tiering]", 400);
}
+ validateTagKeys(tags);
+ rejectReservedName(name);
if (overwrite && tags != null && !tags.isEmpty()) {
throw new AwsException("ValidationException",
@@ -202,11 +216,81 @@ public class SsmService implements ResourceProvider {
400);
}
+ // Terraform sends an empty AllowedPattern for every parameter; AWS treats it as no pattern.
+ if (allowedPattern != null && allowedPattern.isEmpty()) {
+ allowedPattern = null;
+ }
+ if (allowedPattern != null) {
+ if (allowedPattern.length() > MAX_ALLOWED_PATTERN_LENGTH) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'allowedPattern' failed to satisfy constraint: "
+ + "Member must have length less than or equal to " + MAX_ALLOWED_PATTERN_LENGTH, 400);
+ }
+ Pattern pattern;
+ try {
+ pattern = Pattern.compile(allowedPattern);
+ } catch (PatternSyntaxException e) {
+ throw new AwsException("InvalidAllowedPatternException",
+ "The request doesn't meet the regular expression requirement.", 400);
+ }
+ boolean matches;
+ try {
+ // Both pattern and value come from the caller, so bound the backtracking a pattern can force.
+ matches = pattern.matcher(new DeadlineCharSequence(value,
+ System.nanoTime() + ALLOWED_PATTERN_TIMEOUT_NANOS, "AllowedPattern timed out")).matches();
+ } catch (IllegalStateException e) {
+ throw new AwsException("InvalidAllowedPatternException",
+ "AllowedPattern took too long to evaluate against the parameter value.", 400);
+ }
+ if (!matches) {
+ throw new AwsException("ParameterPatternMismatchException",
+ "Parameter value, cannot be validated against allowedPattern: " + allowedPattern, 400);
+ }
+ }
+
+ // Same monitor as the other synchronized SSM writers: the version read and the write are one step.
+ synchronized (this) {
+ return storeParameter(name, value, type, description, overwrite, tags, keyId, allowedPattern,
+ tier, policies, region);
+ }
+ }
+
+ private long storeParameter(String name, String value, String type, String description,
+ boolean overwrite, Map<String, String> tags, String keyId, String allowedPattern,
+ String tier, List<JsonNode> policies, String region) {
+ String storageKey = regionKey(region, name);
+ Parameter existing = parameterStore.get(storageKey).orElse(null);
+
+ if (existing != null && !overwrite) {
+ throw new AwsException("ParameterAlreadyExists",
+ "The parameter already exists. To overwrite this value, set the overwrite option in the request to true.",
+ 400);
+ }
+
long version = (existing != null) ? existing.getVersion() + 1 : 1;
Parameter parameter = new Parameter(name, value, type != null ? type : "String");
parameter.setVersion(version);
parameter.setDescription(description);
+ if ("SecureString".equals(parameter.getType())) {
+ parameter.setKeyId(keyId);
+ }
+ parameter.setAllowedPattern(allowedPattern);
+ // AWS keeps existing policies until new ones, or an empty list, are sent.
+ if (policies == null) {
+ parameter.setPolicies(existing != null ? existing.getPolicies() : null);
+ } else {
+ parameter.setPolicies(policies.isEmpty() ? null : List.copyOf(policies));
+ }
+ if ("Intelligent-Tiering".equals(tier)) {
+ boolean advanced = (existing != null && "Advanced".equals(tierOf(existing)))
+ || parameter.getPolicies() != null
+ || value.getBytes(StandardCharsets.UTF_8).length > STANDARD_TIER_MAX_VALUE_BYTES;
+ tier = advanced ? "Advanced" : "Standard";
+ }
+ // AWS never moves an Advanced parameter back to Standard behind an overwrite that omits the tier
+ // or asks for Intelligent-Tiering.
+ parameter.setTier(tier != null ? tier : existing != null ? tierOf(existing) : "Standard");
parameter.setArn(regionResolver.buildArn("ssm", region, "parameter" + name));
parameter.setLastModifiedDate(Instant.now());
@@ -569,15 +653,26 @@ public class SsmService implements ResourceProvider {
case "Name" -> parameter.getName();
case "Type" -> parameter.getType();
case "DataType" -> parameter.getDataType();
- // Floci stores neither a tier nor a customer key, so every parameter is Standard and
- // a SecureString is encrypted with the AWS managed key, as AWS defaults them.
- case "Tier" -> "Standard";
- case "KeyId" -> "SecureString".equals(parameter.getType()) ? DEFAULT_SSM_KEY_ID : null;
+ case "Tier" -> tierOf(parameter);
+ case "KeyId" -> keyIdOf(parameter);
default -> null;
};
return actual != null && matchesAny(actual, filter);
}
+ /** Parameters stored before Floci kept a tier are Standard, as AWS defaults them. */
+ static String tierOf(Parameter parameter) {
+ return parameter.getTier() != null ? parameter.getTier() : "Standard";
+ }
+
+ /** A SecureString put without a KeyId is encrypted with the AWS managed key. */
+ static String keyIdOf(Parameter parameter) {
+ if (!"SecureString".equals(parameter.getType())) {
+ return null;
+ }
+ return parameter.getKeyId() != null ? parameter.getKeyId() : DEFAULT_SSM_KEY_ID;
+ }
+
private static boolean matchesAny(String actual, ParameterStringFilter filter) {
String option = filter.option() == null ? "Equals" : filter.option();
return filter.values().stream().anyMatch(value -> switch (option) {
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 b100097abd..464416ceab 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
@@ -4,10 +4,12 @@ import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
@RegisterForReflection
@@ -38,6 +40,19 @@ public class Parameter {
@JsonProperty("DataType")
private String dataType = "text";
+ @JsonProperty("KeyId")
+ private String keyId;
+
+ @JsonProperty("AllowedPattern")
+ private String allowedPattern;
+
+ @JsonProperty("Tier")
+ private String tier;
+
+ // Each policy object as submitted; DescribeParameters re-serializes it as the PolicyText.
+ @JsonProperty("Policies")
+ private List<JsonNode> policies;
+
@JsonProperty("Tags")
@JsonAlias({"tags", "Tags"})
private Map<String, String> tags = new HashMap<>();
@@ -84,6 +99,18 @@ public class Parameter {
public String getDataType() { return dataType; }
public void setDataType(String dataType) { this.dataType = dataType; }
+ public String getKeyId() { return keyId; }
+ public void setKeyId(String keyId) { this.keyId = keyId; }
+
+ public String getAllowedPattern() { return allowedPattern; }
+ public void setAllowedPattern(String allowedPattern) { this.allowedPattern = allowedPattern; }
+
+ public String getTier() { return tier; }
+ public void setTier(String tier) { this.tier = tier; }
+
+ public List<JsonNode> getPolicies() { return policies; }
+ public void setPolicies(List<JsonNode> policies) { this.policies = policies; }
+
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
index 6e8cd7eb09..187924b1aa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
@@ -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")
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
index 1ce6541a0f..6ce57d4f24 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
@@ -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");