mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(codeartifact): support the cargo (crates.io) registry format (#8370)
CodeArtifact's Rust/Cargo repositories had no native support at all: no sidecar, no wire protocol, no external connection. Adds it following the same shape as the existing Maven/npm/pypi/NuGet container-backed formats. KellnrSidecarManager/KellnrSidecarClient run a real Kellnr container per cargo-enabled repository and speak its native HTTP API for publish, download, and the sparse index. CodeArtifactCargoController implements the real `cargo` sparse-registry wire protocol (publish, download, sparse index lookup, config.json) and forwards Kellnr's own publish rejections (e.g. republishing an existing version, which the Cargo Book documents as permanently disallowed) verbatim rather than swallowing them into an opaque error. Adds the `public:crates-io` external connection via CargoExternalConnectionClient (real index.crates.io/static.crates.io wire calls) and CodeArtifactCargoExternalConnectionImporter, reusing the existing claim/fence/retention-origin machinery the same way NuGet's own importer does. Cargo's sparse index covers every version of a crate name in one file and a real cargo client always consults it first, so unlike the other formats' importers this one also merges real upstream-only version lines into the local index response (mergeExternalVersions), a read-only proxy step with no retention write of its own, so an upstream-only crate is actually visible to a client's dependency resolution before anything is retained. Fixes against the live Kellnr/crates.io protocols found while addressing review: KellnrSidecarClient now implements listPackages (its absence made every ListPackages call 500 once cargo joined the container-backed formats); sparse-index bucket paths are lowercased per the Cargo Book's own spec (crates.io's own index is case-sensitive about this even though a crate's real name isn't); the admin account behind Kellnr's internal publish token is given a fresh random password per container rather than Kellnr's own shared default; a stale cached publish token (e.g. after a silent container restart) is retried once rather than 401ing forever; both publish-body parsing and the external sparse-index fetch are now bounded against an oversized allocation; a renamed dependency's alias and real name are mapped correctly between the index and publish shapes, and features2/links/rust_version now survive a retained crate's synthesized metadata; the Kellnr image is pinned to the exact version this was built and tested against rather than a floating major tag. Known gaps, called out in docs/services/codeartifact.md: no repository-to-repository upstream importer yet for cargo (every other native format already has one), and no yank/owner/search routes.
This commit is contained in:
1 parent
1b14d10b1f
commit
15a632e446
19 files changed
+4286
-79
No files matched your search
@@ -945,6 +945,15 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("bagetter/bagetter:1.6.5")
|
||||
String nugetImage();
|
||||
|
||||
/**
|
||||
* Image used for the per-repository Kellnr container backing the {@code cargo} format.
|
||||
* Same reasoning as {@link #npmImage()}: Kellnr has no native concept of multiple named
|
||||
* registries 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("ghcr.io/kellnr/kellnr:5.14.1")
|
||||
String cargoImage();
|
||||
}
|
||||
|
||||
interface ConnectServiceConfig {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A real outbound client for the one public Cargo (Rust) repository CodeArtifact's {@code
|
||||
* public:crates-io} external connection names (confirmed real and documented from AWS's own
|
||||
* {@code external-connection.html}, "Rust | Crates.io | public:crates-io"): the real sparse
|
||||
* HTTP index at {@code index.crates.io} and the real {@code .crate} download host at {@code
|
||||
* static.crates.io}, both confirmed live, not assumed:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code https://index.crates.io/config.json} (fetched live): {@code {"dl":
|
||||
* "https://static.crates.io/crates","api":"https://crates.io"}}, confirming the download
|
||||
* template below via the RFC 2789 "no markers" rule.</li>
|
||||
* <li>{@code https://index.crates.io/li/bc/libc} (fetched live): a real per-crate index file,
|
||||
* newline-delimited JSON, one line per version.</li>
|
||||
* <li>{@code https://static.crates.io/crates/libc/0.2.169/download} (fetched live): {@code
|
||||
* 200}, {@code application/gzip}, the real {@code .crate} bytes directly, no redirect observed
|
||||
* for this case (this client still follows redirects defensively, the same as {@link
|
||||
* NuGetExternalConnectionClient}).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Every failure mode (an unknown connection name, a real non-200 response, a network error)
|
||||
* resolves to {@link Optional#empty()} rather than throwing, the same reasoning {@link
|
||||
* NuGetExternalConnectionClient}'s own javadoc gives: a caller here is always deciding whether to
|
||||
* retain something from an external source, and the documented behavior for an unreachable
|
||||
* external repository is to behave exactly as if the content were not found.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CargoExternalConnectionClient {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CargoExternalConnectionClient.class);
|
||||
|
||||
private static final Map<String, String> INDEX_BASE_URLS = Map.of(
|
||||
"public:crates-io", "https://index.crates.io");
|
||||
private static final Map<String, String> DOWNLOAD_BASE_URLS = Map.of(
|
||||
"public:crates-io", "https://static.crates.io/crates");
|
||||
// A real sparse-index file is plain newline-delimited JSON, one short line per published
|
||||
// version; even crates.io's own most-published crates never approach this, but the real
|
||||
// upstream's own response size is otherwise unbounded, so this is checked during the read
|
||||
// itself rather than only after buffering an arbitrarily large response whole.
|
||||
private static final int MAX_SPARSE_INDEX_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final Map<String, String> indexBaseUrls;
|
||||
private final Map<String, String> downloadBaseUrls;
|
||||
|
||||
@Inject
|
||||
public CargoExternalConnectionClient() {
|
||||
this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(), INDEX_BASE_URLS, DOWNLOAD_BASE_URLS);
|
||||
}
|
||||
|
||||
/** For tests: fake base-URL maps, so the wire contract can be exercised against a local
|
||||
* {@code HttpServer} fake instead of the real public registry. */
|
||||
CargoExternalConnectionClient(HttpClient httpClient, Map<String, String> indexBaseUrls,
|
||||
Map<String, String> downloadBaseUrls) {
|
||||
this.httpClient = httpClient;
|
||||
this.indexBaseUrls = indexBaseUrls;
|
||||
this.downloadBaseUrls = downloadBaseUrls;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real, complete sparse-index bytes for {@code packageName} from the real public
|
||||
* registry {@code externalConnectionName} names: every version line this crate's real index
|
||||
* file currently carries, confirmed to be small enough to always buffer whole (a real crate's
|
||||
* own index file, unlike a {@code .crate} itself, is plain newline-delimited JSON text, never
|
||||
* sized anywhere near the asset quota).
|
||||
*/
|
||||
public Optional<byte[]> fetchSparseIndex(String externalConnectionName, String packageName) {
|
||||
String baseUrl = indexBaseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.cratesIoBucketPath(packageName));
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(20)).GET().build();
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not fetch {0}''s real sparse index from external connection {1}: {2}", packageName,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
try (InputStream body = response.body()) {
|
||||
byte[] bytes = body.readNBytes(MAX_SPARSE_INDEX_BYTES + 1);
|
||||
if (bytes.length > MAX_SPARSE_INDEX_BYTES) {
|
||||
LOG.warnv("Skipping {0}''s real sparse index from external connection {1}: larger than {2} bytes.",
|
||||
packageName, externalConnectionName, MAX_SPARSE_INDEX_BYTES);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(bytes);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not read {0}''s real sparse index from external connection {1}: {2}", packageName,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** One crate version's real size and SHA-256, fetched straight to {@code destination} without
|
||||
* ever being held whole in memory: both come from the same streamed copy, via {@link
|
||||
* AssetDigestingInputStream}, rather than a second whole-file read just to hash it afterward. */
|
||||
public record FetchedFile(long size, String sha256) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches {@code packageName}/{@code version}'s real {@code .crate} bytes from the real
|
||||
* public registry {@code externalConnectionName} names, streamed straight to {@code
|
||||
* destination}. Capped at {@code CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the
|
||||
* copy itself, via {@link AssetDigestingInputStream}, the same reasoning {@link
|
||||
* NuGetExternalConnectionClient#fetchPackage(String, String, String, Path)}'s own javadoc
|
||||
* gives: the real registry's own file size is otherwise unbounded and isn't known until the
|
||||
* download is already in progress.
|
||||
*/
|
||||
public Optional<FetchedFile> fetchCrate(String externalConnectionName, String packageName, String version,
|
||||
Path destination) {
|
||||
String baseUrl = downloadBaseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(packageName) + "/"
|
||||
+ SidecarUriUtils.encodeSegment(version) + "/download");
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(SidecarUriUtils.maxTransferTimeout()).GET()
|
||||
.build();
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not fetch {0} {1} from external connection {2}: {3}", packageName, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
try (InputStream body = response.body()) {
|
||||
AssetDigestingInputStream digesting = new AssetDigestingInputStream(body,
|
||||
CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
Files.copy(digesting, destination, StandardCopyOption.REPLACE_EXISTING);
|
||||
return Optional.of(new FetchedFile(digesting.size(), digesting.hashesHex().get("SHA-256")));
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not read {0} {1} from external connection {2}: {3}", packageName, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import io.floci.aws.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.PUT;
|
||||
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.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Serves the real Cargo (Rust) wire protocol behind the URL {@code GetRepositoryEndpoint} returns
|
||||
* for the {@code cargo} format: the sparse HTTP registry index (RFC 2789) and the publish/download
|
||||
* REST API AWS's own "Configure and use Cargo with CodeArtifact" guide documents, not a
|
||||
* CodeArtifact API action. Backed by one Kellnr container per repository, provisioned on first
|
||||
* use (see {@link KellnrSidecarManager}/{@link KellnrSidecarClient} for the sidecar itself).
|
||||
*
|
||||
* <p>Authors its own {@code config.json} rather than proxying Kellnr's own: Kellnr's own response
|
||||
* self-reports its own internal container address (confirmed live), exactly the problem {@link
|
||||
* RepositorySidecarManager#ensureReady}'s {@code publicUrl} parameter exists for, and both the
|
||||
* {@code dl}/{@code api} it needs are a single combined base identical to this repository's own
|
||||
* real endpoint, matching how AWS's own CodeArtifact serves Cargo (one endpoint for index, API,
|
||||
* and downloads alike, unlike crates.io's own split between its index and its API host). The
|
||||
* sparse-index files themselves (one per crate) *are* proxied close to verbatim: unlike a
|
||||
* version's own downloadable asset, nothing in that response is self-referential (a real client
|
||||
* derives the download URL from {@code config.json}'s own {@code dl} template, never from a field
|
||||
* inside an index entry), so there is nothing here to rewrite.
|
||||
*
|
||||
* <p>Requires the token real CodeArtifact requires here, obtained from {@code
|
||||
* GetAuthorizationToken}. AWS's own Cargo configuration doc has the client send it as a bare
|
||||
* {@code Authorization} header with no scheme prefix at all (confirmed from the Cargo Book's own
|
||||
* registry-authentication page); {@link CodeArtifactTokenExtractor} accepts that alongside the
|
||||
* Bearer/Basic schemes every other format already uses.
|
||||
*
|
||||
* <p>Only the subcommands AWS's own guide documents against CodeArtofact: {@code cargo add}/
|
||||
* {@code cargo build} (the sparse index plus the download route) and {@code cargo publish}. No
|
||||
* {@code yank}/{@code owner}/search routes: AWS's own guide never mentions any of the three, so
|
||||
* this isn't filling a real, documented gap by building them.
|
||||
*/
|
||||
@Path("/codeartifact/cargo/{domain}/{repository}/{path:.+}")
|
||||
public class CodeArtifactCargoController {
|
||||
|
||||
private static final String PUBLISH_PATH = "api/v1/crates/new";
|
||||
private static final String DOWNLOAD_PREFIX = "api/v1/crates/";
|
||||
private static final String DOWNLOAD_SUFFIX = "/download";
|
||||
private static final String CONFIG_PATH = "config.json";
|
||||
// A real publish's own metadata (name, version, deps, features, authors, etc.) is plain JSON
|
||||
// text, always well under a megabyte even for a crate with an unusually large dependency
|
||||
// list; this is a generous ceiling, not a realistic average, against the wire body's own
|
||||
// 4-byte client-declared metadata length driving an allocation far larger than the staged
|
||||
// file could ever actually need before the crate's own size is checked.
|
||||
private static final int MAX_PUBLISH_METADATA_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoController(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CodeArtifactCargoExternalConnectionImporter externalConnectionImporter, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
private record RepositoryHandle(String repoId, String region, String owner, String publicBaseUrl) {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.WILDCARD)
|
||||
public Response get(@Context HttpHeaders headers, @PathParam("domain") String domain,
|
||||
@PathParam("repository") String repository, @PathParam("path") String path) {
|
||||
RepositoryHandle handle = requireRepository(headers, domain, repository);
|
||||
AtomicBoolean leaseTransferred = new AtomicBoolean();
|
||||
try {
|
||||
return getWithLease(handle, domain, repository, path, leaseTransferred);
|
||||
} finally {
|
||||
if (!leaseTransferred.get()) {
|
||||
endUse(handle.repoId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Response getWithLease(RepositoryHandle handle, String domain, String repository, String path,
|
||||
AtomicBoolean leaseTransferred) {
|
||||
if (CONFIG_PATH.equals(path)) {
|
||||
return configJson(handle);
|
||||
}
|
||||
Optional<String[]> download = parseDownloadPath(path);
|
||||
if (download.isPresent()) {
|
||||
return downloadCrate(handle, domain, repository, download.get()[0], download.get()[1], leaseTransferred);
|
||||
}
|
||||
return sparseIndexLookup(handle, domain, repository, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo's own sparse-index discovery document, authored directly rather than proxied (see
|
||||
* this class's own javadoc for why): {@code dl}/{@code api} both rooted at this repository's
|
||||
* own real {@code GetRepositoryEndpoint} value, the same "always the real, externally-reachable
|
||||
* address, never this emulator's own internal one" rule {@code CodeArtifactNuGetController
|
||||
* .serviceIndex} already follows. {@code auth-required: true} matches real CodeArtifact's own
|
||||
* behavior: every request here, read or write, already requires a valid token.
|
||||
*/
|
||||
private Response configJson(RepositoryHandle handle) {
|
||||
String body = """
|
||||
{
|
||||
"dl": "%1$s/api/v1/crates",
|
||||
"api": "%1$s",
|
||||
"auth-required": true
|
||||
}
|
||||
""".formatted(handle.publicBaseUrl());
|
||||
return Response.status(200).entity(body).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response downloadCrate(RepositoryHandle handle, String domain, String repository, String packageName,
|
||||
String version, AtomicBoolean leaseTransferred) {
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(handle.owner(), handle.region(), domain, repository,
|
||||
"cargo", null, packageName, version, handle.repoId());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
// A cache miss on this emulator's own Kellnr is exactly the trigger AWS's own docs
|
||||
// describe for an external connection: fetch the real crate from crates.io and retain it,
|
||||
// then let the stream below find it there, the same as any other request. Not attempted
|
||||
// at all when Kellnr already has it: the only extra cost on every other request is this
|
||||
// one cheap local existence check, the same pattern CodeArtifactNuGetController's own
|
||||
// .nupkg route already uses.
|
||||
if (!kellnr.packageVersionExists(handle.repoId(), domain, repository, null, packageName, version)) {
|
||||
externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), packageName, version);
|
||||
}
|
||||
Optional<RepositorySidecarManager.StreamedAsset> streamed = kellnr.fetchPackageVersionAssetStreamed(
|
||||
handle.repoId(), domain, repository, null, packageName, version,
|
||||
packageName + "-" + version + ".crate");
|
||||
if (streamed.isEmpty()) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
leaseTransferred.set(true);
|
||||
InputStream body = StreamingResponses.closingWith(streamed.get().content(), () -> endUse(handle.repoId()));
|
||||
Response.ResponseBuilder builder = Response.status(200).type(MediaType.APPLICATION_OCTET_STREAM);
|
||||
if (streamed.get().contentLength() >= 0) {
|
||||
builder.header("Content-Length", streamed.get().contentLength());
|
||||
}
|
||||
return StreamingResponses.streamingResponse(body, stream -> builder.entity(stream).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* The real sparse-index bytes for the crate {@code path}'s own last segment names (the real
|
||||
* crates.io bucketing scheme, confirmed live in part 1: a 1/2/3-character name buckets by its
|
||||
* own length or first character, a 4+-character name by its own first two then next two
|
||||
* characters: in every case, the crate's real name is the path's own final segment), proxied
|
||||
* close to verbatim. Not filtered by Archived/Disposed status here: see this class's own
|
||||
* javadoc for why that mapping is deliberately deferred rather than guessed at.
|
||||
*
|
||||
* <p>Merged with any real upstream-only version lines the repository's own {@code
|
||||
* public:crates-io} external connection can see (see {@link
|
||||
* CodeArtifactCargoExternalConnectionImporter}'s own javadoc for why this, unlike every other
|
||||
* format's own external-connection importer, needs a listing merge and not just an
|
||||
* on-demand download): a real {@code cargo} client's dependency resolver only ever sees a
|
||||
* version by first finding it here.
|
||||
*/
|
||||
private Response sparseIndexLookup(RepositoryHandle handle, String domain, String repository, String path) {
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
String packageName = lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
|
||||
if (packageName.isEmpty()) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
Optional<byte[]> local = kellnr.fetchSparseIndexRaw(handle.repoId(), domain, repository, packageName);
|
||||
Optional<byte[]> merged = externalConnectionImporter.mergeExternalVersions(handle.region(), domain,
|
||||
handle.owner(), repository, packageName, local);
|
||||
return merged.map(bytes -> Response.status(200).entity(bytes).type(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.build())
|
||||
.orElseGet(() -> Response.status(404).build());
|
||||
}
|
||||
|
||||
/** {@code api/v1/crates/{name}/{version}/download} → {@code [name, version]}, else empty. */
|
||||
private static Optional<String[]> parseDownloadPath(String path) {
|
||||
if (!path.startsWith(DOWNLOAD_PREFIX) || !path.endsWith(DOWNLOAD_SUFFIX)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String middle = path.substring(DOWNLOAD_PREFIX.length(), path.length() - DOWNLOAD_SUFFIX.length());
|
||||
int lastSlash = middle.lastIndexOf('/');
|
||||
if (lastSlash <= 0 || lastSlash == middle.length() - 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new String[] {middle.substring(0, lastSlash), middle.substring(lastSlash + 1)});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a real {@code cargo publish}: {@code PUT} to {@code api/v1/crates/new}, the real
|
||||
* binary wire body (4-byte little-endian metadata length + JSON metadata, then 4-byte
|
||||
* little-endian crate length + the {@code .crate} itself) confirmed directly from the Cargo
|
||||
* Book's own spec text and live against Kellnr in part 1. The whole body is staged to disk
|
||||
* before anything else touches it (never a resident array: a {@code .crate} can approach the
|
||||
* same 5 GB AWS quota any other format's asset can), then forwarded to Kellnr verbatim via
|
||||
* {@link KellnrSidecarClient#publishRawWireBody}: the real client's own metadata, dependency
|
||||
* list included, must survive untouched, the reason that method exists separately from {@link
|
||||
* KellnrSidecarClient#storePackageVersionAsset}'s own reconstructed-metadata path.
|
||||
*/
|
||||
@PUT
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response publish(@Context HttpHeaders headers, @PathParam("domain") String domain,
|
||||
@PathParam("repository") String repository, @PathParam("path") String path,
|
||||
InputStream body) {
|
||||
if (!PUBLISH_PATH.equals(path)) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
RepositoryHandle handle = requireRepository(headers, domain, repository);
|
||||
try {
|
||||
return publishWithLease(handle, domain, repository, body);
|
||||
} finally {
|
||||
endUse(handle.repoId());
|
||||
}
|
||||
}
|
||||
|
||||
private Response publishWithLease(RepositoryHandle handle, String domain, String repository, InputStream body) {
|
||||
java.nio.file.Path staged;
|
||||
try {
|
||||
staged = service.stageAssetBody(
|
||||
new AssetDigestingInputStream(body, CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES));
|
||||
} catch (AssetDigestingInputStream.AssetTooLargeException e) {
|
||||
return Response.status(413).build();
|
||||
}
|
||||
try {
|
||||
return publishStagedBody(handle, domain, repository, staged);
|
||||
} finally {
|
||||
service.deleteStagedAssetBody(staged);
|
||||
}
|
||||
}
|
||||
|
||||
private Response publishStagedBody(RepositoryHandle handle, String domain, String repository,
|
||||
java.nio.file.Path staged) {
|
||||
CargoPublishMetadata metadata;
|
||||
long stagedSize;
|
||||
try {
|
||||
stagedSize = Files.size(staged);
|
||||
metadata = readMetadataPrefix(staged);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Response.status(400).entity(e.getMessage()).build();
|
||||
}
|
||||
// The crate's own real size, not the whole wire body (metadata included): the same 5 GB
|
||||
// AWS quota PublishPackageVersion enforces, checked against the real asset bytes alone,
|
||||
// the same way CodeArtifactNuGetController#pushExtractedForm checks the real .nupkg size
|
||||
// rather than the surrounding multipart envelope.
|
||||
long crateLength = stagedSize - 4 - metadata.metadataLength() - 4;
|
||||
if (crateLength > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) {
|
||||
return Response.status(413).build();
|
||||
}
|
||||
try {
|
||||
service.requireContainerBackedPackagePublishAllowed(handle.region(), domain, handle.owner(), repository,
|
||||
"cargo", null, metadata.name());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(409).entity(e.getMessage()).build();
|
||||
}
|
||||
String beforeRevision;
|
||||
try {
|
||||
beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(handle.region(), domain,
|
||||
handle.owner(), repository, "cargo", null, metadata.name(), metadata.version());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(409).entity(e.getMessage()).build();
|
||||
}
|
||||
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
|
||||
repository, "cargo", null, metadata.name());
|
||||
KellnrSidecarClient.KellnrPublishResult result;
|
||||
synchronized (kellnr.lockFor(handle.repoId())) {
|
||||
result = kellnr.publishRawWireBody(handle.repoId(), staged, stagedSize);
|
||||
}
|
||||
if (result.statusCode() != 200) {
|
||||
// Kellnr's own real rejection (e.g. a republish of an already-existing name/version,
|
||||
// see KellnrSidecarClient#publishRawWireBody's own javadoc) is already shaped exactly
|
||||
// like the Cargo Book's own documented error response: forward it verbatim rather than
|
||||
// translating it into something this controller invents.
|
||||
return Response.status(result.statusCode()).entity(result.body()).type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
service.completeContainerBackedPublishIfCurrentRepository(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), "cargo", metadata.name(), metadata.version(), crateLength, fenceSnapshot,
|
||||
beforeRevision, null, 0L);
|
||||
return Response.status(200).entity("{\"warnings\":null}").type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private record CargoPublishMetadata(String name, String version, int metadataLength) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads just the wire body's own leading length-prefixed JSON metadata (never the crate bytes
|
||||
* that follow it) to learn {@code name}/{@code version}, the same real binary layout {@link
|
||||
* KellnrSidecarClient#publishRawWireBody}'s own javadoc documents.
|
||||
*/
|
||||
private CargoPublishMetadata readMetadataPrefix(java.nio.file.Path staged) throws IOException {
|
||||
try (InputStream in = new BufferedInputStream(Files.newInputStream(staged))) {
|
||||
byte[] lengthBytes = in.readNBytes(4);
|
||||
if (lengthBytes.length != 4) {
|
||||
throw new IllegalArgumentException("Truncated publish body: missing the metadata length prefix.");
|
||||
}
|
||||
int metadataLength = ByteBuffer.wrap(lengthBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
|
||||
if (metadataLength < 0 || metadataLength > MAX_PUBLISH_METADATA_BYTES) {
|
||||
throw new IllegalArgumentException("Publish body's own declared metadata length ("
|
||||
+ metadataLength + " bytes) is not a reasonable size.");
|
||||
}
|
||||
byte[] metadataBytes = in.readNBytes(metadataLength);
|
||||
if (metadataBytes.length != metadataLength) {
|
||||
throw new IllegalArgumentException("Truncated publish body: metadata shorter than its own "
|
||||
+ "declared length.");
|
||||
}
|
||||
JsonNode metadata;
|
||||
try {
|
||||
metadata = mapper.readTree(metadataBytes);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("Could not parse the publish body's own metadata as JSON.");
|
||||
}
|
||||
String name = metadata.path("name").asText(null);
|
||||
String version = metadata.path("vers").asText(null);
|
||||
if (name == null || name.isBlank() || version == null || version.isBlank()) {
|
||||
throw new IllegalArgumentException("Publish metadata is missing a crate name or version.");
|
||||
}
|
||||
return new CargoPublishMetadata(name, version, metadataLength);
|
||||
}
|
||||
}
|
||||
|
||||
private void endUse(String repoId) {
|
||||
kellnr.endUse(repoId);
|
||||
}
|
||||
|
||||
private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) {
|
||||
String token = CodeArtifactTokenExtractor.extractToken(headers);
|
||||
// No WWW-Authenticate scheme challenge: unlike Maven/pypi/NuGet (genuinely Basic, per
|
||||
// AWS's own docs) or npm (genuinely Bearer), a real cargo client's own token has no named
|
||||
// HTTP auth scheme at all (it's sent as a bare Authorization value), so naming one here
|
||||
// would misleadingly suggest a scheme real CodeArtifact doesn't actually expect for Cargo.
|
||||
AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain)
|
||||
.orElseThrow(() -> new NotAuthorizedException(Response.status(401).build()));
|
||||
String repoId;
|
||||
try {
|
||||
repoId = service.resolveContainerIdAndBeginUse("cargo", scope.region(), domain, scope.owner(), repository,
|
||||
kellnr);
|
||||
} catch (AwsException e) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
try {
|
||||
String endpoint = service.getRepositoryEndpoint(scope.region(), domain, scope.owner(), repository,
|
||||
"cargo", null);
|
||||
String publicBaseUrl = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
|
||||
return new RepositoryHandle(repoId, scope.region(), scope.owner(), publicBaseUrl);
|
||||
} catch (RuntimeException e) {
|
||||
endUse(repoId);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+384
@@ -0,0 +1,384 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.services.codeartifact.model.ExternalConnection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Retains a Cargo crate version from the real public {@code crates.io} registry a repository's
|
||||
* {@code public:crates-io} external connection names, the way real CodeArtifact does when a
|
||||
* {@code cargo} client requests a crate version that is not present locally yet (confirmed real
|
||||
* and documented from AWS's own {@code external-connection.html}: "Rust | Crates.io |
|
||||
* public:crates-io"), mirroring {@link CodeArtifactNuGetExternalConnectionImporter}'s own
|
||||
* claim/fence/retention shell exactly.
|
||||
*
|
||||
* <p><b>One thing this format genuinely needs that NuGet/Maven/pypi don't</b>: {@link
|
||||
* CodeArtifactNuGetExternalConnectionImporter}'s own javadoc deliberately does not merge the real
|
||||
* upstream version listing into any local response, since a NuGet client can fetch a known {@code
|
||||
* .nupkg} URL directly without ever consulting a version-list index first. A real {@code cargo}
|
||||
* client cannot work that way: {@code cargo build}/{@code cargo add} always resolve against the
|
||||
* sparse index first, and the index for one crate name is a single file covering every version,
|
||||
* not a per-version URL. Skipping a listing merge the way NuGet does would make an upstream-only
|
||||
* crate invisible to Cargo's own resolver even though the download route alone could serve it.
|
||||
* {@link #mergeExternalVersions} is that merge: a pure, read-only proxy of the real upstream
|
||||
* index's own version lines not already known locally, never a retention write (Kellnr has no
|
||||
* "write an index entry without the crate bytes" capability, so there is nothing to write here
|
||||
* anyway). It takes no package fence snapshot the way {@code CodeArtifactService
|
||||
* #mergeMavenMetadataUnderPackageFence}'s own package-level merge does: that method guards a real,
|
||||
* persistent write to Reposilite's own {@code maven-metadata.xml} against a concurrent {@code
|
||||
* DeletePackage}/{@code DeleteRepository} resurrecting deleted content; this method never
|
||||
* persists anything at all, so the same race's worst case is a single HTTP response momentarily
|
||||
* showing a version that is concurrently being deleted, self-correcting on the very next request
|
||||
* once the deletion fence moves.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactCargoExternalConnectionImporter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CargoExternalConnectionClient externalConnectionClient;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoExternalConnectionImporter(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CargoExternalConnectionClient externalConnectionClient, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionClient = externalConnectionClient;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retain {@code packageName}/{@code version}'s real {@code .crate} into {@code
|
||||
* repoId} from {@code repository}'s own cargo external connection. Returns {@code true} only
|
||||
* when the crate is genuinely present under this connection's claim by the time this returns,
|
||||
* whether because this attempt imported it or a concurrent one already had, the same contract
|
||||
* {@link CodeArtifactNuGetExternalConnectionImporter#tryImport}'s own javadoc documents.
|
||||
*/
|
||||
public boolean tryImport(String region, String domain, String owner, String repository, String repoId,
|
||||
String packageName, String version) {
|
||||
String externalConnectionName = cargoExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"EXTERNAL_UPSTREAM")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName);
|
||||
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName, version);
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
|
||||
domain, owner, repository, "cargo", null, packageName, version, externalConnectionName,
|
||||
RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot);
|
||||
if (!claim.claimed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean imported = false;
|
||||
try {
|
||||
if (kellnr.packageVersionExists(repoId, domain, repository, null, packageName, version)) {
|
||||
imported = service.retainedVersionOriginConnection(region, domain, owner, repository, "cargo", null,
|
||||
packageName, version).filter(externalConnectionName::equals).isPresent();
|
||||
return imported;
|
||||
}
|
||||
Optional<byte[]> index = externalConnectionClient.fetchSparseIndex(externalConnectionName, packageName);
|
||||
if (index.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Optional<JsonNode> indexLine = findIndexLine(index.get(), version);
|
||||
if (indexLine.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Path crateFile;
|
||||
try {
|
||||
crateFile = Files.createTempFile("codeartifact-cargo-import-", ".crate");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to create a staging file for a Cargo external-connection "
|
||||
+ "import", e);
|
||||
}
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> fetched;
|
||||
try {
|
||||
fetched = externalConnectionClient.fetchCrate(externalConnectionName, packageName, version,
|
||||
crateFile);
|
||||
} catch (AssetDigestingInputStream.AssetTooLargeException e) {
|
||||
LOG.warnv("Skipping {0} {1}: the real registry''s own file is larger than this emulator''s "
|
||||
+ "{2}-byte asset quota.", packageName, version,
|
||||
CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
return false;
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String expectedSha256 = indexLine.get().path("cksum").asText(null);
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(fetched.get().sha256())) {
|
||||
LOG.warnv("Skipping {0} {1}: its real bytes do not match the real index''s own cksum.",
|
||||
packageName, version);
|
||||
return false;
|
||||
}
|
||||
long contentLength = fetched.get().size();
|
||||
Path stagedWireBody = buildStagedWireBody(metadataFromIndexLine(indexLine.get()), crateFile);
|
||||
try {
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(
|
||||
region, domain, owner, repository, "cargo", null, packageName, version,
|
||||
versionFenceSnapshot, packageFenceSnapshot, claim.episodeId(), repoId, packageName
|
||||
+ "-" + version + ".crate", contentLength,
|
||||
() -> {
|
||||
KellnrSidecarClient.KellnrPublishResult publishResult = kellnr.publishRawWireBody(
|
||||
repoId, stagedWireBody, fileSize(stagedWireBody));
|
||||
if (publishResult.statusCode() != 200) {
|
||||
throw new IllegalStateException("Kellnr refused this retained crate: upstream "
|
||||
+ "returned " + publishResult.statusCode());
|
||||
}
|
||||
});
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
return imported;
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(stagedWireBody);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Cargo external-connection wire-body file at {0}",
|
||||
stagedWireBody);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(crateFile);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Cargo external-connection crate file at {0}", crateFile);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (imported) {
|
||||
service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository,
|
||||
"cargo", null, packageName, packageFenceSnapshot, repoId);
|
||||
}
|
||||
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "cargo", null, packageName,
|
||||
version, claim.episodeId(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code localIndexBytes}'s own real version lines, plus every real upstream-only version
|
||||
* line {@code packageName}'s own real {@code crates.io} index carries that isn't already a
|
||||
* local line, each upstream line passed through close to verbatim (never re-serialized),
|
||||
* matching the "proxy real content verbatim" philosophy {@code CodeArtifactCargoController}'s
|
||||
* own local sparse-index route already uses. A {@code BLOCK}ed package, or one with no cargo
|
||||
* external connection configured, gets {@code localIndexBytes} back unchanged: "behave exactly
|
||||
* as if the external content did not exist," the same rule every other retention path in this
|
||||
* codebase already follows.
|
||||
*/
|
||||
public Optional<byte[]> mergeExternalVersions(String region, String domain, String owner, String repository,
|
||||
String packageName, Optional<byte[]> localIndexBytes) {
|
||||
String externalConnectionName = cargoExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"EXTERNAL_UPSTREAM")) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
Optional<byte[]> upstream = externalConnectionClient.fetchSparseIndex(externalConnectionName, packageName);
|
||||
if (upstream.isEmpty()) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
List<String> localLines = splitLines(localIndexBytes.orElse(new byte[0]));
|
||||
List<String> upstreamLines = splitLines(upstream.get());
|
||||
Map<String, String> merged = new LinkedHashMap<>();
|
||||
for (String line : localLines) {
|
||||
indexLineVersion(line).ifPresent(vers -> merged.put(vers, line));
|
||||
}
|
||||
for (String line : upstreamLines) {
|
||||
indexLineVersion(line).ifPresent(vers -> merged.putIfAbsent(vers, line));
|
||||
}
|
||||
if (merged.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(String.join("\n", merged.values()).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private Optional<String> indexLineVersion(String line) {
|
||||
try {
|
||||
return Optional.ofNullable(mapper.readTree(line).path("vers").asText(null));
|
||||
} catch (IOException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> splitLines(byte[] indexBytes) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (String line : new String(indexBytes, StandardCharsets.UTF_8).split("\n")) {
|
||||
if (!line.isBlank()) {
|
||||
lines.add(line);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private Optional<JsonNode> findIndexLine(byte[] indexBytes, String version) {
|
||||
for (String line : splitLines(indexBytes)) {
|
||||
JsonNode node;
|
||||
try {
|
||||
node = mapper.readTree(line);
|
||||
} catch (IOException e) {
|
||||
continue;
|
||||
}
|
||||
if (version.equals(node.path("vers").asText(null))) {
|
||||
return Optional.of(node);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* A real {@code cargo publish} metadata object built from {@code indexLine}'s own real
|
||||
* fields, the same honest, bounded limitation {@code KellnrSidecarClient
|
||||
* #minimalPublishMetadata} already documents for {@code CopyPackageVersions}: the real
|
||||
* index never carries {@code authors}/{@code description}/etc. at all (those live in the
|
||||
* {@code .crate}'s own embedded {@code Cargo.toml}, not the index), so those fields stay
|
||||
* null/empty here too. Unlike that method, {@code deps}/{@code features} are the crate's own
|
||||
* real values, not always empty: the real index already has them, confirmed from a live
|
||||
* fetch of {@code index.crates.io}'s own per-crate index file.
|
||||
*
|
||||
* <p>A renamed dependency's alias and real crate name swap fields between the two shapes
|
||||
* (confirmed from the Cargo Book's own registry-index/registry-web-api pages): the index puts
|
||||
* the alias in its own {@code name} and the real crate in {@code package}, while publish
|
||||
* metadata puts the real crate in {@code name} and the alias in {@code
|
||||
* explicit_name_in_toml}; an unrenamed dependency has no {@code package} field at all, and
|
||||
* its index {@code name} is already the real crate name. {@code req} is renamed to {@code
|
||||
* version_req} going the same way; every other dependency field name is identical in both
|
||||
* shapes. {@code features2} (namespaced/weak-dependency feature syntax crates.io splits out
|
||||
* for pre-1.19 Cargo compatibility) is merged into {@code features} rather than dropped, the
|
||||
* same merge the Cargo Book documents a real client performing on read. Top-level {@code
|
||||
* links} is identical in both shapes; top-level {@code rust_version} is carried over even
|
||||
* though crates.io itself re-derives it from the {@code .crate}'s own {@code Cargo.toml}
|
||||
* rather than trusting the index's copy.
|
||||
*/
|
||||
private byte[] metadataFromIndexLine(JsonNode indexLine) {
|
||||
ObjectNode metadata = mapper.createObjectNode();
|
||||
metadata.put("name", indexLine.path("name").asText());
|
||||
metadata.put("vers", indexLine.path("vers").asText());
|
||||
ArrayNode deps = metadata.putArray("deps");
|
||||
for (JsonNode dep : indexLine.path("deps")) {
|
||||
ObjectNode mappedDep = deps.addObject();
|
||||
String aliasInIndex = dep.path("name").asText(null);
|
||||
String realCrateName = dep.path("package").asText(null);
|
||||
if (realCrateName != null) {
|
||||
mappedDep.put("name", realCrateName);
|
||||
mappedDep.put("explicit_name_in_toml", aliasInIndex);
|
||||
} else {
|
||||
mappedDep.put("name", aliasInIndex);
|
||||
mappedDep.put("explicit_name_in_toml", (String) null);
|
||||
}
|
||||
mappedDep.put("version_req", dep.path("req").asText(null));
|
||||
mappedDep.set("features", dep.path("features"));
|
||||
mappedDep.put("optional", dep.path("optional").asBoolean(false));
|
||||
mappedDep.put("default_features", dep.path("default_features").asBoolean(true));
|
||||
mappedDep.set("target", dep.path("target").isMissingNode() ? mapper.nullNode() : dep.path("target"));
|
||||
mappedDep.put("kind", dep.path("kind").asText("normal"));
|
||||
mappedDep.put("registry", (String) null);
|
||||
}
|
||||
ObjectNode features = indexLine.path("features").isObject()
|
||||
? indexLine.path("features").deepCopy() : mapper.createObjectNode();
|
||||
if (indexLine.path("features2").isObject()) {
|
||||
features.setAll((ObjectNode) indexLine.path("features2"));
|
||||
}
|
||||
metadata.set("features", features);
|
||||
metadata.putArray("authors");
|
||||
metadata.put("description", (String) null);
|
||||
metadata.put("documentation", (String) null);
|
||||
metadata.put("homepage", (String) null);
|
||||
metadata.put("readme", (String) null);
|
||||
metadata.put("readme_file", (String) null);
|
||||
metadata.putArray("keywords");
|
||||
metadata.putArray("categories");
|
||||
metadata.put("license", (String) null);
|
||||
metadata.put("license_file", (String) null);
|
||||
metadata.put("repository", (String) null);
|
||||
metadata.putObject("badges");
|
||||
metadata.put("links", indexLine.path("links").asText(null));
|
||||
metadata.put("rust_version", indexLine.path("rust_version").asText(null));
|
||||
return metadata.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the real Cargo publish wire body (see {@code KellnrSidecarClient
|
||||
* #publishRawWireBody}'s own javadoc for its shape) straight to a staged file rather than one
|
||||
* resident {@code byte[]} the way {@code KellnrSidecarClient#publishWireBody} does for {@code
|
||||
* CopyPackageVersions}' own always-small, synthesized-empty-deps case: a crate retained
|
||||
* through an external connection can be sized anywhere up to the same 5 GB quota any other
|
||||
* asset can, so the header is written first and {@code crateFile}'s own real bytes are then
|
||||
* streamed straight through rather than ever held alongside it in memory.
|
||||
*/
|
||||
private static Path buildStagedWireBody(byte[] metadataJson, Path crateFile) {
|
||||
Path staged;
|
||||
try {
|
||||
staged = Files.createTempFile("codeartifact-cargo-import-wire-", ".bin");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to create a staging file for a Cargo external-connection "
|
||||
+ "publish wire body", e);
|
||||
}
|
||||
try {
|
||||
long crateLength = Files.size(crateFile);
|
||||
try (OutputStream out = Files.newOutputStream(staged)) {
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(metadataJson.length).array());
|
||||
out.write(metadataJson);
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) crateLength).array());
|
||||
Files.copy(crateFile, out);
|
||||
}
|
||||
return staged;
|
||||
} catch (IOException e) {
|
||||
// This method's own temp file, not yet handed back to a caller that could clean it up
|
||||
// itself: a caller's own finally is scoped to a path it actually received, so a failure
|
||||
// here must clean up before rethrowing rather than leaving it to a cleanup block that
|
||||
// never starts.
|
||||
try {
|
||||
Files.deleteIfExists(staged);
|
||||
} catch (IOException cleanupFailure) {
|
||||
LOG.warnv(cleanupFailure, "Could not delete a staged Cargo external-connection wire-body file at "
|
||||
+ "{0} after a failed write", staged);
|
||||
}
|
||||
throw new UncheckedIOException("Failed to stage a Cargo external-connection publish wire body", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static long fileSize(Path path) {
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private String cargoExternalConnectionName(String region, String domain, String owner, String repository) {
|
||||
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
|
||||
.filter(ec -> "cargo".equals(ec.getPackageFormat()))
|
||||
.map(ExternalConnection::getExternalConnectionName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,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", "pypi", "nuget");
|
||||
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi", "nuget", "cargo");
|
||||
private static final Set<String> ORIGIN_RESTRICTION_VALUES = Set.of("ALLOW", "BLOCK");
|
||||
/**
|
||||
* Formats AWS documents as valid for {@code GetPackageVersionReadme} specifically: the
|
||||
@@ -3699,7 +3699,12 @@ public class CodeArtifactService implements Resettable {
|
||||
String format, String namespace, String packageName, String version, String repoId,
|
||||
long versionFenceSnapshot, long episodeId) {
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
if ("nuget".equals(format)) {
|
||||
// Not a nuget-specific quirk: needed by any format whose sidecar client holds a real
|
||||
// per-request container lease (beginUse/endUse actually doing something, not the no-op
|
||||
// default) that could go stale if the repository is deleted and recreated mid-write.
|
||||
// KellnrSidecarClient (cargo) delegates beginUse/endUse to a real lease exactly like
|
||||
// BagetterSidecarClient (nuget) does, so it has the identical exposure.
|
||||
if ("nuget".equals(format) || "cargo".equals(format)) {
|
||||
if (!isCurrentRepositorySidecar(owner, region, domain, repository, format, repoId)) {
|
||||
return false;
|
||||
}
|
||||
@@ -4355,7 +4360,7 @@ public class CodeArtifactService implements Resettable {
|
||||
String namespace, String packageName, List<String> versions, Map<String, String> versionRevisions,
|
||||
boolean allowOverwrite, boolean includeFromUpstream) {
|
||||
if (!"generic".equals(format) && !CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
throw validation("format must be 'generic', 'maven', 'npm', 'pypi', or 'nuget'.");
|
||||
throw validation("format must be 'generic', 'maven', 'npm', 'pypi', 'nuget', or 'cargo'.");
|
||||
}
|
||||
boolean hasVersions = versions != null && !versions.isEmpty();
|
||||
boolean hasRevisions = versionRevisions != null && !versionRevisions.isEmpty();
|
||||
@@ -6506,7 +6511,7 @@ public class CodeArtifactService implements Resettable {
|
||||
if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) {
|
||||
throw validation("namespace is required when " + action + " a " + format + " package.");
|
||||
}
|
||||
if (("pypi".equals(format) || "nuget".equals(format)) && namespace != null) {
|
||||
if (("pypi".equals(format) || "nuget".equals(format) || "cargo".equals(format)) && namespace != null) {
|
||||
throw validation(format + " packages do not have a namespace.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,13 @@ 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.
|
||||
* header, accepting every scheme a real package-manager client uses: {@code Bearer <token>}
|
||||
* directly, HTTP Basic with the token as the password field and any username, or a bare token
|
||||
* with no scheme prefix at all. AWS documents Basic for Maven's {@code settings.xml} and
|
||||
* pip/twine's {@code username=aws} convention; Bearer for npm's {@code _authToken}; and a bare
|
||||
* token for Cargo (confirmed directly from the Cargo Book's own registry-authentication page:
|
||||
* "the header value is the API token", no prefix). Accepting all three costs nothing: a real
|
||||
* client of one format never happens to send another format's own scheme.
|
||||
*
|
||||
* <p>Pulled out of {@code CodeArtifactMavenController} once {@code CodeArtifactPypiController}
|
||||
* needed the identical extraction: pip and twine authenticate exactly the way Maven's HTTP wagon
|
||||
@@ -27,9 +30,13 @@ final class 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.
|
||||
* {@code null} when the header is absent, or present but malformed (a declared Basic payload
|
||||
* that doesn't decode, or with no password field); {@link
|
||||
* CodeArtifactService#resolveAuthorizationToken} treats a null token the same as any other
|
||||
* invalid one. A header that starts with neither known scheme prefix is trusted as a bare
|
||||
* token verbatim (trimmed) rather than rejected outright: a malformed value reaching this
|
||||
* fallback is still just as safely rejected downstream, by {@code resolveAuthorizationToken}
|
||||
* failing to recognize it as a real, live-issued token.
|
||||
*/
|
||||
static String extractToken(HttpHeaders headers) {
|
||||
String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||
@@ -42,7 +49,7 @@ final class CodeArtifactTokenExtractor {
|
||||
if (authorization.startsWith(BASIC_PREFIX)) {
|
||||
return passwordFromBasicCredentials(authorization.substring(BASIC_PREFIX.length()));
|
||||
}
|
||||
return null;
|
||||
return authorization.strip();
|
||||
}
|
||||
|
||||
private static String passwordFromBasicCredentials(String base64Credentials) {
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
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.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The HTTP wire protocol for a Kellnr sidecar: Cargo's real registry API (confirmed directly
|
||||
* against a live container, not assumed from Kellnr's own thin docs site, which did not render
|
||||
* through a page fetch): the sparse HTTP index (RFC 2789), the binary publish body the Cargo
|
||||
* Book documents, and Kellnr's own admin routes for a genuine hard delete (Cargo's own protocol
|
||||
* only has "yank," which hides a version without removing it; {@code DeletePackage}/{@code
|
||||
* DeletePackageVersions} need real removal, matching AWS's own documented behavior). Container
|
||||
* lifecycle (start, readiness, stop) is {@link KellnrSidecarManager}'s job; this class asks it for
|
||||
* a ready base URL and speaks Kellnr's own protocol against it.
|
||||
*
|
||||
* <p>Unlike every other container-backed format's sidecar, Kellnr always requires a real
|
||||
* credential for publish, confirmed live: there is no "leave it fully open" switch the way
|
||||
* BaGetter's empty {@code ApiKey} provides ({@code KELLNR_REGISTRY__AUTH_REQUIRED=false}, already
|
||||
* the image's own default, only relaxes anonymous download, never publish). This class holds
|
||||
* exactly one internal credential pair per repository, minted lazily on first need and reused for
|
||||
* that repository's whole container lifetime, entirely invisible to a real CodeArtifact client
|
||||
* (whose own authorization is, and remains, enforced once at Floci's own proxy layer: this is
|
||||
* bookkeeping this client owes Kellnr, not a second authentication scheme a CodeArtifact client
|
||||
* ever sees):
|
||||
* <ul>
|
||||
* <li>An API token (minted via {@code POST /api/v1/user/add_token} under a fresh admin login),
|
||||
* cached in {@link #publishTokensByRepoId} and reused for every {@code PUT /api/v1/crates/new}
|
||||
* publish call.</li>
|
||||
* <li>A fresh admin session login per admin-route call ({@code DELETE /api/v1/ui/delete_version}/
|
||||
* {@code delete_crate}), rather than caching the session cookie: confirmed live that the API
|
||||
* token itself does not work against these admin routes (401), only the session cookie does,
|
||||
* and that cookie expires after 8 hours, so logging in fresh for each (infrequent) admin call
|
||||
* avoids expiry bookkeeping entirely rather than risk a cached cookie going stale mid-use.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code CopyPackageVersions}' own destination write ({@link #storePackageVersionAsset})
|
||||
* always publishes with an empty dependency list: extracting the real {@code [dependencies]}
|
||||
* table out of the copied {@code .crate}'s embedded {@code Cargo.toml} would need a TOML parser,
|
||||
* and this codebase has none (adding one is its own decision, not bundled into this foundational
|
||||
* sidecar work), so a copied crate's own real bytes are unaffected, but its sparse-index entry
|
||||
* under-reports its dependencies until a later pass adds that parsing. Documented here rather
|
||||
* than left silent.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KellnrSidecarClient implements RepositorySidecarManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KellnrSidecarClient.class);
|
||||
|
||||
private final KellnrSidecarManager manager;
|
||||
private final ObjectMapper mapper;
|
||||
private final HttpClient httpClient;
|
||||
// One minted API token per repository, reused for every publish for that repository's whole
|
||||
// container lifetime; cleared on release() so a later repository under the same id never
|
||||
// inherits a stale token pointing at a container that no longer exists. Also evicted and
|
||||
// reminted on a single 401 (see sendPublishWithRetry): PerKeyContainerPool.ensureReady can
|
||||
// silently restart an unhealthy container under the same repository id without telling this
|
||||
// client, which invalidates whatever token was minted under the previous container without
|
||||
// this client ever finding out from anything other than that 401 itself.
|
||||
private final ConcurrentHashMap<String, String> publishTokensByRepoId = new ConcurrentHashMap<>();
|
||||
// Shared with a future CodeArtifactCargoController's own push handler via lockFor(), the same
|
||||
// reason BagetterSidecarClient keeps one: without it, a native push and a
|
||||
// CopyPackageVersions/DeletePackage write for the same repository could interleave.
|
||||
private final ConcurrentHashMap<String, Object> repositoryLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public KellnrSidecarClient(KellnrSidecarManager manager, ObjectMapper mapper) {
|
||||
this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
}
|
||||
|
||||
KellnrSidecarClient(KellnrSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) {
|
||||
this.manager = manager;
|
||||
this.mapper = mapper;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format() {
|
||||
return "cargo";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String ensureReady(String repositoryContainerId, String publicUrl) {
|
||||
return manager.ensureReady(repositoryContainerId, publicUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(String repositoryContainerId) {
|
||||
manager.release(repositoryContainerId);
|
||||
publishTokensByRepoId.remove(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerRepository(String repositoryContainerId) {
|
||||
manager.registerRepository(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginUse(String repositoryContainerId) {
|
||||
manager.beginUse(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endUse(String repositoryContainerId) {
|
||||
manager.endUse(repositoryContainerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo packages have no namespace (AWS: "Python, NuGet, Ruby, and Cargo package versions do
|
||||
* not contain a corresponding component") and exactly one real asset per version, the
|
||||
* {@code .crate} file itself, deterministically named {@code {name}-{version}.crate} (the
|
||||
* real local-cache filename convention a real {@code cargo} client itself uses), so {@code
|
||||
* assetName} is checked against that exact value rather than fetched unconditionally, the
|
||||
* same convention {@code BagetterSidecarClient} already uses for NuGet's own one asset.
|
||||
*/
|
||||
@Override
|
||||
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
if (matchedVersion.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String expectedAssetName = packageName + "-" + matchedVersion.get() + ".crate";
|
||||
if (!expectedAssetName.equals(assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return getBytes(repositoryContainerId, downloadPath(packageName, matchedVersion.get()));
|
||||
}
|
||||
|
||||
/** {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} for why. */
|
||||
@Override
|
||||
public Optional<StreamedAsset> fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain,
|
||||
String repository, String namespace, String packageName, String version, String assetName) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
if (matchedVersion.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String expectedAssetName = packageName + "-" + matchedVersion.get() + ".crate";
|
||||
if (!expectedAssetName.equals(assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return getBytesStreamed(repositoryContainerId, downloadPath(packageName, matchedVersion.get()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every crate name this sidecar holds at least one version of, confirmed live: {@code
|
||||
* GET /api/v1/ui/crates?page=N&page_size=M} needs no credential, returns {@code {"crates":
|
||||
* [{"name":...,"version":...,...}],"page_size":M,"page":N}} with one entry per crate name
|
||||
* (its latest version only, which this bridge doesn't need), and an out-of-range page returns
|
||||
* an empty array rather than erroring, the same paginated-loop shape {@code
|
||||
* BagetterSidecarClient#listPackages} already uses for BaGetter's own search endpoint.
|
||||
*/
|
||||
@Override
|
||||
public List<PackageIdentifier> listPackages(String repositoryContainerId, String domain, String repository) {
|
||||
if (!manager.isRunning(repositoryContainerId)) {
|
||||
return List.of();
|
||||
}
|
||||
List<PackageIdentifier> result = new ArrayList<>();
|
||||
int page = 0;
|
||||
int pageSize = 100;
|
||||
while (true) {
|
||||
JsonNode response = getJson(repositoryContainerId, "/api/v1/ui/crates?page=" + page + "&page_size="
|
||||
+ pageSize).orElseThrow(() -> new IllegalStateException("Could not list packages on the Kellnr "
|
||||
+ "sidecar"));
|
||||
JsonNode crates = response.path("crates");
|
||||
if (!crates.isArray() || crates.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode entry : crates) {
|
||||
String name = entry.path("name").asText(null);
|
||||
if (name != null) {
|
||||
result.add(new PackageIdentifier(null, name));
|
||||
}
|
||||
}
|
||||
page++;
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<JsonNode> getJson(String repositoryContainerId, String encodedPath) {
|
||||
return getBytes(repositoryContainerId, encodedPath).map(bytes -> {
|
||||
try {
|
||||
return mapper.readTree(bytes);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not parse the Kellnr sidecar's own response at "
|
||||
+ encodedPath, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
return !sparseIndexEntries(repositoryContainerId, packageName).isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean packageVersionExists(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
return matchVersion(repositoryContainerId, packageName, version).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every version this sidecar holds for a package, with its publish timestamp, from the sparse
|
||||
* index's own {@code pubtime} field (confirmed live). Does not distinguish a yanked version
|
||||
* from a live one: Cargo's real registry protocol tracks "yanked" as a flag on an otherwise
|
||||
* still-present index entry, not a separate listing, and there is no yank-aware status-override
|
||||
* layer for cargo yet (see this class's own javadoc on scope).
|
||||
*/
|
||||
@Override
|
||||
public List<PackageVersionTimestamp> listPackageVersions(String repositoryContainerId, String domain,
|
||||
String repository, String namespace, String packageName) {
|
||||
List<JsonNode> entries = sparseIndexEntries(repositoryContainerId, packageName);
|
||||
List<PackageVersionTimestamp> result = new ArrayList<>();
|
||||
for (JsonNode entry : entries) {
|
||||
String version = entry.path("vers").asText(null);
|
||||
if (version == null) {
|
||||
continue;
|
||||
}
|
||||
Instant published = null;
|
||||
String publishedText = entry.path("pubtime").asText(null);
|
||||
if (publishedText != null) {
|
||||
try {
|
||||
published = Instant.parse(publishedText);
|
||||
} catch (DateTimeParseException e) {
|
||||
// Leave unmapped: CodeArtifactService falls back to a deterministic tie-break
|
||||
// rather than guessing a time from text that didn't parse.
|
||||
}
|
||||
}
|
||||
result.add(new PackageVersionTimestamp(version, published));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo's own one asset per version is deterministically named (see {@link
|
||||
* #fetchPackageVersionAsset}'s own javadoc), so enumerating it for {@code CopyPackageVersions}
|
||||
* needs only confirm the version exists and name it the same way; empty when it doesn't.
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
return matchedVersion.map(v -> List.of(packageName + "-" + v + ".crate")).orElse(List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code content} (the whole {@code .crate}, Cargo's one asset per version) through the
|
||||
* real publish wire shape confirmed live against Kellnr: a 4-byte little-endian length +
|
||||
* minimal JSON metadata (name/version from this call's own parameters, no dependency list,
|
||||
* see this class's own javadoc), then a 4-byte little-endian length + the raw {@code .crate}
|
||||
* bytes, {@code PUT} to {@code /api/v1/crates/new} with this repository's own internally-held
|
||||
* token in a bare {@code Authorization} header (no {@code Bearer} prefix, confirmed both from
|
||||
* the Cargo Book's own spec text and live against Kellnr).
|
||||
*
|
||||
* <p>Runs inside {@link #lockFor}, the same lock a future native push handler is expected to
|
||||
* share, for the same reason {@code BagetterSidecarClient} already documents for its own
|
||||
* identical lock.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
publish(repositoryContainerId, packageName, version, content);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #storePackageVersionAsset(String, String, String, String, String, String, String,
|
||||
* byte[])}'s own streamed sibling, for an asset too large to comfortably hold twice over in
|
||||
* memory (once as the raw crate, once again inside the combined publish body): the header is
|
||||
* written first and {@code content}'s own real bytes are then streamed straight through via
|
||||
* {@link #publishRawWireBody}, the same shape {@code CodeArtifactCargoExternalConnectionImporter
|
||||
* #buildStagedWireBody} already uses for a crate retained through an external connection,
|
||||
* rather than ever holding the whole crate resident the way the {@code byte[]} overload above
|
||||
* does for {@code CopyPackageVersions}' own always-small case.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, Path content,
|
||||
long contentLength) {
|
||||
byte[] metadata = minimalPublishMetadata(packageName, version);
|
||||
Path staged;
|
||||
try {
|
||||
staged = Files.createTempFile("codeartifact-cargo-copy-wire-", ".bin");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
try {
|
||||
try (OutputStream out = Files.newOutputStream(staged)) {
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(metadata.length).array());
|
||||
out.write(metadata);
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) contentLength).array());
|
||||
Files.copy(content, out);
|
||||
}
|
||||
KellnrPublishResult result;
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
result = publishRawWireBody(repositoryContainerId, staged, Files.size(staged));
|
||||
}
|
||||
if (result.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not publish " + packageName + " " + version + " to the "
|
||||
+ "Kellnr sidecar: upstream returned " + result.statusCode());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(staged);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Kellnr copy wire-body file at {0}", staged);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publish(String repositoryContainerId, String packageName, String version, byte[] crateBytes) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
byte[] metadata = minimalPublishMetadata(packageName, version);
|
||||
byte[] body = publishWireBody(metadata, crateBytes);
|
||||
HttpResponse<String> response = sendPublishWithRetry(repositoryContainerId, baseUrl, token ->
|
||||
HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/api/v1/crates/new"))
|
||||
.timeout(SidecarUriUtils.transferTimeout(body.length))
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", token)
|
||||
.PUT(BodyPublishers.ofByteArray(body))
|
||||
.build());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not publish " + packageName + " " + version + " to the Kellnr "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forwards a real {@code cargo publish}'s own already-correctly-shaped wire body (streamed
|
||||
* from disk, since a {@code .crate} can be large) to {@code PUT /api/v1/crates/new} verbatim,
|
||||
* using this repository's own internally-held token. Deliberately separate from {@link
|
||||
* #storePackageVersionAsset}, which builds its own minimal, dependency-free metadata for
|
||||
* {@code CopyPackageVersions}' sake (see this class's own javadoc): a native publish's own
|
||||
* metadata, built by the real client itself, already carries the package's real dependency
|
||||
* list, which must survive untouched, not be discarded and resynthesized.
|
||||
*
|
||||
* <p>Returns Kellnr's own status and body rather than throwing on a non-200: confirmed live
|
||||
* that Kellnr genuinely rejects a republish of an already-existing name/version with a 400 and
|
||||
* a body already shaped exactly like the Cargo Book's own documented error response ({@code
|
||||
* {"errors":[{"detail":"..."}]}}), matching the Cargo Book's own documented rule that "a
|
||||
* publish is generally permanent" and a version "can never be overwritten". That is a real
|
||||
* answer a real {@code cargo} client understands, not an internal failure to swallow into an
|
||||
* opaque 500; the caller forwards it to the client verbatim.
|
||||
*
|
||||
* <p>Not part of {@link RepositorySidecarManager}: this is Cargo's own native-publish bridge,
|
||||
* called directly by {@code CodeArtifactCargoController}, the same way {@code
|
||||
* BagetterSidecarClient#lockFor} is reused directly by {@code CodeArtifactNuGetController}
|
||||
* without going through the shared interface either.
|
||||
*/
|
||||
record KellnrPublishResult(int statusCode, String body) {
|
||||
}
|
||||
|
||||
KellnrPublishResult publishRawWireBody(String repositoryContainerId, Path stagedWireBody, long contentLength) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpResponse<String> response = sendPublishWithRetry(repositoryContainerId, baseUrl, token -> {
|
||||
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(SidecarUriUtils.combine(
|
||||
URI.create(baseUrl), "/api/v1/crates/new"))
|
||||
.timeout(SidecarUriUtils.transferTimeout(contentLength))
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", token);
|
||||
try {
|
||||
requestBuilder.PUT(BodyPublishers.ofFile(stagedWireBody));
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return requestBuilder.build();
|
||||
});
|
||||
return new KellnrPublishResult(response.statusCode(), response.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a publish request built from whichever token is current, and, only on a {@code 401},
|
||||
* evicts that cached token, mints a fresh one, and retries exactly once: this is how a
|
||||
* container silently restarted under this repository's own id by {@code PerKeyContainerPool
|
||||
* #ensureReady} (see {@link #publishTokensByRepoId}'s own javadoc) heals on its very next
|
||||
* publish attempt instead of 401ing every one of them until Floci itself restarts. {@code
|
||||
* requestForToken} is called again for the retry, so it must build a genuinely fresh {@link
|
||||
* HttpRequest} each time rather than reuse one (an {@link HttpRequest} already carries its own
|
||||
* immutable headers, the stale {@code Authorization} included).
|
||||
*/
|
||||
private HttpResponse<String> sendPublishWithRetry(String repositoryContainerId, String baseUrl,
|
||||
Function<String, HttpRequest> requestForToken) {
|
||||
String token = publishToken(repositoryContainerId, baseUrl);
|
||||
HttpResponse<String> response = sendHttp(requestForToken.apply(token));
|
||||
if (response.statusCode() == 401) {
|
||||
publishTokensByRepoId.remove(repositoryContainerId, token);
|
||||
String freshToken = publishToken(repositoryContainerId, baseUrl);
|
||||
response = sendHttp(requestForToken.apply(freshToken));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private HttpResponse<String> sendHttp(HttpRequest request) {
|
||||
try {
|
||||
return httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to publish this crate", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes every version of the named package via Kellnr's own admin route, confirmed live: a
|
||||
* genuine hard delete, not Cargo's own protocol-level "yank". Runs inside {@link #lockFor},
|
||||
* the same lock {@link #storePackageVersionAsset} and a future native push handler share.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
String query = "name=" + SidecarUriUtils.encodeSegment(packageName);
|
||||
adminDelete(baseUrl, "/api/v1/ui/delete_crate?" + query, cookie, packageName, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the one version this asset belongs to, via the same admin route family as {@link
|
||||
* #deletePackage}: Cargo has exactly one asset per version, so there is no finer grain to
|
||||
* delete at. Runs inside the same {@link #lockFor} lock {@link #storePackageVersionAsset} and
|
||||
* {@link #deletePackage} both take, for the same reason.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
String query = "name=" + SidecarUriUtils.encodeSegment(packageName) + "&version="
|
||||
+ SidecarUriUtils.encodeSegment(version);
|
||||
adminDelete(baseUrl, "/api/v1/ui/delete_version?" + query, cookie, packageName, version);
|
||||
}
|
||||
}
|
||||
|
||||
private void adminDelete(String baseUrl, String pathAndQuery, String cookie, String packageName,
|
||||
String version) {
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), pathAndQuery))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Cookie", cookie)
|
||||
.DELETE()
|
||||
.build();
|
||||
HttpResponse<Void> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to delete " + packageName
|
||||
+ (version == null ? "" : " " + version), e);
|
||||
}
|
||||
// 404 means this exact coordinate is already gone, the same tolerance
|
||||
// BagetterSidecarClient's own delete calls already apply.
|
||||
if (response.statusCode() != 200 && response.statusCode() != 404) {
|
||||
throw new IllegalStateException("Could not delete " + packageName + (version == null ? "" : " "
|
||||
+ version) + " from the Kellnr sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock a future native push handler and this client's own write/delete methods all share
|
||||
* for one repository, so neither can interleave with the other. Package-private so a future
|
||||
* {@code CodeArtifactCargoController} can synchronize its own push-or-conflict check and
|
||||
* forwarded write on the exact same lock, the only way either one closes the race against the
|
||||
* other, the same reason {@code BagetterSidecarClient#lockFor} is package-private.
|
||||
*/
|
||||
Object lockFor(String repositoryContainerId) {
|
||||
return repositoryLocks.computeIfAbsent(repositoryContainerId, k -> new Object());
|
||||
}
|
||||
|
||||
/**
|
||||
* The minimal metadata shape confirmed live to be accepted by Kellnr's real publish endpoint:
|
||||
* every optional field explicitly {@code null}/empty rather than omitted, matching the shape
|
||||
* this class's own hands-on verification used. {@code deps}/{@code features} are always empty
|
||||
* (see this class's own javadoc on why); {@code license} is a fixed placeholder since real
|
||||
* CodeArtifact has no license field of its own to source this from for a sidecar-level copy.
|
||||
*/
|
||||
private byte[] minimalPublishMetadata(String packageName, String version) {
|
||||
ObjectNode metadata = mapper.createObjectNode();
|
||||
metadata.put("name", packageName);
|
||||
metadata.put("vers", version);
|
||||
metadata.putArray("deps");
|
||||
metadata.putObject("features");
|
||||
metadata.putArray("authors");
|
||||
metadata.put("description", (String) null);
|
||||
metadata.put("documentation", (String) null);
|
||||
metadata.put("homepage", (String) null);
|
||||
metadata.put("readme", (String) null);
|
||||
metadata.put("readme_file", (String) null);
|
||||
metadata.putArray("keywords");
|
||||
metadata.putArray("categories");
|
||||
metadata.put("license", (String) null);
|
||||
metadata.put("license_file", (String) null);
|
||||
metadata.put("repository", (String) null);
|
||||
metadata.putObject("badges");
|
||||
metadata.put("links", (String) null);
|
||||
return metadata.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real Cargo publish wire body, confirmed directly from the Cargo Book's own spec text and
|
||||
* live against Kellnr: a 4-byte little-endian length-prefixed JSON metadata object, followed
|
||||
* by a 4-byte little-endian length-prefixed {@code .crate} tarball.
|
||||
*/
|
||||
private static byte[] publishWireBody(byte[] metadataJson, byte[] crateBytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadataJson.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadataJson.length);
|
||||
buffer.put(metadataJson);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private String publishToken(String repositoryContainerId, String baseUrl) {
|
||||
return publishTokensByRepoId.computeIfAbsent(repositoryContainerId,
|
||||
id -> mintPublishToken(repositoryContainerId, baseUrl));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints one fresh API token under a fresh admin login, confirmed live: {@code
|
||||
* POST /api/v1/user/add_token} with the admin session cookie returns {@code
|
||||
* {"name":...,"token":"..."}}. The token itself never expires on its own in Kellnr's own model
|
||||
* (confirmed live across repeated use within this session); the admin session cookie that
|
||||
* mints it does, which is exactly why this is minted once and cached rather than re-derived
|
||||
* from a cached cookie later.
|
||||
*/
|
||||
private String mintPublishToken(String repositoryContainerId, String baseUrl) {
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
byte[] body = "{\"name\":\"floci\"}".getBytes(StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
"/api/v1/user/add_token"))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Cookie", cookie)
|
||||
.POST(BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to mint a publish token", e);
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not mint a Kellnr publish token: upstream returned "
|
||||
+ response.statusCode());
|
||||
}
|
||||
try {
|
||||
return mapper.readTree(response.body()).path("token").asText();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse Kellnr's token-mint response", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs in as Kellnr's own {@code admin} account, confirmed live: {@code POST
|
||||
* /api/v1/user/login} with {@code {"user":"admin","pwd":"<this repository's own random
|
||||
* password>"}} returns a {@code kellnr_session_id} session cookie. The password itself comes
|
||||
* from {@link KellnrSidecarManager#adminPassword}, read fresh on every call rather than
|
||||
* cached, not Kellnr's own shipped {@code admin}/{@code admin} default (see that manager's
|
||||
* own javadoc for why). This admin account is purely internal to this sidecar container
|
||||
* (loopback-bound, never reachable except through Floci itself), the same trust boundary
|
||||
* every other container-backed format's own sidecar already relies on.
|
||||
*/
|
||||
private String adminLogin(String repositoryContainerId, String baseUrl) {
|
||||
ObjectNode credentials = mapper.createObjectNode();
|
||||
credentials.put("user", "admin");
|
||||
credentials.put("pwd", manager.adminPassword(repositoryContainerId));
|
||||
byte[] body = credentials.toString().getBytes(StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
"/api/v1/user/login"))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to log in as its admin", e);
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not log in to the Kellnr sidecar as its admin: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
return response.headers().firstValue("set-cookie")
|
||||
.map(raw -> raw.split(";", 2)[0])
|
||||
.orElseThrow(() -> new IllegalStateException("Kellnr sidecar login did not return a session "
|
||||
+ "cookie"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code empty()} when {@code version} doesn't match any version Kellnr actually holds for
|
||||
* this package, the matching sparse-index entry's own {@code vers} text otherwise. Cargo
|
||||
* version strings have no leading/trailing-zero aliasing the way NuGet's do (AWS documents no
|
||||
* such normalization for Cargo), so this is a plain exact-string match against the index,
|
||||
* unlike {@code BagetterSidecarClient#matchVersion}'s own normalized comparison.
|
||||
*/
|
||||
private Optional<String> matchVersion(String repositoryContainerId, String packageName, String version) {
|
||||
for (JsonNode entry : sparseIndexEntries(repositoryContainerId, packageName)) {
|
||||
String candidate = entry.path("vers").asText(null);
|
||||
if (version.equals(candidate)) {
|
||||
return Optional.of(candidate);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The real, complete sparse-index bytes for one crate, verbatim (confirmed live:
|
||||
* newline-delimited JSON, one object per version, each carrying its own real {@code deps}/
|
||||
* {@code cksum}/{@code features}, not just what {@link #listPackageVersions}' own abstracted
|
||||
* {@code PackageVersionTimestamp} carries). For {@code CodeArtifactCargoController} to serve
|
||||
* close to verbatim: a real {@code cargo} client needs those fields to resolve dependencies
|
||||
* and verify a download's integrity, information none of this interface's own generic bridge
|
||||
* methods carry. Empty, not an error, when the package was never published or this
|
||||
* repository's sidecar was never started.
|
||||
*/
|
||||
Optional<byte[]> fetchSparseIndexRaw(String repositoryContainerId, String domain, String repository,
|
||||
String packageName) {
|
||||
return getBytes(repositoryContainerId, sparseIndexPath(packageName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every line of this package's own sparse-index file, each one JSON describing one published
|
||||
* version (confirmed live: newline-delimited JSON, one object per version). Empty, not an
|
||||
* error, when the package was never published or this repository's sidecar was never started.
|
||||
*/
|
||||
private List<JsonNode> sparseIndexEntries(String repositoryContainerId, String packageName) {
|
||||
Optional<byte[]> raw = getBytes(repositoryContainerId, sparseIndexPath(packageName));
|
||||
if (raw.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<JsonNode> entries = new ArrayList<>();
|
||||
for (String line : new String(raw.get(), StandardCharsets.UTF_8).split("\n")) {
|
||||
String trimmed = line.strip();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
entries.add(mapper.readTree(trimmed));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse the Kellnr sidecar's sparse-index entry for "
|
||||
+ packageName, e);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kellnr's own bucketed index path, the real crates.io bucketing rule (see {@link
|
||||
* SidecarUriUtils#cratesIoBucketPath}, shared with {@code CargoExternalConnectionClient} so
|
||||
* the rule is written once) under Kellnr's own {@code /api/v1/crates/} prefix.
|
||||
*/
|
||||
private static String sparseIndexPath(String packageName) {
|
||||
return "/api/v1/crates/" + SidecarUriUtils.cratesIoBucketPath(packageName);
|
||||
}
|
||||
|
||||
private static String downloadPath(String packageName, String version) {
|
||||
return "/api/v1/crates/dl/" + SidecarUriUtils.encodeSegment(packageName) + "/"
|
||||
+ SidecarUriUtils.encodeSegment(version) + "/download";
|
||||
}
|
||||
|
||||
private Optional<byte[]> getBytes(String repositoryContainerId, String encodedPath) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath))
|
||||
.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 Kellnr sidecar at " + encodedPath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not fetch " + encodedPath + " from the Kellnr sidecar: upstream "
|
||||
+ "returned " + response.statusCode());
|
||||
}
|
||||
return Optional.of(response.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #getBytes}'s streamed sibling, for the one asset download that can be large: a flat
|
||||
* 10-second timeout, fine for {@link #getBytes}'s own small-metadata callers, would cancel a
|
||||
* legitimately large, still-in-progress download here, the same gap every other container-
|
||||
* backed sidecar client's own streamed fetch already closes.
|
||||
*/
|
||||
private Optional<StreamedAsset> getBytesStreamed(String repositoryContainerId, String encodedPath) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath))
|
||||
.timeout(SidecarUriUtils.maxTransferTimeout()).GET().build();
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar at " + encodedPath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
throw new IllegalStateException("Could not fetch " + encodedPath + " from the Kellnr sidecar: upstream "
|
||||
+ "returned " + response.statusCode());
|
||||
}
|
||||
long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1);
|
||||
return Optional.of(new StreamedAsset(response.body(), contentLength));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Starts and stops one Kellnr container per CodeArtifact repository backing the {@code cargo}
|
||||
* format, the same per-repository shape as Verdaccio (npm), pypiserver (pypi), and BaGetter
|
||||
* (nuget) rather than Reposilite's one shared instance. The HTTP protocol lives in {@link
|
||||
* KellnrSidecarClient}. Implements {@link ContainerTeardown} so reset, nuke, and shutdown stop
|
||||
* every container this manager started.
|
||||
*
|
||||
* <p>Unlike BaGetter, Kellnr has no "leave it fully open" configuration: confirmed directly
|
||||
* against a live container, {@code KELLNR_REGISTRY__AUTH_REQUIRED=false} (already the image's own
|
||||
* documented default) only relaxes anonymous download, never publish, which 401s without a valid
|
||||
* token regardless of that setting. So this container is left at its real default auth posture,
|
||||
* and {@link KellnrSidecarClient} itself holds the one internal admin credential every publish
|
||||
* needs (see its own javadoc); real CodeArtifact authorization still happens exactly once, at
|
||||
* Floci's own proxy layer, before a request ever reaches this container, the same reasoning every
|
||||
* other container-backed format's own manager already documents.
|
||||
*
|
||||
* <p>The admin account's own password is a fresh, random value minted per container at creation
|
||||
* (via {@code KELLNR_SETUP__ADMIN_PWD}, confirmed live to override Kellnr's own shipped
|
||||
* {@code admin}/{@code admin} default), not the shipped default itself: every Kellnr image shares
|
||||
* that same default, so anything else already able to reach this container on the configured
|
||||
* Docker network (the same cross-container reachability every sidecar-backed format's own manager
|
||||
* documents, see {@code docs/services/codeartifact.md}) could otherwise log in as this container's
|
||||
* own admin using nothing but public knowledge of Kellnr's defaults, without ever needing the
|
||||
* internal token {@link KellnrSidecarClient} mints under it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KellnrSidecarManager implements ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KellnrSidecarManager.class);
|
||||
// Kellnr's own shipped default (confirmed directly against a live container: it listens on
|
||||
// 8000 with no port configuration set at all).
|
||||
private static final int KELLNR_PORT = 8000;
|
||||
// Kellnr's static SPA shell answers 200 on "/" even before its backend API is actually ready
|
||||
// to serve requests, so it is not a safe readiness signal; this config endpoint only answers
|
||||
// once the real API is up, confirmed live.
|
||||
private static final String HEALTH_PATH = "/api/v1/crates/config.json";
|
||||
private static final SecureRandom ADMIN_PASSWORD_RANDOM = new SecureRandom();
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
// One random admin password per repository's own container, regenerated every time
|
||||
// startContainer() runs for that key (including an internal pool restart of an unhealthy
|
||||
// container under the same key): KellnrSidecarClient reads this fresh on every admin login
|
||||
// rather than caching it, so it always matches whichever container is actually running now.
|
||||
private final ConcurrentHashMap<String, String> adminPasswords = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public KellnrSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("Kellnr", pool);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base URL of a ready Kellnr instance for this cargo repository, starting its container if
|
||||
* this is the first use. {@code publicUrl} is unused: Kellnr's own self-reported {@code
|
||||
* config.json} (and anything else that could embed a self-referential URL) is never proxied
|
||||
* verbatim by a future controller, which is expected to author that response itself, the same
|
||||
* way {@code CodeArtifactNuGetController} already authors its own service index rather than
|
||||
* proxying BaGetter's.
|
||||
*/
|
||||
public String ensureReady(String cargoRepositoryId, String publicUrl) {
|
||||
return pool.ensureReady(cargoRepositoryId, () -> startContainer(cargoRepositoryId));
|
||||
}
|
||||
|
||||
/** Stops and removes the container for one cargo repository, if one was ever started. */
|
||||
public void release(String cargoRepositoryId) {
|
||||
lease.release(cargoRepositoryId);
|
||||
adminPasswords.remove(cargoRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* This cargo repository's own container's current admin password, read fresh on every call
|
||||
* (never cached by the caller) so it always matches whichever container is actually running,
|
||||
* including one silently restarted under the same key by {@link PerKeyContainerPool
|
||||
* #ensureReady}. Only meaningful after {@link #ensureReady} has started this repository's
|
||||
* container at least once.
|
||||
*/
|
||||
String adminPassword(String cargoRepositoryId) {
|
||||
String password = adminPasswords.get(cargoRepositoryId);
|
||||
if (password == null) {
|
||||
throw new IllegalStateException("No Kellnr admin password minted yet for cargo repository "
|
||||
+ cargoRepositoryId);
|
||||
}
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a test that seeds a container directly into the pool without going through this class's
|
||||
* own {@link #ensureReady}/{@link #startContainer}: those real paths always mint and store a
|
||||
* password themselves, so a test standing in for them needs its own way to make one visible to
|
||||
* {@link #adminPassword} too, without reaching for reflection the way its own seeding of
|
||||
* {@code pool}'s containers map already does for that unrelated, pre-existing convention.
|
||||
*/
|
||||
void seedAdminPasswordForTest(String cargoRepositoryId, String password) {
|
||||
adminPasswords.put(cargoRepositoryId, password);
|
||||
}
|
||||
|
||||
public void registerRepository(String cargoRepositoryId) {
|
||||
lease.registerRepository(cargoRepositoryId);
|
||||
}
|
||||
|
||||
public void beginUse(String cargoRepositoryId) {
|
||||
lease.beginUse(cargoRepositoryId);
|
||||
}
|
||||
|
||||
public void endUse(String cargoRepositoryId) {
|
||||
lease.endUse(cargoRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this cargo repository's own Kellnr container is already running, without starting
|
||||
* one for a repository that has never used cargo at all. Every CodeArtifact repository gets a
|
||||
* cargo sidecar id at creation regardless of whether it is ever actually used through cargo,
|
||||
* so a caller that only wants to ask an already-running container what it holds must check
|
||||
* this first rather than provision a brand-new container just to find it has nothing, the same
|
||||
* reasoning {@code BagetterSidecarManager#isRunning} already documents.
|
||||
*/
|
||||
public boolean isRunning(String cargoRepositoryId) {
|
||||
return pool.isTracked(cargoRepositoryId);
|
||||
}
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String cargoRepositoryId) {
|
||||
String image = config.services().codeartifact().cargoImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-kellnr-" + cargoRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
// Set before the container is created, not after: KellnrSidecarClient's own adminLogin
|
||||
// reads this map directly, so the new password must already be visible to it the moment
|
||||
// this container could first be reached, never a window where the map still holds a
|
||||
// previous container's own now-wrong password.
|
||||
String adminPassword = generateAdminPassword();
|
||||
adminPasswords.put(cargoRepositoryId, adminPassword);
|
||||
|
||||
// Loopback-only: nothing inside this container should ever be reachable except through
|
||||
// Floci's own proxy layer, the same reasoning Verdaccio/pypiserver/BaGetter's own managers
|
||||
// already document. KELLNR_ORIGIN__HOSTNAME is required for Kellnr's own self-reported
|
||||
// base URLs (confirmed live); storage is left at the image's own SQLite/local-filesystem
|
||||
// default, matching every other sidecar's own "keep it simple, ephemeral" choice.
|
||||
// KELLNR_SETUP__ADMIN_PWD overrides Kellnr's own shipped admin/admin default (confirmed
|
||||
// live), see this class's own javadoc for why that default is never left in place.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("KELLNR_ORIGIN__HOSTNAME", "localhost")
|
||||
.withEnv("KELLNR_SETUP__ADMIN_PWD", adminPassword)
|
||||
.withLoopbackPortBinding(KELLNR_PORT, 0)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
try {
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(KELLNR_PORT);
|
||||
String url = "http://" + endpoint;
|
||||
LOG.infov("Kellnr sidecar for cargo repository {0} is ready at {1}", cargoRepositoryId, url);
|
||||
return new PerKeyContainerPool.StartedContainer(containerId, url);
|
||||
} catch (RuntimeException e) {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A fresh 256-bit random value, hex-encoded so it is always safe as a Kellnr config env var
|
||||
* and a JSON login body's own string value with no escaping concerns either way. */
|
||||
private static String generateAdminPassword() {
|
||||
byte[] bytes = new byte[32];
|
||||
ADMIN_PASSWORD_RANDOM.nextBytes(bytes);
|
||||
StringBuilder hex = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
hex.append(String.format("%02x", b));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopManagedContainers() {
|
||||
lease.stopManagedContainers();
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,17 @@ import io.floci.aws.core.common.auth.SigV4Canonicalization;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Shared helpers for the Maven, npm, pypi, and NuGet sidecar clients: URI construction out of
|
||||
* each one's own {@code baseUrl} plus one or more caller-supplied path segments (a repository
|
||||
* id, package coordinates, an asset filename), and a request timeout sized for forwarding a
|
||||
* large asset's real bytes rather than a small metadata-only request. Package-private: every
|
||||
* caller lives in this package, and {@link #combine} in particular requires its {@code
|
||||
* encodedPath} argument to already be fully percent-encoded, a precondition not worth exposing
|
||||
* to unrelated callers outside the four clients that know to uphold it.
|
||||
* Shared helpers for the Maven, npm, pypi, NuGet, and Kellnr (Cargo) sidecar clients, and their
|
||||
* external-connection siblings: URI construction out of each one's own {@code baseUrl} plus one
|
||||
* or more caller-supplied path segments (a repository id, package coordinates, an asset
|
||||
* filename), and a request timeout sized for forwarding a large asset's real bytes rather than a
|
||||
* small metadata-only request. Package-private: every caller lives in this package, and {@link
|
||||
* #combine} in particular requires its {@code encodedPath} argument to already be fully
|
||||
* percent-encoded, a precondition not worth exposing to unrelated callers outside the clients
|
||||
* that know to uphold it.
|
||||
*/
|
||||
final class SidecarUriUtils {
|
||||
|
||||
@@ -93,4 +95,33 @@ final class SidecarUriUtils {
|
||||
static Duration maxTransferTimeout() {
|
||||
return transferTimeout(CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real crates.io sparse-index bucketing rule (RFC 2789), confirmed live against both
|
||||
* Kellnr and the real {@code index.crates.io} (a 1 or 2 character name sits directly under a
|
||||
* {@code 1}/{@code 2} directory, a 3 character name adds one more level keyed by its own
|
||||
* first character, and a 4+ character name buckets by its own first two, then next two,
|
||||
* characters), with no leading slash and no host-specific prefix: {@link KellnrSidecarClient}
|
||||
* prepends its own {@code /api/v1/crates/}, {@code CargoExternalConnectionClient} prepends
|
||||
* nothing (the real {@code index.crates.io} serves bucket paths straight off its own root).
|
||||
* Lowercased: the Cargo Book's own registry-index page is explicit that both the bucket
|
||||
* directory names and the index filename itself are the package name "converted to
|
||||
* lowercase," confirmed live against the real production index (a mixed-case crate like
|
||||
* {@code Inflector} 404s at {@code In/fl/Inflector} and only resolves at {@code in/fl/
|
||||
* inflector}; the returned index line's own {@code name} field still preserves the original
|
||||
* case). The {@code packageName} value itself, as used for anything other than this one path,
|
||||
* keeps its original casing.
|
||||
*/
|
||||
static String cratesIoBucketPath(String packageName) {
|
||||
String lower = packageName.toLowerCase(Locale.ROOT);
|
||||
String encoded = encodeSegment(lower);
|
||||
int length = lower.length();
|
||||
if (length <= 2) {
|
||||
return length + "/" + encoded;
|
||||
}
|
||||
if (length == 3) {
|
||||
return "3/" + encodeSegment(lower.substring(0, 1)) + "/" + encoded;
|
||||
}
|
||||
return encodeSegment(lower.substring(0, 2)) + "/" + encodeSegment(lower.substring(2, 4)) + "/" + encoded;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user