mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(ecr): registry policy, replication and scanning configuration (#5817)
* feat(ecr): registry policy, replication and scanning configuration PutRegistryPolicy, GetRegistryPolicy, DeleteRegistryPolicy, PutReplicationConfiguration, DescribeRegistry, PutRegistryScanningConfiguration and GetRegistryScanningConfiguration store the registry's own settings per account and Region and return them as written. Floci does not replicate or scan images or evaluate the policy, as with repository policies. - The policy must be a JSON object; a missing one is RegistryPolicyNotFoundException. - Replication destinations, filters and rule counts are checked against the service model, and an empty rules list clears the configuration. - Scanning defaults to BASIC with no rules, and CONTINUOUS_SCAN is refused with BASIC. Closes #5803 * fix(ecr): put the registry setting writes under one lock PutRegistryPolicy, DeleteRegistryPolicy, PutReplicationConfiguration and PutRegistryScanningConfiguration read the registry's one settings record, change a field and write it back. Terraform applies the three resources in parallel, so two writers could start from the same record and the later write dropped the other's setting. The read, change and write now happen under a lock per account and Region. * refactor(ecr): check registry setting requests against the vendored model The Resource Groups request walker moves to core.common as RequestConstraintCheck, so a service can check a JSON request against botocore's constraints: member types, required members, lengths and counts, number ranges, patterns and enums, each answered in the service's own words. Resource Groups keeps its BadRequestException messages. - tools/aws/request_shapes.py gains build_constraints, which regen_resource_groups_shapes.py now calls; its vendored file is unchanged. - tools/aws/regen_ecr_shapes.py vendors ecr-request-shapes.json for the seven registry setting actions, and aws-data-sync and aws-data-check run it. - EcrJsonHandler checks those requests first, answering InvalidParameterException in ECR's form. The hand-written checks the model states are gone; a policy that is not a JSON object and CONTINUOUS_SCAN with BASIC stay, as the model cannot say them.
This commit is contained in:
1 parent
c4a2c0a4f6
commit
1f96bf42f1
20 files changed
+1493
-116
No files matched your search
@@ -0,0 +1,140 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Checks a JSON request against the constraints a {@code tools/aws/regen_*_shapes.py} generator
|
||||
* vendors from botocore through {@code request_shapes.build_constraints}: each member's type, the
|
||||
* members a structure requires, a string's length, a list's or map's size, a number's range, a
|
||||
* pattern and an enum. A service supplies its own {@link Messages}, so each answers with its own
|
||||
* error code and wording.
|
||||
*
|
||||
* <p>Paths start with the operation name: {@code PutReplicationConfiguration.replicationConfiguration.rules[]},
|
||||
* with {@code []} for a list element and {@code .key} for a map key.
|
||||
*/
|
||||
public final class RequestConstraintCheck {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** How a service words each kind of violation. */
|
||||
public interface Messages {
|
||||
/** {@code value} at {@code path} is not of the shape's JSON {@code type}. */
|
||||
AwsException type(String path, String type);
|
||||
|
||||
/** {@code size} (a length, a count or a number's value) is outside {@code min}..{@code max}. */
|
||||
AwsException bounds(String path, String type, Long min, Long max, long size);
|
||||
|
||||
/** A string does not match the shape's {@code pattern}. */
|
||||
AwsException pattern(String path, String pattern);
|
||||
|
||||
/** A value is not one of the shape's {@code values}. */
|
||||
AwsException enumValue(String path, List<String> values);
|
||||
|
||||
/** The structure member at {@code path} is required but missing or null. */
|
||||
AwsException required(String path);
|
||||
}
|
||||
|
||||
private final JsonNode model;
|
||||
private final Map<String, Pattern> patterns = new HashMap<>();
|
||||
private final Messages messages;
|
||||
|
||||
private RequestConstraintCheck(JsonNode model, Messages messages) {
|
||||
this.model = model;
|
||||
this.messages = messages;
|
||||
for (Map.Entry<String, JsonNode> shape : model.path("shapes").properties()) {
|
||||
if (shape.getValue().has("pattern")) {
|
||||
patterns.put(shape.getKey(), Pattern.compile(shape.getValue().get("pattern").asText()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The vendored resource {@code name}; {@code description} names it in a failure. */
|
||||
public static RequestConstraintCheck load(String name, String description, Messages messages) {
|
||||
return VendoredResources.read(name, description,
|
||||
input -> new RequestConstraintCheck(MAPPER.readTree(input), messages));
|
||||
}
|
||||
|
||||
public static RequestConstraintCheck of(JsonNode model, Messages messages) {
|
||||
return new RequestConstraintCheck(model, messages);
|
||||
}
|
||||
|
||||
/** Checks {@code request}, the body of {@code operation}, against the operation's input shape. */
|
||||
public void check(String operation, JsonNode request) {
|
||||
checkValue(model.path("operations").path(operation).asText(), request, operation);
|
||||
}
|
||||
|
||||
private void checkValue(String name, JsonNode value, String path) {
|
||||
JsonNode shape = model.path("shapes").path(name);
|
||||
String type = shape.path("type").asText();
|
||||
boolean validType = value != null && switch (type) {
|
||||
case "structure", "map" -> value.isObject();
|
||||
case "list" -> value.isArray();
|
||||
case "string" -> value.isTextual();
|
||||
case "integer", "long" -> value.isIntegralNumber() && value.canConvertToLong();
|
||||
default -> false;
|
||||
};
|
||||
if (!validType) {
|
||||
throw messages.type(path, type);
|
||||
}
|
||||
long size = switch (type) {
|
||||
case "string" -> value.textValue().codePointCount(0, value.textValue().length());
|
||||
case "integer", "long" -> value.longValue();
|
||||
default -> value.size();
|
||||
};
|
||||
Long min = shape.has("min") ? shape.get("min").asLong() : null;
|
||||
Long max = shape.has("max") ? shape.get("max").asLong() : null;
|
||||
if (min != null && size < min || max != null && size > max) {
|
||||
throw messages.bounds(path, type, min, max, size);
|
||||
}
|
||||
if (patterns.containsKey(name) && !patterns.get(name).matcher(value.asText()).matches()) {
|
||||
throw messages.pattern(path, shape.get("pattern").asText());
|
||||
}
|
||||
if (shape.has("enum")) {
|
||||
boolean known = false;
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode choice : shape.get("enum")) {
|
||||
known |= choice.equals(value);
|
||||
values.add(choice.asText());
|
||||
}
|
||||
if (!known) {
|
||||
throw messages.enumValue(path, values);
|
||||
}
|
||||
}
|
||||
switch (type) {
|
||||
case "structure" -> {
|
||||
for (JsonNode required : shape.path("required")) {
|
||||
if (!value.hasNonNull(required.asText())) {
|
||||
throw messages.required(path + "." + required.asText());
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
JsonNode member = shape.path("members").get(field.getKey());
|
||||
if (member != null && !field.getValue().isNull()) {
|
||||
checkValue(member.asText(), field.getValue(), path + "." + field.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
case "list" -> {
|
||||
for (JsonNode item : value) {
|
||||
checkValue(shape.get("member").asText(), item, path + "[]");
|
||||
}
|
||||
}
|
||||
case "map" -> {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
checkValue(shape.get("key").asText(), TextNode.valueOf(field.getKey()), path + ".key");
|
||||
checkValue(shape.get("value").asText(), field.getValue(), path + "." + field.getKey());
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ecr.model.ImageDetail;
|
||||
import io.github.hectorvent.floci.services.ecr.model.ImageFailure;
|
||||
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 jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -25,6 +26,7 @@ import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* AWS JSON 1.1 dispatcher for the {@code AmazonEC2ContainerRegistry_V20150921}
|
||||
@@ -42,7 +44,16 @@ public class EcrJsonHandler {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** The actions whose requests are checked against the vendored model constraints first. */
|
||||
private static final Set<String> MODEL_CHECKED = Set.of(
|
||||
"PutRegistryPolicy", "GetRegistryPolicy", "DeleteRegistryPolicy",
|
||||
"PutReplicationConfiguration", "DescribeRegistry",
|
||||
"PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration");
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
if (MODEL_CHECKED.contains(action)) {
|
||||
EcrRequestShapes.check(action, request);
|
||||
}
|
||||
return switch (action) {
|
||||
case "CreateRepository" -> handleCreateRepository(request, region);
|
||||
case "CreatePullThroughCacheRule" -> handleCreatePullThroughCacheRule(request, region);
|
||||
@@ -76,6 +87,14 @@ public class EcrJsonHandler {
|
||||
case "SetRepositoryPolicy" -> handleSetRepositoryPolicy(request, region);
|
||||
case "GetRepositoryPolicy" -> handleGetRepositoryPolicy(request, region);
|
||||
case "DeleteRepositoryPolicy" -> handleDeleteRepositoryPolicy(request, region);
|
||||
case "PutRegistryPolicy" -> registryPolicyResponse(
|
||||
service.putRegistryPolicy(request.path("policyText").asText(null), region));
|
||||
case "GetRegistryPolicy" -> registryPolicyResponse(service.getRegistryPolicy(region));
|
||||
case "DeleteRegistryPolicy" -> registryPolicyResponse(service.deleteRegistryPolicy(region));
|
||||
case "PutReplicationConfiguration" -> handlePutReplicationConfiguration(request, region);
|
||||
case "DescribeRegistry" -> handleDescribeRegistry(region);
|
||||
case "PutRegistryScanningConfiguration" -> handlePutRegistryScanningConfiguration(request, region);
|
||||
case "GetRegistryScanningConfiguration" -> handleGetRegistryScanningConfiguration(region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported."))
|
||||
@@ -609,6 +628,106 @@ public class EcrJsonHandler {
|
||||
// Builders / parsers
|
||||
// ============================================================
|
||||
|
||||
private Response registryPolicyResponse(String policyText) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("registryId", service.registryId());
|
||||
response.put("policyText", policyText);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutReplicationConfiguration(JsonNode request, String region) {
|
||||
JsonNode config = request.path("replicationConfiguration");
|
||||
List<RegistrySettings.ReplicationRule> rules = new ArrayList<>();
|
||||
for (JsonNode rule : config.path("rules")) {
|
||||
List<RegistrySettings.ReplicationDestination> destinations = null;
|
||||
if (rule.path("destinations").isArray()) {
|
||||
destinations = new ArrayList<>();
|
||||
for (JsonNode d : rule.path("destinations")) {
|
||||
destinations.add(new RegistrySettings.ReplicationDestination(
|
||||
d.path("region").asText(null), d.path("registryId").asText(null)));
|
||||
}
|
||||
}
|
||||
rules.add(new RegistrySettings.ReplicationRule(destinations,
|
||||
rule.has("repositoryFilters") ? parseRepositoryFilters(rule.path("repositoryFilters")) : null));
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("replicationConfiguration",
|
||||
buildReplicationConfiguration(service.putReplicationConfiguration(rules, region)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeRegistry(String region) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("registryId", service.registryId());
|
||||
response.set("replicationConfiguration", buildReplicationConfiguration(service.replicationRules(region)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutRegistryScanningConfiguration(JsonNode request, String region) {
|
||||
List<RegistrySettings.ScanningRule> rules = new ArrayList<>();
|
||||
for (JsonNode rule : request.path("rules")) {
|
||||
rules.add(new RegistrySettings.ScanningRule(rule.path("scanFrequency").asText(null),
|
||||
rule.has("repositoryFilters") ? parseRepositoryFilters(rule.path("repositoryFilters")) : null));
|
||||
}
|
||||
RegistrySettings saved = service.putRegistryScanningConfiguration(
|
||||
request.path("scanType").asText(null), rules, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("registryScanningConfiguration", buildScanningConfiguration(saved));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetRegistryScanningConfiguration(String region) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("registryId", service.registryId());
|
||||
response.set("scanningConfiguration", buildScanningConfiguration(service.registryScanningConfiguration(region)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private static List<RegistrySettings.RepositoryFilter> parseRepositoryFilters(JsonNode node) {
|
||||
List<RegistrySettings.RepositoryFilter> filters = new ArrayList<>();
|
||||
for (JsonNode f : node) {
|
||||
filters.add(new RegistrySettings.RepositoryFilter(
|
||||
f.path("filter").asText(null), f.path("filterType").asText(null)));
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
private ObjectNode buildReplicationConfiguration(List<RegistrySettings.ReplicationRule> rules) {
|
||||
ObjectNode config = objectMapper.createObjectNode();
|
||||
ArrayNode out = config.putArray("rules");
|
||||
for (RegistrySettings.ReplicationRule rule : rules) {
|
||||
ObjectNode n = out.addObject();
|
||||
ArrayNode destinations = n.putArray("destinations");
|
||||
for (RegistrySettings.ReplicationDestination d : rule.destinations()) {
|
||||
destinations.addObject().put("region", d.region()).put("registryId", d.registryId());
|
||||
}
|
||||
if (rule.repositoryFilters() != null) {
|
||||
n.set("repositoryFilters", buildRepositoryFilters(rule.repositoryFilters()));
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private ObjectNode buildScanningConfiguration(RegistrySettings settings) {
|
||||
ObjectNode config = objectMapper.createObjectNode();
|
||||
config.put("scanType", settings.getScanType());
|
||||
ArrayNode out = config.putArray("rules");
|
||||
for (RegistrySettings.ScanningRule rule : settings.getScanningRules()) {
|
||||
ObjectNode n = out.addObject();
|
||||
n.put("scanFrequency", rule.scanFrequency());
|
||||
n.set("repositoryFilters", buildRepositoryFilters(rule.repositoryFilters()));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private ArrayNode buildRepositoryFilters(List<RegistrySettings.RepositoryFilter> filters) {
|
||||
ArrayNode out = objectMapper.createArrayNode();
|
||||
for (RegistrySettings.RepositoryFilter f : filters) {
|
||||
out.addObject().put("filter", f.filter()).put("filterType", f.filterType());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private ObjectNode buildImageIdentifier(ImageIdentifier id) {
|
||||
ObjectNode n = objectMapper.createObjectNode();
|
||||
if (id.getImageTag() != null) n.put("imageTag", id.getImageTag());
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package io.github.hectorvent.floci.services.ecr;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestConstraintCheck;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Checks an ECR request against the constraints vendored in {@code aws/ecr-request-shapes.json} by
|
||||
* {@code tools/aws/regen_ecr_shapes.py}. A violation is {@code InvalidParameterException} in ECR's
|
||||
* form, {@code Invalid parameter at '<member>' failed to satisfy constraint: '<rule>'}, with the
|
||||
* member's path from the request's top level.
|
||||
*/
|
||||
final class EcrRequestShapes {
|
||||
|
||||
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
|
||||
"aws/ecr-request-shapes.json", "ECR request shapes",
|
||||
new RequestConstraintCheck.Messages() {
|
||||
@Override
|
||||
public AwsException type(String path, String type) {
|
||||
return invalid(path, "Member must be a " + type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException bounds(String path, String type, Long min, Long max, long size) {
|
||||
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
|
||||
return min != null && size < min
|
||||
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
|
||||
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException pattern(String path, String pattern) {
|
||||
return invalid(path, "must satisfy regular expression '" + pattern + "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException enumValue(String path, List<String> values) {
|
||||
return invalid(path, "Member must satisfy enum value set: " + values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException required(String path) {
|
||||
return invalid(path, "Member must not be null");
|
||||
}
|
||||
});
|
||||
|
||||
private EcrRequestShapes() {
|
||||
}
|
||||
|
||||
static void check(String operation, JsonNode request) {
|
||||
CHECK.check(operation, request);
|
||||
}
|
||||
|
||||
/** The member's path below the operation, with list elements folded into their list. */
|
||||
private static AwsException invalid(String path, String rule) {
|
||||
int dot = path.indexOf('.');
|
||||
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
|
||||
return new AwsException("InvalidParameterException",
|
||||
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
|
||||
@@ -24,6 +25,7 @@ import io.github.hectorvent.floci.services.ecr.model.ImageFailure;
|
||||
import io.github.hectorvent.floci.services.ecr.model.ImageIdentifier;
|
||||
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.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;
|
||||
@@ -62,7 +64,6 @@ public class EcrService implements ResourceProvider {
|
||||
private static final Pattern REGISTRY_ID = Pattern.compile("[0-9]{12}");
|
||||
private static final Pattern LAYER_DIGEST = Pattern.compile("[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+");
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
/** The OCI distribution spec's tag grammar, which the registry's manifest URL takes. */
|
||||
/** ECR's imageTag rule, which the service model bounds at 300 characters. */
|
||||
private static final Pattern ECR_IMAGE_TAG = Pattern.compile("[a-zA-Z0-9_.-]+");
|
||||
/** The OCI distribution spec's tag grammar, which the backing registry's manifest URL takes. */
|
||||
@@ -80,6 +81,8 @@ public class EcrService implements ResourceProvider {
|
||||
private final StorageBackend<String, Repository> repoStore;
|
||||
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 EcrRegistryManager registryManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -97,6 +100,8 @@ public class EcrService implements ResourceProvider {
|
||||
new TypeReference<Map<String, ImageMetadata>>() {}),
|
||||
factory.create("ecr", "pull-through-cache-rules.json",
|
||||
new TypeReference<Map<String, PullThroughCacheRule>>() {}),
|
||||
factory.create("ecr", "registry-settings.json",
|
||||
new TypeReference<Map<String, RegistrySettings>>() {}),
|
||||
registryManager, config, regionResolver);
|
||||
}
|
||||
|
||||
@@ -106,9 +111,21 @@ public class EcrService implements ResourceProvider {
|
||||
EcrRegistryManager registryManager,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
this(repoStore, imageMetaStore, pullThroughCacheRuleStore, new InMemoryStorage<>(),
|
||||
registryManager, config, regionResolver);
|
||||
}
|
||||
|
||||
EcrService(StorageBackend<String, Repository> repoStore,
|
||||
StorageBackend<String, ImageMetadata> imageMetaStore,
|
||||
StorageBackend<String, PullThroughCacheRule> pullThroughCacheRuleStore,
|
||||
StorageBackend<String, RegistrySettings> registrySettingsStore,
|
||||
EcrRegistryManager registryManager,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
this.repoStore = repoStore;
|
||||
this.imageMetaStore = imageMetaStore;
|
||||
this.pullThroughCacheRuleStore = pullThroughCacheRuleStore;
|
||||
this.registrySettingsStore = registrySettingsStore;
|
||||
this.registryManager = registryManager;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
@@ -975,6 +992,137 @@ public class EcrService implements ResourceProvider {
|
||||
return new AwsException("ServerException", "The ECR backing registry failed: " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Registry settings (policy, replication, scanning)
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Stores the registry policy. Its length is checked against the model before this is reached;
|
||||
* 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()) {
|
||||
throw new AwsException("InvalidParameterException", "Invalid parameter at 'PolicyText' failed to satisfy "
|
||||
+ "constraint: 'Invalid registry policy provided'", 400);
|
||||
}
|
||||
updateRegistrySettings(region, settings -> {
|
||||
settings.setPolicyText(policyText);
|
||||
return null;
|
||||
});
|
||||
return policyText;
|
||||
}
|
||||
|
||||
public String getRegistryPolicy(String region) {
|
||||
String policy = registrySettings(region).getPolicyText();
|
||||
if (policy == null) {
|
||||
throw registryPolicyNotFound();
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
/** Removes the registry policy and returns what it was. */
|
||||
public String deleteRegistryPolicy(String region) {
|
||||
return updateRegistrySettings(region, settings -> {
|
||||
String policy = settings.getPolicyText();
|
||||
if (policy == null) {
|
||||
throw registryPolicyNotFound();
|
||||
}
|
||||
settings.setPolicyText(null);
|
||||
return policy;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the replication rules; an empty list clears them. The rules are checked against the
|
||||
* model before this is reached. Floci does not replicate images.
|
||||
*/
|
||||
public List<RegistrySettings.ReplicationRule> putReplicationConfiguration(
|
||||
List<RegistrySettings.ReplicationRule> rules, String region) {
|
||||
updateRegistrySettings(region, settings -> {
|
||||
settings.setReplicationRules(rules.isEmpty() ? null : List.copyOf(rules));
|
||||
return null;
|
||||
});
|
||||
return replicationRules(region);
|
||||
}
|
||||
|
||||
/** The stored replication rules, empty when none are set. */
|
||||
public List<RegistrySettings.ReplicationRule> replicationRules(String region) {
|
||||
List<RegistrySettings.ReplicationRule> rules = registrySettings(region).getReplicationRules();
|
||||
return rules == null ? List.of() : rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the scanning configuration. The model's constraints are checked before this is
|
||||
* reached; {@code CONTINUOUS_SCAN} is refused here with {@code BASIC}, as the API reference
|
||||
* offers it only with enhanced scanning and the model cannot say so. Floci does not scan images.
|
||||
*/
|
||||
public RegistrySettings putRegistryScanningConfiguration(String scanType, List<RegistrySettings.ScanningRule> rules,
|
||||
String region) {
|
||||
String type = scanType == null ? "BASIC" : scanType;
|
||||
List<RegistrySettings.ScanningRule> given = rules == null ? List.of() : rules;
|
||||
for (RegistrySettings.ScanningRule rule : given) {
|
||||
if ("BASIC".equals(type) && "CONTINUOUS_SCAN".equals(rule.scanFrequency())) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"CONTINUOUS_SCAN is supported only with the ENHANCED scan type", 400);
|
||||
}
|
||||
}
|
||||
updateRegistrySettings(region, settings -> {
|
||||
settings.setScanType(type);
|
||||
settings.setScanningRules(List.copyOf(given));
|
||||
return null;
|
||||
});
|
||||
return registryScanningConfiguration(region);
|
||||
}
|
||||
|
||||
/** The scanning configuration, {@code BASIC} with no rules until one is put. */
|
||||
public RegistrySettings registryScanningConfiguration(String region) {
|
||||
RegistrySettings stored = registrySettings(region);
|
||||
RegistrySettings view = new RegistrySettings();
|
||||
view.setScanType(stored.getScanType() == null ? "BASIC" : stored.getScanType());
|
||||
view.setScanningRules(stored.getScanningRules() == null ? List.of() : stored.getScanningRules());
|
||||
return view;
|
||||
}
|
||||
|
||||
/** The registry ID of the caller's account. */
|
||||
public String registryId() {
|
||||
return regionResolver.getAccountId();
|
||||
}
|
||||
|
||||
private RegistrySettings registrySettings(String region) {
|
||||
return registrySettingsStore.get(registrySettingsKey(region)).orElseGet(RegistrySettings::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the registry's settings, changes them and writes them back under the registry's lock.
|
||||
* The settings are one record, and Terraform puts the policy, replication and scanning
|
||||
* configuration in parallel: unlocked, two writers could start from the same record and the
|
||||
* later write would drop the other's field.
|
||||
*/
|
||||
private <T> T updateRegistrySettings(String region, Function<RegistrySettings, T> change) {
|
||||
String key = registrySettingsKey(region);
|
||||
synchronized (registrySettingsLocks.computeIfAbsent(key, k -> new Object())) {
|
||||
RegistrySettings settings = registrySettings(region);
|
||||
T result = change.apply(settings);
|
||||
registrySettingsStore.put(key, settings);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private String registrySettingsKey(String region) {
|
||||
return region + "::" + regionResolver.getAccountId();
|
||||
}
|
||||
|
||||
private AwsException registryPolicyNotFound() {
|
||||
return new AwsException("RegistryPolicyNotFoundException",
|
||||
"Registry policy does not exist in the registry with id '" + regionResolver.getAccountId() + "'", 400);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Tag mutability + resource tags + policies (metadata round-trip)
|
||||
// ============================================================
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.ecr.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A registry's own settings, one record per account and Region: the registry policy, the
|
||||
* replication configuration and the scanning configuration. Floci records them and returns them;
|
||||
* it does not replicate or scan images.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class RegistrySettings {
|
||||
|
||||
/** One repository filter: a prefix ({@code PREFIX_MATCH}) or a wildcard ({@code WILDCARD}). */
|
||||
@RegisterForReflection
|
||||
public record RepositoryFilter(String filter, String filterType) {}
|
||||
|
||||
/** One replication destination. */
|
||||
@RegisterForReflection
|
||||
public record ReplicationDestination(String region, String registryId) {}
|
||||
|
||||
/** One replication rule: where to copy, and which repositories. */
|
||||
@RegisterForReflection
|
||||
public record ReplicationRule(List<ReplicationDestination> destinations, List<RepositoryFilter> repositoryFilters) {}
|
||||
|
||||
/** One scanning rule: how often, and which repositories. */
|
||||
@RegisterForReflection
|
||||
public record ScanningRule(String scanFrequency, List<RepositoryFilter> repositoryFilters) {}
|
||||
|
||||
private String policyText;
|
||||
private List<ReplicationRule> replicationRules;
|
||||
private String scanType;
|
||||
private List<ScanningRule> scanningRules;
|
||||
|
||||
public RegistrySettings() {}
|
||||
|
||||
public String getPolicyText() { return policyText; }
|
||||
public void setPolicyText(String policyText) { this.policyText = policyText; }
|
||||
|
||||
public List<ReplicationRule> getReplicationRules() { return replicationRules; }
|
||||
public void setReplicationRules(List<ReplicationRule> replicationRules) { this.replicationRules = replicationRules; }
|
||||
|
||||
public String getScanType() { return scanType; }
|
||||
public void setScanType(String scanType) { this.scanType = scanType; }
|
||||
|
||||
public List<ScanningRule> getScanningRules() { return scanningRules; }
|
||||
public void setScanningRules(List<ScanningRule> scanningRules) { this.scanningRules = scanningRules; }
|
||||
}
|
||||
+36
-81
@@ -1,97 +1,52 @@
|
||||
package io.github.hectorvent.floci.services.resourcegroups;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.VendoredResources;
|
||||
import io.github.hectorvent.floci.core.common.RequestConstraintCheck;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Checks a Resource Groups request against the constraints vendored in
|
||||
* {@code aws/resource-groups-request-shapes.json} by {@code tools/aws/regen_resource_groups_shapes.py},
|
||||
* answering {@code BadRequestException}.
|
||||
*/
|
||||
final class ResourceGroupsRequestShapes {
|
||||
private static final JsonNode MODEL = VendoredResources.read("aws/resource-groups-request-shapes.json",
|
||||
"Resource Groups request shapes", input -> new ObjectMapper().readTree(input));
|
||||
private static final Map<String, Pattern> PATTERNS = new HashMap<>();
|
||||
|
||||
static {
|
||||
for (Map.Entry<String, JsonNode> shape : MODEL.path("shapes").properties()) {
|
||||
if (shape.getValue().has("pattern")) {
|
||||
PATTERNS.put(shape.getKey(), Pattern.compile(shape.getValue().get("pattern").asText()));
|
||||
}
|
||||
}
|
||||
}
|
||||
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
|
||||
"aws/resource-groups-request-shapes.json", "Resource Groups request shapes",
|
||||
new RequestConstraintCheck.Messages() {
|
||||
@Override
|
||||
public AwsException type(String path, String type) {
|
||||
return bad(path + " must be a " + type + ".");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException bounds(String path, String type, Long min, Long max, long size) {
|
||||
return bad(path + " is outside the modeled bounds.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException pattern(String path, String pattern) {
|
||||
return bad(path + " does not match the modeled pattern.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException enumValue(String path, List<String> values) {
|
||||
return bad(path + " is not a modeled value.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException required(String path) {
|
||||
return bad(path + " is required.");
|
||||
}
|
||||
});
|
||||
|
||||
private ResourceGroupsRequestShapes() {
|
||||
}
|
||||
|
||||
static void check(String operation, JsonNode request) {
|
||||
checkValue(MODEL.path("operations").path(operation).asText(), request, operation);
|
||||
}
|
||||
|
||||
private static void checkValue(String name, JsonNode value, String path) {
|
||||
JsonNode shape = MODEL.path("shapes").path(name);
|
||||
String type = shape.path("type").asText();
|
||||
boolean validType = value != null && switch (type) {
|
||||
case "structure", "map" -> value.isObject();
|
||||
case "list" -> value.isArray();
|
||||
case "string" -> value.isTextual();
|
||||
case "integer", "long" -> value.isIntegralNumber() && value.canConvertToLong();
|
||||
default -> false;
|
||||
};
|
||||
if (!validType) {
|
||||
throw bad(path + " must be a " + type + ".");
|
||||
}
|
||||
long size = switch (type) {
|
||||
case "string" -> value.textValue().codePointCount(0, value.textValue().length());
|
||||
case "integer", "long" -> value.longValue();
|
||||
default -> value.size();
|
||||
};
|
||||
if (shape.has("min") && size < shape.get("min").asLong()
|
||||
|| shape.has("max") && size > shape.get("max").asLong()) {
|
||||
throw bad(path + " is outside the modeled bounds.");
|
||||
}
|
||||
if (PATTERNS.containsKey(name) && !PATTERNS.get(name).matcher(value.asText()).matches()) {
|
||||
throw bad(path + " does not match the modeled pattern.");
|
||||
}
|
||||
if (shape.has("enum")) {
|
||||
boolean known = false;
|
||||
for (JsonNode choice : shape.get("enum")) {
|
||||
known |= choice.equals(value);
|
||||
}
|
||||
if (!known) {
|
||||
throw bad(path + " is not a modeled value.");
|
||||
}
|
||||
}
|
||||
switch (type) {
|
||||
case "structure" -> {
|
||||
for (JsonNode required : shape.path("required")) {
|
||||
if (!value.hasNonNull(required.asText())) {
|
||||
throw bad(path + "." + required.asText() + " is required.");
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
JsonNode member = shape.path("members").get(field.getKey());
|
||||
if (member != null && !field.getValue().isNull()) {
|
||||
checkValue(member.asText(), field.getValue(), path + "." + field.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
case "list" -> {
|
||||
for (JsonNode item : value) {
|
||||
checkValue(shape.get("member").asText(), item, path + "[]");
|
||||
}
|
||||
}
|
||||
case "map" -> {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
checkValue(shape.get("key").asText(), TextNode.valueOf(field.getKey()), path + ".key");
|
||||
checkValue(shape.get("value").asText(), field.getValue(), path + "." + field.getKey());
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
CHECK.check(operation, request);
|
||||
}
|
||||
|
||||
private static AwsException bad(String message) {
|
||||
|
||||
Reference in new issue
Block a user