feat(ecr): PutImage and the layer API (#5784)

* feat(ecr): PutImage and the layer API

PutImage, BatchCheckLayerAvailability, GetDownloadUrlForLayer, InitiateLayerUpload,
UploadLayerPart and CompleteLayerUpload now go through the registry:2 container that
docker push already writes to, so an image written through the API is the image
docker pull and BatchGetImage return.

- PutImage writes the manifest under its tag, or under its digest. It answers
  ImageDigestDoesNotMatchException, ImageAlreadyExistsException,
  ImageTagAlreadyExistsException and LayersNotFoundException as the model lists them.
- Layer uploads map onto registry upload sessions, held in memory. Parts must follow
  each other, be at most 20 MiB, and all but the last at least 5 MiB.
- GetDownloadUrlForLayer returns the blob's address on Floci's registry endpoint.
- The immutable-tag guard moves into EcrService, so a docker push and a PutImage of
  one tag cannot both succeed.

Closes #5735

* fix(ecr): refuse mixed layer digests, keep push time on retag, expire idle uploads

CompleteLayerUpload refuses a second, different layer digest instead of
ignoring it. PutImage keeps an image's first push time when it retags it.
A layer upload idle for a day is refused even when no other upload opens,
and dropping one cancels its registry upload session.

* fix(ecr): check PutImage tags, require a manifest media type, share registry error handling

- PutImage checks imageTag against the OCI tag grammar and answers
  InvalidParameterException otherwise. The tag goes into the registry's manifest URL,
  so v1?x wrote v1 and a slash wrote into another repository.
- A manifest with no mediaType needs imageManifestMediaType, as on AWS, instead of
  Floci guessing one from the manifest's shape.
- PutImage and the layer API reach the registry through one helper, callRegistry,
  in place of five copies of the same failure handling.

* fix(ecr): answer ECR's own message for a tag outside its rule

PutImage refuses a tag outside ECR's rule, [a-zA-Z0-9-_.]+ up to 300 characters,
with ECR's message. A tag ECR takes but the backing registry cannot hold, one
starting with '.' or '-' or longer than 128 characters, is refused with a message
naming that limit, which docs/services/ecr.md now notes.
This commit is contained in:
David authored and GitHub committed 2026-10-20 07:29:43 -04:00
1 parent d0dac9814f
commit c6551a47bc
15 files changed
+1563 -7

No files matched your search

@@ -20,6 +20,7 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -59,6 +60,12 @@ public class EcrJsonHandler {
case "DescribeImages" -> handleDescribeImages(request, region);
case "BatchGetImage" -> handleBatchGetImage(request, region);
case "BatchDeleteImage" -> handleBatchDeleteImage(request, region);
case "PutImage" -> handlePutImage(request, region);
case "BatchCheckLayerAvailability" -> handleBatchCheckLayerAvailability(request, region);
case "GetDownloadUrlForLayer" -> handleGetDownloadUrlForLayer(request, region);
case "InitiateLayerUpload" -> handleInitiateLayerUpload(request, region);
case "UploadLayerPart" -> handleUploadLayerPart(request, region);
case "CompleteLayerUpload" -> handleCompleteLayerUpload(request, region);
case "PutImageTagMutability" -> handlePutImageTagMutability(request, region);
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
@@ -377,6 +384,107 @@ public class EcrJsonHandler {
// Tag mutability + resource tags
// ============================================================
private Response handlePutImage(JsonNode request, String region) {
Image img = service.putImage(
request.path("repositoryName").asText(null),
request.path("imageManifest").asText(null),
request.path("imageManifestMediaType").asText(null),
request.path("imageTag").asText(null),
request.path("imageDigest").asText(null),
request.path("registryId").asText(null),
region);
ObjectNode n = objectMapper.createObjectNode();
n.put("registryId", img.getRegistryId());
n.put("repositoryName", img.getRepositoryName());
n.set("imageId", buildImageIdentifier(img.getImageId()));
n.put("imageManifest", img.getImageManifest());
n.put("imageManifestMediaType", img.getImageManifestMediaType());
ObjectNode response = objectMapper.createObjectNode();
response.set("image", n);
return Response.ok(response).build();
}
private Response handleBatchCheckLayerAvailability(JsonNode request, String region) {
EcrService.BatchCheckLayerAvailabilityResult result = service.batchCheckLayerAvailability(
request.path("repositoryName").asText(null),
parseStringList(request.path("layerDigests")),
request.path("registryId").asText(null),
region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode layers = response.putArray("layers");
for (EcrService.LayerAvailability layer : result.layers()) {
ObjectNode n = layers.addObject();
n.put("layerDigest", layer.layerDigest());
n.put("layerAvailability", layer.availability());
n.put("layerSize", layer.layerSize());
}
ArrayNode failures = response.putArray("failures");
for (EcrService.LayerFailure failure : result.failures()) {
ObjectNode n = failures.addObject();
if (failure.layerDigest() != null) {
n.put("layerDigest", failure.layerDigest());
}
n.put("failureCode", failure.failureCode());
n.put("failureReason", failure.failureReason());
}
return Response.ok(response).build();
}
private Response handleGetDownloadUrlForLayer(JsonNode request, String region) {
String digest = request.path("layerDigest").asText(null);
String url = service.getDownloadUrlForLayer(
request.path("repositoryName").asText(null),
digest,
request.path("registryId").asText(null),
region);
ObjectNode response = objectMapper.createObjectNode();
response.put("downloadUrl", url);
response.put("layerDigest", digest);
return Response.ok(response).build();
}
private Response handleInitiateLayerUpload(JsonNode request, String region) {
EcrService.LayerUpload upload = service.initiateLayerUpload(
request.path("repositoryName").asText(null),
request.path("registryId").asText(null),
region);
ObjectNode response = objectMapper.createObjectNode();
response.put("uploadId", upload.uploadId());
response.put("partSize", EcrLayerUploads.PART_SIZE);
return Response.ok(response).build();
}
private Response handleUploadLayerPart(JsonNode request, String region) {
String repositoryName = request.path("repositoryName").asText(null);
String uploadId = request.path("uploadId").asText(null);
String registryId = request.path("registryId").asText(null);
long lastByte = service.uploadLayerPart(repositoryName, uploadId,
parseLong(request.path("partFirstByte"), "partFirstByte"),
parseLong(request.path("partLastByte"), "partLastByte"),
parseBlob(request.path("layerPartBlob")),
registryId, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", service.registryIdFor(registryId));
response.put("repositoryName", repositoryName);
response.put("uploadId", uploadId);
response.put("lastByteReceived", lastByte);
return Response.ok(response).build();
}
private Response handleCompleteLayerUpload(JsonNode request, String region) {
String repositoryName = request.path("repositoryName").asText(null);
String uploadId = request.path("uploadId").asText(null);
String registryId = request.path("registryId").asText(null);
String digest = service.completeLayerUpload(repositoryName, uploadId,
parseStringList(request.path("layerDigests")), registryId, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("registryId", service.registryIdFor(registryId));
response.put("repositoryName", repositoryName);
response.put("uploadId", uploadId);
response.put("layerDigest", digest);
return Response.ok(response).build();
}
private Response handlePutImageTagMutability(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
@@ -617,6 +725,27 @@ public class EcrJsonHandler {
return out;
}
private static Long parseLong(JsonNode node, String name) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
if (!node.isIntegralNumber() || !node.canConvertToLong()) {
throw new AwsException("InvalidParameterException", name + " must be an integer.", 400);
}
return node.longValue();
}
private static byte[] parseBlob(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
try {
return Base64.getDecoder().decode(node.asText());
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidParameterException", "layerPartBlob must be base64-encoded.", 400);
}
}
private static Integer parseMaxResults(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.core.common.AwsException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
/**
* The layer uploads opened by {@code InitiateLayerUpload}, each tied to the {@code registry:2}
* upload session that holds its bytes. Sessions live in memory, as the registry's own do, and one
* left idle for a day is dropped, along with its registry upload session.
*/
class EcrLayerUploads {
/** The part size {@code InitiateLayerUpload} reports. */
static final long PART_SIZE = 10L * 1024 * 1024;
/** The largest part {@code UploadLayerPart} takes, as the API reference gives it. */
static final long MAX_PART_SIZE = 20L * 1024 * 1024;
/** The smallest part other than the last, as {@code LayerPartTooSmallException} gives it. */
static final long MIN_PART_SIZE = 5L * 1024 * 1024;
static final Duration IDLE_LIMIT = Duration.ofDays(1);
/** One open upload: the repository it belongs to, the registry URL for its next chunk and its parts so far. */
static final class Session {
private final String scope;
private String location;
private long received;
private final List<Long> partSizes = new ArrayList<>();
private Instant lastTouched;
Session(String scope, String location, Instant now) {
this.scope = scope;
this.location = location;
this.lastTouched = now;
}
String location() {
return location;
}
long received() {
return received;
}
List<Long> partSizes() {
return partSizes;
}
/** Records a part the registry accepted, and the URL it gave for the next one. */
void accept(long size, String nextLocation, Instant now) {
partSizes.add(size);
received += size;
location = nextLocation;
lastTouched = now;
}
}
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
private final Clock clock;
/** Cancels a dropped session's registry upload, given its location. */
private final Consumer<String> discard;
EcrLayerUploads(Consumer<String> discard) {
this(Clock.systemUTC(), discard);
}
EcrLayerUploads(Clock clock, Consumer<String> discard) {
this.clock = clock;
this.discard = discard;
}
Instant now() {
return clock.instant();
}
/** Opens an upload for the repository {@code scope} names, returning its upload ID. */
String open(String scope, String location) {
Instant now = clock.instant();
sessions.forEach((id, session) -> {
if (idle(session, now)) {
drop(id, session);
}
});
String uploadId = UUID.randomUUID().toString();
sessions.put(uploadId, new Session(scope, location, now));
return uploadId;
}
/**
* The open upload {@code uploadId} names in this repository, or {@code UploadNotFoundException},
* which is also the answer for one idle for a day even if no other upload has opened since.
*/
Session require(String scope, String uploadId, String repositoryName) {
Session session = uploadId == null ? null : sessions.get(uploadId);
if (session != null && idle(session, clock.instant())) {
drop(uploadId, session);
session = null;
}
if (session == null || !session.scope.equals(scope)) {
throw new AwsException("UploadNotFoundException",
"Upload with id '" + uploadId + "' is not found for repository '" + repositoryName + "'", 400);
}
return session;
}
void close(String uploadId) {
sessions.remove(uploadId);
}
private static boolean idle(Session session, Instant now) {
return session.lastTouched.plus(IDLE_LIMIT).isBefore(now);
}
private void drop(String uploadId, Session session) {
if (sessions.remove(uploadId, session)) {
discard.accept(session.location);
}
}
/**
* A part must follow the last byte received, match its stated range and fit the size limit.
* The error carries the upload and its last valid byte, as {@code InvalidLayerPartException} does.
*/
static void checkPart(Session session, long firstByte, long lastByte, int length,
String registryId, String repositoryName, String uploadId) {
long expected = session.received;
String message = null;
if (firstByte != expected) {
message = "The part's first byte " + firstByte + " is not consecutive to the last byte "
+ "received; the next part must start at byte " + expected + ".";
} else if (length == 0 || lastByte - firstByte + 1 != length) {
message = "The part holds " + length + " bytes, but the range " + firstByte + "-" + lastByte
+ " names " + Math.max(0, lastByte - firstByte + 1) + ".";
} else if (length > MAX_PART_SIZE) {
message = "A layer part can be at most " + MAX_PART_SIZE + " bytes.";
}
if (message != null) {
throw new AwsException("InvalidLayerPartException", message, 400, Map.of(
"registryId", registryId,
"repositoryName", repositoryName,
"uploadId", uploadId,
"lastValidByteReceived", Math.max(0, expected - 1)));
}
}
/** An upload completes only with at least one part, and every part but the last at least 5 MiB. */
static void checkComplete(Session session) {
List<Long> parts = session.partSizes;
if (parts.isEmpty()) {
throw new AwsException("EmptyUploadException", "The layer upload does not contain any layer parts.", 400);
}
for (int i = 0; i < parts.size() - 1; i++) {
if (parts.get(i) < MIN_PART_SIZE) {
throw new AwsException("LayerPartTooSmallException", "Layer parts must be at least 5 MiB in size.", 400);
}
}
}
}
@@ -1,10 +1,13 @@
package io.github.hectorvent.floci.services.ecr;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -36,6 +39,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -55,6 +60,13 @@ public class EcrService implements ResourceProvider {
"(?:[a-z0-9]+(?:(?:\\.|_|__|-+)[a-z0-9]+)*(?:/[a-z0-9]+"
+ "(?:(?:\\.|_|__|-+)[a-z0-9]+)*)*/?|ROOT)");
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. */
private static final Pattern REGISTRY_IMAGE_TAG = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9._-]{0,127}");
private static final Pattern CREDENTIAL_ARN = Pattern.compile(
"arn:" + AwsArnUtils.PARTITION_REGEX + ":secretsmanager:[a-zA-Z0-9-:]+:secret:ecr-pullthroughcache/"
+ "[a-zA-Z0-9/_+=.@-]+");
@@ -71,6 +83,8 @@ public class EcrService implements ResourceProvider {
private final EcrRegistryManager registryManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final EcrLayerUploads layerUploads = new EcrLayerUploads(this::discardUpload);
private final Set<String> inFlightImmutableTags = ConcurrentHashMap.newKeySet();
@Inject
public EcrService(StorageFactory factory,
@@ -621,6 +635,346 @@ public class EcrService implements ResourceProvider {
return new BatchDeleteImageResult(deleted, failures);
}
// ============================================================
// Image push through the API (PutImage and the layer API)
// ============================================================
public record LayerAvailability(String layerDigest, String availability, Long layerSize) {}
public record LayerFailure(String layerDigest, String failureCode, String failureReason) {}
public record BatchCheckLayerAvailabilityResult(List<LayerAvailability> layers, List<LayerFailure> failures) {}
public record LayerUpload(String registryId, String repositoryName, String uploadId) {}
/**
* Writes a manifest to the registry under its tag, or under its digest when no tag is given, so
* {@code docker pull} and {@code BatchGetImage} see it as they see a pushed image.
*/
public Image putImage(String repositoryName, String imageManifest, String imageManifestMediaType,
String imageTag, String imageDigest, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
if (imageManifest == null || imageManifest.isEmpty()) {
throw new AwsException("InvalidParameterException", "imageManifest must not be empty", 400);
}
if (imageTag != null) {
requireImageTag(imageTag);
}
String mediaType = manifestMediaType(imageManifest, imageManifestMediaType);
String digest = "sha256:" + Digests.sha256Hex(imageManifest.getBytes(StandardCharsets.UTF_8));
if (imageDigest != null && !imageDigest.isEmpty() && !imageDigest.equals(digest)) {
throw new AwsException("ImageDigestDoesNotMatchException",
"Invalid parameter at 'imageDigest' failed to satisfy constraint: 'specified digest "
+ imageDigest + " does not match the calculated digest " + digest + "'", 400);
}
requireRegistry();
String storage = registryRepositoryName(repo, region);
RegistryHttpClient http = registryManager.httpClient();
String guarded = imageTag != null && "IMMUTABLE".equals(repo.getImageTagMutability())
? immutableTagKey(repo.getRegistryId(), region, repositoryName, imageTag) : null;
if (guarded != null && !claimImmutableTag(guarded)) {
throw imageTagAlreadyExists(imageTag, repositoryName);
}
try {
return callRegistry(() -> writeManifest(repo, repositoryName, storage, http, imageManifest, mediaType,
imageTag, digest, guarded, region), EcrService::putImageError);
} finally {
if (guarded != null) {
releaseImmutableTag(guarded);
}
}
}
private Image writeManifest(Repository repo, String repositoryName, String storage, RegistryHttpClient http,
String imageManifest, String mediaType, String imageTag, String digest,
String guarded, String region) throws Exception {
String existing = http.headManifestDigestStrict(storage, imageTag != null ? imageTag : digest, null);
if (digest.equals(existing)) {
throw new AwsException("ImageAlreadyExistsException",
"Image with digest '" + digest + "'" + (imageTag != null ? " and tag '" + imageTag + "'" : "")
+ " already exists in the repository with name '" + repositoryName
+ "' in registry with id '" + repo.getRegistryId() + "'", 400);
}
if (existing != null && guarded != null) {
throw imageTagAlreadyExists(imageTag, repositoryName);
}
String stored = http.putManifest(storage, imageTag != null ? imageTag : digest, mediaType, imageManifest);
String finalDigest = stored != null ? stored : digest;
// A retag keeps the image's first push time, as DescribeImages records it.
String metaKey = imageMetaKey(region, repo.getRegistryId(), repositoryName, finalDigest);
if (imageMetaStore.get(metaKey).isEmpty()) {
imageMetaStore.put(metaKey, new ImageMetadata(finalDigest, Instant.now()));
}
Image image = new Image();
image.setRegistryId(repo.getRegistryId());
image.setRepositoryName(repositoryName);
image.setImageId(new ImageIdentifier(imageTag, finalDigest));
image.setImageManifest(imageManifest);
image.setImageManifestMediaType(mediaType);
return image;
}
/**
* Refuses a tag ECR refuses, with ECR's message, then a tag ECR takes but the backing registry
* cannot hold: one starting with '.' or '-', or longer than 128 characters.
*/
private static void requireImageTag(String imageTag) {
if (imageTag.length() > 300) {
throw new AwsException("InvalidParameterException", "Invalid parameter at 'imageTag' failed to satisfy"
+ " constraint: 'Member must have length less than or equal to 300'", 400);
}
if (!ECR_IMAGE_TAG.matcher(imageTag).matches()) {
throw new AwsException("InvalidParameterException", "Invalid parameter at 'imageTag' failed to satisfy"
+ " constraint: 'must satisfy regular expression '[a-zA-Z0-9-_.]+''", 400);
}
if (!REGISTRY_IMAGE_TAG.matcher(imageTag).matches()) {
throw new AwsException("InvalidParameterException", "Floci's backing registry cannot hold the tag '"
+ imageTag + "': it must start with a letter, digit or underscore and be at most 128"
+ " characters", 400);
}
}
/** Reports which of the given layers the repository holds, with their sizes. */
public BatchCheckLayerAvailabilityResult batchCheckLayerAvailability(String repositoryName,
List<String> layerDigests,
String registryId,
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
if (layerDigests == null || layerDigests.isEmpty() || layerDigests.size() > 100) {
throw new AwsException("InvalidParameterException", "layerDigests must hold 1 to 100 digests", 400);
}
requireRegistry();
String storage = registryRepositoryName(repo, region);
RegistryHttpClient http = registryManager.httpClient();
List<LayerAvailability> layers = new ArrayList<>();
List<LayerFailure> failures = new ArrayList<>();
for (String digest : layerDigests) {
if (digest == null || !LAYER_DIGEST.matcher(digest).matches()) {
failures.add(new LayerFailure(digest, "InvalidLayerDigest", "Invalid layer digest"));
continue;
}
Long size = headBlob(http, storage, digest);
if (size == null) {
failures.add(new LayerFailure(digest, "MissingLayerDigest", "Could not find layer"));
} else {
layers.add(new LayerAvailability(digest, "AVAILABLE", size));
}
}
return new BatchCheckLayerAvailabilityResult(layers, failures);
}
/** The address a layer can be fetched from: Floci's registry endpoint, which needs no credentials. */
public String getDownloadUrlForLayer(String repositoryName, String layerDigest, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireLayerDigest(layerDigest);
requireRegistry();
Long size = headBlob(registryManager.httpClient(), registryRepositoryName(repo, region), layerDigest);
if (size == null) {
throw layersNotFound(layerDigest, repositoryName, repo.getRegistryId());
}
return registryManager.blobUrl(repo.getRepositoryUri(), layerDigest);
}
/** Cancels the registry upload session of a layer upload left idle for a day. */
private void discardUpload(String location) {
registryManager.httpClient().cancelUpload(location);
}
/** Opens a registry upload session for one layer. */
public LayerUpload initiateLayerUpload(String repositoryName, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String location = callRegistry(
() -> registryManager.httpClient().startUpload(registryRepositoryName(repo, region)),
EcrService::registryUnavailable);
String uploadId = layerUploads.open(key(region, repo.getRegistryId(), repositoryName), location);
return new LayerUpload(repo.getRegistryId(), repositoryName, uploadId);
}
/** Sends one part of a layer, returning the last byte received. */
public long uploadLayerPart(String repositoryName, String uploadId, Long partFirstByte, Long partLastByte,
byte[] layerPartBlob, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
if (partFirstByte == null || partLastByte == null || layerPartBlob == null
|| partFirstByte < 0 || partLastByte < 0) {
throw new AwsException("InvalidParameterException",
"partFirstByte, partLastByte and layerPartBlob are required and must not be negative", 400);
}
EcrLayerUploads.Session session = layerUploads.require(
key(region, repo.getRegistryId(), repositoryName), uploadId, repositoryName);
synchronized (session) {
EcrLayerUploads.checkPart(session, partFirstByte, partLastByte, layerPartBlob.length,
repo.getRegistryId(), repositoryName, uploadId);
requireRegistry();
String next = callRegistry(
() -> registryManager.httpClient().patchUpload(session.location(), layerPartBlob, partFirstByte),
e -> uploadError(e, uploadId, repositoryName));
session.accept(layerPartBlob.length, next, layerUploads.now());
return partLastByte;
}
}
/** Closes an upload, storing its bytes under the digest given, and returns that digest. */
public String completeLayerUpload(String repositoryName, String uploadId, List<String> layerDigests,
String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
if (layerDigests == null || layerDigests.isEmpty() || layerDigests.size() > 100) {
throw new AwsException("InvalidParameterException", "layerDigests must hold 1 to 100 digests", 400);
}
// An upload holds one layer, so every digest given must name it.
String digest = layerDigests.get(0);
for (String d : layerDigests) {
requireLayerDigest(d);
if (!digest.equals(d)) {
throw new AwsException("InvalidParameterException",
"layerDigests must all name the one layer the upload holds", 400);
}
}
EcrLayerUploads.Session session = layerUploads.require(
key(region, repo.getRegistryId(), repositoryName), uploadId, repositoryName);
synchronized (session) {
EcrLayerUploads.checkComplete(session);
requireRegistry();
RegistryHttpClient http = registryManager.httpClient();
String storage = registryRepositoryName(repo, region);
if (headBlob(http, storage, digest) != null) {
http.cancelUpload(session.location());
layerUploads.close(uploadId);
throw new AwsException("LayerAlreadyExistsException",
"Layer " + digest + " already exists in the repository with name '" + repositoryName
+ "' in registry with id '" + repo.getRegistryId() + "'", 400);
}
callRegistry(() -> {
http.finishUpload(session.location(), digest);
return null;
}, e -> {
layerUploads.close(uploadId);
if ("DIGEST_INVALID".equals(e.code())) {
return new AwsException("InvalidLayerException",
"The layer digest calculated for the upload does not match " + digest, 400);
}
return uploadError(e, uploadId, repositoryName);
});
layerUploads.close(uploadId);
return digest;
}
}
/** The registry ID a request names, or the caller's account when it names none. */
public String registryIdFor(String registryId) {
return effectiveAccount(registryId);
}
/** The key both the registry data plane and {@code PutImage} hold while writing an immutable tag. */
public static String immutableTagKey(String account, String region, String repositoryName, String tag) {
return account + "/" + region + "/" + repositoryName + ":" + tag;
}
/** Claims an immutable tag for one write; false if another write holds it. */
public boolean claimImmutableTag(String key) {
return inFlightImmutableTags.add(key);
}
public void releaseImmutableTag(String key) {
inFlightImmutableTags.remove(key);
}
/** The media type sent, else the manifest's own {@code mediaType}; with neither, the request is refused. */
private static String manifestMediaType(String manifest, String given) {
JsonNode root;
try {
root = MAPPER.readTree(manifest);
} catch (Exception e) {
root = null;
}
if (root == null || !root.isObject()) {
throw new AwsException("InvalidParameterException", "imageManifest is not a valid JSON manifest", 400);
}
if (given != null && !given.isEmpty()) {
return given;
}
String own = root.path("mediaType").asText("");
if (own.isEmpty()) {
throw new AwsException("InvalidParameterException",
"imageManifestMediaType is required when the manifest has no mediaType", 400);
}
return own;
}
private Long headBlob(RegistryHttpClient http, String storage, String digest) {
return callRegistry(() -> http.headBlob(storage, digest), EcrService::registryUnavailable);
}
/** One call to the backing registry. */
@FunctionalInterface
private interface RegistryCall<T> {
T call() throws Exception;
}
/**
* Runs a call to the backing registry, answering a refusal the registry gives with what
* {@code refused} maps it to and any other failure with {@code ServerException}.
*/
private static <T> T callRegistry(RegistryCall<T> call,
Function<RegistryHttpClient.RegistryErrorException, AwsException> refused) {
try {
return call.call();
} catch (AwsException e) {
throw e;
} catch (RegistryHttpClient.RegistryErrorException e) {
throw refused.apply(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw registryUnavailable(e);
} catch (Exception e) {
throw registryUnavailable(e);
}
}
private static void requireLayerDigest(String digest) {
if (digest == null || !LAYER_DIGEST.matcher(digest).matches()) {
throw new AwsException("InvalidParameterException", "Invalid layer digest: " + digest, 400);
}
}
private static AwsException putImageError(RegistryHttpClient.RegistryErrorException e) {
String code = e.code() == null ? "" : e.code();
return switch (code) {
case "MANIFEST_BLOB_UNKNOWN", "BLOB_UNKNOWN" -> new AwsException("LayersNotFoundException",
"The image references layers that are not in the repository: " + e.getMessage(), 400);
case "MANIFEST_INVALID", "MANIFEST_UNVERIFIED", "DIGEST_INVALID", "TAG_INVALID", "NAME_INVALID" ->
new AwsException("InvalidParameterException", "The registry refused the manifest: " + e.getMessage(), 400);
default -> registryUnavailable(e);
};
}
private static AwsException uploadError(RegistryHttpClient.RegistryErrorException e, String uploadId,
String repositoryName) {
if ("BLOB_UPLOAD_UNKNOWN".equals(e.code()) || e.status() == 404) {
return new AwsException("UploadNotFoundException",
"Upload with id '" + uploadId + "' is not found for repository '" + repositoryName + "'", 400);
}
if ("BLOB_UPLOAD_INVALID".equals(e.code()) || e.status() == 416) {
return new AwsException("InvalidLayerPartException", "The registry refused the part: " + e.getMessage(), 400);
}
return registryUnavailable(e);
}
private static AwsException imageTagAlreadyExists(String tag, String repositoryName) {
return new AwsException("ImageTagAlreadyExistsException",
"The image tag '" + tag + "' already exists in the '" + repositoryName
+ "' repository and cannot be overwritten because the repository is immutable.", 400);
}
private static AwsException layersNotFound(String digest, String repositoryName, String registryId) {
return new AwsException("LayersNotFoundException",
"The specified layer " + digest + " could not be found in the repository with name '"
+ repositoryName + "' in the registry with id '" + registryId + "'", 400);
}
private static AwsException registryUnavailable(Exception e) {
return new AwsException("ServerException", "The ECR backing registry failed: " + e.getMessage(), 500);
}
// ============================================================
// Tag mutability + resource tags + policies (metadata round-trip)
// ============================================================
@@ -23,7 +23,6 @@ import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -46,7 +45,6 @@ public class EcrRegistryDataPlane {
private final EcrService ecrService;
private final EmulatorConfig config;
private final Vertx vertx;
private final Set<String> inFlightImmutableTags = ConcurrentHashMap.newKeySet();
@Inject
public EcrRegistryDataPlane(EcrRegistryManager registryManager,
@@ -82,7 +80,7 @@ public class EcrRegistryDataPlane {
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
}
String immutableTag = immutableTag(context, registryRequest);
if (immutableTag != null && !inFlightImmutableTags.add(immutableTag)) {
if (immutableTag != null && !ecrService.claimImmutableTag(immutableTag)) {
context.request().resume();
imageTagAlreadyExists(context, registryRequest);
return;
@@ -103,7 +101,7 @@ public class EcrRegistryDataPlane {
|| !ecrService.isImageTagImmutable(request.repositoryName(), request.accountId(), request.region())) {
return null;
}
return request.accountId() + "/" + request.region() + "/" + request.repositoryName() + ":" + request.tag();
return EcrService.immutableTagKey(request.accountId(), request.region(), request.repositoryName(), request.tag());
}
private void checkTagAndProxy(RoutingContext context, RegistryRequest request, Exchange exchange) {
@@ -242,7 +240,7 @@ public class EcrRegistryDataPlane {
private void release(String immutableTag) {
if (immutableTag != null) {
inFlightImmutableTags.remove(immutableTag);
ecrService.releaseImmutableTag(immutableTag);
}
}
@@ -180,6 +180,18 @@ public class EcrRegistryManager {
return config.services().ecr().tlsUri() && config.tls().enabled();
}
/**
* The address a blob can be fetched from through Floci's registry endpoint: the repository URI's
* host, with {@code /v2/<repository>/blobs/<digest>}, over the scheme the proxy endpoint uses.
*/
public String blobUrl(String repositoryUri, String digest) {
int slash = repositoryUri.indexOf('/');
String endpoint = getProxyEndpoint();
String scheme = endpoint.substring(0, endpoint.indexOf("://"));
return scheme + "://" + repositoryUri.substring(0, slash) + "/v2/" + repositoryUri.substring(slash + 1)
+ "/blobs/" + digest;
}
/**
* Returns the proxy endpoint a docker daemon should log into for any ECR repo.
*
@@ -6,9 +6,11 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
@@ -224,6 +226,146 @@ public class RegistryHttpClient {
return true;
}
/**
* A registry refusal, carrying the first {@code errors[].code} of the registry's error body
* (for example {@code MANIFEST_BLOB_UNKNOWN}) so the ECR API can answer with its own error.
*/
public static class RegistryErrorException extends IOException {
private final int status;
private final String code;
public RegistryErrorException(int status, String code, String message) {
super(message);
this.status = status;
this.code = code;
}
public int status() {
return status;
}
public String code() {
return code;
}
}
/** PUT a manifest under a tag or digest, returning the digest the registry stored it under. */
public String putManifest(String name, String reference, String mediaType, String body)
throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + reference))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", mediaType)
.PUT(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400) {
throw registryError("PUT manifest " + name + "/" + reference, resp);
}
return resp.headers().firstValue("Docker-Content-Digest").orElse(null);
}
/** HEAD a blob, returning its size in bytes, or {@code null} if the repository does not hold it. */
public Long headBlob(String name, String digest) throws IOException, InterruptedException {
HttpResponse<Void> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/blobs/" + digest))
.timeout(Duration.ofSeconds(10))
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.build(),
HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() == 404) {
return null;
}
if (resp.statusCode() >= 400) {
throw new IOException("Registry HEAD blob " + name + "/" + digest + " returned " + resp.statusCode());
}
return resp.headers().firstValueAsLong("Content-Length").orElse(0L);
}
/** Opens a blob upload session, returning the absolute URL the next request goes to. */
public String startUpload(String name) throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/blobs/uploads/"))
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.noBody())
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 202) {
throw registryError("POST blob upload " + name, resp);
}
return uploadLocation(resp);
}
/**
* Sends one chunk of an upload, bytes {@code first} to {@code first + bytes.length - 1}, and
* returns the URL the next request goes to.
*/
public String patchUpload(String location, byte[] bytes, long first) throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(location))
.timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/octet-stream")
.header("Content-Range", first + "-" + (first + bytes.length - 1))
.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(bytes))
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 202) {
throw registryError("PATCH blob upload", resp);
}
return uploadLocation(resp);
}
/** Closes an upload, asking the registry to store what it received under {@code digest}. */
public void finishUpload(String location, String digest) throws IOException, InterruptedException {
String url = location + (location.contains("?") ? "&" : "?")
+ "digest=" + URLEncoder.encode(digest, StandardCharsets.UTF_8);
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/octet-stream")
.PUT(HttpRequest.BodyPublishers.noBody())
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 201) {
throw registryError("PUT blob upload", resp);
}
}
/** Drops an upload session the registry still holds. Best effort. */
public void cancelUpload(String location) {
try {
http.send(HttpRequest.newBuilder(URI.create(location))
.timeout(Duration.ofSeconds(10))
.DELETE()
.build(),
HttpResponse.BodyHandlers.discarding());
} catch (Exception e) {
LOG.debugv("Registry DELETE blob upload failed: {0}", e.getMessage());
}
}
private String uploadLocation(HttpResponse<?> resp) throws IOException {
String location = resp.headers().firstValue("Location").orElse(null);
if (location == null || location.isBlank()) {
throw new IOException("Registry blob upload response has no Location");
}
return location.startsWith("/") ? baseUrl + location : location;
}
private static RegistryErrorException registryError(String what, HttpResponse<String> resp) {
String code = null;
try {
JsonNode errors = MAPPER.readTree(resp.body()).path("errors");
if (errors.isArray() && !errors.isEmpty()) {
code = errors.get(0).path("code").asText(null);
}
} catch (Exception ignored) {
// A body that is not the registry's error JSON leaves the code unknown.
}
return new RegistryErrorException(resp.statusCode(), code,
"Registry " + what + " returned " + resp.statusCode() + ": " + resp.body());
}
/**
* Sums {@code config.size} + each {@code layers[].size} from a manifest body.
* Returns 0 if the body is not a recognised image manifest.