feat(ecr): repository creation templates (#5955)

* feat(ecr): repository creation templates

CreateRepositoryCreationTemplate, DescribeRepositoryCreationTemplates,
UpdateRepositoryCreationTemplate and DeleteRepositoryCreationTemplate store
templates per account and Region, keyed by prefix, with each field checked
against the service model. An update replaces the fields it sets, and an
empty string or list clears one. Templates are recorded, not applied, as
nothing in Floci creates repositories through replication, pull through
cache or create-on-push.

Closes #5804

* refactor(ecr): check repository creation templates against the vendored model

The four template actions join the registry settings in
ecr-request-shapes.json, so the handler checks their requests against the ECR
model's types, lengths, patterns and enums and answers in ECR's
"failed to satisfy constraint" form. The handwritten copies of those rules
go. What the model can't state stays in the service: appliedFor naming at
least one value, and policy text being a JSON object.

The model gives imageTagMutabilityExclusionFilters at least one entry, so an
update sending an empty list is now refused rather than clearing the filters.
Terraform omits the member when the filters are removed and moves to a mode
without exclusions, so an update that leaves the template in such a mode now
drops the filters. Before, they stayed, and every plan showed them again.

* fix(ecr): lock creation template writes, share one JSON object check and fold a trailing slash

Create, update and delete each read a template and then wrote it without a
lock, so two creates of one prefix could both succeed and an update racing a
delete wrote the deleted template back. They now take the registry lock the
registry settings use. The template policies and the registry policy share one
JSON object check that also refuses text after the object, such as {}{}.
ECR assumes a / after every prefix, so prod and prod/ are now one template.
The test helper imports Executable.

* fix(ecr): describe each template once when prefixes differ only by a slash

Describe removed duplicate prefixes before folding the trailing slash, so
prefixes prod and prod/ returned the template twice, and with maxResults 1 a
token followed by an empty page. It now removes duplicates by template key.
The lock tests use the shared testing ParkingStore instead of their own copy.
This commit is contained in:
David authored and GitHub committed 2026-10-26 19:36:42 -04:00
1 parent 6ff4700a22
commit d10db3ce9b
12 files changed
+1120 -18

No files matched your search

@@ -170,3 +170,25 @@ teardown() {
assert_failure
[[ "$output" == *"RegistryPolicyNotFoundException"* ]]
}
@test "ECR: repository creation templates round-trip" {
prefix="floci-cli-$(unique_name)"
run aws_cmd ecr create-repository-creation-template --prefix "$prefix" \
--applied-for PULL_THROUGH_CACHE --description "cli template"
assert_success
[ "$(json_get "$output" '.repositoryCreationTemplate.encryptionConfiguration.encryptionType')" = "AES256" ]
run aws_cmd ecr update-repository-creation-template --prefix "$prefix" --image-tag-mutability IMMUTABLE
assert_success
[ "$(json_get "$output" '.repositoryCreationTemplate.imageTagMutability')" = "IMMUTABLE" ]
run aws_cmd ecr describe-repository-creation-templates --prefixes "$prefix"
assert_success
[ "$(json_get "$output" '.repositoryCreationTemplates[0].description')" = "cli template" ]
run aws_cmd ecr delete-repository-creation-template --prefix "$prefix"
assert_success
run aws_cmd ecr delete-repository-creation-template --prefix "$prefix"
assert_failure
[[ "$output" == *"TemplateNotFoundException"* ]]
}
@@ -374,4 +374,50 @@ class EcrTest {
ecr.putRegistryScanningConfiguration(b -> b.scanType(ScanType.BASIC).rules(List.of()));
}
}
@Test
@Order(15)
@DisplayName("Repository creation templates create, update, describe and delete")
void repositoryCreationTemplateLifecycle() {
String prefix = "floci-sdk-" + System.currentTimeMillis();
try {
CreateRepositoryCreationTemplateResponse created = ecr.createRepositoryCreationTemplate(b -> b
.prefix(prefix)
.description("sdk template")
.appliedFor(RCTAppliedFor.PULL_THROUGH_CACHE, RCTAppliedFor.REPLICATION)
.resourceTags(Tag.builder().key("team").value("platform").build())
.imageTagMutability(ImageTagMutability.IMMUTABLE));
assertThat(created.registryId()).isEqualTo("000000000000");
assertThat(created.repositoryCreationTemplate().prefix()).isEqualTo(prefix);
assertThat(created.repositoryCreationTemplate().encryptionConfiguration().encryptionType())
.isEqualTo(EncryptionType.AES256);
assertThat(created.repositoryCreationTemplate().createdAt()).isNotNull();
assertThatThrownBy(() -> ecr.createRepositoryCreationTemplate(b -> b
.prefix(prefix).appliedFor(RCTAppliedFor.REPLICATION)))
.isInstanceOf(TemplateAlreadyExistsException.class);
UpdateRepositoryCreationTemplateResponse updated = ecr.updateRepositoryCreationTemplate(b -> b
.prefix(prefix)
.appliedFor(RCTAppliedFor.CREATE_ON_PUSH));
assertThat(updated.repositoryCreationTemplate().appliedFor()).containsExactly(RCTAppliedFor.CREATE_ON_PUSH);
assertThat(updated.repositoryCreationTemplate().description()).isEqualTo("sdk template");
DescribeRepositoryCreationTemplatesResponse described =
ecr.describeRepositoryCreationTemplates(b -> b.prefixes(prefix));
assertThat(described.repositoryCreationTemplates()).hasSize(1);
assertThat(described.repositoryCreationTemplates().get(0).resourceTags())
.containsExactly(Tag.builder().key("team").value("platform").build());
assertThat(ecr.deleteRepositoryCreationTemplate(b -> b.prefix(prefix))
.repositoryCreationTemplate().prefix()).isEqualTo(prefix);
assertThatThrownBy(() -> ecr.deleteRepositoryCreationTemplate(b -> b.prefix(prefix)))
.isInstanceOf(TemplateNotFoundException.class);
} finally {
try {
ecr.deleteRepositoryCreationTemplate(b -> b.prefix(prefix));
} catch (TemplateNotFoundException expected) {
// Already deleted by the lifecycle assertion.
}
}
}
}
+6
View File
@@ -14,6 +14,10 @@
| `UpdatePullThroughCacheRule` | Update a rule's credential or custom role |
| `ValidatePullThroughCacheRule` | Validate that a configured rule exists and report it as usable |
| `DeletePullThroughCacheRule` | Delete a pull-through cache rule by repository prefix |
| `CreateRepositoryCreationTemplate` | Store a repository creation template under its prefix (recorded, not applied) |
| `DescribeRepositoryCreationTemplates` | List templates, or those for given prefixes, with pagination |
| `UpdateRepositoryCreationTemplate` | Replace the fields a request sets on a template |
| `DeleteRepositoryCreationTemplate` | Delete a template by prefix |
| `DescribeRepositories` | List repositories or fetch by name |
| `DeleteRepository` | Delete a repository (with `force=true` semantics for non-empty repos) |
| `GetAuthorizationToken` | Returns a docker-login token + proxy endpoint |
@@ -70,6 +74,7 @@ the optional `filter` fields.
- `GetRegistryPolicy` and `DeleteRegistryPolicy` answer `RegistryPolicyNotFoundException` when no policy is set. `PutRegistryPolicy` refuses text that is not a JSON object.
- An empty `rules` list in `PutReplicationConfiguration` clears the configuration. `DescribeRegistry` returns `{"rules": []}` until rules are set.
- The scanning configuration is `BASIC` with no rules until one is put. `CONTINUOUS_SCAN` is refused with `BASIC`, since AWS offers it only with enhanced scanning. `BatchGetRepositoryScanningConfiguration` still reports each repository's own `scanOnPush`. Missing repository names appear in `failures` with `REPOSITORY_NOT_FOUND`, alongside configurations for the names that exist.
- **Repository creation templates.** Templates are kept per account and Region, keyed by `prefix` (`ROOT` included). A new template defaults to `AES256` encryption and `MUTABLE` tags. `UpdateRepositoryCreationTemplate` replaces each field the request sets, an empty string or list clears it, and fields left out are kept. The exclusion filters are the exception: the model requires at least one, so `[]` is refused. Instead, an update that leaves the template in a mode without exclusions (`MUTABLE` or `IMMUTABLE`) drops the filters, which is what Terraform relies on, since it leaves the member out when the filters are removed. `DescribeRepositoryCreationTemplates` leaves out a requested prefix with no template rather than failing. Requests are checked against the vendored ECR model constraints, as the registry settings are, with `InvalidParameterException`. On top of the model, `appliedFor` must name at least one value, and policy text must be a JSON object. Nothing in Floci creates repositories through replication, pull through cache or create-on-push, so templates are never applied.
- **Manifest format negotiation.** `BatchGetImage` forwards the caller's `acceptedMediaTypes` as the upstream `Accept` header. Modern OCI manifests (`application/vnd.oci.image.manifest.v1+json`) and Docker v2 schema 2 are both supported.
- **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `<account>/<region>/<repoName>`, so the same repository name in different accounts or regions cannot collide.
- **Reconcile on first start.** When the registry container starts, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage. This means image bytes are never orphaned across restarts.
@@ -270,6 +275,7 @@ The following ECR features are **not** implemented. Stored values for policies a
- Image scanning (`StartImageScan`, `DescribeImageScanFindings`)
- Image signing and notary attachments
- Lifecycle policy enforcement (the policy text is stored but not applied)
- Applying repository creation templates (they are stored, but Floci never creates repositories through replication, pull through cache or create-on-push)
- Repository policy enforcement (no IAM evaluation against repository-level policies)
- TLS via emulated ACM
+1 -1
View File
@@ -87,7 +87,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 202 |
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 30 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 34 |
| [AWS Resource Groups](resource-groups.md) | `/groups`, `/get-group`, `/delete-group`, `/group-resources`, `/list-group-resources` | REST JSON | 5 |
| [Resource Groups Tagging API](resource-groups-tagging.md) | `POST /` + `X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*` | JSON 1.1 | 5 |
| [Resource Explorer](resource-explorer.md) | `POST /{OperationName}`, rewritten to `/_re2/*` for the four paths S3 Vectors also claims | REST JSON | 32 |
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ecr.model.ImageIdentifier;
import io.github.hectorvent.floci.services.ecr.model.PullThroughCacheRule;
import io.github.hectorvent.floci.services.ecr.model.RegistrySettings;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ecr.model.RepositoryCreationTemplate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -49,7 +50,9 @@ public class EcrJsonHandler {
"PutRegistryPolicy", "GetRegistryPolicy", "DeleteRegistryPolicy",
"PutReplicationConfiguration", "DescribeRegistry",
"PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration",
"BatchGetRepositoryScanningConfiguration");
"BatchGetRepositoryScanningConfiguration",
"CreateRepositoryCreationTemplate", "UpdateRepositoryCreationTemplate",
"DescribeRepositoryCreationTemplates", "DeleteRepositoryCreationTemplate");
public Response handle(String action, JsonNode request, String region) {
if (MODEL_CHECKED.contains(action)) {
@@ -62,6 +65,10 @@ public class EcrJsonHandler {
case "UpdatePullThroughCacheRule" -> handleUpdatePullThroughCacheRule(request, region);
case "ValidatePullThroughCacheRule" -> handleValidatePullThroughCacheRule(request, region);
case "DeletePullThroughCacheRule" -> handleDeletePullThroughCacheRule(request, region);
case "CreateRepositoryCreationTemplate" -> handleCreateRepositoryCreationTemplate(request, region);
case "DescribeRepositoryCreationTemplates" -> handleDescribeRepositoryCreationTemplates(request, region);
case "UpdateRepositoryCreationTemplate" -> handleUpdateRepositoryCreationTemplate(request, region);
case "DeleteRepositoryCreationTemplate" -> handleDeleteRepositoryCreationTemplate(request, region);
case "DescribeRepositories" -> handleDescribeRepositories(request, region);
case "PutImageScanningConfiguration" -> handlePutImageScanningConfiguration(request, region);
case "BatchGetRepositoryScanningConfiguration" ->
@@ -850,6 +857,121 @@ public class EcrJsonHandler {
return n;
}
// ──────────────────────────── Repository creation templates ────────────────────────────
private Response handleCreateRepositoryCreationTemplate(JsonNode request, String region) {
return templateResponse(service.createRepositoryCreationTemplate(parseTemplate(request), region));
}
private Response handleUpdateRepositoryCreationTemplate(JsonNode request, String region) {
return templateResponse(service.updateRepositoryCreationTemplate(parseTemplate(request), region));
}
private Response handleDeleteRepositoryCreationTemplate(JsonNode request, String region) {
return templateResponse(service.deleteRepositoryCreationTemplate(
request.path("prefix").asText(null), region));
}
private Response handleDescribeRepositoryCreationTemplates(JsonNode request, String region) {
JsonNode prefixesNode = request.path("prefixes");
List<String> prefixes = prefixesNode.isMissingNode() || prefixesNode.isNull()
? null
: parseStringList(prefixesNode);
PaginatedResult<RepositoryCreationTemplate> result = service.describeRepositoryCreationTemplates(
prefixes, parseMaxResults(request.path("maxResults")), request.path("nextToken").asText(null), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", service.templateRegistryId());
ArrayNode templates = response.putArray("repositoryCreationTemplates");
result.items().forEach(t -> templates.add(buildTemplate(t)));
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
}
private Response templateResponse(RepositoryCreationTemplate template) {
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", service.templateRegistryId());
response.set("repositoryCreationTemplate", buildTemplate(template));
return Response.ok(response).build();
}
/** The template fields a request sets; each one it leaves out stays null. */
private static RepositoryCreationTemplate parseTemplate(JsonNode request) {
RepositoryCreationTemplate t = new RepositoryCreationTemplate();
t.setPrefix(request.path("prefix").asText(null));
t.setDescription(request.path("description").asText(null));
JsonNode encryption = request.path("encryptionConfiguration");
if (encryption.isObject()) {
t.setEncryptionConfiguration(new RepositoryCreationTemplate.EncryptionConfiguration(
encryption.path("encryptionType").asText(null), encryption.path("kmsKey").asText(null)));
}
if (request.path("resourceTags").isArray()) {
List<RepositoryCreationTemplate.ResourceTag> tags = new ArrayList<>();
request.path("resourceTags").forEach(tag -> tags.add(new RepositoryCreationTemplate.ResourceTag(
tag.path("Key").asText(null), tag.path("Value").asText(null))));
t.setResourceTags(tags);
}
t.setImageTagMutability(request.path("imageTagMutability").asText(null));
if (request.path("imageTagMutabilityExclusionFilters").isArray()) {
List<RepositoryCreationTemplate.ExclusionFilter> filters = new ArrayList<>();
request.path("imageTagMutabilityExclusionFilters").forEach(f -> filters.add(
new RepositoryCreationTemplate.ExclusionFilter(
f.path("filterType").asText(null), f.path("filter").asText(null))));
t.setImageTagMutabilityExclusionFilters(filters);
}
t.setRepositoryPolicy(request.path("repositoryPolicy").asText(null));
t.setLifecyclePolicy(request.path("lifecyclePolicy").asText(null));
if (request.path("appliedFor").isArray()) {
t.setAppliedFor(parseStringList(request.path("appliedFor")));
}
t.setCustomRoleArn(request.path("customRoleArn").asText(null));
return t;
}
private ObjectNode buildTemplate(RepositoryCreationTemplate t) {
ObjectNode n = objectMapper.createObjectNode();
n.put("prefix", t.getPrefix());
if (t.getDescription() != null) {
n.put("description", t.getDescription());
}
if (t.getEncryptionConfiguration() != null) {
ObjectNode enc = n.putObject("encryptionConfiguration");
enc.put("encryptionType", t.getEncryptionConfiguration().encryptionType());
if (t.getEncryptionConfiguration().kmsKey() != null) {
enc.put("kmsKey", t.getEncryptionConfiguration().kmsKey());
}
}
ArrayNode tags = n.putArray("resourceTags");
if (t.getResourceTags() != null) {
t.getResourceTags().forEach(tag -> tags.addObject().put("Key", tag.key()).put("Value", tag.value()));
}
if (t.getImageTagMutability() != null) {
n.put("imageTagMutability", t.getImageTagMutability());
}
if (t.getImageTagMutabilityExclusionFilters() != null && !t.getImageTagMutabilityExclusionFilters().isEmpty()) {
ArrayNode filters = n.putArray("imageTagMutabilityExclusionFilters");
t.getImageTagMutabilityExclusionFilters().forEach(f -> filters.addObject()
.put("filterType", f.filterType()).put("filter", f.filter()));
}
if (t.getRepositoryPolicy() != null) {
n.put("repositoryPolicy", t.getRepositoryPolicy());
}
if (t.getLifecyclePolicy() != null) {
n.put("lifecyclePolicy", t.getLifecyclePolicy());
}
ArrayNode appliedFor = n.putArray("appliedFor");
if (t.getAppliedFor() != null) {
t.getAppliedFor().forEach(appliedFor::add);
}
if (t.getCustomRoleArn() != null) {
n.put("customRoleArn", t.getCustomRoleArn());
}
n.put("createdAt", t.getCreatedAt().getEpochSecond());
n.put("updatedAt", t.getUpdatedAt().getEpochSecond());
return n;
}
private static List<String> parseStringList(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull() || !node.isArray()) {
return new ArrayList<>();
@@ -1,8 +1,11 @@
package io.github.hectorvent.floci.services.ecr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
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.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -27,6 +30,7 @@ import io.github.hectorvent.floci.services.ecr.model.ImageMetadata;
import io.github.hectorvent.floci.services.ecr.model.PullThroughCacheRule;
import io.github.hectorvent.floci.services.ecr.model.RegistrySettings;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ecr.model.RepositoryCreationTemplate;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;
import jakarta.enterprise.context.ApplicationScoped;
@@ -38,6 +42,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -76,6 +81,8 @@ public class EcrService implements ResourceProvider {
"ecr", "ecr-public", "quay", "k8s", "docker-hub",
"github-container-registry", "azure-container-registry",
"gitlab-container-registry", "chainguard");
private static final ObjectReader SINGLE_JSON_VALUE =
MAPPER.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private static final int MAX_REPO_NAME_LENGTH = 256;
private static final int MAX_PULL_THROUGH_CACHE_PREFIX_LENGTH = 30;
@@ -83,7 +90,8 @@ public class EcrService implements ResourceProvider {
private final StorageBackend<String, ImageMetadata> imageMetaStore;
private final StorageBackend<String, PullThroughCacheRule> pullThroughCacheRuleStore;
private final StorageBackend<String, RegistrySettings> registrySettingsStore;
private final Map<String, Object> registrySettingsLocks = new ConcurrentHashMap<>();
private final Map<String, Object> registryLocks = new ConcurrentHashMap<>();
private final StorageBackend<String, RepositoryCreationTemplate> templateStore;
private final EcrRegistryManager registryManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@@ -103,6 +111,8 @@ public class EcrService implements ResourceProvider {
new TypeReference<Map<String, PullThroughCacheRule>>() {}),
factory.create("ecr", "registry-settings.json",
new TypeReference<Map<String, RegistrySettings>>() {}),
factory.create("ecr", "repository-creation-templates.json",
new TypeReference<Map<String, RepositoryCreationTemplate>>() {}),
registryManager, config, regionResolver);
}
@@ -112,7 +122,7 @@ public class EcrService implements ResourceProvider {
EcrRegistryManager registryManager,
EmulatorConfig config,
RegionResolver regionResolver) {
this(repoStore, imageMetaStore, pullThroughCacheRuleStore, new InMemoryStorage<>(),
this(repoStore, imageMetaStore, pullThroughCacheRuleStore, new InMemoryStorage<>(), new InMemoryStorage<>(),
registryManager, config, regionResolver);
}
@@ -120,6 +130,7 @@ public class EcrService implements ResourceProvider {
StorageBackend<String, ImageMetadata> imageMetaStore,
StorageBackend<String, PullThroughCacheRule> pullThroughCacheRuleStore,
StorageBackend<String, RegistrySettings> registrySettingsStore,
StorageBackend<String, RepositoryCreationTemplate> templateStore,
EcrRegistryManager registryManager,
EmulatorConfig config,
RegionResolver regionResolver) {
@@ -127,6 +138,7 @@ public class EcrService implements ResourceProvider {
this.imageMetaStore = imageMetaStore;
this.pullThroughCacheRuleStore = pullThroughCacheRuleStore;
this.registrySettingsStore = registrySettingsStore;
this.templateStore = templateStore;
this.registryManager = registryManager;
this.config = config;
this.regionResolver = regionResolver;
@@ -324,6 +336,181 @@ public class EcrService implements ResourceProvider {
}
}
// ============================================================
// Repository creation templates
// ============================================================
/**
* Stores a template under its prefix. Fields left null take ECR's defaults: AES256 encryption
* and mutable tags.
*/
public RepositoryCreationTemplate createRepositoryCreationTemplate(RepositoryCreationTemplate requested,
String region) {
validateTemplateFields(requested);
String account = regionResolver.getAccountId();
String key = templateKey(region, account, requested.getPrefix());
synchronized (registryLock(region)) {
if (templateStore.get(key).isPresent()) {
throw new AwsException("TemplateAlreadyExistsException",
"The repository creation template with prefix '" + requested.getPrefix()
+ "' already exists in the registry with id '" + account + "'", 400);
}
RepositoryCreationTemplate template = new RepositoryCreationTemplate();
template.setPrefix(requested.getPrefix());
template.setEncryptionConfiguration(new RepositoryCreationTemplate.EncryptionConfiguration("AES256", null));
template.setImageTagMutability("MUTABLE");
applyTemplateFields(template, requested);
Instant now = Instant.now();
template.setCreatedAt(now);
template.setUpdatedAt(now);
templateStore.put(key, template);
return template;
}
}
/**
* Every template in the account and Region, or those named in {@code prefixes}; a prefix with
* no template is left out, as the model lists no not-found error for this action.
*/
public PaginatedResult<RepositoryCreationTemplate> describeRepositoryCreationTemplates(
List<String> prefixes, Integer maxResults, String nextToken, String region) {
String account = regionResolver.getAccountId();
List<RepositoryCreationTemplate> templates;
if (prefixes == null || prefixes.isEmpty()) {
String keyPrefix = region + "::" + account + "::";
templates = templateStore.scan(key -> key.startsWith(keyPrefix));
} else {
Set<String> keys = new LinkedHashSet<>();
for (String prefix : prefixes) {
keys.add(templateKey(region, account, prefix));
}
templates = new ArrayList<>();
for (String key : keys) {
templateStore.get(key).ifPresent(templates::add);
}
}
return Pagination.paginate(templates, RepositoryCreationTemplate::getPrefix,
maxResults, nextToken, 100, 1000, "InvalidParameterException");
}
/** Replaces each field the request sets; an empty string or list clears it. */
public RepositoryCreationTemplate updateRepositoryCreationTemplate(RepositoryCreationTemplate requested,
String region) {
validateTemplateFields(requested);
String key = templateKey(region, regionResolver.getAccountId(), requested.getPrefix());
synchronized (registryLock(region)) {
RepositoryCreationTemplate template = templateStore.get(key)
.orElseThrow(() -> templateNotFound(requested.getPrefix()));
applyTemplateFields(template, requested);
// Exclusion filters mean nothing outside a *_WITH_EXCLUSION mode. Terraform leaves the
// member out when the filters are removed, so they go when the mode no longer takes them.
if (!template.getImageTagMutability().endsWith("_WITH_EXCLUSION")) {
template.setImageTagMutabilityExclusionFilters(null);
}
template.setUpdatedAt(Instant.now());
templateStore.put(key, template);
return template;
}
}
public RepositoryCreationTemplate deleteRepositoryCreationTemplate(String prefix, String region) {
String key = templateKey(region, regionResolver.getAccountId(), prefix);
synchronized (registryLock(region)) {
RepositoryCreationTemplate template = templateStore.get(key).orElseThrow(() -> templateNotFound(prefix));
templateStore.delete(key);
return template;
}
}
/** The registry the templates belong to: the caller's account. */
public String templateRegistryId() {
return regionResolver.getAccountId();
}
/**
* The template rules the ECR model can't state; {@code EcrRequestShapes} has already checked
* the request against the model's types, lengths, patterns and enums.
*/
private static void validateTemplateFields(RepositoryCreationTemplate t) {
if (t.getAppliedFor() != null && t.getAppliedFor().isEmpty()) {
throw invalidTemplate("appliedFor must name at least one of REPLICATION, PULL_THROUGH_CACHE "
+ "or CREATE_ON_PUSH");
}
requireJsonObject(t.getRepositoryPolicy(), "repositoryPolicy");
requireJsonObject(t.getLifecyclePolicy(), "lifecyclePolicy");
}
private static void requireJsonObject(String text, String field) {
if (text == null || text.isEmpty()) {
return;
}
if (!isJsonObject(text)) {
throw invalidTemplate(field + " must be a JSON object");
}
}
/** Whether {@code text} is one JSON object with nothing after it, so {@code {} x} is not. */
private static boolean isJsonObject(String text) {
try {
return SINGLE_JSON_VALUE.readTree(text).isObject();
} catch (JsonProcessingException e) {
return false;
}
}
/** Copies the fields the request sets; an empty string or list clears the stored value. */
private static void applyTemplateFields(RepositoryCreationTemplate template, RepositoryCreationTemplate requested) {
if (requested.getDescription() != null) {
template.setDescription(emptyToNull(requested.getDescription()));
}
if (requested.getEncryptionConfiguration() != null) {
RepositoryCreationTemplate.EncryptionConfiguration e = requested.getEncryptionConfiguration();
template.setEncryptionConfiguration(new RepositoryCreationTemplate.EncryptionConfiguration(
e.encryptionType(), emptyToNull(e.kmsKey())));
}
if (requested.getResourceTags() != null) {
template.setResourceTags(List.copyOf(requested.getResourceTags()));
}
if (requested.getImageTagMutability() != null) {
template.setImageTagMutability(requested.getImageTagMutability());
}
if (requested.getImageTagMutabilityExclusionFilters() != null) {
template.setImageTagMutabilityExclusionFilters(List.copyOf(requested.getImageTagMutabilityExclusionFilters()));
}
if (requested.getRepositoryPolicy() != null) {
template.setRepositoryPolicy(emptyToNull(requested.getRepositoryPolicy()));
}
if (requested.getLifecyclePolicy() != null) {
template.setLifecyclePolicy(emptyToNull(requested.getLifecyclePolicy()));
}
if (requested.getAppliedFor() != null) {
template.setAppliedFor(List.copyOf(new LinkedHashSet<>(requested.getAppliedFor())));
}
if (requested.getCustomRoleArn() != null) {
template.setCustomRoleArn(emptyToNull(requested.getCustomRoleArn()));
}
}
private static String emptyToNull(String value) {
return value == null || value.isEmpty() ? null : value;
}
/** ECR assumes a {@code /} after every prefix, so {@code prod} and {@code prod/} are one template. */
private static String templateKey(String region, String account, String prefix) {
String namespace = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
return region + "::" + account + "::" + namespace;
}
private static AwsException invalidTemplate(String message) {
return new AwsException("InvalidParameterException", message, 400);
}
private AwsException templateNotFound(String prefix) {
return new AwsException("TemplateNotFoundException",
"The repository creation template with prefix '" + prefix
+ "' does not exist in the registry with id '" + regionResolver.getAccountId() + "'", 400);
}
// ============================================================
// CreateRepository
// ============================================================
@@ -1040,13 +1227,7 @@ public class EcrService implements ResourceProvider {
* text that is not a JSON object is refused here, as the model cannot say so.
*/
public String putRegistryPolicy(String policyText, String region) {
JsonNode parsed;
try {
parsed = policyText == null ? null : MAPPER.readTree(policyText);
} catch (Exception e) {
parsed = null;
}
if (parsed == null || !parsed.isObject()) {
if (policyText == null || !isJsonObject(policyText)) {
throw new AwsException("InvalidParameterException", "Invalid parameter at 'PolicyText' failed to satisfy "
+ "constraint: 'Invalid registry policy provided'", 400);
}
@@ -1145,7 +1326,7 @@ public class EcrService implements ResourceProvider {
*/
private <T> T updateRegistrySettings(String region, Function<RegistrySettings, T> change) {
String key = registrySettingsKey(region);
synchronized (registrySettingsLocks.computeIfAbsent(key, k -> new Object())) {
synchronized (registryLock(region)) {
RegistrySettings settings = registrySettings(region);
T result = change.apply(settings);
registrySettingsStore.put(key, settings);
@@ -1153,6 +1334,15 @@ public class EcrService implements ResourceProvider {
}
}
/**
* One lock per registry for every read and write back of its settings and creation templates:
* unlocked, two creates of one template prefix could both succeed, and an update could write
* back a template a delete had just removed.
*/
private Object registryLock(String region) {
return registryLocks.computeIfAbsent(registrySettingsKey(region), k -> new Object());
}
private String registrySettingsKey(String region) {
return region + "::" + regionResolver.getAccountId();
}
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
/**
* A repository creation template: the settings ECR gives a repository it creates for a
* replication, pull through cache or create-on-push rule whose name starts with the template's
* prefix. Floci records templates; nothing in Floci creates repositories that would use them.
*/
@RegisterForReflection
public class RepositoryCreationTemplate {
/** The encryption a created repository gets. */
@RegisterForReflection
public record EncryptionConfiguration(String encryptionType, String kmsKey) {}
/** One tag a created repository gets. */
@RegisterForReflection
public record ResourceTag(String key, String value) {}
/** One tag filter exempt from the template's tag mutability setting. */
@RegisterForReflection
public record ExclusionFilter(String filterType, String filter) {}
private String prefix;
private String description;
private EncryptionConfiguration encryptionConfiguration;
private List<ResourceTag> resourceTags;
private String imageTagMutability;
private List<ExclusionFilter> imageTagMutabilityExclusionFilters;
private String repositoryPolicy;
private String lifecyclePolicy;
private List<String> appliedFor;
private String customRoleArn;
private Instant createdAt;
private Instant updatedAt;
public RepositoryCreationTemplate() {}
public String getPrefix() { return prefix; }
public void setPrefix(String prefix) { this.prefix = prefix; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public EncryptionConfiguration getEncryptionConfiguration() { return encryptionConfiguration; }
public void setEncryptionConfiguration(EncryptionConfiguration encryptionConfiguration) {
this.encryptionConfiguration = encryptionConfiguration;
}
public List<ResourceTag> getResourceTags() { return resourceTags; }
public void setResourceTags(List<ResourceTag> resourceTags) { this.resourceTags = resourceTags; }
public String getImageTagMutability() { return imageTagMutability; }
public void setImageTagMutability(String imageTagMutability) { this.imageTagMutability = imageTagMutability; }
public List<ExclusionFilter> getImageTagMutabilityExclusionFilters() { return imageTagMutabilityExclusionFilters; }
public void setImageTagMutabilityExclusionFilters(List<ExclusionFilter> imageTagMutabilityExclusionFilters) {
this.imageTagMutabilityExclusionFilters = imageTagMutabilityExclusionFilters;
}
public String getRepositoryPolicy() { return repositoryPolicy; }
public void setRepositoryPolicy(String repositoryPolicy) { this.repositoryPolicy = repositoryPolicy; }
public String getLifecyclePolicy() { return lifecyclePolicy; }
public void setLifecyclePolicy(String lifecyclePolicy) { this.lifecyclePolicy = lifecyclePolicy; }
public List<String> getAppliedFor() { return appliedFor; }
public void setAppliedFor(List<String> appliedFor) { this.appliedFor = appliedFor; }
public String getCustomRoleArn() { return customRoleArn; }
public void setCustomRoleArn(String customRoleArn) { this.customRoleArn = customRoleArn; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
}
+190 -1
View File
@@ -11,7 +11,11 @@
"DescribeRegistry": "DescribeRegistryRequest",
"PutRegistryScanningConfiguration": "PutRegistryScanningConfigurationRequest",
"GetRegistryScanningConfiguration": "GetRegistryScanningConfigurationRequest",
"BatchGetRepositoryScanningConfiguration": "BatchGetRepositoryScanningConfigurationRequest"
"BatchGetRepositoryScanningConfiguration": "BatchGetRepositoryScanningConfigurationRequest",
"CreateRepositoryCreationTemplate": "CreateRepositoryCreationTemplateRequest",
"UpdateRepositoryCreationTemplate": "UpdateRepositoryCreationTemplateRequest",
"DescribeRepositoryCreationTemplates": "DescribeRepositoryCreationTemplatesRequest",
"DeleteRepositoryCreationTemplate": "DeleteRepositoryCreationTemplateRequest"
},
"shapes": {
"BatchGetRepositoryScanningConfigurationRequest": {
@@ -23,14 +27,72 @@
"repositoryNames": "ScanningConfigurationRepositoryNameList"
}
},
"CreateRepositoryCreationTemplateRequest": {
"type": "structure",
"required": [
"prefix",
"appliedFor"
],
"members": {
"prefix": "Prefix",
"description": "RepositoryTemplateDescription",
"encryptionConfiguration": "EncryptionConfigurationForRepositoryCreationTemplate",
"resourceTags": "TagList",
"imageTagMutability": "ImageTagMutability",
"imageTagMutabilityExclusionFilters": "ImageTagMutabilityExclusionFilters",
"repositoryPolicy": "RepositoryPolicyText",
"lifecyclePolicy": "LifecyclePolicyTextForRepositoryCreationTemplate",
"appliedFor": "RCTAppliedForList",
"customRoleArn": "CustomRoleArn"
}
},
"CustomRoleArn": {
"type": "string",
"max": 2048
},
"DeleteRegistryPolicyRequest": {
"type": "structure",
"members": {}
},
"DeleteRepositoryCreationTemplateRequest": {
"type": "structure",
"required": [
"prefix"
],
"members": {
"prefix": "Prefix"
}
},
"DescribeRegistryRequest": {
"type": "structure",
"members": {}
},
"DescribeRepositoryCreationTemplatesRequest": {
"type": "structure",
"members": {
"prefixes": "PrefixList",
"nextToken": "NextToken",
"maxResults": "MaxResults"
}
},
"EncryptionConfigurationForRepositoryCreationTemplate": {
"type": "structure",
"required": [
"encryptionType"
],
"members": {
"encryptionType": "EncryptionType",
"kmsKey": "KmsKeyForRepositoryCreationTemplate"
}
},
"EncryptionType": {
"type": "string",
"enum": [
"AES256",
"KMS",
"KMS_DSSE"
]
},
"GetRegistryPolicyRequest": {
"type": "structure",
"members": {}
@@ -39,6 +101,73 @@
"type": "structure",
"members": {}
},
"ImageTagMutability": {
"type": "string",
"enum": [
"MUTABLE",
"IMMUTABLE",
"IMMUTABLE_WITH_EXCLUSION",
"MUTABLE_WITH_EXCLUSION"
]
},
"ImageTagMutabilityExclusionFilter": {
"type": "structure",
"required": [
"filterType",
"filter"
],
"members": {
"filterType": "ImageTagMutabilityExclusionFilterType",
"filter": "ImageTagMutabilityExclusionFilterValue"
}
},
"ImageTagMutabilityExclusionFilterType": {
"type": "string",
"enum": [
"WILDCARD"
]
},
"ImageTagMutabilityExclusionFilterValue": {
"type": "string",
"min": 1,
"max": 128,
"pattern": "^[0-9a-zA-Z._*-]{1,128}$"
},
"ImageTagMutabilityExclusionFilters": {
"type": "list",
"min": 1,
"max": 5,
"member": "ImageTagMutabilityExclusionFilter"
},
"KmsKeyForRepositoryCreationTemplate": {
"type": "string",
"min": 0,
"max": 2048,
"pattern": "^$|arn:aws[a-z0-9-]*:kms:[a-z0-9-]+:[0-9]{12}:key\\/[a-z0-9-]+"
},
"LifecyclePolicyTextForRepositoryCreationTemplate": {
"type": "string",
"min": 0,
"max": 30720
},
"MaxResults": {
"type": "integer",
"min": 1,
"max": 1000
},
"NextToken": {
"type": "string"
},
"Prefix": {
"type": "string",
"min": 1,
"max": 256,
"pattern": "^([a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*(\\/[a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*)*\\/?|ROOT)$"
},
"PrefixList": {
"type": "list",
"member": "Prefix"
},
"PutRegistryPolicyRequest": {
"type": "structure",
"required": [
@@ -64,6 +193,18 @@
"replicationConfiguration": "ReplicationConfiguration"
}
},
"RCTAppliedFor": {
"type": "string",
"enum": [
"REPLICATION",
"PULL_THROUGH_CACHE",
"CREATE_ON_PUSH"
]
},
"RCTAppliedForList": {
"type": "list",
"member": "RCTAppliedFor"
},
"Region": {
"type": "string",
"min": 2,
@@ -173,6 +314,15 @@
"max": 256,
"pattern": "[a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*(\\/[a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*)*"
},
"RepositoryPolicyText": {
"type": "string",
"min": 0,
"max": 10240
},
"RepositoryTemplateDescription": {
"type": "string",
"max": 256
},
"ScanFrequency": {
"type": "string",
"enum": [
@@ -222,6 +372,45 @@
"min": 1,
"max": 255,
"pattern": "^[a-z0-9*](?:[._\\-/a-z0-9*]?[a-z0-9*]+)*$"
},
"Tag": {
"type": "structure",
"required": [
"Key",
"Value"
],
"members": {
"Key": "TagKey",
"Value": "TagValue"
}
},
"TagKey": {
"type": "string"
},
"TagList": {
"type": "list",
"member": "Tag"
},
"TagValue": {
"type": "string"
},
"UpdateRepositoryCreationTemplateRequest": {
"type": "structure",
"required": [
"prefix"
],
"members": {
"prefix": "Prefix",
"description": "RepositoryTemplateDescription",
"encryptionConfiguration": "EncryptionConfigurationForRepositoryCreationTemplate",
"resourceTags": "TagList",
"imageTagMutability": "ImageTagMutability",
"imageTagMutabilityExclusionFilters": "ImageTagMutabilityExclusionFilters",
"repositoryPolicy": "RepositoryPolicyText",
"lifecyclePolicy": "LifecyclePolicyTextForRepositoryCreationTemplate",
"appliedFor": "RCTAppliedForList",
"customRoleArn": "CustomRoleArn"
}
}
}
}
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Repository creation templates over the JSON protocol. Each test uses its own Region so they do
* not share state.
*/
@QuarkusTest
class EcrRepositoryCreationTemplatesIntegrationTest {
private static final String CT = "application/x-amz-json-1.1";
private static final String PREFIX = "AmazonEC2ContainerRegistry_V20150921.";
private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Pull\","
+ "\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":[\"ecr:BatchGetImage\"]}]}";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aTemplateIsCreatedDescribedUpdatedAndDeleted() {
String region = "eu-north-1";
call("CreateRepositoryCreationTemplate", "{\"prefix\":\"prod\",\"description\":\"production\","
+ "\"appliedFor\":[\"PULL_THROUGH_CACHE\",\"REPLICATION\"],"
+ "\"resourceTags\":[{\"Key\":\"team\",\"Value\":\"platform\"}],"
+ "\"imageTagMutability\":\"IMMUTABLE_WITH_EXCLUSION\","
+ "\"imageTagMutabilityExclusionFilters\":[{\"filterType\":\"WILDCARD\",\"filter\":\"latest*\"}],"
+ "\"repositoryPolicy\":" + quote(POLICY) + "}", region).statusCode(200)
.body("registryId", equalTo("000000000000"))
.body("repositoryCreationTemplate.prefix", equalTo("prod"))
.body("repositoryCreationTemplate.encryptionConfiguration.encryptionType", equalTo("AES256"))
.body("repositoryCreationTemplate.resourceTags[0].Key", equalTo("team"))
.body("repositoryCreationTemplate.imageTagMutabilityExclusionFilters[0].filter", equalTo("latest*"))
.body("repositoryCreationTemplate.repositoryPolicy", equalTo(POLICY))
.body("repositoryCreationTemplate.createdAt", notNullValue());
call("CreateRepositoryCreationTemplate", "{\"prefix\":\"prod\",\"appliedFor\":[\"REPLICATION\"]}", region)
.statusCode(400).body("__type", equalTo("TemplateAlreadyExistsException"));
call("DescribeRepositoryCreationTemplates", "{\"prefixes\":[\"prod\",\"absent\"]}", region).statusCode(200)
.body("registryId", equalTo("000000000000"))
.body("repositoryCreationTemplates", hasSize(1))
.body("repositoryCreationTemplates[0].description", equalTo("production"))
.body("repositoryCreationTemplates[0].appliedFor", contains("PULL_THROUGH_CACHE", "REPLICATION"));
call("UpdateRepositoryCreationTemplate", "{\"prefix\":\"prod\",\"description\":\"\","
+ "\"encryptionConfiguration\":{\"encryptionType\":\"KMS\"},\"appliedFor\":[\"CREATE_ON_PUSH\"]}",
region).statusCode(200)
.body("repositoryCreationTemplate.description", nullValue())
.body("repositoryCreationTemplate.encryptionConfiguration.encryptionType", equalTo("KMS"))
.body("repositoryCreationTemplate.appliedFor", contains("CREATE_ON_PUSH"))
.body("repositoryCreationTemplate.repositoryPolicy", equalTo(POLICY));
call("DeleteRepositoryCreationTemplate", "{\"prefix\":\"prod\"}", region).statusCode(200)
.body("repositoryCreationTemplate.prefix", equalTo("prod"));
call("DeleteRepositoryCreationTemplate", "{\"prefix\":\"prod\"}", region).statusCode(400)
.body("__type", equalTo("TemplateNotFoundException"));
call("UpdateRepositoryCreationTemplate", "{\"prefix\":\"prod\",\"description\":\"x\"}", region)
.statusCode(400).body("__type", equalTo("TemplateNotFoundException"));
}
@Test
void templatesPageInPrefixOrder() {
String region = "eu-south-1";
for (String prefix : new String[] {"ROOT", "apps/web", "apps"}) {
call("CreateRepositoryCreationTemplate", "{\"prefix\":\"" + prefix
+ "\",\"appliedFor\":[\"REPLICATION\"]}", region).statusCode(200);
}
String token = call("DescribeRepositoryCreationTemplates", "{\"maxResults\":2}", region).statusCode(200)
.body("repositoryCreationTemplates.prefix", contains("ROOT", "apps"))
.extract().path("nextToken");
call("DescribeRepositoryCreationTemplates", "{\"maxResults\":2,\"nextToken\":\"" + token + "\"}", region)
.statusCode(200)
.body("repositoryCreationTemplates.prefix", contains("apps/web"))
.body("nextToken", nullValue());
}
@Test
void badInputIsAnInvalidParameter() {
String region = "ap-south-2";
for (String body : new String[] {
"{\"prefix\":\"prod\"}",
"{\"prefix\":\"Prod\",\"appliedFor\":[\"REPLICATION\"]}",
"{\"prefix\":\"prod\",\"appliedFor\":[\"SOMETIMES\"]}",
"{\"prefix\":\"prod\",\"appliedFor\":[\"REPLICATION\"],\"imageTagMutability\":\"FROZEN\"}",
"{\"prefix\":\"prod\",\"appliedFor\":[\"REPLICATION\"],\"lifecyclePolicy\":\"not json\"}",
"{\"prefix\":\"prod\",\"appliedFor\":[\"REPLICATION\"],"
+ "\"encryptionConfiguration\":{\"encryptionType\":\"KMS\",\"kmsKey\":\"alias/x\"}}"}) {
call("CreateRepositoryCreationTemplate", body, region).statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
}
// The handler checks the request against the vendored model before the service sees it.
call("CreateRepositoryCreationTemplate", "{\"prefix\":\"prod\"}", region).statusCode(400)
.body("message", equalTo("Invalid parameter at 'appliedFor' failed to satisfy constraint: "
+ "'Member must not be null'"));
call("DescribeRepositoryCreationTemplates", "{\"maxResults\":0}", region).statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
call("DescribeRepositoryCreationTemplates", "{}", region).statusCode(200)
.body("repositoryCreationTemplates", hasSize(0));
}
private static String quote(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
private static ValidatableResponse call(String action, String body, String region) {
return given()
.header("X-Amz-Target", PREFIX + action)
.header("Authorization", "AWS4-HMAC-SHA256 Credential=000000000000/20261016/" + region
+ "/ecr/aws4_request, SignedHeaders=host, Signature=abc")
.contentType(CT)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -122,6 +122,86 @@ class EcrRequestShapesTest {
json("{\"scanType\":\"ENHANCED\",\"rules\":[" + scanRule + "," + scanRule + "]}")));
}
private static final String PREFIX_PATTERN =
"^([a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*(\\/[a-z0-9]+((\\.|_|__|-+)[a-z0-9]+)*)*\\/?|ROOT)$";
private static String template(String fields) {
return "{\"prefix\":\"prod\",\"appliedFor\":[\"REPLICATION\"]" + fields + "}";
}
private static String constraint(String member, String rule) {
return "Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'";
}
@Test
void creationTemplateFields() {
String create = "CreateRepositoryCreationTemplate";
assertEquals(constraint("prefix", "must satisfy regular expression '" + PREFIX_PATTERN + "'"),
refusal(create, "{\"prefix\":\"Prod\",\"appliedFor\":[\"REPLICATION\"]}"));
assertEquals(constraint("prefix", "Member must have length less than or equal to 256"),
refusal(create, "{\"prefix\":\"" + "a".repeat(257) + "\",\"appliedFor\":[\"REPLICATION\"]}"));
assertEquals(constraint("appliedFor", "Member must not be null"), refusal(create, "{\"prefix\":\"prod\"}"));
assertEquals(constraint("appliedFor", "Member must satisfy enum value set: "
+ "[REPLICATION, PULL_THROUGH_CACHE, CREATE_ON_PUSH]"),
refusal(create, "{\"prefix\":\"prod\",\"appliedFor\":[\"PULL\"]}"));
assertEquals(constraint("description", "Member must have length less than or equal to 256"),
refusal(create, template(",\"description\":\"" + "d".repeat(257) + "\"")));
assertEquals(constraint("encryptionConfiguration.encryptionType",
"Member must satisfy enum value set: [AES256, KMS, KMS_DSSE]"),
refusal(create, template(",\"encryptionConfiguration\":{\"encryptionType\":\"RSA\"}")));
assertEquals(constraint("encryptionConfiguration.kmsKey", "must satisfy regular expression "
+ "'^$|arn:aws[a-z0-9-]*:kms:[a-z0-9-]+:[0-9]{12}:key\\/[a-z0-9-]+'"),
refusal(create, template(",\"encryptionConfiguration\":{\"encryptionType\":\"KMS\","
+ "\"kmsKey\":\"alias/mine\"}")));
assertEquals(constraint("imageTagMutability", "Member must satisfy enum value set: "
+ "[MUTABLE, IMMUTABLE, IMMUTABLE_WITH_EXCLUSION, MUTABLE_WITH_EXCLUSION]"),
refusal(create, template(",\"imageTagMutability\":\"FROZEN\"")));
assertEquals(constraint("imageTagMutabilityExclusionFilters.filterType",
"Member must satisfy enum value set: [WILDCARD]"),
refusal(create, template(",\"imageTagMutabilityExclusionFilters\":[{\"filterType\":\"PREFIX_MATCH\","
+ "\"filter\":\"latest\"}]")));
assertEquals(constraint("imageTagMutabilityExclusionFilters.filter",
"must satisfy regular expression '^[0-9a-zA-Z._*-]{1,128}$'"),
refusal(create, template(",\"imageTagMutabilityExclusionFilters\":[{\"filterType\":\"WILDCARD\","
+ "\"filter\":\"no spaces\"}]")));
String filter = "{\"filterType\":\"WILDCARD\",\"filter\":\"v*\"}";
assertEquals(constraint("imageTagMutabilityExclusionFilters", "Member must have length less than or equal to 5"),
refusal(create, template(",\"imageTagMutabilityExclusionFilters\":["
+ String.join(",", Collections.nCopies(6, filter)) + "]")));
assertEquals(constraint("resourceTags.Value", "Member must not be null"),
refusal(create, template(",\"resourceTags\":[{\"Key\":\"team\"}]")));
assertEquals(constraint("repositoryPolicy", "Member must have length less than or equal to 10240"),
refusal(create, template(",\"repositoryPolicy\":\"" + "p".repeat(10241) + "\"")));
assertEquals(constraint("lifecyclePolicy", "Member must have length less than or equal to 30720"),
refusal(create, template(",\"lifecyclePolicy\":\"" + "l".repeat(30721) + "\"")));
assertEquals(constraint("customRoleArn", "Member must have length less than or equal to 2048"),
refusal(create, template(",\"customRoleArn\":\"" + "r".repeat(2049) + "\"")));
// The model gives the exclusion filters at least one entry, so an empty list does not clear them.
assertEquals(constraint("imageTagMutabilityExclusionFilters",
"Member must have length greater than or equal to 1"),
refusal("UpdateRepositoryCreationTemplate",
"{\"prefix\":\"prod\",\"imageTagMutabilityExclusionFilters\":[]}"));
assertEquals(constraint("prefix", "Member must not be null"),
refusal("UpdateRepositoryCreationTemplate", "{\"description\":\"x\"}"));
assertEquals(constraint("prefixes", "must satisfy regular expression '" + PREFIX_PATTERN + "'"),
refusal("DescribeRepositoryCreationTemplates", "{\"prefixes\":[\"Bad\"]}"));
assertEquals(constraint("maxResults", "Member must have value less than or equal to 1000"),
refusal("DescribeRepositoryCreationTemplates", "{\"maxResults\":1001}"));
assertEquals(constraint("prefix", "Member must not be null"), refusal("DeleteRepositoryCreationTemplate", "{}"));
// Emptying a string clears it, so the model allows it where an update can send one.
assertDoesNotThrow(() -> EcrRequestShapes.check("UpdateRepositoryCreationTemplate", json(
"{\"prefix\":\"ROOT\",\"description\":\"\",\"repositoryPolicy\":\"\",\"lifecyclePolicy\":\"\","
+ "\"customRoleArn\":\"\",\"encryptionConfiguration\":{\"encryptionType\":\"KMS\","
+ "\"kmsKey\":\"\"},\"resourceTags\":[],\"appliedFor\":[]}")));
assertDoesNotThrow(() -> EcrRequestShapes.check(create, json(template(
",\"encryptionConfiguration\":{\"encryptionType\":\"KMS_DSSE\",\"kmsKey\":"
+ "\"arn:aws-us-gov:kms:us-gov-west-1:000000000000:key/1234abcd-12ab\"},"
+ "\"imageTagMutabilityExclusionFilters\":[" + String.join(",", Collections.nCopies(5, filter))
+ "],\"resourceTags\":[{\"Key\":\"team\",\"Value\":\"platform\"}]"))));
}
@Test
void readsTakeAnEmptyBody() {
for (String operation : new String[] {"GetRegistryPolicy", "DeleteRegistryPolicy", "DescribeRegistry",
@@ -15,10 +15,13 @@ import io.github.hectorvent.floci.services.ecr.model.ImageMetadata;
import io.github.hectorvent.floci.services.ecr.model.PullThroughCacheRule;
import io.github.hectorvent.floci.services.ecr.model.RegistrySettings;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ecr.model.RepositoryCreationTemplate;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;
import io.github.hectorvent.floci.testing.ParkingStore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.Mockito;
import java.io.IOException;
@@ -31,9 +34,12 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
@@ -1375,6 +1381,7 @@ class EcrServiceTest {
assertInvalid(() -> service.putRegistryPolicy("not json", REGION));
assertInvalid(() -> service.putRegistryPolicy("[]", REGION));
assertInvalid(() -> service.putRegistryPolicy("", REGION));
assertInvalid(() -> service.putRegistryPolicy("{} x", REGION));
}
@Test
@@ -1417,9 +1424,10 @@ class EcrServiceTest {
void registrySettings_areKeptPerAccountAndRegion() {
InMemoryStorage<String, RegistrySettings> store = new InMemoryStorage<>();
EcrService first = new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
store, registryManager, Mockito.mock(EmulatorConfig.class), new RegionResolver(REGION, ACCOUNT));
store, new InMemoryStorage<>(), registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, ACCOUNT));
EcrService other = new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
store, registryManager, Mockito.mock(EmulatorConfig.class),
store, new InMemoryStorage<>(), registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, "111111111111"));
first.putRegistryPolicy(REGISTRY_POLICY, REGION);
@@ -1436,7 +1444,7 @@ class EcrServiceTest {
@Test
void registrySettings_parallelPutsAllSurvive() throws Exception {
EcrService parallel = new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), registryManager, Mockito.mock(EmulatorConfig.class),
new InMemoryStorage<>(), new InMemoryStorage<>(), registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, ACCOUNT));
List<RegistrySettings.ReplicationRule> rules = List.of(replicateTo("eu-west-1", ACCOUNT, null));
ExecutorService pool = Executors.newFixedThreadPool(3);
@@ -1465,4 +1473,230 @@ class EcrServiceTest {
pool.shutdownNow();
}
}
// ------------------------------------------------------------
// Repository creation templates
// ------------------------------------------------------------
private static RepositoryCreationTemplate template(String prefix, String... appliedFor) {
RepositoryCreationTemplate t = new RepositoryCreationTemplate();
t.setPrefix(prefix);
t.setAppliedFor(appliedFor.length == 0 ? null : List.of(appliedFor));
return t;
}
private static void assertInvalidTemplate(Executable call) {
assertEquals("InvalidParameterException", assertThrows(AwsException.class, call).getErrorCode());
}
@Test
void creationTemplate_createsWithDefaultsAndRefusesADuplicate() {
RepositoryCreationTemplate created = service.createRepositoryCreationTemplate(
template("prod", "PULL_THROUGH_CACHE", "REPLICATION"), REGION);
assertEquals("prod", created.getPrefix());
assertEquals("AES256", created.getEncryptionConfiguration().encryptionType());
assertEquals("MUTABLE", created.getImageTagMutability());
assertEquals(List.of("PULL_THROUGH_CACHE", "REPLICATION"), created.getAppliedFor());
assertNotNull(created.getCreatedAt());
assertEquals(created.getCreatedAt(), created.getUpdatedAt());
AwsException duplicate = assertThrows(AwsException.class,
() -> service.createRepositoryCreationTemplate(template("prod", "REPLICATION"), REGION));
assertEquals("TemplateAlreadyExistsException", duplicate.getErrorCode());
}
/** The rules the model can't state; the model's own are in {@code EcrRequestShapesTest}. */
@Test
void creationTemplate_checksWhatTheModelCannotState() {
RepositoryCreationTemplate noAppliedFor = template("prod");
noAppliedFor.setAppliedFor(List.of());
assertInvalidTemplate(() -> service.createRepositoryCreationTemplate(noAppliedFor, REGION));
RepositoryCreationTemplate badPolicy = template("prod", "REPLICATION");
badPolicy.setRepositoryPolicy("[]");
assertInvalidTemplate(() -> service.createRepositoryCreationTemplate(badPolicy, REGION));
RepositoryCreationTemplate badLifecycle = template("prod", "REPLICATION");
badLifecycle.setLifecyclePolicy("not json");
assertInvalidTemplate(() -> service.createRepositoryCreationTemplate(badLifecycle, REGION));
// A JSON object followed by more text is still not a JSON object.
RepositoryCreationTemplate trailingPolicy = template("prod", "REPLICATION");
trailingPolicy.setRepositoryPolicy("{}{}");
assertInvalidTemplate(() -> service.createRepositoryCreationTemplate(trailingPolicy, REGION));
RepositoryCreationTemplate trailingLifecycle = template("prod", "REPLICATION");
trailingLifecycle.setLifecyclePolicy("{\"rules\":[]} []");
assertInvalidTemplate(() -> service.createRepositoryCreationTemplate(trailingLifecycle, REGION));
RepositoryCreationTemplate full = template("ROOT", "CREATE_ON_PUSH");
full.setEncryptionConfiguration(new RepositoryCreationTemplate.EncryptionConfiguration("KMS_DSSE",
"arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab"));
full.setImageTagMutability("IMMUTABLE_WITH_EXCLUSION");
full.setImageTagMutabilityExclusionFilters(
List.of(new RepositoryCreationTemplate.ExclusionFilter("WILDCARD", "latest*")));
full.setRepositoryPolicy("{\"Version\":\"2012-10-17\",\"Statement\":[]}");
full.setLifecyclePolicy("{\"rules\":[]}");
assertEquals("KMS_DSSE", service.createRepositoryCreationTemplate(full, REGION)
.getEncryptionConfiguration().encryptionType());
}
@Test
void creationTemplate_updateReplacesWhatIsSentAndKeepsTheRest() {
RepositoryCreationTemplate created = template("team/app", "REPLICATION");
created.setDescription("first");
created.setRepositoryPolicy("{\"Version\":\"2012-10-17\"}");
service.createRepositoryCreationTemplate(created, REGION);
RepositoryCreationTemplate change = template("team/app");
change.setImageTagMutability("IMMUTABLE");
change.setRepositoryPolicy("");
RepositoryCreationTemplate updated = service.updateRepositoryCreationTemplate(change, REGION);
assertEquals("first", updated.getDescription());
assertEquals(List.of("REPLICATION"), updated.getAppliedFor());
assertEquals("IMMUTABLE", updated.getImageTagMutability());
assertNull(updated.getRepositoryPolicy());
RepositoryCreationTemplate badChange = template("team/app");
badChange.setAppliedFor(List.of());
assertInvalidTemplate(() -> service.updateRepositoryCreationTemplate(badChange, REGION));
assertEquals("TemplateNotFoundException", assertThrows(AwsException.class,
() -> service.updateRepositoryCreationTemplate(template("other"), REGION)).getErrorCode());
}
@Test
void creationTemplate_filtersGoWhenAnUpdateLeavesAnExclusionMode() {
RepositoryCreationTemplate created = template("team/app", "REPLICATION");
created.setImageTagMutability("IMMUTABLE_WITH_EXCLUSION");
created.setImageTagMutabilityExclusionFilters(
List.of(new RepositoryCreationTemplate.ExclusionFilter("WILDCARD", "latest*")));
service.createRepositoryCreationTemplate(created, REGION);
RepositoryCreationTemplate otherMode = template("team/app");
otherMode.setImageTagMutability("MUTABLE_WITH_EXCLUSION");
assertEquals(1, service.updateRepositoryCreationTemplate(otherMode, REGION)
.getImageTagMutabilityExclusionFilters().size(), "an exclusion mode keeps them");
RepositoryCreationTemplate plain = template("team/app");
plain.setImageTagMutability("MUTABLE");
assertNull(service.updateRepositoryCreationTemplate(plain, REGION).getImageTagMutabilityExclusionFilters());
}
@Test
void creationTemplate_describeFiltersAndPagesAndDeleteRemoves() {
for (String prefix : List.of("c", "a", "b")) {
service.createRepositoryCreationTemplate(template(prefix, "REPLICATION"), REGION);
}
PaginatedResult<RepositoryCreationTemplate> first =
service.describeRepositoryCreationTemplates(null, 2, null, REGION);
assertEquals(List.of("a", "b"), first.items().stream().map(RepositoryCreationTemplate::getPrefix).toList());
PaginatedResult<RepositoryCreationTemplate> second =
service.describeRepositoryCreationTemplates(null, 2, first.nextToken(), REGION);
assertEquals(List.of("c"), second.items().stream().map(RepositoryCreationTemplate::getPrefix).toList());
assertNull(second.nextToken());
// A prefix with no template is left out rather than refused.
assertEquals(List.of("b"), service.describeRepositoryCreationTemplates(List.of("b", "missing"), null, null, REGION)
.items().stream().map(RepositoryCreationTemplate::getPrefix).toList());
assertInvalidTemplate(() -> service.describeRepositoryCreationTemplates(null, 1001, null, REGION));
assertEquals("b", service.deleteRepositoryCreationTemplate("b", REGION).getPrefix());
assertEquals("TemplateNotFoundException", assertThrows(AwsException.class,
() -> service.deleteRepositoryCreationTemplate("b", REGION)).getErrorCode());
assertEquals(2, service.describeRepositoryCreationTemplates(null, null, null, REGION).items().size());
}
@Test
void creationTemplate_isKeptPerAccountAndRegion() {
InMemoryStorage<String, RepositoryCreationTemplate> shared = new InMemoryStorage<>();
EcrService home = new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), shared, registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, ACCOUNT));
EcrService other = new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), shared, registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, "111111111111"));
home.createRepositoryCreationTemplate(template("prod", "REPLICATION"), REGION);
assertTrue(other.describeRepositoryCreationTemplates(null, null, null, REGION).items().isEmpty());
assertTrue(home.describeRepositoryCreationTemplates(null, null, null, "eu-west-1").items().isEmpty());
other.createRepositoryCreationTemplate(template("prod", "REPLICATION"), REGION);
assertEquals("TemplateNotFoundException", assertThrows(AwsException.class,
() -> home.deleteRepositoryCreationTemplate("prod", "eu-west-1")).getErrorCode());
}
/** ECR assumes a {@code /} after every prefix, so a trailing one names the same template. */
@Test
void creationTemplate_aTrailingSlashNamesTheSameTemplate() {
service.createRepositoryCreationTemplate(template("prod/", "REPLICATION"), REGION);
assertEquals("TemplateAlreadyExistsException", assertThrows(AwsException.class,
() -> service.createRepositoryCreationTemplate(template("prod", "REPLICATION"), REGION)).getErrorCode());
assertEquals(1, service.describeRepositoryCreationTemplates(List.of("prod"), null, null, REGION)
.items().size());
PaginatedResult<RepositoryCreationTemplate> both =
service.describeRepositoryCreationTemplates(List.of("prod", "prod/"), 1, null, REGION);
assertEquals(1, both.items().size());
assertNull(both.nextToken());
RepositoryCreationTemplate change = template("prod");
change.setDescription("changed");
assertEquals("changed", service.updateRepositoryCreationTemplate(change, REGION).getDescription());
service.deleteRepositoryCreationTemplate("prod", REGION);
assertTrue(service.describeRepositoryCreationTemplates(null, null, null, REGION).items().isEmpty());
}
@Test
void creationTemplate_aSecondCreateOfThePrefixWaitsAndIsRefused() throws Exception {
ParkingStore<RepositoryCreationTemplate> store = new ParkingStore<>();
EcrService templates = templateService(store);
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
store.parkNextRead();
Future<?> first = pool.submit(() -> templates.createRepositoryCreationTemplate(
template("prod", "REPLICATION"), REGION));
assertTrue(store.awaitParked());
Future<?> second = pool.submit(() -> templates.createRepositoryCreationTemplate(
template("prod", "REPLICATION"), REGION));
assertThrows(TimeoutException.class, () -> second.get(200, TimeUnit.MILLISECONDS),
"the second create must wait for the first");
store.release();
first.get(5, TimeUnit.SECONDS);
ExecutionException refused = assertThrows(ExecutionException.class, () -> second.get(5, TimeUnit.SECONDS));
assertEquals("TemplateAlreadyExistsException", ((AwsException) refused.getCause()).getErrorCode());
} finally {
store.release();
pool.shutdownNow();
}
}
@Test
void creationTemplate_aDeleteDuringAnUpdateStaysDeleted() throws Exception {
ParkingStore<RepositoryCreationTemplate> store = new ParkingStore<>();
EcrService templates = templateService(store);
templates.createRepositoryCreationTemplate(template("prod", "REPLICATION"), REGION);
RepositoryCreationTemplate change = template("prod");
change.setDescription("changed");
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
store.parkNextRead();
Future<?> update = pool.submit(() -> templates.updateRepositoryCreationTemplate(change, REGION));
assertTrue(store.awaitParked());
Future<?> delete = pool.submit(() -> templates.deleteRepositoryCreationTemplate("prod", REGION));
assertThrows(TimeoutException.class, () -> delete.get(200, TimeUnit.MILLISECONDS),
"the delete must wait for the update");
store.release();
update.get(5, TimeUnit.SECONDS);
delete.get(5, TimeUnit.SECONDS);
} finally {
store.release();
pool.shutdownNow();
}
assertTrue(templates.describeRepositoryCreationTemplates(null, null, null, REGION).items().isEmpty());
}
private EcrService templateService(InMemoryStorage<String, RepositoryCreationTemplate> store) {
return new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), store, registryManager, Mockito.mock(EmulatorConfig.class),
new RegionResolver(REGION, ACCOUNT));
}
}
+4 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""Vendor ECR request constraints from botocore's Apache-2.0 service model.
`EcrRequestShapes` checks the registry setting actions against the vendored file through the
shared `RequestConstraintCheck`: member types, required members, lengths and counts, patterns and
`EcrRequestShapes` checks the registry setting and repository creation template actions against
the vendored file through the shared `RequestConstraintCheck`: member types, required members, lengths and counts, patterns and
enum values, as the model states them.
Run from anywhere in the repo:
@@ -26,6 +26,8 @@ OPERATIONS = (
"PutReplicationConfiguration", "DescribeRegistry",
"PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration",
"BatchGetRepositoryScanningConfiguration",
"CreateRepositoryCreationTemplate", "UpdateRepositoryCreationTemplate",
"DescribeRepositoryCreationTemplates", "DeleteRepositoryCreationTemplate",
)