fix(ssm): validate PutParameter names and resolve tagging ARNs only in the request's region (#7965)

* fix(iam): evaluate SSM GetParametersByPath and GetParameters against the requested parameters

GetParametersByPath is now checked against the parameter ARN of its Path, and GetParameters against each entry in Names, instead of parameter/*. A root Path keeps the parameter/* fallback.

* test(ssm): cover path and per-name IAM checks on parameter reads

* fix(iam): read each SSM operation's own resource field and drop read selectors

GetParametersByPath is evaluated against Path only, GetParameters and DeleteParameters against Names only, and other actions against Name only, so a field the handler ignores can no longer stand in for the one it acts on. GetParameter and GetParameters names lose their :version or :label selector, in name and ARN form, before the parameter ARN is built, so a grant on the base parameter covers them.

* test(ssm): cover per-operation IAM fields, read selectors and batch deletion

GetParametersByPath with a denied Path and an allowed extraneous Names entry is refused; a grant on a parameter allows reading its versions and labels by name and ARN; DeleteParameters needs a grant on every name and deletes nothing when one is refused.

* fix(iam): check SSM Names as the handler reads them and the root path as parameter/

Names is iterated the way SsmJsonHandler iterates it, so an object-shaped Names is checked against each of its values instead of parameter/*. A name that looks like an ARN but does not parse loses its selector like any other name, matching how SsmService reads it. GetParametersByPath on the root path is checked against parameter/, the empty parameter name AWS authorizes it against; a missing or empty Path keeps the parameter/* fallback.

* test(ssm): prove path and batch-delete checks with a Deny under a parameter/* Allow

Both tests now allow the action on parameter/* and deny it on the protected path or parameter, so they fail where the request is checked against parameter/* and pass only when it is checked against the Path or every entry in Names.

* fix(iam): treat an SSM request without an operation as a Name request

Set.of rejects a null lookup, so the Names and selector-read checks now test for a missing operation first; such a request falls to the Name branch as it did before.

* fix(iam): check GetParametersByPath without a Path against the root path

SsmJsonHandler reads Path with asText and SsmService lists a blank path from the root, so a missing, empty or non-text Path is now checked against parameter/, the same resource as Path="/", instead of parameter/*. A Deny on parameter/ could otherwise be sidestepped by leaving Path out. A null Path or, for the parameter operations whose handler reads Name with asText, a null Name is checked against parameter/null, the parameter the handler acts on. The builder's Javadoc is split into shorter sentences and wrapped to 120 columns.

* test(ssm): prove a Deny holds against read selectors and the root path

A Deny on a parameter refuses GetParameter on its version, its label and its ARN with a label, and a Deny on parameter/ refuses GetParametersByPath on Path="/" and with no Path at all, each under a parameter/* Allow.

* fix(ssm): reject a PutParameter name outside the parameter name syntax

* test(ssm): cover PutParameter rejecting colon and space names

* fix(iam): check SSM names with the whitespace their handler keeps

* test(ssm): cover untrimmed Name and Names in IAM checks

* test(ssm): prove a Deny holds against GetParameters selectors

* fix(ssm): strip surrounding spaces from a PutParameter name as AWS does

* fix(iam): check a PutParameter against the name it stores, spaces stripped

* test(ssm): cover PutParameter stripping surrounding spaces from a name

* test(iam): cover a PutParameter Name checked with its spaces stripped

* fix(ssm): read a parameter//name ARN as //name, not /name

* test(ssm): prove a parameter//name ARN cannot read a denied /name

* fix(iam): check GetParametersByPath on its path without a trailing slash

* test(iam): prove a Deny on a path holds when GetParametersByPath adds a trailing slash

* fix(iam): check an empty SSM name on parameter/, not parameter/*

* test(iam): cover an empty SSM Name and Names entry checked on parameter/

* fix(cloudformation): record an SSM parameter under the name PutParameter stores

* test(cloudformation): cover an SSM parameter Name with surrounding spaces

* fix(iam): check SSM tagging against the parameter its ResourceId names

* test(iam): cover SSM tagging checked against ResourceId, not an injected Name

* fix(cloudformation): update an SSM parameter in place when its prior id differs only by surrounding spaces

* test(cloudformation): cover updating a parameter recorded with surrounding spaces

* fix(ssm): resolve a tagging ResourceId ARN only in the request's partition, region and account

AddTagsToResource, ListTagsForResource and RemoveTagsFromResource now resolve
an ARN ResourceId the way parameter reads do: only an ssm parameter/ ARN in the
request's partition, region and account names a stored parameter. An ARN for
another region or account, or a parameter ARN without the slash after
parameter, is looked up as a literal name and reported as InvalidResourceId.

IAM evaluates tagging against the ResourceId ARN as sent, so before this a
foreign-region ARN could pass a Deny on the local parameter's ARN and still
tag the local parameter.

* test(iam): cover SSM tagging by a foreign-region ARN leaving a denied parameter untagged

* fix(cloudformation): replace an SSM parameter whose prior id has surrounding spaces

A stack created before parameter names were stripped stored its parameter
under the spaced name, so updating it in place under the stripped name read a
parameter that does not exist and failed with ParameterNotFound. The update
is a replacement again, as for any changed physical id: it creates the
stripped name and deletes the spaced parameter when the update commits.

* refactor(iam): shorten the SSM resource ARN builder's Javadoc

* fix(ssm): resolve a legacy parameter<name> ARN in tagging calls

Before parameter ARNs matched AWS, Floci gave a top-level parameter the
form parameter<name>, and the ARN normalization promised those ARNs
still resolve. Tagging now reads its ResourceId through the
request-scoped read path, which rejected them. A parameter<name> ARN of
the request's partition, region and account is now read as
parameter/<name> before the lookup; one from any other partition,
region or account is still rejected.

* fix(iam): check a legacy parameter<name> tagging ARN as parameter/<name>

The tagging handler reads a parameter<name> ResourceId ARN of the
request's partition, region and account as parameter/<name>. IAM now
evaluates the same ARN, so a Deny on parameter/<name> holds against the
legacy form and IAM and the handler agree on the parameter. A legacy ARN
of another partition, region or account is evaluated as given, and the
handler rejects it.

* fix(ssm): trim only spaces from a PutParameter name

AWS removes leading and trailing spaces from a PutParameter name, not
other whitespace. PutParameter, the AWS::SSM::Parameter provisioner and
the IAM check on PutParameter used String.strip(), which also dropped
tabs, newlines and non-breaking spaces, so such a name was stored under
a different name instead of failing validation. All three now share
SsmService.withoutSurroundingSpaces, which removes only the space
character, so IAM still checks the name the handler stores.
UnlabelParameterVersion keeps its existing strip() on both sides.

* fix(cloudformation): roll back an SSM parameter without PutParameter's name checks

A failed stack update restores the parameter through PutParameter under
the name its snapshot recorded. PutParameter now trims spaces and
rejects colons and interior spaces, so restoring a parameter stored
before those checks either failed, leaving the rollback half done, or
wrote a different, trimmed name. SsmService.restoreParameter overwrites
the parameter under its exact stored name with the rest of
PutParameter's validation, and the rollback uses it.

* docs(ssm): describe parameter name checks, tagging ARNs and IAM resources

Document that PutParameter trims only spaces and rejects names outside
the parameter name syntax, that tagging accepts parameter ARNs of the
request's partition, region and account (the legacy parameter<name>
form included), and which request field each action's IAM check reads.

* fix(iam): check a GetParametersByPath path ending in // as the path searched

GetParametersByPath searches under a Path that already ends in a slash
unchanged, so /app// lists /app//<name>. Dropping one slash checked it
against parameter/app/, which a Deny on parameter/app// never matched.
Only a single trailing slash is dropped now.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

* fix(iam): read a legacy SSM tagging ARN in the request's partition

The tagging handlers decide whether a legacy parameter<name> ARN is the
request's own using the request's partition, which for a Region no
partition publishes is the deployment's. The IAM check used the
commercial partition there, so in a non-aws deployment it checked the
literal parameter<name> ARN while the handler tagged parameter/<name>,
and a Deny on parameter/<name> did not apply. SSM requests now carry the
request's partition into the check, as Route 53's do.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

* test(cloudformation): fail an SSM rollback restore through restoreParameter

The rollback restore now writes through SsmService.restoreParameter rather
than putParameter, so the integration test's simulated restore failure has
to stub that method for the rollback to fail as the tests expect.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

* refactor(iam): leave SSM request resources to the existing builder

Move the SSM IAM resource changes out of this branch so it carries only the
SSM service fixes. The resource-per-operation work moves onto the IAM
request-resource generator separately. withLegacyParameterSlash goes back to
private now that only SsmService reads it.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

* test(ssm): cover a parameter//name ARN reading nothing under one slash

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

* docs(ssm): drop the IAM resource description and note the double-slash ARN

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>

---------

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>
This commit is contained in:
Tyler Webb authored and GitHub committed 2026-11-12 20:02:54 -04:00
1 parent 54ea160aa6
commit 0383d65acb
7 files changed
+305 -31

No files matched your search

+12 -2
View File
@@ -36,6 +36,14 @@ Retained flat-name parameters from older Floci versions expose canonical
preserves the ARN's partition, region and account, along with the parameter's value,
version, tags and history. Refresh cached Terraform outputs or policies that consumed
the old malformed ARN; malformed policy resources do not grant access to the canonical ARN.
The tagging actions still accept that old `parameter<name>` form as `ResourceId` when it names
the request's partition, region and account, and read it as `parameter/<name>`.
`PutParameter` removes leading and trailing spaces from `Name` before it validates and stores it,
as AWS does; a tab, newline or other whitespace is not removed. The name must then consist of
letters, numbers, `.`, `-`, `_` and the `/` separator, so a colon or an interior space fails with
a `ValidationException`. A parameter stored under such a name by an older Floci version can still
be read, overwritten by a CloudFormation rollback, and deleted.
`GetParametersByPath` supports `Type` and `KeyId` entries in `ParameterFilters`, with `Equals`
(the default) or `BeginsWith`. Values within one filter combine with OR; multiple
@@ -201,12 +209,14 @@ aws ssm get-parameter --name /aws/reference/secretsmanager/my-app/api-key --with
A parameter's ARN is `arn:<partition>:ssm:<region>:<account>:parameter/<name without leading slash>`
for both a top-level name such as `db-host` and a path such as `/app/db/host`, as on AWS.
The CloudFormation `Arn` attribute of an `AWS::SSM::Parameter` is the same ARN, and
`AddTagsToResource`, `ListTagsForResource` and `RemoveTagsFromResource` accept it as `ResourceId`.
An ECS container secret's `valueFrom` accepts it too.
`AddTagsToResource`, `ListTagsForResource` and `RemoveTagsFromResource` accept it as `ResourceId`
when it names the request's partition, region and account; an ARN naming another one fails with
`InvalidResourceId`. An ECS container secret's `valueFrom` accepts it too.
`GetParameter` and `GetParameters` accept the returned ARN, optionally followed by
`:version` or `:label`, for parameters in the caller's account and request region.
Batch reads keep unresolved inputs in `InvalidParameters` in their original form.
An ARN whose resource is `parameter//<name>` names `//<name>`, never `/<name>`.
ARNs naming another account, region or partition never resolve to a same-name local
parameter. Cross-account shared parameters are not modeled. Secrets Manager
references continue to use `/aws/reference/secretsmanager/<secret-id>`, not a
@@ -21,7 +21,9 @@ import java.util.Set;
import java.util.TreeSet;
/**
* Provisions {@code AWS::SSM::Parameter}. The parameter name is the physical id and {@code Ref}.
* Provisions {@code AWS::SSM::Parameter}. The parameter name is the physical id and {@code Ref}, without the
* surrounding spaces {@code PutParameter} strips before it stores the parameter. A prior physical id recorded
* with those spaces is a different name, so the update replaces that parameter.
*
* <p>A create, and the replacement a changed name makes, is one {@code PutParameter} that carries
* the template's tags and does not overwrite, as AWS's handler sends it: a name that already exists
@@ -59,8 +61,8 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
ReplacementCleanup.endRollbackRetry(r);
}
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"),
r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false);
String name = SsmService.withoutSurroundingSpaces(ctx.stablePhysicalName(
ctx.resolveOptional(props, "Name"), r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false));
String value = ctx.resolveOptional(props, "Value");
if (value == null) {
value = "";
@@ -252,8 +254,8 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
&& Objects.equals(tier, current.getTier())
&& Objects.equals(policies, current.getPolicies());
if (!unchanged) {
ssmService.putParameter(name, value, type, description, true, null, keyId, allowedPattern, tier,
policies, region);
ssmService.restoreParameter(name, value, type, description, keyId, allowedPattern, tier, policies,
region);
}
reconcileTags(name, CfnRollback.snapshotTagKeys(snapshot), CfnRollback.snapshotTags(snapshot), region);
}
@@ -81,6 +81,8 @@ public class SsmService implements ResourceProvider {
private static final String PARAMETER_NAME_FORMAT_RULE = "If formed as a path, it can consist of sub-paths "
+ "divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following "
+ "3 symbols .-_";
/** The characters a parameter name may hold: letters, numbers, {@code .-_} and the {@code /} separator. */
private static final Pattern PARAMETER_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_./-]+");
/** A bare name, or a path of non-empty segments; AWS also lets a colon through here. */
private static final Pattern UNLABEL_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_.:-]+|(/[A-Za-z0-9_.:-]+)+");
@@ -252,6 +254,10 @@ public class SsmService implements ResourceProvider {
return putParameter(name, value, type, description, overwrite, tags, null, null, null, null, region);
}
/**
* Create or update a parameter, returning its version. As AWS does, surrounding spaces are removed from the
* name before it is validated and stored.
*/
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) {
@@ -263,8 +269,26 @@ public class SsmService implements ResourceProvider {
+ "Member must satisfy enum value set: [Standard, Advanced, Intelligent-Tiering]");
}
validateTagKeys(tags);
rejectReservedName(name);
name = withoutSurroundingSpaces(name);
rejectInvalidName(name);
return writeParameter(name, value, type, description, overwrite, tags, keyId, allowedPattern, tier, policies,
region);
}
/**
* Overwrites a parameter under the name it is stored with, without the name trimming and validation
* {@code PutParameter} applies, so a CloudFormation rollback can restore a parameter stored before those checks.
* Returns the new version.
*/
public long restoreParameter(String name, String value, String type, String description, String keyId,
String allowedPattern, String tier, List<JsonNode> policies, String region) {
return writeParameter(name, value, type, description, true, null, keyId, allowedPattern, tier, policies,
region);
}
private long writeParameter(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) {
if (overwrite && tags != null && !tags.isEmpty()) {
throw new AwsException("ValidationException",
"Invalid request: tags and overwrite can't be used together. To create a "
@@ -536,13 +560,16 @@ public class SsmService implements ResourceProvider {
* and regardless of case, so an account can never write over a public parameter. The rule
* keys on the first path segment rather than a bare prefix, so a name such as
* {@code ssm-auto-stack-Param-ABC}, which CloudFormation generates for a stack whose name
* starts with ssm, is still accepted.
* starts with ssm, is still accepted. A name holding anything but letters, numbers, {@code .-_} and the
* {@code /} separator, such as an interior space or the colon that starts a read's version or label selector,
* is rejected with the same message.
*/
private static void rejectReservedName(String name) {
private static void rejectInvalidName(String name) {
String bare = name == null ? "" : name.startsWith("/") ? name.substring(1) : name;
String lower = bare.toLowerCase(Locale.ROOT);
if (lower.equals("aws") || lower.equals("ssm") // partition-literal: reserved name prefix
|| lower.startsWith("aws/") || lower.startsWith("ssm/")) {
|| lower.startsWith("aws/") || lower.startsWith("ssm/")
|| name == null || !PARAMETER_NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException",
"Parameter name: can't be prefixed with \"aws\" or \"ssm\" (case-insensitive). "
+ PARAMETER_NAME_FORMAT_RULE, 400);
@@ -1095,7 +1122,7 @@ public class SsmService implements ResourceProvider {
public void addTagsToResource(String resourceId, Map<String, String> tags, String region) {
validateTagKeys(tags);
String storageKey = regionKey(region, parameterName(resourceId, region));
String storageKey = regionKey(region, parameterTagName(resourceId, region));
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -1108,6 +1135,25 @@ public class SsmService implements ResourceProvider {
LOG.debugv("Added tags to parameter: {0}", resourceId);
}
/**
* The name without its leading and trailing spaces, as {@code PutParameter} stores it. Only the space character
* is removed; a tab, newline or other whitespace stays and fails name validation.
*/
public static String withoutSurroundingSpaces(String name) {
if (name == null) {
return null;
}
int start = 0;
int end = name.length();
while (start < end && name.charAt(start) == ' ') {
start++;
}
while (end > start && name.charAt(end - 1) == ' ') {
end--;
}
return name.substring(start, end);
}
/**
* The key constraint AWS checks before any lookup, naming the offending key by its 1-based
* position in the request's {@code Tags} list.
@@ -1135,7 +1181,7 @@ public class SsmService implements ResourceProvider {
}
public Map<String, String> listTagsForResource(String resourceId, String region) {
String storageKey = regionKey(region, parameterName(resourceId, region));
String storageKey = regionKey(region, parameterTagName(resourceId, region));
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -1143,7 +1189,7 @@ public class SsmService implements ResourceProvider {
}
public void removeTagsFromResource(String resourceId, List<String> tagKeys, String region) {
String storageKey = regionKey(region, parameterName(resourceId, region));
String storageKey = regionKey(region, parameterTagName(resourceId, region));
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -1282,8 +1328,9 @@ public class SsmService implements ResourceProvider {
/**
* The stored name a parameter name or ARN addresses. The ARN carries a leading slash the stored name may
* lack, so {@code parameter/foo} falls back to {@code foo} when only {@code foo} is stored. A version or
* label selector after the last colon is kept, but the fallback checks the name without it.
* lack, so {@code parameter/foo} falls back to {@code foo} when only {@code foo} is stored, but
* {@code parameter//foo} names {@code //foo} and never falls back to {@code /foo}. A version or label selector
* after the last colon is kept, but the fallback checks the name without it.
*/
private String parameterName(String nameOrArn, String region) {
return parameterName(nameOrArn, region, false);
@@ -1293,6 +1340,43 @@ public class SsmService implements ResourceProvider {
return parameterName(nameOrArn, region, true);
}
/**
* The stored name a tagging {@code ResourceId} addresses. A legacy {@code parameter<name>} ARN of the request's
* partition, region and account is read as {@code parameter/<name>}; see {@link #withLegacyParameterSlash}.
*/
private String parameterTagName(String resourceId, String region) {
return parameterReadName(withLegacyParameterSlash(resourceId,
regionResolver.partitionForRegion(region), region, regionResolver.getAccountId()), region);
}
/**
* The {@code parameter/<name>} ARN for a legacy {@code parameter<name>} ARN of the given partition, region and
* account. Floci gave a top-level parameter that form before its ARNs matched AWS, and tagging still resolves
* it. Any other value, including a legacy ARN of another partition, region or account, is returned as is.
*/
private static String withLegacyParameterSlash(String resourceId, String partition, String region,
String accountId) {
if (resourceId == null || !AwsArnUtils.looksLikeArn(resourceId)) {
return resourceId;
}
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(resourceId);
} catch (IllegalArgumentException e) {
return resourceId;
}
if (!"ssm".equals(arn.service()) || !arn.resource().startsWith("parameter")) {
return resourceId;
}
String name = arn.resource().substring("parameter".length());
if (name.isEmpty() || name.startsWith("/") || !arn.partition().equals(partition)
|| !arn.region().equals(region) || !arn.accountId().equals(accountId)) {
return resourceId;
}
return new AwsArnUtils.Arn(arn.partition(), arn.service(), arn.region(), arn.accountId(),
"parameter/" + name).toString();
}
private String parameterName(String nameOrArn, String region, boolean parameterRead) {
if (AwsArnUtils.looksLikeArn(nameOrArn)) {
try {
@@ -1308,7 +1392,8 @@ public class SsmService implements ResourceProvider {
String name = arn.resource().substring("parameter".length());
int separator = name.lastIndexOf(':');
String baseName = separator > 0 ? name.substring(0, separator) : name;
if (baseName.startsWith("/") && parameterStore.get(regionKey(region, baseName)).isEmpty()
if (baseName.startsWith("/") && !baseName.startsWith("//")
&& parameterStore.get(regionKey(region, baseName)).isEmpty()
&& parameterStore.get(regionKey(region, baseName.substring(1))).isPresent()) {
return name.substring(1);
}
@@ -480,8 +480,7 @@ class CloudFormationSsmRollbackIntegrationTest {
Mockito.doThrow(new AwsException("InternalServerError", "simulated restore failure", 500))
.doCallRealMethod()
.when(ssmService)
.putParameter(eq(name), eq(priorValue), any(), any(), eq(true), any(), any(), any(), any(), any(),
anyString());
.restoreParameter(eq(name), eq(priorValue), any(), any(), any(), any(), any(), any(), anyString());
}
private void failDeleting(String name) {
@@ -136,6 +136,44 @@ class SsmCfnProvisionerTest {
assertEquals("env,team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
}
@Test
void aNameWithSurroundingSpacesIsRecordedAsTheNameSsmStores() {
StackResource r = parameter(null, null);
provisioner.provision(r, props().put("Name", " " + NAME + " "), ctx());
verify(ssm).putParameter(NAME, "v", "String", null, false, Map.of(), REGION);
assertEquals(NAME, r.getPhysicalId());
assertEquals(NAME, r.getAttributes().get("Name"));
assertEquals(ARN, r.getAttributes().get("Arn"));
}
@Test
void aPriorPhysicalIdWithSurroundingSpacesIsReplacedByTheStrippedName() {
String spaced = " " + NAME + " ";
StackResource r = parameter(spaced, null);
ProvisionContext create = ctx();
ProvisionContext update = new ProvisionContext(create.engine(), create.region(), create.accountId(),
create.stackName(), spaced);
provisioner.provision(r, props().put("Name", spaced), update);
verify(ssm, never()).getParameter(anyString(), anyString());
verify(ssm).putParameter(NAME, "v", "String", null, false, Map.of(), REGION);
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), eq(true), anyString());
assertEquals(NAME, r.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(spaced, provisioner.updateCleanupPhysicalId(r));
assertFalse(provisioner.retainsFailedUpdateState(r));
UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
provisioner.clearUpdate(r);
assertTrue(cleanup.complete());
verify(ssm).deleteParameter(spaced, REGION);
verify(ssm, never()).deleteParameter(NAME, REGION);
}
@Test
void parameterWithoutTagsIsNotTagged() {
StackResource r = parameter(null, null);
@@ -209,8 +247,8 @@ class SsmCfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(r));
verify(ssm).putParameter(NAME, "old", "String", "described outside the stack", true, null, null,
"^[a-z]+$", "Advanced", policies, REGION);
verify(ssm).restoreParameter(NAME, "old", "String", "described outside the stack", null, "^[a-z]+$",
"Advanced", policies, REGION);
verify(ssm).removeTagsFromResource(NAME, List.of("added"), REGION);
verify(ssm).addTagsToResource(NAME, Map.of("env", "dev", "team", "a"), REGION);
verify(ssm, never()).addTagsToResource(eq(NAME), argThat(tags -> tags.containsKey("external")), eq(REGION));
@@ -225,8 +263,8 @@ class SsmCfnProvisionerTest {
StackResource r = parameter(NAME, null);
provisioner.provision(r, props(), updateCtx());
afterTheUpdate(Map.of());
when(ssm.putParameter(eq(NAME), eq("old"), eq("String"), any(), eq(true), any(), any(), any(), any(),
any(), eq(REGION)))
when(ssm.restoreParameter(eq(NAME), eq("old"), eq("String"), any(), any(), any(), any(), any(),
eq(REGION)))
.thenThrow(new AwsException("InternalServerError", "simulated", 500))
.thenReturn(3L);
@@ -260,10 +298,10 @@ class SsmCfnProvisionerTest {
provisioner.provision(skipped, props(), updateCtx(stored("current", Map.of())));
afterTheUpdate(Map.of());
assertTrue(provisioner.rollbackUpdate(skipped));
verify(ssm).putParameter(eq(NAME), eq("current"), eq("String"), any(), eq(true), any(), any(), any(),
any(), any(), eq(REGION));
verify(ssm, never()).putParameter(eq(NAME), eq("stale"), anyString(), any(), anyBoolean(), any(), any(),
any(), any(), any(), anyString());
verify(ssm).restoreParameter(eq(NAME), eq("current"), eq("String"), any(), any(), any(), any(), any(),
eq(REGION));
verify(ssm, never()).restoreParameter(eq(NAME), eq("stale"), anyString(), any(), any(), any(), any(),
any(), anyString());
}
/** AWS's handler checks the parameter exists before an update in place writes it. */
@@ -292,8 +330,8 @@ class SsmCfnProvisionerTest {
assertEquals("ParameterNotFound",
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)).getErrorCode());
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), any(), any(),
any(), any(), any(), anyString());
verify(ssm, never()).restoreParameter(anyString(), anyString(), anyString(), any(), any(), any(), any(),
any(), anyString());
assertTrue(provisioner.retainsFailedUpdateState(r));
}
@@ -305,8 +343,8 @@ class SsmCfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(r));
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), any(), any(),
any(), any(), any(), anyString());
verify(ssm, never()).restoreParameter(anyString(), anyString(), anyString(), any(), any(), any(), any(),
any(), anyString());
verify(ssm).addTagsToResource(NAME, Map.of("team", "a"), REGION);
}
@@ -1903,6 +1903,95 @@ class SsmIntegrationTest {
.body("Parameters", hasSize(0));
}
@Test
void putParameterRejectsANameOutsideTheParameterNameSyntaxAndStoresNothing() {
for (String name : List.of("/name-syntax/db:secret", "/name-syntax/db secret", "/name-syntax/db\\t",
"\\u00a0/name-syntax/db")) {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"" + name + "\", \"Value\": \"v\", \"Type\": \"String\" }")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Parameter name: can't be prefixed with \"aws\" or \"ssm\" "
+ "(case-insensitive). If formed as a path, it can consist of sub-paths divided by slash "
+ "symbol; each sub-path can be formed as a mix of letters, numbers and the following 3 "
+ "symbols .-_"));
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"" + name + "\" }")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterNotFound"));
}
}
@Test
void putParameterStoresANameWithoutItsSurroundingSpaces() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \" /name-spaces/db \", \"Value\": \"v\", \"Type\": \"String\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("Version", equalTo(1));
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"/name-spaces/db\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameter.Name", equalTo("/name-spaces/db"))
.body("Parameter.Value", equalTo("v"));
}
@Test
void aDoubleSlashArnDoesNotReadTheParameterUnderOneSlash() {
String name = "/double-slash-" + UUID.randomUUID();
String doubleSlashArn = "arn:aws:ssm:us-east-1:000000000000:parameter/" + name;
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"" + name + "\", \"Value\": \"v\", \"Type\": \"String\" }")
.when()
.post("/")
.then()
.statusCode(200);
for (String selected : List.of(doubleSlashArn, doubleSlashArn + ":1")) {
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Name\": \"" + selected + "\" }")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ParameterNotFound"));
given()
.header("X-Amz-Target", "AmazonSSM.GetParameters")
.contentType(SSM_CONTENT_TYPE)
.body("{ \"Names\": [\"" + selected + "\"] }")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameters", hasSize(0))
.body("InvalidParameters", contains(selected));
}
}
private void putIntelligentTiering(String name, String jsonEscapedValue) {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
@@ -236,6 +236,24 @@ class SsmServiceTest {
+ "Member must have length less than or equal to 128", ex.getMessage());
}
@Test
void restoreParameter_overwritesANameThatPutParameterRejectsUnderThatExactName() {
String legacy = " /legacy name ";
assertThrows(AwsException.class,
() -> ssmService.putParameter(legacy, "v", "String", null, true, "us-east-1"));
ssmService.restoreParameter(legacy, "v1", "String", null, null, null, null, null, "us-east-1");
long version = ssmService.restoreParameter(legacy, "v2", "String", "restored", null, null, null, null,
"us-east-1");
assertEquals(2L, version);
Parameter restored = ssmService.getParameter(legacy, "us-east-1");
assertEquals(legacy, restored.getName());
assertEquals("v2", restored.getValue());
assertEquals("restored", restored.getDescription());
assertThrows(AwsException.class, () -> ssmService.getParameter("/legacy name", "us-east-1"));
}
@Test
void putParameter_invalidTagKeyIsRejectedAndTheParameterIsNotCreated() {
String region = "eu-west-1";
@@ -1590,6 +1608,39 @@ class SsmServiceTest {
assertEquals(Map.of(), ssmService.listTagsForResource("arn-tagged", "us-east-1"));
}
@Test
void tagOperations_byLegacyArnWithoutParameterSlash_tagTheTopLevelParameter() {
ssmService.putParameter("legacy-tagged", "v", "String", null, false, "us-east-1");
String legacyArn = "arn:aws:ssm:us-east-1:000000000000:parameterlegacy-tagged";
ssmService.addTagsToResource(legacyArn, Map.of("env", "dev", "team", "core"), "us-east-1");
assertEquals(Map.of("env", "dev", "team", "core"), ssmService.listTagsForResource(legacyArn, "us-east-1"));
ssmService.removeTagsFromResource(legacyArn, List.of("team"), "us-east-1");
assertEquals(Map.of("env", "dev"), ssmService.listTagsForResource("legacy-tagged", "us-east-1"));
}
@Test
void tagOperations_byArn_findNothingOutsideTheRequestRegionAndAccount() {
ssmService.putParameter("/arn/scoped", "v", "String", null, false, "us-east-1");
ssmService.putParameter("secret", "v", "String", null, false, "us-east-1");
for (String arn : List.of("arn:aws:ssm:us-west-2:000000000000:parameter/arn/scoped",
"arn:aws:ssm:us-east-1:111122223333:parameter/arn/scoped",
"arn:aws-us-gov:ssm:us-east-1:000000000000:parameter/arn/scoped",
"arn:aws:ssm:us-west-2:000000000000:parametersecret",
"arn:aws:ssm:us-east-1:111122223333:parametersecret",
"arn:aws-us-gov:ssm:us-east-1:000000000000:parametersecret")) {
AwsException ex = assertThrows(AwsException.class,
() -> ssmService.addTagsToResource(arn, Map.of("env", "dev"), "us-east-1"));
assertEquals("InvalidResourceId", ex.getErrorCode());
assertThrows(AwsException.class, () -> ssmService.listTagsForResource(arn, "us-east-1"));
assertThrows(AwsException.class,
() -> ssmService.removeTagsFromResource(arn, List.of("env"), "us-east-1"));
}
assertEquals(Map.of(), ssmService.listTagsForResource("/arn/scoped", "us-east-1"));
assertEquals(Map.of(), ssmService.listTagsForResource("secret", "us-east-1"));
}
@Test
void tagOperations_byArn_findAPathStoredWithoutLeadingSlash() {
ssmService.putParameter("arn/relative", "v", "String", null, false, "us-east-1");