feat(ssm): support UnlabelParameterVersion (#5339)

* feat(ssm): support UnlabelParameterVersion

Remove one or more labels from a parameter version. Labels attached to
the version are returned in RemovedLabels; labels that are not on that
version, including ones attached to a different version, are returned in
InvalidLabels and left in place. A missing parameter is ParameterNotFound,
a missing version ParameterVersionNotFound, and an omitted ParameterVersion
or an empty or oversized label list a ValidationException.

* fix(ssm): match AWS errors and ordering in UnlabelParameterVersion

Verified against real AWS (us-east-1):

- Report every missing or invalid member in one ValidationException, in
  the order name, parameterVersion, labels, and render the label list
  the way AWS does ('[prod, ]').
- Reject a string or boolean ParameterVersion and a non-string Name or
  label with SerializationException; truncate a fractional version and
  clamp one outside the range of a long, as AWS does.
- Reject an ARN, a malformed or ssm-prefixed name, and deny an
  aws-prefixed one before the lookup; ignore surrounding whitespace in
  the lookup but echo the name as sent in error messages.
- Word ParameterVersionNotFound as AWS does.
- Return RemovedLabels in the order the labels are stored on the
  version, and InvalidLabels in request order.

LabelParameterVersion shares the label-list parsing, so its label
validation messages and non-string labels now match AWS too.

* fix(ssm): take the service monitor when deleting parameters

PutParameter, LabelParameterVersion and UnlabelParameterVersion already
run under the SsmService monitor, but DeleteParameter and
DeleteParameters did not. A delete landing between a label or unlabel
call's lookup and its history write left orphaned history that a later
PutParameter of the same name appended to.

Also pin LabelParameterVersion's AWS-verified label validation messages
and its SerializationException for a non-string label in its own
integration test, and share the parameter-name format rule between the
two reserved-name messages.
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-10-09 13:11:29 -04:00
1 parent 07ebc33d28
commit 4f34a903fc
7 files changed
+651 -81

No files matched your search

@@ -26,6 +26,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -65,6 +66,7 @@ public class SsmJsonHandler {
case "GetParameterHistory" -> handleGetParameterHistory(request, region);
case "DescribeParameters" -> handleDescribeParameters(request, region);
case "LabelParameterVersion" -> handleLabelParameterVersion(request, region);
case "UnlabelParameterVersion" -> handleUnlabelParameterVersion(request, region);
case "AddTagsToResource" -> handleAddTagsToResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(request, region);
@@ -1021,46 +1023,70 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
private static final int MAX_LABELS = 10;
private static final int MAX_LABEL_LENGTH = 100;
private static final BigDecimal LONG_MIN = BigDecimal.valueOf(Long.MIN_VALUE);
private static final BigDecimal LONG_MAX = BigDecimal.valueOf(Long.MAX_VALUE);
private List<String> requireLabels(JsonNode request) {
List<String> labels = optionalLabels(request);
String violation = SsmService.labelListViolation(labels);
if (violation != null) {
throw SsmService.validationErrors(List.of(violation));
}
return labels;
}
/** The {@code Labels} member, or null when absent; a non-string member fails to deserialize, as on AWS. */
private static List<String> optionalLabels(JsonNode request) {
JsonNode labelsNode = request.path("Labels");
if (labelsNode.isMissingNode() || labelsNode.isNull()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at 'labels' failed to satisfy constraint: Member must not be null",
400);
}
if (!labelsNode.isArray() || labelsNode.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
400);
}
if (labelsNode.size() > MAX_LABELS) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to "
+ MAX_LABELS,
400);
return null;
}
List<String> labels = new ArrayList<>(labelsNode.size());
for (JsonNode l : labelsNode) {
String label = l.asText();
if (!l.isTextual() || label.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
400);
if (l.isNull()) {
labels.add(null);
} else if (l.isTextual()) {
labels.add(l.textValue());
} else {
throw serializationException(l, "String");
}
if (label.length() > MAX_LABEL_LENGTH) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to "
+ MAX_LABEL_LENGTH,
400);
}
labels.add(label);
}
return labels;
}
private static String optionalString(JsonNode request, String field) {
JsonNode node = request.path(field);
if (node.isMissingNode() || node.isNull()) {
return null;
}
if (!node.isTextual()) {
throw serializationException(node, "String");
}
return node.textValue();
}
/** AWS truncates a fractional number and clamps one outside the range of a long. */
private static Long optionalLong(JsonNode request, String field) {
JsonNode node = request.path(field);
if (node.isMissingNode() || node.isNull()) {
return null;
}
if (!node.isNumber()) {
throw serializationException(node, "Long");
}
return node.decimalValue().max(LONG_MIN).min(LONG_MAX).longValue();
}
private static AwsException serializationException(JsonNode node, String targetType) {
String token = switch (node.getNodeType()) {
case STRING -> "STRING_VALUE";
case NUMBER -> "NUMBER_VALUE";
case BOOLEAN -> node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
default -> node.getNodeType().name();
};
return new AwsException("SerializationException", token + " can not be converted to a " + targetType, 400);
}
private Response handleLabelParameterVersion(JsonNode request, String region) {
String name = request.path("Name").asText();
Long parameterVersion = request.hasNonNull("ParameterVersion")
@@ -1079,6 +1105,41 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
private Response handleUnlabelParameterVersion(JsonNode request, String region) {
String name = optionalString(request, "Name");
Long parameterVersion = optionalLong(request, "ParameterVersion");
List<String> labels = optionalLabels(request);
List<String> violations = new ArrayList<>();
if (name == null) {
violations.add("Value null at 'name' failed to satisfy constraint: Member must not be null");
} else if (name.isEmpty()) {
violations.add("Value '' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 1");
}
if (parameterVersion == null) {
violations.add("Value null at 'parameterVersion' failed to satisfy constraint: Member must not be null");
}
String labelViolation = SsmService.labelListViolation(labels);
if (labelViolation != null) {
violations.add(labelViolation);
}
if (!violations.isEmpty()) {
throw SsmService.validationErrors(violations);
}
SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
name, parameterVersion, labels, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode removedArray = objectMapper.createArrayNode();
result.removedLabels().forEach(removedArray::add);
response.set("RemovedLabels", removedArray);
ArrayNode invalidArray = objectMapper.createArrayNode();
result.invalidLabels().forEach(invalidArray::add);
response.set("InvalidLabels", invalidArray);
return Response.ok(response).build();
}
private Response handleAddTagsToResource(JsonNode request, String region) {
String resourceId = request.path("ResourceId").asText();
Map<String, String> tags = new LinkedHashMap<>();
@@ -62,6 +62,12 @@ public class SsmService implements ResourceProvider {
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;
/** The tail AWS appends to every rejected parameter name, whichever prefix the operation reserves. */
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 .-_";
/** 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_.:-]+)+");
/**
* Account-default values for the service settings floci models. AWS rejects
@@ -454,9 +460,7 @@ public class SsmService implements ResourceProvider {
|| lower.startsWith("aws/") || lower.startsWith("ssm/")) {
throw new AwsException("ValidationException",
"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 .-_", 400);
+ PARAMETER_NAME_FORMAT_RULE, 400);
}
}
@@ -560,7 +564,7 @@ public class SsmService implements ResourceProvider {
return !paramName.substring(normalizedPath.length()).contains("/");
}
public void deleteParameter(String name, String region) {
public synchronized void deleteParameter(String name, String region) {
String storageKey = regionKey(region, name);
if (parameterStore.get(storageKey).isEmpty()) {
throw new AwsException("ParameterNotFound",
@@ -571,7 +575,7 @@ public class SsmService implements ResourceProvider {
LOG.infov("Deleted parameter: {0}", name);
}
public List<String> deleteParameters(List<String> names, String region) {
public synchronized List<String> deleteParameters(List<String> names, String region) {
List<String> deleted = new ArrayList<>();
for (String name : names) {
String storageKey = regionKey(region, name);
@@ -686,28 +690,7 @@ public class SsmService implements ResourceProvider {
public synchronized LabelParameterVersionResult labelParameterVersion(String name, Long parameterVersion,
List<String> labels, String region) {
if (labels == null || labels.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
400);
}
if (labels.size() > 10) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to 10",
400);
}
for (String label : labels) {
if (label == null || label.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
400);
}
if (label.length() > 100) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to 100",
400);
}
}
validateLabelList(labels);
String storageKey = regionKey(region, name);
Parameter current = parameterStore.get(storageKey).orElseThrow(() ->
@@ -791,6 +774,109 @@ public class SsmService implements ResourceProvider {
return labelParameterVersion(name, Long.valueOf(parameterVersion), labels, region);
}
public record UnlabelParameterVersionResult(List<String> removedLabels, List<String> invalidLabels) {}
/**
* Detaches labels from one version. A label that is not on that version, including one
* attached to a different version, is reported in {@code invalidLabels} and left in place.
* As on AWS, {@code removedLabels} follows the order the labels are stored on the version,
* {@code invalidLabels} the order of the request, and error messages echo the name as sent
* although the lookup ignores surrounding whitespace.
*/
public synchronized UnlabelParameterVersionResult unlabelParameterVersion(String name, long parameterVersion,
List<String> labels, String region) {
validateLabelList(labels);
String trimmed = name.strip();
if (AwsArnUtils.isArn(trimmed)) {
throw new AwsException("ValidationException", "Parameter ARN is not supported for this operation.", 400);
}
String bare = trimmed.startsWith("/") ? trimmed.substring(1) : trimmed;
String lower = bare.toLowerCase(Locale.ROOT);
if (!UNLABEL_NAME_PATTERN.matcher(trimmed).matches() || lower.startsWith("ssm")) {
throw new AwsException("ValidationException",
"Parameter name: can't be prefixed with \"ssm\" (case-insensitive). "
+ PARAMETER_NAME_FORMAT_RULE, 400);
}
if (lower.startsWith("aws")) { // partition-literal: reserved parameter name prefix
throw new AwsException("AccessDeniedException",
"No access to reserved parameter name: " + bare + ".", 400);
}
String storageKey = regionKey(region, trimmed);
if (parameterStore.get(storageKey).isEmpty()) {
throw new AwsException("ParameterNotFound", "Parameter " + name + " not found.", 400);
}
List<ParameterHistory> existingHistory = historyStore.get(storageKey).orElse(List.of());
List<ParameterHistory> updatedHistory = new ArrayList<>(existingHistory.size());
ParameterHistory targetCopy = null;
for (ParameterHistory h : existingHistory) {
ParameterHistory copy = new ParameterHistory(h);
if (copy.getVersion() == parameterVersion) {
targetCopy = copy;
}
updatedHistory.add(copy);
}
if (targetCopy == null) {
throw new AwsException("ParameterVersionNotFound",
"Systems Manager could not find version " + parameterVersion + " of " + name
+ ". Verify the version and try again.", 400);
}
List<String> targetLabels = targetCopy.getLabels() != null
? new ArrayList<>(targetCopy.getLabels())
: new ArrayList<>();
Set<String> requested = new LinkedHashSet<>(labels);
List<String> removedLabels = targetLabels.stream().filter(requested::contains).toList();
List<String> invalidLabels = requested.stream().filter(l -> !targetLabels.contains(l)).toList();
if (!removedLabels.isEmpty()) {
targetLabels.removeAll(requested);
targetCopy.setLabels(targetLabels);
historyStore.put(storageKey, updatedHistory);
LOG.infov("Removed labels {0} from parameter {1} version {2}", removedLabels, trimmed, parameterVersion);
}
return new UnlabelParameterVersionResult(removedLabels, invalidLabels);
}
private static void validateLabelList(List<String> labels) {
String violation = labelListViolation(labels);
if (violation != null) {
throw validationErrors(List.of(violation));
}
}
/**
* The constraint a {@code ParameterLabelList} breaks, worded as AWS words it, or null. AWS
* renders the list with Java's {@code List.toString}, so {@code [""]} reads {@code '[]'}.
*/
static String labelListViolation(List<String> labels) {
if (labels == null) {
return "Value null at 'labels' failed to satisfy constraint: Member must not be null";
}
String prefix = "Value '" + labels + "' at 'labels' failed to satisfy constraint: ";
if (labels.isEmpty()) {
return prefix + "Member must have length greater than or equal to 1";
}
if (labels.size() > 10) {
return prefix + "Member must have length less than or equal to 10";
}
boolean memberOutOfRange = labels.stream()
.anyMatch(label -> label == null || label.isEmpty() || label.length() > 100);
if (memberOutOfRange) {
return prefix + "Member must satisfy constraint: [Member must have length less than or equal to 100, "
+ "Member must have length greater than or equal to 1]";
}
return null;
}
static AwsException validationErrors(List<String> violations) {
String count = violations.size() == 1
? "1 validation error detected: "
: violations.size() + " validation errors detected: ";
return new AwsException("ValidationException", count + String.join("; ", violations), 400);
}
private static boolean isValidLabel(String label) {
if (label == null || label.isEmpty() || label.length() > 100) {
return false;