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

@@ -876,6 +876,15 @@ public interface EmulatorConfig {
*/
@WithDefault("verdaccio/verdaccio:6.10.4")
String npmImage();
/**
* Image used for the per-repository pypiserver container backing the {@code pypi} format.
* Same reasoning as {@link #npmImage()}: pypiserver has no native concept of multiple
* named indexes inside one instance either, so this gets one container per CodeArtifact
* repository too, and there is no single external instance a URL override could name.
*/
@WithDefault("pypiserver/pypiserver:v2.4.2")
String pypiImage();
}
interface ConnectServiceConfig {
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.core.common;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/**
* Parses a {@code multipart/form-data} body into its plain text fields and, at most, one file
* part, without RESTEasy's {@code MultipartFormDataInput}: that reads reflectively in a way that
* needs its own native-image registration per caller, where this is a handful of byte-array
* scans. Pulled out of {@code S3Controller}'s presigned-POST handling once
* {@code CodeArtifactPypiController} needed the identical parsing for a twine upload's own
* multipart body.
*/
public final class MultipartFormParser {
private MultipartFormParser() {
}
/** One named field's value, or the one file part carrying a {@code filename} parameter. */
public record FilePart(String fieldName, String filename, String contentType, byte[] content) {}
/** {@code fields} excludes the file part; {@code file} is empty when the body carried none. */
public record ParsedForm(Map<String, String> fields, Optional<FilePart> file) {}
/** The {@code boundary} parameter of a {@code multipart/form-data} Content-Type, if present. */
public static Optional<String> extractBoundary(String contentType) {
if (contentType == null) {
return Optional.empty();
}
for (String part : contentType.split(";")) {
String trimmed = part.trim();
if (trimmed.toLowerCase(Locale.ROOT).startsWith("boundary=")) {
String boundary = trimmed.substring("boundary=".length()).trim();
if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
boundary = boundary.substring(1, boundary.length() - 1);
}
return Optional.of(boundary);
}
}
return Optional.empty();
}
public static ParsedForm parse(byte[] body, String boundary) {
Map<String, String> fields = new LinkedHashMap<>();
FilePart file = null;
byte[] boundaryBytes = ("--" + boundary).getBytes(StandardCharsets.UTF_8);
for (byte[] part : splitParts(body, boundaryBytes)) {
int headerEnd = indexOfDoubleNewline(part);
if (headerEnd < 0) {
continue;
}
String headers = new String(part, 0, headerEnd, StandardCharsets.UTF_8);
int bodyStart = headerEnd + 4; // skip \r\n\r\n
byte[] partBody = Arrays.copyOfRange(part, bodyStart, part.length);
// Trim the trailing CRLF the boundary split leaves on every part body.
if (partBody.length >= 2
&& partBody[partBody.length - 2] == '\r'
&& partBody[partBody.length - 1] == '\n') {
partBody = Arrays.copyOf(partBody, partBody.length - 2);
}
String disposition = extractHeaderValue(headers, "Content-Disposition");
if (disposition == null) {
continue;
}
String fieldName = extractDispositionParam(disposition, "name");
if (fieldName == null) {
continue;
}
String filename = extractDispositionParam(disposition, "filename");
if (filename != null) {
String partContentType = extractHeaderValue(headers, "Content-Type");
file = new FilePart(fieldName, filename,
partContentType == null ? null : partContentType.trim(), partBody);
} else {
fields.put(fieldName, new String(partBody, StandardCharsets.UTF_8));
}
}
return new ParsedForm(fields, Optional.ofNullable(file));
}
private static List<byte[]> splitParts(byte[] body, byte[] boundary) {
List<byte[]> parts = new ArrayList<>();
int pos = indexOf(body, boundary, 0);
if (pos < 0) {
return parts;
}
pos += boundary.length;
if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {
return parts; // closing boundary immediately, no parts
}
if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {
pos += 2;
}
while (pos < body.length) {
int nextBoundary = indexOf(body, boundary, pos);
if (nextBoundary < 0) {
break;
}
parts.add(Arrays.copyOfRange(body, pos, nextBoundary));
pos = nextBoundary + boundary.length;
if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {
break;
}
if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {
pos += 2;
}
}
return parts;
}
private static int indexOf(byte[] data, byte[] pattern, int fromIndex) {
outer:
for (int i = fromIndex; i <= data.length - pattern.length; i++) {
for (int j = 0; j < pattern.length; j++) {
if (data[i + j] != pattern[j]) {
continue outer;
}
}
return i;
}
return -1;
}
private static int indexOfDoubleNewline(byte[] data) {
for (int i = 0; i < data.length - 3; i++) {
if (data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') {
return i;
}
}
return -1;
}
private static String extractHeaderValue(String headers, String headerName) {
String lowerHeaders = headers.toLowerCase(Locale.ROOT);
String lowerName = headerName.toLowerCase(Locale.ROOT) + ":";
int idx = lowerHeaders.indexOf(lowerName);
if (idx < 0) {
return null;
}
int valueStart = idx + lowerName.length();
int lineEnd = headers.indexOf('\r', valueStart);
if (lineEnd < 0) {
lineEnd = headers.indexOf('\n', valueStart);
}
if (lineEnd < 0) {
lineEnd = headers.length();
}
return headers.substring(valueStart, lineEnd).trim();
}
private static String extractDispositionParam(String disposition, String paramName) {
String search = paramName + "=";
int idx = disposition.indexOf(search);
if (idx < 0) {
return null;
}
int valueStart = idx + search.length();
if (valueStart >= disposition.length()) {
return null;
}
if (disposition.charAt(valueStart) == '"') {
valueStart++;
int valueEnd = disposition.indexOf('"', valueStart);
if (valueEnd < 0) {
return disposition.substring(valueStart);
}
return disposition.substring(valueStart, valueEnd);
} else {
int valueEnd = disposition.indexOf(';', valueStart);
if (valueEnd < 0) {
valueEnd = disposition.length();
}
return disposition.substring(valueStart, valueEnd).trim();
}
}
}
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.appconfig.AppConfigDataController;
import io.github.hectorvent.floci.services.batch.BatchController;
import io.github.hectorvent.floci.services.bedrock.BedrockController;
import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeController;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactMavenController;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactPypiController;
import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;
import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
import io.github.hectorvent.floci.services.eks.EksController;
@@ -743,7 +745,9 @@ public class ResolvedServiceCatalog {
"codeartifact", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("codeartifact"), Set.of(),
Set.of(io.github.hectorvent.floci.services.codeartifact.CodeArtifactController.class)),
Set.of(io.github.hectorvent.floci.services.codeartifact.CodeArtifactController.class,
CodeArtifactMavenController.class,
CodeArtifactPypiController.class)),
descriptor("verifiedpermissions", "verifiedpermissions", config.services().verifiedpermissions().enabled(), true,
"verifiedpermissions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
@@ -18,10 +18,6 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
/**
* Serves the real Maven repository wire protocol behind the URL {@code GetRepositoryEndpoint}
* returns for the {@code maven} format: plain GET/PUT/HEAD over a GAV path, not a CodeArtifact
@@ -43,9 +39,6 @@ import java.util.Optional;
@Path("/codeartifact/maven/{domain}/{repository}/{gav:.+}")
public class CodeArtifactMavenController {
private static final String BEARER_PREFIX = "Bearer ";
private static final String BASIC_PREFIX = "Basic ";
private final CodeArtifactService service;
private final ReposiliteSidecarClient reposilite;
@@ -96,7 +89,7 @@ public class CodeArtifactMavenController {
}
private String requireRepositoryId(HttpHeaders headers, String domain, String repository) {
String token = extractToken(headers);
String token = CodeArtifactTokenExtractor.extractToken(headers);
AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain)
.orElseThrow(() -> new NotAuthorizedException("Basic realm=\"floci-codeartifact\""));
String repoId;
@@ -108,33 +101,4 @@ public class CodeArtifactMavenController {
reposilite.ensureRepository(repoId);
return repoId;
}
/**
* {@code null} when neither scheme is present, malformed, or the Basic credentials have no
* password field; {@link CodeArtifactService#resolveAuthorizationToken} treats a null token
* the same as any other invalid one.
*/
private static String extractToken(HttpHeaders headers) {
String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorization == null) {
return null;
}
if (authorization.startsWith(BEARER_PREFIX)) {
return authorization.substring(BEARER_PREFIX.length());
}
if (authorization.startsWith(BASIC_PREFIX)) {
return passwordFromBasicCredentials(authorization.substring(BASIC_PREFIX.length()));
}
return null;
}
private static String passwordFromBasicCredentials(String base64Credentials) {
try {
String decoded = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
int separator = decoded.indexOf(':');
return separator >= 0 ? decoded.substring(separator + 1) : null;
} catch (IllegalArgumentException e) {
return null;
}
}
}
@@ -0,0 +1,284 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.MultipartFormParser;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* Serves the real PyPI simple-repository wire protocol behind the URL
* {@code GetRepositoryEndpoint} returns for the {@code pypi} format: the same plain GET/POST
* pip and twine speak against real PyPI, not a CodeArtifact API action. Backed by one pypiserver
* container per repository, provisioned on first use.
*
* <p>Requires the bearer token real CodeArtifact requires here, obtained from
* {@code GetAuthorizationToken} and scoped to the domain being accessed. AWS documents pip and
* twine both authenticating with HTTP Basic ({@code username=aws, password=<token>}, verified
* against AWS's own pip and twine configuration docs), the same convention Maven's HTTP wagon
* uses, not npm's Bearer-only {@code _authToken}; {@link CodeArtifactTokenExtractor} accepts
* either scheme.
*
* <p>A pip/twine request carries no SigV4 {@code Authorization} header, so there is no account or
* Region to resolve from it the way the CodeArtifact JSON API does; the token itself supplies
* both, since it was issued under a specific account and Region.
*
* <p>Unlike Maven and npm, this rejects a re-upload of a file pypiserver has already published
* itself: pypiserver has no immutability check of its own (confirmed by uploading the same
* name/version/filename twice against a real instance; the second upload silently replaces the
* first), unlike Reposilite ({@code redeployment: false}) and Verdaccio (rejects natively,
* matching real npm). A pre-upload check against pypiserver's own simple index and the existing
* file's own bytes is what gives PyPI the same immutability guarantee the other two formats
* already get for free from their sidecars, including AWS's own documented exception to it:
* republishing an asset whose content is byte-identical to what is already there succeeds
* idempotently rather than conflicting (verified against AWS's CodeArtifact packages-overview
* docs, "Overwriting package assets": only a same-name upload with <i>different</i> content
* returns 409).
*/
@Path("/codeartifact/pypi/{domain}/{repository}")
public class CodeArtifactPypiController {
private static final String SIMPLE_PATH = "/simple/";
private final CodeArtifactService service;
private final PypiserverSidecarManager pypiserver;
private final HttpClient httpClient;
private final ConcurrentHashMap<String, Object> uploadLocks = new ConcurrentHashMap<>();
@Inject
public CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarManager pypiserver) {
this(service, pypiserver, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarManager pypiserver,
HttpClient httpClient) {
this.service = service;
this.pypiserver = pypiserver;
this.httpClient = httpClient;
}
private record RepositoryHandle(String repoId, String baseUrl, String pathPrefix) {
}
// No route for the bare "/simple/" project-list endpoint: AWS's CodeArtifact User Guide
// documents it as unsupported ("Unsupported PyPI APIs", only /simple/<project>/ is served).
/**
* pypiserver's own simple-index HTML links to package files with a root-relative
* {@code href="/packages/<file>"}, resolved by pip against whatever host it actually
* connected to: this proxy's own host, not pypiserver's. Left unrewritten, that resolves to
* {@code /packages/<file>} at the proxy's root, not under this repository's
* {@code /codeartifact/pypi/<domain>/<repository>/} prefix where {@link #downloadFile} is
* actually routed, so pip would 404 trying to install anything the index lists. Verified
* against a real pypiserver response before writing this, not assumed.
*/
@GET
@Path("simple/{package}/")
@Produces(MediaType.TEXT_HTML)
public Response packageIndex(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository,
@PathParam("package") String packageName) {
RepositoryHandle handle = requireRepository(headers, domain, repository);
Response response = proxyGet(handle.baseUrl(), SIMPLE_PATH + packageName + "/");
if (response.getStatus() != 200) {
return response;
}
String html = new String((byte[]) response.getEntity(), StandardCharsets.UTF_8);
String rewritten = html.replace("href=\"/packages/", "href=\"" + handle.pathPrefix() + "/packages/");
return Response.status(200).entity(rewritten.getBytes(StandardCharsets.UTF_8)).type(MediaType.TEXT_HTML)
.build();
}
@GET
@Path("packages/{filename}")
@Produces(MediaType.WILDCARD)
public Response downloadFile(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository,
@PathParam("filename") String filename) {
String baseUrl = requireRepository(headers, domain, repository).baseUrl();
return proxyGet(baseUrl, "/packages/" + filename);
}
/**
* Handles a twine upload: {@code POST} to the repository root with a
* {@code multipart/form-data} body whose {@code content} part is the package file and whose
* {@code name}/{@code version} fields identify it. When the exact filename being uploaded is
* already published, compares its existing bytes to the new upload: byte-identical content
* succeeds without forwarding anything (idempotent, matching AWS's own documented behavior for
* a retried publish), while different content is rejected with 409 before ever reaching
* pypiserver, since pypiserver has no immutability check of its own.
*
* <p>The existence check and the forwarded publish run inside a lock keyed by this
* repository's id: unlike Reposilite ({@code redeployment: false}), pypiserver has no atomic
* backstop of its own, so without this lock two uploads racing the same new filename could
* both observe "not published yet" and both succeed, with pypiserver silently keeping whichever
* write landed last instead of either one being rejected.
*/
@POST
@Consumes(MediaType.WILDCARD)
public Response upload(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository, byte[] body) {
byte[] content = body != null ? body : new byte[0];
// Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy
// Reactive has already buffered the full body into this byte[] before this method runs,
// so this rejects anything that made it this far rather than bounding memory use upfront.
if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) {
return Response.status(413).build();
}
RepositoryHandle handle = requireRepository(headers, domain, repository);
String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
String boundary = MultipartFormParser.extractBoundary(contentType).orElse(null);
if (boundary == null) {
return Response.status(400).entity("Could not determine multipart boundary from Content-Type.").build();
}
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(content, boundary);
String packageName = form.fields().get("name");
Optional<MultipartFormParser.FilePart> file = form.file();
if (packageName == null || packageName.isBlank() || file.isEmpty()) {
return Response.status(400).entity("Upload must include name and content fields.").build();
}
Object lock = uploadLocks.computeIfAbsent(handle.repoId(), k -> new Object());
synchronized (lock) {
Optional<byte[]> existing = existingFileContent(handle.baseUrl(), packageName, file.get().filename());
if (existing.isPresent()) {
if (Arrays.equals(existing.get(), file.get().content())) {
return Response.status(200).build();
}
return Response.status(409)
.entity("File already exists. See "
+ "https://docs.aws.amazon.com/codeartifact/latest/ug/PyPI-format.html")
.build();
}
return forwardUpload(handle.baseUrl(), contentType, content);
}
}
/**
* {@code empty()} when {@code filename} isn't listed in the package's simple index yet, its
* actual bytes otherwise. pypiserver normalizes a package name for its own simple-index path
* the same way real PyPI does (PEP 503: lowercase, runs of {@code -_.} collapsed to one
* {@code -}); querying with the raw, as-uploaded name for a package whose normalized form
* differs would 404 even though the package exists.
*
* <p>A connectivity failure here throws rather than returning {@code empty()}: treating "the
* check couldn't complete" the same as "nothing published yet" would let an upload with
* different content through to pypiserver (which has no conflict check of its own) during
* exactly the moment this proxy's own protection is unavailable, the opposite of fail-safe.
*/
private Optional<byte[]> existingFileContent(String baseUrl, String packageName, String filename) {
String normalized = normalizePackageName(packageName);
HttpRequest indexRequest = HttpRequest.newBuilder(URI.create(baseUrl + SIMPLE_PATH + normalized + "/"))
.timeout(Duration.ofSeconds(5)).GET().build();
HttpResponse<String> indexResponse;
try {
indexResponse = httpClient.send(indexRequest, BodyHandlers.ofString());
} catch (Exception e) {
throw new IllegalStateException(
"Could not check pypi package " + packageName + " for an existing " + filename
+ " before publishing", e);
}
if (indexResponse.statusCode() == 404) {
return Optional.empty();
}
if (indexResponse.statusCode() != 200) {
throw new IllegalStateException(
"Could not check pypi package " + packageName + " for an existing " + filename
+ ": upstream returned " + indexResponse.statusCode());
}
if (!indexResponse.body().contains(filename)) {
return Optional.empty();
}
HttpRequest fileRequest = HttpRequest.newBuilder(URI.create(baseUrl + "/packages/" + filename))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> fileResponse;
try {
fileResponse = httpClient.send(fileRequest, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException(
"Could not fetch the existing pypi file " + filename + " to check for a content match", e);
}
if (fileResponse.statusCode() != 200) {
throw new IllegalStateException(
"Could not fetch the existing pypi file " + filename + " to check for a content match: "
+ "upstream returned " + fileResponse.statusCode());
}
return Optional.of(fileResponse.body());
}
private static String normalizePackageName(String name) {
return name.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-");
}
private Response forwardUpload(String baseUrl, String contentType, byte[] content) {
HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/"))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", contentType)
.POST(BodyPublishers.ofByteArray(content))
.build();
HttpResponse<Void> response;
try {
response = httpClient.send(request, BodyHandlers.discarding());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the pypi sidecar to publish this file", e);
}
return Response.status(response.statusCode()).build();
}
private Response proxyGet(String baseUrl, String path) {
HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + path))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> response;
try {
response = httpClient.send(request, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the pypi sidecar at " + path, e);
}
if (response.statusCode() == 404) {
return Response.status(404).build();
}
String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream");
return Response.status(response.statusCode()).entity(response.body()).type(contentType).build();
}
private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) {
String token = CodeArtifactTokenExtractor.extractToken(headers);
AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain)
.orElseThrow(() -> new NotAuthorizedException("Basic realm=\"floci-codeartifact\""));
String repoId;
try {
repoId = service.ensureFormatContainerId("pypi", scope.region(), domain, scope.owner(), repository);
} catch (AwsException e) {
throw new NotFoundException();
}
String baseUrl = pypiserver.ensureReady(repoId, null);
return new RepositoryHandle(repoId, baseUrl, "/codeartifact/pypi/" + domain + "/" + repository);
}
}
@@ -73,7 +73,7 @@ public class CodeArtifactService implements Resettable {
* and the backfill in {@link #ensureFormatContainerId} already handle it, including for
* repositories created before that format's proxy existed.
*/
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm");
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi");
private static final Logger LOG = Logger.getLogger(CodeArtifactService.class);
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.codeartifact;
import jakarta.ws.rs.core.HttpHeaders;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* Extracts a CodeArtifact authorization token from an incoming request's {@code Authorization}
* header, accepting either scheme real package-manager clients use: {@code Bearer <token>}
* directly, or HTTP Basic with the token as the password field and any username. AWS documents
* only Basic for Maven's {@code settings.xml} and pip/twine's {@code username=aws} convention;
* accepting Bearer too costs nothing and matches what a Bearer-only format like npm sends.
*
* <p>Pulled out of {@code CodeArtifactMavenController} once {@code CodeArtifactPypiController}
* needed the identical extraction: pip and twine authenticate exactly the way Maven's HTTP wagon
* does (verified against AWS's own pip and twine configuration docs, both showing
* {@code username=aws, password=<token>}), not the Bearer-only convention npm's {@code _authToken}
* uses.
*/
final class CodeArtifactTokenExtractor {
private static final String BEARER_PREFIX = "Bearer ";
private static final String BASIC_PREFIX = "Basic ";
private CodeArtifactTokenExtractor() {
}
/**
* {@code null} when neither scheme is present, malformed, or the Basic credentials have no
* password field; {@link CodeArtifactService#resolveAuthorizationToken} treats a null token
* the same as any other invalid one.
*/
static String extractToken(HttpHeaders headers) {
String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorization == null) {
return null;
}
if (authorization.startsWith(BEARER_PREFIX)) {
return authorization.substring(BEARER_PREFIX.length());
}
if (authorization.startsWith(BASIC_PREFIX)) {
return passwordFromBasicCredentials(authorization.substring(BASIC_PREFIX.length()));
}
return null;
}
private static String passwordFromBasicCredentials(String base64Credentials) {
try {
String decoded = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
int separator = decoded.indexOf(':');
return separator >= 0 ? decoded.substring(separator + 1) : null;
} catch (IllegalArgumentException e) {
return null;
}
}
}
@@ -0,0 +1,131 @@
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
/**
* Lazily starts and manages one pypiserver container per CodeArtifact repository backing the
* {@code pypi} format. Like Verdaccio (npm), pypiserver has no native concept of multiple named
* indexes inside one instance, so pypi repositories each get their own container instead of
* sharing one the way Reposilite's Maven repositories do. The per-key container lifecycle (map of
* running containers, per-key start lock, health poll, restart-on-unhealthy, stop-all on
* shutdown/reset) is generic and lives in {@link PerKeyContainerPool}; this class only knows how
* to build and configure a pypiserver container specifically.
*
* <p>Each container is configured with authentication disabled (real CodeArtifact authorization
* happens once at Floci's proxy layer, {@code CodeArtifactPypiController}, before a request ever
* reaches this container) and {@code --disable-fallback}, matching the Maven and npm proxies' own
* deliberate choice not to resolve upstream repositories or external connections: pypiserver
* otherwise redirects a package missing from its local index to the real, public PyPI.
*
* <p>Unlike Verdaccio, this needs no public-URL environment variable: pypiserver's simple-index
* responses link to package files with a root-relative path ({@code /packages/<file>}), which pip
* and twine resolve against whatever host they actually connected to, not an address the
* container returns itself. There is nothing here for an internal, client-unreachable address to
* leak into. That root-relative path still needs rewriting to this repository's own
* {@code /codeartifact/pypi/<domain>/<repository>} prefix before a client sees it, since the
* download route lives there, not at the proxy's bare root; {@code CodeArtifactPypiController}
* does that rewrite, not this class.
*/
@ApplicationScoped
public class PypiserverSidecarManager implements RepositorySidecarManager, ContainerTeardown {
private static final Logger LOG = Logger.getLogger(PypiserverSidecarManager.class);
private static final String FORMAT = "pypi";
private static final int PYPISERVER_PORT = 8080;
private static final String HEALTH_PATH = "/health";
private static final String PACKAGES_DIR = "/data/packages";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private final PerKeyContainerPool pool;
@Inject
public PypiserverSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
}
@Override
public String format() {
return FORMAT;
}
/**
* Base URL of a ready pypiserver instance for this pypi repository, starting its container if
* this is the first use. {@code publicUrl} is unused: see the class javadoc for why pypiserver
* needs no self-referential URL rewritten.
*/
@Override
public String ensureReady(String pypiRepositoryId, String publicUrl) {
return pool.ensureReady(pypiRepositoryId, () -> startContainer(pypiRepositoryId));
}
/** Stops and removes the container for one pypi repository, if one was ever started. */
@Override
public void release(String pypiRepositoryId) {
pool.stopContainer(pypiRepositoryId);
}
private PerKeyContainerPool.StartedContainer startContainer(String pypiRepositoryId) {
String image = config.services().codeartifact().pypiImage();
String containerName = ContainerStorageHelper.dockerName(config, "floci-pypiserver-" + pypiRepositoryId);
lifecycleManager.removeIfExists(containerName);
// Loopback-only: this container authenticates nothing on its own (auth disabled below), so
// the Bearer check in CodeArtifactPypiController is the only thing standing between a
// client and the backing storage. Publishing this to every interface would let anyone who
// can reach the host bypass that check entirely, the same reasoning as Verdaccio's binding.
ContainerSpec spec = containerBuilder.newContainer(image)
.withName(containerName)
.withLoopbackPortBinding(PYPISERVER_PORT, 0)
.withDockerNetwork(config.services().dockerNetwork())
.withEmbeddedDns()
.withLogRotation()
.withCmd(List.of(
"run",
"-p", String.valueOf(PYPISERVER_PORT),
// Disables pypiserver's own auth entirely (real CodeArtifact authorization
// is already enforced before a request reaches this container) and its
// default redirect-to-real-PyPI for a package missing from the local index,
// matching the Maven and npm proxies' own choice not to resolve upstreams.
"-a", ".",
"-P", ".",
"--disable-fallback",
"--health-endpoint", HEALTH_PATH,
PACKAGES_DIR))
.build();
String containerId = lifecycleManager.create(spec);
try {
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
EndpointInfo endpoint = info.getEndpoint(PYPISERVER_PORT);
String url = "http://" + endpoint;
LOG.infov("pypiserver sidecar for pypi repository {0} is ready at {1}", pypiRepositoryId, url);
return new PerKeyContainerPool.StartedContainer(containerId, url);
} catch (RuntimeException e) {
lifecycleManager.stopAndRemove(containerId, null);
throw e;
}
}
@Override
public void stopManagedContainers() {
pool.stopAll();
}
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.IamEnforcementFilter;
import io.github.hectorvent.floci.core.common.MultipartFormParser;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -3444,55 +3445,14 @@ public class S3Controller {
}
private Response doHandlePresignedPost(String bucket, String contentType, byte[] body) {
String boundary = extractBoundary(contentType);
if (boundary == null) {
throw new AwsException("InvalidArgument",
"Could not determine multipart boundary from Content-Type.", 400);
}
String boundary = MultipartFormParser.extractBoundary(contentType).orElseThrow(() ->
new AwsException("InvalidArgument",
"Could not determine multipart boundary from Content-Type.", 400));
Map<String, String> fields = new LinkedHashMap<>();
byte[] fileData = null;
String fileContentType = null;
byte[] boundaryBytes = ("--" + boundary).getBytes(StandardCharsets.UTF_8);
List<byte[]> parts = splitMultipartParts(body, boundaryBytes);
for (byte[] part : parts) {
int headerEnd = indexOfDoubleNewline(part);
if (headerEnd < 0) {
continue;
}
String headers = new String(part, 0, headerEnd, StandardCharsets.UTF_8);
int bodyStart = headerEnd + 4; // skip \r\n\r\n
byte[] partBody = Arrays.copyOfRange(part, bodyStart, part.length);
// Trim trailing \r\n from part body
if (partBody.length >= 2
&& partBody[partBody.length - 2] == '\r'
&& partBody[partBody.length - 1] == '\n') {
partBody = Arrays.copyOf(partBody, partBody.length - 2);
}
String disposition = extractHeaderValue(headers, "Content-Disposition");
if (disposition == null) {
continue;
}
String fieldName = extractDispositionParam(disposition, "name");
if (fieldName == null) {
continue;
}
String filename = extractDispositionParam(disposition, "filename");
if (filename != null) {
fileData = partBody;
String partContentType = extractHeaderValue(headers, "Content-Type");
if (partContentType != null) {
fileContentType = partContentType.trim();
}
} else {
fields.put(fieldName, new String(partBody, StandardCharsets.UTF_8));
}
}
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(body, boundary);
Map<String, String> fields = form.fields();
byte[] fileData = form.file().map(MultipartFormParser.FilePart::content).orElse(null);
String fileContentType = form.file().map(MultipartFormParser.FilePart::contentType).orElse(null);
String key = fields.get("key");
if (key == null || key.isEmpty()) {
@@ -3768,123 +3728,6 @@ public class S3Controller {
return fields.get(fieldName);
}
private static String extractBoundary(String contentType) {
if (contentType == null) {
return null;
}
for (String part : contentType.split(";")) {
String trimmed = part.trim();
if (trimmed.toLowerCase(Locale.ROOT).startsWith("boundary=")) {
String boundary = trimmed.substring("boundary=".length()).trim();
if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
boundary = boundary.substring(1, boundary.length() - 1);
}
return boundary;
}
}
return null;
}
private static List<byte[]> splitMultipartParts(byte[] body, byte[] boundary) {
java.util.ArrayList<byte[]> parts = new java.util.ArrayList<>();
int pos = indexOf(body, boundary, 0);
if (pos < 0) {
return parts;
}
// Skip past the first boundary line
pos += boundary.length;
// Skip the CRLF or -- after boundary
if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {
return parts; // closing boundary immediately
}
if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {
pos += 2;
}
while (pos < body.length) {
int nextBoundary = indexOf(body, boundary, pos);
if (nextBoundary < 0) {
break;
}
parts.add(Arrays.copyOfRange(body, pos, nextBoundary));
pos = nextBoundary + boundary.length;
// Check for closing boundary --
if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {
break;
}
// Skip CRLF after boundary
if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {
pos += 2;
}
}
return parts;
}
private static int indexOf(byte[] data, byte[] pattern, int fromIndex) {
outer:
for (int i = fromIndex; i <= data.length - pattern.length; i++) {
for (int j = 0; j < pattern.length; j++) {
if (data[i + j] != pattern[j]) {
continue outer;
}
}
return i;
}
return -1;
}
private static int indexOfDoubleNewline(byte[] data) {
for (int i = 0; i < data.length - 3; i++) {
if (data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') {
return i;
}
}
return -1;
}
private static String extractHeaderValue(String headers, String headerName) {
String lowerHeaders = headers.toLowerCase(Locale.ROOT);
String lowerName = headerName.toLowerCase(Locale.ROOT) + ":";
int idx = lowerHeaders.indexOf(lowerName);
if (idx < 0) {
return null;
}
int valueStart = idx + lowerName.length();
int lineEnd = headers.indexOf('\r', valueStart);
if (lineEnd < 0) {
lineEnd = headers.indexOf('\n', valueStart);
}
if (lineEnd < 0) {
lineEnd = headers.length();
}
return headers.substring(valueStart, lineEnd).trim();
}
private static String extractDispositionParam(String disposition, String paramName) {
String search = paramName + "=";
int idx = disposition.indexOf(search);
if (idx < 0) {
return null;
}
int valueStart = idx + search.length();
if (valueStart >= disposition.length()) {
return null;
}
if (disposition.charAt(valueStart) == '"') {
valueStart++;
int valueEnd = disposition.indexOf('"', valueStart);
if (valueEnd < 0) {
return disposition.substring(valueStart);
}
return disposition.substring(valueStart, valueEnd);
} else {
int valueEnd = disposition.indexOf(';', valueStart);
if (valueEnd < 0) {
valueEnd = disposition.length();
}
return disposition.substring(valueStart, valueEnd).trim();
}
}
private static final int MAX_INLINE_TAGS = 10;
private static final int MAX_INLINE_TAGGING_HEADER_BYTES = 8 * 1024;