mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
6ce3fbbd2e
commit
064f302ab1
4 files changed
+748
-53
No files matched your search
@@ -29,6 +29,7 @@ import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -264,13 +265,28 @@ class EcrServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepository_forceRemovesRepositoryStorageAndPrunesFinalRepositoryStorage() {
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
void deleteRepository_forceRemovesRepositoryStorageAndPrunesFinalRepositoryStorage() throws Exception {
|
||||
// The fake catalog carries the bare name (hostname-style push), so the
|
||||
// storage delete must target it rather than the empty namespaced form.
|
||||
String digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
try (FakeRegistryServer registry = new FakeRegistryServer(REPO, "v1", digest, manifest)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
|
||||
service.deleteRepository(REPO, null, true, REGION);
|
||||
service.deleteRepository(REPO, null, true, REGION);
|
||||
|
||||
verify(registryManager).deleteRepositoryStorage(ACCOUNT + "/" + REGION + "/" + REPO);
|
||||
verify(registryManager).pruneStorage();
|
||||
verify(registryManager).deleteRepositoryStorageByInternalName(REPO);
|
||||
verify(registryManager).pruneStorage();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -284,17 +300,30 @@ class EcrServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepository_forceRetainsMetadataWhenRegistryCleanupFails() {
|
||||
Mockito.doThrow(new IllegalStateException("registry unavailable"))
|
||||
.when(registryManager).deleteRepositoryStorage(ACCOUNT + "/" + REGION + "/" + REPO);
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
void deleteRepository_forceRetainsMetadataWhenRegistryCleanupFails() throws Exception {
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
try (FakeRegistryServer registry = new FakeRegistryServer(REPO, "v1",
|
||||
"sha256:2222222222222222222222222222222222222222222222222222222222222222", manifest)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
Mockito.doThrow(new IllegalStateException("registry unavailable"))
|
||||
.when(registryManager).deleteRepositoryStorageByInternalName(anyString());
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(REPO, null, true, REGION));
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(REPO, null, true, REGION));
|
||||
|
||||
assertEquals("ServerException", ex.getErrorCode());
|
||||
assertEquals(REPO, service.describeRepositories(List.of(REPO), null, REGION).getFirst().getRepositoryName());
|
||||
verify(registryManager, never()).pruneStorage();
|
||||
assertEquals("ServerException", ex.getErrorCode());
|
||||
assertEquals(REPO, service.describeRepositories(List.of(REPO), null, REGION).getFirst().getRepositoryName());
|
||||
verify(registryManager, never()).pruneStorage();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -387,6 +416,250 @@ class EcrServiceTest {
|
||||
// PutImageTagMutability
|
||||
// ------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void hostnameStylePushesUnderBareRepoNameAreVisibleViaListAndDescribeImages() throws Exception {
|
||||
// A docker push to <account>.dkr.ecr.<region>.localhost:<port>/<repo>
|
||||
// reaches the raw registry, so the image is stored under the bare repo
|
||||
// name with no account/region prefix (issue #2444).
|
||||
String repositoryName = "probe/roundtrip";
|
||||
String tag = "v1";
|
||||
String digest = "sha256:2222222222222222222222222222222222222222222222222222222222222222";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {
|
||||
"mediaType": "application/vnd.docker.container.image.v1+json",
|
||||
"size": 100,
|
||||
"digest": "sha256:config"
|
||||
},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
|
||||
try (FakeRegistryServer registry = new FakeRegistryServer(repositoryName, tag, digest, manifest)) {
|
||||
when(registryManager.getRepositoryUri(ACCOUNT, REGION, repositoryName))
|
||||
.thenReturn(ACCOUNT + ".dkr.ecr." + REGION + ".localhost:" + registry.port() + "/" + repositoryName);
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
|
||||
List<ImageIdentifier> imageIds = service.listImages(repositoryName, null, REGION);
|
||||
assertEquals(1, imageIds.size());
|
||||
assertEquals(tag, imageIds.get(0).getImageTag());
|
||||
assertEquals(digest, imageIds.get(0).getImageDigest());
|
||||
|
||||
EcrService.DescribeImagesResult described = service.describeImages(repositoryName, null, null, REGION);
|
||||
assertTrue(described.failures().isEmpty());
|
||||
assertEquals(1, described.imageDetails().size());
|
||||
assertEquals(digest, described.imageDetails().get(0).getImageDigest());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepositoryForceDeletesResolvedStorageEntry() throws Exception {
|
||||
// Hostname-style push landed under the bare name; force-delete must
|
||||
// remove that entry (not the empty namespaced one) through the single
|
||||
// #2982 storage mechanism, then drop the metadata row.
|
||||
String repositoryName = "probe/deleteme";
|
||||
String tag = "v1";
|
||||
String digest = "sha256:3333333333333333333333333333333333333333333333333333333333333333";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
|
||||
try (FakeRegistryServer registry = new FakeRegistryServer(repositoryName, tag, digest, manifest)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
service.deleteRepository(repositoryName, null, true, REGION);
|
||||
|
||||
verify(registryManager).deleteRepositoryStorageByInternalName(repositoryName);
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(repositoryName, null, true, REGION),
|
||||
"metadata row must be gone after force-delete");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareEntryOnSecondCatalogPageStillResolves() throws Exception {
|
||||
// registry:2 caps _catalog pages at 100 entries; a bare entry beyond the
|
||||
// first page must still be found (Greptile P1: catalog pagination).
|
||||
String repositoryName = "probe/paged";
|
||||
String tag = "v1";
|
||||
String digest = "sha256:7777777777777777777777777777777777777777777777777777777777777777";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
|
||||
try (PaginatedCatalogRegistryServer registry =
|
||||
new PaginatedCatalogRegistryServer(repositoryName, 150)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
List<ImageIdentifier> ids = service.listImages(repositoryName, null, REGION);
|
||||
assertEquals(1, ids.size());
|
||||
assertEquals(tag, ids.get(0).getImageTag());
|
||||
assertEquals(digest, ids.get(0).getImageDigest());
|
||||
org.junit.jupiter.api.Assertions.assertTrue(registry.sawSecondPageRequest(),
|
||||
"resolver must follow the Link header to page 2");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void untaggedDigestOnlyRepositoryResolvesAndDescribes() throws Exception {
|
||||
// A bare-name repo whose only manifest is untagged (digest-addressable):
|
||||
// tags/list returns null tags, but the catalog still lists the repo, so
|
||||
// resolution must not misroute it (Greptile P1: untagged images).
|
||||
String repositoryName = "probe/untagged";
|
||||
String digest = "sha256:4444444444444444444444444444444444444444444444444444444444444444";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
|
||||
try (UntaggedRegistryServer registry = new UntaggedRegistryServer(repositoryName, digest)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
|
||||
// BatchGetImage by digest resolves the bare-name entry via catalog membership.
|
||||
EcrService.BatchGetImageResult got = service.batchGetImage(
|
||||
repositoryName,
|
||||
List.of(new ImageIdentifier(null, digest)),
|
||||
null, null, REGION);
|
||||
assertTrue(got.failures().isEmpty(), () -> "unexpected failures: " + got.failures());
|
||||
assertEquals(1, got.images().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareEntryClaimedByOtherAccountIsNotResolvedForThisScope() throws Exception {
|
||||
// Both accounts have metadata for the same repo name in the same region;
|
||||
// only ONE bare registry entry exists. Account A's lookups must resolve
|
||||
// to its own (namespaced, empty) entry, never to the shared bare entry
|
||||
// holding account B's images (Greptile P1: scope isolation).
|
||||
String repositoryName = "probe/shared-name";
|
||||
String tag = "v1";
|
||||
String digest = "sha256:6666666666666666666666666666666666666666666666666666666666666666";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
|
||||
try (FakeRegistryServer registry =
|
||||
new FakeRegistryServer(repositoryName, tag, digest, manifest)) {
|
||||
// The fake serves the BARE name in its catalog and tags, simulating
|
||||
// a hostname-style push that bypassed the namespacing.
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
|
||||
// Account B created metadata for the same name.
|
||||
service.createRepository(repositoryName, "111111111111", null, null, null, null, null, REGION);
|
||||
// Account A creates its own repository; its namespaced entry does not
|
||||
// exist in this registry, but a bare entry with that name DOES, so the
|
||||
// ambiguity guard must keep resolution on A's namespaced form.
|
||||
service.createRepository(repositoryName, ACCOUNT, null, null, null, null, null, REGION);
|
||||
|
||||
List<ImageIdentifier> ids = service.listImages(repositoryName, ACCOUNT, REGION);
|
||||
assertTrue(ids.isEmpty(),
|
||||
"bare entry owned by another account must not resolve for this scope");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepositoryForceFailsWhenRegistryCleanupFails() throws Exception {
|
||||
// Storage deletion throws: force-delete must surface a 500 and keep
|
||||
// the metadata row instead of reporting success (Greptile P1).
|
||||
String repositoryName = "probe/failing-delete";
|
||||
String tag = "v1";
|
||||
String digest = "sha256:5555555555555555555555555555555555555555555555555555555555555555";
|
||||
String manifest = """
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
|
||||
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
|
||||
"layers": []
|
||||
}
|
||||
""";
|
||||
try (FakeRegistryServer registry = new FakeRegistryServer(repositoryName, tag, digest, manifest)) {
|
||||
when(registryManager.httpClient())
|
||||
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
|
||||
doThrow(new RuntimeException("rm failed"))
|
||||
.when(registryManager).deleteRepositoryStorageByInternalName(anyString());
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(repositoryName, null, true, REGION));
|
||||
assertEquals("ServerException", ex.getErrorCode());
|
||||
|
||||
// Metadata survives so the operator can retry after fixing the registry.
|
||||
assertEquals(1, service.describeRepositories(List.of(repositoryName), null, REGION).size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepositoryForceAbortsOnNullPointerDuringDiscovery() throws Exception {
|
||||
// An NPE (bug or null body element) must abort the delete, never
|
||||
// masquerade as a registry outage (Greptile P1).
|
||||
String repositoryName = "probe/npe-discovery";
|
||||
RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class);
|
||||
when(registryManager.httpClient()).thenReturn(http);
|
||||
when(http.listTagsStrict(anyString()))
|
||||
.thenThrow(new NullPointerException("registry endpoint is null"));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(repositoryName, null, true, REGION));
|
||||
assertEquals("ServerException", ex.getErrorCode());
|
||||
|
||||
// Metadata survives so the operator can retry.
|
||||
assertEquals(1, service.describeRepositories(List.of(repositoryName), null, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRepositoryAbortsWhenRegistryUnreachable() throws Exception {
|
||||
// A refused connection (registry down) must abort the delete, never
|
||||
// assume the repo empty: otherwise non-force bypasses
|
||||
// RepositoryNotEmptyException and force orphans pullable images
|
||||
// behind deleted metadata (Greptile P1).
|
||||
String repositoryName = "probe/unreachable-registry";
|
||||
RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class);
|
||||
when(registryManager.httpClient()).thenReturn(http);
|
||||
when(http.listTagsStrict(anyString()))
|
||||
.thenThrow(new java.net.ConnectException("Connection refused"));
|
||||
|
||||
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.deleteRepository(repositoryName, null, true, REGION));
|
||||
assertEquals("ServerException", ex.getErrorCode());
|
||||
|
||||
// Metadata survives so the operator can retry after recovery.
|
||||
assertEquals(1, service.describeRepositories(List.of(repositoryName), null, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putImageTagMutability_roundTrips() {
|
||||
service.createRepository(REPO, null, null, null, null, null, null, REGION);
|
||||
@@ -501,6 +774,7 @@ class EcrServiceTest {
|
||||
private final String tag;
|
||||
private final String digest;
|
||||
private final String manifest;
|
||||
private final List<String> deletedDigests = new java.util.ArrayList<>();
|
||||
|
||||
private FakeRegistryServer(String repository, String tag, String digest, String manifest) throws IOException {
|
||||
this.repository = repository;
|
||||
@@ -516,6 +790,14 @@ class EcrServiceTest {
|
||||
return server.getAddress().getPort();
|
||||
}
|
||||
|
||||
private boolean sawDelete() {
|
||||
return !deletedDigests.isEmpty();
|
||||
}
|
||||
|
||||
private String lastDeletedDigest() {
|
||||
return deletedDigests.isEmpty() ? null : deletedDigests.get(deletedDigests.size() - 1);
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
String method = exchange.getRequestMethod();
|
||||
@@ -523,6 +805,16 @@ class EcrServiceTest {
|
||||
send(exchange, 200, "");
|
||||
return;
|
||||
}
|
||||
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
|
||||
sendJson(exchange, 200, "{\"repositories\":[\"" + repository + "\"]}");
|
||||
return;
|
||||
}
|
||||
if (path.equals("/v2/" + repository + "/manifests/" + digest) && "DELETE".equals(method)) {
|
||||
deletedDigests.add(digest);
|
||||
exchange.sendResponseHeaders(202, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
if (("/v2/" + repository + "/tags/list").equals(path) && "GET".equals(method)) {
|
||||
sendJson(exchange, 200, "{\"name\":\"" + repository + "\",\"tags\":[\"" + tag + "\"]}");
|
||||
return;
|
||||
@@ -564,4 +856,217 @@ class EcrServiceTest {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registry whose _catalog spans two pages (Link header); repo lives on page 2. */
|
||||
private static final class PaginatedCatalogRegistryServer implements AutoCloseable {
|
||||
private final HttpServer server;
|
||||
private final String repository;
|
||||
private final String tag;
|
||||
private final String digest;
|
||||
private final List<String> filler;
|
||||
private volatile boolean secondPageRequested;
|
||||
|
||||
private PaginatedCatalogRegistryServer(String repository, int fillerCount) throws IOException {
|
||||
this.repository = repository;
|
||||
this.tag = "v1";
|
||||
this.digest = "sha256:7777777777777777777777777777777777777777777777777777777777777777";
|
||||
List<String> f = new java.util.ArrayList<>();
|
||||
for (int i = 0; i < fillerCount; i++) {
|
||||
f.add(String.format("filler/%03d", i));
|
||||
}
|
||||
this.filler = f;
|
||||
this.server = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
this.server.createContext("/v2/", this::handle);
|
||||
this.server.start();
|
||||
}
|
||||
|
||||
private int port() {
|
||||
return server.getAddress().getPort();
|
||||
}
|
||||
|
||||
private boolean sawSecondPageRequest() {
|
||||
return secondPageRequested;
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
String query = exchange.getRequestURI().getQuery();
|
||||
String method = exchange.getRequestMethod();
|
||||
if ("/v2/".equals(path) && "GET".equals(method)) {
|
||||
send(exchange, 200, "");
|
||||
return;
|
||||
}
|
||||
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
|
||||
boolean pageTwo = query != null && query.contains("last=");
|
||||
if (pageTwo) {
|
||||
secondPageRequested = true;
|
||||
sendJson(exchange, 200, "{\"repositories\":[\"" + repository + "\"]}");
|
||||
} else {
|
||||
String joined = filler.stream()
|
||||
.map(r -> "\"" + r + "\"")
|
||||
.reduce((a, b) -> a + "," + b)
|
||||
.orElse("");
|
||||
exchange.getResponseHeaders().add("Link",
|
||||
"</v2/_catalog?n=100&last=" + filler.get(filler.size() - 1).replace("/", "%2F") + ">; rel=\"next\"");
|
||||
sendJson(exchange, 200, "{\"repositories\":[" + joined + "]}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (path.equals("/v2/" + repository + "/tags/list") && "GET".equals(method)) {
|
||||
sendJson(exchange, 200, "{\"name\":\"" + repository + "\",\"tags\":[\"" + tag + "\"]}");
|
||||
return;
|
||||
}
|
||||
if (path.equals("/v2/" + repository + "/manifests/" + tag) && "HEAD".equals(method)) {
|
||||
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void sendJson(HttpExchange exchange, int status, String body) throws IOException {
|
||||
exchange.getResponseHeaders().add("Content-Type", "application/json");
|
||||
send(exchange, status, body);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes();
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registry serving a catalog entry whose repository has no tags (digest-only). */
|
||||
private static final class UntaggedRegistryServer implements AutoCloseable {
|
||||
private final HttpServer server;
|
||||
private final String repository;
|
||||
private final String digest;
|
||||
|
||||
private UntaggedRegistryServer(String repository, String digest) throws IOException {
|
||||
this.repository = repository;
|
||||
this.digest = digest;
|
||||
this.server = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
this.server.createContext("/v2/", this::handle);
|
||||
this.server.start();
|
||||
}
|
||||
|
||||
private int port() {
|
||||
return server.getAddress().getPort();
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
String method = exchange.getRequestMethod();
|
||||
if ("/v2/".equals(path) && "GET".equals(method)) {
|
||||
send(exchange, 200, "");
|
||||
return;
|
||||
}
|
||||
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
|
||||
sendJson(exchange, 200, "{\"repositories\":[\"" + repository + "\"]}");
|
||||
return;
|
||||
}
|
||||
if (path.equals("/v2/" + repository + "/tags/list") && "GET".equals(method)) {
|
||||
// registry:2 returns tags: null when only untagged manifests exist.
|
||||
sendJson(exchange, 200, "{\"name\":\"" + repository + "\",\"tags\":null}");
|
||||
return;
|
||||
}
|
||||
if (path.equals("/v2/" + repository + "/manifests/" + digest)
|
||||
&& ("GET".equals(method) || "HEAD".equals(method))) {
|
||||
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
|
||||
if ("HEAD".equals(method)) {
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
exchange.getResponseHeaders().add("Content-Type",
|
||||
"application/vnd.docker.distribution.manifest.v2+json");
|
||||
send(exchange, 200, "{\"schemaVersion\":2,\"config\":{\"size\":1},\"layers\":[]}");
|
||||
return;
|
||||
}
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void sendJson(HttpExchange exchange, int status, String body) throws IOException {
|
||||
exchange.getResponseHeaders().add("Content-Type", "application/json");
|
||||
send(exchange, status, body);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes();
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registry that reports a fixed catalog; nothing else resolves. */
|
||||
private static final class CatalogOnlyRegistryServer implements AutoCloseable {
|
||||
private final HttpServer server;
|
||||
private final List<String> repositories;
|
||||
|
||||
private CatalogOnlyRegistryServer(List<String> repositories) throws IOException {
|
||||
this.repositories = repositories;
|
||||
this.server = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
this.server.createContext("/v2/", this::handle);
|
||||
this.server.start();
|
||||
}
|
||||
|
||||
private int port() {
|
||||
return server.getAddress().getPort();
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
String method = exchange.getRequestMethod();
|
||||
if ("/v2/".equals(path) && "GET".equals(method)) {
|
||||
send(exchange, 200, "");
|
||||
return;
|
||||
}
|
||||
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
|
||||
String joined = repositories.stream()
|
||||
.map(r -> "\"" + r + "\"")
|
||||
.reduce((a, b) -> a + "," + b)
|
||||
.orElse("");
|
||||
sendJson(exchange, 200, "{\"repositories\":[" + joined + "]}");
|
||||
return;
|
||||
}
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void sendJson(HttpExchange exchange, int status, String body) throws IOException {
|
||||
exchange.getResponseHeaders().add("Content-Type", "application/json");
|
||||
send(exchange, status, body);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes();
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user