feat(codeartifact): add PyPI format support via pypiserver sidecar (#4998)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-02 23:51:56 -05:00
1 parent d0c7c23f6b
commit fca7d87f2d
19 files changed
+1799 -229

No files matched your search

@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MultipartFormParserTest {
private static final String BOUNDARY = "boundary123";
@Test
void extractBoundaryReadsTheParameterRegardlessOfQuoting() {
assertEquals(Optional.of("abc"), MultipartFormParser.extractBoundary("multipart/form-data; boundary=abc"));
assertEquals(Optional.of("abc"),
MultipartFormParser.extractBoundary("multipart/form-data; boundary=\"abc\""));
assertEquals(Optional.empty(), MultipartFormParser.extractBoundary("application/json"));
assertEquals(Optional.empty(), MultipartFormParser.extractBoundary(null));
}
@Test
void parseSeparatesTextFieldsFromTheFilePart() {
byte[] body = multipart(
field("name", "requests"),
field("version", "2.34.2"),
file("content", "requests-2.34.2-py3-none-any.whl", "application/octet-stream",
"fake wheel bytes"));
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(body, BOUNDARY);
assertEquals("requests", form.fields().get("name"));
assertEquals("2.34.2", form.fields().get("version"));
assertFalse(form.fields().containsKey("content"));
assertTrue(form.file().isPresent());
MultipartFormParser.FilePart file = form.file().get();
assertEquals("content", file.fieldName());
assertEquals("requests-2.34.2-py3-none-any.whl", file.filename());
assertEquals("application/octet-stream", file.contentType());
assertEquals("fake wheel bytes", new String(file.content(), StandardCharsets.UTF_8));
}
@Test
void parseReturnsAnEmptyFileWhenNoPartCarriesAFilename() {
byte[] body = multipart(field("key", "value"));
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(body, BOUNDARY);
assertEquals("value", form.fields().get("key"));
assertTrue(form.file().isEmpty());
}
@Test
void parsePreservesBinaryContentThatContainsCrlfBytes() {
byte[] binary = {0x50, 0x4B, 0x03, 0x04, '\r', '\n', 0x00, (byte) 0xFF};
byte[] body = multipart(filePart("content", "binary.bin", "application/octet-stream", binary));
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(body, BOUNDARY);
assertTrue(form.file().isPresent());
assertArrayEqualsExactly(binary, form.file().get().content());
}
@Test
void parseOnAnEmptyOrMalformedBodyReturnsNoFieldsAndNoFile() {
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(new byte[0], BOUNDARY);
assertTrue(form.fields().isEmpty());
assertTrue(form.file().isEmpty());
}
private static void assertArrayEqualsExactly(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i], "byte at index " + i);
}
}
private static byte[] multipart(byte[]... parts) {
StringBuilder header = new StringBuilder();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
for (byte[] part : parts) {
out.write(("--" + BOUNDARY + "\r\n").getBytes(StandardCharsets.UTF_8));
out.write(part);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
out.write(("--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new IllegalStateException(e);
}
return out.toByteArray();
}
private static byte[] field(String name, String value) {
String part = "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value;
return part.getBytes(StandardCharsets.UTF_8);
}
private static byte[] file(String fieldName, String filename, String contentType, String content) {
return filePart(fieldName, filename, contentType, content.getBytes(StandardCharsets.UTF_8));
}
private static byte[] filePart(String fieldName, String filename, String contentType, byte[] content) {
String header = "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + filename + "\"\r\n"
+ "Content-Type: " + contentType + "\r\n\r\n";
byte[] headerBytes = header.getBytes(StandardCharsets.UTF_8);
byte[] result = new byte[headerBytes.length + content.length];
System.arraycopy(headerBytes, 0, result, 0, headerBytes.length);
System.arraycopy(content, 0, result, headerBytes.length, content.length);
return result;
}
}
@@ -170,6 +170,49 @@ class ServiceEnablementIntegrationTest {
.body("message", equalTo("Service fis is not enabled."));
}
/**
* {@code CodeArtifactMavenController} and {@code CodeArtifactPypiController} serve a real
* package-manager wire protocol, not a CodeArtifact JSON API action, so nothing about a
* request to either carries a SigV4 signature or an {@code X-Amz-Target} for
* {@code ServiceEnabledFilter} to resolve a service from the normal ways. Both must still be
* registered in the {@code codeartifact} descriptor's own resource-class set, matched by JAX-RS
* routing alone: without that registration a disabled codeartifact service does not stop
* either from reaching its own token check and responding with a 401 instead of ever saying
* the service itself is unavailable. Caught after CodeArtifactPypiController needed the exact
* same registration CodeArtifactMavenController had been missing.
*/
@Test
void mavenWireProtocolRequestsAreRejectedWhenServiceDisabled() {
given()
.header("Authorization", "Bearer whatever")
.when()
.get("/codeartifact/maven/some-domain/some-repo/some/path/1.0/file.jar")
.then()
.statusCode(400)
.contentType("application/json")
.header("X-Amzn-Errortype", "ServiceNotAvailableException")
.body("__type", equalTo("ServiceNotAvailableException"))
.body("message", equalTo("Service codeartifact is not enabled."));
}
@Test
void pypiWireProtocolRequestsAreRejectedWhenServiceDisabled() {
// Not the bare "/simple/" root: AWS doesn't support that path either (only
// /simple/<project>/ is), so Floci has no route for it at all, and a request to a
// genuinely unrouted path 404s before this filter ever runs. "/simple/<project>/" is a
// real, routed endpoint, so it still demonstrates the service-disabled rejection.
given()
.header("Authorization", "Bearer whatever")
.when()
.get("/codeartifact/pypi/some-domain/some-repo/simple/some-pkg/")
.then()
.statusCode(400)
.contentType("application/json")
.header("X-Amzn-Errortype", "ServiceNotAvailableException")
.body("__type", equalTo("ServiceNotAvailableException"))
.body("message", equalTo("Service codeartifact is not enabled."));
}
@Test
void signedRdsDataExecuteRequestsReturnJsonWhenServiceDisabled() {
given()
@@ -203,6 +246,7 @@ class ServiceEnablementIntegrationTest {
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.acm.enabled", "false",
"floci.services.codeartifact.enabled", "false",
"floci.services.dynamodb.enabled", "false",
"floci.services.ecs.enabled", "false",
"floci.services.fis.enabled", "false",
@@ -0,0 +1,326 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Optional;
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 java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Exercises {@link CodeArtifactPypiController} against a fake pypiserver backend (a real
* {@link HttpServer}, not a mock of the JDK {@link HttpClient}, since that client's request/response
* types are effectively unmockable) so the proxy-passthrough, auth-resolution, and pre-upload
* overwrite-rejection logic all run for real. {@link CodeArtifactService} and
* {@link PypiserverSidecarManager} are mocked: what they do is already covered by
* {@code CodeArtifactServiceTest} and {@code PypiserverSidecarManagerTest}, what matters here is how
* this controller uses their results.
*/
class CodeArtifactPypiControllerTest {
private static final String DOMAIN = "dom";
private static final String REPOSITORY = "repo";
private static final String REGION = "us-east-1";
private static final String OWNER = "000000000000";
private HttpServer backend;
private String backendUrl;
private CodeArtifactService service;
private PypiserverSidecarManager pypiserver;
private CodeArtifactPypiController controller;
@BeforeEach
void setUp() throws Exception {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.start();
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
service = mock(CodeArtifactService.class);
pypiserver = mock(PypiserverSidecarManager.class);
when(service.resolveAuthorizationToken(anyString(), eq(DOMAIN)))
.thenReturn(Optional.of(new AuthorizationTokenScope(OWNER, REGION)));
when(service.ensureFormatContainerId(eq("pypi"), eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY)))
.thenReturn("pypi-repo-id");
when(pypiserver.ensureReady(eq("pypi-repo-id"), any())).thenReturn(backendUrl);
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
controller = new CodeArtifactPypiController(service, pypiserver, httpClient);
}
@AfterEach
void tearDown() {
backend.stop(0);
}
@Test
void requireBaseUrlRejectsAMissingOrUnresolvableToken() {
when(service.resolveAuthorizationToken(anyString(), eq(DOMAIN))).thenReturn(Optional.empty());
assertThrows(NotAuthorizedException.class,
() -> controller.packageIndex(headers("Bearer bogus"), DOMAIN, REPOSITORY, "my-pkg"));
}
@Test
void requireBaseUrlTranslatesAMissingRepositoryIntoNotFound() {
when(service.ensureFormatContainerId(eq("pypi"), eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY)))
.thenThrow(new AwsException("ResourceNotFoundException", "no such repository", 404));
assertThrows(NotFoundException.class,
() -> controller.packageIndex(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg"));
}
@Test
void packageIndexRewritesRootRelativePackageLinksToThisRepositorysPathPrefix() {
// Real pypiserver response shape, confirmed against a live container: a root-relative
// href, not the bare filename a naive fixture might use.
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 200, "text/html",
"<a href=\"/packages/my-pkg-1.0.tar.gz#sha256=abc\">my-pkg-1.0.tar.gz</a>"));
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#sha256=abc\""), body);
}
@Test
void downloadFileProxiesRawBytesFromTheBackend() {
byte[] content = "package bytes".getBytes(StandardCharsets.UTF_8);
backend.createContext("/packages/my-pkg-1.0.tar.gz",
exchange -> respond(exchange, 200, "application/octet-stream", content));
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg-1.0.tar.gz");
assertEquals(200, response.getStatus());
assertEquals("package bytes", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
}
@Test
void downloadFileReturns404WhenTheBackendHasNoSuchFile() {
backend.createContext("/packages/missing.tar.gz", exchange -> respond(exchange, 404, "text/plain", ""));
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY, "missing.tar.gz");
assertEquals(404, response.getStatus());
}
@Test
void uploadRejectsABodyWithNoDeterminableBoundary() {
Response response = controller.upload(headers("Bearer good", "application/octet-stream"), DOMAIN, REPOSITORY,
"not multipart".getBytes(StandardCharsets.UTF_8));
assertEquals(400, response.getStatus());
}
@Test
void uploadRejectsAMultipartBodyMissingNameOrContent() {
byte[] body = multipart("boundary123", "version", "1.0.0");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(400, response.getStatus());
}
@Test
void uploadRejectsAFileAlreadyListedInTheBackendsSimpleIndex() {
backend.createContext("/simple/my-pkg/",
exchange -> respond(exchange, 200, "text/html", "<a href=\"my_pkg-1.0.tar.gz\">my_pkg-1.0.tar.gz</a>"));
AtomicReference<Boolean> uploadReceived = new AtomicReference<>(false);
backend.createContext("/", exchange -> {
if ("POST".equals(exchange.getRequestMethod())) {
uploadReceived.set(true);
}
respond(exchange, 200, "text/plain", "");
});
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
}
@Test
void uploadOfByteIdenticalContentSucceedsIdempotentlyWithoutForwardingToTheBackend() {
String sameContent = "same content";
backend.createContext("/simple/my-pkg/",
exchange -> respond(exchange, 200, "text/html", "<a href=\"my_pkg-1.0.tar.gz\">my_pkg-1.0.tar.gz</a>"));
backend.createContext("/packages/my_pkg-1.0.tar.gz",
exchange -> respond(exchange, 200, "application/octet-stream", sameContent));
AtomicReference<Boolean> uploadReceived = new AtomicReference<>(false);
backend.createContext("/", exchange -> {
if ("POST".equals(exchange.getRequestMethod())) {
uploadReceived.set(true);
}
respond(exchange, 200, "text/plain", "");
});
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", sameContent);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(200, response.getStatus());
assertEquals(false, uploadReceived.get());
}
@Test
void uploadForwardsANewFileToTheBackendWhenNothingConflicts() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
AtomicReference<String> receivedBody = new AtomicReference<>();
backend.createContext("/", exchange -> {
if ("POST".equals(exchange.getRequestMethod())) {
receivedBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
}
respond(exchange, 200, "text/plain", "");
});
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(200, response.getStatus());
assertTrue(receivedBody.get().contains("new content"));
}
@Test
void uploadFailsClosedWhenTheExistenceCheckCannotReachTheBackend() {
// Nothing listens on this port: the existence check's own connect attempt fails, which
// must reject the upload rather than silently treating the failure as "not published yet."
when(pypiserver.ensureReady(eq("pypi-repo-id"), any())).thenReturn("http://127.0.0.1:1");
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content");
assertThrows(IllegalStateException.class, () -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body));
}
@Test
void concurrentUploadsOfDifferentContentForTheSameNewFilenameAreSerialized() throws Exception {
CountDownLatch holdFirstCheck = new CountDownLatch(1);
CountDownLatch firstCheckEntered = new CountDownLatch(1);
AtomicInteger indexHits = new AtomicInteger(0);
AtomicBoolean published = new AtomicBoolean(false);
backend.createContext("/simple/my-pkg/", exchange -> {
if (indexHits.incrementAndGet() == 1) {
firstCheckEntered.countDown();
try {
assertTrue(holdFirstCheck.await(5, TimeUnit.SECONDS), "test never released the first check");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (published.get()) {
respond(exchange, 200, "text/html", "<a href=\"/packages/my_pkg-1.0.tar.gz\">my_pkg-1.0.tar.gz</a>");
} else {
respond(exchange, 404, "text/plain", "");
}
});
backend.createContext("/packages/my_pkg-1.0.tar.gz",
exchange -> respond(exchange, 200, "application/octet-stream", "content-A"));
backend.createContext("/", exchange -> {
if ("POST".equals(exchange.getRequestMethod())) {
published.set(true);
}
respond(exchange, 200, "text/plain", "");
});
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Response> first = pool.submit(() -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-A")));
assertTrue(firstCheckEntered.await(5, TimeUnit.SECONDS), "first upload never started its check");
Future<Response> second = pool.submit(() -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-B")));
// The second upload must block on the same repository's lock, held by the first, and
// so cannot even reach the backend yet: without the lock this would race ahead and
// both uploads could observe "not published yet" before either one's POST lands.
assertThrows(TimeoutException.class, () -> second.get(500, TimeUnit.MILLISECONDS));
assertEquals(1, indexHits.get(), "second upload must not have reached the backend yet");
holdFirstCheck.countDown();
assertEquals(200, first.get(5, TimeUnit.SECONDS).getStatus());
assertEquals(409, second.get(5, TimeUnit.SECONDS).getStatus());
} finally {
pool.shutdownNow();
}
}
private static HttpHeaders headers(String authorization) {
return headers(authorization, "text/plain");
}
private static HttpHeaders headers(String authorization, String contentType) {
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.getHeaderString("Authorization")).thenReturn(authorization);
when(headers.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn(contentType);
return headers;
}
private static byte[] multipart(String boundary, String fieldName, String value) {
String body = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"" + fieldName + "\"\r\n\r\n"
+ value + "\r\n"
+ "--" + boundary + "--\r\n";
return body.getBytes(StandardCharsets.UTF_8);
}
private static byte[] multipartWithFile(String boundary, String packageName, String filename, String content) {
String body = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"name\"\r\n\r\n"
+ packageName + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"content\"; filename=\"" + filename + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n"
+ content + "\r\n"
+ "--" + boundary + "--\r\n";
return body.getBytes(StandardCharsets.UTF_8);
}
private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String contentType,
String body) throws java.io.IOException {
respond(exchange, status, contentType, body.getBytes(StandardCharsets.UTF_8));
}
private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String contentType,
byte[] body) throws java.io.IOException {
exchange.getResponseHeaders().add("Content-Type", contentType);
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
exchange.close();
}
}
@@ -0,0 +1,402 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
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 java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Runs a real PyPI-shaped upload/download round trip against a live, per-repository pypiserver
* container, started by {@link PypiserverSidecarManager} exactly as in production. The upload body
* is a hand-built multipart form matching the fields a real {@code twine upload} sends (verified
* against a live pypiserver instance and real twine by hand during design), not a captured fixture:
* unlike npm's envelope, the parsing itself ({@link io.github.hectorvent.floci.core.common.MultipartFormParser})
* is already covered by its own unit tests and by {@code CodeArtifactPypiControllerTest}, so what
* this class needs to prove is the real container's behavior, not the parser's fidelity to one
* exact client's byte-for-byte output.
*/
@QuarkusTest
@TestProfile(CodeArtifactPypiSidecarProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactPypiDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "pypi-sidecar-domain";
private static final String REPO = "pypi-sidecar-repo";
private static final String PACKAGE_NAME = "floci-pypiserver-spike";
// Real sdist filenames use underscores where the package name uses hyphens; exercising this
// exact mismatch is what proves the PEP 503 normalization in the overwrite-check actually runs,
// not just a name that happens to already match its own normalized form.
private static final String FILENAME = "floci_pypiserver_spike-1.0.0.tar.gz";
private static String bearerToken;
@BeforeAll
static void setUp() {
CodeArtifactPypiSidecarProfile.requireDockerAndTheSidecarImage();
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void createDomainRepositoryAndAuthorizationToken() {
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);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
@Test
@Order(1)
void uploadThenDownloadRoundTripsTheExactBytesThroughTheSimpleIndex() {
byte[] content = "real-sdist-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, content))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
String indexHtml = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(200)
.extract().asString();
assertTrue(indexHtml.contains(FILENAME), "simple index must list the uploaded file: " + indexHtml);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + FILENAME)
.then().statusCode(200)
.extract().asByteArray();
assertEquals(new String(content, StandardCharsets.UTF_8), new String(fetched, StandardCharsets.UTF_8));
}
/**
* AWS's own CodeArtifact docs ("Overwriting package assets" in packages-overview.html) say a
* republish of an asset whose content is byte-identical to what is already published succeeds
* because the operation is idempotent; only different content gets the 409 the next test
* covers. A naive "is this filename already listed" check would reject both cases alike, which
* would make twine's own retry-after-a-dropped-response behavior fail spuriously.
*/
@Test
@Order(2)
void reuploadingTheExactSameFileSucceedsIdempotently() {
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, "real-sdist-bytes".getBytes(StandardCharsets.UTF_8)))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + FILENAME)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("real-sdist-bytes", new String(fetched, StandardCharsets.UTF_8));
}
@Test
@Order(3)
void reuploadingTheSameFileIsRejectedAndTheOriginalContentSurvives() {
byte[] differentContent = "different-sdist-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, differentContent))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(409);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/packages/" + FILENAME)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("real-sdist-bytes", new String(fetched, StandardCharsets.UTF_8));
}
@Test
@Order(4)
void missingPackageAndMissingRepositoryAreNotFound() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/does-not-exist/")
.then().statusCode(404);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/no-such-repo/simple/does-not-exist/")
.then().statusCode(404);
}
@Test
@Order(5)
void repositoriesAreIsolatedFromEachOther() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-repo")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/other-repo/simple/" + PACKAGE_NAME + "/")
.then().statusCode(404);
}
@Test
@Order(6)
void missingOrWrongDomainTokensAreUnauthorized() {
// /simple/<package>/, not the bare /simple/ root: AWS doesn't support that path either,
// so there's no route for it at all, and an unrouted path 404s before auth ever runs.
// Challenges as Basic, not Bearer: real pip and twine both authenticate with HTTP Basic
// (username=aws, password=<token>), so this is the scheme a retry would actually honor.
given().get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(401)
.header("WWW-Authenticate", startsWith("Basic"));
given().header("Authorization", "Bearer not-a-real-token")
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(401);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=other-pypi-token-domain")
.then().statusCode(200);
String otherDomainToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=other-pypi-token-domain")
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + otherDomainToken)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(401);
}
@Test
@Order(7)
void aRealPipClientsBasicAuthCredentialsAreAcceptedWithTheTokenAsThePassword() {
String basic = "Basic " + Base64.getEncoder().encodeToString(("aws:" + bearerToken).getBytes(StandardCharsets.UTF_8));
given().header("Authorization", basic)
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(200)
.body(containsString(FILENAME));
}
@Test
@Order(8)
void concurrentFirstUseOfANewRepositoryOnlyStartsOneContainer() throws InterruptedException {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=concurrent-repo")
.then().statusCode(200);
int attempts = 8;
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger notFoundResponses = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
pool.submit(() -> {
ready.countDown();
try {
go.await();
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/concurrent-repo/simple/does-not-exist/")
.then().statusCode(404);
notFoundResponses.incrementAndGet();
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
});
}
ready.await(5, TimeUnit.SECONDS);
go.countDown();
} finally {
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
}
assertEquals(attempts, notFoundResponses.get());
}
@Test
@Order(9)
void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesPackages() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, "first-generation".getBytes(StandardCharsets.UTF_8)))
.post("/codeartifact/pypi/" + DOMAIN + "/reused-name/")
.then().statusCode(200);
given().header("Authorization", AUTH)
.delete("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/reused-name/simple/" + PACKAGE_NAME + "/")
.then().statusCode(404);
}
@Test
@Order(10)
void aDomainCreatedInANonDefaultRegionIsServedThroughTheTokensOwnRegion() {
String nonDefaultRegionAuth =
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-west-2/codeartifact/aws4_request";
String domain = "pypi-sidecar-non-default-region-domain";
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=" + REPO)
.then().statusCode(200);
String token = given().header("Authorization", nonDefaultRegionAuth)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + token)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, "non-default-region-bytes".getBytes(StandardCharsets.UTF_8)))
.post("/codeartifact/pypi/" + domain + "/" + REPO + "/")
.then().statusCode(200);
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/pypi/" + domain + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(200);
}
@Test
@Order(11)
void aDomainCreatedUnderANonDefaultAccountIsServedThroughTheTokensOwnAccount() {
String otherAccountAuth = "AWS4-HMAC-SHA256 Credential=111122223333/20260904/us-east-1/codeartifact/aws4_request";
String domain = "pypi-sidecar-cross-account-domain";
given().contentType("application/json").header("Authorization", otherAccountAuth).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", otherAccountAuth).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=" + REPO)
.then().statusCode(200);
String token = given().header("Authorization", otherAccountAuth)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + token)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, "cross-account-bytes".getBytes(StandardCharsets.UTF_8)))
.post("/codeartifact/pypi/" + domain + "/" + REPO + "/")
.then().statusCode(200);
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/pypi/" + domain + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
.then().statusCode(200);
}
/**
* Proves the actual mechanism, not just that {@code PypiserverSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
* {@code /state/reset}, and this is what stops a live container.
*
* <p>Ordered before every other test, for the same reason {@code CodeArtifactNpmDockerIntegrationTest}'s
* equivalent reset test runs first: a reset stops every container this process's pool is
* tracking, not just the one this test starts, so running it after the other tests would sweep
* up their containers too and break the baseline comparison for a reason unrelated to whether
* this test's own container actually stopped.
*/
@Test
@Order(-1)
void stateResetStopsTheRepositorysPypiserverContainer() throws Exception {
int baseline = runningPypiserverTestContainerCount();
String domain = "pypi-sidecar-reset-domain";
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=reset-repo")
.then().statusCode(200);
String token = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
// A 404 read still starts the container; only a missing token skips it.
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/pypi/" + domain + "/reset-repo/simple/does-not-exist/")
.then().statusCode(404);
assertEquals(baseline + 1, runningPypiserverTestContainerCount(),
"expected reset-repo's pypiserver container to be running before reset");
given().post("/_floci/state/reset").then().statusCode(200);
assertEquals(baseline, runningPypiserverTestContainerCount(),
"state reset must stop reset-repo's pypiserver container");
}
private static int runningPypiserverTestContainerCount() throws IOException, InterruptedException {
Process process = new ProcessBuilder("docker", "ps", "-q",
"--filter", "name=floci-aws-codeartifact-pypi-test-pypiserver-")
.redirectErrorStream(true).start();
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
process.waitFor();
return output.isBlank() ? 0 : (int) output.lines().count();
}
/**
* The fields a real {@code twine upload} sends (verified by hand against a live pypiserver
* instance during design); pypiserver, and this controller's own parsing, only look at
* {@code name} and the {@code content} file part, so the rest are included for realism only.
*/
private static byte[] twineUploadBody(String boundary, String packageName, String filename, byte[] content) {
String preamble = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\":action\"\r\n\r\n"
+ "file_upload\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"protocol_version\"\r\n\r\n"
+ "1\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"name\"\r\n\r\n"
+ packageName + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
+ "1.0.0\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"filetype\"\r\n\r\n"
+ "sdist\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"content\"; filename=\"" + filename + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n";
String closing = "\r\n--" + boundary + "--\r\n";
byte[] preambleBytes = preamble.getBytes(StandardCharsets.UTF_8);
byte[] closingBytes = closing.getBytes(StandardCharsets.UTF_8);
byte[] body = new byte[preambleBytes.length + content.length + closingBytes.length];
System.arraycopy(preambleBytes, 0, body, 0, preambleBytes.length);
System.arraycopy(content, 0, body, preambleBytes.length, content.length);
System.arraycopy(closingBytes, 0, body, preambleBytes.length + content.length, closingBytes.length);
return body;
}
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.quarkus.test.junit.QuarkusTestProfile;
import org.eclipse.microprofile.config.ConfigProvider;
import org.junit.jupiter.api.Assumptions;
import java.util.Map;
/**
* Shared by every CodeArtifact integration test that needs a real pypiserver sidecar container,
* started by {@link PypiserverSidecarManager} exactly as in production. Namespaces containers as
* {@code floci-codeartifact-pypi-test-*} so the manager's remove-before-start never touches a
* developer's real running Floci. Needs Docker; skipped without it. Locally it is also skipped
* when the pinned image is not present, so a developer without registry access is not stuck; in
* CI a missing image is a failure, since a vanished tag must not pass silently.
*/
public class CodeArtifactPypiSidecarProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.docker.resource-namespace", "codeartifact-pypi-test");
}
public static void requireDockerAndTheSidecarImage() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for CodeArtifact pypi "
+ "sidecar integration tests");
String image = ConfigProvider.getConfig().getValue("floci.services.codeartifact.pypi-image", String.class);
Assumptions.assumeTrue(imageUsable(image), "pypiserver sidecar image " + image + " is not present locally");
}
private static boolean isDockerAvailable() {
return run("docker", "version", "--format", "{{.Server.Version}}");
}
private static boolean imageUsable(String image) {
if ("true".equals(System.getenv("CI"))) {
return true;
}
return run("docker", "image", "inspect", image);
}
private static boolean run(String... command) {
try {
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
return process.waitFor() == 0;
} catch (Exception ignored) {
// Docker (or the image) isn't available; the caller turns this into a skipped test,
// not a failure, so there is nothing more useful to log here.
return false;
}
}
}
@@ -300,7 +300,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertEquals(Set.of("maven", "npm"), created.getSidecarContainerIds().keySet());
assertEquals(Set.of("maven", "npm", "pypi"), created.getSidecarContainerIds().keySet());
created.getSidecarContainerIds().values()
.forEach(id -> assertTrue(id != null && !id.isBlank()));
}
@@ -313,7 +313,7 @@ class CodeArtifactServiceTest {
service.deleteRepository(REGION, "dom", null, "repo");
CodeArtifactRepository recreated = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
for (String format : Set.of("maven", "npm")) {
for (String format : Set.of("maven", "npm", "pypi")) {
assertTrue(
!first.getSidecarContainerIds().get(format).equals(recreated.getSidecarContainerIds().get(format)),
"a recreated repository must never reuse the previous one's container id for a format, "
@@ -506,6 +506,9 @@ class CodeArtifactServiceTest {
String endpoint = service.getRepositoryEndpoint(REGION, "dom", null, "repo", "npm", null);
assertEquals("http://localhost:4566/codeartifact/npm/dom/repo/", endpoint);
String pypiEndpoint = service.getRepositoryEndpoint(REGION, "dom", null, "repo", "pypi", null);
assertEquals("http://localhost:4566/codeartifact/pypi/dom/repo/", pypiEndpoint);
AwsException e = assertThrows(AwsException.class,
() -> service.getRepositoryEndpoint(REGION, "dom", null, "repo", "not-a-format", null));
assertEquals("ValidationException", e.getErrorCode());
@@ -0,0 +1,73 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Same reasoning as {@code VerdaccioSidecarManagerTest}: {@link PypiserverSidecarManager}'s own
* {@link PerKeyContainerPool#stopAll()} behavior is already covered by {@code PerKeyContainerPoolTest},
* so what matters here is the wiring, that the manager genuinely implements {@link ContainerTeardown}
* and hands the pool container ids it actually started.
*/
class PypiserverSidecarManagerTest {
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
private final EmulatorConfig config = mock(EmulatorConfig.class);
@Test
void implementsContainerTeardownSoStateResetAndNukeCanFindIt() {
assertInstanceOf(ContainerTeardown.class, manager());
}
@Test
void stopManagedContainersStopsEveryContainerThePoolIsTracking() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1");
seedPooledContainer(manager, "pypi-repo-2", "tracked-pypiserver-2");
manager.stopManagedContainers();
verify(lifecycleManager).stopAndRemove("tracked-pypiserver-1", null);
verify(lifecycleManager).stopAndRemove("tracked-pypiserver-2", null);
}
@Test
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
PypiserverSidecarManager manager = manager();
manager.stopManagedContainers();
verifyNoInteractions(lifecycleManager);
}
private PypiserverSidecarManager manager() {
return new PypiserverSidecarManager(containerBuilder, lifecycleManager, config);
}
@SuppressWarnings("unchecked")
private static void seedPooledContainer(PypiserverSidecarManager manager, String key, String containerId)
throws Exception {
Field poolField = PypiserverSidecarManager.class.getDeclaredField("pool");
poolField.setAccessible(true);
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
containersField.setAccessible(true);
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, "http://127.0.0.1:1"));
}
}