fix(ecr): paginate image listings (#6544)

* fix(ecr): paginate image listings

* fix(ecr): fetch digests only for the selected page

* fix(test): await ECR tag release after stream reset

* refactor(ecr): remove unused image listing overload
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-25 21:37:26 -04:00
1 parent 671e4bfb7c
commit b29c8f8a60
7 files changed
+339 -23

No files matched your search

+6 -1
View File
@@ -17,7 +17,7 @@
| `DescribeRepositories` | List repositories or fetch by name |
| `DeleteRepository` | Delete a repository (with `force=true` semantics for non-empty repos) |
| `GetAuthorizationToken` | Returns a docker-login token + proxy endpoint |
| `ListImages` | Enumerate tags and digests in a repository |
| `ListImages` | Enumerate paginated tags and digests in a repository |
| `DescribeImages` | Image metadata: digest, size, push timestamp, manifest media type |
| `BatchGetImage` | Fetch image manifests, honoring `acceptedMediaTypes` |
| `BatchDeleteImage` | Delete images by tag or digest |
@@ -37,6 +37,11 @@
| `PutReplicationConfiguration` / `DescribeRegistry` | Store the registry's replication rules and return them with the registry ID (stored, not acted on) |
| `PutRegistryScanningConfiguration` / `GetRegistryScanningConfiguration` | Store the registry's scan type and scanning rules (stored, not acted on) |
`ListImages` accepts `maxResults` from 1 to 1000 (default 100) and returns `nextToken`
when another page remains. Tokens are scoped to the region, registry, and repository;
local pages use stable tag order. Listing still enumerates tagged images and ignores
the optional `filter` fields.
### Admin Endpoints
| Endpoint | Description |
+6
View File
@@ -360,6 +360,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ecr</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrock</artifactId>
@@ -315,14 +315,27 @@ public class EcrJsonHandler {
private Response handleListImages(JsonNode request, String region) {
String repo = request.path("repositoryName").asText(null);
String registryId = request.path("registryId").asText(null);
List<ImageIdentifier> ids = service.listImages(repo, registryId, region);
JsonNode limit = request.get("maxResults");
if (limit != null && !limit.isNull() && (!limit.isIntegralNumber() || !limit.canConvertToInt())) {
throw new AwsException("InvalidParameterException", "maxResults must be between 1 and 1000", 400);
}
JsonNode token = request.get("nextToken");
if (token != null && !token.isNull() && !token.isTextual()) {
throw new AwsException("InvalidParameterException", "Invalid nextToken", 400);
}
Integer maxResults = request.hasNonNull("maxResults") ? limit.asInt() : null;
PaginatedResult<ImageIdentifier> page = service.listImages(repo, registryId, region,
maxResults, request.path("nextToken").asText(null));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
for (ImageIdentifier id : ids) {
for (ImageIdentifier id : page.items()) {
arr.add(buildImageIdentifier(id));
}
response.set("imageIds", arr);
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
}
return Response.ok(response).build();
}
@@ -33,6 +33,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
@@ -513,25 +514,37 @@ public class EcrService implements ResourceProvider {
// ListImages / DescribeImages / BatchGetImage / BatchDeleteImage
// ============================================================
public List<ImageIdentifier> listImages(String repositoryName, String registryId, String region) {
public PaginatedResult<ImageIdentifier> listImages(String repositoryName, String registryId, String region,
Integer maxResults, String nextToken) {
int limit = maxResults != null ? maxResults : 100;
if (limit < 1 || limit > 1000) {
throw new AwsException("InvalidParameterException", "maxResults must be between 1 and 1000", 400);
}
String namespace = "ListImages:" + region + ":" + effectiveAccount(registryId) + ":" + repositoryName;
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName);
try {
RegistryHttpClient http = registryManager.httpClient();
List<String> tags = http.listTags(internal);
List<ImageIdentifier> out = new ArrayList<>();
for (String tag : tags) {
String digest = http.headManifestDigest(internal, tag, null);
out.add(new ImageIdentifier(tag, digest));
}
return out;
} catch (Exception e) {
PaginatedResult<String> page = Pagination.paginate(http.listTags(internal), Function.identity(),
limit, nextToken, namespace,
token -> new AwsException("InvalidParameterException", "Invalid nextToken", 400));
return new PaginatedResult<>(imageIdentifiers(http, internal, page.items()), page.nextToken());
} catch (IOException | InterruptedException e) {
LOG.warnv("ListImages registry query failed for {0}: {1}", repositoryName, e.getMessage());
return List.of();
return new PaginatedResult<>(List.of(), null);
}
}
private static List<ImageIdentifier> imageIdentifiers(RegistryHttpClient http, String internal, List<String> tags)
throws IOException, InterruptedException {
List<ImageIdentifier> identifiers = new ArrayList<>();
for (String tag : tags) {
identifiers.add(new ImageIdentifier(tag, http.headManifestDigest(internal, tag, null)));
}
return identifiers;
}
public DescribeImagesResult describeImages(String repositoryName,
List<ImageIdentifier> requested,
String registryId,
@@ -0,0 +1,269 @@
package io.github.hectorvent.floci.services.ecr;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecr.EcrClient;
import software.amazon.awssdk.services.ecr.model.InvalidParameterException;
import software.amazon.awssdk.services.ecr.model.ListImagesResponse;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@QuarkusTest
class EcrListImagesPaginationIntegrationTest {
private static final String ACCOUNT = "741650100001";
private static final Region REGION = Region.EU_CENTRAL_1;
private static final String DIGEST = "sha256:" + "a".repeat(64);
@InjectMock
EcrRegistryManager registryManager;
@Inject
StorageFactory storageFactory;
@Inject
ObjectMapper mapper;
private final Map<String, String> images = new ConcurrentHashMap<>();
private final List<SeededRepository> repositories = new ArrayList<>();
private final AtomicInteger manifestHeads = new AtomicInteger();
private HttpServer registry;
private EcrClient client;
private String repository;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void setUp() throws IOException {
registry = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
registry.createContext("/v2/", this::registryRequest);
registry.start();
when(registryManager.tryEnsureStarted()).thenReturn(true);
when(registryManager.httpClient()).thenReturn(new RegistryHttpClient(
"http://127.0.0.1:" + registry.getAddress().getPort()));
when(registryManager.internalRepoName(anyString(), anyString(), anyString()))
.thenAnswer(call -> call.getArgument(0) + "/" + call.getArgument(1) + "/" + call.getArgument(2));
when(registryManager.getRepositoryUri(anyString(), anyString(), anyString()))
.thenAnswer(call -> "localhost:4566/" + call.getArgument(2));
client = client(REGION);
repository = createRepository(client, REGION);
}
@AfterEach
void cleanUp() {
AccountAwareStorageBackend<Repository> store = storageFactory.create("ecr", "repositories.json",
new TypeReference<Map<String, Repository>>() {});
repositories.forEach(repo -> store.deleteForAccount(ACCOUNT,
repo.region().id() + "::" + ACCOUNT + "::" + repo.name()));
if (client != null) {
client.close();
}
if (registry != null) {
registry.stop(0);
}
}
@Test
void sdkPagesDistinctTagsEvenWhenTheyShareTheSameDigest() {
seed(3);
ListImagesResponse first = client.listImages(request -> request.repositoryName(repository).maxResults(1));
assertEquals(List.of("tag-000"), tags(first));
assertNotNull(first.nextToken());
ListImagesResponse second = client.listImages(request -> request.repositoryName(repository).registryId(ACCOUNT)
.maxResults(1).nextToken(first.nextToken()));
assertEquals(List.of("tag-001"), tags(second));
assertNotNull(second.nextToken());
ListImagesResponse last = client.listImages(request -> request.repositoryName(repository)
.maxResults(1).nextToken(second.nextToken()));
assertEquals(List.of("tag-002"), tags(last));
assertNull(last.nextToken());
assertEquals(List.of("tag-000", "tag-001", "tag-002"), client.listImagesPaginator(request -> request
.repositoryName(repository).maxResults(2)).imageIds().stream().map(image -> image.imageTag()).toList());
assertTrue(first.imageIds().stream().allMatch(image -> DIGEST.equals(image.imageDigest())));
}
@Test
void sdkUsesTheHundredItemDefaultAndAcceptsTheThousandItemMaximum() {
seed(101);
ListImagesResponse first = client.listImages(request -> request.repositoryName(repository));
assertEquals(100, first.imageIds().size());
assertNotNull(first.nextToken());
ListImagesResponse last = client.listImages(request -> request.repositoryName(repository)
.nextToken(first.nextToken()));
assertEquals(1, last.imageIds().size());
assertNull(last.nextToken());
assertEquals(101, client.listImages(request -> request.repositoryName(repository)
.maxResults(1000)).imageIds().size());
}
@Test
void sdkFetchesOnlyTheDigestsOnEachReturnedPage() {
seed(3);
ListImagesResponse first = client.listImages(request -> request.repositoryName(repository).maxResults(1));
assertEquals(1, manifestHeads.get());
assertNotNull(first.nextToken());
ListImagesResponse second = client.listImages(request -> request.repositoryName(repository)
.maxResults(1).nextToken(first.nextToken()));
assertEquals(List.of("tag-001"), tags(second));
assertEquals(2, manifestHeads.get());
}
@Test
void sdkRejectsInvalidTokensWithoutFetchingDigests() {
seed(3);
assertThrows(InvalidParameterException.class,
() -> client.listImages(request -> request.repositoryName(repository).nextToken("%%%%")));
assertEquals(0, manifestHeads.get());
}
@ParameterizedTest
@ValueSource(ints = {-1, 0, 1001})
void sdkRejectsInvalidPageSizes(int maxResults) {
assertEquals(400, assertThrows(InvalidParameterException.class,
() -> client.listImages(request -> request.repositoryName(repository).maxResults(maxResults))).statusCode());
}
@ParameterizedTest
@ValueSource(strings = {"not-a-token", "%%%%"})
void sdkRejectsMalformedTokens(String token) {
assertEquals(400, assertThrows(InvalidParameterException.class,
() -> client.listImages(request -> request.repositoryName(repository).nextToken(token))).statusCode());
}
@Test
void sdkRejectsTokensFromAnotherRepositoryOrRegion() {
seed(2);
String token = client.listImages(request -> request.repositoryName(repository).maxResults(1)).nextToken();
assertNotNull(token);
String otherRepository = createRepository(client, REGION);
assertEquals(400, assertThrows(InvalidParameterException.class,
() -> client.listImages(request -> request.repositoryName(otherRepository).nextToken(token))).statusCode());
try (EcrClient otherRegion = client(Region.EU_WEST_1)) {
otherRegion.createRepository(request -> request.repositoryName(repository));
repositories.add(new SeededRepository(Region.EU_WEST_1, repository));
assertEquals(400, assertThrows(InvalidParameterException.class,
() -> otherRegion.listImages(request -> request.repositoryName(repository).nextToken(token))).statusCode());
}
}
@Test
void sdkResumesAfterADeletedTagWithoutSkippingTheNextTag() {
seed(3);
ListImagesResponse first = client.listImages(request -> request.repositoryName(repository).maxResults(1));
assertEquals(List.of("tag-000"), tags(first));
assertNotNull(first.nextToken());
images.remove("tag-000");
ListImagesResponse last = client.listImages(request -> request.repositoryName(repository)
.maxResults(2).nextToken(first.nextToken()));
assertEquals(List.of("tag-001", "tag-002"), tags(last));
assertNull(last.nextToken());
}
@Test
void sdkReturnsAnEmptyPageWithoutAToken() {
ListImagesResponse response = client.listImages(request -> request.repositoryName(repository));
assertTrue(response.imageIds().isEmpty());
assertNull(response.nextToken());
}
@ParameterizedTest
@ValueSource(strings = {"\"maxResults\":4294967297", "\"maxResults\":1.5", "\"maxResults\":\"1\"",
"\"nextToken\":{}", "\"nextToken\":[]"})
void httpRejectsMalformedPaginationFields(String field) {
given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921.ListImages")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ "/20261025/" + REGION.id() + "/ecr/aws4_request")
.contentType("application/x-amz-json-1.1")
.body("{\"repositoryName\":\"" + repository + "\",\"registryId\":\"" + ACCOUNT + "\"," + field + "}")
.post("/").then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
}
private String createRepository(EcrClient api, Region region) {
String name = "page-" + UUID.randomUUID();
api.createRepository(request -> request.repositoryName(name));
repositories.add(new SeededRepository(region, name));
return name;
}
private void seed(int count) {
IntStream.range(0, count).forEach(index -> images.put("tag-%03d".formatted(index), DIGEST));
}
private void registryRequest(HttpExchange exchange) throws IOException {
try (exchange) {
String path = exchange.getRequestURI().getPath();
if ("GET".equals(exchange.getRequestMethod())) {
Map<String, Object> body = path.endsWith("/tags/list")
? Map.of("tags", images.keySet().stream().sorted(Comparator.reverseOrder()).toList())
: Map.of("repositories", List.of());
byte[] bytes = mapper.writeValueAsBytes(body);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
} else {
manifestHeads.incrementAndGet();
String digest = images.get(path.substring(path.lastIndexOf('/') + 1));
if (digest != null) {
exchange.getResponseHeaders().set("Docker-Content-Digest", digest);
}
exchange.sendResponseHeaders(digest != null ? 200 : 404, -1);
}
}
}
private static List<String> tags(ListImagesResponse response) {
return response.imageIds().stream().map(image -> image.imageTag()).toList();
}
private static EcrClient client(Region region) {
return EcrClient.builder().endpointOverride(URI.create("http://localhost:" + RestAssured.port))
.httpClientBuilder(UrlConnectionHttpClient.builder()).region(region)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(ACCOUNT, "test")))
.build();
}
private record SeededRepository(Region region, String name) {}
}
@@ -404,7 +404,7 @@ class EcrServiceTest {
when(registryManager.tryEnsureStarted()).thenReturn(false);
assertEquals("ServerException",
assertThrows(AwsException.class, () -> service.listImages(REPO, null, REGION)).getErrorCode());
assertThrows(AwsException.class, () -> service.listImages(REPO, null, REGION, null, null)).getErrorCode());
assertEquals("ServerException",
assertThrows(AwsException.class,
() -> service.describeImages(REPO, null, null, REGION)).getErrorCode());
@@ -639,7 +639,7 @@ class EcrServiceTest {
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
List<ImageIdentifier> imageIds = service.listImages(repositoryName, null, REGION);
List<ImageIdentifier> imageIds = service.listImages(repositoryName, null, REGION, null, null).items();
assertEquals(1, imageIds.size());
assertEquals(tag, imageIds.get(0).getImageTag());
assertEquals(digest, imageIds.get(0).getImageDigest());
@@ -693,7 +693,7 @@ class EcrServiceTest {
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
List<ImageIdentifier> imageIds = service.listImages(repositoryName, null, REGION);
List<ImageIdentifier> imageIds = service.listImages(repositoryName, null, REGION, null, null).items();
assertEquals(1, imageIds.size());
assertEquals(tag, imageIds.get(0).getImageTag());
assertEquals(digest, imageIds.get(0).getImageDigest());
@@ -758,7 +758,7 @@ class EcrServiceTest {
.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);
List<ImageIdentifier> ids = service.listImages(repositoryName, null, REGION, null, null).items();
assertEquals(1, ids.size());
assertEquals(tag, ids.get(0).getImageTag());
assertEquals(digest, ids.get(0).getImageDigest());
@@ -831,7 +831,7 @@ class EcrServiceTest {
// 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);
List<ImageIdentifier> ids = service.listImages(repositoryName, ACCOUNT, REGION, null, null).items();
assertTrue(ids.isEmpty(),
"bare entry owned by another account must not resolve for this scope");
}
@@ -488,6 +488,7 @@ class EcrRegistryDataPlaneTest {
void aWriteResetDuringTheTagCheckNeverReachesTheRegistryAndFreesTheTag() throws Exception {
AtomicReference<HttpServerRequest> heldCheck = new AtomicReference<>();
CountDownLatch checkArrived = new CountDownLatch(1);
CountDownLatch tagReleased = new CountDownLatch(1);
AtomicInteger manifestWrites = new AtomicInteger();
AtomicReference<String> manifestBody = new AtomicReference<>();
HttpServer registry = vertx.createHttpServer()
@@ -515,7 +516,7 @@ class EcrRegistryDataPlaneTest {
HttpServer dataPlane = null;
HttpClient client = null;
try {
dataPlane = dataPlane(registry, true);
dataPlane = dataPlane(registry, true, tagReleased);
client = vertx.createHttpClient(new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(false));
@@ -532,9 +533,8 @@ class EcrRegistryDataPlaneTest {
assertTrue(checkArrived.await(5, TimeUnit.SECONDS), "the data plane checks the tag first");
write.reset();
// A PING answered after the reset means the data plane has read the reset first.
write.connection().ping(Buffer.buffer("12345678"))
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
assertTrue(tagReleased.await(2, TimeUnit.SECONDS),
"the reset releases the tag while its registry check is still blocked");
heldCheck.get().response().setStatusCode(404).end();
assertEquals(201, putManifest(dataPlane.actualPort()).statusCode());
@@ -557,6 +557,10 @@ class EcrRegistryDataPlaneTest {
* us-east-1 is stored as {@code legacy/platform-api}, with immutable tags when asked.
*/
private HttpServer dataPlane(HttpServer registry, boolean immutableTags) throws Exception {
return dataPlane(registry, immutableTags, null);
}
private HttpServer dataPlane(HttpServer registry, boolean immutableTags, CountDownLatch tagReleased) throws Exception {
EcrRegistryManager registryManager = Mockito.mock(EcrRegistryManager.class);
EcrService ecrService = Mockito.mock(EcrService.class);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
@@ -569,7 +573,13 @@ class EcrRegistryDataPlaneTest {
// The tag lock lives in EcrService, so the mock holds a real one.
Set<String> heldTags = ConcurrentHashMap.newKeySet();
when(ecrService.claimImmutableTag(anyString())).thenAnswer(call -> heldTags.add(call.getArgument(0)));
Mockito.doAnswer(call -> heldTags.remove(call.getArgument(0)))
Mockito.doAnswer(call -> {
boolean removed = heldTags.remove(call.getArgument(0));
if (removed && tagReleased != null) {
tagReleased.countDown();
}
return null;
})
.when(ecrService).releaseImmutableTag(anyString());
when(ecrService.registryRepositoryName("platform/api", "000000000000", "us-east-1"))
.thenReturn("legacy/platform-api");