diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index ec6a1008d8..66e5cfb1a6 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -45,6 +45,7 @@ behind them yet. | `DescribePackageVersion` | Returns a package version's status, revision, and origin. | | `GetPackageVersionAsset` | Downloads one asset from a package version by name, optionally pinned to a specific revision. | | `ListPackageVersionAssets` | Lists the assets of a package version, with size and hashes. | +| `ListPackageVersions` | Lists a package's versions with status, revision, and origin, paginated and sorted most recently published first; `defaultDisplayVersion` is `dist-tags.latest` for npm, the most recently published version otherwise. | | `GetPackageVersionReadme` | Returns the readme text for a package version; `npm`, `pypi`, and `nuget` only, matching AWS's own restriction for this action. | | `CopyPackageVersions` | Copies one or more versions of a package from one repository to another in the same domain. | | `TagResource` | Adds or updates tags on a domain or repository ARN. | @@ -253,11 +254,12 @@ state. that is not the caller's own account looks up that account's domain/repository with no trust-policy or permissions-policy enforcement, consistent with Floci's IAM enforcement being opt-in elsewhere, but worth knowing if you rely on domain-sharing semantics. -- **Package management beyond publish/describe/get-asset/list-assets isn't implemented.** - `ListPackages`, `ListPackageVersions`, `DeletePackageVersions`, `DisposePackageVersions`, and +- **Package management beyond publish/describe/get-asset/list-assets/list-versions isn't + implemented.** `ListPackages`, `DeletePackageVersions`, `DisposePackageVersions`, and `UpdatePackageVersionsStatus` don't exist yet; the only way to move a version from `Unfinished` to `Published` today is a follow-up `PublishPackageVersion` call that omits the `unfinished` - flag. + flag. Every version `ListPackageVersions` reports is `Published` or `Unfinished` for this same + reason: nothing yet produces `Unlisted`, `Archived`, or `Disposed`. - **`CopyPackageVersions` has no full cross-call rollback on a mid-copy sidecar failure.** (`generic`, `maven`, `npm`, `pypi`, and `nuget` are all supported — matching real AWS, which places no `format` restriction on this action at all, unlike `PublishPackageVersion`'s own diff --git a/docs/services/index.md b/docs/services/index.md index 726755dbc9..851d1db247 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -124,7 +124,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Backup](backup.md) | `/backup-vaults/*`, `/logically-air-gapped-backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 35 | | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 | -| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 32 | +| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 33 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 27 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 | diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClient.java index 5a463150b3..f9f7421587 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClient.java @@ -13,8 +13,14 @@ import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -117,6 +123,110 @@ public class BagetterSidecarClient implements RepositorySidecarManager { return matchVersion(repositoryContainerId, packageName.toLowerCase(Locale.ROOT), version).isPresent(); } + /** + * {@link #listVersions} already gives every version BaGetter holds for this package; the only + * new work is a publish timestamp for each. BaGetter's flat container has none of its own + * (confirmed: {@code index.json} carries only the version strings), but its NuGet V3 + * Registration resource's {@code catalogEntry.published} does, confirmed live against a real + * container — read here purely as an internal data source for this one field, not by + * standing up a registration endpoint of Floci's own the way {@code CodeArtifactNuGetController} + * would (this class's own class-level documentation explains why that's deliberately never + * built for real NuGet clients to use). + */ + @Override + public List listPackageVersions(String repositoryContainerId, String domain, + String repository, String namespace, String packageName) { + String lowerId = packageName.toLowerCase(Locale.ROOT); + List versions = listVersions(repositoryContainerId, lowerId); + if (versions.isEmpty()) { + return List.of(); + } + Map published = registrationPublishedTimes(repositoryContainerId, lowerId); + List result = new ArrayList<>(); + for (String version : versions) { + result.add(new PackageVersionTimestamp(version, published.get(version))); + } + return result; + } + + /** + * Every version's {@code catalogEntry.published}, keyed by version string. The real NuGet V3 + * Registration resource splits a package with many versions across separate pages (each + * {@code items} entry carrying its own {@code @id} to fetch instead of an inline {@code + * items} array once a package has enough versions), so a page missing an inline {@code items} + * array is followed to its own {@code @id} rather than assumed to mean "no more versions" — + * even though BaGetter, a single small self-hosted feed, was never observed paginating this + * way for the handful of versions any test here publishes. + * + *

Keyed by {@link NuGetVersions#normalize}, not the raw {@code catalogEntry.version} text: + * {@link #listPackageVersions}'s caller looks entries up by the version {@link #listVersions} + * returns, which is itself normalized (lowercased, no leading zeros) from BaGetter's flat + * container resource. A raw-cased or non-normalized key here (e.g. {@code 1.0.0-Beta} instead + * of {@code 1.0.0-beta}) would simply never be found, losing that version's timestamp. + */ + private Map registrationPublishedTimes(String repositoryContainerId, String lowerId) { + Optional index = getJson(repositoryContainerId, "/v3/registration/" + + SidecarUriUtils.encodeSegment(lowerId) + "/index.json"); + if (index.isEmpty()) { + return Map.of(); + } + Map result = new LinkedHashMap<>(); + for (JsonNode page : index.get().path("items")) { + JsonNode items = page.path("items"); + if (!items.isArray()) { + String pageId = page.path("@id").asText(""); + items = pageId.isEmpty() ? null : getJsonAbsolute(pageId).map(p -> p.path("items")).orElse(null); + if (items == null) { + continue; + } + } + for (JsonNode entry : items) { + JsonNode catalogEntry = entry.path("catalogEntry"); + String version = catalogEntry.path("version").asText(""); + String publishedText = catalogEntry.path("published").asText(""); + if (version.isEmpty() || publishedText.isEmpty()) { + continue; + } + try { + result.put(NuGetVersions.normalize(version), OffsetDateTime.parse(publishedText).toInstant()); + } catch (DateTimeParseException e) { + // Leave unmapped: CodeArtifactService falls back to a deterministic tie-break + // rather than guessing a time from text that didn't parse. + } + } + } + return result; + } + + private Optional getJson(String repositoryContainerId, String encodedPath) { + String baseUrl = ensureReady(repositoryContainerId, null); + return getJsonAbsolute(baseUrl + encodedPath); + } + + private Optional getJsonAbsolute(String absoluteUrl) { + HttpRequest request = HttpRequest.newBuilder(URI.create(absoluteUrl)).timeout(Duration.ofSeconds(10)) + .GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofString()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the BaGetter sidecar at " + absoluteUrl, e); + } + if (response.statusCode() == 404) { + return Optional.empty(); + } + if (response.statusCode() != 200) { + throw new IllegalStateException("Could not reach the BaGetter sidecar at " + absoluteUrl + + ": upstream returned " + response.statusCode()); + } + try { + return Optional.of(mapper.readTree(response.body())); + } catch (Exception e) { + throw new IllegalStateException("Could not parse the BaGetter sidecar's response from " + absoluteUrl, + e); + } + } + /** * Deletes every version of the named package, confirmed against a live container. * diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java index f9dca03c84..f43536c83e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java @@ -452,6 +452,49 @@ public class CodeArtifactController { return ok(response); } + @POST + @Path("/v1/package/versions") + @Consumes(MediaType.WILDCARD) + public Response listPackageVersions(@Context HttpHeaders headers, @QueryParam("domain") String domain, + @QueryParam("domain-owner") String domainOwner, + @QueryParam("repository") String repository, + @QueryParam("format") String format, + @QueryParam("namespace") String namespace, + @QueryParam("package") String packageName, + @QueryParam("status") String status, + @QueryParam("sortBy") String sortBy, + @QueryParam("max-results") String maxResults, + @QueryParam("next-token") String nextToken, + @QueryParam("originType") String originType) { + String region = regionResolver.resolveRegion(headers); + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(region, domain, + domainOwner, repository, format, namespace, packageName, status, sortBy, + Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken, originType); + ObjectNode response = objectMapper.createObjectNode(); + if (result.defaultDisplayVersion() != null) { + response.put("defaultDisplayVersion", result.defaultDisplayVersion()); + } + response.put("format", result.format()); + if (result.namespace() != null) { + response.put("namespace", result.namespace()); + } + response.put("package", result.packageName()); + ArrayNode versions = response.putArray("versions"); + result.versions().forEach(summary -> { + ObjectNode node = versions.addObject(); + node.put("version", summary.version()); + node.put("revision", summary.revision()); + node.put("status", summary.status()); + ObjectNode origin = node.putObject("origin"); + origin.put("originType", "INTERNAL"); + origin.putObject("domainEntryPoint").put("repositoryName", repository); + }); + if (result.nextToken() != null) { + response.put("nextToken", result.nextToken()); + } + return ok(response); + } + @GET @Path("/v1/package/version/readme") public Response getPackageVersionReadme(@Context HttpHeaders headers, @QueryParam("domain") String domain, diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java index 51bb2cbddb..e3eaee5016 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java @@ -40,6 +40,7 @@ import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -90,6 +91,12 @@ public class CodeArtifactService implements Resettable { * than silently 404ing the way an unimplemented capability elsewhere here might. */ private static final Set README_FORMATS = Set.of("npm", "pypi", "nuget"); + /** The real {@code PackageVersionStatus} wire enum, confirmed against {@code service-2.json}. */ + private static final Set PACKAGE_VERSION_STATUSES = + Set.of("Published", "Unfinished", "Unlisted", "Archived", "Disposed", "Deleted"); + /** The real {@code PackageVersionOriginType} wire enum. Floci never ingests from an external + * connection, so every version {@link #listPackageVersions} ever reports is {@code INTERNAL}. */ + private static final Set ORIGIN_TYPES = Set.of("INTERNAL", "EXTERNAL", "UNKNOWN"); private static final Logger LOG = Logger.getLogger(CodeArtifactService.class); @@ -137,6 +144,14 @@ public class CodeArtifactService implements Resettable { public record AssetSummary(String name, long size, Map hashes) {} public record PackageVersionAssetsListResult(String format, String namespace, String packageName, String version, String versionRevision, List assets, String nextToken) {} + public record PackageVersionSummary(String version, String revision, String status) {} + public record ListPackageVersionsResult(String format, String namespace, String packageName, + String defaultDisplayVersion, List versions, String nextToken) {} + /** Internal working shape shared by the generic and container-backed branches of {@link + * #listPackageVersions} before status/origin filtering and pagination are applied. + * {@code publishedEpochSeconds} is {@code null} when nothing is known to order by. */ + private record PackageVersionEntry(String version, String revision, String status, + Long publishedEpochSeconds) {} public record AuthorizationToken(String token, long expirationEpochSeconds) {} public record AuthorizationTokenScope(String owner, String region) {} private record AuthorizationTokenRecord(String owner, String region, String domain, Instant expiration) {} @@ -883,6 +898,167 @@ public class CodeArtifactService implements Resettable { page.nextToken()); } + /** + * Lists every version of one package. For {@code generic}, reads straight from the stored + * {@link CodeArtifactPackageVersion} records {@link #genericPackageVersions} already groups by + * package; container-backed formats have no such record (same reason {@link + * #describePackageVersion} bridges them), so this reuses each sidecar's own new {@link + * RepositorySidecarManager#listPackageVersions}. + * + *

Existence follows the exact same rule {@link #describePackage} already uses (a version + * published somewhere, or an origin configuration set with {@link + * #putPackageOriginConfiguration} even with zero versions behind it), rather than + * {@code genericPackageVersions}/the sidecar's own list being empty on its own: a package + * origin-config'd but never published to genuinely exists with zero versions, which is an + * empty {@code versions} list here, not a 404, the same distinction {@code describePackage} + * already draws. + * + *

Real AWS returns every status by default ("Package versions of all statuses will be + * returned by default," the operation's own doc), but two of its own sibling actions' + * documentation names this exact operation as the one place {@code Archived} and {@code + * Disposed} versions are hidden unless the caller filters by that exact status + * (DeletePackageVersions: "Archived packages... don't show up with list package APIs (for + * example, ListPackageVersions)"; DisposePackageVersions: pass {@code status=Disposed} "to + * view all disposed package versions"). {@code Unlisted} stays included by default: its own + * status description only talks about exclusion from each format's own native package-manager + * listing (a different mechanism, never this management API). Resolved this way rather than + * guessed, since the two sibling pages directly contradict the general doc's "all statuses" + * line for exactly these two statuses. + * + *

{@code sortBy=PUBLISHED_TIME}, the only value {@code PackageVersionSortType} has, is + * always applied (most recently published first) regardless of whether the caller passes it: + * there is no other sort mode for an omitted value to mean instead. {@code originType} other + * than {@code INTERNAL} always answers empty: Floci has no external-connection ingestion for + * any format, so nothing it ever lists is {@code EXTERNAL} or {@code UNKNOWN}. + * + *

{@code defaultDisplayVersion} is computed over every {@code Published} version + * regardless of the {@code status}/{@code originType} filters applied to the returned {@code + * versions} page, the same way {@code describePackage}'s own fields aren't scoped by anything + * caller-supplied either: it represents the package's one real default, not a property of + * this particular request's filters. + */ + public ListPackageVersionsResult listPackageVersions(String region, String domain, String domainOwner, + String repository, String format, String namespace, String packageName, String status, String sortBy, + Integer maxResults, String nextToken, String originType) { + validatePackageCoordinates(format, namespace, packageName, "listing the versions of"); + requireNonBlank(domain, "domain"); + requireNonBlank(repository, "repository"); + if (status != null && !PACKAGE_VERSION_STATUSES.contains(status)) { + throw validation("status must be one of " + PACKAGE_VERSION_STATUSES + "."); + } + if (sortBy != null && !"PUBLISHED_TIME".equals(sortBy)) { + throw validation("sortBy must be PUBLISHED_TIME."); + } + if (originType != null && !ORIGIN_TYPES.contains(originType)) { + throw validation("originType must be one of " + ORIGIN_TYPES + "."); + } + String owner = effectiveOwner(domainOwner); + requireRepository(owner, repositoryKey(region, domain, repository), repository); + + String originKey = packageKey(region, domain, repository, format, namespace, packageName); + boolean hasOriginConfig = packageOriginConfigs.getForAccount(owner, originKey).isPresent(); + List entries; + String preferredDisplayVersion = null; + if (CONTAINER_BACKED_FORMATS.contains(format)) { + String repoId = ensureFormatContainerId(format, region, domain, owner, repository); + RepositorySidecarManager manager = sidecarRegistry.forFormat(format) + .orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, + "package")); + List raw; + try { + raw = manager.listPackageVersions(repoId, domain, repository, namespace, packageName); + } catch (UnsupportedOperationException e) { + throw new AwsException("InternalServerException", "Listing " + format + " package versions is not " + + "yet supported by this emulator.", 500); + } + if (raw.isEmpty() && !hasOriginConfig) { + throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); + } + entries = raw.stream() + .map(v -> new PackageVersionEntry(v.version(), + synthesizeContainerBackedRevision(format, repoId, namespace, packageName, v.version()), + "Published", v.publishedTime() == null ? null : v.publishedTime().getEpochSecond())) + .toList(); + preferredDisplayVersion = manager.preferredDisplayVersion(repoId, domain, repository, namespace, + packageName).orElse(null); + } else { + List versions = genericPackageVersions(region, domain, owner, repository, + format, namespace, packageName); + if (versions.isEmpty() && !hasOriginConfig) { + throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); + } + entries = versions.stream() + .map(pv -> new PackageVersionEntry(pv.getVersion(), pv.getRevision(), pv.getStatus(), + pv.getPublishedTime())) + .toList(); + } + + String preferredVersion = preferredDisplayVersion; + String defaultDisplayVersion = preferredVersion != null + && entries.stream().anyMatch(e -> e.version().equals(preferredVersion) + && "Published".equals(e.status())) + ? preferredVersion + : mostRecentlyPublishedVersion(entries); + + List matchingOrigin = originType != null && !"INTERNAL".equals(originType) + ? List.of() + : entries; + List filtered = status != null + ? matchingOrigin.stream().filter(e -> status.equals(e.status())).toList() + : matchingOrigin.stream() + .filter(e -> !"Archived".equals(e.status()) && !"Disposed".equals(e.status())) + .toList(); + + PaginatedResult page = Pagination.paginate(filtered, + CodeArtifactService::packageVersionSortCursor, maxResults, nextToken, 50, 1000, + "ValidationException"); + List summaries = page.items().stream() + .map(e -> new PackageVersionSummary(e.version(), e.revision(), e.status())) + .toList(); + return new ListPackageVersionsResult(format, namespace, packageName, defaultDisplayVersion, summaries, + page.nextToken()); + } + + /** + * {@link Pagination#paginate} always sorts ascending by this cursor, but {@code + * ListPackageVersions} is always most-recently-published-first (see {@link + * #listPackageVersions}'s own javadoc): the publish time is inverted into a fixed-width, + * zero-padded decimal so its own ascending string order is the descending time order this + * needs, with the version itself as a deterministic tie-break for two versions published in + * the same second (or, for a {@code generic} {@code Unfinished} version, two with no publish + * time at all). Fine as an opaque cursor: nothing ever decodes this value back into its parts, + * the same way every other paginated action here only ever compares whole tokens. + */ + private static String packageVersionSortCursor(PackageVersionEntry entry) { + long effectiveSeconds = entry.publishedEpochSeconds() == null ? 0 : entry.publishedEpochSeconds(); + return String.format("%020d:%s", Long.MAX_VALUE - effectiveSeconds, entry.version()); + } + + /** + * AWS documents Maven and PyPI's {@code defaultDisplayVersion} as simply "the most recently + * published package version," and this codebase's own research found no stated rule at all + * for {@code generic} or {@code nuget} — applying the same fallback to those two is the + * best-justified inference available, not an AWS-confirmed rule for them specifically. Only + * {@code Published} versions are eligible: an {@code Unfinished} one was never actually + * completed, so it can never be "the" default to show. {@code null} when nothing qualifies + * (every version is {@code Unfinished}). + * + *

Picks the first {@code Published} entry under {@link #packageVersionSortCursor}'s own + * ordering, rather than independently re-deriving "most recent" from the raw timestamp: a + * second tie-break computed here that disagreed with the cursor's could list one version + * first while naming a different one the default. Reusing the cursor also means a sidecar + * that could not supply a timestamp for any version (so every {@code publishedEpochSeconds} + * is {@code null}) still gets a deterministic default — whichever {@code Published} version + * the cursor's own tie-break puts first — instead of reporting none at all. + */ + private static String mostRecentlyPublishedVersion(List entries) { + return entries.stream() + .filter(e -> "Published".equals(e.status())) + .min(Comparator.comparing(CodeArtifactService::packageVersionSortCursor)) + .map(PackageVersionEntry::version) + .orElse(null); + } + /** * Unlike {@code GetPackageVersionAsset}, real CodeArtifact's {@code DescribePackageVersion} * response has no asset listing at all (confirmed against the wire model: {@code diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java index b7db78dc59..a0dcc7cdd3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java @@ -14,6 +14,9 @@ import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -137,6 +140,74 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { return packageFiles(baseUrl, packageName).stream().anyMatch(file -> file.version().equals(version)); } + /** + * pypiserver's own per-project JSON listing ({@link #packageFiles}'s source, read directly + * here by the {@code releases} map's own keys instead) has no timestamp field of its own + * (confirmed against a live container), so this follows each version's first listed file's + * download URL with a plain {@code HEAD} and reads the real {@code Last-Modified} response + * header it returns. Only one file per version needs checking: every file of the same release + * lands on disk within the same upload, close enough that picking "the first one" over "the + * most recently modified one" makes no practical difference, and the JSON listing gives no + * way to know which upload order they actually arrived in regardless. + */ + @Override + public List listPackageVersions(String repositoryContainerId, String domain, + String repository, String namespace, String packageName) { + String baseUrl = ensureReady(repositoryContainerId, null); + String normalized = normalizePackageName(packageName); + URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(normalized) + + "/json"); + HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofString()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the pypiserver sidecar to list versions of " + + packageName, e); + } + if (response.statusCode() == 404) { + return List.of(); + } + if (response.statusCode() != 200) { + throw new IllegalStateException("Could not list versions of " + packageName + " on the pypiserver " + + "sidecar: upstream returned " + response.statusCode()); + } + JsonNode releases; + try { + releases = mapper.readTree(response.body()).path("releases"); + } catch (Exception e) { + throw new IllegalStateException("Could not parse pypiserver's version listing for " + packageName, e); + } + List result = new ArrayList<>(); + releases.fieldNames().forEachRemaining(version -> { + JsonNode files = releases.path(version); + String fileUrl = files.isEmpty() ? "" : files.get(0).path("url").asText(""); + result.add(new PackageVersionTimestamp(version, fileUrl.isEmpty() ? null : lastModified(fileUrl))); + }); + return result; + } + + private Instant lastModified(String fileUrl) { + HttpRequest request = HttpRequest.newBuilder(URI.create(fileUrl)).timeout(Duration.ofSeconds(10)) + .method("HEAD", BodyPublishers.noBody()).build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.discarding()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the pypiserver sidecar to check " + fileUrl, e); + } + if (response.statusCode() != 200) { + return null; + } + return response.headers().firstValue("Last-Modified").flatMap(value -> { + try { + return Optional.of(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(value))); + } catch (DateTimeParseException e) { + return Optional.empty(); + } + }).orElse(null); + } + /** * Removes a whole package, every version at once, confirmed against a live container: the pinned * image's management endpoint ({@code POST /} with {@code :action=remove_pkg}) deletes one exact diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java index fba3c2e587..5f455c821f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java @@ -263,6 +263,78 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { return names; } + /** + * Enumerates every version directory beneath the artifact itself (the same {@code files} + * array {@link #listPackageVersionAssetNames} already reads one level down, here kept to its + * {@code DIRECTORY} entries, inverted from that method's own {@code FILE}-only filter), then + * asks each version's own details page (again the same endpoint {@link #packageVersionExists} + * already confirms existence through) for a representative publish time: the latest {@code + * lastModifiedTime} among its files, since a real {@code mvn deploy} writes the POM and the + * main artifact as two separate PUTs a moment apart and the later one is the more accurate + * "when this version became complete." A version directory with no {@code FILE} entries at + * all (never happens through a real deploy, but not assumed impossible) reports no timestamp + * rather than guessing one. + */ + @Override + public List listPackageVersions(String repositoryContainerId, String domain, + String repository, String namespace, String packageName) { + String baseUrl = manager.ensureReady(); + String artifactPath = "/api/maven/details" + packageDirectoryPath(repositoryContainerId, namespace, + packageName); + HttpRequest artifactRequest = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), + artifactPath)) + .timeout(Duration.ofSeconds(30)) + .header("Authorization", manager.basicAuthHeader()) + .GET() + .build(); + HttpResponse artifactResponse = send(artifactRequest, BodyHandlers.ofString()); + if (artifactResponse.statusCode() == 404) { + return List.of(); + } + if (artifactResponse.statusCode() != 200) { + throw new IllegalStateException("Could not list versions of " + packageName + " on the Reposilite " + + "sidecar: upstream returned " + artifactResponse.statusCode()); + } + List result = new ArrayList<>(); + for (JsonNode entry : readTree(artifactResponse.body()).path("files")) { + if (!"DIRECTORY".equals(entry.path("type").asText())) { + continue; + } + String version = entry.path("name").asText(); + result.add(new PackageVersionTimestamp(version, latestFileTimestamp(baseUrl, + versionDetailsPath(repositoryContainerId, namespace, packageName, version)))); + } + return result; + } + + private Instant latestFileTimestamp(String baseUrl, String versionDetailsPath) { + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), versionDetailsPath)) + .timeout(Duration.ofSeconds(30)) + .header("Authorization", manager.basicAuthHeader()) + .GET() + .build(); + HttpResponse response = send(request, BodyHandlers.ofString()); + if (response.statusCode() == 404) { + return null; + } + if (response.statusCode() != 200) { + throw new IllegalStateException("Could not read publish times for " + versionDetailsPath + " on the " + + "Reposilite sidecar: upstream returned " + response.statusCode()); + } + Instant latest = null; + for (JsonNode file : readTree(response.body()).path("files")) { + if (!"FILE".equals(file.path("type").asText()) || !file.has("lastModifiedTime")) { + continue; + } + double epochSeconds = file.path("lastModifiedTime").asDouble(); + Instant timestamp = Instant.ofEpochMilli(Math.round(epochSeconds * 1000.0)); + if (latest == null || timestamp.isAfter(latest)) { + latest = timestamp; + } + } + return latest; + } + /** * Writes {@code content} straight to this version's {@code assetName} path, for {@code * CopyPackageVersions}'s destination write. Unlike {@link #deployArtifact}, this never diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java index d81a0631ce..c834df723e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.codeartifact; +import java.time.Instant; import java.util.List; import java.util.Optional; @@ -190,4 +191,44 @@ public interface RepositorySidecarManager { default void recordVersionAvailable(String repositoryContainerId, String domain, String repository, String namespace, String packageName, String version) { } + + /** + * One version this sidecar holds for a package, paired with when it was published, for + * {@link #listPackageVersions}. {@code publishedTime} is {@code null} when this sidecar's own + * protocol has no timestamp for that version at all; {@code CodeArtifactService} then falls + * back to a deterministic tie-break (the version string itself) rather than treating it as + * more or less recent than any other version. + */ + record PackageVersionTimestamp(String version, Instant publishedTime) {} + + /** + * Every version this sidecar holds of the named package, for bridging {@code + * ListPackageVersions} when there is no generic-format record to list versions from, the same + * reason {@link #listPackageVersionAssetNames} exists for one version's own assets. Unlike + * that method, there is no existing "list everything under this package" primitive to lean + * on: each implementation needs its own new, format-specific enumeration. The default throws + * {@link UnsupportedOperationException}, the same convention {@link #deletePackage} already + * uses for a capability not every sidecar backs; every container-backed format's own client + * overrides this. + */ + default List listPackageVersions(String repositoryContainerId, String domain, + String repository, String namespace, String packageName) { + throw new UnsupportedOperationException(format() + " package versions cannot be listed through this " + + "sidecar"); + } + + /** + * This format's own preferred "default display" version for a package, independent of publish + * recency, for {@code ListPackageVersions}' {@code defaultDisplayVersion}. {@code empty()} by + * default: every sidecar Floci currently backs besides npm has no such separate preference of + * its own (AWS documents Maven and PyPI's default display version as simply "the most recently + * published package version," which {@code CodeArtifactService} already falls back to on an + * empty result here). {@code VerdaccioSidecarClient} overrides this: npm's own {@code + * dist-tags.latest} is exactly this preference, and AWS documents the same most-recently- + * published fallback for npm only when that tag isn't set. + */ + default Optional preferredDisplayVersion(String repositoryContainerId, String domain, String repository, + String namespace, String packageName) { + return Optional.empty(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/VerdaccioSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/VerdaccioSidecarClient.java index 71b37a9269..5939563930 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/VerdaccioSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/VerdaccioSidecarClient.java @@ -19,6 +19,9 @@ import java.net.http.HttpResponse.BodyHandlers; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Optional; @@ -114,6 +117,59 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { .orElse(false); } + /** + * Verdaccio's own packument already lists every version it holds, each keyed in the + * top-level {@code time} map by the same version string {@code versions} itself uses + * (confirmed live: it auto-populates this on every publish, even though Floci's own publish + * payload never sends one). A version present in {@code versions} but missing from {@code + * time} (never observed live, but not assumed impossible) reports no timestamp rather than + * guessing one; {@code time} also carries two non-version keys of its own ({@code created}, + * {@code modified}) that {@code versions} never does, so only looking a version up by that + * exact key, never iterating {@code time}'s own fields, keeps those two out of the result. + */ + @Override + public List listPackageVersions(String repositoryContainerId, String domain, + String repository, String namespace, String packageName) { + String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository)); + Optional document = fetchPackageDocument(baseUrl, namespace, packageName); + if (document.isEmpty()) { + return List.of(); + } + JsonNode time = document.get().path("time"); + List result = new ArrayList<>(); + document.get().path("versions").fieldNames().forEachRemaining(version -> { + String publishedText = time.path(version).asText(null); + Instant published = null; + if (publishedText != null) { + try { + published = Instant.parse(publishedText); + } catch (DateTimeParseException e) { + // Leave unset: CodeArtifactService falls back to a deterministic tie-break + // rather than guessing a time from text that didn't parse. + } + } + result.add(new PackageVersionTimestamp(version, published)); + }); + return result; + } + + /** + * npm's own {@code dist-tags.latest}, AWS's documented preference for npm's {@code + * defaultDisplayVersion} ahead of the most-recently-published fallback every other format + * uses. {@code empty()} both when the package doesn't exist and when it exists but carries no + * {@code latest} tag (a real npm publish always sets one, but an empty packument with no + * versions at all, reachable only via {@code PutPackageOriginConfiguration}, has none), + * letting {@code CodeArtifactService} fall back to the same most-recently-published rule in + * either case. + */ + @Override + public Optional preferredDisplayVersion(String repositoryContainerId, String domain, String repository, + String namespace, String packageName) { + String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository)); + return fetchPackageDocument(baseUrl, namespace, packageName) + .map(document -> document.path("dist-tags").path("latest").asText(null)); + } + /** * Removes a whole package, every version at once, the same way the real npm CLI's final * unpublish step does: fetch the packument for its current {@code _rev}, then {@code DELETE} the diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClientTest.java index d4b34ed4d4..3ba8da7cf2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClientTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/BagetterSidecarClientTest.java @@ -14,6 +14,7 @@ import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.net.http.HttpClient; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -23,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -273,6 +275,60 @@ class BagetterSidecarClientTest { assertTrue(result.isEmpty()); } + /** + * BaGetter's flat container (what {@link #respondWithVersions} fakes) always returns + * normalized, lowercased version strings, but its registration resource's {@code + * catalogEntry.version} keeps the original publish casing. A mixed-case prerelease like + * {@code 1.0.0-Beta} must still have its published time found when looked up by the + * flat-container's normalized {@code 1.0.0-beta}. + */ + @Test + void listPackageVersionsFindsAPublishedTimeForAMixedCasePrereleaseVersion() throws Exception { + BagetterSidecarManager manager = manager(); + seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl); + respondWithVersions("demo-pkg", "1.0.0-beta"); + respondWithRegistration("demo-pkg", "1.0.0-Beta", "2026-01-15T10:00:00.0000000+00:00"); + + List result = client(manager) + .listPackageVersions("nuget-repo-1", "dom", "repo", null, "demo-pkg"); + + assertEquals(1, result.size()); + assertEquals("1.0.0-beta", result.get(0).version()); + assertEquals(Instant.parse("2026-01-15T10:00:00Z"), result.get(0).publishedTime()); + } + + /** + * {@code getJsonAbsolute}'s 404-only "nothing there" handling must not also swallow a real + * upstream failure: an auth or server error on the registration resource must surface as an + * error, the same way a non-404 failure on the flat container already does elsewhere in this + * client, rather than silently reporting every version as having no publish time. + */ + @Test + void listPackageVersionsThrowsWhenTheRegistrationResourceFailsWithARealError() throws Exception { + BagetterSidecarManager manager = manager(); + seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl); + respondWithVersions("demo-pkg", "1.0.0"); + backend.createContext("/v3/registration/demo-pkg/index.json", exchange -> { + exchange.sendResponseHeaders(500, -1); + exchange.close(); + }); + + assertThrows(IllegalStateException.class, () -> client(manager) + .listPackageVersions("nuget-repo-1", "dom", "repo", null, "demo-pkg")); + } + + private void respondWithRegistration(String packageName, String version, String published) { + String json = "{\"items\":[{\"items\":[{\"catalogEntry\":{\"version\":\"" + version + "\",\"published\":\"" + + published + "\"}}]}]}"; + backend.createContext("/v3/registration/" + packageName + "/index.json", exchange -> { + byte[] bytes = json.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + exchange.close(); + }); + } + private void respondWithVersions(String packageName, String... versions) { String json = "{\"versions\":[" + String.join(",", java.util.Arrays.stream(versions).map(v -> "\"" + v + "\"").toArray(String[]::new)) + "]}"; diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java index 6a79c17e93..91660fb075 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java @@ -570,6 +570,26 @@ class CodeArtifactMavenDockerIntegrationTest { assertEquals(Digests.sha256Hex("real-jar-bytes".getBytes(StandardCharsets.UTF_8)), hashes.get("SHA-256")); } + /** + * Bridges to the same real Reposilite sidecar {@link #listPackageVersionAssetsBridgesToTheRealReposiliteSidecar} + * already confirmed holds {@code spike}'s {@code 1.0.0}, walking the artifact-level directory + * listing one level up from that test's own version directory. + */ + @Test + @Order(21) + void listPackageVersionsBridgesToTheRealReposiliteSidecar() { + given().header("Authorization", AUTH) + .post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=maven" + + "&namespace=com.example&package=spike") + .then().statusCode(200) + .body("package", equalTo("spike")) + .body("defaultDisplayVersion", equalTo("1.0.0")) + .body("versions.size()", equalTo(1)) + .body("versions[0].version", equalTo("1.0.0")) + .body("versions[0].status", equalTo("Published")) + .body("versions[0].origin.originType", equalTo("INTERNAL")); + } + /** * A throwaway groupId/artifactId, not {@link #GAV}: deleting it exercises Reposilite's real * directory delete (confirmed live before this was built: a single {@code DELETE} on the diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDockerIntegrationTest.java index ce84d2f396..0a19f9dae6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDockerIntegrationTest.java @@ -769,6 +769,26 @@ class CodeArtifactNpmDockerIntegrationTest { assertEquals(Digests.sha256Hex(expectedTarballBytes), hashes.get("SHA-256")); } + /** + * Bridges to the same real Verdaccio sidecar {@link #listPackageVersionAssetsBridgesToTheRealVerdaccioSidecar} + * already confirmed holds {@link #PACKAGE_NAME}'s {@code 1.0.0}, reading the packument's own + * {@code versions}/{@code time} maps instead of one version's {@code dist} entry. + */ + @Test + @Order(21) + void listPackageVersionsBridgesToTheRealVerdaccioSidecar() { + given().header("Authorization", AUTH) + .post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm" + + "&package=" + PACKAGE_NAME) + .then().statusCode(200) + .body("package", equalTo(PACKAGE_NAME)) + .body("defaultDisplayVersion", equalTo("1.0.0")) + .body("versions.size()", equalTo(1)) + .body("versions[0].version", equalTo("1.0.0")) + .body("versions[0].status", equalTo("Published")) + .body("versions[0].origin.originType", equalTo("INTERNAL")); + } + /** * Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method * named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNuGetDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNuGetDockerIntegrationTest.java index 85a5c14af5..0fbfa3f147 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNuGetDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNuGetDockerIntegrationTest.java @@ -461,6 +461,27 @@ class CodeArtifactNuGetDockerIntegrationTest { assertEquals(Digests.sha256Hex(nupkg), hashes.get("SHA-256")); } + /** + * Bridges to the same real BaGetter sidecar {@link #listPackageVersionAssetsBridgesToTheRealBagetterSidecar} + * already pushed {@code ListAssets.Package}'s {@link #VERSION} to, reading the flat + * container's {@code index.json} version list plus the NuGet V3 Registration resource's + * {@code catalogEntry.published} for ordering, instead of one version's own asset. + */ + @Test + @Order(16) + void listPackageVersionsBridgesToTheRealBagetterSidecar() { + given().header("Authorization", AUTH) + .post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget" + + "&package=ListAssets.Package") + .then().statusCode(200) + .body("package", equalTo("ListAssets.Package")) + .body("defaultDisplayVersion", equalTo(VERSION)) + .body("versions.size()", equalTo(1)) + .body("versions[0].version", equalTo(VERSION)) + .body("versions[0].status", equalTo("Published")) + .body("versions[0].origin.originType", equalTo("INTERNAL")); + } + private static long describeDomainAssetSizeBytes() { return given().header("Authorization", AUTH) .get("/v1/domain?domain=" + DOMAIN) diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiDockerIntegrationTest.java index 7ffa627260..9a9856553a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiDockerIntegrationTest.java @@ -651,6 +651,27 @@ class CodeArtifactPypiDockerIntegrationTest { assertEquals(Digests.sha256Hex(content), hashes.get("SHA-256")); } + /** + * Bridges to the same real pypiserver sidecar {@link #listPackageVersionAssetsBridgesToTheRealPypiserverSidecar} + * already uploaded {@code list-assets-pypi-pkg}'s {@code 1.0.0} to, reading the per-project + * JSON listing's {@code releases} keys plus a {@code HEAD} on the file's own URL for its + * publish time, instead of one release's file entries. + */ + @Test + @Order(19) + void listPackageVersionsBridgesToTheRealPypiserverSidecar() { + given().header("Authorization", AUTH) + .post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=pypi" + + "&package=list-assets-pypi-pkg") + .then().statusCode(200) + .body("package", equalTo("list-assets-pypi-pkg")) + .body("defaultDisplayVersion", equalTo("1.0.0")) + .body("versions.size()", equalTo(1)) + .body("versions[0].version", equalTo("1.0.0")) + .body("versions[0].status", equalTo("Published")) + .body("versions[0].origin.originType", equalTo("INTERNAL")); + } + /** * Proves the actual mechanism, not just that {@code PypiserverSidecarManager} has a method * named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java index 3ae13fe9f9..e6ce8a3332 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -32,6 +33,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -3251,6 +3253,273 @@ class CodeArtifactServiceTest { assertEquals("ValidationException", missingVersion.getErrorCode()); } + // ----------------------------------------------------- ListPackageVersions + + @Test + void listPackageVersionsReturnsEveryPublishedVersionForAGenericPackage() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8)); + publishGeneric("repo", "my-pkg", "2.0.0", "b".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg", null, null, null, null, null); + + assertEquals(2, result.versions().size()); + Set versions = result.versions().stream().map(CodeArtifactService.PackageVersionSummary::version) + .collect(Collectors.toSet()); + assertEquals(Set.of("1.0.0", "2.0.0"), versions); + result.versions().forEach(v -> assertEquals("Published", v.status())); + } + + @Test + void listPackageVersionsIncludesUnfinishedByDefaultButAnExplicitStatusFiltersExactly() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8)); + service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "2.0.0", "b.txt", + Digests.sha256Hex("b".getBytes(StandardCharsets.UTF_8)), "true", "b".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.ListPackageVersionsResult all = service.listPackageVersions(REGION, "dom", null, "repo", + "generic", "ns", "my-pkg", null, null, null, null, null); + assertEquals(2, all.versions().size()); + + CodeArtifactService.ListPackageVersionsResult publishedOnly = service.listPackageVersions(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg", "Published", null, null, null, null); + assertEquals(1, publishedOnly.versions().size()); + assertEquals("1.0.0", publishedOnly.versions().get(0).version()); + + CodeArtifactService.ListPackageVersionsResult unfinishedOnly = service.listPackageVersions(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg", "Unfinished", null, null, null, null); + assertEquals(1, unfinishedOnly.versions().size()); + assertEquals("2.0.0", unfinishedOnly.versions().get(0).version()); + } + + @Test + void listPackageVersionsFailsNotFoundForAGenericPackageThatWasNeverPublished() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg", null, null, null, null, null)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void listPackageVersionsReturnsAnEmptyListForAnOriginConfigOnlyPackage() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK", + "BLOCK"); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg", null, null, null, null, null); + + assertTrue(result.versions().isEmpty()); + assertEquals(null, result.defaultDisplayVersion()); + } + + @Test + void listPackageVersionsBridgesToReposiliteForMavenOrderedMostRecentFirstWithPagination() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)), + new RepositorySidecarManager.PackageVersionTimestamp("2.0", Instant.ofEpochSecond(2000)))); + + CodeArtifactService.ListPackageVersionsResult page1 = service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, 1, null, null); + assertEquals(1, page1.versions().size()); + assertEquals("2.0", page1.versions().get(0).version()); + assertEquals("Published", page1.versions().get(0).status()); + assertTrue(page1.versions().get(0).revision() != null && !page1.versions().get(0).revision().isBlank()); + assertEquals("2.0", page1.defaultDisplayVersion()); + assertTrue(page1.nextToken() != null); + + CodeArtifactService.ListPackageVersionsResult page2 = service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, 1, page1.nextToken(), null); + assertEquals(1, page2.versions().size()); + assertEquals("1.0", page2.versions().get(0).version()); + assertTrue(page2.nextToken() == null); + } + + /** + * A sidecar that could not supply a timestamp for any version (every {@code + * PackageVersionTimestamp.publishedTime} is {@code null}) must still report a deterministic + * default rather than omitting {@code defaultDisplayVersion} entirely: it should be whichever + * {@code Published} version the list itself puts first. + */ + @Test + void listPackageVersionsPicksADeterministicDefaultWhenNoVersionHasAPublishedTime() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", null), + new RepositorySidecarManager.PackageVersionTimestamp("2.0", null))); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, null, null, null); + + assertEquals("1.0", result.versions().get(0).version()); + assertEquals("1.0", result.defaultDisplayVersion()); + } + + /** + * {@code packageVersionSortCursor} and {@code defaultDisplayVersion} must break a same-second + * publish tie the same direction: the first {@code Published} version the list returns is + * always the default, never a different one a separate lexicographic comparison would have + * picked (which, for versions like {@code 9.0} and {@code 10.0}, disagrees with list order). + */ + @Test + void listPackageVersionsDefaultDisplayVersionAgreesWithListOrderOnASameSecondTie() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("9.0", Instant.ofEpochSecond(1000)), + new RepositorySidecarManager.PackageVersionTimestamp("10.0", Instant.ofEpochSecond(1000)))); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, null, null, null); + + assertEquals(result.versions().get(0).version(), result.defaultDisplayVersion()); + } + + @Test + void listPackageVersionsRoutesEveryContainerBackedFormatToTheSidecarBridge() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + when(verdaccioClient.listPackageVersions(eq(created.getSidecarContainerIds().get("npm")), eq("dom"), + eq("repo"), isNull(), eq("my-pkg"))).thenReturn( + List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", null))); + when(pypiserverClient.listPackageVersions(eq(created.getSidecarContainerIds().get("pypi")), eq("dom"), + eq("repo"), isNull(), eq("my-pkg"))).thenReturn( + List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", null))); + when(bagetterClient.listPackageVersions(eq(created.getSidecarContainerIds().get("nuget")), eq("dom"), + eq("repo"), isNull(), eq("my-pkg"))).thenReturn( + List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", null))); + + for (String format : List.of("npm", "pypi", "nuget")) { + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", format, null, "my-pkg", null, null, null, null, null); + assertEquals(1, result.versions().size()); + assertEquals("1.0.0", result.versions().get(0).version()); + assertEquals("Published", result.versions().get(0).status()); + } + } + + @Test + void listPackageVersionsFailsNotFoundForAContainerBackedPackageThatWasNeverPublished() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, null, null, null)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void listPackageVersionsOriginTypeExternalOrUnknownReturnsEmptyButKeepsDefaultDisplayVersion() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8)); + + for (String originType : List.of("EXTERNAL", "UNKNOWN")) { + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg", null, null, null, null, originType); + assertTrue(result.versions().isEmpty()); + assertEquals("1.0.0", result.defaultDisplayVersion()); + } + } + + @Test + void listPackageVersionsDefaultDisplayVersionPrefersNpmDistTagLatestOverMostRecentlyPublished() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("npm"); + when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), + eq("my-pkg"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000)), + new RepositorySidecarManager.PackageVersionTimestamp("2.0.0", Instant.ofEpochSecond(2000)))); + when(verdaccioClient.preferredDisplayVersion(eq(repoId), eq("dom"), eq("repo"), isNull(), + eq("my-pkg"))).thenReturn(Optional.of("1.0.0")); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "npm", null, "my-pkg", null, null, null, null, null); + + assertEquals("1.0.0", result.defaultDisplayVersion()); + } + + @Test + void listPackageVersionsRejectsAFormatAwsDoesNotSupport() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", null, + "repo", "not-a-real-format", null, "my-pkg", null, null, null, null, null)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void listPackageVersionsRequiresANamespaceForMaven() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", null, + "repo", "maven", null, "a", null, null, null, null, null)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void listPackageVersionsRejectsANamespaceForPypiAndNuGet() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + for (String format : List.of("pypi", "nuget")) { + AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", null, + "repo", format, "a-namespace", "my-pkg", null, null, null, null, null)); + assertEquals("ValidationException", e.getErrorCode()); + } + } + + @Test + void listPackageVersionsRequiresDomainAndRepository() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException missingDomain = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, + null, null, "repo", "generic", "ns", "my-pkg", null, null, null, null, null)); + assertEquals("ValidationException", missingDomain.getErrorCode()); + + AwsException missingRepository = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, + "dom", null, null, "generic", "ns", "my-pkg", null, null, null, null, null)); + assertEquals("ValidationException", missingRepository.getErrorCode()); + } + + @Test + void listPackageVersionsRejectsAnInvalidStatusSortByOrOriginType() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8)); + + AwsException badStatus = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg", "NotAStatus", null, null, null, null)); + assertEquals("ValidationException", badStatus.getErrorCode()); + + AwsException badSortBy = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg", null, "NOT_A_SORT", null, null, null)); + assertEquals("ValidationException", badSortBy.getErrorCode()); + + AwsException badOriginType = assertThrows(AwsException.class, () -> service.listPackageVersions(REGION, + "dom", null, "repo", "generic", "ns", "my-pkg", null, null, null, null, "NOT_AN_ORIGIN")); + assertEquals("ValidationException", badOriginType.getErrorCode()); + } + // --------------------------------------------- NuGet revision normalization @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java index c091d7a92a..3a2169bfe6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java @@ -638,6 +638,24 @@ class ReposiliteSidecarClientTest { () -> client.listPackageVersionAssetNames("dom--repo", "dom", "repo", "com.example", "a", "1.0")); } + /** + * A transient error on one version's own details page (auth failure, Reposilite briefly + * unavailable) must surface as a real error, the same way a non-404 failure on the + * artifact-level listing just above already does, rather than being treated identically to + * "this version has no files yet" and silently reporting no publish time for it. + */ + @Test + void listPackageVersionsThrowsWhenAVersionsDetailsPageFailsWithARealError() { + server.createContext("/api/maven/details/dom--repo/com/example/a", + exchange -> respond(exchange, 200, "{\"name\":\"a\",\"type\":\"DIRECTORY\",\"files\":[" + + "{\"name\":\"1.0\",\"type\":\"DIRECTORY\"}]}")); + server.createContext("/api/maven/details/dom--repo/com/example/a/1.0", + exchange -> respond(exchange, 500, "{\"status\":500,\"message\":\"internal error\"}")); + + assertThrows(IllegalStateException.class, + () -> client.listPackageVersions("dom--repo", "dom", "repo", "com.example", "a")); + } + @Test void storePackageVersionAssetPutsTheBytesDirectlyEvenWhenDifferingContentAlreadyExists() throws Exception { // deployArtifact's own redeployment:false preflight would refuse this; storePackageVersionAsset