mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecr): scope the registry data plane to each account and answer NAME_UNKNOWN (#9171)
The registry data plane and the catalog reconcile run outside any request, so the account-aware repository store read and wrote them as the default account. A repository another account created was not found: its IMMUTABLE tags were not enforced, and the reconcile recreated it in the default account's partition. The data plane's lookups now read the repository in the account its registry host names, and the reconcile reads and writes each entry in the account it belongs to, the configured default account for a pre-proxy namespace even when a request of another account started the registry. A push or pull for a repository nobody created fell back to the default namespace, so registry:2 stored it and the next start adopted it. Once the catalog has been read, such a name now answers 404 NAME_UNKNOWN before any byte reaches the registry, once it has been checked against the registry running now: a recovered registry's catalog is read again. Until then it answers unavailable, since its images may be in the registry: the start's catalog read is strict now, so a failed read no longer counts as an empty catalog, and the data plane retries it, at most every 30 seconds. A client that leaves while the catalog is read gives its write admission back at once, and a lookup that fails after the read is answered with a 500 rather than left waiting. The EKS registry-hosts and ECR TLS data-plane tests create their repository before pushing. Closes #6101 Closes #6140 Co-authored-by: Yi-111-a <153097222+Yi-111-a@users.noreply.github.com>
This commit is contained in:
1 parent
a966242daf
commit
d8809f6f0e
11 files changed
+676
-47
No files matched your search
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.config;
|
||||
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -37,6 +38,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@TestProfile(SelfSignedTlsProfile.class)
|
||||
class EcrTlsDataPlaneDockerIntegrationTest {
|
||||
|
||||
private static final String ECR = "AmazonEC2ContainerRegistry_V20150921";
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int sslPort;
|
||||
|
||||
@@ -49,6 +52,7 @@ class EcrTlsDataPlaneDockerIntegrationTest {
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.ecr.registry-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,7 +72,10 @@ class EcrTlsDataPlaneDockerIntegrationTest {
|
||||
assertEquals(200, pingResponse.statusCode());
|
||||
assertEquals("registry/2.0", pingResponse.header("Docker-Distribution-Api-Version"));
|
||||
|
||||
// 2. Upload layer blob over TLS
|
||||
// 2. Create the repository, as ECR answers a push to one nobody created with NAME_UNKNOWN, then
|
||||
// upload the layer blob over TLS
|
||||
RestAssuredJsonUtils.awsAction(ECR, "CreateRepository", "{\"repositoryName\":\"tls-repo\"}")
|
||||
.then().statusCode(200);
|
||||
byte[] layerBytes = "floci-ecr-tls-layer-content-v1".getBytes(StandardCharsets.UTF_8);
|
||||
String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
|
||||
|
||||
@@ -169,6 +176,8 @@ class EcrTlsDataPlaneDockerIntegrationTest {
|
||||
SimpleResponse deleteManifest = execute(tlsClient, HttpMethod.DELETE, sslPort, tlsHost,
|
||||
"/v2/tls-repo/manifests/" + manifestDigest, null, null, null);
|
||||
assertEquals(202, deleteManifest.statusCode());
|
||||
RestAssuredJsonUtils.awsAction(ECR, "DeleteRepository", "{\"repositoryName\":\"tls-repo\",\"force\":true}")
|
||||
.then().statusCode(200);
|
||||
} finally {
|
||||
tlsClient.close();
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
@@ -37,6 +38,7 @@ 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;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Pushes an image through the ECR API alone, as SDK-based copy tools do: a layer uploaded in parts,
|
||||
@@ -53,6 +55,7 @@ class EcrImagePushApiDockerIntegrationTest {
|
||||
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 static final String OTHER_ACCOUNT = "111111111111";
|
||||
|
||||
private final String repo = "push-api/" + UUID.randomUUID().toString().substring(0, 8);
|
||||
private final String immutableRepo = repo + "-immutable";
|
||||
@@ -338,29 +341,88 @@ class EcrImagePushApiDockerIntegrationTest {
|
||||
call("DeleteRepository", "{\"repositoryName\":\"" + untaggedRepo + "\"}").statusCode(200);
|
||||
}
|
||||
|
||||
/** Last, since every class on this profile shares one registry. */
|
||||
@Test
|
||||
@Order(12)
|
||||
void aRepositoryOfAnotherAccountTakesPushesAtItsOwnRegistryAndKeepsItsTagsImmutable() throws Exception {
|
||||
String otherRepo = repo + "-other-account";
|
||||
callAs(OTHER_ACCOUNT, "CreateRepository", "{\"repositoryName\":\"" + otherRepo
|
||||
+ "\",\"imageTagMutability\":\"IMMUTABLE\"}").statusCode(200);
|
||||
try {
|
||||
String upload = initiate(OTHER_ACCOUNT, otherRepo);
|
||||
part(OTHER_ACCOUNT, otherRepo, upload, 0, config).statusCode(200);
|
||||
complete(OTHER_ACCOUNT, otherRepo, upload, configDigest).statusCode(200);
|
||||
String first = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "%s",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": %d, "digest": "%s"},
|
||||
"layers": []
|
||||
}""".formatted(DOCKER_MANIFEST, config.length, configDigest);
|
||||
String host = OTHER_ACCOUNT + ".dkr.ecr.us-east-1.localhost";
|
||||
String path = "/v2/" + otherRepo + "/manifests/v1";
|
||||
|
||||
assertEquals(201, registryRequest(host, path, HttpMethod.PUT, null, first).statusCode());
|
||||
Fetched rewritten = registryRequest(host, path, HttpMethod.PUT, null, first.replace("[]", "[ ]"));
|
||||
|
||||
assertEquals(400, rewritten.statusCode());
|
||||
assertTrue(rewritten.body().toString().contains("TAG_INVALID"), rewritten.body().toString());
|
||||
} finally {
|
||||
callAs(OTHER_ACCOUNT, "DeleteRepository", "{\"repositoryName\":\"" + otherRepo + "\",\"force\":true}")
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void aRepositoryNobodyCreatedIsUnknownToTheRegistry() throws Exception {
|
||||
String host = "000000000000.dkr.ecr.us-east-1.localhost";
|
||||
String path = "/v2/" + repo + "-never-created/manifests/1";
|
||||
|
||||
Fetched pulled = registryGet(host, path, DOCKER_MANIFEST);
|
||||
Fetched pushed = registryRequest(host, path, HttpMethod.PUT, null, manifest);
|
||||
|
||||
assertEquals(404, pulled.statusCode());
|
||||
assertTrue(pulled.body().toString().contains("NAME_UNKNOWN"), pulled.body().toString());
|
||||
assertEquals(404, pushed.statusCode());
|
||||
assertTrue(pushed.body().toString().contains("NAME_UNKNOWN"), pushed.body().toString());
|
||||
}
|
||||
|
||||
/** Last, since every class on this profile shares one registry. */
|
||||
@Test
|
||||
@Order(14)
|
||||
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 + "\"}")
|
||||
return initiate(null, repository);
|
||||
}
|
||||
|
||||
private String initiate(String account, String repository) {
|
||||
return callAs(account, "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
|
||||
return part(null, repository, uploadId, first, bytes);
|
||||
}
|
||||
|
||||
private static ValidatableResponse part(String account, String repository, String uploadId, long first,
|
||||
byte[] bytes) {
|
||||
return callAs(account, "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
|
||||
return complete(null, repository, uploadId, digest);
|
||||
}
|
||||
|
||||
private static ValidatableResponse complete(String account, String repository, String uploadId, String digest) {
|
||||
return callAs(account, "CompleteLayerUpload", "{\"repositoryName\":\"" + repository + "\",\"uploadId\":\"" + uploadId
|
||||
+ "\",\"layerDigests\":[\"" + digest + "\"]}");
|
||||
}
|
||||
|
||||
@@ -404,13 +466,20 @@ class EcrImagePushApiDockerIntegrationTest {
|
||||
private record Fetched(int statusCode, String digest, Buffer body) {}
|
||||
|
||||
private static ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
return callAs(null, action, body);
|
||||
}
|
||||
|
||||
/** A call as {@code account}, which a 12-digit access key selects, or as the default account when null. */
|
||||
private static ValidatableResponse callAs(String account, String action, String body) {
|
||||
RequestSpecification request = given()
|
||||
.header("X-Amz-Target", PREFIX + action)
|
||||
.contentType(CT)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
.body(body);
|
||||
if (account != null) {
|
||||
request.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20261121/us-east-1/ecr/aws4_request");
|
||||
}
|
||||
return request.when().post("/").then();
|
||||
}
|
||||
|
||||
private static byte[] randomBytes(int size) {
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package io.floci.aws.services.ecr;
|
||||
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
@@ -12,6 +17,7 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
@@ -35,6 +41,15 @@ class EcrIntegrationTest {
|
||||
private static final String WEST_REGION = "us-west-2";
|
||||
private static final String WEST_CREDENTIAL =
|
||||
"AWS4-HMAC-SHA256 Credential=000000000000/20260923/" + WEST_REGION + "/ecr/aws4_request";
|
||||
private static final String OTHER_ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT_CREDENTIAL =
|
||||
"AWS4-HMAC-SHA256 Credential=" + OTHER_ACCOUNT + "/20260923/us-east-1/ecr/aws4_request";
|
||||
|
||||
@Inject
|
||||
EcrService ecrService;
|
||||
|
||||
@Inject
|
||||
EcrRegistryManager registryManager;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -518,4 +533,49 @@ class EcrIntegrationTest {
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("PullThroughCacheRuleNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(17)
|
||||
void theCatalogReconcileGivesAPreProxyNamespaceToTheDefaultAccountWhicheverRequestStartedTheRegistry() {
|
||||
String legacy = "legacy-reconcile/service";
|
||||
|
||||
// The reconcile runs inside the request that started the registry, here one of account 111111111111.
|
||||
// The earlier tests' last delete stopped the registry, and a catalog is only ever read from a running one.
|
||||
RequestScopes.runAs(OTHER_ACCOUNT, () -> {
|
||||
registryManager.tryEnsureStarted();
|
||||
ecrService.reconcileFromCatalog(List.of(legacy));
|
||||
});
|
||||
|
||||
describeRepository(legacy, null)
|
||||
.statusCode(200)
|
||||
.body("repositories[0].registryId", equalTo("000000000000"));
|
||||
describeRepository(legacy, OTHER_ACCOUNT_CREDENTIAL)
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("RepositoryNotFoundException"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", PREFIX + "DeleteRepository")
|
||||
.contentType(CT)
|
||||
.body("""
|
||||
{ "repositoryName": "%s", "force": true }
|
||||
""".formatted(legacy))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** DescribeRepositories for one name, as the account {@code authorization} names, or the default one when null. */
|
||||
private static ValidatableResponse describeRepository(String name, String authorization) {
|
||||
RequestSpecification request = given()
|
||||
.header("X-Amz-Target", PREFIX + "DescribeRepositories")
|
||||
.contentType(CT)
|
||||
.body("""
|
||||
{ "repositoryNames": ["%s"] }
|
||||
""".formatted(name));
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
return request.when().post("/").then();
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ class EcrServiceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REPO = "floci-it/svc-test";
|
||||
private static final String OTHER_ACCOUNT = "111111111111";
|
||||
|
||||
private EcrService service;
|
||||
private EcrRegistryManager registryManager;
|
||||
@@ -395,6 +396,54 @@ class EcrServiceTest {
|
||||
assertThrows(AwsException.class, () -> service.describeRepositories(List.of("legacy"), null, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDataPlaneReadsARepositoryInTheAccountItsRegistryHostNames() {
|
||||
AccountAwareStorageBackend<Repository> repositories = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
EcrService accountAware = accountAwareService(repositories, new RegionResolver(REGION, ACCOUNT));
|
||||
// Where account 111111111111's own CreateRepository keeps it: in that account's partition.
|
||||
repositories.putForAccount(OTHER_ACCOUNT, REGION + "::" + OTHER_ACCOUNT + "::app",
|
||||
repository("app", OTHER_ACCOUNT, "IMMUTABLE"));
|
||||
|
||||
assertTrue(accountAware.isImageTagImmutable("app", OTHER_ACCOUNT, REGION));
|
||||
assertEquals(OTHER_ACCOUNT + "/" + REGION + "/app",
|
||||
accountAware.registryRepositoryName("app", OTHER_ACCOUNT, REGION));
|
||||
assertFalse(accountAware.isImageTagImmutable("app", ACCOUNT, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNameNobodyCreatedIsUnknownOnceTheCatalogIsReadAndUnavailableBefore() {
|
||||
when(registryManager.isCatalogReconciled()).thenReturn(false);
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> service.registryRepositoryName("never-created", ACCOUNT, REGION));
|
||||
|
||||
when(registryManager.isCatalogReconciled()).thenReturn(true);
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> service.registryRepositoryName("never-created", ACCOUNT, REGION));
|
||||
|
||||
assertEquals("RepositoryNotFoundException", missing.getErrorCode());
|
||||
assertEquals("The repository with name 'never-created' does not exist in the registry with id '"
|
||||
+ ACCOUNT + "'", missing.getMessage());
|
||||
verify(registryManager, never()).internalRepoName(anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCatalogReconcileKeepsANamespacedRepositoryInItsOwnAccount() {
|
||||
AccountAwareStorageBackend<Repository> repositories = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
EcrService accountAware = accountAwareService(repositories, new RegionResolver(REGION, ACCOUNT));
|
||||
String keptKey = REGION + "::" + OTHER_ACCOUNT + "::kept";
|
||||
repositories.putForAccount(OTHER_ACCOUNT, keptKey, repository("kept", OTHER_ACCOUNT, "IMMUTABLE"));
|
||||
|
||||
accountAware.reconcileFromCatalog(List.of(
|
||||
OTHER_ACCOUNT + "/" + REGION + "/kept", OTHER_ACCOUNT + "/" + REGION + "/recovered"));
|
||||
|
||||
assertEquals("IMMUTABLE", repositories.getForAccount(OTHER_ACCOUNT, keptKey).orElseThrow()
|
||||
.getImageTagMutability());
|
||||
assertEquals(OTHER_ACCOUNT, repositories.getForAccount(OTHER_ACCOUNT, REGION + "::" + OTHER_ACCOUNT
|
||||
+ "::recovered").orElseThrow().getRegistryId());
|
||||
assertTrue(repositories.scanAllAccountEntries(key -> true).stream()
|
||||
.allMatch(entry -> OTHER_ACCOUNT.equals(entry.accountId())));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// Registry unavailable (Floci inside Docker with no Docker daemon)
|
||||
// ------------------------------------------------------------
|
||||
@@ -663,13 +712,7 @@ class EcrServiceTest {
|
||||
@Test
|
||||
void deleteRepository_keepsSharedStorageForRepositoriesOwnedByAnotherAccount() {
|
||||
AccountAwareStorageBackend<Repository> repositories = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
EcrService accountAwareService = new EcrService(
|
||||
repositories,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
registryManager,
|
||||
Mockito.mock(EmulatorConfig.class),
|
||||
new RegionResolver(REGION, ACCOUNT));
|
||||
EcrService accountAwareService = accountAwareService(repositories, new RegionResolver(REGION, ACCOUNT));
|
||||
accountAwareService.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
repositories.putForAccount("111111111111", REGION + "::111111111111::other", new Repository());
|
||||
|
||||
@@ -1606,6 +1649,20 @@ class EcrServiceTest {
|
||||
assertEquals("yes", existing.getTags().get("preserved"));
|
||||
}
|
||||
|
||||
private EcrService accountAwareService(AccountAwareStorageBackend<Repository> repositories,
|
||||
RegionResolver regionResolver) {
|
||||
return new EcrService(repositories, new InMemoryStorage<>(), new InMemoryStorage<>(), registryManager,
|
||||
Mockito.mock(EmulatorConfig.class), regionResolver);
|
||||
}
|
||||
|
||||
private static Repository repository(String name, String account, String imageTagMutability) {
|
||||
Repository repository = new Repository();
|
||||
repository.setRepositoryName(name);
|
||||
repository.setRegistryId(account);
|
||||
repository.setImageTagMutability(imageTagMutability);
|
||||
return repository;
|
||||
}
|
||||
|
||||
private static final class FakeRegistryServer implements AutoCloseable {
|
||||
private final HttpServer server;
|
||||
private final String repository;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.ecr.registry;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.ecr.EcrService;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
import io.vertx.core.Context;
|
||||
@@ -26,6 +27,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -871,6 +873,171 @@ class EcrRegistryDataPlaneTest {
|
||||
assertTrue(response.body().isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"GET, /v2/never-created/manifests/1",
|
||||
"HEAD, /v2/never-created/manifests/1",
|
||||
"PUT, /v2/never-created/manifests/1",
|
||||
"POST, /v2/never-created/blobs/uploads/"
|
||||
})
|
||||
void aRepositoryNobodyCreatedIsUnknownBeforeAnyByteReachesTheRegistry(String method, String path)
|
||||
throws Exception {
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(ecrService.registryRepositoryName("never-created", "000000000000", "us-east-1"))
|
||||
.thenThrow(new AwsException("RepositoryNotFoundException",
|
||||
"The repository with name 'never-created' does not exist in the registry with id '000000000000'",
|
||||
400));
|
||||
|
||||
RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.valueOf(method), path);
|
||||
|
||||
// The name is refused only once the registry running now has had its catalog read.
|
||||
InOrder order = Mockito.inOrder(manager);
|
||||
order.verify(manager).ensureStarted();
|
||||
order.verify(manager).ensureCatalogReconciled();
|
||||
assertEquals(404, response.status());
|
||||
assertEquals("application/json", response.contentType());
|
||||
assertEquals("registry/2.0", response.apiVersion());
|
||||
if (!"HEAD".equals(method)) {
|
||||
JsonObject error = new JsonObject(response.body()).getJsonArray("errors").getJsonObject(0);
|
||||
assertEquals("NAME_UNKNOWN", error.getString("code"));
|
||||
assertEquals("The repository with name 'never-created' does not exist in the registry with id "
|
||||
+ "'000000000000'", error.getString("message"));
|
||||
}
|
||||
Mockito.verify(manager, Mockito.never()).httpClient();
|
||||
if ("PUT".equals(method) || "POST".equals(method)) {
|
||||
Mockito.verify(manager).releaseWriteAdmission();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestBeforeTheCatalogIsReadStartsTheRegistryAndReadsItFirst() throws Exception {
|
||||
HttpServer registry = vertx.createHttpServer().requestHandler(request -> request.response()
|
||||
.setStatusCode(200).putHeader("Content-Type", "application/json").end("{}"))
|
||||
.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
when(manager.httpClient()).thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(manager.isCatalogReconciled()).thenReturn(false);
|
||||
try {
|
||||
RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.GET,
|
||||
"/v2/platform/api/manifests/latest");
|
||||
|
||||
assertEquals(200, response.status());
|
||||
InOrder order = Mockito.inOrder(manager, ecrService);
|
||||
order.verify(manager).ensureStarted();
|
||||
order.verify(manager).ensureCatalogReconciled();
|
||||
order.verify(ecrService).registryRepositoryName("platform/api", "000000000000", "us-east-1");
|
||||
} finally {
|
||||
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"GET", "PUT"})
|
||||
void aNameTheUnreadCatalogCannotPlaceIsUnavailableRatherThanUnknown(String method) throws Exception {
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(manager.isCatalogReconciled()).thenReturn(false);
|
||||
when(ecrService.registryRepositoryName("held", "000000000000", "us-east-1"))
|
||||
.thenThrow(new IllegalStateException("The ECR registry catalog has not been read yet"));
|
||||
|
||||
RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.valueOf(method),
|
||||
"/v2/held/manifests/1");
|
||||
|
||||
assertEquals(503, response.status());
|
||||
assertEquals("registry/2.0", response.apiVersion());
|
||||
assertEquals("UNAVAILABLE",
|
||||
new JsonObject(response.body()).getJsonArray("errors").getJsonObject(0).getString("code"));
|
||||
Mockito.verify(manager, Mockito.never()).httpClient();
|
||||
if ("PUT".equals(method)) {
|
||||
Mockito.verify(manager).releaseWriteAdmission();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNameTheEarlierCatalogMissedIsPlacedByTheRecoveredRegistrysCatalog() throws Exception {
|
||||
HttpServer registry = vertx.createHttpServer().requestHandler(request -> request.response()
|
||||
.setStatusCode(200).putHeader("Content-Type", "application/json").end("{}"))
|
||||
.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
when(manager.httpClient()).thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(ecrService.registryRepositoryName("restored", "000000000000", "us-east-1"))
|
||||
.thenThrow(new AwsException("RepositoryNotFoundException",
|
||||
"The repository with name 'restored' does not exist in the registry with id '000000000000'",
|
||||
400))
|
||||
.thenReturn("restored");
|
||||
try {
|
||||
RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.GET, "/v2/restored/manifests/1");
|
||||
|
||||
assertEquals(200, response.status());
|
||||
InOrder order = Mockito.inOrder(manager, ecrService);
|
||||
order.verify(ecrService).registryRepositoryName("restored", "000000000000", "us-east-1");
|
||||
order.verify(manager).ensureStarted();
|
||||
order.verify(manager).ensureCatalogReconciled();
|
||||
order.verify(ecrService).registryRepositoryName("restored", "000000000000", "us-east-1");
|
||||
} finally {
|
||||
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClientLeavingWhileTheCatalogIsReadGivesItsWriteAdmissionBackAtOnce() throws Exception {
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(manager.isCatalogReconciled()).thenReturn(false);
|
||||
CountDownLatch readStarted = new CountDownLatch(1);
|
||||
CountDownLatch finishRead = new CountDownLatch(1);
|
||||
Mockito.doAnswer(call -> {
|
||||
readStarted.countDown();
|
||||
finishRead.await(5, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).when(manager).ensureCatalogReconciled();
|
||||
CountDownLatch released = new CountDownLatch(1);
|
||||
Mockito.doAnswer(call -> {
|
||||
released.countDown();
|
||||
return null;
|
||||
}).when(manager).releaseWriteAdmission();
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
try {
|
||||
HttpClientRequest upload = client.request(new RequestOptions().setHost("127.0.0.1")
|
||||
.setPort(dataPlane.actualPort()).setMethod(HttpMethod.POST)
|
||||
.setURI("/v2/platform/api/blobs/uploads/"))
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
upload.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566");
|
||||
upload.setChunked(true);
|
||||
upload.write("partial");
|
||||
assertTrue(readStarted.await(5, TimeUnit.SECONDS), "the upload waits for the catalog read");
|
||||
|
||||
upload.connection().close();
|
||||
|
||||
assertTrue(released.await(2, TimeUnit.SECONDS),
|
||||
"the admission comes back while the catalog read is still blocked");
|
||||
} finally {
|
||||
finishRead.countDown();
|
||||
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLookupFailingAfterTheCatalogReadIsAnsweredRatherThanLeftWaiting() throws Exception {
|
||||
EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);
|
||||
HttpServer dataPlane = dataPlane(manager, false, null);
|
||||
when(manager.isCatalogReconciled()).thenReturn(false);
|
||||
when(ecrService.isImageTagImmutable("platform/api", "000000000000", "us-east-1"))
|
||||
.thenThrow(new IllegalStateException("metadata store unavailable"));
|
||||
|
||||
RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.PUT, "/v2/platform/api/manifests/v1");
|
||||
|
||||
assertEquals(500, response.status());
|
||||
Mockito.verify(manager).releaseWriteAdmission();
|
||||
Mockito.verify(manager, Mockito.never()).httpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
void upstreamErrorResponsesPassThroughUnchanged() throws Exception {
|
||||
HttpServer registry = vertx.createHttpServer().requestHandler(request -> request.response()
|
||||
@@ -1012,6 +1179,8 @@ class EcrRegistryDataPlaneTest {
|
||||
}).when(ecrService).unlockRepositoryWrites(anyString());
|
||||
when(ecrService.registryRepositoryName("platform/api", "000000000000", "us-east-1"))
|
||||
.thenReturn("legacy/platform-api");
|
||||
// The steady state: the registry's catalog has been read since it started.
|
||||
when(registryManager.isCatalogReconciled()).thenReturn(true);
|
||||
|
||||
Router router = Router.router(vertx);
|
||||
new EcrRegistryDataPlane(registryManager, ecrService, config, vertx).register(router);
|
||||
|
||||
@@ -42,6 +42,7 @@ import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -201,7 +202,7 @@ class EcrRegistryManagerTest {
|
||||
List<String> events = new ArrayList<>();
|
||||
RegistryHttpClient client = Mockito.mock(RegistryHttpClient.class);
|
||||
when(client.baseUrl()).thenReturn("http://localhost:" + BASE_PORT);
|
||||
when(client.catalog()).thenAnswer(invocation -> {
|
||||
when(client.catalogStrict()).thenAnswer(invocation -> {
|
||||
events.add("catalog");
|
||||
return List.of("repository");
|
||||
});
|
||||
@@ -222,6 +223,92 @@ class EcrRegistryManagerTest {
|
||||
assertEquals(List.of("healthy", "catalog", "reconciled"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCatalogTheRegistryFailedToGiveIsReadAgainRatherThanTakenAsEmpty() throws Exception {
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(
|
||||
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
|
||||
RegistryHttpClient client = registryClient();
|
||||
when(client.catalogStrict())
|
||||
.thenThrow(new IOException("Registry catalog returned 500"))
|
||||
.thenReturn(List.of("legacy/service"));
|
||||
List<List<String>> reconciled = new ArrayList<>();
|
||||
manager.setReconcileHook(reconciled::add);
|
||||
|
||||
manager.ensureStarted();
|
||||
|
||||
assertFalse(manager.isCatalogReconciled());
|
||||
assertTrue(reconciled.isEmpty());
|
||||
|
||||
manager.ensureCatalogReconciled();
|
||||
manager.ensureCatalogReconciled();
|
||||
|
||||
assertTrue(manager.isCatalogReconciled());
|
||||
assertEquals(List.of(List.of("legacy/service")), reconciled);
|
||||
verify(client, times(2)).catalogStrict();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedCatalogRetryWaitsBeforeTheNextRead() throws Exception {
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(
|
||||
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
|
||||
ManualClock clock = new ManualClock(Instant.parse("2026-11-21T00:00:00Z"));
|
||||
manager.setClock(clock);
|
||||
RegistryHttpClient client = registryClient();
|
||||
when(client.catalogStrict()).thenThrow(new IOException("Registry catalog returned 500"));
|
||||
manager.setReconcileHook(repositories -> { });
|
||||
|
||||
manager.ensureStarted();
|
||||
manager.ensureCatalogReconciled();
|
||||
clock.advance(Duration.ofMillis(EcrRegistryManager.RECONCILE_RETRY_MILLIS - 1));
|
||||
manager.ensureCatalogReconciled();
|
||||
|
||||
verify(client, times(2)).catalogStrict();
|
||||
|
||||
clock.advance(Duration.ofMillis(1));
|
||||
manager.ensureCatalogReconciled();
|
||||
|
||||
verify(client, times(3)).catalogStrict();
|
||||
assertFalse(manager.isCatalogReconciled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCatalogRetryWaitsForTheRegistryToStart() throws Exception {
|
||||
RegistryHttpClient client = registryClient();
|
||||
manager.setReconcileHook(repositories -> { });
|
||||
|
||||
manager.ensureCatalogReconciled();
|
||||
|
||||
verify(client, never()).catalogStrict();
|
||||
assertFalse(manager.isCatalogReconciled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecoveredRegistryHasItsCatalogReadAgain() throws Exception {
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo("first-container", Map.of()))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo("second-container", Map.of()));
|
||||
RegistryHttpClient client = registryClient();
|
||||
when(client.catalogStrict()).thenReturn(List.of()).thenReturn(List.of("restored/service"));
|
||||
List<List<String>> reconciled = new ArrayList<>();
|
||||
manager.setReconcileHook(reconciled::add);
|
||||
|
||||
manager.ensureStarted();
|
||||
when(lifecycleManager.presenceOf("first-container")).thenReturn(ContainerPresence.ABSENT);
|
||||
manager.ensureStarted();
|
||||
|
||||
assertTrue(manager.isCatalogReconciled());
|
||||
assertEquals(List.of(List.of(), List.of("restored/service")), reconciled);
|
||||
}
|
||||
|
||||
/** A registry client the manager uses in place of HTTP, answering the health check at once. */
|
||||
private RegistryHttpClient registryClient() {
|
||||
RegistryHttpClient client = Mockito.mock(RegistryHttpClient.class);
|
||||
when(client.baseUrl()).thenReturn("http://localhost:" + BASE_PORT);
|
||||
manager = Mockito.spy(manager);
|
||||
Mockito.doReturn(client).when(manager).httpClient();
|
||||
return client;
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedLabelsContainerWithResourceIdentity() {
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RdsMockProfile;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -68,6 +69,9 @@ class EksRegistryHostsDockerIntegrationTest {
|
||||
private static final Logger LOG = Logger.getLogger(EksRegistryHostsDockerIntegrationTest.class);
|
||||
private static final String JSON = "application/json";
|
||||
private static final String POD = "registry-hosts-pod";
|
||||
// Not "000000000000": the generated ECR mirror only covers the default account, so this account's
|
||||
// registry host is only reachable at all because of the registry-hosts configuration below.
|
||||
private static final String IMAGE_ACCOUNT = "111122223333";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
@@ -105,11 +109,14 @@ class EksRegistryHostsDockerIntegrationTest {
|
||||
String clusterName = "reg-hosts-dock-" + suffix;
|
||||
String nodegroupName = "ng-" + suffix;
|
||||
String repo = "reg-hosts-it-" + suffix;
|
||||
// Not "000000000000": the generated ECR mirror only covers the default account, so this
|
||||
// hostname is only reachable at all because of the registry-hosts configuration below.
|
||||
String host = "111122223333.dkr.ecr.us-east-1.localhost:" + httpPort;
|
||||
String host = IMAGE_ACCOUNT + ".dkr.ecr.us-east-1.localhost:" + httpPort;
|
||||
String imageRef = host + "/" + repo + ":v1";
|
||||
|
||||
// ECR answers a push to a repository nobody created with NAME_UNKNOWN, so the account creates it first.
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
ecrAsImageAccount("CreateRepository", "{\"repositoryName\":\"" + repo + "\"}");
|
||||
cleanup.register(() -> ecrAsImageAccount("DeleteRepository",
|
||||
"{\"repositoryName\":\"" + repo + "\",\"force\":true}"));
|
||||
pushMinimalImage(host, repo);
|
||||
|
||||
given().contentType(JSON)
|
||||
@@ -415,6 +422,16 @@ class EksRegistryHostsDockerIntegrationTest {
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
private static void ecrAsImageAccount(String action, String body) {
|
||||
given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + IMAGE_ACCOUNT
|
||||
+ "/20260923/us-east-1/ecr/aws4_request")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private void uploadBlob(String host, String repo, String digest, byte[] content) {
|
||||
String location = given().header("Host", host)
|
||||
.when().post("/v2/" + repo + "/blobs/uploads/")
|
||||
|
||||
Reference in new issue
Block a user