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
@@ -104,8 +104,9 @@ is refused with the model's message, as AWS does. `imageStatus` and `DescribeIma
|
||||
- The scanning configuration is `BASIC` with no rules until one is put. `CONTINUOUS_SCAN` is refused with `BASIC`, since AWS offers it only with enhanced scanning. `BatchGetRepositoryScanningConfiguration` still reports each repository's own `scanOnPush`. Missing repository names appear in `failures` with `REPOSITORY_NOT_FOUND`, alongside configurations for the names that exist.
|
||||
- **Repository creation templates.** Templates are kept per account and Region, keyed by `prefix` (`ROOT` included). A new template defaults to `AES256` encryption and `MUTABLE` tags. `UpdateRepositoryCreationTemplate` replaces each field the request sets, an empty string or list clears it, and fields left out are kept. The exclusion filters are the exception: the model requires at least one, so `[]` is refused. Instead, an update that leaves the template in a mode without exclusions (`MUTABLE` or `IMMUTABLE`) drops the filters, which is what Terraform relies on, since it leaves the member out when the filters are removed. `DescribeRepositoryCreationTemplates` leaves out a requested prefix with no template rather than failing. Requests are checked against the vendored ECR model constraints, as the registry settings are, with `InvalidParameterException`. On top of the model, `appliedFor` must name at least one value, and policy text must be a JSON object. Nothing in Floci creates repositories through replication, pull through cache or create-on-push, so templates are never applied.
|
||||
- **Manifest format negotiation.** `BatchGetImage` forwards the caller's `acceptedMediaTypes` as the upstream `Accept` header. Modern OCI manifests (`application/vnd.oci.image.manifest.v1+json`) and Docker v2 schema 2 are both supported.
|
||||
- **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `<account>/<region>/<repoName>`, so the same repository name in different accounts or regions cannot collide.
|
||||
- **Reconcile on first start.** When the registry container starts, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage. This means image bytes are never orphaned across restarts.
|
||||
- **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `<account>/<region>/<repoName>`, so the same repository name in different accounts or regions cannot collide. The data plane reads a repository in the account its registry host names, so a repository any account created takes pushes and pulls at `<account>.dkr.ecr.<region>...` with its own settings, `IMMUTABLE` tags included.
|
||||
- **Unknown repositories.** A push or pull for a repository nobody created answers `404 NAME_UNKNOWN` (`The repository with name '<name>' does not exist in the registry with id '<account>'`) before any byte reaches the registry, as ECR does, rather than storing the image.
|
||||
- **Reconcile on first start.** When the registry container starts, or is recovered after it stopped or disappeared, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage, in the account each namespace belongs to. This means image bytes are never orphaned across restarts. Until the catalog has been read, a name without metadata answers `503 UNAVAILABLE` rather than `NAME_UNKNOWN`, since its images may be in the registry; a read that failed is retried on the next push or pull, at most every 30 seconds.
|
||||
- **Upgrade from direct registry access.** Floci recreates an older backing container with the same volume and a loopback-only port binding. Repositories written through the former direct endpoint retain their physical paths and map to the default account and Region; their returned URI moves to port `4566`.
|
||||
- **Lambda, ECS and EMR Serverless integration.** Image-backed Lambda functions (`PackageType=Image`), ECS task containers and the custom images of EMR Serverless applications (in its `docker` runner mode) reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `<account>.dkr.ecr.<region>.amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:<flociPort>/<account>/<region>/<repo>`) in either URI style and with or without TLS, an address a Linux Docker daemon pulls from over plain HTTP. On Docker Desktop the rewrite is `<account>.dkr.ecr.<region>.localhost:<flociPort>/<repo>` instead: Desktop's daemon runs in a VM and dials `localhost` there, where a host port Docker chose for Floci is not bound, while it sends `*.localhost` through its host proxy to the port Floci publishes. Floci asks the daemon once whether it is Docker Desktop. CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. With `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set, the rewritten reference, and a loopback `repositoryUri` named directly, are still pulled from Floci's registry: the base goes in front of the images a mirror holds, never of one on `localhost`.
|
||||
- **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `<base>/<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`.
|
||||
|
||||
@@ -296,23 +296,27 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
* Recreates {@link Repository} metadata entries for registry namespaces found in the catalog.
|
||||
* Namespaces created by Floci are {@code <account>/<region>/<repoName>}; pre-proxy registry
|
||||
* namespaces are recovered for the default account and region without moving image storage.
|
||||
*
|
||||
* <p>The catalog is read when the registry starts, outside any request or inside the one that
|
||||
* happened to start it, so each entry is read and written in the account it belongs to: the
|
||||
* configured default account for a pre-proxy namespace, the account a namespaced one begins with.
|
||||
*/
|
||||
void reconcileFromCatalog(List<String> catalog) {
|
||||
if (catalog == null || catalog.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String defaultAccount = regionResolver.getDefaultAccountId();
|
||||
String defaultRegion = regionResolver.getDefaultRegion();
|
||||
int recreated = 0;
|
||||
for (String registryRepositoryName : catalog) {
|
||||
String defaultAccount = regionResolver.getAccountId();
|
||||
String defaultRegion = regionResolver.getDefaultRegion();
|
||||
String legacyKey = key(defaultRegion, defaultAccount, registryRepositoryName);
|
||||
Optional<Repository> legacyRepository = repoStore.get(legacyKey);
|
||||
Optional<Repository> legacyRepository = repositoryInAccount(defaultAccount, legacyKey);
|
||||
if (legacyRepository.isPresent()) {
|
||||
Repository repo = legacyRepository.get();
|
||||
repo.setRepositoryUri(registryManager.getRepositoryUri(
|
||||
defaultAccount, defaultRegion, repo.getRepositoryName()));
|
||||
repo.setRegistryRepositoryName(registryRepositoryName);
|
||||
repoStore.put(legacyKey, repo);
|
||||
AccountAwareStorageBackend.putInAccount(repoStore, defaultAccount, legacyKey, repo);
|
||||
continue;
|
||||
}
|
||||
String[] parts = registryRepositoryName.split("/", 3);
|
||||
@@ -322,14 +326,14 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
String region = namespaced ? parts[1] : defaultRegion;
|
||||
String repoName = namespaced ? parts[2] : registryRepositoryName;
|
||||
String key = key(region, account, repoName);
|
||||
Optional<Repository> existing = repoStore.get(key);
|
||||
Optional<Repository> existing = repositoryInAccount(account, key);
|
||||
if (existing.isPresent()) {
|
||||
Repository repo = existing.get();
|
||||
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
|
||||
if (!namespaced) {
|
||||
repo.setRegistryRepositoryName(registryRepositoryName);
|
||||
}
|
||||
repoStore.put(key, repo);
|
||||
AccountAwareStorageBackend.putInAccount(repoStore, account, key, repo);
|
||||
continue;
|
||||
}
|
||||
Repository repo = new Repository();
|
||||
@@ -341,7 +345,7 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
repo.setRegistryRepositoryName(registryRepositoryName);
|
||||
}
|
||||
repo.setCreatedAt(Instant.now());
|
||||
repoStore.put(key, repo);
|
||||
AccountAwareStorageBackend.putInAccount(repoStore, account, key, repo);
|
||||
recreated++;
|
||||
}
|
||||
if (recreated > 0) {
|
||||
@@ -349,6 +353,18 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository stored under {@code key} in {@code account}. An entry from before the store was kept by account
|
||||
* is the default account's, as the store reads it, and moves into that account when it asks.
|
||||
*/
|
||||
private Optional<Repository> repositoryInAccount(String account, String key) {
|
||||
if (repoStore instanceof AccountAwareStorageBackend<Repository> aware) {
|
||||
boolean ownsLegacyEntries = account.equals(regionResolver.getDefaultAccountId());
|
||||
return aware.getForAccountMigratingLegacy(account, key, repo -> ownsLegacyEntries);
|
||||
}
|
||||
return repoStore.get(key);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Repository creation templates
|
||||
// ============================================================
|
||||
@@ -1715,21 +1731,42 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
return repo;
|
||||
}
|
||||
|
||||
/** Returns whether the repository rejects a second manifest write for an existing tag. */
|
||||
/**
|
||||
* Returns whether the repository rejects a second manifest write for an existing tag. The registry data plane
|
||||
* asks outside any request, so the repository is read in the account its registry host names.
|
||||
*/
|
||||
public boolean isImageTagImmutable(String repositoryName, String registryId, String region) {
|
||||
String account = effectiveAccount(registryId);
|
||||
return repoStore.get(key(region, account, repositoryName))
|
||||
return dataPlaneRepository(repositoryName, account, region)
|
||||
.map(Repository::getImageTagMutability)
|
||||
.filter("IMMUTABLE"::equals)
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
/** Returns the physical registry namespace selected for an ECR repository. */
|
||||
/**
|
||||
* Returns the physical registry namespace of an ECR repository, for the registry data plane, which asks outside
|
||||
* any request: the repository is read in the account its registry host names. A name with no repository is
|
||||
* refused as ECR refuses it, with {@code RepositoryNotFoundException} the data plane answers as
|
||||
* {@code NAME_UNKNOWN}, once the registry's catalog has been read into the metadata. Before that, a repository
|
||||
* whose images the registry holds may have no metadata yet, so the name is refused as unavailable rather than
|
||||
* as missing.
|
||||
*/
|
||||
public String registryRepositoryName(String repositoryName, String registryId, String region) {
|
||||
String account = effectiveAccount(registryId);
|
||||
return repoStore.get(key(region, account, repositoryName))
|
||||
return dataPlaneRepository(repositoryName, account, region)
|
||||
.map(repo -> registryRepositoryName(repo, region))
|
||||
.orElseGet(() -> registryManager.internalRepoName(account, region, repositoryName));
|
||||
.orElseThrow(() -> {
|
||||
if (!registryManager.isCatalogReconciled()) {
|
||||
return new IllegalStateException("The ECR registry catalog has not been read yet, so "
|
||||
+ "repository '" + repositoryName + "' in registry " + account
|
||||
+ " cannot be told from a missing one.");
|
||||
}
|
||||
return notFound(repositoryName, account);
|
||||
});
|
||||
}
|
||||
|
||||
private Optional<Repository> dataPlaneRepository(String repositoryName, String account, String region) {
|
||||
return AccountAwareStorageBackend.readInAccount(repoStore, account, key(region, account, repositoryName));
|
||||
}
|
||||
|
||||
public void tagResource(String repoName, String registryId, Map<String, String> tags, String region) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.ecr.registry;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.NetworkExposureGuard;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.ecr.EcrService;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
@@ -91,19 +92,105 @@ public class EcrRegistryDataPlane {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean writeAdmissionHeld = isWrite;
|
||||
context.request().pause();
|
||||
RegistryRequest registryRequest = request.get();
|
||||
if (registryRequest.repositoryName().isEmpty()) {
|
||||
admit(context, registryRequest, isWrite);
|
||||
} else if (registryManager.isCatalogReconciled()) {
|
||||
String storage;
|
||||
try {
|
||||
storage = ecrService.registryRepositoryName(
|
||||
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region());
|
||||
} catch (RuntimeException e) {
|
||||
// The registry may have been recovered since its catalog was read, so a name that catalog does
|
||||
// not place is checked against the registry running now before it is refused.
|
||||
resolveAfterTheCatalogThenAdmit(context, registryRequest, isWrite);
|
||||
return;
|
||||
}
|
||||
admit(context, registryRequest.withStorageRepositoryName(storage), isWrite);
|
||||
} else {
|
||||
resolveAfterTheCatalogThenAdmit(context, registryRequest, isWrite);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Until the catalog of the registry running now has been read, a name with no metadata cannot be told from a
|
||||
* repository whose images the registry holds, so the registry is started, or recovered, and its catalog read
|
||||
* first, off the event loop, before the name is resolved.
|
||||
*
|
||||
* <p>Exactly one of the client leaving and the read finishing takes the request on: a client that goes away
|
||||
* meanwhile gives its write admission back at once, so garbage collection does not wait on a write that can
|
||||
* no longer come.
|
||||
*/
|
||||
private void resolveAfterTheCatalogThenAdmit(RoutingContext context, RegistryRequest registryRequest,
|
||||
boolean writeAdmitted) {
|
||||
AtomicBoolean waiting = new AtomicBoolean(true);
|
||||
context.response().closeHandler(closed -> {
|
||||
if (waiting.compareAndSet(true, false) && writeAdmitted) {
|
||||
registryManager.releaseWriteAdmission();
|
||||
}
|
||||
});
|
||||
vertx.<String>executeBlocking(promise -> {
|
||||
try {
|
||||
registryManager.ensureStarted();
|
||||
registryManager.ensureCatalogReconciled();
|
||||
promise.complete(ecrService.registryRepositoryName(
|
||||
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
|
||||
} catch (Exception e) {
|
||||
promise.fail(e);
|
||||
}
|
||||
}).onComplete(result -> {
|
||||
if (!waiting.compareAndSet(true, false)) {
|
||||
return;
|
||||
}
|
||||
if (context.response().closed()) {
|
||||
if (writeAdmitted) {
|
||||
registryManager.releaseWriteAdmission();
|
||||
}
|
||||
} else if (result.failed()) {
|
||||
refuseUnresolved(context, registryRequest, writeAdmitted, result.cause());
|
||||
} else {
|
||||
try {
|
||||
admit(context, registryRequest.withStorageRepositoryName(result.result()), writeAdmitted);
|
||||
} catch (Throwable t) {
|
||||
// admit gave back what it took. Off the router's call stack nothing else answers the failure,
|
||||
// so it gets the 500 the synchronous path's would.
|
||||
context.request().resume();
|
||||
context.fail(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a request whose repository could not be resolved: {@code 404 NAME_UNKNOWN} for one nobody created, as
|
||||
* ECR answers before any byte reaches the registry, and unavailable for anything else.
|
||||
*/
|
||||
private void refuseUnresolved(RoutingContext context, RegistryRequest registryRequest,
|
||||
boolean writeAdmissionHeld, Throwable failure) {
|
||||
if (writeAdmissionHeld) {
|
||||
registryManager.releaseWriteAdmission();
|
||||
}
|
||||
context.request().resume();
|
||||
if (failure instanceof AwsException aws && "RepositoryNotFoundException".equals(aws.getErrorCode())) {
|
||||
if (!context.response().ended() && !context.response().closed()) {
|
||||
context.response().putHeader("Docker-Distribution-API-Version", "registry/2.0");
|
||||
registryError(context, 404, "NAME_UNKNOWN", aws.getMessage());
|
||||
}
|
||||
return;
|
||||
}
|
||||
LOG.debugv(failure, "Could not resolve ECR repository {0} in registry {1}",
|
||||
registryRequest.repositoryName(), registryRequest.accountId());
|
||||
registryUnavailable(context);
|
||||
}
|
||||
|
||||
/** Takes a resolved request on to its immutable-tag claim, its repository write lock and the registry. */
|
||||
private void admit(RoutingContext context, RegistryRequest registryRequest, boolean writeAdmitted) {
|
||||
boolean writeAdmissionHeld = writeAdmitted;
|
||||
Exchange activeExchange = null;
|
||||
String immutableTag = null;
|
||||
boolean tagClaimed = false;
|
||||
try {
|
||||
context.request().pause();
|
||||
|
||||
RegistryRequest registryRequest = request.get();
|
||||
if (!registryRequest.repositoryName().isEmpty()) {
|
||||
registryRequest = registryRequest.withStorageRepositoryName(
|
||||
ecrService.registryRepositoryName(
|
||||
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
|
||||
}
|
||||
immutableTag = immutableTag(context, registryRequest);
|
||||
if (immutableTag != null) {
|
||||
if (!ecrService.claimImmutableTag(immutableTag)) {
|
||||
@@ -118,7 +205,8 @@ public class EcrRegistryDataPlane {
|
||||
tagClaimed = true;
|
||||
}
|
||||
|
||||
Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest), isWrite);
|
||||
Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest),
|
||||
isWriteRequest(context.request().method()));
|
||||
activeExchange = exchange;
|
||||
writeAdmissionHeld = false;
|
||||
context.response().closeHandler(closed -> exchange.end());
|
||||
@@ -133,7 +221,6 @@ public class EcrRegistryDataPlane {
|
||||
release(immutableTag);
|
||||
}
|
||||
if (writeAdmissionHeld) {
|
||||
writeAdmissionHeld = false;
|
||||
registryManager.releaseWriteAdmission();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ public class EcrRegistryManager {
|
||||
private static final String NAMED_VOLUME = "ecr-registry-data";
|
||||
private static final String REPOSITORIES_PATH = "/var/lib/registry/docker/registry/v2/repositories/";
|
||||
private static final int GC_KILL_GRACE_SECONDS = 2;
|
||||
static final long RECONCILE_RETRY_MILLIS = 30_000;
|
||||
|
||||
/**
|
||||
* Matches an AWS-shaped ECR image URI in any partition:
|
||||
@@ -112,6 +113,8 @@ public class EcrRegistryManager {
|
||||
private volatile boolean started;
|
||||
private volatile boolean ready;
|
||||
private volatile boolean reconciled;
|
||||
/** When a reconcile retry last failed, by {@link #clock}; 0 while none has. */
|
||||
private volatile long reconcileRetryFailedAt;
|
||||
// Bug #6150: Track active garbage collection window
|
||||
private volatile boolean garbageCollecting;
|
||||
private final Object writeAdmissionLock = new Object();
|
||||
@@ -402,6 +405,33 @@ public class EcrRegistryManager {
|
||||
this.reconcileHook = hook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the catalog into the reconcile hook again when the read at start failed, so a
|
||||
* registry that answered its health check but not its catalog does not leave the
|
||||
* repositories it holds without metadata. A no-op once a read succeeded, with no hook,
|
||||
* or before the registry started. A retry that fails waits {@link #RECONCILE_RETRY_MILLIS}
|
||||
* before the next, so a lookup made meanwhile does not pay a catalog read each time.
|
||||
*
|
||||
* <p>Holds the monitor {@link #ensureStarted()} and the storage deletes take, so the
|
||||
* hook's metadata writes cannot interleave with a forced repository delete.
|
||||
*/
|
||||
public synchronized void ensureCatalogReconciled() {
|
||||
if (reconciled || reconcileHook == null || !started) {
|
||||
return;
|
||||
}
|
||||
long now = clock.millis();
|
||||
if (reconcileRetryFailedAt != 0 && now - reconcileRetryFailedAt < RECONCILE_RETRY_MILLIS) {
|
||||
return;
|
||||
}
|
||||
runReconcileOnce();
|
||||
reconcileRetryFailedAt = reconciled ? 0 : now;
|
||||
}
|
||||
|
||||
/** Whether the registry's catalog has been read into the reconcile hook since it started. */
|
||||
public boolean isCatalogReconciled() {
|
||||
return reconciled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts {@link #ensureStarted()} and reports whether the backing registry is
|
||||
* usable, instead of propagating the failure. Callers that only need repository
|
||||
@@ -468,6 +498,9 @@ public class EcrRegistryManager {
|
||||
registryAddress = null;
|
||||
started = false;
|
||||
ready = false;
|
||||
// The recovered registry's catalog is read again: it can hold images the one read before did not.
|
||||
reconciled = false;
|
||||
reconcileRetryFailedAt = 0;
|
||||
if (presence == ContainerPresence.ABSENT) {
|
||||
portAllocator.release(hostPort);
|
||||
hostPort = config.services().ecr().registryBasePort();
|
||||
@@ -630,7 +663,9 @@ public class EcrRegistryManager {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
List<String> repos = httpClient().catalog();
|
||||
// The strict read: a catalog the registry failed to give is not an empty one, and taking
|
||||
// it as one would leave the repositories it holds without metadata.
|
||||
List<String> repos = httpClient().catalogStrict();
|
||||
reconcileHook.accept(repos);
|
||||
reconciled = true;
|
||||
} catch (Exception e) {
|
||||
@@ -870,6 +905,7 @@ public class EcrRegistryManager {
|
||||
started = false;
|
||||
ready = false;
|
||||
reconciled = false;
|
||||
reconcileRetryFailedAt = 0;
|
||||
reopenWriteAdmission();
|
||||
hostPort = config.services().ecr().registryBasePort();
|
||||
}
|
||||
|
||||
@@ -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