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

@@ -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