diff --git a/docs/services/ecr.md b/docs/services/ecr.md index 38fea8849a..cc0f584f77 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -23,7 +23,7 @@ | `DescribeRepositories` | Page 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 paginated tags and digests in a repository | +| `ListImages` | Enumerate paginated tags and digests in a repository, tagged and untagged, filtered by `tagStatus` | | `DescribeImages` | Image metadata: digest, size, push timestamp, manifest media type | | `BatchGetImage` | Fetch image manifests, honoring `acceptedMediaTypes` | | `BatchDeleteImage` | Delete images by tag or digest; a tag delete removes only that tag | @@ -60,8 +60,18 @@ or change the registry's blob upload behavior. `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. +local pages use stable tag order. `ListImages` and `DescribeImages` also list untagged +images by digest, taken from the recorded pushes, and honour `filter.tagStatus` +(`TAGGED`, `UNTAGGED` or `ANY`). `ANY` and `UNTAGGED` cost one manifest HEAD per tag while +an untagged digest is recorded. With explicit `imageIds`, `DescribeImages` returns the +requested images and does not apply `tagStatus`, because telling tagged from untagged for +an explicit id would need the same walk of every tag. A registry error fails the call +instead of returning an empty list. + +`ListImages` and `DescribeImages` requests are checked against the vendored model: an +empty `imageIds` list, an unknown `tagStatus` or `imageStatus`, or a missing `repositoryName` +is refused with the model's message, as AWS does. `imageStatus` and `DescribeImages`' +`maxResults` and `nextToken` are accepted but not applied. ### Admin Endpoints diff --git a/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java b/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java index 3528526738..455cb6e493 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java @@ -55,7 +55,8 @@ public class EcrJsonHandler { "PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration", "BatchGetRepositoryScanningConfiguration", "CreateRepositoryCreationTemplate", "UpdateRepositoryCreationTemplate", - "DescribeRepositoryCreationTemplates", "DeleteRepositoryCreationTemplate"); + "DescribeRepositoryCreationTemplates", "DeleteRepositoryCreationTemplate", + "ListImages", "DescribeImages"); public Response handle(String action, JsonNode request, String region) { if (MODEL_CHECKED.contains(action)) { @@ -356,7 +357,7 @@ public class EcrJsonHandler { } Integer maxResults = request.hasNonNull("maxResults") ? limit.asInt() : null; PaginatedResult page = service.listImages(repo, registryId, region, - maxResults, request.path("nextToken").asText(null)); + maxResults, request.path("nextToken").asText(null), tagStatus(request)); ObjectNode response = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); @@ -370,12 +371,17 @@ public class EcrJsonHandler { return Response.ok(response).build(); } + private static String tagStatus(JsonNode request) { + return request.path("filter").path("tagStatus").asText(null); + } + private Response handleDescribeImages(JsonNode request, String region) { String repo = request.path("repositoryName").asText(null); String registryId = request.path("registryId").asText(null); List requested = parseImageIds(request.path("imageIds")); - EcrService.DescribeImagesResult result = service.describeImages(repo, requested, registryId, region); + EcrService.DescribeImagesResult result = service.describeImages(repo, requested, registryId, region, + tagStatus(request)); ObjectNode response = objectMapper.createObjectNode(); ArrayNode details = objectMapper.createArrayNode(); diff --git a/src/main/java/io/floci/aws/services/ecr/EcrService.java b/src/main/java/io/floci/aws/services/ecr/EcrService.java index 27ae304912..28e2f16c76 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrService.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrService.java @@ -740,39 +740,94 @@ public class EcrService implements ResourceProvider, Resettable { public PaginatedResult listImages(String repositoryName, String registryId, String region, Integer maxResults, String nextToken) { + return listImages(repositoryName, registryId, region, maxResults, nextToken, null); + } + + public PaginatedResult listImages(String repositoryName, String registryId, String region, + Integer maxResults, String nextToken, String tagStatus) { + String status = normalizeTagStatus(tagStatus); 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; + String namespace = "ListImages:" + region + ":" + effectiveAccount(registryId) + ":" + repositoryName + + ":" + status; Repository repo = requireRepo(repositoryName, registryId, region); requireRegistry(); String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName); - try { + return callRegistry(() -> { RegistryHttpClient http = registryManager.httpClient(); - PaginatedResult page = Pagination.paginate(http.listTags(internal), Function.identity(), - limit, nextToken, namespace, + PaginatedResult page = Pagination.paginate( + imageReferences(http, repo.getRegistryId(), region, repositoryName, internal, status), + 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 new PaginatedResult<>(List.of(), null); - } + }, EcrService::registryUnavailable); } - private static List imageIdentifiers(RegistryHttpClient http, String internal, List tags) + /** A reference naming an untagged image is its digest; a tag cannot contain a colon, so the two never clash. */ + private static boolean isDigestReference(String reference) { + return reference.startsWith("sha256:"); + } + + private static List imageIdentifiers(RegistryHttpClient http, String internal, List refs) throws IOException, InterruptedException { List identifiers = new ArrayList<>(); - for (String tag : tags) { - identifiers.add(new ImageIdentifier(tag, http.headManifestDigest(internal, tag, null))); + for (String ref : refs) { + identifiers.add(isDigestReference(ref) + ? new ImageIdentifier(null, ref) + : new ImageIdentifier(ref, http.headManifestDigestStrict(internal, ref, null))); } return identifiers; } + /** The {@code tagStatus} filter, already checked against the model by the handler; absent means {@code ANY}. */ + private static String normalizeTagStatus(String tagStatus) { + return tagStatus == null ? "ANY" : tagStatus; + } + + /** + * What an enumeration of a repository's images walks: the tags, then the digests of the untagged + * images, as the filter asks. The registry lists only tags, so untagged digests come from the + * push records, minus every digest a tag resolves to. The registry has no tag-to-digest lookup, so + * ANY and UNTAGGED pay one HEAD per tag whenever a recorded digest is still unaccounted for (a + * re-pushed tag leaves its old digest recorded); TAGGED pays none. The page of results itself is + * resolved afterwards. + */ + private List imageReferences(RegistryHttpClient http, String account, String region, + String repositoryName, String internal, String status) + throws IOException, InterruptedException { + List tags = http.listTagsStrict(internal); + List refs = new ArrayList<>(); + if (!status.equals("UNTAGGED")) { + refs.addAll(tags); + } + if (!status.equals("TAGGED")) { + Set candidates = recordedDigests(account, region, repositoryName); + for (String tag : tags) { + if (candidates.isEmpty()) { + break; + } + candidates.remove(http.headManifestDigestStrict(internal, tag, null)); + } + refs.addAll(heldDigests(http, internal, candidates, Integer.MAX_VALUE)); + } + return refs; + } + public DescribeImagesResult describeImages(String repositoryName, List requested, String registryId, String region) { + return describeImages(repositoryName, requested, registryId, region, null); + } + + public DescribeImagesResult describeImages(String repositoryName, + List requested, + String registryId, + String region, + String tagStatus) { + String status = normalizeTagStatus(tagStatus); Repository repo = requireRepo(repositoryName, registryId, region); requireRegistry(); String internal = resolveRegistryRepoName(repo.getRegistryId(), region, repositoryName); @@ -780,11 +835,9 @@ public class EcrService implements ResourceProvider, Resettable { List refs = new ArrayList<>(); if (requested == null || requested.isEmpty()) { - try { - refs.addAll(http.listTags(internal)); - } catch (Exception e) { - LOG.warnv("DescribeImages tag enumeration failed for {0}: {1}", repositoryName, e.getMessage()); - } + refs.addAll(callRegistry( + () -> imageReferences(http, repo.getRegistryId(), region, repositoryName, internal, status), + EcrService::registryUnavailable)); } else { for (ImageIdentifier id : requested) { if (id.getImageTag() != null) refs.add(id.getImageTag()); @@ -1978,6 +2031,27 @@ public class EcrService implements ResourceProvider, Resettable { */ private boolean holdsImage(String account, String region, String repositoryName, String internal) throws IOException, InterruptedException { + return !heldDigests(registryManager.httpClient(), internal, + recordedDigests(account, region, repositoryName), 1).isEmpty(); + } + + /** The first {@code limit} candidates whose manifest the registry still holds. */ + private static List heldDigests(RegistryHttpClient http, String internal, Set candidates, + int limit) throws IOException, InterruptedException { + List held = new ArrayList<>(); + for (String digest : candidates) { + if (held.size() == limit) { + break; + } + if (http.headManifestDigestStrict(internal, digest, null) != null) { + held.add(digest); + } + } + return held; + } + + /** Digests the push records and the pending pushes name for one repository; candidates, not proof. */ + private Set recordedDigests(String account, String region, String repositoryName) { String metaPrefix = key(region, account, repositoryName) + "::"; Set digests = new LinkedHashSet<>(); synchronized (imageMetaStore) { @@ -1988,12 +2062,7 @@ public class EcrService implements ResourceProvider, Resettable { } }); } - for (String digest : digests) { - if (registryManager.httpClient().headManifestDigestStrict(internal, digest, null) != null) { - return true; - } - } - return false; + return digests; } /** diff --git a/src/main/resources/aws/ecr-request-shapes.json b/src/main/resources/aws/ecr-request-shapes.json index 4088eca93e..5eb1e36b12 100644 --- a/src/main/resources/aws/ecr-request-shapes.json +++ b/src/main/resources/aws/ecr-request-shapes.json @@ -20,7 +20,9 @@ "CreateRepositoryCreationTemplate": "CreateRepositoryCreationTemplateRequest", "UpdateRepositoryCreationTemplate": "UpdateRepositoryCreationTemplateRequest", "DescribeRepositoryCreationTemplates": "DescribeRepositoryCreationTemplatesRequest", - "DeleteRepositoryCreationTemplate": "DeleteRepositoryCreationTemplateRequest" + "DeleteRepositoryCreationTemplate": "DeleteRepositoryCreationTemplateRequest", + "ListImages": "ListImagesRequest", + "DescribeImages": "DescribeImagesRequest" }, "shapes": { "AccountSettingName": { @@ -85,6 +87,27 @@ "principalArn": "PrincipalArn" } }, + "DescribeImagesFilter": { + "type": "structure", + "members": { + "tagStatus": "TagStatus", + "imageStatus": "ImageStatusFilter" + } + }, + "DescribeImagesRequest": { + "type": "structure", + "required": [ + "repositoryName" + ], + "members": { + "registryId": "RegistryId", + "repositoryName": "RepositoryName", + "imageIds": "ImageIdentifierList", + "nextToken": "NextToken", + "maxResults": "MaxResults", + "filter": "DescribeImagesFilter" + } + }, "DescribeRegistryRequest": { "type": "structure", "members": {} @@ -132,6 +155,36 @@ "type": "structure", "members": {} }, + "ImageDigest": { + "type": "string" + }, + "ImageIdentifier": { + "type": "structure", + "members": { + "imageDigest": "ImageDigest", + "imageTag": "ImageTag" + } + }, + "ImageIdentifierList": { + "type": "list", + "min": 1, + "max": 100, + "member": "ImageIdentifier" + }, + "ImageStatusFilter": { + "type": "string", + "enum": [ + "ACTIVE", + "ARCHIVED", + "ACTIVATING", + "ANY" + ] + }, + "ImageTag": { + "type": "string", + "min": 1, + "max": 300 + }, "ImageTagMutability": { "type": "string", "enum": [ @@ -181,6 +234,26 @@ "min": 0, "max": 30720 }, + "ListImagesFilter": { + "type": "structure", + "members": { + "tagStatus": "TagStatus", + "imageStatus": "ImageStatusFilter" + } + }, + "ListImagesRequest": { + "type": "structure", + "required": [ + "repositoryName" + ], + "members": { + "registryId": "RegistryId", + "repositoryName": "RepositoryName", + "nextToken": "NextToken", + "maxResults": "MaxResults", + "filter": "ListImagesFilter" + } + }, "ListPullTimeUpdateExclusionsRequest": { "type": "structure", "members": { @@ -454,6 +527,14 @@ "type": "list", "member": "Tag" }, + "TagStatus": { + "type": "string", + "enum": [ + "TAGGED", + "UNTAGGED", + "ANY" + ] + }, "TagValue": { "type": "string" }, diff --git a/src/test/java/io/floci/aws/services/ecr/EcrListImagesPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/ecr/EcrListImagesPaginationIntegrationTest.java index d7e5bdeb62..46e9e1f29c 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrListImagesPaginationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrListImagesPaginationIntegrationTest.java @@ -25,12 +25,15 @@ 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.ImageDetail; import software.amazon.awssdk.services.ecr.model.InvalidParameterException; import software.amazon.awssdk.services.ecr.model.ListImagesResponse; +import software.amazon.awssdk.services.ecr.model.TagStatus; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -56,6 +59,7 @@ 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); + private static final String UNTAGGED_DIGEST = "sha256:" + "b".repeat(64); @InjectMock EcrRegistryManager registryManager; @@ -63,6 +67,8 @@ class EcrListImagesPaginationIntegrationTest { StorageFactory storageFactory; @Inject ObjectMapper mapper; + @Inject + EcrService ecrService; private final Map images = new ConcurrentHashMap<>(); private final List repositories = new ArrayList<>(); @@ -202,6 +208,23 @@ class EcrListImagesPaginationIntegrationTest { assertNull(last.nextToken()); } + @Test + void sdkListsAnUntaggedImageByDigestAndFiltersByTagStatus() { + seed(1); + images.put(UNTAGGED_DIGEST, UNTAGGED_DIGEST); + ecrService.recordImagePush(ACCOUNT, REGION.id(), repository, DIGEST, Instant.now()); + ecrService.recordImagePush(ACCOUNT, REGION.id(), repository, UNTAGGED_DIGEST, Instant.now()); + assertEquals(List.of(DIGEST + "/tag-000", UNTAGGED_DIGEST + "/null"), listed(null)); + assertEquals(List.of(DIGEST + "/tag-000", UNTAGGED_DIGEST + "/null"), listed(TagStatus.ANY)); + assertEquals(List.of(DIGEST + "/tag-000"), listed(TagStatus.TAGGED)); + assertEquals(List.of(UNTAGGED_DIGEST + "/null"), listed(TagStatus.UNTAGGED)); + List details = client.describeImages(request -> request.repositoryName(repository) + .filter(filter -> filter.tagStatus(TagStatus.UNTAGGED))).imageDetails(); + assertEquals(1, details.size()); + assertEquals(UNTAGGED_DIGEST, details.get(0).imageDigest()); + assertTrue(details.get(0).imageTags().isEmpty()); + } + @Test void sdkReturnsAnEmptyPageWithoutAToken() { ListImagesResponse response = client.listImages(request -> request.repositoryName(repository)); @@ -236,8 +259,17 @@ class EcrListImagesPaginationIntegrationTest { try (exchange) { String path = exchange.getRequestURI().getPath(); if ("GET".equals(exchange.getRequestMethod())) { + String reference = path.substring(path.lastIndexOf('/') + 1); + if (path.contains("/manifests/") && !images.containsKey(reference)) { + exchange.sendResponseHeaders(404, -1); + return; + } + if (path.contains("/manifests/")) { + exchange.getResponseHeaders().set("Docker-Content-Digest", images.get(reference)); + } Map body = path.endsWith("/tags/list") - ? Map.of("tags", images.keySet().stream().sorted(Comparator.reverseOrder()).toList()) + ? Map.of("tags", images.keySet().stream().filter(key -> !key.startsWith("sha256:")) + .sorted(Comparator.reverseOrder()).toList()) : Map.of("repositories", List.of()); byte[] bytes = mapper.writeValueAsBytes(body); exchange.getResponseHeaders().set("Content-Type", "application/json"); @@ -254,6 +286,16 @@ class EcrListImagesPaginationIntegrationTest { } } + private List listed(TagStatus status) { + return client.listImages(request -> { + request.repositoryName(repository); + if (status != null) { + request.filter(filter -> filter.tagStatus(status)); + } + }).imageIds().stream() + .map(image -> image.imageDigest() + "/" + image.imageTag()).sorted().toList(); + } + private static List tags(ListImagesResponse response) { return response.imageIds().stream().map(image -> image.imageTag()).toList(); } diff --git a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java index 0f8fd47f34..762b71d79b 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java @@ -1086,6 +1086,35 @@ class EcrServiceTest { } } + @Test + void aRegistryErrorFailsListAndDescribeImagesInsteadOfListingTaggedImagesAsUntagged() throws Exception { + RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class); + when(registryManager.httpClient()).thenReturn(http); + service.createRepository(REPO, null, null, null, null, null, null, REGION); + service.recordImagePush(ACCOUNT, REGION, REPO, DELETE_DIGEST, Instant.now()); + + // The tag listing fails while a recorded digest is present: the tagged image must not + // surface as untagged, so both operations fail instead of answering. + when(http.listTagsStrict(anyString())).thenThrow(new ConnectException("Connection refused")); + when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST); + // A manifest HEAD that fails for a tag fails the walk the same way. + Executable headFails = () -> { + Mockito.doReturn(List.of("release")).when(http).listTagsStrict(anyString()); + doThrow(new ConnectException("Connection refused")) + .when(http).headManifestDigestStrict(anyString(), anyString(), any()); + service.listImages(REPO, null, REGION, null, null, "ANY"); + }; + List calls = List.of( + () -> service.listImages(REPO, null, REGION, null, null, "UNTAGGED"), + () -> service.describeImages(REPO, null, null, REGION, "ANY"), + headFails); + for (int i = 0; i < calls.size(); i++) { + AwsException ex = assertThrows(AwsException.class, calls.get(i), "call " + i); + assertEquals("ServerException", ex.getErrorCode(), "call " + i); + assertEquals(500, ex.getHttpStatus(), "call " + i); + } + } + @Test void batchDeleteImageRefusesTheDeleteWhenTheTagListingFails() throws Exception { String repositoryName = "batch-delete/listing-fails"; diff --git a/tools/aws/regen_ecr_shapes.py b/tools/aws/regen_ecr_shapes.py index 39ea2ad8ca..c2a0bb0259 100644 --- a/tools/aws/regen_ecr_shapes.py +++ b/tools/aws/regen_ecr_shapes.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Vendor ECR request constraints from botocore's Apache-2.0 service model. -`EcrRequestShapes` checks the registry setting and repository creation template actions against +`EcrRequestShapes` checks the registry setting, repository creation template and image listing actions against the vendored file through the shared `RequestConstraintCheck`: member types, required members, lengths and counts, patterns and enum values, as the model states them. @@ -30,6 +30,7 @@ OPERATIONS = ( "BatchGetRepositoryScanningConfiguration", "CreateRepositoryCreationTemplate", "UpdateRepositoryCreationTemplate", "DescribeRepositoryCreationTemplates", "DeleteRepositoryCreationTemplate", + "ListImages", "DescribeImages", )