fix(ecr): join the ECR API with the backing registry (#2466)

* fix(ecr): join the ECR API with the backing registry

Hostname-style ECR repository URIs resolve to loopback and hit the raw
registry:2 container directly, so a docker push stores the image under
the bare repository name while every API lookup (ListImages,
DescribeImages, BatchGetImage, BatchDeleteImage, best-effort tag
listing) only ever resolved the namespaced (account/region/repo) form.
Name mismatch meant pushed images were silently invisible, no error.

Adds resolveRegistryRepoName(): prefers the namespaced form, falls back
to the bare name when nothing is stored there, with a cross-account/
cross-region ambiguity guard using the storage backend's unfiltered
scan so the guard sees other scopes' claims in production, not just
the calling account. Wired into every read path above.

Force-delete resolves the name first (bare vs namespaced) and routes
storage cleanup through #2982's filesystem-cleanup mechanism
(EcrRegistryManager.deleteRepositoryStorageByInternalName) instead of
its own per-tag HEAD-then-DELETE loop, so hostname-style bare-name
content is actually removed instead of #2982's original code silently
missing it. Tag/catalog/digest discovery during force-delete uses
strict variants that throw on a genuine registry error (ServerException,
matching service-2.json); any failure (unreachable registry included)
now aborts the delete with metadata intact rather than assuming the
repository empty, except when no HTTP client is wired at all (a pure
test double with no backing registry to clean up). Catalog pagination
follows the registry's Link header rather than assuming a single page.

Closes #2444.

* fix(ecr): explicit type and no em dashes per AGENTS.md

hasOtherScopeClaim used var for the cast to
AccountAwareStorageBackend<Repository>; AGENTS.md requires explicit
types (KenkoGeek review). Also replaced a few em dashes introduced in
new comments across the review's final round of tests, which AGENTS.md
forbids repo-wide and CI enforces.

---------

Co-authored-by: anmolxlight <anmolxlight@users.noreply.github.com>
This commit is contained in:
Anmol Mishraandanmolxlight authored and GitHub committed 2026-09-14 16:31:51 -04:00
1 parent 6ce3fbbd2e
commit 064f302ab1
4 files changed
+748 -53

No files matched your search

@@ -218,16 +218,45 @@ public class EcrService implements ResourceProvider {
String key = key(region, account, repositoryName);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(repositoryName, account));
List<String> tags = listTagsBestEffort(repo, region);
if (!force && !tags.isEmpty()) {
// Check whether the registry has any tagged images for this repo.
// A test double with no HTTP client means no backing registry exists,
// so there is nothing to clean up. Any failure against a real client
// aborts the delete: an unreachable registry cannot prove the repo
// empty (non-force must not bypass RepositoryNotEmptyException) and
// force must not orphan pullable images behind deleted metadata.
List<String> tags;
boolean registryAvailable = true;
if (registryManager.httpClient() == null) {
// Test double without an HTTP layer (Mockito default): no backing
// registry exists, so there is nothing to clean up.
tags = List.of();
registryAvailable = false;
} else try {
tags = listTagsOrThrow(account, region, repositoryName);
} catch (Exception e) {
if (isRegistryUnreachable(e)) {
throw new AwsException("ServerException",
"Backing registry unreachable for repository '" + repositoryName
+ "': retry after the registry recovers (" + e.getMessage() + ")",
500);
}
throw new AwsException("ServerException",
"Failed to clean up the backing registry for repository '" + repositoryName + "': "
+ e.getMessage(),
500);
}
if (!tags.isEmpty() && !force) {
throw new AwsException("RepositoryNotEmptyException",
"The repository with name '" + repositoryName
+ "' in registry with id '" + account + "' cannot be deleted because it still contains images",
400);
}
if (force) {
deleteRepositoryStorage(registryRepositoryName(repo, region));
if (force && registryAvailable) {
// Single cleanup mechanism (#2982): remove the repository storage
// directories inside the registry container. Routed through
// resolveRegistryRepoName so content pushed under the bare name
// via hostname-style URIs is removed too (issue #2444).
deleteRepositoryStorageResolved(account, region, repositoryName);
}
repoStore.delete(key);
@@ -263,7 +292,7 @@ public class EcrService implements ResourceProvider {
public List<ImageIdentifier> listImages(String repositoryName, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryRepositoryName(repo, region);
String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName);
try {
RegistryHttpClient http = registryManager.httpClient();
List<String> tags = http.listTags(internal);
@@ -285,7 +314,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryRepositoryName(repo, region);
String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<String> refs = new ArrayList<>();
@@ -360,7 +389,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryRepositoryName(repo, region);
String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<Image> images = new ArrayList<>();
@@ -400,7 +429,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryRepositoryName(repo, region);
String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName);
RegistryHttpClient http = registryManager.httpClient();
List<ImageIdentifier> deleted = new ArrayList<>();
@@ -609,7 +638,8 @@ public class EcrService implements ResourceProvider {
private List<String> listTagsBestEffort(Repository repo, String region) {
try {
return registryManager.httpClient().listTags(registryRepositoryName(repo, region));
return registryManager.httpClient()
.listTags(resolveRegistryRepoName(repo.getRegistryId(), region, repo.getRepositoryName()));
} catch (Exception e) {
LOG.debugv("Could not list tags for {0} (registry not available): {1}",
repo.getRepositoryName(), e.getMessage());
@@ -617,11 +647,17 @@ public class EcrService implements ResourceProvider {
}
}
private void deleteRepositoryStorage(String registryRepositoryName) {
/**
* Deletes registry storage for the repository under the name it was
* actually pushed as. Hostname-style pushes land under the bare name,
* which {@code internalRepoName} alone never addresses (issue #2444).
*/
private void deleteRepositoryStorageResolved(String account, String region, String repositoryName) {
String internal = resolveRegistryRepoName(account, region, repositoryName);
try {
registryManager.deleteRepositoryStorage(registryRepositoryName);
registryManager.deleteRepositoryStorageByInternalName(internal);
} catch (Exception e) {
throw registryFailure(registryRepositoryName, e);
throw registryFailure(repositoryName, e);
}
}
@@ -639,6 +675,90 @@ public class EcrService implements ResourceProvider {
"Could not delete images from repository '" + repositoryName + "'", 500);
}
/**
* Lists tags and propagates registry failures. Used by force-delete to
* distinguish "registry unreachable" (skip cleanup) from "registry
* available but listing failed" (abort deletion).
*/
private List<String> listTagsOrThrow(String account, String region, String repoName) throws Exception {
return registryManager.httpClient()
.listTagsStrict(resolveRegistryRepoNameStrict(account, region, repoName));
}
/**
* Resolves the repository name as stored in the backing registry.
* Hostname-style URIs ({@code <account>.dkr.ecr.<region>.localhost:<port>/<repo>})
* reach the raw registry, so docker pushes land under the bare repo name,
* while path-style URIs land under {@code <account>/<region>/<repo>}.
* Resolution uses catalog membership (not tag listing) so untagged,
* digest-only repositories resolve correctly. The namespaced form wins
* when both exist.
*
* <p>Ambiguity guard: a bare-name entry can only be claimed when no
* <em>other</em> account/region has metadata for the same repository name.
* Otherwise the bare entry's owning scope is unknown and resolving to it
* would let one scope read or delete another scope's images, so the call
* falls back to the (empty) namespaced form.
*/
private String resolveRegistryRepoName(String account, String region, String repoName) {
try {
return resolveRegistryRepoNameStrict(account, region, repoName);
} catch (Exception e) {
LOG.debugv("Registry lookup failed while resolving {0}: {1}", repoName, e.getMessage());
return registryManager.internalRepoName(account, region, repoName);
}
}
private String resolveRegistryRepoNameStrict(String account, String region, String repoName) throws Exception {
String internal = registryManager.internalRepoName(account, region, repoName);
List<String> catalog = registryManager.httpClient().catalogStrict();
if (catalog.contains(internal)) {
return internal;
}
if (catalog.contains(repoName)) {
String currentKey = region + "::" + account + "::" + repoName;
boolean otherScopeClaimsIt = hasOtherScopeClaim(repoName, currentKey);
if (!otherScopeClaimsIt) {
return repoName;
}
LOG.warnv("Bare registry entry {0} claimed by another account/region; "
+ "resolving {0} to its namespaced form", repoName, internal);
}
return internal;
}
private boolean hasOtherScopeClaim(String repoName, String currentKey) {
String suffix = "::" + repoName;
if (repoStore instanceof AccountAwareStorageBackend<?> aware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<Repository> typed = (AccountAwareStorageBackend<Repository>) aware;
return typed.scanAllAccountEntries(k -> k.endsWith(suffix) && !k.equals(currentKey))
.stream().findAny().isPresent();
}
return repoStore.keys().stream()
.anyMatch(k -> k.endsWith(suffix) && !k.equals(currentKey));
}
private static boolean isRegistryUnreachable(Throwable e) {
// Only genuine connectivity failures qualify. An NPE or an "is null"
// message means a bug or an answered error body, those must abort
// the delete, never masquerade as an outage.
Throwable t = e;
while (t != null) {
if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException
|| t instanceof java.net.SocketTimeoutException) {
return true;
}
String msg = t.getMessage();
if (msg != null && (msg.contains("Connection refused") || msg.contains("Connection reset")
|| msg.contains("Failed to connect") || msg.contains("Connection timed out"))) {
return true;
}
t = t.getCause();
}
return false;
}
private static String key(String region, String account, String repoName) {
return region + "::" + account + "::" + repoName;
}
@@ -455,16 +455,20 @@ public class EcrRegistryManager {
/** Removes repository manifest storage without removing descendant repository directories. */
public synchronized void deleteRepositoryStorage(String accountId, String region, String repositoryName) {
deleteRepositoryStorage(internalRepoName(accountId, region, repositoryName));
deleteRepositoryStorageByInternalName(internalRepoName(accountId, region, repositoryName));
}
/** Removes storage for a registry namespace selected by the ECR control plane. */
public synchronized void deleteRepositoryStorage(String repository) {
/**
* Removes repository manifest storage for an already-resolved internal
* repository name. Used when the caller resolved a bare name (hostname-style
* pushes) that {@code internalRepoName} alone never addresses (issue #2444).
*/
public synchronized void deleteRepositoryStorageByInternalName(String internalRepoName) {
ensureStarted();
if (!started || containerId == null) {
throw new IllegalStateException("ECR registry is not started");
}
String path = repositoryStoragePath(repository);
String path = repositoryStoragePath(internalRepoName);
StringBuilder output = new StringBuilder();
DockerClient dockerClient = lifecycleManager.getDockerClient();
ExecCreateCmdResponse exec = dockerClient
@@ -49,30 +49,77 @@ public class RegistryHttpClient {
}
}
/** Lists all repository names known to the backing registry. */
/**
* Lists all repository names known to the backing registry, following the
* {@code Link} header pagination that {@code GET /v2/_catalog} uses
* (registry:2 caps each page at 100 entries by default).
*/
public List<String> catalog() throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/_catalog"))
.timeout(Duration.ofSeconds(10))
.GET()
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) {
LOG.warnv("Registry catalog returned {0}: {1}", resp.statusCode(), resp.body());
return Collections.emptyList();
}
JsonNode root = MAPPER.readTree(resp.body());
JsonNode repos = root.get("repositories");
if (repos == null || !repos.isArray()) {
return Collections.emptyList();
try {
return catalogStrict();
} catch (IOException e) {
LOG.warnv("Registry catalog returned error: {0}", e.getMessage());
return List.of();
}
}
/**
* Strict catalog: throws on any non-200 so callers can distinguish
* &quot;no repos&quot; from &quot;registry failure&quot;.
*/
public List<String> catalogStrict() throws IOException, InterruptedException {
List<String> out = new ArrayList<>();
repos.forEach(n -> out.add(n.asText()));
String url = baseUrl + "/v2/_catalog";
for (int page = 0; page < 10_000 && url != null; page++) {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(10))
.GET()
.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) {
throw new IOException("Registry catalog returned " + resp.statusCode() + ": " + resp.body());
}
JsonNode root = MAPPER.readTree(resp.body());
JsonNode repos = root.get("repositories");
if (repos != null && repos.isArray()) {
repos.forEach(n -> out.add(n.asText()));
}
url = nextCatalogPage(resp.headers().firstValue("Link").orElse(null));
}
return out;
}
/** Extracts {@code </v2/_catalog?n=..&last=..>} from a registry Link header. */
private String nextCatalogPage(String link) {
if (link == null || link.isBlank()) {
return null;
}
int start = link.indexOf('<');
int end = link.indexOf('>');
if (start < 0 || end <= start) {
return null;
}
String target = link.substring(start + 1, end);
return target.startsWith("/") ? baseUrl + target : target;
}
/** Lists tags for a repository. Returns an empty list if the repo is not yet known to the registry. */
public List<String> listTags(String name) throws IOException, InterruptedException {
try {
return listTagsStrict(name);
} catch (IOException e) {
LOG.warnv("Registry tags/list returned error: {0}", e.getMessage());
return Collections.emptyList();
}
}
/**
* Lists tags, throwing on registry errors so callers can distinguish
* &quot;no tags&quot; from &quot;registry failure&quot;. 404 still returns
* empty; any other non-200 or malformed 200 throws {@link IOException}.
*/
public List<String> listTagsStrict(String name) throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/tags/list"))
.timeout(Duration.ofSeconds(10))
@@ -83,14 +130,16 @@ public class RegistryHttpClient {
return Collections.emptyList();
}
if (resp.statusCode() != 200) {
LOG.warnv("Registry tags/list returned {0}: {1}", resp.statusCode(), resp.body());
return Collections.emptyList();
throw new IOException("Registry tags/list returned " + resp.statusCode() + ": " + resp.body());
}
JsonNode root = MAPPER.readTree(resp.body());
JsonNode tags = root.get("tags");
if (tags == null || tags.isNull() || !tags.isArray()) {
if (tags == null || tags.isNull()) {
return Collections.emptyList();
}
if (!tags.isArray()) {
throw new IOException("Registry tags/list returned non-array tags: " + resp.body());
}
List<String> out = new ArrayList<>();
tags.forEach(n -> out.add(n.asText()));
return out;
@@ -102,6 +151,20 @@ public class RegistryHttpClient {
*/
public String headManifestDigest(String name, String reference, List<String> acceptedMediaTypes)
throws IOException, InterruptedException {
try {
return headManifestDigestStrict(name, reference, acceptedMediaTypes);
} catch (IOException e) {
LOG.warnv("Registry HEAD manifest {0}/{1} returned error: {2}", name, reference, e.getMessage());
return null;
}
}
/**
* Strict HEAD: throws on registry error or missing digest so force-delete
* can abort instead of silently skipping a tag. 404 still returns null.
*/
public String headManifestDigestStrict(String name, String reference, List<String> acceptedMediaTypes)
throws IOException, InterruptedException {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + reference))
.timeout(Duration.ofSeconds(10))
.method("HEAD", HttpRequest.BodyPublishers.noBody());
@@ -111,10 +174,13 @@ public class RegistryHttpClient {
return null;
}
if (resp.statusCode() >= 400) {
LOG.warnv("Registry HEAD manifest {0}/{1} returned {2}", name, reference, resp.statusCode());
return null;
throw new IOException("Registry HEAD manifest " + name + "/" + reference + " returned " + resp.statusCode());
}
return resp.headers().firstValue("Docker-Content-Digest").orElse(null);
String digest = resp.headers().firstValue("Docker-Content-Digest").orElse(null);
if (digest == null || digest.isBlank()) {
throw new IOException("Registry HEAD manifest " + name + "/" + reference + " missing Docker-Content-Digest");
}
return digest;
}
/** Result of {@link #getManifest}: digest, body, and content media type. */