fix(ssm): return a SecureString's KMS ciphertext when a read does not decrypt (#7335)

* fix(ssm): return a SecureString's KMS ciphertext when a read does not decrypt

GetParameter, GetParameters, GetParametersByPath and GetParameterHistory
returned a SecureString's plaintext whether or not the request set
WithDecryption. AWS encrypts the value with KMS on PutParameter, under the
parameter's key with the PARAMETER_ARN encryption context, and returns
that ciphertext unless the read asks for decryption.

PutParameter now encrypts a SecureString with Floci's KMS and stores the
ciphertext with the version, so every read of a version returns the same
value and KMS Decrypt with the parameter's ARN as context returns the
plaintext. A key KMS cannot use, a value over KMS's 4096-byte limit, and
a version stored before this change are still returned unencrypted.

* fix(ssm): log a SecureString stored without a ciphertext and keep the at-rest note

* fix(ssm): say how AWS encrypts Advanced SecureStrings and reuse the shared test client
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-02 15:07:34 -04:00
1 parent cb093f87cb
commit d44e96eab8
8 files changed
+278 -11

No files matched your search

+18 -1
View File
@@ -225,8 +225,25 @@ or create the AWS RAM resource share AWS makes for a shared parameter.
All AWS parameter types are accepted: `String`, `StringList`, `SecureString`.
`PutParameter` encrypts a `SecureString` with Floci's KMS under the parameter's key
(`alias/aws/ssm` when none was given), with the encryption context `PARAMETER_ARN` set to the
parameter's ARN, as AWS does. A read without `WithDecryption` (`GetParameter`, `GetParameters`,
`GetParametersByPath`, `GetParameterHistory`) returns that ciphertext, the same one on every read
of a version, and KMS `Decrypt` with that context returns the plaintext. With `WithDecryption`
the plaintext is returned.
!!! note
`SecureString` parameters are stored as-is without actual KMS encryption in Floci. The type is preserved and returned correctly, but the value is not encrypted at rest.
The encryption applies to what the API returns, not to storage: Floci saves each
`SecureString` version's plaintext alongside its ciphertext, so the plaintext stays readable in
the persisted state files.
A `KeyId` that Floci's KMS cannot use, which AWS would refuse on `PutParameter`, is accepted,
and such a parameter is returned unencrypted. So is a value over KMS's 4096-byte limit, and a
parameter version stored before Floci encrypted `SecureString` values.
AWS encrypts every Advanced `SecureString` with the AWS Encryption SDK, so its value is the
SDK's encrypted message. Floci encrypts an Advanced value up to 4096 bytes with a plain KMS
`Encrypt` instead, the same as a Standard one.
## Parameter Store Change events
@@ -170,7 +170,7 @@ public class SsmJsonHandler {
authorizeSecretValues(List.of(param), authorization);
ObjectNode response = objectMapper.createObjectNode();
response.set("Parameter", parameterToNode(param));
response.set("Parameter", parameterToNode(param, withDecryption));
return Response.ok(response).build();
}
@@ -186,7 +186,7 @@ public class SsmJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode parametersArray = objectMapper.createArrayNode();
for (Parameter p : params) {
parametersArray.add(parameterToNode(p));
parametersArray.add(parameterToNode(p, withDecryption));
}
response.set("Parameters", parametersArray);
response.set("InvalidParameters", invalidParameterNames(names,
@@ -239,6 +239,7 @@ public class SsmJsonHandler {
PageRequest pageRequest = pageRequest(request, GET_PARAMETERS_BY_PATH_MAX_RESULTS);
String path = request.path("Path").asText();
boolean recursive = request.path("Recursive").asBoolean(false);
boolean withDecryption = request.path("WithDecryption").asBoolean(false);
List<ParameterStringFilter> filters = parameterFilters(request);
List<Parameter> params = ssmService.getParametersByPath(path, recursive, filters, region);
@@ -254,7 +255,7 @@ public class SsmJsonHandler {
GET_PARAMETERS_BY_PATH_TOKEN + ssmService.accountId() + ":" + region + ":" + recursive + ":"
+ (path.endsWith("/") ? path : path + "/") + (labeledVersions ? ":labels" : ""));
for (Parameter p : page.items()) {
parametersArray.add(parameterToNode(p));
parametersArray.add(parameterToNode(p, withDecryption));
}
response.set("Parameters", parametersArray);
putNextToken(response, page);
@@ -298,6 +299,7 @@ public class SsmJsonHandler {
private Response handleGetParameterHistory(JsonNode request, String region) {
PageRequest pageRequest = pageRequest(request, GET_PARAMETER_HISTORY_MAX_RESULTS);
String name = request.path("Name").asText();
boolean withDecryption = request.path("WithDecryption").asBoolean(false);
List<ParameterHistory> history = ssmService.getParameterHistory(name, region);
ObjectNode response = objectMapper.createObjectNode();
@@ -310,7 +312,7 @@ public class SsmJsonHandler {
ObjectNode node = objectMapper.createObjectNode();
node.put("Name", h.getName());
node.put("Version", h.getVersion());
node.put("Value", h.getValue());
node.put("Value", responseValue(withDecryption, h.getValue(), h.getEncryptedValue()));
node.put("Type", h.getType());
if (h.getKeyId() != null) {
node.put("KeyId", h.getKeyId());
@@ -1312,11 +1314,16 @@ public class SsmJsonHandler {
}
}
private ObjectNode parameterToNode(Parameter p) {
/** A SecureString read without decryption answers the ciphertext PutParameter stored, as AWS does. */
private static String responseValue(boolean withDecryption, String value, String encryptedValue) {
return withDecryption || encryptedValue == null ? value : encryptedValue;
}
private ObjectNode parameterToNode(Parameter p, boolean withDecryption) {
ObjectNode node = objectMapper.createObjectNode();
node.put("Name", p.getName());
if (p.getValue() != null) {
node.put("Value", p.getValue());
node.put("Value", responseValue(withDecryption, p.getValue(), p.getEncryptedValue()));
}
node.put("Type", p.getType());
node.put("Version", p.getVersion());
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -105,11 +106,12 @@ public class SsmService implements ResourceProvider {
private final Ec2ImageCatalog imageCatalog;
private final SecretsManagerService secretsManager;
private final SsmEventPublisher eventPublisher;
private final KmsService kmsService;
@Inject
public SsmService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
Ec2ImageCatalog imageCatalog, SecretsManagerService secretsManager,
SsmEventPublisher eventPublisher) {
SsmEventPublisher eventPublisher, KmsService kmsService) {
this(
storageFactory.create("ssm", "ssm-parameters.json",
new TypeReference<>() {
@@ -133,7 +135,8 @@ public class SsmService implements ResourceProvider {
regionResolver,
imageCatalog,
secretsManager,
eventPublisher
eventPublisher,
kmsService
);
}
@@ -207,6 +210,21 @@ public class SsmService implements ResourceProvider {
int maxParameterHistory, RegionResolver regionResolver,
Ec2ImageCatalog imageCatalog, SecretsManagerService secretsManager,
SsmEventPublisher eventPublisher) {
this(parameterStore, historyStore, documentPermissionStore, documentStore, serviceSettingStore,
associationStore, maxParameterHistory, regionResolver, imageCatalog, secretsManager,
eventPublisher, null);
}
/** A null KMS service stores SecureString values without a ciphertext. */
SsmService(StorageBackend<String, Parameter> parameterStore,
StorageBackend<String, List<ParameterHistory>> historyStore,
StorageBackend<String, List<String>> documentPermissionStore,
StorageBackend<String, SsmDocument> documentStore,
StorageBackend<String, ServiceSetting> serviceSettingStore,
StorageBackend<String, SsmAssociation> associationStore,
int maxParameterHistory, RegionResolver regionResolver,
Ec2ImageCatalog imageCatalog, SecretsManagerService secretsManager,
SsmEventPublisher eventPublisher, KmsService kmsService) {
this.parameterStore = parameterStore;
this.historyStore = historyStore;
this.documentPermissionStore = documentPermissionStore;
@@ -218,6 +236,7 @@ public class SsmService implements ResourceProvider {
this.imageCatalog = imageCatalog;
this.secretsManager = secretsManager;
this.eventPublisher = eventPublisher;
this.kmsService = kmsService;
}
/**
@@ -332,6 +351,7 @@ public class SsmService implements ResourceProvider {
// or asks for Intelligent-Tiering.
parameter.setTier(tier != null ? tier : existing != null ? tierOf(existing) : "Standard");
parameter.setArn(regionResolver.buildArn("ssm", region, parameterResource(name)));
parameter.setEncryptedValue(encryptedValueOf(parameter, region));
parameter.setLastModifiedDate(Instant.now());
if (existing != null && existing.getTags() != null) {
@@ -351,6 +371,27 @@ public class SsmService implements ResourceProvider {
return parameter;
}
/**
* AWS encrypts a SecureString under its KMS key with the {@code PARAMETER_ARN} encryption context
* and returns that ciphertext to a read without decryption. A key KMS cannot use, which AWS refuses
* on PutParameter, leaves the parameter without one.
*/
private String encryptedValueOf(Parameter parameter, String region) {
if (kmsService == null || !"SecureString".equals(parameter.getType())) {
return null;
}
try {
byte[] ciphertext = kmsService.encrypt(parameter.getKeyId(),
parameter.getValue().getBytes(StandardCharsets.UTF_8),
Map.of("PARAMETER_ARN", parameter.getArn()), region);
return Base64.getEncoder().encodeToString(ciphertext);
} catch (AwsException e) {
LOG.warnv("Storing SecureString {0} without a ciphertext: KMS cannot encrypt under {1}: {2}",
parameter.getArn(), parameter.getKeyId(), e.getMessage());
return null;
}
}
/** AWS's form is {@code parameter/<name>} whether or not the name starts with a slash. */
public static String parameterResource(String name) {
return "parameter" + (name.startsWith("/") ? name : "/" + name);
@@ -554,6 +595,7 @@ public class SsmService implements ResourceProvider {
private static Parameter historicalParameter(Parameter current, ParameterHistory history) {
Parameter parameter = new Parameter(current.getName(), history.getValue(), history.getType());
parameter.setEncryptedValue(history.getEncryptedValue());
parameter.setVersion(history.getVersion());
parameter.setDescription(history.getDescription());
parameter.setLastModifiedDate(history.getLastModifiedDate());
@@ -60,6 +60,10 @@ public class Parameter {
@JsonAlias({"tags", "Tags"})
private Map<String, String> tags = new HashMap<>();
// The SecureString value as KMS encrypted it on PutParameter, returned by a read without WithDecryption.
@JsonProperty("EncryptedValue")
private String encryptedValue;
// Only set on a copy answering a name:version or name:label read; never persisted.
@JsonIgnore
private String selector;
@@ -84,6 +88,9 @@ public class Parameter {
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
public String getEncryptedValue() { return encryptedValue; }
public void setEncryptedValue(String encryptedValue) { this.encryptedValue = encryptedValue; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
@@ -21,6 +21,9 @@ public class ParameterHistory {
@JsonProperty("Value")
private String value;
@JsonProperty("EncryptedValue")
private String encryptedValue;
@JsonProperty("Type")
private String type;
@@ -42,6 +45,7 @@ public class ParameterHistory {
this.name = parameter.getName();
this.version = parameter.getVersion();
this.value = parameter.getValue();
this.encryptedValue = parameter.getEncryptedValue();
this.type = parameter.getType();
this.keyId = parameter.getKeyId();
this.lastModifiedDate = parameter.getLastModifiedDate();
@@ -52,6 +56,7 @@ public class ParameterHistory {
this.name = other.name;
this.version = other.version;
this.value = other.value;
this.encryptedValue = other.encryptedValue;
this.type = other.type;
this.keyId = other.keyId;
this.lastModifiedDate = other.lastModifiedDate;
@@ -68,6 +73,9 @@ public class ParameterHistory {
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
public String getEncryptedValue() { return encryptedValue; }
public void setEncryptedValue(String encryptedValue) { this.encryptedValue = encryptedValue; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
@@ -769,7 +769,7 @@ class Ec2KeyPairCfnProvisionerTest {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ssm().maxParameterHistory()).thenReturn(5);
return new SsmService(factory, config, new RegionResolver(REGION, ACCOUNT_ID),
null, null, mock(SsmEventPublisher.class));
null, null, mock(SsmEventPublisher.class), null);
}
private static StackResource resource() {
@@ -2118,7 +2118,7 @@ class SsmIntegrationTest {
.header("X-Amz-Target", "AmazonSSM.GetParameters")
.contentType(SSM_CONTENT_TYPE)
.body("""
{ "Names": ["/selector/param:1", "/selector/param:9"] }
{ "Names": ["/selector/param:1", "/selector/param:9"], "WithDecryption": true }
""")
.when()
.post("/")
@@ -0,0 +1,186 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.Parameter;
import software.amazon.awssdk.services.ssm.model.ParameterHistory;
import software.amazon.awssdk.services.ssm.model.ParameterType;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@QuarkusTest
class SsmSecureStringCiphertextIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private SsmClient ssm;
@BeforeAll
static void configureContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void createClient() {
ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1);
}
@AfterEach
void closeClient() {
ssm.close();
}
@Test
void getParameterWithoutDecryptionReturnsTheValueEncryptedUnderTheAwsManagedKey() {
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "s3cr3t", null);
Parameter parameter = ssm.getParameter(r -> r.name(name)).parameter();
assertNotEquals("s3cr3t", parameter.value());
JsonPath decrypted = decrypt(parameter.value(), parameter.arn());
assertEquals("s3cr3t", plaintextOf(decrypted));
assertEquals(keyArnOf("alias/aws/ssm"), decrypted.getString("KeyId"));
}
@Test
void getParameterWithoutDecryptionReturnsTheValueEncryptedUnderTheParametersOwnKey() {
String keyId = createKey();
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "own-key", keyId);
Parameter parameter = ssm.getParameter(r -> r.name(name)).parameter();
JsonPath decrypted = decrypt(parameter.value(), parameter.arn());
assertEquals("own-key", plaintextOf(decrypted));
assertEquals(keyArnOf(keyId), decrypted.getString("KeyId"));
}
@Test
void everyReadOfOneVersionReturnsTheSameCiphertext() {
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "stable", null);
Parameter first = ssm.getParameter(r -> r.name(name)).parameter();
String second = ssm.getParameter(r -> r.name(name)).parameter().value();
assertEquals("stable", plaintextOf(decrypt(first.value(), first.arn())));
assertEquals(first.value(), second);
}
@Test
void aVersionSelectorReturnsThatVersionsCiphertext() {
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "first", null);
ssm.putParameter(r -> r.name(name).value("second").type(ParameterType.SECURE_STRING).overwrite(true));
Parameter parameter = ssm.getParameter(r -> r.name(name + ":1")).parameter();
assertEquals("first", plaintextOf(decrypt(parameter.value(), parameter.arn())));
}
@Test
void getParameterWithDecryptionReturnsThePlaintext() {
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "s3cr3t", null);
assertEquals("s3cr3t", ssm.getParameter(r -> r.name(name).withDecryption(true)).parameter().value());
}
@Test
void getParametersWithoutDecryptionReturnsCiphertext() {
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "batch", null);
Parameter parameter = ssm.getParameters(r -> r.names(name)).parameters().getFirst();
assertEquals("batch", plaintextOf(decrypt(parameter.value(), parameter.arn())));
}
@Test
void getParametersByPathWithoutDecryptionReturnsCiphertextAndWithDecryptionThePlaintext() {
String path = "/ciphertext/" + UUID.randomUUID();
putSecure(path + "/secret", "by-path", null);
Parameter encrypted = ssm.getParametersByPath(r -> r.path(path)).parameters().getFirst();
Parameter decrypted = ssm.getParametersByPath(r -> r.path(path).withDecryption(true)).parameters().getFirst();
assertEquals("by-path", plaintextOf(decrypt(encrypted.value(), encrypted.arn())));
assertEquals("by-path", decrypted.value());
}
@Test
void getParameterHistoryWithoutDecryptionReturnsEachVersionEncryptedUnderItsOwnKey() {
String keyId = createKey();
String name = "/ciphertext/" + UUID.randomUUID();
putSecure(name, "first", keyId);
ssm.putParameter(r -> r.name(name).value("second").type(ParameterType.SECURE_STRING).overwrite(true));
String arn = ssm.getParameter(r -> r.name(name)).parameter().arn();
List<ParameterHistory> encrypted = ssm.getParameterHistory(r -> r.name(name)).parameters();
List<ParameterHistory> decrypted = ssm.getParameterHistory(r -> r.name(name).withDecryption(true)).parameters();
JsonPath first = decrypt(encrypted.get(0).value(), arn);
JsonPath second = decrypt(encrypted.get(1).value(), arn);
assertEquals("first", plaintextOf(first));
assertEquals(keyArnOf(keyId), first.getString("KeyId"));
assertEquals("second", plaintextOf(second));
assertEquals(keyArnOf("alias/aws/ssm"), second.getString("KeyId"));
assertEquals(List.of("first", "second"), decrypted.stream().map(ParameterHistory::value).toList());
}
@Test
void aStringParameterIsReturnedAsStoredWithoutDecryption() {
String name = "/ciphertext/" + UUID.randomUUID();
ssm.putParameter(r -> r.name(name).value("plain").type(ParameterType.STRING));
assertEquals("plain", ssm.getParameter(r -> r.name(name)).parameter().value());
}
private void putSecure(String name, String value, String keyId) {
ssm.putParameter(r -> r.name(name).value(value).type(ParameterType.SECURE_STRING).keyId(keyId));
}
private static String createKey() {
return kms("CreateKey", "{}").getString("KeyMetadata.KeyId");
}
private static String keyArnOf(String keyId) {
return kms("DescribeKey", "{\"KeyId\":\"" + keyId + "\"}").getString("KeyMetadata.Arn");
}
private static JsonPath decrypt(String ciphertext, String parameterArn) {
return kms("Decrypt", """
{"CiphertextBlob": "%s", "EncryptionContext": {"PARAMETER_ARN": "%s"}}
""".formatted(ciphertext, parameterArn));
}
private static String plaintextOf(JsonPath decrypted) {
return new String(Base64.getDecoder().decode(decrypted.getString("Plaintext")), StandardCharsets.UTF_8);
}
private static JsonPath kms(String operation, String body) {
return given()
.header("X-Amz-Target", "TrentService." + operation)
.contentType(CONTENT_TYPE)
.body(body)
.when().post("/")
.then().statusCode(200)
.extract().jsonPath();
}
}