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

@@ -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();
}
}