mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecr): check lifecycle policies against the rules ECR documents (#9304)
PutLifecyclePolicy and an AWS::ECR::Repository's LifecyclePolicy now refuse what the ECR user guide rules out: a tagged rule without exactly one tag filter, filters on other statuses, more than four wildcards in a pattern, unknown count types, a countUnit other than days for the since types or any countUnit for imageCountMoreThan, a countNumber below 1, storage classes and actions that do not fit the count type, an any rule that is not last, two untagged rules and a prefix used by two rules in one storage class. Refusals use ECR's message form and keep the prior policy. Part of #5874.
This commit is contained in:
1 parent
d4bbb1bf96
commit
0cef64ebad
5 files changed
+672
-25
No files matched your search
+15
-4
@@ -44,10 +44,21 @@
|
||||
| `PutRegistryScanningConfiguration` / `GetRegistryScanningConfiguration` | Store the registry's scan type and scanning rules (stored, not acted on) |
|
||||
| `GetAccountSetting` / `PutAccountSetting` | Read and store account settings for the registry (stored, not acted on) |
|
||||
|
||||
`PutLifecyclePolicy` checks that the document is one JSON object with a nonempty
|
||||
`rules` array and unique positive integer priorities. Rejected documents return
|
||||
`InvalidParameterException` without replacing the prior policy. Selection and
|
||||
action validation, expiration, and registry garbage collection remain unimplemented.
|
||||
`PutLifecyclePolicy`, and an `AWS::ECR::Repository` in CloudFormation, check the document
|
||||
against the rules in the ECR user guide:
|
||||
|
||||
- At least one rule, each with a unique positive `rulePriority`.
|
||||
- `tagStatus` is `tagged`, `untagged` or `any`. A `tagged` rule needs exactly one of `tagPrefixList` and `tagPatternList`, and the other two statuses allow neither. A pattern can have at most four `*` wildcards.
|
||||
- `countType` is `imageCountMoreThan`, `sinceImagePushed`, `sinceImagePulled` or `sinceImageTransitioned`. The three `since` types need `countUnit` `days`, and `imageCountMoreThan` takes no `countUnit`. `countNumber` is a positive integer.
|
||||
- `storageClass` is `standard`, the default, except for `sinceImageTransitioned`, which needs `archive`.
|
||||
- `action.type` is `expire` or `transition`. A `transition` needs `targetStorageClass` `archive`, and `sinceImageTransitioned` allows only `expire`.
|
||||
- Among the rules selecting one storage class, an `any` rule has a higher `rulePriority` than every other rule, only one rule selects untagged images, and no tag prefix appears in two rules.
|
||||
|
||||
Enum values are matched without regard to case. A refused document returns
|
||||
`InvalidParameterException` with ECR's message form, `Invalid parameter at 'LifecyclePolicyText'
|
||||
failed to satisfy constraint: 'Lifecycle policy validation failure: ...'` (`Lifecycle policy parsing
|
||||
failure: ...` for a document that is not a JSON object of the right shape), and the prior policy is
|
||||
kept. Expiration and registry garbage collection remain unimplemented.
|
||||
|
||||
`GetAccountSetting` and `PutAccountSetting` keep values per account and Region.
|
||||
Supported names are `BASIC_SCAN_TYPE_VERSION` (`AWS_NATIVE`), `REGISTRY_POLICY_SCOPE`
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
package io.floci.aws.services.ecr;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A lifecycle policy document as {@code PutLifecyclePolicy} takes it, checked against the rules the ECR user guide
|
||||
* gives for lifecycle policy properties and their evaluation. Enum values are matched without regard to case.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/lifecycle_policy_parameters.html">Lifecycle
|
||||
* policy properties</a>
|
||||
*/
|
||||
public record EcrLifecyclePolicy(List<Rule> rules) {
|
||||
|
||||
/** Which images a rule's selection looks at by their tags. */
|
||||
public enum TagStatus { TAGGED, UNTAGGED, ANY }
|
||||
|
||||
/** The storage class a rule selects images of. */
|
||||
public enum StorageClass { STANDARD, ARCHIVE }
|
||||
|
||||
/** What a rule counts against {@code countNumber}. */
|
||||
public enum CountType {
|
||||
IMAGE_COUNT_MORE_THAN("imageCountMoreThan"),
|
||||
SINCE_IMAGE_PUSHED("sinceImagePushed"),
|
||||
SINCE_IMAGE_PULLED("sinceImagePulled"),
|
||||
SINCE_IMAGE_TRANSITIONED("sinceImageTransitioned");
|
||||
|
||||
private final String wireName;
|
||||
|
||||
CountType(String wireName) {
|
||||
this.wireName = wireName;
|
||||
}
|
||||
|
||||
public String wireName() {
|
||||
return wireName;
|
||||
}
|
||||
|
||||
boolean countsDays() {
|
||||
return this != IMAGE_COUNT_MORE_THAN;
|
||||
}
|
||||
}
|
||||
|
||||
/** What a rule does to the images it selects. */
|
||||
public enum ActionType { EXPIRE, TRANSITION }
|
||||
|
||||
/**
|
||||
* One rule. {@code tagPatterns} and {@code tagPrefixes} are empty unless the rule selects tagged images, and at
|
||||
* most one of them is not.
|
||||
*/
|
||||
public record Rule(int priority, TagStatus tagStatus, List<String> tagPatterns, List<String> tagPrefixes,
|
||||
StorageClass storageClass, CountType countType, int countNumber, ActionType action) {}
|
||||
|
||||
private static final ObjectReader SINGLE_JSON_VALUE =
|
||||
new ObjectMapper().reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
private static final int MAX_PATTERN_WILDCARDS = 4;
|
||||
|
||||
/** Parses and checks {@code text}; a document ECR would refuse is refused with ECR's message form. */
|
||||
public static EcrLifecyclePolicy parse(String text) {
|
||||
JsonNode policy;
|
||||
try {
|
||||
policy = text == null ? null : SINGLE_JSON_VALUE.readTree(text);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
if (policy == null || !policy.isObject()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
JsonNode rules = present(policy.get("rules"));
|
||||
if (rules != null && !rules.isArray()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
if (rules == null || rules.isEmpty()) {
|
||||
throw validationFailure("A lifecycle policy must have at least one rule.");
|
||||
}
|
||||
List<Rule> parsed = new ArrayList<>();
|
||||
Set<Integer> priorities = new HashSet<>();
|
||||
for (JsonNode rule : rules) {
|
||||
Rule next = rule(rule);
|
||||
if (!priorities.add(next.priority())) {
|
||||
throw validationFailure("Each rule must have a unique rulePriority.");
|
||||
}
|
||||
parsed.add(next);
|
||||
}
|
||||
checkRulesOfEachStorageClass(parsed);
|
||||
return new EcrLifecyclePolicy(List.copyOf(parsed));
|
||||
}
|
||||
|
||||
private static Rule rule(JsonNode rule) {
|
||||
if (!rule.isObject()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
Integer priority = positiveInteger(rule.get("rulePriority"));
|
||||
if (priority == null) {
|
||||
throw validationFailure("rulePriority must be a positive integer.");
|
||||
}
|
||||
JsonNode selection = object(rule, "selection", "Every rule must have a selection.");
|
||||
TagStatus tagStatus = enumValue(selection.get("tagStatus"), TagStatus.class);
|
||||
if (tagStatus == null) {
|
||||
throw validationFailure("tagStatus must be tagged, untagged or any.");
|
||||
}
|
||||
List<String> patterns = strings(selection, "tagPatternList");
|
||||
List<String> prefixes = strings(selection, "tagPrefixList");
|
||||
checkTagFilters(tagStatus, patterns, prefixes);
|
||||
|
||||
CountType countType = countType(selection.get("countType"));
|
||||
StorageClass storageClass = storageClass(selection.get("storageClass"), countType);
|
||||
checkCountUnit(present(selection.get("countUnit")), countType);
|
||||
int countNumber = countNumber(selection.get("countNumber"));
|
||||
|
||||
JsonNode action = object(rule, "action", "Every rule must have an action.");
|
||||
ActionType actionType = enumValue(action.get("type"), ActionType.class);
|
||||
if (actionType == null) {
|
||||
throw validationFailure("The action type must be expire or transition.");
|
||||
}
|
||||
if (actionType == ActionType.TRANSITION) {
|
||||
if (enumValue(action.get("targetStorageClass"), StorageClass.class) != StorageClass.ARCHIVE) {
|
||||
throw validationFailure("targetStorageClass must be archive when the action type is transition.");
|
||||
}
|
||||
if (countType == CountType.SINCE_IMAGE_TRANSITIONED) {
|
||||
throw validationFailure("countType sinceImageTransitioned can only be used with the expire action.");
|
||||
}
|
||||
}
|
||||
return new Rule(priority, tagStatus, patterns, prefixes, storageClass, countType, countNumber, actionType);
|
||||
}
|
||||
|
||||
private static void checkTagFilters(TagStatus tagStatus, List<String> patterns, List<String> prefixes) {
|
||||
if (tagStatus != TagStatus.TAGGED) {
|
||||
if (!patterns.isEmpty() || !prefixes.isEmpty()) {
|
||||
throw validationFailure("tagPrefixList and tagPatternList can only be used when tagStatus=TAGGED.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!patterns.isEmpty() && !prefixes.isEmpty()) {
|
||||
throw validationFailure("A rule can specify tagPrefixList or tagPatternList, but not both.");
|
||||
}
|
||||
if (patterns.isEmpty() && prefixes.isEmpty()) {
|
||||
throw validationFailure("Must specify tagPrefixList or tagPatternList when tagStatus=TAGGED.");
|
||||
}
|
||||
for (String pattern : patterns) {
|
||||
if (pattern.chars().filter(c -> c == '*').count() > MAX_PATTERN_WILDCARDS) {
|
||||
throw validationFailure("A tag pattern can have at most " + MAX_PATTERN_WILDCARDS + " wildcards.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CountType countType(JsonNode node) {
|
||||
String value = node != null && node.isTextual() ? node.asText() : null;
|
||||
for (CountType countType : CountType.values()) {
|
||||
if (countType.wireName().equalsIgnoreCase(value)) {
|
||||
return countType;
|
||||
}
|
||||
}
|
||||
throw validationFailure(
|
||||
"countType must be imageCountMoreThan, sinceImagePushed, sinceImagePulled or sinceImageTransitioned.");
|
||||
}
|
||||
|
||||
/** Archived images are selected only by age in the archive, and only that count selects them. */
|
||||
private static StorageClass storageClass(JsonNode node, CountType countType) {
|
||||
StorageClass storageClass = StorageClass.STANDARD;
|
||||
if (present(node) != null) {
|
||||
storageClass = enumValue(node, StorageClass.class);
|
||||
if (storageClass == null) {
|
||||
throw validationFailure("storageClass must be standard or archive.");
|
||||
}
|
||||
}
|
||||
boolean archive = countType == CountType.SINCE_IMAGE_TRANSITIONED;
|
||||
if (archive && storageClass != StorageClass.ARCHIVE) {
|
||||
throw validationFailure("storageClass must be archive when countType is sinceImageTransitioned.");
|
||||
}
|
||||
if (!archive && storageClass != StorageClass.STANDARD) {
|
||||
throw validationFailure("storageClass must be standard when countType is " + countType.wireName() + ".");
|
||||
}
|
||||
return storageClass;
|
||||
}
|
||||
|
||||
private static void checkCountUnit(JsonNode countUnit, CountType countType) {
|
||||
if (!countType.countsDays()) {
|
||||
if (countUnit != null) {
|
||||
throw validationFailure("countUnit can only be used when countType is sinceImagePushed, "
|
||||
+ "sinceImagePulled or sinceImageTransitioned.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (countUnit == null || !countUnit.isTextual() || !"days".equalsIgnoreCase(countUnit.asText())) {
|
||||
throw validationFailure("countUnit must be days when countType is " + countType.wireName() + ".");
|
||||
}
|
||||
}
|
||||
|
||||
/** A countNumber below 1 is refused with the JSON schema validator's own text, as ECR quotes it. */
|
||||
private static int countNumber(JsonNode node) {
|
||||
if (node != null && node.isIntegralNumber() && node.canConvertToInt() && node.intValue() < 1) {
|
||||
throw validationFailure("numeric instance is lower than the required minimum (minimum: 1, found: "
|
||||
+ node.intValue() + ")\n");
|
||||
}
|
||||
Integer countNumber = positiveInteger(node);
|
||||
if (countNumber == null) {
|
||||
throw validationFailure("countNumber must be a positive integer.");
|
||||
}
|
||||
return countNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks across the rules selecting one storage class: a rule selecting any image has a higher rulePriority than
|
||||
* every rule that does not, at most one rule selects untagged images, and no tag prefix appears in two rules.
|
||||
*/
|
||||
private static void checkRulesOfEachStorageClass(List<Rule> rules) {
|
||||
Map<StorageClass, List<Rule>> byStorageClass = new EnumMap<>(StorageClass.class);
|
||||
for (Rule rule : rules) {
|
||||
byStorageClass.computeIfAbsent(rule.storageClass(), ignored -> new ArrayList<>()).add(rule);
|
||||
}
|
||||
for (List<Rule> group : byStorageClass.values()) {
|
||||
int highestSelective = Integer.MIN_VALUE;
|
||||
int lowestAny = Integer.MAX_VALUE;
|
||||
int untagged = 0;
|
||||
Set<String> prefixes = new HashSet<>();
|
||||
for (Rule rule : group) {
|
||||
switch (rule.tagStatus()) {
|
||||
case ANY -> lowestAny = Math.min(lowestAny, rule.priority());
|
||||
case UNTAGGED -> {
|
||||
highestSelective = Math.max(highestSelective, rule.priority());
|
||||
untagged++;
|
||||
}
|
||||
case TAGGED -> {
|
||||
highestSelective = Math.max(highestSelective, rule.priority());
|
||||
for (String prefix : new LinkedHashSet<>(rule.tagPrefixes())) {
|
||||
if (!prefixes.add(prefix)) {
|
||||
throw validationFailure("The rules selecting a storage class must have a unique set "
|
||||
+ "of tag prefixes.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lowestAny < highestSelective) {
|
||||
throw validationFailure("A rule with tagStatus=ANY must have the highest rulePriority.");
|
||||
}
|
||||
if (untagged > 1) {
|
||||
throw validationFailure("Only one rule selecting a storage class can select untagged images.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A member that must be an object when given: one left out or null is refused, one of another type unmapped. */
|
||||
private static JsonNode object(JsonNode parent, String member, String missing) {
|
||||
JsonNode node = present(parent.get(member));
|
||||
if (node == null) {
|
||||
throw validationFailure(missing);
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/** A list of strings, empty when left out or null; anything but an array of strings cannot be mapped. */
|
||||
private static List<String> strings(JsonNode parent, String member) {
|
||||
JsonNode node = present(parent.get(member));
|
||||
if (node == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode value : node) {
|
||||
if (!value.isTextual()) {
|
||||
throw parsingFailure();
|
||||
}
|
||||
values.add(value.asText());
|
||||
}
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
private static <E extends Enum<E>> E enumValue(JsonNode node, Class<E> type) {
|
||||
if (node == null || !node.isTextual()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Enum.valueOf(type, node.asText().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The value of an integer node of 1 or more that fits an int; null for anything else. */
|
||||
private static Integer positiveInteger(JsonNode node) {
|
||||
if (node == null || !node.isIntegralNumber() || !node.canConvertToInt() || node.intValue() < 1) {
|
||||
return null;
|
||||
}
|
||||
return node.intValue();
|
||||
}
|
||||
|
||||
private static JsonNode present(JsonNode node) {
|
||||
return node == null || node.isNull() ? null : node;
|
||||
}
|
||||
|
||||
private static AwsException parsingFailure() {
|
||||
return invalid("Lifecycle policy parsing failure: Could not map policyString into LifecyclePolicy.");
|
||||
}
|
||||
|
||||
private static AwsException validationFailure(String reason) {
|
||||
return invalid("Lifecycle policy validation failure: " + reason);
|
||||
}
|
||||
|
||||
private static AwsException invalid(String constraint) {
|
||||
return new AwsException("InvalidParameterException",
|
||||
"Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: '" + constraint + "'", 400);
|
||||
}
|
||||
}
|
||||
@@ -1828,27 +1828,9 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
return repo;
|
||||
}
|
||||
|
||||
/** Refuses a lifecycle policy document ECR would refuse; see {@link EcrLifecyclePolicy#parse}. */
|
||||
public static void validateLifecyclePolicyDocument(String text) {
|
||||
JsonNode policy;
|
||||
try {
|
||||
policy = text == null ? null : SINGLE_JSON_VALUE.readTree(text);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InvalidParameterException", "Lifecycle policy must be a JSON object", 400);
|
||||
}
|
||||
JsonNode rules = policy == null || !policy.isObject() ? null : policy.get("rules");
|
||||
if (rules == null || !rules.isArray() || rules.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Lifecycle policy must contain a nonempty rules array", 400);
|
||||
}
|
||||
Set<Integer> priorities = new LinkedHashSet<>();
|
||||
for (JsonNode rule : rules) {
|
||||
JsonNode priority = rule.get("rulePriority");
|
||||
if (priority == null || !priority.isIntegralNumber() || !priority.canConvertToInt()
|
||||
|| priority.intValue() <= 0 || !priorities.add(priority.intValue())) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Lifecycle rule priorities must be unique positive integers", 400);
|
||||
}
|
||||
}
|
||||
EcrLifecyclePolicy.parse(text);
|
||||
}
|
||||
|
||||
public Repository getLifecyclePolicy(String repoName, String registryId, String region) {
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
package io.floci.aws.services.ecr;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.ActionType;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.CountType;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.Rule;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.StorageClass;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.TagStatus;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class EcrLifecyclePolicyTest {
|
||||
|
||||
private static final String PREFIX = "Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: '";
|
||||
private static final String PARSING_FAILURE =
|
||||
PREFIX + "Lifecycle policy parsing failure: Could not map policyString into LifecyclePolicy.'";
|
||||
private static final String EXPIRE = "{\"type\":\"expire\"}";
|
||||
private static final String TRANSITION = "{\"type\":\"transition\",\"targetStorageClass\":\"archive\"}";
|
||||
|
||||
/** The policies of the ECR user guide's lifecycle policy examples page, each of which ECR takes. */
|
||||
static Stream<String> userGuideExamples() {
|
||||
return Stream.of(
|
||||
policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"prod*\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":14}", EXPIRE)),
|
||||
policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePulled\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":90}", TRANSITION)),
|
||||
policy(rule(1, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\","
|
||||
+ "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\",\"countNumber\":365}",
|
||||
EXPIRE)),
|
||||
policy(rule(1, "{\"tagStatus\":\"untagged\",\"countType\":\"imageCountMoreThan\",\"countNumber\":1}",
|
||||
EXPIRE)),
|
||||
policy(rule(1, tagged("[\"prod*\"]", 1), EXPIRE), rule(2, tagged("[\"beta*\"]", 1), EXPIRE)),
|
||||
policy(rule(1, tagged("[\"beta*\"]", 1), EXPIRE), rule(2, tagged("[\"prod*\"]", 1), EXPIRE)),
|
||||
policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"alpha*\",\"beta*\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countNumber\":5,\"countUnit\":\"days\"}", EXPIRE)),
|
||||
policy(rule(1, tagged("[\"alpha*\",\"beta*\"]", 1), EXPIRE)),
|
||||
policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":1}",
|
||||
EXPIRE)),
|
||||
policy(rule(1, tagged("[\"alpha*\"]", 1), EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":1}", EXPIRE),
|
||||
rule(3, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":1}",
|
||||
EXPIRE)),
|
||||
policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"prod*\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":30}", TRANSITION)),
|
||||
policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":30}", TRANSITION),
|
||||
rule(2, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\","
|
||||
+ "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":365}", EXPIRE)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("userGuideExamples")
|
||||
void everyUserGuideExampleIsTaken(String policy) {
|
||||
EcrLifecyclePolicy.parse(policy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleIsReadWithItsDefaults() {
|
||||
EcrLifecyclePolicy policy = EcrLifecyclePolicy.parse(policy(
|
||||
rule(3, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"v\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":7}", EXPIRE),
|
||||
rule(9, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":2}", TRANSITION)));
|
||||
|
||||
assertEquals(List.of(
|
||||
new Rule(3, TagStatus.TAGGED, List.of(), List.of("prod", "v"), StorageClass.STANDARD,
|
||||
CountType.SINCE_IMAGE_PUSHED, 7, ActionType.EXPIRE),
|
||||
new Rule(9, TagStatus.ANY, List.of(), List.of(), StorageClass.STANDARD,
|
||||
CountType.IMAGE_COUNT_MORE_THAN, 2, ActionType.TRANSITION)), policy.rules());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enumValuesAreMatchedWithoutRegardToCase() {
|
||||
EcrLifecyclePolicy policy = EcrLifecyclePolicy.parse(policy(rule(1,
|
||||
"{\"tagStatus\":\"ANY\",\"storageClass\":\"Archive\",\"countType\":\"SINCEIMAGETRANSITIONED\","
|
||||
+ "\"countUnit\":\"DAYS\",\"countNumber\":365}", "{\"type\":\"EXPIRE\"}")));
|
||||
|
||||
assertEquals(new Rule(1, TagStatus.ANY, List.of(), List.of(), StorageClass.ARCHIVE,
|
||||
CountType.SINCE_IMAGE_TRANSITIONED, 365, ActionType.EXPIRE), policy.rules().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUntaggedRuleBeforeAnAnyRuleAndTwoAnyRulesAreTaken() {
|
||||
EcrLifecyclePolicy.parse(policy(
|
||||
rule(1, "{\"tagStatus\":\"untagged\",\"countType\":\"imageCountMoreThan\",\"countNumber\":2}", EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":2}", EXPIRE),
|
||||
rule(3, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":2}", EXPIRE)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Each storage class has its own rule set, so an archive rule selecting any image can come first, and a prefix
|
||||
* one storage class uses can be used again by the other.
|
||||
*/
|
||||
@Test
|
||||
void theRulesOfEachStorageClassAreCheckedApart() {
|
||||
EcrLifecyclePolicy.parse(policy(
|
||||
rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\"],\"storageClass\":\"archive\","
|
||||
+ "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\",\"countNumber\":90}",
|
||||
EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\",\"countType\":\"sinceImageTransitioned\","
|
||||
+ "\"countUnit\":\"days\",\"countNumber\":365}", EXPIRE),
|
||||
rule(3, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"prod\"],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE),
|
||||
rule(4, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"beta\"],\"storageClass\":\"standard\","
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE),
|
||||
rule(5, "{\"tagStatus\":\"untagged\",\"storageClass\":\"standard\","
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTagListsOnAnUntaggedRuleAreTakenAsLeftOut() {
|
||||
EcrLifecyclePolicy.parse(policy(rule(1, "{\"tagStatus\":\"untagged\",\"tagPrefixList\":[],"
|
||||
+ "\"tagPatternList\":null,\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)));
|
||||
}
|
||||
|
||||
/** The messages recorded from ECR for these documents. */
|
||||
static Stream<Arguments> recordedRejections() {
|
||||
return Stream.of(
|
||||
Arguments.of("{1:2}", PARSING_FAILURE),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":0}", EXPIRE)),
|
||||
PREFIX + "Lifecycle policy validation failure: numeric instance is lower than the required "
|
||||
+ "minimum (minimum: 1, found: 0)\n'"),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
PREFIX + "Lifecycle policy validation failure: Must specify tagPrefixList or tagPatternList "
|
||||
+ "when tagStatus=TAGGED.'"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("recordedRejections")
|
||||
void aRejectionCarriesEcrsMessage(String policy, String message) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy));
|
||||
|
||||
assertEquals("InvalidParameterException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNegativeCountNumberIsQuotedAsTheValidatorFoundIt() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy(rule(1,
|
||||
"{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":-3}", EXPIRE))));
|
||||
|
||||
assertEquals(PREFIX + "Lifecycle policy validation failure: numeric instance is lower than the required "
|
||||
+ "minimum (minimum: 1, found: -3)\n'", e.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "[]", "\"rules\"", "{\"rules\":[", "{\"rules\":[]} []", "{\"rules\":{}}",
|
||||
"{\"rules\":[1]}", "{\"rules\":[{\"rulePriority\":1,\"selection\":[],\"action\":{\"type\":\"expire\"}}]}",
|
||||
"{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"tagged\",\"tagPrefixList\":\"prod\","
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":{\"type\":\"expire\"}}]}",
|
||||
"{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"tagged\",\"tagPatternList\":[1],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":{\"type\":\"expire\"}}]}",
|
||||
"{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":1},\"action\":\"expire\"}]}"})
|
||||
void aDocumentThatIsNotALifecyclePolicyCannotBeMapped(String policy) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy));
|
||||
|
||||
assertEquals(PARSING_FAILURE, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingDocumentCannotBeMapped() {
|
||||
assertEquals(PARSING_FAILURE, assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(null))
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
static Stream<Arguments> invalidRules() {
|
||||
String anyCount = "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":1}";
|
||||
return Stream.of(
|
||||
Arguments.of("{}", "A lifecycle policy must have at least one rule."),
|
||||
Arguments.of("{\"rules\":null}", "A lifecycle policy must have at least one rule."),
|
||||
Arguments.of("{\"rules\":[]}", "A lifecycle policy must have at least one rule."),
|
||||
Arguments.of(policy(rule(1, anyCount, EXPIRE), rule(1, anyCount, EXPIRE)),
|
||||
"Each rule must have a unique rulePriority."),
|
||||
Arguments.of(policy("{\"selection\":" + anyCount + ",\"action\":" + EXPIRE + "}"),
|
||||
"rulePriority must be a positive integer."),
|
||||
Arguments.of(policy(rule("\"1\"", anyCount, EXPIRE)), "rulePriority must be a positive integer."),
|
||||
Arguments.of(policy(rule("1.0", anyCount, EXPIRE)), "rulePriority must be a positive integer."),
|
||||
Arguments.of(policy(rule("0", anyCount, EXPIRE)), "rulePriority must be a positive integer."),
|
||||
Arguments.of(policy(rule("2147483648", anyCount, EXPIRE)), "rulePriority must be a positive integer."),
|
||||
Arguments.of(policy("{\"rulePriority\":1,\"action\":" + EXPIRE + "}"),
|
||||
"Every rule must have a selection."),
|
||||
Arguments.of(policy("{\"rulePriority\":1,\"selection\":" + anyCount + "}"),
|
||||
"Every rule must have an action."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"some\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":1}", EXPIRE)), "tagStatus must be tagged, untagged or any."),
|
||||
Arguments.of(policy(rule(1, "{\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)),
|
||||
"tagStatus must be tagged, untagged or any."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"untagged\",\"tagPrefixList\":[\"prod\"],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)),
|
||||
"tagPrefixList and tagPatternList can only be used when tagStatus=TAGGED."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"tagPatternList\":[\"prod*\"],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)),
|
||||
"tagPrefixList and tagPatternList can only be used when tagStatus=TAGGED."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\"],"
|
||||
+ "\"tagPatternList\":[\"prod*\"],\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
"A rule can specify tagPrefixList or tagPatternList, but not both."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)),
|
||||
"Must specify tagPrefixList or tagPatternList when tagStatus=TAGGED."),
|
||||
Arguments.of(policy(rule(1, tagged("[\"*test*1*2*3\",\"test*1*2*3*4*5*6\"]", 1), EXPIRE)),
|
||||
"A tag pattern can have at most 4 wildcards."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountLessThan\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
"countType must be imageCountMoreThan, sinceImagePushed, sinceImagePulled or "
|
||||
+ "sinceImageTransitioned."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countUnit\":\"days\",\"countNumber\":1}", EXPIRE)),
|
||||
"countUnit can only be used when countType is sinceImagePushed, sinceImagePulled or "
|
||||
+ "sinceImageTransitioned."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
"countUnit must be days when countType is sinceImagePushed."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePulled\","
|
||||
+ "\"countUnit\":\"hours\",\"countNumber\":1}", EXPIRE)),
|
||||
"countUnit must be days when countType is sinceImagePulled."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\"}", EXPIRE)),
|
||||
"countNumber must be a positive integer."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":\"5\"}", EXPIRE)), "countNumber must be a positive integer."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"storageClass\":\"glacier\","
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)),
|
||||
"storageClass must be standard or archive."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImageTransitioned\","
|
||||
+ "\"countUnit\":\"days\",\"countNumber\":365}", EXPIRE)),
|
||||
"storageClass must be archive when countType is sinceImageTransitioned."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\","
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":1}",
|
||||
EXPIRE)),
|
||||
"storageClass must be standard when countType is sinceImagePushed."),
|
||||
Arguments.of(policy(rule(1, anyCount, "{\"type\":\"delete\"}")),
|
||||
"The action type must be expire or transition."),
|
||||
Arguments.of(policy(rule(1, anyCount, "{\"type\":\"transition\"}")),
|
||||
"targetStorageClass must be archive when the action type is transition."),
|
||||
Arguments.of(policy(rule(1, anyCount, "{\"type\":\"transition\",\"targetStorageClass\":\"standard\"}")),
|
||||
"targetStorageClass must be archive when the action type is transition."),
|
||||
Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\","
|
||||
+ "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":365}", TRANSITION)),
|
||||
"countType sinceImageTransitioned can only be used with the expire action."),
|
||||
Arguments.of(policy(rule(1, anyCount, EXPIRE), rule(2, tagged("[\"prod*\"]", 1), EXPIRE)),
|
||||
"A rule with tagStatus=ANY must have the highest rulePriority."),
|
||||
Arguments.of(policy(
|
||||
rule(1, "{\"tagStatus\":\"untagged\",\"countType\":\"imageCountMoreThan\","
|
||||
+ "\"countNumber\":1}", EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\","
|
||||
+ "\"countUnit\":\"days\",\"countNumber\":1}", EXPIRE)),
|
||||
"Only one rule selecting a storage class can select untagged images."),
|
||||
Arguments.of(policy(
|
||||
rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"v1\"],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"v1\",\"prod\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
"The rules selecting a storage class must have a unique set of tag prefixes."),
|
||||
Arguments.of(policy(
|
||||
rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"beta\"],"
|
||||
+ "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE),
|
||||
rule(2, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"qa\"],"
|
||||
+ "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\","
|
||||
+ "\"countNumber\":1}", EXPIRE)),
|
||||
"The rules selecting a storage class must have a unique set of tag prefixes."));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("invalidRules")
|
||||
void aDocumentBreakingAPolicyRuleIsRefused(String policy, String reason) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy));
|
||||
|
||||
assertEquals("InvalidParameterException", e.getErrorCode());
|
||||
assertEquals(PREFIX + "Lifecycle policy validation failure: " + reason + "'", e.getMessage());
|
||||
}
|
||||
|
||||
private static String policy(String... rules) {
|
||||
return "{\"rules\":[" + String.join(",", rules) + "]}";
|
||||
}
|
||||
|
||||
private static String rule(int priority, String selection, String action) {
|
||||
return rule(String.valueOf(priority), selection, action);
|
||||
}
|
||||
|
||||
private static String rule(String priority, String selection, String action) {
|
||||
return "{\"rulePriority\":" + priority + ",\"description\":\"rule\",\"selection\":" + selection
|
||||
+ ",\"action\":" + action + "}";
|
||||
}
|
||||
|
||||
private static String tagged(String patterns, int count) {
|
||||
return "{\"tagStatus\":\"tagged\",\"tagPatternList\":" + patterns
|
||||
+ ",\"countType\":\"imageCountMoreThan\",\"countNumber\":" + count + "}";
|
||||
}
|
||||
}
|
||||
+27
-1
@@ -98,7 +98,12 @@ class EcrLifecyclePolicyValidationIntegrationTest {
|
||||
new Object[]{region, policyWithPriority("\"rulePriority\":0,")},
|
||||
new Object[]{region, policyWithPriority("\"rulePriority\":-1,")},
|
||||
new Object[]{region, policyWithPriority("\"rulePriority\":null,")},
|
||||
new Object[]{region, policyWithPriority("\"rulePriority\":2147483648,")}));
|
||||
new Object[]{region, policyWithPriority("\"rulePriority\":2147483648,")},
|
||||
new Object[]{region, "{\"rules\":[" + RULE.replace("\"countNumber\":2", "\"countNumber\":0") + "]}"},
|
||||
new Object[]{region, "{\"rules\":[" + RULE.replace("\"any\"", "\"tagged\"") + "]}"},
|
||||
new Object[]{region, "{\"rules\":[" + RULE + ","
|
||||
+ RULE.replace("\"rulePriority\":1", "\"rulePriority\":2")
|
||||
.replace("\"tagStatus\":\"any\"", "\"tagStatus\":\"untagged\"") + "]}"}));
|
||||
}
|
||||
|
||||
private static String policyWithPriority(String property) {
|
||||
@@ -123,6 +128,27 @@ class EcrLifecyclePolicyValidationIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** ECR's validator ends its text with a newline, which the message keeps inside the closing quote. */
|
||||
@Test
|
||||
void aRefusedDocumentCarriesEcrsMessage() {
|
||||
String repository = "lifecycle-validation/" + UUID.randomUUID();
|
||||
try (EcrClient client = AwsTestClients.create(EcrClient.builder(), "test", Region.US_EAST_1)) {
|
||||
InvalidParameterException zeroCount = assertThrows(InvalidParameterException.class,
|
||||
() -> client.putLifecyclePolicy(r -> r.repositoryName(repository).lifecyclePolicyText(
|
||||
"{\"rules\":[" + RULE.replace("\"countNumber\":2", "\"countNumber\":0") + "]}")));
|
||||
InvalidParameterException malformed = assertThrows(InvalidParameterException.class,
|
||||
() -> client.putLifecyclePolicy(r -> r.repositoryName(repository)
|
||||
.lifecyclePolicyText("{1:2}" + " ".repeat(100))));
|
||||
|
||||
assertEquals("Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: 'Lifecycle policy "
|
||||
+ "validation failure: numeric instance is lower than the required minimum (minimum: 1, found: 0)"
|
||||
+ "\n'", zeroCount.awsErrorDetails().errorMessage());
|
||||
assertEquals("Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: 'Lifecycle policy "
|
||||
+ "parsing failure: Could not map policyString into LifecyclePolicy.'",
|
||||
malformed.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("invalidPolicies")
|
||||
void rejectedPolicyPreservesThePreviouslyAcceptedDocument(Region region, String invalidPolicy) {
|
||||
|
||||
Reference in new issue
Block a user