feat(codeartifact): list a package version's direct dependencies (#8474)

Adds ListPackageVersionDependencies, extracted from each format's own metadata
file: the POM for Maven, package.json for npm, the wheel/sdist metadata for
pypi, and the .nuspec for NuGet. Scoped to exactly npm/pypi/maven/nuget,
matching AWS's own documented Valid Values for this action's format
parameter; generic, cargo, ruby, and swift are rejected with a
ValidationException even though cargo's own sparse index already carries the
data, since AWS does not document cargo as a valid format for this specific
action.

A new RepositorySidecarManager#listPackageVersionDependencies default method
(throwing UnsupportedOperationException, the same convention
listPackageVersionAssetNames already uses) is overridden by all four valid
formats' sidecar clients:

- ReposiliteSidecarClient tries the version's standard release POM name
  first, falling back to the real directory listing for a -SNAPSHOT
  version's own timestamped filename (and surfacing a genuine fetch error
  through that same fallback, rather than reporting it as an empty
  dependency list), and parses it with a new PomDependencies helper. That
  helper only ever walks direct children of a known element rather than
  Document#getElementsByTagName, specifically so a managed version pin under
  dependencyManagement or a conditionally-activated dependency under profiles
  is never mistaken for a real, always-active dependency. One synthetic
  "parent"-typed entry is emitted when <parent> is present. No ${property}
  placeholder resolution on a dependency's raw version text, a documented
  limitation.
- VerdaccioSidecarClient reads dependencies/devDependencies/
  peerDependencies/optionalDependencies straight off the already-fetched
  packument's version document, splitting a scoped dependency name the same
  way CodeArtifactNpmDataPlane already does for the package's own name.
- BagetterSidecarClient reuses the same already-proven .nuspec fetch
  fetchPackageVersionReadme falls back to, with NuspecXml extended with a new
  dependencies() method that flattens every <group targetFramework> block
  (and the older schema's bare <dependency> with no group wrapper) into one
  list.
- PypiserverSidecarClient is new ground: a new PypiVersionMetadata helper
  opens a real wheel via plain ZipInputStream, or an sdist via GZIPInputStream
  plus a new minimal hand-rolled TAR reader (classic 512-byte headers only,
  no long-name or PAX support) for .tar.gz/.tgz, or via ZipInputStream for a
  .zip sdist, bounding the total bytes it will ever decompress while
  scanning one archive so a small, highly compressible entry ahead of the
  real metadata entry cannot force unbounded decompression. Only the exact
  top-level dist-info/METADATA or PKG-INFO entry is matched, never a nested
  one, so a wheel or sdist that vendors another package's own dist-info
  alongside its own cannot have that vendored entry mistaken for the real
  one. Requires-Dist headers are parsed with RFC822 continuation-line
  folding, stopping at the blank line that ends the real header block so a
  Requires-Dist-looking line inside the package's own long description is
  never read as a real dependency. Any "; extra == ..." environment marker
  is kept verbatim in versionRequirement rather than stripped, since
  PackageDependency has no marker field. A release available only as a real
  .tar.bz2/.tar.xz sdist is reported as having no dependencies rather than
  attempted, since bzip2/xz decompression would need a new runtime
  dependency this codebase deliberately avoids.

XmlParser gained a new parseDocument(byte[]) overload so a POM or .nuspec's
own raw bytes reach the parser directly: the existing String-based overload
pre-decodes as UTF-8 before the parser ever sees the original bytes, which
would silently corrupt or fail to parse a document that declares a different
encoding. PomDependencies and NuspecXml both now go through the byte-based
overload.

CodeArtifactService#listPackageVersionDependencies validates the format
against this narrower set before the shared validatePackageCoordinates call,
which already enforces the maven-namespace-required and
pypi/nuget-namespace-forbidden rules AWS documents for this action.
Pagination's cursor now folds in each entry's own original-list index as a
final tiebreaker, so two byte-for-byte identical dependencies (e.g. the same
NuGet package id declared under two different target-framework groups with
the same version requirement) never share a cursor and silently drop across
a page boundary.

Verified with standalone parser unit tests, per-client wire-contract tests
against a JDK HttpServer fake, CodeArtifactServiceTest dispatch and
validation cases, and a live Docker-gated round trip added to all four
existing format Docker integration tests, each publishing a real artifact
with real dependency metadata through the real sidecar container.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 13:49:06 -04:00
1 parent 5059a3cd40
commit 6be7641359
25 files changed
+1689 -5

No files matched your search

+1
View File
@@ -45,6 +45,7 @@ proxy 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. |
| `ListPackageVersionDependencies` | Lists a package version's direct dependencies, extracted from that format's own metadata file (the POM for Maven, `package.json` for npm, the wheel/sdist metadata for pypi, the `.nuspec` for NuGet); `npm`, `pypi`, `maven`, and `nuget` only, matching AWS's own restriction for this action (`generic`, `cargo`, `ruby`, and `swift` are all rejected, even though Cargo's own sparse index already carries the data). Maven requires a `namespace` (groupId); pypi and NuGet reject one. A dependency's raw `${property}` placeholder in a Maven version is returned as-is, never resolved; a NuGet dependency declared under more than one `<group targetFramework>` is returned once per group, so the same package id can legitimately appear more than once with a different version. |
| `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. |
| `ListPackages` | Lists package names across every format in a repository, with each package's origin controls; paginated, optionally filtered by format, namespace prefix, package-name prefix, or publish/upstream restriction. |
| `GetPackageVersionReadme` | Returns the readme text for a package version; `npm`, `pypi`, and `nuget` only, matching AWS's own restriction for this action. |
+1 -1
View File
@@ -131,7 +131,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/package-group*`, `/v1/list-associated-packages`, `/v1/get-associated-package-group`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 47 |
| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/package-group*`, `/v1/list-associated-packages`, `/v1/get-associated-package-group`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 48 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*`, `/key-value-stores/*` | REST XML, REST JSON | 61 |
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 |
| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 |
@@ -60,6 +60,18 @@ public final class XmlParser {
* DTD processing disabled. DOM is required by the JDK XML-DSig API.
*/
public static Document parseDocument(String xml) throws Exception {
return parseDocument(xml.getBytes(StandardCharsets.UTF_8));
}
/**
* As above, parsing the original raw bytes directly rather than a {@link String} already
* decoded as UTF-8: letting the parser itself read {@code xml}'s own bytes is what lets it
* honor a declared non-UTF-8 {@code encoding} in the XML prolog, or a UTF-16 byte-order mark,
* the way the XML spec requires. Pre-decoding as UTF-8 before this point (the {@link
* #parseDocument(String)} overload's own contract, left unchanged for its existing callers)
* would silently corrupt or fail to parse a document that declares a different encoding.
*/
public static Document parseDocument(byte[] xml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
@@ -68,8 +80,7 @@ public final class XmlParser {
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
return factory.newDocumentBuilder().parse(
new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
return factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml));
}
/**
@@ -537,6 +537,35 @@ public class BagetterSidecarClient implements RepositorySidecarManager {
return Optional.of(NuspecXml.parse(nuspec.get()).description().orElse(""));
}
/**
* Reads {@code <dependencies>} straight off the same real {@code .nuspec}
* {@link #fetchPackageVersionReadme} already fetches and parses, via
* {@link NuspecXml#dependencies}. NuGet never carries {@code dependencyType} (AWS's own docs:
* "the dependencyType field is never set for NuGet packages") and has no namespace component,
* so every entry maps straight across with both left {@code null}.
*/
@Override
public List<CodeArtifactService.PackageDependency> listPackageVersionDependencies(
String repositoryContainerId, String domain, String repository, String namespace, String packageName,
String version) {
String lowerId = packageName.toLowerCase(Locale.ROOT);
Optional<String> normalizedVersion = matchVersion(repositoryContainerId, lowerId, version);
if (normalizedVersion.isEmpty()) {
return List.of();
}
Optional<byte[]> nuspec = getBytes(repositoryContainerId, "/v3/package/"
+ SidecarUriUtils.encodeSegment(lowerId) + "/" + SidecarUriUtils.encodeSegment(normalizedVersion.get())
+ "/" + SidecarUriUtils.encodeSegment(lowerId) + ".nuspec");
if (nuspec.isEmpty()) {
return List.of();
}
List<CodeArtifactService.PackageDependency> dependencies = new ArrayList<>();
for (NuspecXml.RawDependency raw : NuspecXml.dependencies(nuspec.get())) {
dependencies.add(new CodeArtifactService.PackageDependency(null, raw.id(), null, raw.version()));
}
return dependencies;
}
/**
* {@code empty()} when {@code version} doesn't match any version BaGetter actually holds for this
* package, its own normalized form otherwise. BaGetter lists each version it holds already
@@ -464,6 +464,49 @@ public class CodeArtifactController {
return ok(response);
}
@POST
@Path("/v1/package/version/dependencies")
@Consumes(MediaType.WILDCARD)
public Response listPackageVersionDependencies(@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("version") String version,
@QueryParam("next-token") String nextToken) {
String region = regionResolver.resolveRegion(headers);
CodeArtifactService.PackageVersionDependenciesListResult result = service.listPackageVersionDependencies(
region, domain, domainOwner, repository, format, namespace, packageName, version, nextToken);
ObjectNode dependenciesResponse = objectMapper.createObjectNode();
dependenciesResponse.put("format", result.format());
if (result.namespace() != null) {
dependenciesResponse.put("namespace", result.namespace());
}
dependenciesResponse.put("package", result.packageName());
dependenciesResponse.put("version", result.version());
dependenciesResponse.put("versionRevision", result.versionRevision());
ArrayNode dependencies = dependenciesResponse.putArray("dependencies");
result.dependencies().forEach(dependency -> {
ObjectNode node = dependencies.addObject();
if (dependency.namespace() != null) {
node.put("namespace", dependency.namespace());
}
node.put("package", dependency.packageName());
if (dependency.dependencyType() != null) {
node.put("dependencyType", dependency.dependencyType());
}
if (dependency.versionRequirement() != null) {
node.put("versionRequirement", dependency.versionRequirement());
}
});
if (result.nextToken() != null) {
dependenciesResponse.put("nextToken", result.nextToken());
}
return ok(dependenciesResponse);
}
@POST
@Path("/v1/package/versions")
@Consumes(MediaType.WILDCARD)
@@ -100,6 +100,15 @@ public class CodeArtifactService implements Resettable {
* than silently 404ing the way an unimplemented capability elsewhere here might.
*/
private static final Set<String> README_FORMATS = Set.of("npm", "pypi", "nuget");
/**
* Formats AWS documents as valid for {@code ListPackageVersionDependencies} specifically: the
* action's own request parameter doc gives "Valid Values: npm | pypi | maven | nuget",
* narrower than the shared eight-value {@code PackageFormat} wire enum every other
* package-version action here accepts. Generic, Ruby, Swift, and (despite its sparse index
* already carrying a real {@code deps} array) Cargo package versions are rejected outright for
* this action rather than silently 404ing or extending AWS's own documented scope.
*/
private static final Set<String> DEPENDENCY_FORMATS = Set.of("npm", "pypi", "maven", "nuget");
/** The real {@code PackageVersionStatus} wire enum, confirmed against {@code service-2.json}. */
private static final Set<String> PACKAGE_VERSION_STATUSES =
Set.of("Published", "Unfinished", "Unlisted", "Archived", "Disposed", "Deleted");
@@ -201,6 +210,10 @@ public class CodeArtifactService implements Resettable {
public record AssetSummary(String name, long size, Map<String, String> hashes) {}
public record PackageVersionAssetsListResult(String format, String namespace, String packageName,
String version, String versionRevision, List<AssetSummary> assets, String nextToken) {}
public record PackageDependency(String namespace, String packageName, String dependencyType,
String versionRequirement) {}
public record PackageVersionDependenciesListResult(String format, String namespace, String packageName,
String version, String versionRevision, List<PackageDependency> dependencies, String nextToken) {}
public record PackageVersionSummary(String version, String revision, String status, String originType,
String externalConnectionName, String upstreamRepositoryName) {}
public record ListPackageVersionsResult(String format, String namespace, String packageName,
@@ -1318,6 +1331,80 @@ public class CodeArtifactService implements Resettable {
page.nextToken());
}
/**
* Lists the direct dependencies of one package version, extracted from that format's own
* metadata file (the POM for Maven, {@code package.json} for npm, the wheel/sdist metadata for
* pypi, the {@code .nuspec} for NuGet). AWS documents this action for exactly those 4 formats
* ({@link #DEPENDENCY_FORMATS}), narrower than {@link #CONTAINER_BACKED_FORMATS}: generic and
* Cargo are rejected here even though Cargo's own sparse index already carries a real {@code
* deps} array, since AWS's own request parameter doc does not list Cargo as a valid format for
* this specific action.
*/
public PackageVersionDependenciesListResult listPackageVersionDependencies(String region, String domain,
String domainOwner, String repository, String format, String namespace, String packageName,
String version, String nextToken) {
if (format == null || !DEPENDENCY_FORMATS.contains(format)) {
throw validation("format must be one of " + DEPENDENCY_FORMATS + ".");
}
requireNonBlank(domain, "domain");
requireNonBlank(repository, "repository");
requireNonBlank(version, "packageVersion");
validatePackageToken("packageVersion", version);
validatePackageCoordinates(format, namespace, packageName, "listing the dependencies of");
String owner = effectiveOwner(domainOwner);
requireRepository(owner, repositoryKey(region, domain, repository), repository);
RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
.orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName
+ "' was not found.", version, "package-version"));
String repoId = resolveContainerIdAndBeginUse(format, region, domain, owner, repository, manager);
try {
if (!manager.packageVersionExists(repoId, domain, repository, namespace, packageName, version)) {
throw notFound("Package version '" + version + "' of package '" + packageName
+ "' was not found.", version, "package-version");
}
List<PackageDependency> dependencies;
try {
dependencies = manager.listPackageVersionDependencies(repoId, domain, repository, namespace,
packageName, version);
} catch (UnsupportedOperationException e) {
throw new AwsException("InternalServerException", "Listing a " + format + " package version's "
+ "dependencies is not yet supported by this emulator.", 500);
}
List<IndexedDependency> indexed = new ArrayList<>(dependencies.size());
for (int i = 0; i < dependencies.size(); i++) {
indexed.add(new IndexedDependency(i, dependencies.get(i)));
}
PaginatedResult<IndexedDependency> page = Pagination.paginate(indexed, this::dependencyCursor, null,
nextToken, 100, 1000, "ValidationException");
String revision = currentContainerBackedVersionStatus(owner, region, domain, repository, format,
namespace, packageName, version, repoId).revision();
return new PackageVersionDependenciesListResult(format, namespace, packageName, version, revision,
page.items().stream().map(IndexedDependency::dependency).toList(), page.nextToken());
} finally {
endSidecarUse(manager, repoId);
}
}
private record IndexedDependency(int index, PackageDependency dependency) {}
/**
* A stable, always-unique pagination cursor for {@link #listPackageVersionDependencies}:
* every field folded in, plus the entry's own original-list index as a final tiebreaker, so
* two byte-for-byte identical dependencies (e.g. the same NuGet package id declared under two
* different target-framework groups with the same version requirement) never share a cursor.
* Without the index, {@link Pagination#slice}'s own "resume strictly after this cursor" logic
* would skip every entry sharing the boundary cursor when a page happens to end on one of them.
*/
private String dependencyCursor(IndexedDependency indexed) {
PackageDependency dependency = indexed.dependency();
return (dependency.namespace() == null ? "" : dependency.namespace()) + "\u0000"
+ dependency.packageName() + "\u0000"
+ (dependency.dependencyType() == null ? "" : dependency.dependencyType()) + "\u0000"
+ (dependency.versionRequirement() == null ? "" : dependency.versionRequirement()) + "\u0000"
+ String.format("%010d", indexed.index());
}
/**
* Lists every version of one package. For {@code generic}, reads straight from the stored
* {@link CodeArtifactPackageVersion} records {@link #genericPackageVersions} already groups by
@@ -3,6 +3,7 @@ package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.XmlParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.ByteArrayInputStream;
@@ -10,9 +11,10 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.zip.ZipEntry;
@@ -40,6 +42,70 @@ final class NuspecXml {
record Metadata(String id, String version, Optional<String> description) {
}
/** One {@code <dependency id="" version=""/>} entry, verbatim, before any format mapping. */
record RawDependency(String id, String version) {
}
/**
* Every direct dependency declared under {@code <metadata>/<dependencies>}, flattened across
* however many {@code <group targetFramework="...">} blocks the nuspec has (AWS's own
* {@code PackageDependency} shape carries no target-framework field, so the same package id
* can legitimately appear more than once with a different {@code version} across frameworks;
* that is correct, AWS-matching behavior, not something to deduplicate). Also handles the
* older nuspec schema's bare {@code <dependency>} directly under {@code <dependencies>} with
* no {@code <group>} wrapper at all. Empty when the nuspec declares no dependencies.
*/
static List<RawDependency> dependencies(byte[] content) {
Document document;
try {
document = XmlParser.parseDocument(content);
} catch (Exception e) {
throw new IllegalStateException("Could not parse the package version's .nuspec file.", e);
}
NodeList metadataNodes = document.getDocumentElement().getElementsByTagName("metadata");
if (metadataNodes.getLength() == 0) {
return List.of();
}
NodeList dependenciesNodes = ((Element) metadataNodes.item(0)).getElementsByTagName("dependencies");
if (dependenciesNodes.getLength() == 0) {
return List.of();
}
List<RawDependency> dependencies = new ArrayList<>();
NodeList children = dependenciesNodes.item(0).getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element element = (Element) child;
if ("group".equals(element.getLocalName())) {
addDependencyChildren(element, dependencies);
} else if ("dependency".equals(element.getLocalName())) {
addDependency(element, dependencies);
}
}
return dependencies;
}
private static void addDependencyChildren(Element group, List<RawDependency> dependencies) {
NodeList children = group.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && "dependency".equals(((Element) child).getLocalName())) {
addDependency((Element) child, dependencies);
}
}
}
private static void addDependency(Element dependency, List<RawDependency> dependencies) {
String id = dependency.getAttribute("id");
if (id.isBlank()) {
return;
}
String version = dependency.getAttribute("version");
dependencies.add(new RawDependency(id, version.isBlank() ? null : version));
}
/**
* {@code content} is the raw bytes of a {@code .nuspec} file taken from inside a caller-supplied
* {@code .nupkg} upload, so this hardens the parser against XXE the same way any other
@@ -50,7 +116,7 @@ final class NuspecXml {
static Metadata parse(byte[] content) {
Document document;
try {
document = XmlParser.parseDocument(new String(content, StandardCharsets.UTF_8));
document = XmlParser.parseDocument(content);
} catch (Exception e) {
throw new IllegalStateException("Could not parse the uploaded package's .nuspec file.", e);
}
@@ -0,0 +1,96 @@
package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.XmlParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Pulls direct dependencies out of a Maven POM's XML for {@code ListPackageVersionDependencies},
* using the shared, hardened {@link XmlParser#parseDocument}. Only ever walks direct children of
* a known element, never {@link Document#getElementsByTagName}: that method recurses into every
* matching descendant, which would wrongly pull managed version pins out of
* {@code <project>/<dependencyManagement>/<dependencies>} (not real dependencies) and
* conditionally-activated dependencies out of {@code <project>/<profiles>/<profile>/<dependencies>}
* (not always-active) as if they were direct dependencies of the version itself.
*/
final class PomDependencies {
private PomDependencies() {
}
/**
* {@code pomBytes} is the exact asset this package version's own Maven coordinate names
* ({@code <artifactId>-<version>.pom}), fetched the same way any other asset is. No
* {@code ${property}} placeholder resolution is performed on a dependency's raw
* {@code <version>} text: a documented limitation, not a build gap, since resolving effective
* POM properties would need a full Maven model builder this emulator does not have.
*/
static List<CodeArtifactService.PackageDependency> parse(byte[] pomBytes) {
Document document;
try {
document = XmlParser.parseDocument(pomBytes);
} catch (Exception e) {
throw new IllegalStateException("Could not parse the package version's POM file.", e);
}
Element project = document.getDocumentElement();
List<CodeArtifactService.PackageDependency> dependencies = new ArrayList<>();
directChild(project, "parent").ifPresent(parent -> {
String artifactId = directChildText(parent, "artifactId").orElse(null);
if (artifactId != null) {
dependencies.add(new CodeArtifactService.PackageDependency(
directChildText(parent, "groupId").orElse(null), artifactId, "parent",
directChildText(parent, "version").orElse(null)));
}
});
directChild(project, "dependencies").ifPresent(dependenciesElement -> {
for (Element dependency : directChildren(dependenciesElement, "dependency")) {
String artifactId = directChildText(dependency, "artifactId").orElse(null);
if (artifactId == null) {
continue;
}
String groupId = directChildText(dependency, "groupId").orElse(null);
String version = directChildText(dependency, "version").orElse(null);
String scope = directChildText(dependency, "scope").orElse(null);
boolean optional = "true".equalsIgnoreCase(directChildText(dependency, "optional").orElse("false"));
String dependencyType = optional ? "optional" : scope != null ? scope : "compile";
dependencies.add(new CodeArtifactService.PackageDependency(groupId, artifactId, dependencyType,
version));
}
});
return dependencies;
}
private static Optional<Element> directChild(Element parent, String localName) {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && localName.equals(((Element) child).getLocalName())) {
return Optional.of((Element) child);
}
}
return Optional.empty();
}
private static List<Element> directChildren(Element parent, String localName) {
List<Element> matches = new ArrayList<>();
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && localName.equals(((Element) child).getLocalName())) {
matches.add((Element) child);
}
}
return matches;
}
private static Optional<String> directChildText(Element parent, String localName) {
return directChild(parent, localName).map(Element::getTextContent).map(String::trim)
.filter(text -> !text.isEmpty());
}
}
@@ -0,0 +1,288 @@
package io.floci.aws.services.codeartifact;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Extracts a pypi release's {@code Requires-Dist} metadata for {@code
* ListPackageVersionDependencies}: pypiserver's own {@code /<project>/json} API carries only
* filenames and URLs, never a distribution's embedded metadata, so this opens the actual asset
* bytes a caller already fetched (a wheel's real {@code .dist-info/METADATA}, or an sdist's real
* {@code PKG-INFO}) and parses the RFC822-style header text itself.
*/
final class PypiVersionMetadata {
// A real METADATA/PKG-INFO file is at most a few KB; generous headroom, not a realistic size,
// so a crafted entry cannot drive an unbounded allocation, the same reasoning NuspecXml's own
// MAX_NUSPEC_BYTES bound uses.
private static final int MAX_METADATA_BYTES = 1024 * 1024;
// Bounds the TOTAL bytes this reader will ever decompress while scanning one archive,
// including every entry it skips before (or without ever) finding the real metadata entry:
// without this, a small, highly compressible archive with a large entry ahead of the real
// one would make every dependency request for that version decompress an effectively
// unbounded amount of data (a real decompression-bomb denial-of-service risk, not contrived).
private static final long MAX_TOTAL_SCAN_BYTES = 64L * 1024 * 1024;
private static final int TAR_BLOCK_SIZE = 512;
private static final int TAR_NAME_OFFSET = 0;
private static final int TAR_NAME_LENGTH = 100;
private static final int TAR_SIZE_OFFSET = 124;
private static final int TAR_SIZE_LENGTH = 12;
private PypiVersionMetadata() {
}
/**
* A wheel is a plain ZIP archive; this finds the one entry matching exactly
* {@code <single-segment>.dist-info/METADATA} (one {@code /}, confirmed by requiring the
* first and last slash indices to coincide). Requiring exactly one path segment before the
* filename is deliberate: a wheel that vendors another package's own dist-info alongside its
* own (a real, documented setuptools pattern, e.g. {@code setuptools/_vendor/packaging-*
* .dist-info/METADATA}) would otherwise match that nested entry instead of the real top-level
* one, reporting the vendored package's dependencies rather than the wheel's own. Empty when
* no such entry exists.
*/
static Optional<byte[]> extractWheelMetadata(byte[] wheelBytes) {
return extractFromZip(wheelBytes, name -> isTopLevelEntry(name, ".dist-info/METADATA"),
"wheel", "METADATA");
}
/**
* A {@code .zip}-packaged sdist (an older, still AWS/pypiserver-recognized source-distribution
* format alongside the far more common {@code .tar.gz}), scanned the same way as a wheel but
* matching exactly {@code <single-segment>/PKG-INFO}.
*/
static Optional<byte[]> extractZipSdistMetadata(byte[] zipBytes) {
return extractFromZip(zipBytes, name -> isTopLevelEntry(name, "/PKG-INFO"), "sdist", "PKG-INFO");
}
private static Optional<byte[]> extractFromZip(byte[] archiveBytes, Predicate<String> matches,
String archiveKind, String entryKind) {
long[] remaining = {MAX_TOTAL_SCAN_BYTES};
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archiveBytes))) {
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
if (!entry.isDirectory() && matches.test(entry.getName())) {
return Optional.of(readBounded(zip, remaining, entryKind));
}
discardBounded(zip, remaining);
entry = zip.getNextEntry();
}
} catch (IOException e) {
throw new UncheckedIOException("Could not read the package version's " + archiveKind
+ " archive.", e);
}
return Optional.empty();
}
/** True when {@code name} has exactly one {@code /} and ends with {@code suffix}. */
private static boolean isTopLevelEntry(String name, String suffix) {
int firstSlash = name.indexOf('/');
return firstSlash >= 0 && firstSlash == name.lastIndexOf('/') && name.endsWith(suffix);
}
/**
* A {@code .tar.gz}/{@code .tgz} sdist (gzip-compressed TAR, the modern default pip/setuptools
* produce); this decompresses it and walks a minimal subset of the TAR format (classic
* 512-byte header blocks, the null-terminated name field and octal size field every real
* pip/setuptools-produced archive has) to find the one entry matching exactly
* {@code <single-segment>/PKG-INFO} (one {@code /}: a nested {@code PKG-INFO} belonging to a
* vendored or bundled package must not be mistaken for the sdist's own top-level one).
* Deliberately does not support symlinks, GNU long-name ({@code @LongLink}), or PAX extended
* headers: a documented, bounded limitation, not a general-purpose TAR reader. {@code
* .tar.bz2}/{@code .tar.xz} sdists are real, pypiserver-recognized formats this does not
* parse at all (bzip2/xz decompression would need a new dependency this codebase deliberately
* avoids), so callers must not route those bytes through this method; see {@link
* PypiserverSidecarClient#listPackageVersionDependencies} for how a release available only in
* one of those formats is handled. Empty when no matching entry is found or the archive ends
* before one is.
*/
static Optional<byte[]> extractSdistMetadata(byte[] sdistBytes) {
long[] remaining = {MAX_TOTAL_SCAN_BYTES};
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(sdistBytes))) {
byte[] header = new byte[TAR_BLOCK_SIZE];
while (readFully(gzip, header, remaining) == TAR_BLOCK_SIZE && !isZeroBlock(header)) {
String name = tarEntryName(header);
long size = tarEntrySize(header);
if (size < 0) {
break;
}
long paddedSize = ((size + TAR_BLOCK_SIZE - 1) / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE;
if (isTopLevelEntry(name, "/PKG-INFO")) {
if (size > MAX_METADATA_BYTES) {
throw new IllegalStateException("The package version's PKG-INFO exceeds "
+ MAX_METADATA_BYTES + " bytes.");
}
byte[] content = new byte[(int) size];
readFully(gzip, content, remaining);
skipFully(gzip, paddedSize - size, remaining);
return Optional.of(content);
}
skipFully(gzip, paddedSize, remaining);
}
} catch (IOException e) {
throw new UncheckedIOException("Could not read the package version's sdist archive.", e);
}
return Optional.empty();
}
/**
* Every {@code Requires-Dist} header in {@code metadata}'s RFC822-style text, folding a
* continuation line (one starting with whitespace) into the header it continues first.
* Scanning stops at the first blank line, the real RFC822 boundary between the header block
* and the message body (a package's own long description): without that boundary, a
* description that happens to contain a line looking like {@code Requires-Dist: ...} (a real
* risk, since that is literally itself a documented example string in PyPA's own packaging
* guide) would be wrongly reported as a real dependency. The bare package name is the leading
* run of name characters; everything after it, including any {@code ; extra == "..."}
* environment marker, is returned verbatim as {@code versionRequirement} rather than
* stripped: {@code PackageDependency} has no marker field, and nothing in AWS's own
* documentation of this action indicates CodeArtifact itself strips one.
*/
static List<CodeArtifactService.PackageDependency> parseRequiresDist(byte[] metadata) {
List<CodeArtifactService.PackageDependency> dependencies = new ArrayList<>();
for (String line : foldHeaderLines(new String(metadata, StandardCharsets.UTF_8))) {
int colon = line.indexOf(':');
if (colon < 0 || !"Requires-Dist".equalsIgnoreCase(line.substring(0, colon).trim())) {
continue;
}
String value = line.substring(colon + 1).trim();
int nameEnd = 0;
while (nameEnd < value.length() && isPackageNameChar(value.charAt(nameEnd))) {
nameEnd++;
}
if (nameEnd == 0) {
continue;
}
String versionRequirement = value.substring(nameEnd).trim();
dependencies.add(new CodeArtifactService.PackageDependency(null, value.substring(0, nameEnd),
"Requires-Dist", versionRequirement.isEmpty() ? null : versionRequirement));
}
return dependencies;
}
private static boolean isPackageNameChar(char c) {
return Character.isLetterOrDigit(c) || c == '.' || c == '-' || c == '_';
}
private static List<String> foldHeaderLines(String text) {
List<String> logicalLines = new ArrayList<>();
for (String rawLine : text.split("\n", -1)) {
String line = rawLine.endsWith("\r") ? rawLine.substring(0, rawLine.length() - 1) : rawLine;
if (line.isEmpty()) {
break;
}
if (!logicalLines.isEmpty() && (line.startsWith(" ") || line.startsWith("\t"))) {
int last = logicalLines.size() - 1;
logicalLines.set(last, logicalLines.get(last) + " " + line.strip());
} else {
logicalLines.add(line);
}
}
return logicalLines;
}
private static String tarEntryName(byte[] header) {
int end = TAR_NAME_OFFSET;
while (end < TAR_NAME_OFFSET + TAR_NAME_LENGTH && header[end] != 0) {
end++;
}
return new String(header, TAR_NAME_OFFSET, end - TAR_NAME_OFFSET, StandardCharsets.UTF_8);
}
/** {@code -1} on a header this reader cannot make sense of, so the caller stops scanning. */
private static long tarEntrySize(byte[] header) {
int start = TAR_SIZE_OFFSET;
int end = TAR_SIZE_OFFSET + TAR_SIZE_LENGTH;
while (start < end && header[start] == ' ') {
start++;
}
while (end > start && (header[end - 1] == 0 || header[end - 1] == ' ')) {
end--;
}
if (end <= start) {
return 0;
}
try {
return Long.parseLong(new String(header, start, end - start, StandardCharsets.US_ASCII), 8);
} catch (NumberFormatException e) {
return -1;
}
}
private static boolean isZeroBlock(byte[] block) {
for (byte b : block) {
if (b != 0) {
return false;
}
}
return true;
}
private static void chargeBudget(long[] remaining, int bytes) {
remaining[0] -= bytes;
if (remaining[0] < 0) {
throw new IllegalStateException("The package version's archive exceeds this reader's "
+ MAX_TOTAL_SCAN_BYTES + "-byte total decompression budget.");
}
}
private static int readFully(InputStream in, byte[] buffer, long[] remaining) throws IOException {
int total = 0;
while (total < buffer.length) {
int read = in.read(buffer, total, buffer.length - total);
if (read < 0) {
break;
}
chargeBudget(remaining, read);
total += read;
}
return total;
}
private static void skipFully(InputStream in, long bytes, long[] remaining) throws IOException {
long toSkip = bytes;
byte[] buffer = new byte[8192];
while (toSkip > 0) {
int read = in.read(buffer, 0, (int) Math.min(buffer.length, toSkip));
if (read < 0) {
return;
}
chargeBudget(remaining, read);
toSkip -= read;
}
}
private static void discardBounded(InputStream in, long[] remaining) throws IOException {
byte[] chunk = new byte[8192];
int read;
while ((read = in.read(chunk)) != -1) {
chargeBudget(remaining, read);
}
}
private static byte[] readBounded(InputStream in, long[] remaining, String entryKind) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] chunk = new byte[8192];
int read;
while ((read = in.read(chunk)) != -1) {
chargeBudget(remaining, read);
if (buffer.size() + read > MAX_METADATA_BYTES) {
throw new IllegalStateException("The package version's " + entryKind + " exceeds "
+ MAX_METADATA_BYTES + " bytes decompressed.");
}
buffer.write(chunk, 0, read);
}
return buffer.toByteArray();
}
}
@@ -378,6 +378,59 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
return filenames;
}
/**
* pypiserver's own {@code /<project>/json} API carries only filenames and URLs, never a
* distribution's embedded {@code Requires-Dist} metadata, so this picks a representative
* asset for the version and opens it directly: a {@code .whl} (a plain ZIP, simpler and more
* reliable to parse) if one exists, otherwise an sdist in one of the formats this reader can
* actually decompress ({@code .tar.gz}/{@code .tgz}, both gzip+tar, or {@code .zip}). When
* several wheels exist for the version (e.g. per-platform builds), the first by lexicographic
* filename order is used, a deterministic choice rather than "whichever happens to list
* first" - a documented simplification, since real AWS's own tie-break for this case is not
* publicly documented either. Empty when the version has no wheel or decompressible-sdist
* asset at all (including when it exists only as a real {@code .tar.bz2}/{@code .tar.xz}
* sdist, both real formats {@link #ARCHIVE_SUFFIX} recognizes that this reader deliberately
* does not attempt, since bzip2/xz decompression would need a new runtime dependency), or the
* chosen asset has no parseable {@code Requires-Dist} metadata.
*/
@Override
public List<CodeArtifactService.PackageDependency> listPackageVersionDependencies(
String repositoryContainerId, String domain, String repository, String namespace, String packageName,
String version) {
List<String> filenames = listPackageVersionAssetNames(repositoryContainerId, domain, repository, namespace,
packageName, version);
String wheel = filenames.stream().filter(name -> name.endsWith(".whl")).sorted().findFirst().orElse(null);
String assetName = wheel;
if (assetName == null) {
// .tar.gz/.tgz (both real gzip+tar) and .zip are all real sdist formats this sidecar's
// own ARCHIVE_SUFFIX already recognizes and this reader can actually decompress. A
// release available only as .tar.bz2/.tar.xz (also real, ARCHIVE_SUFFIX-recognized
// formats) falls through to the empty-list return below rather than being misread:
// bzip2/xz decompression would need a new runtime dependency this codebase
// deliberately avoids.
assetName = filenames.stream()
.filter(name -> name.endsWith(".tar.gz") || name.endsWith(".tgz") || name.endsWith(".zip"))
.sorted().findFirst().orElse(null);
}
if (assetName == null) {
return List.of();
}
Optional<byte[]> asset = fetchPackageVersionAsset(repositoryContainerId, domain, repository, namespace,
packageName, version, assetName);
if (asset.isEmpty()) {
return List.of();
}
Optional<byte[]> metadata;
if (wheel != null) {
metadata = PypiVersionMetadata.extractWheelMetadata(asset.get());
} else if (assetName.endsWith(".zip")) {
metadata = PypiVersionMetadata.extractZipSdistMetadata(asset.get());
} else {
metadata = PypiVersionMetadata.extractSdistMetadata(asset.get());
}
return metadata.map(PypiVersionMetadata::parseRequiresDist).orElse(List.of());
}
/**
* Uploads {@code content} as {@code assetName} the same real {@code twine upload} wire shape
* {@code CodeArtifactPypiController#upload} already forwards unmodified, confirmed against a
@@ -349,6 +349,41 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
return names;
}
/**
* Fetches this version's own POM and parses its {@code <dependencies>}/{@code <parent>}
* elements with {@link PomDependencies}. Tries the standard release name
* ({@code <artifactId>-<version>.pom}) first, through {@link #fetchPackageVersionAsset}
* rather than a dedicated route: the overwhelmingly common case, and avoids a second network
* round trip for it. A {@code -SNAPSHOT} version's real POM is not named that way at all —
* {@code mvn deploy} writes it under a timestamped unique-snapshot name instead (e.g.
* {@code artifact-1.0-20261115.120000-1.pom}) — so a miss falls back to the real directory
* listing {@link #listPackageVersionAssetNames} already exposes and picks whichever entry
* ends in {@code .pom} there (the lexicographically greatest one, i.e. the most recent
* timestamp, if more than one snapshot deploy's files are still present). That fallback also
* means a genuine Reposilite error (not a real 404) surfaces as the same {@link
* IllegalStateException} {@link #listPackageVersionAssetNames} already throws for an
* unexpected status, rather than this method silently reporting an empty dependency list for
* a version whose POM fetch merely failed.
*/
@Override
public List<CodeArtifactService.PackageDependency> listPackageVersionDependencies(
String repositoryContainerId, String domain, String repository, String namespace, String packageName,
String version) {
Optional<byte[]> pom = fetchPackageVersionAsset(repositoryContainerId, domain, repository, namespace,
packageName, version, packageName + "-" + version + ".pom");
if (pom.isEmpty()) {
String pomName = listPackageVersionAssetNames(repositoryContainerId, domain, repository, namespace,
packageName, version).stream()
.filter(name -> name.endsWith(".pom"))
.max(String::compareTo)
.orElse(null);
pom = pomName == null ? Optional.empty()
: fetchPackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName,
version, pomName);
}
return pom.map(PomDependencies::parse).orElse(List.of());
}
/**
* Enumerates every version directory beneath the artifact itself (the same {@code files}
* array {@link #listPackageVersionAssetNames} already reads one level down, here kept to its
@@ -183,6 +183,21 @@ public interface RepositorySidecarManager {
return Optional.empty();
}
/**
* Direct dependencies of one package version, extracted from the metadata file for this
* format (the POM for Maven, {@code package.json} for npm, the wheel/sdist metadata for pypi,
* the {@code .nuspec} for NuGet). Only the 4 formats AWS itself documents for {@code
* ListPackageVersionDependencies} override this; the default throws {@link
* UnsupportedOperationException}, the same convention {@link #listPackageVersionAssetNames}
* already uses for a capability not every sidecar backs.
*/
default List<CodeArtifactService.PackageDependency> listPackageVersionDependencies(
String repositoryContainerId, String domain, String repository, String namespace, String packageName,
String version) {
throw new UnsupportedOperationException(format() + " package version dependencies cannot be listed "
+ "through this sidecar");
}
/**
* Lists the asset name of every file published under one package version, for bridging
* {@code CopyPackageVersions} when there is no generic-format record to enumerate assets from
@@ -479,6 +479,55 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
return filename == null ? List.of() : List.of(filename);
}
/**
* Reads {@code dependencies}/{@code devDependencies}/{@code peerDependencies}/
* {@code optionalDependencies} straight off this version's own packument entry, exactly as
* stored on publish/retention (confirmed live: {@link #storeVersion} preserves them verbatim).
* A name appearing in more than one of the 4 maps emits a separate entry for each, rather than
* being deduplicated: a package can legitimately be both a runtime default and a dev-only
* override with different version ranges.
*/
@Override
public List<CodeArtifactService.PackageDependency> listPackageVersionDependencies(
String repositoryContainerId, String domain, String repository, String namespace, String packageName,
String version) {
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
Optional<JsonNode> document = fetchPackageDocument(baseUrl, namespace, packageName);
if (document.isEmpty()) {
return List.of();
}
JsonNode versionDoc = document.get().path("versions").path(version);
if (versionDoc.isMissingNode()) {
return List.of();
}
List<CodeArtifactService.PackageDependency> dependencies = new ArrayList<>();
addNpmDependencies(dependencies, versionDoc.path("dependencies"), "regular");
addNpmDependencies(dependencies, versionDoc.path("devDependencies"), "dev");
addNpmDependencies(dependencies, versionDoc.path("peerDependencies"), "peer");
addNpmDependencies(dependencies, versionDoc.path("optionalDependencies"), "optional");
return dependencies;
}
private static void addNpmDependencies(List<CodeArtifactService.PackageDependency> dependencies,
JsonNode dependencyMap, String dependencyType) {
Iterator<String> names = dependencyMap.fieldNames();
while (names.hasNext()) {
String name = names.next();
String versionRequirement = dependencyMap.path(name).asText(null);
String dependencyNamespace = null;
String dependencyPackageName = name;
if (name.startsWith("@")) {
int slash = name.indexOf('/');
if (slash > 0) {
dependencyNamespace = name.substring(1, slash);
dependencyPackageName = name.substring(slash + 1);
}
}
dependencies.add(new CodeArtifactService.PackageDependency(dependencyNamespace, dependencyPackageName,
dependencyType, versionRequirement));
}
}
/**
* Publishes {@code version} straight to this sidecar's own packument, the real npm registry
* wire shape confirmed against a live Verdaccio container: a {@code PUT} to the package path
@@ -337,6 +337,41 @@ class BagetterSidecarClientTest {
assertTrue(result.isEmpty());
}
@Test
void listPackageVersionDependenciesReadsTheRealNuspecDependenciesGroups() throws Exception {
BagetterSidecarManager manager = manager();
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
respondWithVersions("demo-pkg", "1.0.0");
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>demo-pkg</id><version>1.0.0</version>"
+ "<dependencies><group targetFramework=\"net6.0\">"
+ "<dependency id=\"Newtonsoft.Json\" version=\"13.0.1\"/></group></dependencies>"
+ "</metadata></package>";
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.nuspec", exchange -> {
byte[] body = nuspec.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"nuget-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertEquals(List.of(new CodeArtifactService.PackageDependency(null, "Newtonsoft.Json", null, "13.0.1")),
dependencies);
}
@Test
void listPackageVersionDependenciesIsEmptyWhenTheVersionWasNeverPublished() throws Exception {
BagetterSidecarManager manager = manager();
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
respondWithVersions("demo-pkg", "1.0.0");
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"nuget-repo-1", "dom", "repo", null, "demo-pkg", "9.9.9");
assertTrue(dependencies.isEmpty());
}
/**
* BaGetter's flat container (what {@link #respondWithVersions} fakes) always returns
* normalized, lowercased version strings, but its registration resource's {@code
@@ -834,6 +834,42 @@ class CodeArtifactMavenDockerIntegrationTest {
assertEquals(before + metadata.length, after);
}
/**
* A throwaway groupId/artifactId, not {@link #GAV}: {@code ListPackageVersionDependencies}
* parses this version's own real POM, fetched back off the real Reposilite sidecar, rather
* than anything hand-built in process.
*/
@Test
@Order(25)
void listPackageVersionDependenciesParsesTheRealPomFetchedBackFromReposilite() {
byte[] jar = "depcheck-jar-bytes".getBytes(StandardCharsets.UTF_8);
String pomXml = "<project><parent><groupId>com.example</groupId><artifactId>depcheck-parent</artifactId>"
+ "<version>9.0.0</version></parent><dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>depcheck-dep</artifactId>"
+ "<version>2.0.0</version><scope>test</scope></dependency>"
+ "</dependencies></project>";
given().header("Authorization", "Bearer " + bearerToken).body(jar)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/depcheck/1.0.0/depcheck-1.0.0.jar")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken).body(pomXml.getBytes(StandardCharsets.UTF_8))
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/depcheck/1.0.0/depcheck-1.0.0.pom")
.then().statusCode(200);
JsonPath body = given().header("Authorization", AUTH)
.post("/v1/package/version/dependencies?domain=" + DOMAIN + "&repository=" + REPO + "&format=maven"
+ "&namespace=com.example&package=depcheck&version=1.0.0")
.then().statusCode(200)
.body("package", equalTo("depcheck"))
.body("dependencies.size()", equalTo(2))
.extract().jsonPath();
List<String> dependencyTypes = body.getList("dependencies.dependencyType", String.class);
List<String> packageNames = body.getList("dependencies.package", String.class);
assertTrue(dependencyTypes.contains("parent"), "expected a parent entry among " + dependencyTypes);
assertTrue(packageNames.contains("depcheck-parent"));
assertTrue(dependencyTypes.contains("test"), "expected a test-scoped entry among " + dependencyTypes);
assertTrue(packageNames.contains("depcheck-dep"));
}
/**
* Reads the real Reposilite instance's own {@code maven} settings domain directly (the same
* shared container {@link ReposiliteSidecarManager} started for every test in this class).
@@ -753,6 +753,40 @@ class CodeArtifactNpmDockerIntegrationTest {
+ copiedVersion.path("dist").path("tarball").asText());
}
@Test
@Order(25)
void listPackageVersionDependenciesReadsAllFourDependencyMapsFromTheRealSidecar() {
String packageName = "listdeps-npm-pkg";
byte[] tarball = "list-deps-npm-tarball-bytes".getBytes(StandardCharsets.UTF_8);
String envelope = "{\"name\":\"" + packageName + "\",\"versions\":{\"1.0.0\":{\"name\":\"" + packageName
+ "\",\"version\":\"1.0.0\","
+ "\"dependencies\":{\"@types/node\":\"^18.0.0\"},"
+ "\"devDependencies\":{\"jest\":\"^29.0.0\"},"
+ "\"peerDependencies\":{\"react\":\">=16\"},"
+ "\"optionalDependencies\":{\"fsevents\":\"^2.0.0\"},"
+ "\"dist\":{\"tarball\":\"http://ignored/" + packageName + "-1.0.0.tgz\"}}},\"_attachments\":{\""
+ packageName + "-1.0.0.tgz\":{\"content_type\":\"application/octet-stream\",\"data\":\""
+ Base64.getEncoder().encodeToString(tarball) + "\",\"length\":" + tarball.length + "}}}";
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(envelope)
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
JsonPath body = given().header("Authorization", AUTH)
.post("/v1/package/version/dependencies?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm"
+ "&package=" + packageName + "&version=1.0.0")
.then().statusCode(200)
.body("package", equalTo(packageName))
.body("dependencies.size()", equalTo(4))
.extract().jsonPath();
List<String> packageNames = body.getList("dependencies.package", String.class);
List<String> namespaces = body.getList("dependencies.namespace", String.class);
assertTrue(packageNames.contains("node"));
assertEquals("types", namespaces.get(packageNames.indexOf("node")));
assertTrue(packageNames.contains("jest"));
assertTrue(packageNames.contains("react"));
assertTrue(packageNames.contains("fsevents"));
}
/**
* The real-world gap this closes: {@code ListPackageVersionAssets} used to not exist at all.
* Confirms the bridge enumerates npm's one-asset-per-version packument entry against the real
@@ -641,6 +641,54 @@ class CodeArtifactNuGetDockerIntegrationTest {
* entry and reference it with a nuspec {@code <readme>} element, the real NuGet readme-file
* feature.
*/
/**
* A real {@code .nupkg} whose {@code .nuspec} declares one {@code <dependencies>} group, for
* {@code ListPackageVersionDependencies} to parse back off the real BaGetter sidecar.
*/
private static byte[] buildNupkgWithDependency(String id, String version, String dependencyId,
String dependencyVersion) {
String nuspec = "<?xml version=\"1.0\"?>"
+ "<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">"
+ "<metadata><id>" + id + "</id><version>" + version + "</version><authors>floci</authors>"
+ "<description>a package with a real dependency</description>"
+ "<dependencies><group targetFramework=\"net6.0\">"
+ "<dependency id=\"" + dependencyId + "\" version=\"" + dependencyVersion + "\"/>"
+ "</group></dependencies></metadata></package>";
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry(id + ".nuspec"));
zip.write(nuspec.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return out.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
@Order(19)
void listPackageVersionDependenciesReadsTheRealNuspecFromTheRealBagetterSidecar() {
String packageId = "ListDeps.Package";
byte[] nupkg = buildNupkgWithDependency(packageId, VERSION, "Newtonsoft.Json", "13.0.1");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nupkg))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
given().header("Authorization", AUTH)
.post("/v1/package/version/dependencies?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget"
+ "&package=" + packageId + "&version=" + VERSION)
.then().statusCode(200)
.body("package", equalTo(packageId))
.body("dependencies.size()", equalTo(1))
.body("dependencies[0].package", equalTo("Newtonsoft.Json"))
.body("dependencies[0].versionRequirement", equalTo("13.0.1"))
.body("dependencies[0].containsKey('dependencyType')", equalTo(false));
}
private static byte[] buildNupkg(String id, String version, String description, String readmePathOrNull,
String readmeTextOrNull) {
String readmeElement = readmePathOrNull == null ? "" : "<readme>" + readmePathOrNull + "</readme>";
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@@ -27,6 +28,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.zip.GZIPOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -922,6 +924,61 @@ class CodeArtifactPypiDockerIntegrationTest {
return output.isBlank() ? 0 : (int) output.lines().count();
}
/**
* A real gzipped tarball holding one {@code <name>-<version>/PKG-INFO} entry with real
* {@code Requires-Dist} headers, the exact shape {@code PypiVersionMetadata.extractSdistMetadata}
* expects: classic 512-byte TAR header blocks, no long-name or PAX extensions.
*/
private static byte[] buildSdistWithRequiresDist(String packageDirectoryName, String metadataText)
throws IOException {
byte[] metadataBytes = metadataText.getBytes(StandardCharsets.UTF_8);
byte[] header = new byte[512];
byte[] nameBytes = (packageDirectoryName + "/PKG-INFO").getBytes(StandardCharsets.UTF_8);
System.arraycopy(nameBytes, 0, header, 0, nameBytes.length);
byte[] sizeOctal = String.format("%011o", metadataBytes.length).getBytes(StandardCharsets.US_ASCII);
System.arraycopy(sizeOctal, 0, header, 124, sizeOctal.length);
header[156] = '0';
int padding = (512 - metadataBytes.length % 512) % 512;
ByteArrayOutputStream tar = new ByteArrayOutputStream();
tar.write(header);
tar.write(metadataBytes);
tar.write(new byte[padding]);
tar.write(new byte[1024]);
ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(gzipped)) {
gzip.write(tar.toByteArray());
}
return gzipped.toByteArray();
}
@Test
@Order(23)
void listPackageVersionDependenciesParsesRequiresDistFromARealSdistAtTheRealPypiserverSidecar()
throws IOException {
String packageName = "listdeps-pypi-pkg";
String filename = "listdeps_pypi_pkg-1.0.0.tar.gz";
byte[] sdist = buildSdistWithRequiresDist("listdeps_pypi_pkg-1.0.0",
"Metadata-Version: 2.1\nName: listdeps-pypi-pkg\nVersion: 1.0.0\n"
+ "Requires-Dist: requests (>=2.0.0)\n");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, filename, sdist))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
given().header("Authorization", AUTH)
.post("/v1/package/version/dependencies?domain=" + DOMAIN + "&repository=" + REPO + "&format=pypi"
+ "&package=" + packageName + "&version=1.0.0")
.then().statusCode(200)
.body("package", equalTo(packageName))
.body("dependencies.size()", equalTo(1))
.body("dependencies[0].package", equalTo("requests"))
.body("dependencies[0].dependencyType", equalTo("Requires-Dist"))
.body("dependencies[0].versionRequirement", equalTo("(>=2.0.0)"));
}
/**
* The fields a real {@code twine upload} sends (verified by hand against a live pypiserver
* instance during design); pypiserver, and this controller's own parsing, only look at
@@ -5328,6 +5328,141 @@ class CodeArtifactServiceTest {
assertEquals("ValidationException", missingVersion.getErrorCode());
}
// ----------------------------------------------------- ListPackageVersionDependencies
@Test
void listPackageVersionDependenciesBridgesToReposiliteForMaven() {
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.packageVersionExists(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
when(reposiliteClient.listPackageVersionDependencies(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(
List.of(new CodeArtifactService.PackageDependency("com.example", "b", "compile", "2.0.0")));
CodeArtifactService.PackageVersionDependenciesListResult result = service.listPackageVersionDependencies(
REGION, "dom", null, "repo", "maven", "com.example", "a", "1.0", null);
assertEquals(1, result.dependencies().size());
assertEquals("b", result.dependencies().get(0).packageName());
assertEquals("compile", result.dependencies().get(0).dependencyType());
}
@Test
void listPackageVersionDependenciesFailsNotFoundForAMavenVersionThatWasNeverPublished() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersionDependencies(REGION, "dom",
null, "repo", "maven", "com.example", "a", "1.0", null));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void listPackageVersionDependenciesRoutesEveryValidFormatToTheSidecarBridge() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
for (String format : List.of("npm", "pypi", "nuget")) {
AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersionDependencies(REGION,
"dom", null, "repo", format, null, "my-pkg", "1.0.0", null));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
}
@Test
void listPackageVersionDependenciesRejectsAFormatAwsDoesNotDocumentForThisAction() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
for (String format : List.of("generic", "cargo", "ruby", "swift", "not-a-real-format")) {
AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersionDependencies(REGION,
"dom", null, "repo", format, null, "my-pkg", "1.0.0", null));
assertEquals("ValidationException", e.getErrorCode());
}
}
@Test
void listPackageVersionDependenciesRequiresANamespaceForMaven() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service.listPackageVersionDependencies(REGION,
"dom", null, "repo", "maven", null, "a", "1.0", null));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void listPackageVersionDependenciesRejectsANamespaceForPypiAndNuGet() {
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.listPackageVersionDependencies(REGION,
"dom", null, "repo", format, "a-namespace", "my-pkg", "1.0.0", null));
assertEquals("ValidationException", e.getErrorCode());
}
}
@Test
void listPackageVersionDependenciesPaginatesWithANextToken() {
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.packageVersionExists(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
List<CodeArtifactService.PackageDependency> many = new ArrayList<>();
for (int i = 0; i < 150; i++) {
many.add(new CodeArtifactService.PackageDependency(null, "dep-" + String.format("%03d", i), "regular",
"1.0.0"));
}
when(verdaccioClient.listPackageVersionDependencies(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(many);
CodeArtifactService.PackageVersionDependenciesListResult firstPage = service.listPackageVersionDependencies(
REGION, "dom", null, "repo", "npm", null, "my-pkg", "1.0.0", null);
assertEquals(100, firstPage.dependencies().size());
assertTrue(firstPage.nextToken() != null);
CodeArtifactService.PackageVersionDependenciesListResult secondPage = service.listPackageVersionDependencies(
REGION, "dom", null, "repo", "npm", null, "my-pkg", "1.0.0", firstPage.nextToken());
assertEquals(50, secondPage.dependencies().size());
}
/**
* Qodo review finding: byte-for-byte identical dependency entries (a real shape for NuGet,
* where the same package id can be declared under more than one target-framework group with
* the same version requirement) must not share a pagination cursor - if a 100-item page ends
* between two of them, resuming "strictly after" a shared cursor would silently drop whichever
* one(s) land past the boundary.
*/
@Test
void listPackageVersionDependenciesPaginationNeverDropsIdenticalEntriesAcrossAPageBoundary() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("nuget");
when(bagetterClient.packageVersionExists(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
List<CodeArtifactService.PackageDependency> many = new ArrayList<>();
for (int i = 0; i < 150; i++) {
// Every entry is byte-for-byte identical: the real worst case for a cursor collision.
many.add(new CodeArtifactService.PackageDependency(null, "Shared.Package", null, "1.0.0"));
}
when(bagetterClient.listPackageVersionDependencies(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(many);
CodeArtifactService.PackageVersionDependenciesListResult firstPage = service.listPackageVersionDependencies(
REGION, "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", null);
CodeArtifactService.PackageVersionDependenciesListResult secondPage = service.listPackageVersionDependencies(
REGION, "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", firstPage.nextToken());
assertEquals(100, firstPage.dependencies().size());
assertEquals(50, secondPage.dependencies().size());
}
// ----------------------------------------------------- ListPackageVersions
@Test
@@ -7,6 +7,7 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -108,6 +109,41 @@ class NuspecXmlTest {
assertThrows(IllegalStateException.class, () -> NuspecXml.extractFromNupkg(nupkg));
}
@Test
void dependenciesFlattensEveryTargetFrameworkGroupAndAllowsTheSamePackageTwice() {
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>Demo</id><version>1.0.0</version>"
+ "<dependencies>"
+ "<group targetFramework=\"net6.0\"><dependency id=\"Newtonsoft.Json\" version=\"13.0.1\"/></group>"
+ "<group targetFramework=\"netstandard2.0\"><dependency id=\"Newtonsoft.Json\" version=\"12.0.3\"/>"
+ "<dependency id=\"NoVersion\"/></group>"
+ "</dependencies></metadata></package>";
List<NuspecXml.RawDependency> dependencies = NuspecXml.dependencies(nuspec.getBytes(StandardCharsets.UTF_8));
assertEquals(3, dependencies.size());
assertEquals(new NuspecXml.RawDependency("Newtonsoft.Json", "13.0.1"), dependencies.get(0));
assertEquals(new NuspecXml.RawDependency("Newtonsoft.Json", "12.0.3"), dependencies.get(1));
assertEquals(new NuspecXml.RawDependency("NoVersion", null), dependencies.get(2));
}
@Test
void dependenciesHandlesTheLegacySchemaWithNoGroupWrapper() {
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>Demo</id><version>1.0.0</version>"
+ "<dependencies><dependency id=\"Old.Style\" version=\"1.2.3\"/></dependencies>"
+ "</metadata></package>";
List<NuspecXml.RawDependency> dependencies = NuspecXml.dependencies(nuspec.getBytes(StandardCharsets.UTF_8));
assertEquals(List.of(new NuspecXml.RawDependency("Old.Style", "1.2.3")), dependencies);
}
@Test
void dependenciesIsEmptyWhenTheNuspecDeclaresNone() {
List<NuspecXml.RawDependency> dependencies = NuspecXml.dependencies(NUSPEC.getBytes(StandardCharsets.UTF_8));
assertTrue(dependencies.isEmpty());
}
private static byte[] buildNupkg(String rootNuspecOrNull) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -0,0 +1,89 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PomDependenciesTest {
@Test
void parseReadsTheParentAndEveryDirectDependencyWithTheirOwnDependencyType() {
String pom = "<project>"
+ "<parent><groupId>com.example</groupId><artifactId>parent-pom</artifactId><version>1.0.0</version>"
+ "</parent>"
+ "<dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>no-scope</artifactId>"
+ "<version>1.2.3</version></dependency>"
+ "<dependency><groupId>com.example</groupId><artifactId>test-scoped</artifactId>"
+ "<version>2.0.0</version><scope>test</scope></dependency>"
+ "<dependency><groupId>com.example</groupId><artifactId>optional-and-scoped</artifactId>"
+ "<version>3.0.0</version><scope>provided</scope><optional>true</optional></dependency>"
+ "</dependencies>"
+ "</project>";
List<CodeArtifactService.PackageDependency> dependencies =
PomDependencies.parse(pom.getBytes(StandardCharsets.UTF_8));
assertEquals(4, dependencies.size());
assertEquals(new CodeArtifactService.PackageDependency("com.example", "parent-pom", "parent", "1.0.0"),
dependencies.get(0));
assertEquals(new CodeArtifactService.PackageDependency("com.example", "no-scope", "compile", "1.2.3"),
dependencies.get(1));
assertEquals(new CodeArtifactService.PackageDependency("com.example", "test-scoped", "test", "2.0.0"),
dependencies.get(2));
assertEquals(new CodeArtifactService.PackageDependency("com.example", "optional-and-scoped", "optional",
"3.0.0"), dependencies.get(3));
}
@Test
void parseIgnoresDependencyManagementAndProfileDependencies() {
String pom = "<project>"
+ "<dependencyManagement><dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>managed-only</artifactId>"
+ "<version>9.9.9</version></dependency>"
+ "</dependencies></dependencyManagement>"
+ "<profiles><profile><id>extra</id><dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>profile-only</artifactId>"
+ "<version>8.8.8</version></dependency>"
+ "</dependencies></profile></profiles>"
+ "<dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>real-dependency</artifactId>"
+ "<version>1.0.0</version></dependency>"
+ "</dependencies>"
+ "</project>";
List<CodeArtifactService.PackageDependency> dependencies =
PomDependencies.parse(pom.getBytes(StandardCharsets.UTF_8));
assertEquals(List.of(new CodeArtifactService.PackageDependency("com.example", "real-dependency", "compile",
"1.0.0")), dependencies);
}
@Test
void parseReturnsNoRawPropertyResolution() {
String pom = "<project><dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>versioned-by-property</artifactId>"
+ "<version>${some.property}</version></dependency>"
+ "</dependencies></project>";
List<CodeArtifactService.PackageDependency> dependencies =
PomDependencies.parse(pom.getBytes(StandardCharsets.UTF_8));
assertEquals("${some.property}", dependencies.get(0).versionRequirement());
}
@Test
void parseReturnsNoDependenciesForAPomWithNeitherAParentNorADependenciesBlock() {
String pom = "<project><groupId>com.example</groupId><artifactId>leaf</artifactId><version>1.0.0</version>"
+ "</project>";
List<CodeArtifactService.PackageDependency> dependencies =
PomDependencies.parse(pom.getBytes(StandardCharsets.UTF_8));
assertTrue(dependencies.isEmpty());
}
}
@@ -0,0 +1,198 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PypiVersionMetadataTest {
private static final String METADATA_TEXT = "Metadata-Version: 2.1\n"
+ "Name: demo-package\n"
+ "Version: 1.0.0\n"
+ "Requires-Dist: requests (>=2.0.0)\n"
+ "Requires-Dist: a-very-long-dependency-name-that-wraps\n"
+ " (>=1.0,<2.0)\n"
+ "Requires-Dist: colorama; sys_platform == \"win32\"\n"
+ "Requires-Dist: bare-name\n";
@Test
void extractWheelMetadataFindsTheDistInfoMetadataEntry() throws IOException {
byte[] wheel = buildZip("demo_package-1.0.0.dist-info/METADATA", METADATA_TEXT);
Optional<byte[]> metadata = PypiVersionMetadata.extractWheelMetadata(wheel);
assertTrue(metadata.isPresent());
assertEquals(METADATA_TEXT, new String(metadata.get(), StandardCharsets.UTF_8));
}
@Test
void extractWheelMetadataIsEmptyWhenNoDistInfoMetadataEntryExists() throws IOException {
byte[] wheel = buildZip("demo_package/__init__.py", "# not metadata");
assertTrue(PypiVersionMetadata.extractWheelMetadata(wheel).isEmpty());
}
@Test
void extractSdistMetadataFindsThePkgInfoEntry() throws IOException {
byte[] sdist = buildTarGz("demo_package-1.0.0/PKG-INFO", METADATA_TEXT);
Optional<byte[]> metadata = PypiVersionMetadata.extractSdistMetadata(sdist);
assertTrue(metadata.isPresent());
assertEquals(METADATA_TEXT, new String(metadata.get(), StandardCharsets.UTF_8));
}
@Test
void extractSdistMetadataIsEmptyWhenNoPkgInfoEntryExists() throws IOException {
byte[] sdist = buildTarGz("demo_package-1.0.0/setup.py", "print('hi')");
assertTrue(PypiVersionMetadata.extractSdistMetadata(sdist).isEmpty());
}
@Test
void parseRequiresDistFoldsContinuationsAndKeepsEnvironmentMarkersVerbatim() {
List<CodeArtifactService.PackageDependency> dependencies =
PypiVersionMetadata.parseRequiresDist(METADATA_TEXT.getBytes(StandardCharsets.UTF_8));
assertEquals(4, dependencies.size());
assertEquals(new CodeArtifactService.PackageDependency(null, "requests", "Requires-Dist", "(>=2.0.0)"),
dependencies.get(0));
assertEquals(new CodeArtifactService.PackageDependency(null, "a-very-long-dependency-name-that-wraps",
"Requires-Dist", "(>=1.0,<2.0)"), dependencies.get(1));
assertEquals(new CodeArtifactService.PackageDependency(null, "colorama", "Requires-Dist",
"; sys_platform == \"win32\""), dependencies.get(2));
assertEquals(new CodeArtifactService.PackageDependency(null, "bare-name", "Requires-Dist", null),
dependencies.get(3));
}
/**
* Qodo review finding: a wheel that vendors another package's own dist-info alongside its own
* (a real setuptools pattern) must not have the vendored, nested entry mistaken for the
* wheel's own top-level one, even when it appears first in the archive.
*/
@Test
void extractWheelMetadataIgnoresAVendoredNestedDistInfoEntry() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry("demo_package/_vendor/other-9.0.dist-info/METADATA"));
zip.write("Name: other\nRequires-Dist: not-the-real-one\n".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
zip.putNextEntry(new ZipEntry("demo_package-1.0.0.dist-info/METADATA"));
zip.write(METADATA_TEXT.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
Optional<byte[]> metadata = PypiVersionMetadata.extractWheelMetadata(out.toByteArray());
assertTrue(metadata.isPresent());
assertEquals(METADATA_TEXT, new String(metadata.get(), StandardCharsets.UTF_8));
}
@Test
void extractZipSdistMetadataFindsTheTopLevelPkgInfoEntryAndIgnoresANestedOne() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry("demo_package-1.0.0/vendored/other/PKG-INFO"));
zip.write("Requires-Dist: not-the-real-one\n".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
zip.putNextEntry(new ZipEntry("demo_package-1.0.0/PKG-INFO"));
zip.write(METADATA_TEXT.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
Optional<byte[]> metadata = PypiVersionMetadata.extractZipSdistMetadata(out.toByteArray());
assertTrue(metadata.isPresent());
assertEquals(METADATA_TEXT, new String(metadata.get(), StandardCharsets.UTF_8));
}
/**
* Qodo review finding: a small, highly compressible entry ahead of the real metadata entry
* must not let this reader decompress an effectively unbounded amount of data looking for it.
* 80 MiB of zeros compresses to only a few hundred bytes, so this stays a fast unit test while
* still exceeding the reader's own 64 MiB total-scan budget.
*/
@Test
void extractWheelMetadataAbortsRatherThanDecompressingAnUnboundedPrecedingEntry() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry("huge-padding.bin"));
zip.write(new byte[80 * 1024 * 1024]);
zip.closeEntry();
zip.putNextEntry(new ZipEntry("demo_package-1.0.0.dist-info/METADATA"));
zip.write(METADATA_TEXT.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
byte[] wheel = out.toByteArray();
assertThrows(IllegalStateException.class, () -> PypiVersionMetadata.extractWheelMetadata(wheel));
}
/**
* Qodo review finding: a `Requires-Dist:`-looking line inside the long description (the
* message body, after the RFC822 header/body blank-line boundary) must not be reported as a
* real dependency. {@code Requires-Dist} is literally used as an example string in PyPA's own
* packaging guide, so this is a real, not contrived, risk.
*/
@Test
void parseRequiresDistIgnoresAHeaderLookingLineInsideTheDescriptionBody() {
String metadata = "Metadata-Version: 2.1\n"
+ "Name: demo-package\n"
+ "Requires-Dist: requests\n"
+ "\n"
+ "A long description that happens to mention Requires-Dist: fake-package as an example.\n";
List<CodeArtifactService.PackageDependency> dependencies =
PypiVersionMetadata.parseRequiresDist(metadata.getBytes(StandardCharsets.UTF_8));
assertEquals(List.of(new CodeArtifactService.PackageDependency(null, "requests", "Requires-Dist", null)),
dependencies);
}
private static byte[] buildZip(String entryName, String content) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry(entryName));
zip.write(content.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return out.toByteArray();
}
private static byte[] buildTarGz(String entryName, String content) throws IOException {
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream tar = new ByteArrayOutputStream();
tar.write(tarHeader(entryName, contentBytes.length));
tar.write(contentBytes);
int padding = (512 - contentBytes.length % 512) % 512;
tar.write(new byte[padding]);
tar.write(new byte[1024]);
ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(gzipped)) {
gzip.write(tar.toByteArray());
}
return gzipped.toByteArray();
}
private static byte[] tarHeader(String name, int size) {
byte[] header = new byte[512];
byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
System.arraycopy(nameBytes, 0, header, 0, nameBytes.length);
byte[] sizeOctal = String.format("%011o", size).getBytes(StandardCharsets.US_ASCII);
System.arraycopy(sizeOctal, 0, header, 124, sizeOctal.length);
header[156] = '0';
return header;
}
}
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
@@ -23,6 +24,9 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -531,6 +535,121 @@ class PypiserverSidecarClientTest {
() -> client(manager).deletePackage("pypi-repo-1", "dom", "repo", null, "demo-pkg"));
}
@Test
void listPackageVersionDependenciesParsesRequiresDistFromARealWheel() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
String filename = "demo_pkg-1.0.0-py3-none-any.whl";
respondWithJsonReleases("demo-pkg", Map.of("1.0.0", List.of(filename)));
respondWithSimpleIndex("demo-pkg", filename);
byte[] wheel = buildWheel("demo_pkg-1.0.0.dist-info/METADATA",
"Metadata-Version: 2.1\nName: demo-pkg\nRequires-Dist: requests (>=2.0.0)\n");
backend.createContext("/packages/" + filename, exchange -> {
exchange.sendResponseHeaders(200, wheel.length);
exchange.getResponseBody().write(wheel);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertEquals(List.of(new CodeArtifactService.PackageDependency(null, "requests", "Requires-Dist",
"(>=2.0.0)")), dependencies);
}
/**
* {@code .tar.bz2}/{@code .tar.xz} are real, {@code ARCHIVE_SUFFIX}-recognized sdist formats
* this reader deliberately never attempts to decompress (bzip2/xz would need a new runtime
* dependency) — a version available only in one of those must come back empty, not throw.
*/
@Test
void listPackageVersionDependenciesIsEmptyWhenTheVersionHasNoWheelOrSupportedSdist() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
respondWithJsonReleases("demo-pkg", Map.of("1.0.0", List.of("demo_pkg-1.0.0.tar.bz2")));
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertTrue(dependencies.isEmpty());
}
/** {@code .tgz} is the same real gzip+tar format as {@code .tar.gz}, just a shorter suffix. */
@Test
void listPackageVersionDependenciesParsesRequiresDistFromARealTgzSdist() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
String filename = "demo_pkg-1.0.0.tgz";
respondWithJsonReleases("demo-pkg", Map.of("1.0.0", List.of(filename)));
respondWithSimpleIndex("demo-pkg", filename);
byte[] sdist = buildTarGzSdist("demo_pkg-1.0.0/PKG-INFO",
"Metadata-Version: 2.1\nName: demo-pkg\nRequires-Dist: requests (>=2.0.0)\n");
backend.createContext("/packages/" + filename, exchange -> {
exchange.sendResponseHeaders(200, sdist.length);
exchange.getResponseBody().write(sdist);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertEquals(List.of(new CodeArtifactService.PackageDependency(null, "requests", "Requires-Dist",
"(>=2.0.0)")), dependencies);
}
/** {@code .zip} is a real, pypiserver-recognized sdist format alongside {@code .tar.gz}. */
@Test
void listPackageVersionDependenciesParsesRequiresDistFromARealZipSdist() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
String filename = "demo_pkg-1.0.0.zip";
respondWithJsonReleases("demo-pkg", Map.of("1.0.0", List.of(filename)));
respondWithSimpleIndex("demo-pkg", filename);
byte[] sdist = buildWheel("demo_pkg-1.0.0/PKG-INFO",
"Metadata-Version: 2.1\nName: demo-pkg\nRequires-Dist: requests (>=2.0.0)\n");
backend.createContext("/packages/" + filename, exchange -> {
exchange.sendResponseHeaders(200, sdist.length);
exchange.getResponseBody().write(sdist);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertEquals(List.of(new CodeArtifactService.PackageDependency(null, "requests", "Requires-Dist",
"(>=2.0.0)")), dependencies);
}
private static byte[] buildTarGzSdist(String entryName, String content) throws Exception {
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
byte[] header = new byte[512];
byte[] nameBytes = entryName.getBytes(StandardCharsets.UTF_8);
System.arraycopy(nameBytes, 0, header, 0, nameBytes.length);
byte[] sizeOctal = String.format("%011o", contentBytes.length).getBytes(StandardCharsets.US_ASCII);
System.arraycopy(sizeOctal, 0, header, 124, sizeOctal.length);
header[156] = '0';
ByteArrayOutputStream tar = new ByteArrayOutputStream();
tar.write(header);
tar.write(contentBytes);
tar.write(new byte[(512 - contentBytes.length % 512) % 512]);
tar.write(new byte[1024]);
ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(gzipped)) {
gzip.write(tar.toByteArray());
}
return gzipped.toByteArray();
}
private static byte[] buildWheel(String entryName, String metadataText) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.putNextEntry(new ZipEntry(entryName));
zip.write(metadataText.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
return out.toByteArray();
}
private void respondWithJsonReleases(String packageName, Map<String, List<String>> releases) {
StringBuilder json = new StringBuilder("{\"info\":{\"version\":\"\"},\"releases\":{");
boolean firstVersion = true;
@@ -739,6 +739,85 @@ class ReposiliteSidecarClientTest {
"com.example", "weird"));
}
@Test
void listPackageVersionDependenciesParsesTheFetchedPomsParentAndDependencies() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
String pom = "<project><parent><groupId>com.example</groupId><artifactId>parent-pom</artifactId>"
+ "<version>1.0.0</version></parent><dependencies>"
+ "<dependency><groupId>com.example</groupId><artifactId>other</artifactId>"
+ "<version>2.0.0</version><scope>test</scope></dependency>"
+ "</dependencies></project>";
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.pom", exchange -> respond(exchange, 200, pom));
List<CodeArtifactService.PackageDependency> dependencies = client.listPackageVersionDependencies("dom--repo",
"dom", "repo", "com.example", "a", "1.0");
assertThat(dependencies, containsInAnyOrder(
new CodeArtifactService.PackageDependency("com.example", "parent-pom", "parent", "1.0.0"),
new CodeArtifactService.PackageDependency("com.example", "other", "test", "2.0.0")));
}
@Test
void listPackageVersionDependenciesIsEmptyWhenTheVersionHasNoPom() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.pom", exchange -> respond(exchange, 404, ""));
server.createContext("/api/maven/details/dom--repo/com/example/a/1.0",
exchange -> respond(exchange, 200, "{\"name\":\"1.0\",\"type\":\"DIRECTORY\",\"files\":["
+ "{\"name\":\"a-1.0.jar\",\"type\":\"FILE\"}]}"));
assertThat(client.listPackageVersionDependencies("dom--repo", "dom", "repo", "com.example", "a", "1.0"),
equalTo(List.of()));
}
/**
* Qodo review finding: a {@code -SNAPSHOT} version's real POM is not named
* {@code <artifactId>-<version>.pom} at all - a real {@code mvn deploy} writes it under a
* timestamped unique-snapshot name instead - so the literal-name fetch misses and the fallback
* to the real directory listing must find and fetch the real file.
*/
@Test
void listPackageVersionDependenciesResolvesASnapshotsRealTimestampedPom() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
server.createContext("/dom--repo/com/example/a/1.0-SNAPSHOT/a-1.0-SNAPSHOT.pom",
exchange -> respond(exchange, 404, ""));
server.createContext("/api/maven/details/dom--repo/com/example/a/1.0-SNAPSHOT",
exchange -> respond(exchange, 200, "{\"name\":\"1.0-SNAPSHOT\",\"type\":\"DIRECTORY\",\"files\":["
+ "{\"name\":\"a-1.0-20261115.120000-1.jar\",\"type\":\"FILE\"},"
+ "{\"name\":\"a-1.0-20261115.120000-1.pom\",\"type\":\"FILE\"}]}"));
String pom = "<project><dependencies><dependency><groupId>com.example</groupId>"
+ "<artifactId>snapshot-dep</artifactId><version>1.0.0</version></dependency>"
+ "</dependencies></project>";
server.createContext("/dom--repo/com/example/a/1.0-SNAPSHOT/a-1.0-20261115.120000-1.pom",
exchange -> respond(exchange, 200, pom));
List<CodeArtifactService.PackageDependency> dependencies = client.listPackageVersionDependencies("dom--repo",
"dom", "repo", "com.example", "a", "1.0-SNAPSHOT");
assertThat(dependencies, equalTo(List.of(
new CodeArtifactService.PackageDependency("com.example", "snapshot-dep", "compile", "1.0.0"))));
}
/**
* Qodo review finding: a genuine Reposilite error on the POM fetch (not a real 404) must
* surface as an error, not be silently reported as "no dependencies" - this reuses {@link
* #listPackageVersionAssetNames}'s own already-established unexpected-status handling as the
* fallback path, which is exactly what makes this case throw rather than return quietly.
*/
@Test
void listPackageVersionDependenciesThrowsWhenTheFallbackListingFailsWithARealError() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.pom", exchange -> respond(exchange, 404, ""));
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.listPackageVersionDependencies("dom--repo", "dom", "repo", "com.example", "a", "1.0"));
}
@Test
void listPackageVersionAssetNamesReturnsOnlyTheFileEntriesFromTheVersionDirectory() {
server.createContext("/api/maven/details/dom--repo/com/example/a/1.0",
@@ -374,6 +374,51 @@ class VerdaccioSidecarClientTest {
null, "demo-pkg"));
}
@Test
void listPackageVersionDependenciesReadsAllFourDependencyMapsFromTheStoredVersionDoc() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", backendUrl);
String body = "{\"versions\":{\"1.0.0\":{"
+ "\"dependencies\":{\"@types/node\":\"^18.0.0\"},"
+ "\"devDependencies\":{\"jest\":\"^29.0.0\"},"
+ "\"peerDependencies\":{\"react\":\">=16\"},"
+ "\"optionalDependencies\":{\"fsevents\":\"^2.0.0\"}"
+ "}}}";
backend.createContext("/demo-pkg", exchange -> {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertEquals(4, dependencies.size());
assertTrue(dependencies.contains(
new CodeArtifactService.PackageDependency("types", "node", "regular", "^18.0.0")));
assertTrue(dependencies.contains(new CodeArtifactService.PackageDependency(null, "jest", "dev", "^29.0.0")));
assertTrue(dependencies.contains(new CodeArtifactService.PackageDependency(null, "react", "peer", ">=16")));
assertTrue(dependencies.contains(
new CodeArtifactService.PackageDependency(null, "fsevents", "optional", "^2.0.0")));
}
@Test
void listPackageVersionDependenciesIsEmptyWhenThePackageDoesNotExist() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", backendUrl);
backend.createContext("/demo-pkg", exchange -> {
exchange.sendResponseHeaders(404, -1);
exchange.close();
});
List<CodeArtifactService.PackageDependency> dependencies = client(manager).listPackageVersionDependencies(
"npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0");
assertTrue(dependencies.isEmpty());
}
private void respondWithMetadata(String packagePath, String version, String tarballPath) {
String body = "{\"versions\":{\"" + version + "\":{\"dist\":{\"tarball\":\"http://ignored" + tarballPath
+ "\"}}}}";