feat(codeartifact): retain pypi packages from the public:pypi external connection (#7741)

Adds the public:pypi external connection: a repository configured with it now
lists and, on a real download miss, retains packages from the live pypi.org
registry, the same promise-now/fetch-later miss-then-fetch behavior
CodeArtifact already has for npm's, NuGet's and Maven's own external
connections.

AWS documents Python's own retention as importing every asset of a resolved
version together ("CodeArtifact will import all the assets in that package
version", "some contain over 100 assets"), unlike npm/NuGet's one asset per
version; CodeArtifactPypiExternalConnectionImporter#tryImportAsset mirrors
that, fetching every real file the registry lists for the resolved version in
one claim episode, not just the one requested.

PypiExternalConnectionClient speaks the registry's real PEP 691 JSON Simple
API. A real PyPI file's download URL is not deterministic from its
coordinate (files.pythonhosted.org serves it under an opaque per-file hash
path, unlike NuGet's flat-container route), so the URL is read directly off
the trusted index response rather than built, with an explicit host
allowlist so this client never follows a URL to a host it does not actually
trust for that connection.

CodeArtifactPypiController#packageIndex merges in unretained external
filenames (listing-only, fetched lazily on an actual download miss), the
same split every other format's own importer here already uses, and now
also lists a package pypiserver has never heard of at all, as long as the
external connection does.

A file's version is resolved by checking its filename against the real
index's own versions list, reusing the existing
PypiserverSidecarClient#filenameEmbedsVersion rather than re-deriving it.
ensureRetainedPackageOriginDefaultIfCurrentRepository is used rather than
the plain variant, matching the stricter check
CodeArtifactNuGetExternalConnectionImporter already uses.

Deliberately out of scope, noted in the importer's own javadoc: refreshing a
retained version's yanked metadata on every later install (also
AWS-documented) -- pypiserver has no such concept in its wire protocol at
all.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-10 06:37:43 -06:00
1 parent 90a4455905
commit 8e4c1994b7
8 files changed
+2101 -25

No files matched your search

@@ -26,10 +26,14 @@ import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
/**
@@ -71,18 +75,22 @@ public class CodeArtifactPypiController {
private final CodeArtifactService service;
private final PypiserverSidecarClient pypiserver;
private final CodeArtifactPypiExternalConnectionImporter externalConnectionImporter;
private final HttpClient httpClient;
private final ConcurrentHashMap<String, Object> uploadLocks = new ConcurrentHashMap<>();
@Inject
public CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarClient pypiserver) {
this(service, pypiserver, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
public CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarClient pypiserver,
CodeArtifactPypiExternalConnectionImporter externalConnectionImporter) {
this(service, pypiserver, externalConnectionImporter,
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarClient pypiserver,
HttpClient httpClient) {
CodeArtifactPypiExternalConnectionImporter externalConnectionImporter, HttpClient httpClient) {
this.service = service;
this.pypiserver = pypiserver;
this.externalConnectionImporter = externalConnectionImporter;
this.httpClient = httpClient;
}
@@ -101,6 +109,15 @@ public class CodeArtifactPypiController {
* {@code /codeartifact/pypi/<domain>/<repository>/} prefix where {@link #downloadFile} is
* actually routed, so pip would 404 trying to install anything the index lists. Verified
* against a real pypiserver response before writing this, not assumed.
*
* <p>Merges in whichever files {@code repository}'s own pypi external connection names that
* are not already listed above, the same promise-now/fetch-later split {@code
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} already documents for npm:
* without this, a real {@code pip} client could never even learn that an unretained file
* exists, let alone request it through {@link #downloadFile}, the one place its real bytes
* are actually fetched and stored. Run even when pypiserver itself has never heard of this
* package at all ({@code response.getStatus() == 404}): a package that only exists on the
* real public registry so far must still be listable, the same as real CodeArtifact.
*/
@GET
@Path("simple/{package}/")
@@ -112,18 +129,85 @@ public class CodeArtifactPypiController {
try {
Response response = proxyGet(handle.baseUrl(), SIMPLE_PATH + SidecarUriUtils.encodeSegment(packageName)
+ "/");
if (response.getStatus() != 200) {
String rewrittenOrNull;
Set<String> knownFilenames;
if (response.getStatus() == 200) {
String html = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
rewrittenOrNull = html.replace("href=\"/packages/", "href=\"" + handle.pathPrefix() + "/packages/");
knownFilenames = hrefFilenames(html);
} else if (response.getStatus() == 404) {
rewrittenOrNull = null;
knownFilenames = Set.of();
} else {
return response;
}
String html = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
String rewritten = html.replace("href=\"/packages/", "href=\"" + handle.pathPrefix() + "/packages/");
return Response.status(200).entity(rewritten.getBytes(StandardCharsets.UTF_8)).type(MediaType.TEXT_HTML)
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
externalConnectionImporter.additionalExternalFilenames(handle.region(), domain, handle.owner(),
repository, handle.repoId(), packageName, knownFilenames);
if (rewrittenOrNull == null && additional.isEmpty()) {
return response;
}
String merged = withAdditionalFilenames(rewrittenOrNull, handle.pathPrefix(), additional);
return Response.status(200).entity(merged.getBytes(StandardCharsets.UTF_8)).type(MediaType.TEXT_HTML)
.build();
} finally {
pypiserver.endUse(handle.repoId());
}
}
/**
* Appends an {@code <a href="...">} entry for each of {@code additional}'s filenames to
* {@code bodyHtmlOrNull}, right before its closing {@code </body>} tag, or builds a minimal
* document from scratch when {@code bodyHtmlOrNull} is {@code null} (pypiserver itself has no
* local listing for this package at all yet). {@code additional} ultimately comes from the
* real public registry's own response, and nothing here depends on it being free of
* characters that would otherwise be read as markup: the link text is HTML-escaped, and the
* {@code href} itself is percent-encoded via {@link SidecarUriUtils#encodeSegment} rather than
* merely HTML-escaped, the same way every other place in this controller that places a
* caller- or response-supplied filename into a URI path segment already does (see {@link
* #downloadFile}); HTML-escaping alone would leave a literal {@code #} or {@code ?} free to
* be read as a URI fragment or query string by whatever real client resolves this href,
* silently truncating the path it actually requests.
*
* <p>Each entry also carries the real registry's own {@code data-yanked}/{@code
* data-requires-python} attributes (PEP 592/PEP 700) when it has them: a real {@code pip}
* client uses exactly these to filter out a yanked release or one its own interpreter cannot
* satisfy, and without them here, a file this repository has not retained yet would look
* unconditionally eligible on the very first install, even though the registry's own response
* already said otherwise (raised in review).
*/
private static String withAdditionalFilenames(String bodyHtmlOrNull, String pathPrefix,
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional) {
if (additional.isEmpty()) {
return bodyHtmlOrNull;
}
StringBuilder extra = new StringBuilder();
for (CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile file : additional) {
extra.append("<a href=\"").append(pathPrefix).append("/packages/")
.append(SidecarUriUtils.encodeSegment(file.filename())).append("\"");
if (file.requiresPythonOrNull() != null) {
extra.append(" data-requires-python=\"").append(escapeHtml(file.requiresPythonOrNull()))
.append("\"");
}
if (file.yanked()) {
extra.append(" data-yanked=\"\"");
}
extra.append(">").append(escapeHtml(file.filename())).append("</a><br>\n");
}
if (bodyHtmlOrNull == null) {
return "<!DOCTYPE html><html><body>\n" + extra + "</body></html>";
}
int bodyClose = bodyHtmlOrNull.toLowerCase(Locale.ROOT).lastIndexOf("</body>");
if (bodyClose < 0) {
return bodyHtmlOrNull + extra;
}
return bodyHtmlOrNull.substring(0, bodyClose) + extra + bodyHtmlOrNull.substring(bodyClose);
}
private static String escapeHtml(String value) {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
/**
* pypi's real download route is a bare filename with no package name or version anywhere in
* the URL, unlike Maven's GAV path or nuget's content route, so there is nothing in a download
@@ -137,6 +221,13 @@ public class CodeArtifactPypiController {
* the override records instead needs no write-time bookkeeping at all: whichever path put the
* real file there, an override written later by {@code UpdatePackageVersionsStatus}/{@code
* DisposePackageVersions} is found the same way regardless.
*
* <p>A local miss, with no matching Archived/Disposed override, is exactly AWS's own
* documented trigger for an external connection: a real client requesting a file this
* emulator's own pypiserver sidecar does not have yet. Never attempted when {@code match} is
* non-null: that means a status override already exists for the version this filename
* belongs to, Archived or Disposed, and retention must never resurrect it, the same guard
* {@link #upload} already enforces on the publish side.
*/
@GET
@Path("packages/{filename}")
@@ -155,7 +246,13 @@ public class CodeArtifactPypiController {
return Response.status(404).build();
}
}
return proxyGet(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename));
Response response = proxyGet(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename));
if (match == null && response.getStatus() == 404
&& externalConnectionImporter.tryImportAsset(handle.region(), domain, handle.owner(), repository,
handle.repoId(), filename)) {
return proxyGet(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename));
}
return response;
} finally {
pypiserver.endUse(handle.repoId());
}
@@ -330,7 +427,7 @@ public class CodeArtifactPypiController {
* silently fetching a different path than the one actually requested.
*/
private Optional<byte[]> existingFileContent(String baseUrl, String packageName, String filename) {
String normalized = normalizePackageName(packageName);
String normalized = PypiserverSidecarClient.normalizePackageName(packageName);
URI indexUri = SidecarUriUtils.combine(URI.create(baseUrl),
SIMPLE_PATH + SidecarUriUtils.encodeSegment(normalized) + "/");
HttpRequest indexRequest = HttpRequest.newBuilder(indexUri).timeout(Duration.ofSeconds(5)).GET().build();
@@ -372,10 +469,6 @@ public class CodeArtifactPypiController {
return Optional.of(fileResponse.body());
}
private static String normalizePackageName(String name) {
return name.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-");
}
private record ArchivedOrDisposedMatch(String packageName, String version) {
}
@@ -416,14 +509,24 @@ public class CodeArtifactPypiController {
* this check.
*/
private static boolean indexListsFilename(String indexBody, String filename) {
return SIMPLE_INDEX_HREF.matcher(indexBody).results()
.map(match -> {
String href = match.group(1);
String name = href.substring(href.lastIndexOf('/') + 1);
int fragment = name.indexOf('#');
return fragment < 0 ? name : name.substring(0, fragment);
})
.anyMatch(filename::equals);
return hrefFilenames(indexBody).contains(filename);
}
/**
* Every real filename {@code html}'s own {@code href="..."} attributes name, with any
* trailing {@code #...} hash fragment stripped: shared by {@link #indexListsFilename}'s own
* single-filename check and {@link #packageIndex}'s own external-connection merge, which
* needs the whole set to know what pypiserver's local listing already has.
*/
private static Set<String> hrefFilenames(String html) {
Set<String> filenames = new LinkedHashSet<>();
for (MatchResult match : SIMPLE_INDEX_HREF.matcher(html).results().toList()) {
String href = match.group(1);
String name = href.substring(href.lastIndexOf('/') + 1);
int fragment = name.indexOf('#');
filenames.add(fragment < 0 ? name : name.substring(0, fragment));
}
return filenames;
}
private Response forwardUpload(String baseUrl, String contentType, byte[] content) {
@@ -0,0 +1,562 @@
package io.floci.aws.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Retains pypi package versions from the real public repository a repository's {@code
* public:pypi} external connection names, the way real CodeArtifact does when a {@code pip}/
* {@code twine} client requests a package version that is not present locally yet. Confirmed
* against the User Guide's own "Requesting Python packages from upstreams and external
* connections" section, not inferred:
*
* <ul>
* <li><b>Every asset of a version, imported together.</b> "When importing a Python package
* version from pypi.org, CodeArtifact will import all the assets in that package version,"
* explicitly unlike npm/NuGet's "only have one asset per package version": a popular package's
* version can have "over 100 assets," so {@link #tryImportAsset} always imports every real file
* the public registry lists for the resolved version, the same best-effort, all-reachable-
* siblings shape {@code CodeArtifactMavenExternalConnectionImporter} already uses for Maven's
* own (much smaller, fixed) 4-name standard bundle.</li>
* <li><b>No release-only restriction.</b> Unlike Maven's own external connections, AWS's docs
* name no equivalent carve-out for pypi prereleases, and no exclusion for a <i>yanked</i>
* version either (yanked only changes what a real {@code pip} client itself does with a
* version once it is fetched, never whether CodeArtifact imports it): every version and file
* this emulator's own real public repository lists is eligible.</li>
* <li><b>Checking asset origins.</b> A package version's retention origin, once confirmed,
* never changes (see {@link CodeArtifactService#claimRetainedVersionOrigin}'s own javadoc,
* generalized from Maven's own first use of this mechanism); an import attempt under a
* different connection than what is already claimed for that exact version is refused
* outright.</li>
* <li><b>Coordinated with this emulator's own deletion and disposal.</b> The real write, via
* {@link CodeArtifactService#retainAssetUnderVersionFence}, happens inside the exact same lock
* {@code DeletePackageVersions}/{@code DeletePackage}/{@code DeleteRepository}/{@code
* DisposePackageVersions} already hold for their entire duration, so the two can never
* interleave.</li>
* </ul>
*
* <p>Deliberately not modeled here: refreshing a retained version's <i>yanked</i> metadata on
* every later install, which the same User Guide section also documents. {@code pypiserver} has
* no concept of a yanked flag anywhere in its own wire protocol, so surfacing it to a real
* {@code pip} client would need a new field on this emulator's own package-version model with no
* connection to the actual asset-retention gap this class closes; tracked separately as a
* follow-up rather than widening this scope. For the same reason, this never re-fetches every
* byte of an already-fully-retained version on a later {@code pip install}: {@link
* CodeArtifactPypiController#packageIndex}'s own merge (see {@link
* #additionalExternalFilenames}) re-lists whichever new files the real registry has added since,
* cheaply, on every request, and {@link #tryImportAsset} only ever fetches real bytes for a file
* that is not already present locally, the same lazy-write/eager-list split every other format's
* own external-connection importer in this package already uses.
*/
@ApplicationScoped
public class CodeArtifactPypiExternalConnectionImporter {
private static final Logger LOG = Logger.getLogger(CodeArtifactPypiExternalConnectionImporter.class);
private final CodeArtifactService service;
private final PypiserverSidecarClient pypiserver;
private final PypiExternalConnectionClient externalConnectionClient;
private final ObjectMapper mapper;
// Keyed by repoId+packageName+version: serializes the "is this sibling already written"
// recheck together with the write that follows it, closing the gap a bare in-memory snapshot
// taken once before the whole sibling loop cannot (see tryImportAsset's own loop for the race
// this closes). In-process only, like every other sidecar bookkeeping map in this package: it
// only needs to order concurrent attempts within this one Floci instance, the same scope
// SidecarConcurrency's own per-container locks already have.
private final ConcurrentHashMap<String, Object> siblingWriteLocks = new ConcurrentHashMap<>();
// Fire-and-forget home for the siblings tryImportAsset itself does not wait on (see that
// method's own javadoc). Matches CodePipelineService's own instance-field executor, the only
// precedent anywhere in this codebase for this shape of background work; no CDI
// ManagedExecutor/@Asynchronous/Mutiny usage exists here for it.
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
@Inject
public CodeArtifactPypiExternalConnectionImporter(CodeArtifactService service, PypiserverSidecarClient pypiserver,
PypiExternalConnectionClient externalConnectionClient, ObjectMapper mapper) {
this.service = service;
this.pypiserver = pypiserver;
this.externalConnectionClient = externalConnectionClient;
this.mapper = mapper;
}
@PreDestroy
void shutdown() {
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warn("Pypi sibling import workers did not stop within the shutdown timeout");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warn("Interrupted while stopping pypi sibling import workers", e);
}
}
/**
* One real file the external connection's own Simple API names, not yet known locally:
* {@code yanked} and {@code requiresPythonOrNull} are read straight off that same response
* (PEP 592/PEP 700's {@code yanked} and {@code requires-python} fields) so {@link
* CodeArtifactPypiController#packageIndex} can carry them into the merged index as the real
* {@code data-yanked}/{@code data-requires-python} attributes a real {@code pip} client
* actually looks for when choosing a candidate (raised in review: leaving them off would let
* pip pick a yanked release, or attempt to build an sdist its own interpreter cannot satisfy,
* for a file this emulator has not retained yet, a gap on the very first install, separate
* from this class's own already-documented choice not to refresh retained metadata later).
*/
public record ExternalIndexFile(String filename, boolean yanked, String requiresPythonOrNull) {
}
/**
* The real public repository's own files for {@code packageName} that are not already in
* {@code alreadyKnownFilenames}, for {@link CodeArtifactPypiController#packageIndex} to
* advertise alongside {@code pypiserver}'s own local listing (rewritten to this repository's
* own download route, the same as every locally-known file already is). Advertising a file
* here never fetches or stores its real bytes: that only happens once a real client actually
* requests it, through {@link #tryImportAsset}, the same promise-now/fetch-later split {@code
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} already documents for npm.
*
* <p>A file whose own version resolves to one this repository already marked {@code
* Archived}/{@code Disposed} is left out, the same existence check a per-version download
* itself already enforces through {@link
* CodeArtifactService#requireContainerBackedVersionDownloadable}: the real registry's own
* listing has no idea this repository ever marked it that way, so without this, a disposed
* version could be advertised right back, only to have {@link #tryImportAsset} correctly, but
* confusingly, refuse to write it once actually requested.
*/
public List<ExternalIndexFile> additionalExternalFilenames(String region, String domain, String owner,
String repository, String repoId, String packageName, Set<String> alreadyKnownFilenames) {
String externalConnectionName = pypiExternalConnectionName(region, domain, owner, repository);
if (externalConnectionName == null) {
return List.of();
}
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName)) {
return List.of();
}
JsonNode index = fetchSimpleIndexJson(externalConnectionName, packageName).orElse(null);
if (index == null) {
return List.of();
}
List<String> versions = versionsOf(index);
List<ExternalIndexFile> additional = new ArrayList<>();
for (JsonNode file : index.path("files")) {
String filename = file.path("filename").asText(null);
if (filename == null || alreadyKnownFilenames.contains(filename)) {
continue;
}
Optional<String> version = resolveVersion(versions, packageName, filename);
if (version.isEmpty()) {
continue;
}
try {
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "pypi", null,
packageName, version.get(), repoId);
} catch (AwsException e) {
continue;
}
additional.add(new ExternalIndexFile(filename, file.path("yanked").asBoolean(false),
file.path("requires-python").asText(null)));
}
return additional;
}
/**
* Attempts to retain {@code filename} itself, into {@code repoId}, from {@code repository}'s
* own pypi external connection. Returns {@code true} only when {@code filename} itself is
* genuinely present under this connection's claim by the time this returns: a caller that
* gets {@code false} back should fall through to its own existing not-found response exactly
* as if this method had never been called.
*
* <p>Every other real file of the same resolved version is still retained, matching AWS's own
* documented "CodeArtifact will import all the assets in that package version" behavior, but
* never inline here: this fetches and writes {@code filename} itself synchronously, then hands
* the remaining siblings to a background task under this same claim episode (a second {@link
* CodeArtifactService#claimRetainedVersionOrigin} call, bumping {@code inFlightAttempts} the
* exact way a second concurrent caller already would) and returns as soon as {@code filename}
* is settled. A version can have "over 100 assets," so fetching every one of them inline, in
* order, before answering the one file {@link CodeArtifactPypiController#downloadFile} is
* actually waiting on, could easily outlast a real {@code pip} client's own default 15s read
* timeout on the very first install of a popular package (raised in review: hectorvent, #7741).
*
* <p>{@code filename} is the only identity {@link
* CodeArtifactPypiController#downloadFile} has to work with (pypi's real download route, like
* this emulator's own, names no package or version anywhere in the URL): the package name is
* recovered from it via {@link PypiserverSidecarClient#guessPackageName}, the same filename
* parser the publish-side {@code publish:BLOCK} check already relies on for an identical
* reason, and the version is then recovered by checking {@code filename} against every
* version the real registry's own response names ({@link #resolveVersion}), not guessed
* independently: a version string can appear anywhere inside a real pypi filename (build
* tags, local-version segments), so only checking it against the registry's own actual
* version list, the same way {@link PypiserverSidecarClient#filenameEmbedsVersion} already
* verifies a <em>claimed</em> version against a filename, avoids mismatching whichever version
* happens to parse out syntactically.
*/
public boolean tryImportAsset(String region, String domain, String owner, String repository, String repoId,
String filename) {
String externalConnectionName = pypiExternalConnectionName(region, domain, owner, repository);
if (externalConnectionName == null) {
return false;
}
Optional<String> packageName = PypiserverSidecarClient.guessPackageName(filename);
if (packageName.isEmpty()) {
return false;
}
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName.get())) {
return false;
}
// Snapshotted here, before fetchSimpleIndexJson below issues its own real outbound
// fetch, not after it returns: claimRetainedVersionOrigin's own javadoc documents this
// package-fence snapshot as taken "atomically and before any real network fetch" for
// every format that calls it. Capturing it only after that fetch, as a version's filename
// resolution once did here, would let a DeletePackage racing the fetch go completely
// undetected: the snapshot would already read the post-deletion fence as its own
// baseline, so the claim below would see no change at all and happily reclaim (and
// re-populate) a package this repository just deleted. The real registry's own response
// time is exactly the slow part this snapshot needs to precede (raised in review).
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"pypi", null, packageName.get());
JsonNode index = fetchSimpleIndexJson(externalConnectionName, packageName.get()).orElse(null);
if (index == null) {
return false;
}
List<String> versions = versionsOf(index);
Optional<String> version = resolveVersion(versions, packageName.get(), filename);
if (version.isEmpty()) {
return false;
}
// The version itself can only be resolved from the real registry's own response above
// (pypi's download route, unlike NuGet's, names no version anywhere in the URL), so
// unlike packageFenceSnapshot this cannot be captured any earlier than right here; nothing
// but fast, in-memory work runs between this and the claim immediately below.
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"pypi", null, packageName.get(), version.get());
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
domain, owner, repository, "pypi", null, packageName.get(), version.get(), externalConnectionName,
packageFenceSnapshot);
if (!claim.claimed()) {
return false;
}
boolean importedRequested = false;
boolean importedAny = false;
try {
// What this version already has locally, so a file already retained (by an earlier
// attempt, or a concurrent one under this exact same claim episode) is never
// re-fetched from the real registry just to write back bytes already there. Computed
// inside this try, not before it as a bare statement once did here: a transient
// sidecar failure from this call must still reach the finally below so the claim this
// attempt just took is never left stranded (raised in review) -- a stuck claim would
// make every later attempt for this exact version see it as still externally
// originated even though nothing was ever actually retained.
Set<String> alreadyPresent;
try {
alreadyPresent = Set.copyOf(pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null,
packageName.get(), version.get()));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not list {0} {1}''s existing assets on the pypiserver sidecar while attempting "
+ "a pypi retention through an external connection; treating it as not retained.",
packageName.get(), version.get());
return false;
}
if (alreadyPresent.contains(filename)) {
// Raised the same way npm's own tryImportAsset already handles it: a concurrent
// attempt under this exact same claim episode (see claimRetainedVersionOrigin's
// own javadoc on inFlightAttempts) may already have written this exact file by
// the time this attempt gets here. Only confirming it under this connection, not
// existence alone, tells that apart from some other origin having it.
importedAny = service.retainedVersionOriginConnection(region, domain, owner, repository, "pypi",
null, packageName.get(), version.get()).filter(externalConnectionName::equals).isPresent();
importedRequested = importedAny;
return importedRequested;
}
String importLockKey = repoId + "|" + packageName.get() + "|" + version.get();
// Splits the version's own files into the one filename actually requested (imported
// synchronously below, so downloadFile's own proxy retry has real bytes to serve the
// moment this call returns) and every other sibling, handed off to importRemainingSiblingsInBackground
// rather than fetched inline here (see this method's own javadoc).
JsonNode requestedCandidate = null;
List<JsonNode> remainingSiblings = new ArrayList<>();
for (JsonNode file : index.path("files")) {
String candidateFilename = file.path("filename").asText(null);
String url = file.path("url").asText(null);
if (candidateFilename == null || url == null || alreadyPresent.contains(candidateFilename)) {
continue;
}
if (resolveVersion(versions, packageName.get(), candidateFilename)
.filter(version.get()::equals).isEmpty()) {
continue;
}
if (candidateFilename.equals(filename)) {
requestedCandidate = file;
} else {
remainingSiblings.add(file);
}
}
boolean fenceStillMatched = true;
if (requestedCandidate != null) {
FileImportStatus status = importOneCandidateFile(region, domain, owner, repository, repoId,
packageName.get(), version.get(), externalConnectionName, versionFenceSnapshot,
packageFenceSnapshot, claim.episodeId(), importLockKey, requestedCandidate, filename);
switch (status) {
case WROTE -> {
importedAny = true;
importedRequested = true;
}
case ALREADY_PRESENT -> {
// Mirrors the attempt-start check above: existence alone does not prove
// this connection wrote it. A concurrent attempt under this exact same
// episode may have written it between the outer alreadyPresent snapshot
// and this lock.
importedRequested = service.retainedVersionOriginConnection(region, domain, owner,
repository, "pypi", null, packageName.get(), version.get())
.filter(externalConnectionName::equals).isPresent();
importedAny = importedAny || importedRequested;
}
case FENCE_GONE -> fenceStillMatched = false;
case SKIPPED -> {
// Fetch/size/hash failure: filename genuinely is not present, importedRequested
// stays false.
}
}
}
if (fenceStillMatched && !remainingSiblings.isEmpty()) {
CodeArtifactService.RetainedVersionOriginClaimOutcome backgroundClaim = service
.claimRetainedVersionOrigin(region, domain, owner, repository, "pypi", null,
packageName.get(), version.get(), externalConnectionName, packageFenceSnapshot);
if (backgroundClaim.claimed()) {
List<JsonNode> siblingsToImport = remainingSiblings;
String resolvedPackageName = packageName.get();
String resolvedVersion = version.get();
executor.submit(() -> importRemainingSiblingsInBackground(region, domain, owner, repository,
repoId, resolvedPackageName, resolvedVersion, externalConnectionName,
versionFenceSnapshot, packageFenceSnapshot, backgroundClaim.episodeId(), importLockKey,
siblingsToImport));
}
}
return importedRequested;
} finally {
if (importedAny) {
// Checks the repository's own current sidecar container id, not just a package-
// level deletion fence, matching CodeArtifactNuGetExternalConnectionImporter#
// tryImport rather than npm's/Maven's own plain call: an existence check alone
// cannot tell apart a DeleteRepository followed by a same-name recreate from the
// original repository this attempt's own repoId still names (see
// ensureRetainedPackageOriginDefaultIfCurrentRepository's own javadoc).
service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository,
"pypi", null, packageName.get(), packageFenceSnapshot, repoId);
}
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "pypi", null,
packageName.get(), version.get(), claim.episodeId(), importedAny);
}
}
/**
* Finishes importing {@code siblings} on a background thread, under {@code episodeId} (its
* own claim, taken separately from {@link #tryImportAsset}'s own attempt so each has its own
* {@code inFlightAttempts} slot per {@link CodeArtifactService#claimRetainedVersionOrigin}'s
* own javadoc) -- the part of {@link #tryImportAsset}'s own work the caller never waits on.
* Any fetch/size/hash failure for one sibling only skips that sibling; a version-gone fence
* mismatch stops the whole remaining batch, the same as {@link #tryImportAsset}'s own
* now-synchronous single-file path does.
*/
private void importRemainingSiblingsInBackground(String region, String domain, String owner, String repository,
String repoId, String packageName, String version, String externalConnectionName,
long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, String importLockKey,
List<JsonNode> siblings) {
boolean importedAny = false;
try {
for (JsonNode file : siblings) {
String candidateFilename = file.path("filename").asText(null);
FileImportStatus status = importOneCandidateFile(region, domain, owner, repository, repoId,
packageName, version, externalConnectionName, versionFenceSnapshot, packageFenceSnapshot,
episodeId, importLockKey, file, candidateFilename);
if (status == FileImportStatus.FENCE_GONE) {
break;
}
if (status == FileImportStatus.WROTE) {
importedAny = true;
}
}
} finally {
if (importedAny) {
service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository,
"pypi", null, packageName, packageFenceSnapshot, repoId);
}
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "pypi", null, packageName,
version, episodeId, importedAny);
}
}
private enum FileImportStatus {
WROTE, ALREADY_PRESENT, SKIPPED, FENCE_GONE
}
/**
* Fetches, size/hash-verifies, and writes one real file the registry's own index names, under
* the lock/recheck/write sequence that closes the double-count race two concurrent attempts
* (the synchronous requested-file path and a background sibling batch, or two separate {@code
* pip} requests) could otherwise hit on the exact same {@code candidateFilename} (raised in
* review: a prior fix here narrowed this window but did not close it).
*/
private FileImportStatus importOneCandidateFile(String region, String domain, String owner, String repository,
String repoId, String packageName, String version, String externalConnectionName,
long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, String importLockKey,
JsonNode file, String candidateFilename) {
String url = file.path("url").asText(null);
Optional<PypiExternalConnectionClient.FetchedAsset> fetched;
try {
fetched = externalConnectionClient.fetchFile(externalConnectionName, url);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not fetch {0} from {1} while retaining a pypi package through an "
+ "external connection; skipping this file.", url, externalConnectionName);
return FileImportStatus.SKIPPED;
}
if (fetched.isEmpty()) {
return FileImportStatus.SKIPPED;
}
byte[] content = fetched.get().content();
// The same 5 GB AWS quota CodeArtifactPypiController#upload already enforces on a direct
// publish: without this, a single huge real file would be buffered whole (fetchFile has no
// streaming size cap of its own) and then written and counted as if any size were
// acceptable here just because it came from an external connection rather than a direct
// upload (raised in review).
if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) {
LOG.warnv("Skipping {0}: the real registry''s own file is larger than this emulator''s "
+ "{1}-byte asset quota.", candidateFilename, CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
return FileImportStatus.SKIPPED;
}
// PEP 691/700's own hashes.sha256, verified against the real fetched bytes before they are
// ever written: fetchFile already restricts which host a file's bytes can come from, but a
// host passing that check is not the same as the bytes genuinely matching what the trusted
// index response itself said this exact file is (a truncated transfer, or a compromised/
// misbehaving file host, would otherwise be retained and served as if it were correct).
// Verified only when the index actually names a hash (PEP 691 makes the field optional,
// though pypi.org's own real responses always include it): its absence is not itself proof
// of tampering, so this does not refuse a file over a missing hash alone, only a mismatched
// one.
String expectedSha256 = file.path("hashes").path("sha256").asText(null);
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(sha256Hex(content))) {
LOG.warnv("Skipping {0}: its real bytes do not match the sha256 the registry''s own index "
+ "names for it.", candidateFilename);
return FileImportStatus.SKIPPED;
}
// The lock below, the recheck inside it, and the write together close a gap the bare
// in-memory alreadyPresent snapshot taken once before this whole import started cannot on
// its own: a second call into this exact version -- a different pip request racing this
// one, or the background sibling batch racing the synchronous requested-file path -- could
// reach the very same candidate. retainAssetUnderVersionFence's own write has no way to
// tell a fresh write from a re-write of identical content (see AssetRetentionAttemptResult's
// own javadoc), so without serializing the recheck and the write together on a lock keyed
// to this exact version, two such calls could both see candidateFilename missing and both
// write it, double-counting its bytes in DescribeDomain's assetSizeBytes.
synchronized (siblingWriteLocks.computeIfAbsent(importLockKey, key -> new Object())) {
if (pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, packageName, version)
.contains(candidateFilename)) {
return FileImportStatus.ALREADY_PRESENT;
}
// The fence check and the real write happen inside the very same synchronized call
// DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions already
// hold across their own entire operation, so a write here and one of those four
// operations can never interleave.
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
domain, owner, repository, "pypi", null, packageName, version, versionFenceSnapshot,
packageFenceSnapshot, episodeId, repoId, candidateFilename, content,
() -> pypiserver.storePackageVersionAsset(repoId, domain, repository, null, packageName, version,
candidateFilename, content));
if (!result.fenceMatched()) {
// The version itself is gone: every later candidate in this same attempt would
// fail the exact same way.
return FileImportStatus.FENCE_GONE;
}
return result.wroteNewContent() ? FileImportStatus.WROTE : FileImportStatus.SKIPPED;
}
}
private Optional<JsonNode> fetchSimpleIndexJson(String externalConnectionName, String packageName) {
Optional<PypiExternalConnectionClient.FetchedAsset> fetched;
try {
fetched = externalConnectionClient.fetchSimpleIndex(externalConnectionName, packageName);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not fetch {0}''s simple index from {1} while resolving its versions through an "
+ "external connection; leaving it unresolved.", packageName, externalConnectionName);
return Optional.empty();
}
if (fetched.isEmpty()) {
return Optional.empty();
}
try {
return Optional.of(mapper.readTree(fetched.get().content()));
} catch (IOException e) {
LOG.warnv(e, "Could not parse {0}''s simple index fetched from {1}; leaving it unresolved.", packageName,
externalConnectionName);
return Optional.empty();
}
}
private static List<String> versionsOf(JsonNode index) {
List<String> versions = new ArrayList<>();
for (JsonNode version : index.path("versions")) {
String text = version.asText(null);
if (text != null) {
versions.add(text);
}
}
return versions;
}
/**
* Which of {@code candidateVersions} {@code filename} actually belongs to, checked with
* {@link PypiserverSidecarClient#filenameEmbedsVersion} rather than parsed independently from
* the filename alone: a version string can appear more than once inside a real filename (a
* local-version segment, a build tag), so only testing it against the registry's own real,
* already-known version list tells a genuine match from a coincidental one.
*/
private static Optional<String> resolveVersion(List<String> candidateVersions, String packageName,
String filename) {
return candidateVersions.stream()
.filter(version -> PypiserverSidecarClient.filenameEmbedsVersion(filename, packageName, version))
.findFirst();
}
private static String sha256Hex(byte[] content) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is not available in this JVM", e);
}
}
private String pypiExternalConnectionName(String region, String domain, String owner, String repository) {
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
.filter(ec -> "pypi".equals(ec.getPackageFormat()))
.map(ExternalConnection::getExternalConnectionName)
.findFirst()
.orElse(null);
}
}
@@ -0,0 +1,263 @@
package io.floci.aws.services.codeartifact;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* A real outbound client for the one public pypi repository CodeArtifact's {@code public:pypi}
* external connection names: {@code https://pypi.org}, confirmed live, not inferred.
*
* <p>Unlike NuGet's deterministic {@code {id}/{version}/{filename}} content route, a real PyPI
* file's actual download URL is not deterministic from its coordinate: {@code
* files.pythonhosted.org} serves it under an opaque, per-file hash path (confirmed live, e.g.
* {@code /packages/d3/5b/<hash>/is-even-0.0.0.tar.gz}), so there is no path this client can build
* on its own the way {@link NuGetExternalConnectionClient} does. {@link #fetchSimpleIndex} is
* what actually supplies that real URL, one package at a time, read directly off the real
* registry's own PEP 691 JSON Simple API response ({@code files[].url}); {@link #fetchFile} just
* follows whatever absolute URL the caller read out of that trusted response, never one supplied
* by anything outside this client's own fixed, hardcoded {@code public:pypi} base.
*
* <p>{@link #fetchSimpleIndex} requests the JSON form of the real Simple API (PEP 691, {@code
* Accept: application/vnd.pypi.simple.v1+json}) rather than the plain-HTML form every pypi
* client is guaranteed to support, the same deliberate choice {@link NpmExternalConnectionClient}
* already makes for npm's own abbreviated packument format: confirmed live against {@code
* pypi.org} that this content type is served, and real pip itself also prefers it over HTML via
* the exact same content negotiation when the index advertises it, so this is still the real wire
* shape a real client uses, not a different endpoint invented for this emulator's own
* convenience. The JSON form's {@code files} entries carry no explicit version field of their
* own (confirmed live): {@link CodeArtifactPypiExternalConnectionImporter} resolves a file's
* version from its filename, the same way a real {@code pip}/{@code pypiserver} installation
* does, using the response's own top-level {@code versions} array as the candidate list.
*
* <p>Every failure mode (an unknown connection name, a real non-200 response, a network error)
* resolves to {@link Optional#empty()} rather than throwing: a caller here is always deciding
* whether to retain a package version from an external source, and AWS's own documented behavior
* for an unreachable external repository is to behave exactly as if the asset were not found,
* with no special error surfaced to the client.
*/
@ApplicationScoped
public class PypiExternalConnectionClient {
private static final Logger LOG = Logger.getLogger(PypiExternalConnectionClient.class);
private static final String SIMPLE_JSON_ACCEPT = "application/vnd.pypi.simple.v1+json";
private static final Map<String, String> BASE_URLS = Map.of(
"public:pypi", "https://pypi.org");
/**
* Real hosts {@link #fetchFile} trusts for a given connection name beyond that connection's
* own simple-index host (confirmed live: {@code public:pypi}'s real files are served from
* {@code files.pythonhosted.org}, a different host than {@code pypi.org} itself). Kept
* separate from {@link #baseUrls} rather than folded into it, since a connection's index host
* and its real file host are not the same thing here, unlike every other format's own client
* in this package.
*/
private static final Map<String, Set<String>> ADDITIONAL_TRUSTED_FILE_HOSTS = Map.of(
"public:pypi", Set.of("files.pythonhosted.org"));
/** Maximum number of redirect hops {@link #fetchFile} will chase manually, matching the JDK's
* own default cap for {@link HttpClient.Redirect#NORMAL}. */
private static final int MAX_FILE_REDIRECTS = 5;
private final HttpClient httpClient;
private final HttpClient fileHttpClient;
private final Map<String, String> baseUrls;
private final Map<String, Set<String>> additionalTrustedFileHosts;
@Inject
public PypiExternalConnectionClient() {
this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(), BASE_URLS);
}
/** For tests: a fake base-URL map, so the wire contract can be exercised against a local
* {@code HttpServer} fake instead of the real public registry. */
PypiExternalConnectionClient(HttpClient httpClient, Map<String, String> baseUrls) {
this(httpClient, baseUrls, ADDITIONAL_TRUSTED_FILE_HOSTS);
}
/** For tests: also overrides {@link #ADDITIONAL_TRUSTED_FILE_HOSTS} directly, so {@link
* #fetchFile}'s host check can be exercised without relying on real DNS for a second host. */
PypiExternalConnectionClient(HttpClient httpClient, Map<String, String> baseUrls,
Map<String, Set<String>> additionalTrustedFileHosts) {
this.httpClient = httpClient;
// Deliberately its own client, built with Redirect.NEVER regardless of whatever policy
// httpClient above was given: isTrustedFileHost below only ever inspects the URI this
// client is about to request, never one somewhere in the middle of an auto-followed
// redirect chain. A java.net.http.HttpClient's redirect policy is client-wide, not
// overridable per-request, so sharing httpClient here (built with Redirect.NORMAL in
// production, matching every sibling external-connection client) would let a 3xx response
// from a host that genuinely passed that check silently hand this request to an entirely
// different, unchecked host before fetchFile ever sees the final response, defeating the
// host check below. fetchFile instead chases a redirect itself, one hop at a time,
// re-validating the new location's host before ever requesting it.
this.fileHttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NEVER).build();
this.baseUrls = baseUrls;
this.additionalTrustedFileHosts = additionalTrustedFileHosts;
}
/** One package's real Simple API response, or one real file's bytes, fetched from the real
* public registry. */
public record FetchedAsset(byte[] content) {}
/**
* Fetches {@code packageName}'s own real PEP 691 JSON Simple API response from the real
* public registry {@code externalConnectionName} names. {@code packageName} is normalized
* (PEP 503) before being placed in the request path, matching real pip's own behavior and
* the real registry's own case/separator-insensitive routing (confirmed live: an
* un-normalized name still resolves there, but the normalized spelling is what this
* emulator's own sidecar and controller already standardize on everywhere else).
*/
public Optional<FetchedAsset> fetchSimpleIndex(String externalConnectionName, String packageName) {
String baseUrl = baseUrls.get(externalConnectionName);
if (baseUrl == null) {
return Optional.empty();
}
String normalized = PypiserverSidecarClient.normalizePackageName(packageName);
URI uri = SidecarUriUtils.combine(URI.create(baseUrl),
"/simple/" + SidecarUriUtils.encodeSegment(normalized) + "/");
try {
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(20))
.header("Accept", SIMPLE_JSON_ACCEPT)
.GET()
.build();
HttpResponse<byte[]> response = httpClient.send(request, BodyHandlers.ofByteArray());
return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Optional.empty();
} catch (IOException e) {
LOG.warnv("Could not fetch {0}''s simple index from external connection {1}: {2}", packageName,
externalConnectionName, e.getMessage());
return Optional.empty();
}
}
/**
* Fetches one real file's bytes from {@code fileUrl}, an absolute URL the caller must have
* read directly off a {@link #fetchSimpleIndex} response already confirmed to have come from
* {@code externalConnectionName}'s own fixed base: this never accepts or builds a URL of its
* own, since a real PyPI file's own storage path ({@code files.pythonhosted.org}'s opaque
* hash directories) cannot be computed from a coordinate the way every other sidecar client
* here can.
*
* <p>Unlike every other sidecar client here, this is the one place in this package that
* issues a real outbound request to a URL read out of response <i>content</i> rather than
* built from a fixed, hardcoded base, so {@code externalConnectionName}'s recognition alone
* is not enough: {@code fileUrl}'s own host must also match either that connection's own
* simple-index host, or one of its {@link #ADDITIONAL_TRUSTED_FILE_HOSTS}. This never widens
* to "any host the real registry's response happens to mention," only the specific,
* confirmed-live file host {@code public:pypi} actually uses, the same fixed-allowlist shape
* {@link #baseUrls} itself already is.
*
* <p>That same host check is re-applied to every redirect hop, not just {@code fileUrl}
* itself: {@link #fileHttpClient} is built with {@link HttpClient.Redirect#NEVER} specifically
* so a {@code 3xx} response is handled right here rather than chased transparently inside
* {@link HttpClient#send}, since an auto-followed redirect would hand the real request to
* whatever host the response names before this method ever gets a chance to check it.
*/
public Optional<FetchedAsset> fetchFile(String externalConnectionName, String fileUrl) {
String baseUrl = baseUrls.get(externalConnectionName);
if (baseUrl == null) {
return Optional.empty();
}
URI uri;
try {
uri = URI.create(fileUrl);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
for (int hop = 0; hop <= MAX_FILE_REDIRECTS; hop++) {
if (!isTrustedFileHost(externalConnectionName, baseUrl, uri)) {
LOG.warnv("Refusing to fetch {0} for external connection {1}: its host is not a trusted file "
+ "host for that connection.", uri, externalConnectionName);
return Optional.empty();
}
HttpResponse<byte[]> response;
try {
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(30))
.GET()
.build();
response = fileHttpClient.send(request, BodyHandlers.ofByteArray());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Optional.empty();
} catch (IOException e) {
LOG.warnv("Could not fetch {0} from external connection {1}: {2}", uri, externalConnectionName,
e.getMessage());
return Optional.empty();
}
if (isRedirect(response.statusCode())) {
String location = response.headers().firstValue("Location").orElse(null);
if (location == null) {
return Optional.empty();
}
try {
uri = uri.resolve(location);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
continue;
}
return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty();
}
LOG.warnv("Too many redirects fetching {0} from external connection {1}; giving up.", fileUrl,
externalConnectionName);
return Optional.empty();
}
private static boolean isRedirect(int statusCode) {
return statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307
|| statusCode == 308;
}
/**
* Whether {@code fileUrl}'s own host is one this client actually trusts for
* {@code externalConnectionName}: either {@code baseUrl}'s own host (every file this
* connection's own simple-index host happens to serve directly), or one of this instance's
* {@code additionalTrustedFileHosts} for that same connection name. A host comparison, not a
* prefix comparison: a lookalike host such as {@code files.pythonhosted.org.evil.example}
* must not pass just because it starts with a trusted name.
*
* <p>Also requires {@code fileUri}'s own scheme to match {@code baseUrl}'s (raised in
* review): a host check alone says nothing about the scheme, so a {@code http://} URL, or a
* redirect hop downgrading to one, naming an otherwise-trusted host would still pass it,
* sending the real file's bytes in plaintext even though {@code public:pypi}'s own
* configured base is {@code https}. Compared against {@code baseUrl}'s own scheme rather than
* a hardcoded {@code https}, the same way the host check already compares against its own
* host rather than a hardcoded name, so the local {@code HttpServer} fakes this class's own
* tests run against (plain {@code http}) keep working unchanged.
*/
private boolean isTrustedFileHost(String externalConnectionName, String baseUrl, URI fileUri) {
String host = fileUri.getHost();
if (host == null) {
return false;
}
URI base = URI.create(baseUrl);
if (!base.getScheme().equalsIgnoreCase(fileUri.getScheme())) {
return false;
}
String baseHost = base.getHost();
if (host.equalsIgnoreCase(baseHost)) {
return true;
}
return additionalTrustedFileHosts.getOrDefault(externalConnectionName, Set.of()).stream()
.anyMatch(host::equalsIgnoreCase);
}
}
@@ -124,13 +124,16 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
}
/**
* PEP 503 normalization: lowercase, runs of {@code -_.} collapsed to one {@code -}, same as
* {@code CodeArtifactPypiController}'s own pre-upload index check. {@code -} and {@code _}
* PEP 503 normalization: lowercase, runs of {@code -_.} collapsed to one {@code -}. Not
* {@code private}: {@code CodeArtifactPypiController}'s own pre-upload index check and the
* pypi external-connection classes ({@link PypiExternalConnectionClient}, {@link
* CodeArtifactPypiExternalConnectionImporter}) all need the exact same normalization, so this
* is the one copy all of them call rather than each keeping its own. {@code -} and {@code _}
* collapsing to the same character here is what lets this match a filename's own escaped
* name portion (wheels, and modern sdists, replace a name's internal {@code -}/{@code .}
* with {@code _}) against the caller-supplied, unescaped {@code packageName}.
*/
private static String normalizePackageName(String packageName) {
static String normalizePackageName(String packageName) {
return packageName.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-");
}
@@ -17,8 +17,10 @@ import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -30,6 +32,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -63,6 +66,7 @@ class CodeArtifactPypiControllerTest {
private String backendUrl;
private CodeArtifactService service;
private PypiserverSidecarClient pypiserver;
private CodeArtifactPypiExternalConnectionImporter externalConnectionImporter;
private CodeArtifactPypiController controller;
@BeforeEach
@@ -84,9 +88,13 @@ class CodeArtifactPypiControllerTest {
when(service.containerBackedOverriddenVersionStatusesByRepository(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"))).thenReturn(Map.of());
when(pypiserver.ensureReady(eq("pypi-repo-id"), any())).thenReturn(backendUrl);
// Mockito's own default answer already returns an empty List/false for every unstubbed
// method here, matching a repository with no pypi external connection configured at all;
// individual tests below override specific calls to exercise the merge/retention paths.
externalConnectionImporter = mock(CodeArtifactPypiExternalConnectionImporter.class);
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
controller = new CodeArtifactPypiController(service, pypiserver, httpClient);
controller = new CodeArtifactPypiController(service, pypiserver, externalConnectionImporter, httpClient);
}
@AfterEach
@@ -161,6 +169,171 @@ class CodeArtifactPypiControllerTest {
assertEquals(404, response.getStatus());
}
/**
* AWS's own documented trigger for a pypi external connection: a real local miss. The fake
* backend answers 404 first (nothing retained yet) and 200 once the importer reports a
* successful retention, standing in for pypiserver actually having the file by the time this
* controller retries.
*/
@Test
void downloadFileRetainsFromTheExternalConnectionOnALocalMissThenServesTheRealBytes() {
AtomicInteger requestCount = new AtomicInteger();
backend.createContext("/packages/ext-pkg-1.0.0.tar.gz", exchange -> {
if (requestCount.getAndIncrement() == 0) {
respond(exchange, 404, "text/plain", "");
} else {
respond(exchange, 200, "application/octet-stream", "real-upstream-bytes");
}
});
when(externalConnectionImporter.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, "pypi-repo-id",
"ext-pkg-1.0.0.tar.gz")).thenReturn(true);
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY,
"ext-pkg-1.0.0.tar.gz");
assertEquals(200, response.getStatus());
assertEquals("real-upstream-bytes", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
assertEquals(2, requestCount.get());
}
@Test
void downloadFileStaysA404WhenTheExternalConnectionDoesNotHaveItEither() {
backend.createContext("/packages/unknown-everywhere.tar.gz",
exchange -> respond(exchange, 404, "text/plain", ""));
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY,
"unknown-everywhere.tar.gz");
assertEquals(404, response.getStatus());
verify(externalConnectionImporter).tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, "pypi-repo-id",
"unknown-everywhere.tar.gz");
}
/**
* {@link #packageIndexRewritesRootRelativePackageLinksToThisRepositorysPathPrefix} already
* covers the plain local-listing path; this one proves the external-connection merge actually
* runs alongside it, adding an entry pypiserver's own local index never listed.
*/
@Test
void packageIndexMergesInAFileTheExternalConnectionNamesThatIsNotKnownLocally() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 200, "text/html",
"<a href=\"/packages/my-pkg-1.0.tar.gz\">my-pkg-1.0.tar.gz</a>"));
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("my-pkg"), eq(Set.of("my-pkg-1.0.tar.gz"))))
.thenReturn(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(
"my-pkg-2.0.tar.gz", false, null)));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg");
assertEquals(200, response.getStatus());
String body = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
assertTrue(body.contains("href=\"/codeartifact/pypi/" + DOMAIN + "/" + REPOSITORY
+ "/packages/my-pkg-1.0.tar.gz\""), body);
assertTrue(body.contains("href=\"/codeartifact/pypi/" + DOMAIN + "/" + REPOSITORY
+ "/packages/my-pkg-2.0.tar.gz\""), body);
}
/**
* {@code additionalExternalFilenames} ultimately returns whatever a real external connection's
* own response named: nothing here enforces that it is free of characters HTML would read as
* markup. The real pypi.org registry's own filenames are strictly validated and could never
* actually contain any of these, but {@code withAdditionalFilenames}/{@code escapeHtml} are
* written as though the input is untrusted, and had no test actually proving that, unlike the
* hash/slash/question-mark literal tests the rest of this proxy already has for other inputs.
*/
@Test
void packageIndexEscapesAnExternalFilenameBeforePlacingItInTheMergedHtml() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
String wicked = "wicked\"><script>alert(1)</script>.tar.gz";
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("my-pkg"), eq(Set.of())))
.thenReturn(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(wicked, false,
null)));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg");
assertEquals(200, response.getStatus());
String body = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
assertTrue(body.contains("wicked&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;.tar.gz"), body);
assertFalse(body.contains("<script>"), body);
assertFalse(body.contains("wicked\">"), body);
}
/**
* Mirrors {@link #downloadFileTreatsAHashInTheFilenameAsLiteralNotAUriFragment} for the merge
* side: HTML-escaping alone would leave a literal {@code #} free to be read as a URI fragment
* by whatever real client resolves this href, silently truncating the path it actually
* requests to everything before the {@code #}.
*/
@Test
void packageIndexPercentEncodesAHashInAnExternalFilenameInsteadOfLeavingItAsAUriFragment() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("my-pkg"), eq(Set.of())))
.thenReturn(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(
"my-pkg-1.0#evil.tar.gz", false, null)));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg");
assertEquals(200, response.getStatus());
String body = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
assertTrue(body.contains("href=\"/codeartifact/pypi/" + DOMAIN + "/" + REPOSITORY
+ "/packages/my-pkg-1.0%23evil.tar.gz\""), body);
}
/**
* A package pypiserver has never heard of (no local upload, ever) but that the real public
* registry has must still be listable, the same as real CodeArtifact: without this, a package
* could only ever be discovered through an external connection after some other request
* happened to retain one of its files first.
*/
@Test
void packageIndexListsAPackageThatOnlyExistsOnTheExternalConnectionSoFar() {
backend.createContext("/simple/only-external/", exchange -> respond(exchange, 404, "text/plain", ""));
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("only-external"), eq(Set.of())))
.thenReturn(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(
"only-external-1.0.tar.gz", false, null)));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "only-external");
assertEquals(200, response.getStatus());
String body = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
assertTrue(body.contains("href=\"/codeartifact/pypi/" + DOMAIN + "/" + REPOSITORY
+ "/packages/only-external-1.0.tar.gz\""), body);
}
/**
* The fix for a real finding: a real pip client filters candidates using exactly these two
* attributes (PEP 592/PEP 700). Without them, a file this repository has not retained yet
* would look unconditionally eligible on the very first install even though the registry's
* own response already named it yanked or Python-incompatible.
*/
@Test
void packageIndexEmitsDataYankedAndDataRequiresPythonForAnExternalFile() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("my-pkg"), eq(Set.of())))
.thenReturn(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(
"my-pkg-1.0.tar.gz", true, ">=3.9")));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg");
assertEquals(200, response.getStatus());
String body = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
assertTrue(body.contains("data-requires-python=\"&gt;=3.9\""), body);
assertTrue(body.contains("data-yanked=\"\""), body);
}
@Test
void packageIndexStaysA404WhenNeitherLocalNorTheExternalConnectionHasThePackage() {
backend.createContext("/simple/nowhere/", exchange -> respond(exchange, 404, "text/plain", ""));
Response response = controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "nowhere");
assertEquals(404, response.getStatus());
}
/**
* The fix for a real finding: building the request URI with a plain string concatenation
* would let a {@code #} in a caller-supplied filename get interpreted as a URI fragment and
@@ -237,6 +410,8 @@ class CodeArtifactPypiControllerTest {
assertEquals(404, response.getStatus());
assertEquals(false, downloadReceived.get());
verify(pypiserver).endUse("pypi-repo-id");
// Retention must never resurrect a version this repository already marked Archived.
verify(externalConnectionImporter, never()).tryImportAsset(any(), any(), any(), any(), any(), any());
}
/**
@@ -0,0 +1,189 @@
package io.floci.aws.services.codeartifact;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Retains a real pypi package version from the real, live {@code public:pypi} repository (not a
* local fake), through the native simple-repository route, the way a real {@code pip install}
* would. {@code is-even} 0.0.0 is picked because it is tiny (its one real sdist is about 1.3 KB)
* and unlikely to ever be pulled from pypi.org or change. A genuine network dependency, unlike
* every other sidecar-backed test here, which only ever talks to a container Floci itself
* started; see {@code CodeArtifactPypiExternalConnectionImporterTest} for the mocked,
* deterministic coverage of the claim/fence/mixed-origin logic this test does not re-exercise.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactPypiExternalConnectionDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "pypi-external-connection-domain";
private static final String REPO = "pypi-external-connection-repo";
private static final String BLOCKED_REPO = "pypi-external-connection-blocked-repo";
private static final String PACKAGE_NAME = "is-even";
private static final String VERSION = "0.0.0";
private static final String FILENAME = "is-even-0.0.0.tar.gz";
// The real pypi.org registry also has a wheel for this exact version: proves AWS's own
// documented "CodeArtifact will import all the assets in that package version" by fetching
// only the sdist above and then finding the wheel already retained alongside it, never
// fetched directly.
private static final String SIBLING_WHEEL_FILENAME = "is_even-0.0.0-py3-none-any.whl";
private static String bearerToken;
@BeforeAll
static void setUp() {
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.pypi-image");
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void createDomainRepositoriesConnectionAndToken() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
+ "&external-connection=public:pypi")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
+ "&external-connection=public:pypi")
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
@Test
@Order(1)
void theSimpleIndexListsTheRealFileBeforeItIsEverDownloaded() {
String indexHtml = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(200)
.extract().asString();
assertThat(indexHtml, containsString(FILENAME));
}
@Test
@Order(2)
void fetchingAMissingFileRetainsItFromTheRealPypiOrgConnectionAndCountsItsBytes() {
long assetSizeBytesBefore = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(0L, assetSizeBytesBefore);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + FILENAME)
.then().statusCode(200)
.extract().asByteArray();
// A real sdist is a real gzip: 0x1f 0x8b magic bytes, not asserting exact content since
// the real artifact is out of this test's control.
assertEquals(0x1f, fetched[0] & 0xFF);
assertEquals(0x8b, fetched[1] & 0xFF);
// AWS: "CodeArtifact will import all the assets in that package version" -- the real
// sibling wheel for this exact version must already be retained too, never fetched
// directly by this test.
byte[] siblingWheel = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + SIBLING_WHEEL_FILENAME)
.then().statusCode(200)
.extract().asByteArray();
// A real wheel is a real zip: "PK" magic bytes.
assertEquals('P', (char) siblingWheel[0]);
assertEquals('K', (char) siblingWheel[1]);
// Proves both files' bytes are actually counted toward DescribeDomain's assetSizeBytes,
// the same way a direct twine upload already is.
long assetSizeBytesAfter = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(assetSizeBytesBefore + fetched.length + siblingWheel.length, assetSizeBytesAfter);
}
@Test
@Order(3)
void refetchingTheSameFileServesItWithoutRetainingItAgain() {
long assetSizeBytesBefore = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + FILENAME)
.then().statusCode(200)
.extract().asByteArray();
assertEquals(0x1f, fetched[0] & 0xFF);
assertEquals(0x8b, fetched[1] & 0xFF);
long assetSizeBytesAfter = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(assetSizeBytesBefore, assetSizeBytesAfter);
}
@Test
@Order(4)
void aRetainedVersionReportsAnExternalOriginNotInternal() {
given().header("Authorization", AUTH)
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=pypi&package="
+ PACKAGE_NAME)
.then().statusCode(200)
.body("versions[0].version", equalTo(VERSION))
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
.body("versions[0].origin.domainEntryPoint.externalConnectionName", equalTo("public:pypi"));
}
@Test
@Order(5)
void upstreamBlockPreventsRetentionEvenThoughTheRealPackageExists() {
putPackageOriginConfiguration(AUTH, DOMAIN, BLOCKED_REPO, "pypi", null, PACKAGE_NAME, "ALLOW", "BLOCK");
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + BLOCKED_REPO + "/packages/" + FILENAME)
.then().statusCode(404);
given().header("Authorization", AUTH)
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=pypi&package="
+ PACKAGE_NAME)
.then().statusCode(200)
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
}
@Test
@Order(6)
void aFileTheRealRepositoryDoesNotHaveIsNeverRetained() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/does-not-exist-9.9.9.tar.gz")
.then().statusCode(404);
}
}
@@ -0,0 +1,545 @@
package io.floci.aws.services.codeartifact;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link CodeArtifactPypiExternalConnectionImporter}'s own decision logic: when it attempts a
* real external-connection fetch at all, which real files it imports together for a resolved
* version, and what it writes back. {@link PypiserverSidecarClient} and {@link
* PypiExternalConnectionClient} are both mocked, so no real network or pypiserver call ever
* happens here; their own wire contracts have their own tests.
*/
class CodeArtifactPypiExternalConnectionImporterTest {
private static final String REGION = "us-east-1";
private static final String DOMAIN = "dom";
private static final String OWNER = "123456789012";
private static final String REPOSITORY = "repo";
private static final String REPO_ID = "repo-id";
private static final String PACKAGE_NAME = "widget";
private static final String VERSION = "1.0.0";
private static final String SDIST_FILENAME = "widget-1.0.0.tar.gz";
private static final String WHEEL_FILENAME = "widget-1.0.0-py3-none-any.whl";
private static final byte[] SDIST_CONTENT = "sdist-content".getBytes();
private static final byte[] WHEEL_CONTENT = "wheel-content".getBytes();
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
private static final long EPISODE_ID = 7L;
private final ObjectMapper mapper = new ObjectMapper();
private CodeArtifactService service;
private PypiserverSidecarClient pypiserver;
private PypiExternalConnectionClient externalConnectionClient;
private CodeArtifactPypiExternalConnectionImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
pypiserver = mock(PypiserverSidecarClient.class);
externalConnectionClient = mock(PypiExternalConnectionClient.class);
importer = new CodeArtifactPypiExternalConnectionImporter(service, pypiserver, externalConnectionClient,
mapper);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of(new ExternalConnection("public:pypi", "pypi", "AVAILABLE")));
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString())).thenReturn(false);
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString())).thenReturn(42L);
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString())).thenReturn(99L);
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyString(), anyLong()))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
when(pypiserver.listPackageVersionAssetNames(anyString(), anyString(), anyString(), any(), anyString(),
anyString())).thenReturn(List.of());
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(
simpleIndexJson(List.of(VERSION), SDIST_FILENAME, WHEEL_FILENAME))));
when(externalConnectionClient.fetchFile(eq("public:pypi"), eq(urlFor(SDIST_FILENAME))))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(SDIST_CONTENT)));
when(externalConnectionClient.fetchFile(eq("public:pypi"), eq(urlFor(WHEEL_FILENAME))))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(WHEEL_CONTENT)));
}
@Test
void importsTheRequestedFileFromTheExternalConnection() {
// No wheel sibling in this version's own index, so nothing is handed off to the
// background executor here: sibling handoff has its own dedicated test below.
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(
simpleIndexJson(List.of(VERSION), SDIST_FILENAME))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
"pypi", null, PACKAGE_NAME, 42L, REPO_ID);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
@Test
void importsEveryRealSiblingOfTheResolvedVersionNotJustTheRequestedFile() {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, WHEEL_FILENAME);
assertTrue(imported);
// The requested file (the wheel) is written synchronously, so it is already there the
// moment tryImportAsset returns.
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(WHEEL_FILENAME), eq(WHEEL_CONTENT), any());
// AWS: "CodeArtifact will import all the assets in that package version" -- the sdist is
// still imported, just handed off to run in the background (raised in review: hectorvent,
// #7741), so this waits for it rather than asserting it happened synchronously.
verify(service, timeout(2000)).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(),
eq(EPISODE_ID), eq(REPO_ID), eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
}
@Test
void skipsAFileAlreadyPresentLocallyWithoutRefetchingIt() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(List.of(SDIST_FILENAME));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, WHEEL_FILENAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchFile(eq("public:pypi"), eq(urlFor(SDIST_FILENAME)));
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
}
@Test
void returnsFalseWhenNoPypiExternalConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of());
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void returnsFalseWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME))
.thenReturn(true);
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchSimpleIndex(anyString(), anyString());
}
@Test
void returnsFalseWhenTheFilenameCannotBeParsedIntoAPackageName() {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "not-a-real-file");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchSimpleIndex(anyString(), anyString());
}
@Test
void returnsFalseWhenTheRealIndexNamesNoVersionTheFilenameActuallyMatches() {
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(
simpleIndexJson(List.of("2.0.0"), "widget-2.0.0.tar.gz"))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION, "public:pypi", 42L))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString());
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
}
@Test
void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedTheExactFile() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(List.of(SDIST_FILENAME));
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.of("public:pypi"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
/**
* Unlike npm's/NuGet's own single-asset attempt, this one can loop over as many real sibling
* files as the registry lists (AWS: "some contain over 100 assets"), long enough for a
* concurrent sibling attempt under this exact same claim episode to have already written a
* later candidate by the time this one's own slow fetch for it finishes. Simulated here by
* having {@code listPackageVersionAssetNames} answer empty on the attempt-start snapshot, then
* list the sdist from the second call onward, as if a sibling attempt wrote it in that gap.
*/
@Test
void skipsWritingASiblingThatAConcurrentAttemptAlreadyWroteWhileThisOneWasStillFetching() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(List.of(), List.of(SDIST_FILENAME));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, WHEEL_FILENAME);
assertTrue(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(WHEEL_FILENAME), eq(WHEEL_CONTENT), any());
}
/**
* The same race as above, but landing on the specifically requested file rather than a
* sibling: this attempt's own return value must still reflect it as imported, confirmed under
* this connection exactly the way the attempt-start check already does, without writing it a
* second time.
*/
@Test
void confirmsTheRequestedFileWithoutRewritingItWhenAConcurrentAttemptWroteItWhileThisOneWasStillFetching() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(List.of(), List.of(SDIST_FILENAME));
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.of("public:pypi"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertTrue(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
}
/**
* A direct {@code twine} publish can land between this attempt's own claim and the local
* existence check below; existence alone proves nothing about who actually wrote it. Mirrors
* {@code CodeArtifactNuGetExternalConnectionImporterTest}'s identical case for nuget.
*/
@Test
void doesNotMislabelAFileADirectPublishWroteDuringTheRaceAsExternallyRetained() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(List.of(SDIST_FILENAME));
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.empty());
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void additionalExternalFilenamesMergesFilesNotAlreadyKnownLocally() {
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of(SDIST_FILENAME));
assertEquals(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(WHEEL_FILENAME, false,
null)), additional);
}
/**
* The fix for a real finding: without these, a file this repository has not retained yet
* would look unconditionally eligible to a real pip client evaluating the merged index, even
* though the real registry's own response already said it is yanked or needs a different
* interpreter.
*/
@Test
void additionalExternalFilenamesCarriesYankedAndRequiresPythonMetadataThrough() {
ObjectNode root = mapper.createObjectNode();
root.put("name", PACKAGE_NAME);
root.putArray("versions").add(VERSION);
ObjectNode file = root.putArray("files").addObject();
file.put("filename", WHEEL_FILENAME);
file.put("url", urlFor(WHEEL_FILENAME));
file.put("yanked", true);
file.put("requires-python", ">=3.9");
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(toBytes(root))));
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of());
assertEquals(List.of(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(WHEEL_FILENAME, true,
">=3.9")), additional);
}
@Test
void additionalExternalFilenamesExcludesAFileForAnArchivedVersion() {
doThrow(new AwsException("ResourceNotFoundException", "Package version '1.0.0' is Archived.", 404))
.when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, REPOSITORY, "pypi",
null, PACKAGE_NAME, VERSION, REPO_ID);
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of());
assertEquals(List.of(), additional);
}
@Test
void additionalExternalFilenamesReturnsEmptyWhenNoConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of());
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of());
assertEquals(List.of(), additional);
}
@Test
void additionalExternalFilenamesReturnsEmptyWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME))
.thenReturn(true);
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of());
assertEquals(List.of(), additional);
}
/**
* The fix for a real finding: claimRetainedVersionOrigin's own javadoc documents its
* packageFenceSnapshot parameter as captured "atomically and before any real network fetch."
* Capturing it only after fetchSimpleIndex returns would let a DeletePackage racing that real
* outbound call go completely undetected, since the snapshot would already read the
* post-deletion fence as its own baseline.
*/
@Test
void snapshotsThePackageFenceBeforeFetchingTheRealIndexSoARacingDeleteIsNotMissed() {
InOrder inOrder = inOrder(service, externalConnectionClient);
importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
inOrder.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME);
inOrder.verify(externalConnectionClient).fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME));
}
/**
* The fix for a real finding: the sidecar listing that decides what is already present used
* to run as a bare statement between the claim and the try/finally that finishes it. A
* transient sidecar failure there used to propagate straight out of this method, skipping
* finishRetainedVersionOriginAttempt entirely and stranding the claim this attempt just took.
*/
@Test
void aSidecarFailureListingExistingAssetsStillFinishesTheClaimInsteadOfStrandingIt() {
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenThrow(new IllegalStateException("sidecar unreachable"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
/**
* The fix for a real finding: a file whose real bytes do not match the sha256 the trusted
* index response itself named for it must never be written or counted, the same as if it had
* never been fetched at all.
*/
@Test
void skipsAFileWhoseFetchedBytesDoNotMatchTheIndexsOwnSha256() {
ObjectNode root = mapper.createObjectNode();
root.put("name", PACKAGE_NAME);
root.putArray("versions").add(VERSION);
ObjectNode file = root.putArray("files").addObject();
file.put("filename", SDIST_FILENAME);
file.put("url", urlFor(SDIST_FILENAME));
file.putObject("hashes").put("sha256", "0".repeat(64));
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(toBytes(root))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(),
any(), anyLong(), anyLong(), anyLong(), any(), any(), any(), any());
}
/** A file whose real bytes genuinely match the index's own sha256 is still imported normally. */
@Test
void importsAFileWhoseFetchedBytesMatchTheIndexsOwnSha256() throws Exception {
ObjectNode root = mapper.createObjectNode();
root.put("name", PACKAGE_NAME);
root.putArray("versions").add(VERSION);
ObjectNode file = root.putArray("files").addObject();
file.put("filename", SDIST_FILENAME);
file.put("url", urlFor(SDIST_FILENAME));
file.putObject("hashes").put("sha256", HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(SDIST_CONTENT)));
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(toBytes(root))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
}
/**
* The fix for a real finding: two concurrent calls into tryImportAsset for the exact same
* requested file -- the way two different pip requests for the exact same file of the same
* version actually would race -- must never both write it, even though each one's own
* attempt-start snapshot is taken independently. Both calls process their requested file
* (now the same file for both) synchronously, on their own calling thread, so this exercises
* the lock exactly where it used to; the sibling each call also backgrounds (the wheel) is
* deliberately not asserted on here, since it is covered by {@link
* #importsEveryRealSiblingOfTheResolvedVersionNotJustTheRequestedFile}. The first call's own
* write of the requested file is held open by a latch while the second call is started,
* proving the second cannot even reach its own recheck for that same file until the first
* releases the lock the fix adds, keyed to this exact version.
*/
@Test
void serializesConcurrentAttemptsWritingTheSameVersionsSiblingFiles() throws Exception {
CountDownLatch firstWriteStarted = new CountDownLatch(1);
CountDownLatch releaseFirstWrite = new CountDownLatch(1);
AtomicBoolean sdistWritten = new AtomicBoolean(false);
AtomicInteger sdistWriteAttempts = new AtomicInteger();
when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenAnswer(invocation -> sdistWritten.get() ? List.of(SDIST_FILENAME) : List.<String>of());
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.of("public:pypi"));
when(service.retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(), any(), anyLong(),
anyLong(), anyLong(), any(), eq(SDIST_FILENAME), any(), any())).thenAnswer(invocation -> {
if (sdistWriteAttempts.getAndIncrement() == 0) {
firstWriteStarted.countDown();
assertTrue(releaseFirstWrite.await(5, TimeUnit.SECONDS), "test never released the first write");
}
sdistWritten.set(true);
return new CodeArtifactService.AssetRetentionAttemptResult(true, true);
});
when(service.retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(), any(), anyLong(),
anyLong(), anyLong(), any(), eq(WHEEL_FILENAME), any(), any()))
.thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Boolean> first = pool.submit(
() -> importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME));
assertTrue(firstWriteStarted.await(5, TimeUnit.SECONDS), "first attempt never started writing");
Future<Boolean> second = pool.submit(
() -> importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME));
assertThrows(TimeoutException.class, () -> second.get(500, TimeUnit.MILLISECONDS),
"second attempt must not reach its own recheck while the first still holds the lock");
releaseFirstWrite.countDown();
assertTrue(first.get(5, TimeUnit.SECONDS));
assertTrue(second.get(5, TimeUnit.SECONDS));
} finally {
pool.shutdownNow();
}
verify(service, times(1)).retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(),
any(), anyLong(), anyLong(), anyLong(), any(), eq(SDIST_FILENAME), any(), any());
}
private static String urlFor(String filename) {
return "https://files.pythonhosted.org/packages/aa/bb/" + filename;
}
private byte[] toBytes(ObjectNode root) {
try {
return mapper.writeValueAsBytes(root);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private byte[] simpleIndexJson(List<String> versions, String... filenames) {
ObjectNode root = mapper.createObjectNode();
root.put("name", PACKAGE_NAME);
ArrayNode versionsNode = root.putArray("versions");
versions.forEach(versionsNode::add);
ArrayNode files = root.putArray("files");
for (String filename : filenames) {
ObjectNode file = files.addObject();
file.put("filename", filename);
file.put("url", urlFor(filename));
file.put("yanked", false);
}
return toBytes(root);
}
}
@@ -0,0 +1,236 @@
package io.floci.aws.services.codeartifact;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* The wire contract towards the real public pypi repository, exercised against a local {@code
* HttpServer} fake standing in for it, named {@code fake} in these tests rather than the real
* {@code public:pypi} connection name.
*/
class PypiExternalConnectionClientTest {
private HttpServer server;
private String serverBaseUrl;
private PypiExternalConnectionClient client;
@BeforeEach
void startServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.start();
serverBaseUrl = "http://127.0.0.1:" + server.getAddress().getPort();
Map<String, String> baseUrls = Map.of("fake", serverBaseUrl);
client = new PypiExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(),
baseUrls);
}
@AfterEach
void stopServer() {
server.stop(0);
}
@Test
void fetchSimpleIndexReturnsTheRealBytesOnA200AndSendsThePep691Accept() {
byte[] content = "{\"files\":[]}".getBytes(StandardCharsets.UTF_8);
AtomicReference<String> seenAccept = new AtomicReference<>();
server.createContext("/simple/widget/", exchange -> {
seenAccept.set(exchange.getRequestHeaders().getFirst("Accept"));
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchSimpleIndex("fake", "widget");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
assertEquals("application/vnd.pypi.simple.v1+json", seenAccept.get());
}
@Test
void fetchSimpleIndexNormalizesThePackageNameInThePath() {
byte[] content = "{\"files\":[]}".getBytes(StandardCharsets.UTF_8);
server.createContext("/simple/widget-name/", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchSimpleIndex("fake", "Widget_Name");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchSimpleIndexReturnsEmptyOnA404() {
server.createContext("/simple/widget/", exchange -> respondEmpty(exchange, 404));
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchSimpleIndex("fake", "widget");
assertFalse(result.isPresent());
}
@Test
void fetchSimpleIndexReturnsEmptyForAnUnknownConnectionName() {
Optional<PypiExternalConnectionClient.FetchedAsset> result =
client.fetchSimpleIndex("public:pypi", "widget");
assertFalse(result.isPresent());
}
@Test
void fetchFileReturnsTheRealBytesOnA200FromAnAbsoluteUrl() {
byte[] content = "sdist-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchFileReturnsEmptyOnA404() {
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> respondEmpty(exchange, 404));
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertFalse(result.isPresent());
}
@Test
void fetchFileReturnsEmptyForAnUnknownConnectionNameEvenWhenTheUrlIsReachable() {
byte[] content = "sdist-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("public:pypi",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertFalse(result.isPresent());
}
@Test
void fetchFileReturnsEmptyWhenTheUrlsHostIsNotTheConnectionsOwnHostOrAnAdditionalTrustedOne() {
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
fail("should never be requested: its host is not trusted");
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("fake",
"http://evil.example/packages/aa/bb/widget-1.0.0.tar.gz");
assertFalse(result.isPresent());
}
/**
* The fix for a real finding: a host check alone says nothing about the scheme, so a
* {@code http://} URL naming an otherwise-trusted host would still have passed it, sending
* the real file's bytes in plaintext even though this connection's own configured base is
* {@code https}. Scheme is compared against the connection's own base, not a hardcoded
* {@code https}, which is exactly why {@code client}'s own http base elsewhere in this file
* never needs this: only a connection actually configured for https enforces it.
*/
@Test
void fetchFileRefusesAnHttpUrlOnAnOtherwiseTrustedHostWhenTheConnectionIsConfiguredForHttps() {
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> fail("should never be requested: "
+ "its scheme does not match the connection's own https base"));
PypiExternalConnectionClient httpsConfigured = new PypiExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(),
Map.of("fake", "https://this-host-is-never-actually-requested.invalid"),
Map.of("fake", Set.of("127.0.0.1")));
Optional<PypiExternalConnectionClient.FetchedAsset> result = httpsConfigured.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertFalse(result.isPresent());
}
@Test
void fetchFileTrustsAConnectionsOwnAdditionalFileHostEvenWhenItDiffersFromTheIndexHost() {
byte[] content = "sdist-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
PypiExternalConnectionClient withAdditionalHost = new PypiExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(),
Map.of("fake", "http://this-host-is-never-actually-requested.invalid"),
Map.of("fake", Set.of("127.0.0.1")));
Optional<PypiExternalConnectionClient.FetchedAsset> result = withAdditionalHost.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchFileRefusesToFollowARedirectToAHostThatIsNotTrusted() {
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.getResponseHeaders().add("Location", "http://evil.example/stolen.tar.gz");
respondEmpty(exchange, 302);
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertFalse(result.isPresent());
}
@Test
void fetchFileFollowsARedirectThatStaysOnATrustedHost() {
byte[] content = "sdist-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.getResponseHeaders().add("Location", serverBaseUrl + "/packages/cc/dd/widget-1.0.0.tar.gz");
respondEmpty(exchange, 302);
});
server.createContext("/packages/cc/dd/widget-1.0.0.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<PypiExternalConnectionClient.FetchedAsset> result = client.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
exchange.sendResponseHeaders(status, -1);
exchange.close();
}
}