From 8e4c1994b7badfb4b695e5515044679550cd69bf Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:37:43 -0400 Subject: [PATCH] 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. --- .../CodeArtifactPypiController.java | 145 ++++- ...rtifactPypiExternalConnectionImporter.java | 562 ++++++++++++++++++ .../PypiExternalConnectionClient.java | 263 ++++++++ .../codeartifact/PypiserverSidecarClient.java | 9 +- .../CodeArtifactPypiControllerTest.java | 177 +++++- ...ternalConnectionDockerIntegrationTest.java | 189 ++++++ ...actPypiExternalConnectionImporterTest.java | 545 +++++++++++++++++ .../PypiExternalConnectionClientTest.java | 236 ++++++++ 8 files changed, 2101 insertions(+), 25 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java create mode 100644 src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java create mode 100644 src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionDockerIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java create mode 100644 src/test/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClientTest.java diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java index fd3595d839..7bba70fe97 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java @@ -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 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///} 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. + * + *

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 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 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 } entry for each of {@code additional}'s filenames to + * {@code bodyHtmlOrNull}, right before its closing {@code } 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. + * + *

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 additional) { + if (additional.isEmpty()) { + return bodyHtmlOrNull; + } + StringBuilder extra = new StringBuilder(); + for (CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile file : additional) { + extra.append("").append(escapeHtml(file.filename())).append("
\n"); + } + if (bodyHtmlOrNull == null) { + return "\n" + extra + ""; + } + int bodyClose = bodyHtmlOrNull.toLowerCase(Locale.ROOT).lastIndexOf(""); + if (bodyClose < 0) { + return bodyHtmlOrNull + extra; + } + return bodyHtmlOrNull.substring(0, bodyClose) + extra + bodyHtmlOrNull.substring(bodyClose); + } + + private static String escapeHtml(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + /** * 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. + * + *

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 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 hrefFilenames(String html) { + Set 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) { diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java new file mode 100644 index 0000000000..7fa3b9c814 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java @@ -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: + * + *

    + *
  • Every asset of a version, imported together. "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.
  • + *
  • No release-only restriction. Unlike Maven's own external connections, AWS's docs + * name no equivalent carve-out for pypi prereleases, and no exclusion for a yanked + * 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.
  • + *
  • Checking asset origins. 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.
  • + *
  • Coordinated with this emulator's own deletion and disposal. 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.
  • + *
+ * + *

Deliberately not modeled here: refreshing a retained version's yanked 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 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. + * + *

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 additionalExternalFilenames(String region, String domain, String owner, + String repository, String repoId, String packageName, Set 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 versions = versionsOf(index); + List additional = new ArrayList<>(); + for (JsonNode file : index.path("files")) { + String filename = file.path("filename").asText(null); + if (filename == null || alreadyKnownFilenames.contains(filename)) { + continue; + } + Optional 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. + * + *

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). + * + *

{@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 claimed 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 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 versions = versionsOf(index); + Optional 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 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 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 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 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 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 fetchSimpleIndexJson(String externalConnectionName, String packageName) { + Optional 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 versionsOf(JsonNode index) { + List 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 resolveVersion(List 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); + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java b/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java new file mode 100644 index 0000000000..598c7c078e --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java @@ -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. + * + *

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//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. + * + *

{@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. + * + *

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 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> 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 baseUrls; + private final Map> 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 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 baseUrls, + Map> 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 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 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. + * + *

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 content 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. + * + *

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 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 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. + * + *

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); + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java index de39dad7f6..416e75c49c 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java @@ -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("[-_.]+", "-"); } diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java index 6ea5782cdc..a1e5ea529a 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java @@ -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", + "my-pkg-1.0.tar.gz")); + 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\">.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"><script>alert(1)</script>.tar.gz"), body); + assertFalse(body.contains("