diff --git a/docs/services/ecr.md b/docs/services/ecr.md index a9f2bf0be9..3d8e659baf 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -45,20 +45,24 @@ | `GetAccountSetting` / `PutAccountSetting` | Read and store account settings for the registry (stored, not acted on) | `PutLifecyclePolicy`, and an `AWS::ECR::Repository` in CloudFormation, check the document -against the rules in the ECR user guide: +as ECR does, 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. +- The text is 100 to 30720 characters, as the API model bounds it. +- One to 50 rules, each with a unique positive `rulePriority`, a `selection` and an `action`. +- `tagStatus` is `tagged`, `untagged` or `any`. A `tagged` rule needs exactly one of `tagPrefixList` (at most 10 prefixes) 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, at least 90 for `sinceImageTransitioned`. - `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. +- `action.type` is `expire` or `transition`. An `expire` action carries nothing else, a `transition` needs `targetStorageClass` `archive`, and `sinceImageTransitioned` allows only `expire`. +- Among the rules selecting one storage class, an `any` rule has the highest `rulePriority`, so there is one at most, 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. +Values are matched exactly as the guide spells them, and a selection member the guide does not +list is refused. A refused document returns `InvalidParameterException` in ECR's message form, +`Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: '...'`, with the prior +policy kept. As on ECR, malformed JSON, or a document that does not map onto ECR's rule types, +gives `Lifecycle policy parsing failure: ...`, a document breaking the JSON schema gives the schema +validator's own text after `Lifecycle policy validation failure: `, and a broken rule gives a sentence +naming it. Where ECR's wording is known, from refusals quoted publicly and replays recorded against +ECR, Floci uses it. 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` diff --git a/src/main/java/io/floci/aws/services/ecr/EcrLifecyclePolicy.java b/src/main/java/io/floci/aws/services/ecr/EcrLifecyclePolicy.java index b4ad9cae23..2294ea5fe4 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrLifecyclePolicy.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrLifecyclePolicy.java @@ -10,26 +10,47 @@ import io.floci.aws.core.common.AwsException; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.TreeSet; +import java.util.function.Function; /** - * 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. + * A lifecycle policy document as {@code PutLifecyclePolicy} takes it, checked in the stages ECR's refusals show: the + * JSON is parsed, checked against a JSON schema whose validator's own text ECR quotes, mapped onto ECR's rule types, + * and then checked against the rules the ECR user guide states. Values are matched exactly as the guide spells them. * * @see Lifecycle * policy properties + * @see Lifecycle policy + * evaluation rules */ public record EcrLifecyclePolicy(List rules) { /** Which images a rule's selection looks at by their tags. */ - public enum TagStatus { TAGGED, UNTAGGED, ANY } + public enum TagStatus { + TAGGED("tagged"), UNTAGGED("untagged"), ANY("any"); + + private final String wireName; + + TagStatus(String wireName) { + this.wireName = wireName; + } + } /** The storage class a rule selects images of. */ - public enum StorageClass { STANDARD, ARCHIVE } + public enum StorageClass { + STANDARD("standard"), ARCHIVE("archive"); + + private final String wireName; + + StorageClass(String wireName) { + this.wireName = wireName; + } + } /** What a rule counts against {@code countNumber}. */ public enum CountType { @@ -47,10 +68,6 @@ public record EcrLifecyclePolicy(List rules) { public String wireName() { return wireName; } - - boolean countsDays() { - return this != IMAGE_COUNT_MORE_THAN; - } } /** What a rule does to the images it selects. */ @@ -65,9 +82,18 @@ public record EcrLifecyclePolicy(List rules) { private static final ObjectReader SINGLE_JSON_VALUE = new ObjectMapper().reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final int MAX_RULES = 50; + private static final int MAX_TAG_PREFIXES = 10; private static final int MAX_PATTERN_WILDCARDS = 4; + /** "Images must be in archive storage for a minimum of 90 days before deletion." */ + private static final int MIN_ARCHIVE_DAYS = 90; + private static final Set SELECTION_MEMBERS = Set.of("tagStatus", "tagPatternList", "tagPrefixList", + "storageClass", "countType", "countUnit", "countNumber"); + /** The alternatives of the selection and action schemas, which ECR counts in its oneOf message. */ + private static final int SELECTION_SCHEMAS = CountType.values().length; + private static final int ACTION_SCHEMAS = ActionType.values().length; - /** Parses and checks {@code text}; a document ECR would refuse is refused with ECR's message form. */ + /** Parses and checks {@code text}; a document ECR would refuse is refused with ECR's message. */ public static EcrLifecyclePolicy parse(String text) { JsonNode policy; try { @@ -75,146 +101,251 @@ public record EcrLifecyclePolicy(List rules) { } catch (JsonProcessingException e) { throw parsingFailure(); } - if (policy == null || !policy.isObject()) { + if (policy == null || policy.isMissingNode()) { throw parsingFailure(); } - JsonNode rules = present(policy.get("rules")); - if (rules != null && !rules.isArray()) { - throw parsingFailure(); + checkSchema(policy); + List rules = new ArrayList<>(); + for (JsonNode rule : policy.get("rules")) { + rules.add(map(rule)); } - if (rules == null || rules.isEmpty()) { - throw validationFailure("A lifecycle policy must have at least one rule."); - } - List parsed = new ArrayList<>(); - Set 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)); + checkRules(rules); + return new EcrLifecyclePolicy(List.copyOf(rules)); } - private static Rule rule(JsonNode rule) { - if (!rule.isObject()) { + // ------------------------------------------------------------ + // The JSON schema: ECR quotes its validator, newline included + // ------------------------------------------------------------ + + private static void checkSchema(JsonNode policy) { + requireType(policy, "object"); + requireMembers(policy, "rules"); + JsonNode rules = policy.get("rules"); + requireType(rules, "array"); + if (rules.isEmpty()) { + throw schemaFailure("array is too short: must have at least 1 elements but instance has 0 elements"); + } + requireAtMost(rules, MAX_RULES); + for (JsonNode rule : rules) { + requireType(rule, "object"); + requireMembers(rule, "action", "rulePriority", "selection"); + requirePositiveInteger(rule.get("rulePriority")); + requireType(rule.get("selection"), "object"); + checkSelectionSchema(rule.get("selection")); + requireType(rule.get("action"), "object"); + checkActionSchema(rule.get("action")); + } + } + + private static void checkSelectionSchema(JsonNode selection) { + requireMembers(selection, "countNumber", "countType", "tagStatus"); + for (String list : List.of("tagPatternList", "tagPrefixList")) { + JsonNode values = selection.get(list); + if (values != null) { + requireType(values, "array"); + values.forEach(value -> requireType(value, "string")); + } + } + if (selection.has("tagPrefixList")) { + requireAtMost(selection.get("tagPrefixList"), MAX_TAG_PREFIXES); + } + requirePositiveInteger(selection.get("countNumber")); + if (!matchesACountSchema(selection)) { + throw schemaFailure(noSchemaMatched(SELECTION_SCHEMAS)); + } + } + + /** + * Each count type has a schema of its own: {@code imageCountMoreThan} takes no {@code countUnit}, the others take + * {@code days}, and none takes a member the guide does not list. + */ + private static boolean matchesACountSchema(JsonNode selection) { + for (Iterator members = selection.fieldNames(); members.hasNext(); ) { + if (!SELECTION_MEMBERS.contains(members.next())) { + return false; + } + } + CountType countType = wireValue(selection.get("countType"), CountType.values(), CountType::wireName); + if (countType == null) { + return false; + } + JsonNode countUnit = selection.get("countUnit"); + return countType == CountType.IMAGE_COUNT_MORE_THAN + ? countUnit == null + : countUnit != null && countUnit.isTextual() && countUnit.asText().equals("days"); + } + + /** An expire action carries only its type; a transition can also carry where it moves images to. */ + private static void checkActionSchema(JsonNode action) { + String type = action.path("type").isTextual() ? action.get("type").asText() : ""; + JsonNode target = action.get("targetStorageClass"); + boolean matched = switch (type) { + case "expire" -> action.size() == 1; + case "transition" -> action.size() == 1 || action.size() == 2 && target != null && target.isTextual() + && target.asText().equals(StorageClass.ARCHIVE.wireName); + default -> false; + }; + if (!matched) { + throw schemaFailure(noSchemaMatched(ACTION_SCHEMAS)); + } + } + + private static void requireMembers(JsonNode object, String... members) { + Set missing = new TreeSet<>(); + for (String member : members) { + if (!object.has(member)) { + missing.add(member); + } + } + if (!missing.isEmpty()) { + throw schemaFailure("object has missing required properties ([\"" + String.join("\",\"", missing) + + "\"])"); + } + } + + private static void requireType(JsonNode node, String type) { + if (!typeOf(node).equals(type)) { + throw schemaFailure("instance type (" + typeOf(node) + + ") does not match any allowed primitive type (allowed: [\"" + type + "\"])"); + } + } + + /** An integer of at least 1; one too large for ECR's rule types passes the schema and fails the mapping. */ + private static void requirePositiveInteger(JsonNode node) { + requireType(node, "integer"); + if (node.bigIntegerValue().signum() < 1) { + throw schemaFailure("numeric instance is lower than the required minimum (minimum: 1, found: " + + node.asText() + ")"); + } + } + + private static void requireAtMost(JsonNode array, int max) { + if (array.size() > max) { + throw schemaFailure("array is too long: must have at most " + max + " elements but instance has " + + array.size() + " elements"); + } + } + + private static String typeOf(JsonNode node) { + return switch (node.getNodeType()) { + case ARRAY -> "array"; + case BOOLEAN -> "boolean"; + case NULL -> "null"; + case NUMBER -> node.isIntegralNumber() ? "integer" : "number"; + case OBJECT -> "object"; + case STRING -> "string"; + default -> "unknown"; + }; + } + + private static String noSchemaMatched(int schemas) { + return "instance failed to match exactly one schema (matched 0 out of " + schemas + ")"; + } + + // ------------------------------------------------------------ + // Mapping onto ECR's rule types: what does not fit is unmapped + // ------------------------------------------------------------ + + private static Rule map(JsonNode rule) { + JsonNode selection = rule.get("selection"); + JsonNode action = rule.get("action"); + TagStatus tagStatus = wireValue(selection.get("tagStatus"), TagStatus.values(), status -> status.wireName); + StorageClass storageClass = selection.has("storageClass") + ? wireValue(selection.get("storageClass"), StorageClass.values(), storage -> storage.wireName) + : StorageClass.STANDARD; + boolean transition = action.get("type").asText().equals("transition"); + if (tagStatus == null || storageClass == null || !rule.get("rulePriority").canConvertToInt() + || !selection.get("countNumber").canConvertToInt() + || transition && !action.has("targetStorageClass")) { 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 patterns = strings(selection, "tagPatternList"); - List prefixes = strings(selection, "tagPrefixList"); - checkTagFilters(tagStatus, patterns, prefixes); + return new Rule(rule.get("rulePriority").intValue(), tagStatus, strings(selection.get("tagPatternList")), + strings(selection.get("tagPrefixList")), storageClass, + wireValue(selection.get("countType"), CountType.values(), CountType::wireName), + selection.get("countNumber").intValue(), transition ? ActionType.TRANSITION : ActionType.EXPIRE); + } - 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."); + private static List strings(JsonNode values) { + List strings = new ArrayList<>(); + if (values != null) { + values.forEach(value -> strings.add(value.asText())); } - 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."); + return List.copyOf(strings); + } + + private static E wireValue(JsonNode node, E[] values, Function wireName) { + if (node == null || !node.isTextual()) { + return null; + } + for (E value : values) { + if (wireName.apply(value).equals(node.asText())) { + return value; } - if (countType == CountType.SINCE_IMAGE_TRANSITIONED) { + } + return null; + } + + // ------------------------------------------------------------ + // The user guide's rules, in ECR's sentences where known + // ------------------------------------------------------------ + + private static void checkRules(List rules) { + Set priorities = new HashSet<>(); + for (Rule rule : rules) { + if (!priorities.add(rule.priority())) { + throw validationFailure("Duplicate priority in multiple rules"); + } + } + for (Rule rule : rules) { + checkTagFilters(rule); + checkStorageClass(rule); + if (rule.countType() == CountType.SINCE_IMAGE_TRANSITIONED && rule.action() == ActionType.TRANSITION) { throw validationFailure("countType sinceImageTransitioned can only be used with the expire action."); } } - return new Rule(priority, tagStatus, patterns, prefixes, storageClass, countType, countNumber, actionType); + checkRulesOfEachStorageClass(rules); } - private static void checkTagFilters(TagStatus tagStatus, List patterns, List prefixes) { - if (tagStatus != TagStatus.TAGGED) { - if (!patterns.isEmpty() || !prefixes.isEmpty()) { + private static void checkTagFilters(Rule rule) { + if (rule.tagStatus() != TagStatus.TAGGED) { + if (!rule.tagPatterns().isEmpty() || !rule.tagPrefixes().isEmpty()) { throw validationFailure("tagPrefixList and tagPatternList can only be used when tagStatus=TAGGED."); } return; } - if (!patterns.isEmpty() && !prefixes.isEmpty()) { + if (!rule.tagPatterns().isEmpty() && !rule.tagPrefixes().isEmpty()) { throw validationFailure("A rule can specify tagPrefixList or tagPatternList, but not both."); } - if (patterns.isEmpty() && prefixes.isEmpty()) { + if (rule.tagPatterns().isEmpty() && rule.tagPrefixes().isEmpty()) { throw validationFailure("Must specify tagPrefixList or tagPatternList when tagStatus=TAGGED."); } - for (String pattern : patterns) { + for (String pattern : rule.tagPatterns()) { if (pattern.chars().filter(c -> c == '*').count() > MAX_PATTERN_WILDCARDS) { - throw validationFailure("A tag pattern can have at most " + MAX_PATTERN_WILDCARDS + " wildcards."); + throw validationFailure("Invalid tag pattern provided. Total number of * must not exceed " + + MAX_PATTERN_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) { + /** Archived images are selected only by age in the archive, and only after their minimum stay there. */ + private static void checkStorageClass(Rule rule) { + boolean archive = rule.countType() == CountType.SINCE_IMAGE_TRANSITIONED; + if (archive && rule.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() + "."); + if (!archive && rule.storageClass() != StorageClass.STANDARD) { + throw validationFailure("storageClass must be standard when countType is " + + rule.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 (archive && rule.countNumber() < MIN_ARCHIVE_DAYS) { + throw validationFailure("countNumber must be at least " + MIN_ARCHIVE_DAYS + + " when countType is sinceImageTransitioned."); } - 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. + * Checks across the rules selecting one storage class: a rule selecting any image has the highest rulePriority of + * them all, so only one can, at most one rule selects untagged images, and no tag prefix appears in two rules. */ private static void checkRulesOfEachStorageClass(List rules) { Map> byStorageClass = new EnumMap<>(StorageClass.class); @@ -222,19 +353,16 @@ public record EcrLifecyclePolicy(List rules) { byStorageClass.computeIfAbsent(rule.storageClass(), ignored -> new ArrayList<>()).add(rule); } for (List group : byStorageClass.values()) { - int highestSelective = Integer.MIN_VALUE; + int highest = Integer.MIN_VALUE; int lowestAny = Integer.MAX_VALUE; int untagged = 0; Set prefixes = new HashSet<>(); for (Rule rule : group) { + highest = Math.max(highest, rule.priority()); switch (rule.tagStatus()) { case ANY -> lowestAny = Math.min(lowestAny, rule.priority()); - case UNTAGGED -> { - highestSelective = Math.max(highestSelective, rule.priority()); - untagged++; - } + case UNTAGGED -> 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 " @@ -244,73 +372,28 @@ public record EcrLifecyclePolicy(List rules) { } } } - if (lowestAny < highestSelective) { - throw validationFailure("A rule with tagStatus=ANY must have the highest rulePriority."); + if (lowestAny < highest) { + throw validationFailure("Rule for tagStatus=ANY must have the lowest priority per storage class."); } if (untagged > 1) { - throw validationFailure("Only one rule selecting a storage class can select untagged images."); + throw validationFailure("Only one rule can select Untagged images per storage class."); } } } - /** 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 strings(JsonNode parent, String member) { - JsonNode node = present(parent.get(member)); - if (node == null) { - return List.of(); - } - if (!node.isArray()) { - throw parsingFailure(); - } - List values = new ArrayList<>(); - for (JsonNode value : node) { - if (!value.isTextual()) { - throw parsingFailure(); - } - values.add(value.asText()); - } - return List.copyOf(values); - } - - private static > E enumValue(JsonNode node, Class 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; - } + // ------------------------------------------------------------ + // ECR's message forms + // ------------------------------------------------------------ private static AwsException parsingFailure() { return invalid("Lifecycle policy parsing failure: Could not map policyString into LifecyclePolicy."); } + /** The validator's own text, which ECR quotes with the newline the validator ends it with. */ + private static AwsException schemaFailure(String report) { + return validationFailure(report + "\n"); + } + private static AwsException validationFailure(String reason) { return invalid("Lifecycle policy validation failure: " + reason); } diff --git a/src/main/java/io/floci/aws/services/ecr/EcrService.java b/src/main/java/io/floci/aws/services/ecr/EcrService.java index 551a0be0f3..2820abc332 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrService.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrService.java @@ -90,6 +90,8 @@ public class EcrService implements ResourceProvider, Resettable { private static final int MAX_REPO_NAME_LENGTH = 256; private static final int MAX_PULL_TIME_EXCLUSIONS = 100; private static final int MAX_PULL_THROUGH_CACHE_PREFIX_LENGTH = 30; + private static final int MIN_LIFECYCLE_POLICY_LENGTH = 100; + private static final int MAX_LIFECYCLE_POLICY_LENGTH = 30720; private static final Map ACCOUNT_SETTING_DEFAULTS = Map.of( "BASIC_SCAN_TYPE_VERSION", "AWS_NATIVE", "REGISTRY_POLICY_SCOPE", "V2", "BLOB_MOUNTING", "DISABLED"); @@ -1828,8 +1830,21 @@ public class EcrService implements ResourceProvider, Resettable { return repo; } - /** Refuses a lifecycle policy document ECR would refuse; see {@link EcrLifecyclePolicy#parse}. */ + /** + * Refuses a lifecycle policy document ECR would refuse: one outside the model's 100 to 30720 characters, then one + * {@link EcrLifecyclePolicy#parse} refuses. + */ public static void validateLifecyclePolicyDocument(String text) { + String bound = null; + if (text != null && text.length() < MIN_LIFECYCLE_POLICY_LENGTH) { + bound = "greater than or equal to " + MIN_LIFECYCLE_POLICY_LENGTH; + } else if (text != null && text.length() > MAX_LIFECYCLE_POLICY_LENGTH) { + bound = "less than or equal to " + MAX_LIFECYCLE_POLICY_LENGTH; + } + if (bound != null) { + throw new AwsException("InvalidParameterException", "Invalid parameter at 'lifecyclePolicyText' failed to " + + "satisfy constraint: 'Member must have length " + bound + "'", 400); + } EcrLifecyclePolicy.parse(text); } diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyTest.java index 1c05108646..6fa626360e 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyTest.java @@ -12,6 +12,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import java.util.Collections; import java.util.List; import java.util.stream.Stream; @@ -23,8 +24,14 @@ 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 VALIDATION = PREFIX + "Lifecycle policy validation failure: "; private static final String EXPIRE = "{\"type\":\"expire\"}"; private static final String TRANSITION = "{\"type\":\"transition\",\"targetStorageClass\":\"archive\"}"; + private static final String ANY_COUNT = "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\"," + + "\"countNumber\":1}"; + private static final String NO_SELECTION_MATCHED = + "instance failed to match exactly one schema (matched 0 out of 4)"; + private static final String NO_ACTION_MATCHED = "instance failed to match exactly one schema (matched 0 out of 2)"; /** The policies of the ECR user guide's lifecycle policy examples page, each of which ECR takes. */ static Stream userGuideExamples() { @@ -43,13 +50,11 @@ class EcrLifecyclePolicyTest { 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, ANY_COUNT, 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)), + rule(3, ANY_COUNT, EXPIRE)), policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"prod*\"]," + "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":30}", TRANSITION)), policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\"," @@ -79,28 +84,9 @@ class EcrLifecyclePolicyTest { 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. + * Each storage class has its own rule set: an archive rule selecting any image can come before the standard + * rules, a prefix one storage class uses can be used by the other, and each can have one untagged rule. */ @Test void theRulesOfEachStorageClassAreCheckedApart() { @@ -108,39 +94,106 @@ class EcrLifecyclePolicyTest { 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\"," + rule(2, "{\"tagStatus\":\"untagged\",\"storageClass\":\"archive\"," + + "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\",\"countNumber\":90}", + EXPIRE), + rule(3, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\"," + + "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\",\"countNumber\":365}", + EXPIRE), + rule(4, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\"]," + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE), rule(5, "{\"tagStatus\":\"untagged\",\"storageClass\":\"standard\"," + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE))); } + /** A prefix repeated within one rule's own list counts once. */ @Test - void emptyTagListsOnAnUntaggedRuleAreTakenAsLeftOut() { - EcrLifecyclePolicy.parse(policy(rule(1, "{\"tagStatus\":\"untagged\",\"tagPrefixList\":[]," - + "\"tagPatternList\":null,\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE))); + void aPrefixRepeatedWithinOneRuleIsTaken() { + EcrLifecyclePolicy.parse(policy( + rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"prod\"]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE), + rule(2, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"beta\"]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE))); } - /** The messages recorded from ECR for these documents. */ - static Stream recordedRejections() { + @Test + void anEmptyTagListOnAnUntaggedRuleIsTakenAsLeftOut() { + EcrLifecyclePolicy.parse(policy(rule(1, "{\"tagStatus\":\"untagged\",\"tagPrefixList\":[]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE))); + } + + @Test + void fiftyRulesAndTenPrefixesAreTaken() { + String[] rules = new String[50]; + for (int i = 0; i < 49; i++) { + rules[i] = rule(i + 1, tagged("[\"v" + i + "*\"]", 1), EXPIRE); + } + rules[49] = rule(50, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[" + prefixes(10) + + "],\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE); + + EcrLifecyclePolicy.parse(policy(rules)); + } + + /** + * The messages ECR answered for these documents, from recordings, from measurements against ECR and from + * refusals users quoted. + */ + static Stream refusalsEcrAnswered() { + String[] fiftyOne = Collections.nCopies(51, rule(1, ANY_COUNT, EXPIRE)).toArray(String[]::new); 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'"), + VALIDATION + "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.'")); + VALIDATION + "Must specify tagPrefixList or tagPatternList when tagStatus=TAGGED.'"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"notARealCountType\"," + + "\"countNumber\":1}", EXPIRE)), + VALIDATION + NO_SELECTION_MATCHED + "\n'"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\"," + + "\"countUnit\":\"days\",\"countNumber\":10}", EXPIRE)), + VALIDATION + NO_SELECTION_MATCHED + "\n'"), + Arguments.of(policy(rule(1, ANY_COUNT, "{\"type\":\"expire\",\"targetStorageClass\":null}")), + VALIDATION + NO_ACTION_MATCHED + "\n'"), + Arguments.of(policy(rule(1, ANY_COUNT, "{\"type\":\"transition\"}")), PARSING_FAILURE), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":\"prod\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + VALIDATION + "instance type (string) does not match any allowed primitive type " + + "(allowed: [\"array\"])\n'"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"untagged\",\"tagPrefixList\":null," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + VALIDATION + "instance type (null) does not match any allowed primitive type " + + "(allowed: [\"array\"])\n'"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\"," + + "\"countNumber\":\"5\"}", EXPIRE)), + VALIDATION + "instance type (string) does not match any allowed primitive type " + + "(allowed: [\"integer\"])\n'"), + Arguments.of(policy(rule(1, ANY_COUNT, EXPIRE), rule(1, tagged("[\"prod*\"]", 1), EXPIRE)), + VALIDATION + "Duplicate priority in multiple rules'"), + Arguments.of(policy(rule(1, ANY_COUNT, EXPIRE), rule(2, "{\"tagStatus\":\"untagged\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + VALIDATION + "Rule for tagStatus=ANY must have the lowest priority per storage class.'"), + Arguments.of(policy( + rule(1, "{\"tagStatus\":\"untagged\",\"countType\":\"imageCountMoreThan\"," + + "\"countNumber\":1}", EXPIRE), + rule(2, "{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\"," + + "\"countUnit\":\"days\",\"countNumber\":1}", EXPIRE)), + VALIDATION + "Only one rule can select Untagged images per storage class.'"), + Arguments.of(policy(rule(1, tagged("[\"a*b*b*b*b*\"]", 1), EXPIRE)), + VALIDATION + "Invalid tag pattern provided. Total number of * must not exceed 4'"), + Arguments.of(policy(fiftyOne), + VALIDATION + "array is too long: must have at most 50 elements but instance has 51 " + + "elements\n'"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[" + prefixes(16) + + "],\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + VALIDATION + "array is too long: must have at most 10 elements but instance has 16 " + + "elements\n'")); } @ParameterizedTest - @MethodSource("recordedRejections") - void aRejectionCarriesEcrsMessage(String policy, String message) { + @MethodSource("refusalsEcrAnswered") + void aRefusalCarriesEcrsMessage(String policy, String message) { AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy)); assertEquals("InvalidParameterException", e.getErrorCode()); @@ -148,58 +201,106 @@ class EcrLifecyclePolicyTest { 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()); + /** + * Refusals no ECR answer shows, worded as the same JSON schema validator words them: its type, required member, + * minimum and array length checks, and the alternatives a selection or an action must match one of. + */ + static Stream schemaRefusals() { + return Stream.of( + Arguments.of("[]", "instance type (array) does not match any allowed primitive type " + + "(allowed: [\"object\"])"), + Arguments.of("{}", "object has missing required properties ([\"rules\"])"), + Arguments.of("{\"rules\":{}}", "instance type (object) does not match any allowed primitive type " + + "(allowed: [\"array\"])"), + Arguments.of("{\"rules\":[]}", "array is too short: must have at least 1 elements but instance has 0 " + + "elements"), + Arguments.of("{\"rules\":[1]}", "instance type (integer) does not match any allowed primitive type " + + "(allowed: [\"object\"])"), + Arguments.of(policy("{\"rulePriority\":1}"), + "object has missing required properties ([\"action\",\"selection\"])"), + Arguments.of(policy(rule("0", ANY_COUNT, EXPIRE)), + "numeric instance is lower than the required minimum (minimum: 1, found: 0)"), + Arguments.of(policy(rule("1.0", ANY_COUNT, EXPIRE)), + "instance type (number) does not match any allowed primitive type (allowed: [\"integer\"])"), + Arguments.of(policy(rule("\"1\"", ANY_COUNT, EXPIRE)), + "instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])"), + Arguments.of(policy(rule("null", ANY_COUNT, EXPIRE)), + "instance type (null) does not match any allowed primitive type (allowed: [\"integer\"])"), + Arguments.of(policy(rule(1, "[]", EXPIRE)), + "instance type (array) does not match any allowed primitive type (allowed: [\"object\"])"), + Arguments.of(policy(rule(1, "{\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + "object has missing required properties ([\"tagStatus\"])"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[1]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), + "instance type (integer) does not match any allowed primitive type (allowed: [\"string\"])"), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"IMAGECOUNTMORETHAN\"," + + "\"countNumber\":1}", EXPIRE)), NO_SELECTION_MATCHED), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\"," + + "\"countNumber\":1}", EXPIRE)), NO_SELECTION_MATCHED), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\"," + + "\"countUnit\":\"Days\",\"countNumber\":1}", EXPIRE)), NO_SELECTION_MATCHED), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixlist\":[\"prod\"]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), NO_SELECTION_MATCHED), + Arguments.of(policy(rule(1, ANY_COUNT, "\"expire\"")), + "instance type (string) does not match any allowed primitive type (allowed: [\"object\"])"), + Arguments.of(policy(rule(1, ANY_COUNT, "{\"type\":\"EXPIRE\"}")), NO_ACTION_MATCHED), + Arguments.of(policy(rule(1, ANY_COUNT, "{\"type\":\"delete\"}")), NO_ACTION_MATCHED), + Arguments.of(policy(rule(1, ANY_COUNT, + "{\"type\":\"transition\",\"targetStorageClass\":\"standard\"}")), NO_ACTION_MATCHED)); } @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\"}}]}", + @MethodSource("schemaRefusals") + void aDocumentTheSchemaRefusesIsRefusedWithTheValidatorsText(String policy, String report) { + AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy)); + + assertEquals(VALIDATION + report + "\n'", e.getMessage()); + } + + /** What passes the schema but fits none of ECR's rule types: a value it does not name, or a number too large. */ + @ParameterizedTest + @ValueSource(strings = {"", " ", "{\"rules\":[", "{\"rules\":[]} []", + "{\"rules\":[{\"rulePriority\":2147483648,\"selection\":" + ANY_COUNT + ",\"action\":" + EXPIRE + "}]}", "{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\"," - + "\"countNumber\":1},\"action\":\"expire\"}]}"}) - void aDocumentThatIsNotALifecyclePolicyCannotBeMapped(String policy) { + + "\"countNumber\":2147483648},\"action\":" + EXPIRE + "}]}", + "{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"TAGGED\",\"tagPrefixList\":[\"prod\"]," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":" + EXPIRE + "}]}", + "{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"some\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":" + EXPIRE + "}]}", + "{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"any\",\"storageClass\":\"glacier\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":" + EXPIRE + "}]}"}) + void aDocumentEcrCannotMapIsRefused(String policy) { AwsException e = assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(policy)); assertEquals(PARSING_FAILURE, e.getMessage()); } + /** The model bounds the text to 100 to 30720 characters, checked before the document, with the member's name. */ + @Test + void aDocumentOutsideTheModelsLengthIsRefusedBeforeItIsRead() { + AwsException tooShort = assertThrows(AwsException.class, + () -> EcrService.validateLifecyclePolicyDocument("{\"rules\":[]}")); + String padded = policy(rule(1, ANY_COUNT, EXPIRE)) + " ".repeat(30720); + AwsException tooLong = assertThrows(AwsException.class, + () -> EcrService.validateLifecyclePolicyDocument(padded)); + + assertEquals("Invalid parameter at 'lifecyclePolicyText' failed to satisfy constraint: 'Member must have " + + "length greater than or equal to 100'", tooShort.getMessage()); + assertEquals("Invalid parameter at 'lifecyclePolicyText' failed to satisfy constraint: 'Member must have " + + "length less than or equal to 30720'", tooLong.getMessage()); + EcrService.validateLifecyclePolicyDocument(policy(rule(1, ANY_COUNT, EXPIRE))); + } + @Test void aMissingDocumentCannotBeMapped() { assertEquals(PARSING_FAILURE, assertThrows(AwsException.class, () -> EcrLifecyclePolicy.parse(null)) .getMessage()); } - static Stream invalidRules() { - String anyCount = "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":1}"; + /** The rules of the user guide that no ECR answer shows the wording of, in Floci's own sentences. */ + static Stream ruleRefusals() { + String archive = "\"storageClass\":\"archive\",\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\""; 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."), @@ -213,29 +314,6 @@ class EcrLifecyclePolicyTest { 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."), @@ -243,24 +321,15 @@ class EcrLifecyclePolicyTest { + "\"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)), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\"," + archive + ",\"countNumber\":89}", EXPIRE)), + "countNumber must be at least 90 when countType is sinceImageTransitioned."), + Arguments.of(policy(rule(1, "{\"tagStatus\":\"any\"," + archive + ",\"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, ANY_COUNT, EXPIRE), rule(2, "{\"tagStatus\":\"any\"," + + "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":1}", + EXPIRE)), + "Rule for tagStatus=ANY must have the lowest priority per storage class."), Arguments.of(policy( rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":[\"prod\",\"v1\"]," + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE), @@ -272,18 +341,17 @@ class EcrLifecyclePolicyTest { 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)), + + "\"countType\":\"imageCountMoreThan\",\"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) { + @MethodSource("ruleRefusals") + void aDocumentBreakingAUserGuideRuleIsRefused(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()); + assertEquals(VALIDATION + reason + "'", e.getMessage()); } private static String policy(String... rules) { @@ -303,4 +371,12 @@ class EcrLifecyclePolicyTest { return "{\"tagStatus\":\"tagged\",\"tagPatternList\":" + patterns + ",\"countType\":\"imageCountMoreThan\",\"countNumber\":" + count + "}"; } + + private static String prefixes(int count) { + StringBuilder prefixes = new StringBuilder(); + for (int i = 0; i < count; i++) { + prefixes.append(i == 0 ? "" : ",").append("\"").append(Integer.toHexString(i)).append("\""); + } + return prefixes.toString(); + } } diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java index b81e9ff5c8..961c332ab5 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java @@ -139,6 +139,9 @@ class EcrLifecyclePolicyValidationIntegrationTest { InvalidParameterException malformed = assertThrows(InvalidParameterException.class, () -> client.putLifecyclePolicy(r -> r.repositoryName(repository) .lifecyclePolicyText("{1:2}" + " ".repeat(100)))); + InvalidParameterException tooShort = assertThrows(InvalidParameterException.class, + () -> client.putLifecyclePolicy(r -> r.repositoryName(repository) + .lifecyclePolicyText("{\"rules\":[]}"))); 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)" @@ -146,6 +149,8 @@ class EcrLifecyclePolicyValidationIntegrationTest { assertEquals("Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: 'Lifecycle policy " + "parsing failure: Could not map policyString into LifecyclePolicy.'", malformed.awsErrorDetails().errorMessage()); + assertEquals("Invalid parameter at 'lifecyclePolicyText' failed to satisfy constraint: 'Member must have " + + "length greater than or equal to 100'", tooShort.awsErrorDetails().errorMessage()); } }