mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
d0dac9814f
commit
c6551a47bc
15 files changed
+1563
-7
No files matched your search
+304
@@ -0,0 +1,304 @@
|
||||
package io.github.hectorvent.floci.services.ecr;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.json.Json;
|
||||
import io.vertx.core.net.SocketAddress;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Pushes an image through the ECR API alone, as SDK-based copy tools do: a layer uploaded in parts,
|
||||
* a config blob, then {@code PutImage}. The result must be the image the registry data plane, and
|
||||
* so {@code docker pull}, serves, and a retag through {@code PutImage} must reach it too.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class EcrImagePushApiDockerIntegrationTest {
|
||||
|
||||
private static final String CT = "application/x-amz-json-1.1";
|
||||
private static final String PREFIX = "AmazonEC2ContainerRegistry_V20150921.";
|
||||
private static final int MIB = 1024 * 1024;
|
||||
private static final String DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
|
||||
|
||||
private final String repo = "push-api/" + UUID.randomUUID().toString().substring(0, 8);
|
||||
private final String immutableRepo = repo + "-immutable";
|
||||
private final byte[] layer = randomBytes(5 * MIB + 1000);
|
||||
private final byte[] config = "{\"architecture\":\"amd64\",\"os\":\"linux\"}".getBytes(StandardCharsets.UTF_8);
|
||||
private final String layerDigest = "sha256:" + Digests.sha256Hex(layer);
|
||||
private final String configDigest = "sha256:" + Digests.sha256Hex(config);
|
||||
private String manifest;
|
||||
private String manifestDigest;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
private boolean created;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.ecr.registry-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
/** Once, but per test: RestAssured has its port only once a test starts. */
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
if (created) {
|
||||
return;
|
||||
}
|
||||
created = true;
|
||||
call("CreateRepository", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200);
|
||||
call("CreateRepository", "{\"repositoryName\":\"" + immutableRepo + "\",\"imageTagMutability\":\"IMMUTABLE\"}")
|
||||
.statusCode(200);
|
||||
manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "%s",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": %d, "digest": "%s"},
|
||||
"layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "size": %d, "digest": "%s"}]
|
||||
}""".formatted(DOCKER_MANIFEST, config.length, configDigest, layer.length, layerDigest);
|
||||
manifestDigest = "sha256:" + Digests.sha256Hex(manifest.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void aLayerUploadsInPartsThatMustFollowEachOther() {
|
||||
String uploadId = initiate(repo);
|
||||
byte[] first = Arrays.copyOfRange(layer, 0, 5 * MIB);
|
||||
byte[] rest = Arrays.copyOfRange(layer, 5 * MIB, layer.length);
|
||||
|
||||
part(repo, uploadId, 0, first).statusCode(200).body("lastByteReceived", equalTo(5 * MIB - 1));
|
||||
part(repo, uploadId, 0, first).statusCode(400)
|
||||
.body("__type", equalTo("InvalidLayerPartException"))
|
||||
.body("lastValidByteReceived", equalTo(5 * MIB - 1));
|
||||
part(repo, uploadId, 5 * MIB, rest).statusCode(200).body("lastByteReceived", equalTo(layer.length - 1));
|
||||
|
||||
complete(repo, uploadId, layerDigest).statusCode(200)
|
||||
.body("layerDigest", equalTo(layerDigest))
|
||||
.body("uploadId", equalTo(uploadId));
|
||||
complete(repo, uploadId, layerDigest).statusCode(400).body("__type", equalTo("UploadNotFoundException"));
|
||||
|
||||
String configUpload = initiate(repo);
|
||||
part(repo, configUpload, 0, config).statusCode(200);
|
||||
complete(repo, configUpload, configDigest).statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void aBadUploadIsRefused() {
|
||||
String again = initiate(repo);
|
||||
part(repo, again, 0, config).statusCode(200);
|
||||
complete(repo, again, configDigest).statusCode(400).body("__type", equalTo("LayerAlreadyExistsException"));
|
||||
|
||||
String empty = initiate(repo);
|
||||
complete(repo, empty, layerDigest).statusCode(400).body("__type", equalTo("EmptyUploadException"));
|
||||
|
||||
String small = initiate(repo);
|
||||
part(repo, small, 0, new byte[10]).statusCode(200);
|
||||
part(repo, small, 10, new byte[10]).statusCode(200);
|
||||
complete(repo, small, "sha256:" + Digests.sha256Hex(new byte[20])).statusCode(400)
|
||||
.body("__type", equalTo("LayerPartTooSmallException"));
|
||||
|
||||
String mismatch = initiate(repo);
|
||||
part(repo, mismatch, 0, "other".getBytes(StandardCharsets.UTF_8)).statusCode(200);
|
||||
complete(repo, mismatch, "sha256:" + Digests.sha256Hex(new byte[1])).statusCode(400)
|
||||
.body("__type", equalTo("InvalidLayerException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void uploadedLayersAreAvailable() {
|
||||
String missing = "sha256:" + "0".repeat(64);
|
||||
call("BatchCheckLayerAvailability", "{\"repositoryName\":\"" + repo + "\",\"layerDigests\":[\""
|
||||
+ layerDigest + "\",\"" + configDigest + "\",\"" + missing + "\",\"bad\"]}")
|
||||
.statusCode(200)
|
||||
.body("layers", hasSize(2))
|
||||
.body("layers[0].layerDigest", equalTo(layerDigest))
|
||||
.body("layers[0].layerAvailability", equalTo("AVAILABLE"))
|
||||
.body("layers[0].layerSize", equalTo(layer.length))
|
||||
.body("layers[1].layerSize", equalTo(config.length))
|
||||
.body("failures.failureCode", hasItems("MissingLayerDigest", "InvalidLayerDigest"))
|
||||
.body("failures.layerDigest", hasItems(missing, "bad"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void putImageWritesTheManifestThatPullsServe() throws Exception {
|
||||
call("PutImage", putImage(repo, manifest, "v1")).statusCode(200)
|
||||
.body("image.imageId.imageTag", equalTo("v1"))
|
||||
.body("image.imageId.imageDigest", equalTo(manifestDigest))
|
||||
.body("image.imageManifestMediaType", equalTo(DOCKER_MANIFEST))
|
||||
.body("image.repositoryName", equalTo(repo));
|
||||
call("PutImage", putImage(repo, manifest, "v1")).statusCode(400)
|
||||
.body("__type", equalTo("ImageAlreadyExistsException"));
|
||||
|
||||
String unknownLayer = manifest.replace(layerDigest, "sha256:" + "1".repeat(64));
|
||||
call("PutImage", putImage(repo, unknownLayer, "broken")).statusCode(400)
|
||||
.body("__type", equalTo("LayersNotFoundException"));
|
||||
|
||||
Fetched pulled = registryGet("000000000000.dkr.ecr.us-east-1.localhost",
|
||||
"/v2/" + repo + "/manifests/v1", DOCKER_MANIFEST);
|
||||
assertEquals(200, pulled.statusCode());
|
||||
assertEquals(manifestDigest, pulled.digest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void aRetagReadsTheManifestAndPutsItUnderANewTag() {
|
||||
String read = call("BatchGetImage", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":[{\"imageTag\":\"v1\"}]}")
|
||||
.statusCode(200)
|
||||
.extract().path("images[0].imageManifest");
|
||||
|
||||
call("PutImage", putImage(repo, read, "release")).statusCode(200)
|
||||
.body("image.imageId.imageDigest", equalTo(manifestDigest));
|
||||
call("DescribeImages", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":[{\"imageTag\":\"release\"}]}")
|
||||
.statusCode(200)
|
||||
.body("imageDetails[0].imageDigest", equalTo(manifestDigest));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void theDownloadUrlServesTheLayer() throws Exception {
|
||||
String url = call("GetDownloadUrlForLayer", "{\"repositoryName\":\"" + repo + "\",\"layerDigest\":\""
|
||||
+ layerDigest + "\"}")
|
||||
.statusCode(200)
|
||||
.body("layerDigest", equalTo(layerDigest))
|
||||
.extract().path("downloadUrl");
|
||||
URI uri = URI.create(url);
|
||||
assertEquals("/v2/" + repo + "/blobs/" + layerDigest, uri.getPath());
|
||||
|
||||
Fetched response = registryGet(uri.getHost(), uri.getPath(), null);
|
||||
assertEquals(200, response.statusCode());
|
||||
assertArrayEquals(layer, response.body().getBytes());
|
||||
|
||||
call("GetDownloadUrlForLayer", "{\"repositoryName\":\"" + repo + "\",\"layerDigest\":\"sha256:"
|
||||
+ "2".repeat(64) + "\"}")
|
||||
.statusCode(400).body("__type", equalTo("LayersNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void anImmutableTagIsWrittenOnce() {
|
||||
String upload = initiate(immutableRepo);
|
||||
part(immutableRepo, upload, 0, config).statusCode(200);
|
||||
complete(immutableRepo, upload, configDigest).statusCode(200);
|
||||
String first = """
|
||||
{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json",\
|
||||
"config":{"mediaType":"application/vnd.oci.image.config.v1+json","size":%d,"digest":"%s"},\
|
||||
"layers":[]}""".formatted(config.length, configDigest);
|
||||
String second = first.replace("\"layers\":[]", "\"layers\":[],\"annotations\":{\"build\":\"2\"}");
|
||||
|
||||
call("PutImage", putImage(immutableRepo, first, "v1")).statusCode(200);
|
||||
call("PutImage", putImage(immutableRepo, second, "v1")).statusCode(400)
|
||||
.body("__type", equalTo("ImageTagAlreadyExistsException"));
|
||||
call("PutImage", putImage(immutableRepo, second, "v2")).statusCode(200)
|
||||
.body("image.imageManifestMediaType", equalTo("application/vnd.oci.image.manifest.v1+json"));
|
||||
}
|
||||
|
||||
/** Last, since every class on this profile shares one registry. */
|
||||
@Test
|
||||
@Order(8)
|
||||
void cleanUp() {
|
||||
call("DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}").statusCode(200);
|
||||
call("DeleteRepository", "{\"repositoryName\":\"" + immutableRepo + "\",\"force\":true}").statusCode(200);
|
||||
}
|
||||
|
||||
private String initiate(String repository) {
|
||||
return call("InitiateLayerUpload", "{\"repositoryName\":\"" + repository + "\"}")
|
||||
.statusCode(200)
|
||||
.body("partSize", equalTo(10 * MIB))
|
||||
.extract().path("uploadId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse part(String repository, String uploadId, long first, byte[] bytes) {
|
||||
return call("UploadLayerPart", "{\"repositoryName\":\"" + repository + "\",\"uploadId\":\"" + uploadId
|
||||
+ "\",\"partFirstByte\":" + first + ",\"partLastByte\":" + (first + bytes.length - 1)
|
||||
+ ",\"layerPartBlob\":\"" + Base64.getEncoder().encodeToString(bytes) + "\"}");
|
||||
}
|
||||
|
||||
private static ValidatableResponse complete(String repository, String uploadId, String digest) {
|
||||
return call("CompleteLayerUpload", "{\"repositoryName\":\"" + repository + "\",\"uploadId\":\"" + uploadId
|
||||
+ "\",\"layerDigests\":[\"" + digest + "\"]}");
|
||||
}
|
||||
|
||||
private static String putImage(String repository, String imageManifest, String tag) {
|
||||
return "{\"repositoryName\":\"" + repository + "\",\"imageTag\":\"" + tag + "\",\"imageManifest\":"
|
||||
+ Json.encode(imageManifest) + "}";
|
||||
}
|
||||
|
||||
/** A GET through Floci's registry data plane, by the host name a Docker client would use. */
|
||||
private Fetched registryGet(String host, String path, String accept) throws Exception {
|
||||
int port = RestAssured.port;
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
RequestOptions options = new RequestOptions()
|
||||
.setServer(SocketAddress.inetSocketAddress(port, "127.0.0.1"))
|
||||
.setHost(host)
|
||||
.setPort(port)
|
||||
.setMethod(HttpMethod.GET)
|
||||
.setURI(path);
|
||||
return client.request(options)
|
||||
.compose(request -> {
|
||||
if (accept != null) {
|
||||
request.putHeader("Accept", accept);
|
||||
}
|
||||
return request.send();
|
||||
})
|
||||
.compose(response -> response.body().map(body -> new Fetched(
|
||||
response.statusCode(), response.getHeader("Docker-Content-Digest"), body)))
|
||||
.onComplete(ignored -> client.close())
|
||||
.toCompletionStage().toCompletableFuture().get(30, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/** A data plane response: its status, its {@code Docker-Content-Digest} and its body. */
|
||||
private record Fetched(int statusCode, String digest, Buffer body) {}
|
||||
|
||||
private static ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", PREFIX + action)
|
||||
.contentType(CT)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
private static byte[] randomBytes(int size) {
|
||||
byte[] bytes = new byte[size];
|
||||
new Random(5735).nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
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.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* {@code PutImage} and the layer API's checks that come before the registry is reached: unknown
|
||||
* repositories, unknown uploads and malformed input. Needs no Docker; the push itself is covered
|
||||
* by {@code EcrImagePushApiDockerIntegrationTest}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class EcrImagePushApiIntegrationTest {
|
||||
|
||||
private static final String CT = "application/x-amz-json-1.1";
|
||||
private static final String PREFIX = "AmazonEC2ContainerRegistry_V20150921.";
|
||||
private static final String REPO = "push-api-it/checks";
|
||||
private static final String OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
|
||||
private static final String DIGEST = "sha256:" + "a".repeat(64);
|
||||
private static final String UPLOAD_ID = "6a1f2b3c-0000-4000-8000-000000000000";
|
||||
|
||||
private boolean created;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
/** Once, but per test: RestAssured has its port only once a test starts. */
|
||||
@BeforeEach
|
||||
void createRepository() {
|
||||
if (!created) {
|
||||
call("CreateRepository", "{\"repositoryName\":\"" + REPO + "\"}").statusCode(200);
|
||||
created = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyActionNeedsAnExistingRepository() {
|
||||
String missing = "\"repositoryName\":\"push-api-it/missing\"";
|
||||
String[][] calls = {
|
||||
{"PutImage", "{" + missing + ",\"imageManifest\":\"{}\",\"imageTag\":\"v1\"}"},
|
||||
{"BatchCheckLayerAvailability", "{" + missing + ",\"layerDigests\":[\"" + DIGEST + "\"]}"},
|
||||
{"GetDownloadUrlForLayer", "{" + missing + ",\"layerDigest\":\"" + DIGEST + "\"}"},
|
||||
{"InitiateLayerUpload", "{" + missing + "}"},
|
||||
{"UploadLayerPart", "{" + missing + ",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"partFirstByte\":0,\"partLastByte\":0,\"layerPartBlob\":\"YQ==\"}"},
|
||||
{"CompleteLayerUpload", "{" + missing + ",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"layerDigests\":[\"" + DIGEST + "\"]}"},
|
||||
};
|
||||
for (String[] c : calls) {
|
||||
call(c[0], c[1]).statusCode(400).body("__type", equalTo("RepositoryNotFoundException"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImageChecksTheManifestAndItsDigest() {
|
||||
call("PutImage", "{\"repositoryName\":\"" + REPO + "\",\"imageManifest\":\"{}\",\"imageTag\":\"v1\","
|
||||
+ "\"imageManifestMediaType\":\"" + OCI_MANIFEST + "\",\"imageDigest\":\"" + DIGEST + "\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ImageDigestDoesNotMatchException"))
|
||||
.body("message", containsString("sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"));
|
||||
call("PutImage", "{\"repositoryName\":\"" + REPO + "\",\"imageManifest\":\"not json\",\"imageTag\":\"v1\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("PutImage", "{\"repositoryName\":\"" + REPO + "\",\"imageManifest\":\"\",\"imageTag\":\"v1\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
// With no mediaType in the manifest, AWS requires imageManifestMediaType rather than guessing.
|
||||
call("PutImage", "{\"repositoryName\":\"" + REPO + "\",\"imageManifest\":\"{}\",\"imageTag\":\"v1\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", containsString("imageManifestMediaType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImageRefusesATagEcrRefusesWithEcrsMessage() {
|
||||
// Each would otherwise change the registry URL: v1?x writes v1, a slash names another repository.
|
||||
for (String tag : new String[] {"v1?x", "team/v1", "v1#x", "v 1", "v1:x"}) {
|
||||
putTag(tag).statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", equalTo("Invalid parameter at 'imageTag' failed to satisfy constraint: "
|
||||
+ "'must satisfy regular expression '[a-zA-Z0-9-_.]+''"));
|
||||
}
|
||||
putTag("t".repeat(301)).statusCode(400)
|
||||
.body("message", containsString("Member must have length less than or equal to 300"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImageRefusesATagTheBackingRegistryCannotHold() {
|
||||
// ECR takes these; the OCI tag grammar the registry follows does not.
|
||||
for (String tag : new String[] {".v1", "-v1", "t".repeat(129), "t".repeat(300)}) {
|
||||
putTag(tag).statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", containsString("Floci's backing registry cannot hold the tag"));
|
||||
}
|
||||
}
|
||||
|
||||
private static ValidatableResponse putTag(String tag) {
|
||||
return call("PutImage", "{\"repositoryName\":\"" + REPO + "\",\"imageManifest\":\"{}\","
|
||||
+ "\"imageManifestMediaType\":\"" + OCI_MANIFEST + "\",\"imageTag\":\"" + tag + "\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void layerDigestsAreChecked() {
|
||||
call("GetDownloadUrlForLayer", "{\"repositoryName\":\"" + REPO + "\",\"layerDigest\":\"not-a-digest\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("BatchCheckLayerAvailability", "{\"repositoryName\":\"" + REPO + "\",\"layerDigests\":[]}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("CompleteLayerUpload", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"layerDigests\":[]}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("CompleteLayerUpload", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"layerDigests\":[\"bad\"]}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
// An upload holds one layer: a second, different digest is refused, not ignored.
|
||||
call("CompleteLayerUpload", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"layerDigests\":[\"sha256:" + "a".repeat(64) + "\",\"sha256:" + "b".repeat(64) + "\"]}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownUploadIsNotFound() {
|
||||
call("UploadLayerPart", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"partFirstByte\":0,\"partLastByte\":0,\"layerPartBlob\":\"YQ==\"}")
|
||||
.statusCode(400).body("__type", equalTo("UploadNotFoundException"));
|
||||
call("CompleteLayerUpload", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"layerDigests\":[\"" + DIGEST + "\"]}")
|
||||
.statusCode(400).body("__type", equalTo("UploadNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadPartInputIsChecked() {
|
||||
call("UploadLayerPart", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"partFirstByte\":-1,\"partLastByte\":0,\"layerPartBlob\":\"YQ==\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("UploadLayerPart", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"partFirstByte\":0,\"partLastByte\":0,\"layerPartBlob\":\"%%%\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
call("UploadLayerPart", "{\"repositoryName\":\"" + REPO + "\",\"uploadId\":\"" + UPLOAD_ID
|
||||
+ "\",\"partFirstByte\":\"zero\",\"partLastByte\":0,\"layerPartBlob\":\"YQ==\"}")
|
||||
.statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", PREFIX + action)
|
||||
.contentType(CT)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package io.github.hectorvent.floci.services.ecr;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class EcrLayerUploadsTest {
|
||||
|
||||
private static final String SCOPE = "us-east-1::000000000000::app";
|
||||
private static final long MIB = 1024 * 1024;
|
||||
|
||||
@Test
|
||||
void aPartMustStartAtTheNextByteAndMatchItsRange() {
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(location -> { });
|
||||
EcrLayerUploads.Session session = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/u1"), "app");
|
||||
|
||||
assertDoesNotThrow(() -> check(session, 0, 9, 10));
|
||||
session.accept(10, "http://r/u2", Instant.now());
|
||||
|
||||
AwsException gap = assertThrows(AwsException.class, () -> check(session, 11, 20, 10));
|
||||
assertEquals("InvalidLayerPartException", gap.getErrorCode());
|
||||
assertEquals(9L, gap.getExtendedData().get("lastValidByteReceived"));
|
||||
assertEquals("app", gap.getExtendedData().get("repositoryName"));
|
||||
|
||||
assertEquals("InvalidLayerPartException",
|
||||
assertThrows(AwsException.class, () -> check(session, 0, 9, 10)).getErrorCode());
|
||||
assertEquals("InvalidLayerPartException",
|
||||
assertThrows(AwsException.class, () -> check(session, 10, 19, 9)).getErrorCode());
|
||||
assertEquals("InvalidLayerPartException",
|
||||
assertThrows(AwsException.class, () -> check(session, 10, 9, 0)).getErrorCode());
|
||||
assertDoesNotThrow(() -> check(session, 10, 19, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartOver20MiBIsRefused() {
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(location -> { });
|
||||
EcrLayerUploads.Session session = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/u"), "app");
|
||||
int tooBig = (int) (EcrLayerUploads.MAX_PART_SIZE + 1);
|
||||
|
||||
assertEquals("InvalidLayerPartException",
|
||||
assertThrows(AwsException.class, () -> check(session, 0, tooBig - 1, tooBig)).getErrorCode());
|
||||
int largest = (int) EcrLayerUploads.MAX_PART_SIZE;
|
||||
assertDoesNotThrow(() -> check(session, 0, largest - 1, largest));
|
||||
}
|
||||
|
||||
@Test
|
||||
void completionNeedsAPartAndEveryPartButTheLastAtLeast5MiB() {
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(location -> { });
|
||||
EcrLayerUploads.Session empty = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/a"), "app");
|
||||
assertEquals("EmptyUploadException",
|
||||
assertThrows(AwsException.class, () -> EcrLayerUploads.checkComplete(empty)).getErrorCode());
|
||||
|
||||
EcrLayerUploads.Session small = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/b"), "app");
|
||||
small.accept(5 * MIB - 1, "http://r/b2", Instant.now());
|
||||
small.accept(10, "http://r/b3", Instant.now());
|
||||
assertEquals("LayerPartTooSmallException",
|
||||
assertThrows(AwsException.class, () -> EcrLayerUploads.checkComplete(small)).getErrorCode());
|
||||
|
||||
EcrLayerUploads.Session ok = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/c"), "app");
|
||||
ok.accept(5 * MIB, "http://r/c2", Instant.now());
|
||||
ok.accept(10, "http://r/c3", Instant.now());
|
||||
assertDoesNotThrow(() -> EcrLayerUploads.checkComplete(ok));
|
||||
|
||||
EcrLayerUploads.Session single = uploads.require(SCOPE, uploads.open(SCOPE, "http://r/d"), "app");
|
||||
single.accept(10, "http://r/d2", Instant.now());
|
||||
assertDoesNotThrow(() -> EcrLayerUploads.checkComplete(single));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUploadBelongsToItsRepositoryAndEndsWhenClosed() {
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(location -> { });
|
||||
String id = uploads.open(SCOPE, "http://r/u");
|
||||
|
||||
assertEquals("UploadNotFoundException", assertThrows(AwsException.class,
|
||||
() -> uploads.require("us-east-1::000000000000::other", id, "other")).getErrorCode());
|
||||
assertEquals("UploadNotFoundException", assertThrows(AwsException.class,
|
||||
() -> uploads.require(SCOPE, "6a1f2b3c-0000-4000-8000-000000000000", "app")).getErrorCode());
|
||||
assertEquals("http://r/u", uploads.require(SCOPE, id, "app").location());
|
||||
|
||||
uploads.close(id);
|
||||
assertEquals("UploadNotFoundException",
|
||||
assertThrows(AwsException.class, () -> uploads.require(SCOPE, id, "app")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUploadIdleForADayIsDroppedWhenTheNextOneOpens() {
|
||||
MutableClock clock = new MutableClock(Instant.parse("2026-10-15T00:00:00Z"));
|
||||
List<String> discarded = new ArrayList<>();
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(clock, discarded::add);
|
||||
String stale = uploads.open(SCOPE, "http://r/stale");
|
||||
String touched = uploads.open(SCOPE, "http://r/touched");
|
||||
|
||||
clock.advance(Duration.ofHours(23));
|
||||
uploads.require(SCOPE, touched, "app").accept(10, "http://r/touched2", clock.instant());
|
||||
clock.advance(Duration.ofHours(2));
|
||||
uploads.open(SCOPE, "http://r/new");
|
||||
|
||||
assertEquals("UploadNotFoundException",
|
||||
assertThrows(AwsException.class, () -> uploads.require(SCOPE, stale, "app")).getErrorCode());
|
||||
assertEquals("http://r/touched2", uploads.require(SCOPE, touched, "app").location());
|
||||
assertEquals(List.of("http://r/stale"), discarded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUploadIdleForADayIsRefusedEvenWhenNoOtherOpens() {
|
||||
MutableClock clock = new MutableClock(Instant.parse("2026-10-15T00:00:00Z"));
|
||||
List<String> discarded = new ArrayList<>();
|
||||
EcrLayerUploads uploads = new EcrLayerUploads(clock, discarded::add);
|
||||
String id = uploads.open(SCOPE, "http://r/idle");
|
||||
|
||||
clock.advance(Duration.ofHours(25));
|
||||
|
||||
assertEquals("UploadNotFoundException",
|
||||
assertThrows(AwsException.class, () -> uploads.require(SCOPE, id, "app")).getErrorCode());
|
||||
assertEquals(List.of("http://r/idle"), discarded);
|
||||
}
|
||||
|
||||
private static void check(EcrLayerUploads.Session session, long first, long last, int length) {
|
||||
EcrLayerUploads.checkPart(session, first, last, length, "000000000000", "app", "upload");
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
MutableClock(Instant now) {
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
void advance(Duration duration) {
|
||||
now = now.plus(duration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return now;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneOffset getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -902,6 +902,23 @@ class EcrServiceTest {
|
||||
assertEquals(1, service.describeRepositories(List.of(repositoryName), null, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImage_retagKeepsTheFirstPushTime() {
|
||||
InMemoryStorage<String, ImageMetadata> metaStore = new InMemoryStorage<>();
|
||||
EcrService withMeta = new EcrService(new InMemoryStorage<>(), metaStore, pullThroughCacheRuleStore,
|
||||
registryManager, Mockito.mock(EmulatorConfig.class), new RegionResolver(REGION, ACCOUNT));
|
||||
when(registryManager.httpClient()).thenReturn(Mockito.mock(RegistryHttpClient.class));
|
||||
withMeta.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
String manifest = "{\"schemaVersion\":2,\"mediaType\":\"application/vnd.docker.distribution.manifest.v2+json\"}";
|
||||
|
||||
withMeta.putImage(REPO, manifest, null, "v1", null, null, REGION);
|
||||
Instant firstPush = metaStore.scan(k -> true).get(0).getPushedAt();
|
||||
withMeta.putImage(REPO, manifest, null, "release", null, null, REGION);
|
||||
|
||||
assertEquals(1, metaStore.scan(k -> true).size());
|
||||
assertEquals(firstPush, metaStore.scan(k -> true).get(0).getPushedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImageTagMutability_roundTrips() {
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
|
||||
+8
@@ -25,6 +25,8 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -36,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Unit tests for routing AWS-shaped ECR repository URIs through Floci's data plane. */
|
||||
@@ -563,6 +566,11 @@ class EcrRegistryDataPlaneTest {
|
||||
.thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));
|
||||
when(ecrService.isImageTagImmutable("platform/api", "000000000000", "us-east-1"))
|
||||
.thenReturn(immutableTags);
|
||||
// The tag lock lives in EcrService, so the mock holds a real one.
|
||||
Set<String> heldTags = ConcurrentHashMap.newKeySet();
|
||||
when(ecrService.claimImmutableTag(anyString())).thenAnswer(call -> heldTags.add(call.getArgument(0)));
|
||||
Mockito.doAnswer(call -> heldTags.remove(call.getArgument(0)))
|
||||
.when(ecrService).releaseImmutableTag(anyString());
|
||||
when(ecrService.registryRepositoryName("platform/api", "000000000000", "us-east-1"))
|
||||
.thenReturn("legacy/platform-api");
|
||||
|
||||
|
||||
Reference in new issue
Block a user