feat(codeartifact): add NuGet/BaGetter sidecar for the nuget format (#5790)

Bridges the nuget package format to a real per-repository BaGetter
container, the same Manager/Client sidecar shape already established for
Maven (Reposilite), npm (Verdaccio), and pypi (pypiserver): a real NuGet V3
push/install round trip through CodeArtifactNuGetController, GetPackageVersionAsset
and GetPackageVersionReadme bridged to the live sidecar, and DeletePackage wired
through the same CONTAINER_BACKED_FORMATS dispatch the other three formats use.

GetPackageVersionReadme is answered live against BaGetter (its own readme-file
and nuspec-description endpoints) rather than captured at publish time, since
unlike Verdaccio and pypiserver, BaGetter can answer for a specific historical
version after the fact.

Pins bagetter/bagetter, the actively maintained fork of the original,
long-stale loic-sharma/BaGet (no commits since mid-2024, every one of its own
releases tagged -preview/-prerelease), confirmed directly against a live
container for push/download/readme/delete semantics before relying on them.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-16 18:19:33 -05:00
1 parent feafbfe083
commit 3db18d58a5
17 files changed
+2180 -87

No files matched your search

@@ -887,6 +887,15 @@ public interface EmulatorConfig {
*/
@WithDefault("pypiserver/pypiserver:v2.4.2")
String pypiImage();
/**
* Image used for the per-repository BaGetter container backing the {@code nuget} format.
* Same reasoning as {@link #npmImage()}: BaGetter has no native concept of multiple named
* feeds 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("bagetter/bagetter:1.6.5")
String nugetImage();
}
interface ConnectServiceConfig {
@@ -11,8 +11,9 @@ import java.util.concurrent.atomic.AtomicLong;
* that lifecycle logic (map of running containers, per-key start lock so concurrent first-use of
* two different keys never blocks on each other, health poll, restart-on-unhealthy, stop-all on
* shutdown) has nothing Verdaccio-specific in it; only how to actually build and start a container
* for a given key does. A future per-repository sidecar (pypiserver, BaGet) can reuse this
* directly instead of re-deriving the same map/lock/poll skeleton.
* for a given key does. {@code PypiserverSidecarManager} and {@code BagetterSidecarManager}
* already reuse this directly instead of re-deriving the same map/lock/poll skeleton; a future
* per-repository sidecar for a new format can do the same.
*
* <p>Callers own the health-check path and the actual container creation (image, config, env),
* supplied per call since those are exactly the format-specific parts.
@@ -0,0 +1,276 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
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.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* The HTTP wire protocol for a BaGetter sidecar: the NuGet V3 Package Content resource (flat
* container) and the V2-shaped publish resource BaGetter's push/delete endpoints still use.
* Container lifecycle (start, readiness, stop) is {@link BagetterSidecarManager}'s job; this class
* asks it for a ready base URL and speaks BaGetter's own protocol against it.
*
* <p>Deliberately does not implement the NuGet V3 Registration or Search resources:
* {@code nuget install}/{@code dotnet add package} both resolve a package's versions and
* dependencies from the Package Content resource alone (confirmed directly: NuGet's own V3
* client falls back to the flat container's {@code index.json} plus each version's {@code
* .nuspec} when a source advertises no {@code RegistrationsBaseUrl} resource), and AWS's own
* CodeArtifact User Guide documents {@code nuget list} itself as unsupported against CodeArtifact
* regardless (only V3 of the protocol works at all), which is exactly what Search would back.
* {@code CodeArtifactNuGetController} authors its own service index rather than proxying BaGetter's,
* so this never needs to rewrite a self-referential URL out of a BaGetter response the way
* {@code PypiserverSidecarClient} rewrites pypiserver's simple-index HTML.
*/
@ApplicationScoped
public class BagetterSidecarClient implements RepositorySidecarManager {
private final BagetterSidecarManager manager;
private final ObjectMapper mapper;
private final HttpClient httpClient;
// Shared with CodeArtifactNuGetController's own push handler via lockFor(), keyed by
// repository container id: without one lock both paths take, a native push that lists a
// not-yet-deleted version and a DeletePackage's own version-list snapshot can interleave,
// letting a version pushed in that window survive a DeletePackage that already "succeeded".
private final ConcurrentHashMap<String, Object> repositoryLocks = new ConcurrentHashMap<>();
@Inject
public BagetterSidecarClient(BagetterSidecarManager manager, ObjectMapper mapper) {
this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
BagetterSidecarClient(BagetterSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) {
this.manager = manager;
this.mapper = mapper;
this.httpClient = httpClient;
}
@Override
public String format() {
return "nuget";
}
@Override
public String ensureReady(String repositoryContainerId, String publicUrl) {
return manager.ensureReady(repositoryContainerId, publicUrl);
}
@Override
public void release(String repositoryContainerId) {
manager.release(repositoryContainerId);
}
/**
* NuGet 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 .nupkg} file itself; AWS's own NuGet asset-name-normalization doc says this name is
* constructed from the normalized package name and version, so {@code assetName} is checked
* against that exact, deterministic value rather than fetched unconditionally: a caller asking
* for any other name is asking for an asset that was never, and could never be, published.
*/
@Override
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version, String assetName) {
String lowerId = packageName.toLowerCase(Locale.ROOT);
Optional<String> normalizedVersion = matchVersion(repositoryContainerId, lowerId, version);
if (normalizedVersion.isEmpty()) {
return Optional.empty();
}
String expectedAssetName = lowerId + "." + normalizedVersion.get() + ".nupkg";
if (!expectedAssetName.equals(assetName)) {
return Optional.empty();
}
return getBytes(repositoryContainerId, "/v3/package/" + SidecarUriUtils.encodeSegment(lowerId) + "/"
+ SidecarUriUtils.encodeSegment(normalizedVersion.get()) + "/"
+ SidecarUriUtils.encodeSegment(expectedAssetName));
}
@Override
public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
String packageName) {
return !listVersions(repositoryContainerId, packageName.toLowerCase(Locale.ROOT)).isEmpty();
}
/**
* Bridges {@code DescribePackageVersion}: reuses {@link #matchVersion}, the same normalized
* lookup {@link #fetchPackageVersionAsset} and {@link #fetchPackageVersionReadme} already use
* against BaGetter's own flat container listing, so a caller-supplied version in any form
* BaGetter itself would accept (leading zeroes, a trailing zero fourth segment, build
* metadata) resolves the same way here as it does for those two.
*/
@Override
public boolean packageVersionExists(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version) {
return matchVersion(repositoryContainerId, packageName.toLowerCase(Locale.ROOT), version).isPresent();
}
/**
* Deletes every version of the named package, confirmed against a live container.
*
* <p>Runs inside {@link #lockFor}: without it, a native push that lists the (not yet
* updated) version set after this method's own {@link #listVersions} snapshot, but finishes
* before this method's delete loop does, would add a version this call never knew to delete,
* leaving it behind even though {@code DeletePackage} already reported success.
*/
@Override
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
String packageName) {
synchronized (lockFor(repositoryContainerId)) {
String lowerId = packageName.toLowerCase(Locale.ROOT);
String baseUrl = ensureReady(repositoryContainerId, null);
for (String version : listVersions(repositoryContainerId, lowerId)) {
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/api/v2/package/"
+ SidecarUriUtils.encodeSegment(lowerId) + "/" + SidecarUriUtils.encodeSegment(version));
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).DELETE().build();
HttpResponse<Void> response;
try {
response = httpClient.send(request, BodyHandlers.discarding());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the BaGetter sidecar to delete " + packageName
+ " " + version, e);
}
// 404 means this exact version is already gone: a sibling file deleted in an
// earlier iteration can't cause this (NuGet has one asset per version, unlike
// pypi), and a concurrent delete of the same package can't either now that both
// paths share this lock.
if (response.statusCode() != 204 && response.statusCode() != 404) {
throw new IllegalStateException("Could not delete " + packageName + " " + version + " from the "
+ "BaGetter sidecar: upstream returned " + response.statusCode());
}
}
}
}
/**
* The lock {@link #deletePackage} and {@code CodeArtifactNuGetController}'s own push handler
* both take for one repository, so a push and a delete for the same repository can never
* interleave; different repositories never block each other. Package-private so the
* controller can synchronize its own push-or-conflict check and forwarded write on the exact
* same lock this method does, the only way either one closes the race against the other.
*/
Object lockFor(String repositoryContainerId) {
return repositoryLocks.computeIfAbsent(repositoryContainerId, k -> new Object());
}
/**
* {@code empty()} only when {@code version} genuinely was never published; a published version
* with no readme file embedded answers {@code Optional.of("")} rather than {@code empty()}, the
* same empty-string parity already established for npm and pypi (a version republished without
* a readme records nothing to look up otherwise, which would 404 a version that genuinely
* exists). Unlike npm and pypi, this is answered live against the sidecar rather than from a
* record captured at publish time: BaGetter, unlike Verdaccio and pypiserver, keeps every
* version's own readme (if the nuspec declared one via {@code <readme>}) addressable by exact
* version for as long as that version exists, confirmed directly against BaGetter's own package
* content controller, so there is nothing to lose by not capturing it eagerly.
*
* <p>Falls back to the nuspec {@code <description>} element, a mandatory field in every valid
* nuspec, when the version exists but embeds no separate readme file: AWS documents this
* action as returning "the readme file or descriptive text for a package version", exactly
* this two-tier fallback.
*/
@Override
public Optional<String> fetchPackageVersionReadme(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version) {
String lowerId = packageName.toLowerCase(Locale.ROOT);
Optional<String> normalizedVersion = matchVersion(repositoryContainerId, lowerId, version);
if (normalizedVersion.isEmpty()) {
return Optional.empty();
}
Optional<byte[]> readme = getBytes(repositoryContainerId, "/v3/package/"
+ SidecarUriUtils.encodeSegment(lowerId) + "/" + SidecarUriUtils.encodeSegment(normalizedVersion.get())
+ "/readme");
if (readme.isPresent()) {
return Optional.of(new String(readme.get(), StandardCharsets.UTF_8));
}
Optional<byte[]> nuspec = getBytes(repositoryContainerId, "/v3/package/"
+ SidecarUriUtils.encodeSegment(lowerId) + "/" + SidecarUriUtils.encodeSegment(normalizedVersion.get())
+ "/" + SidecarUriUtils.encodeSegment(lowerId) + ".nuspec");
if (nuspec.isEmpty()) {
// The version was just confirmed to exist via matchVersion above; a nuspec that
// vanishes in the narrow window between that check and this fetch is a genuine
// mid-flight race (a concurrent DeletePackage), not a version that never existed.
return Optional.of("");
}
return Optional.of(NuspecXml.parse(nuspec.get()).description().orElse(""));
}
/**
* {@code empty()} when {@code version} doesn't match any version BaGetter actually holds for this
* package, its own normalized form otherwise. BaGetter lists each version it holds already
* normalized and lowercased (confirmed directly against its own {@code PackageContentController
* .GetPackageVersionsAsync}), so {@code version} is matched against that list under the same
* normalization applied to both sides rather than trusted as already being in that exact form:
* a caller is free to ask for {@code 1.00.0} and get the version BaGetter itself calls {@code
* 1.0.0}, the same leading-zero and trailing-zero normalization AWS documents for NuGet.
*/
private Optional<String> matchVersion(String repositoryContainerId, String lowerId, String version) {
String wanted = NuGetVersions.normalize(version);
for (String candidate : listVersions(repositoryContainerId, lowerId)) {
if (candidate.equals(wanted)) {
return Optional.of(candidate);
}
}
return Optional.empty();
}
private List<String> listVersions(String repositoryContainerId, String lowerId) {
String baseUrl = ensureReady(repositoryContainerId, null);
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/v3/package/" + SidecarUriUtils.encodeSegment(lowerId)
+ "/index.json");
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
try {
response = httpClient.send(request, BodyHandlers.ofString());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the BaGetter sidecar to list versions of " + lowerId, e);
}
if (response.statusCode() == 404) {
return List.of();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not list versions of " + lowerId + " on the BaGetter sidecar: "
+ "upstream returned " + response.statusCode());
}
JsonNode versions;
try {
versions = mapper.readTree(response.body()).path("versions");
} catch (Exception e) {
throw new IllegalStateException("Could not parse BaGetter's version listing for " + lowerId, e);
}
return versions.isArray()
? versions.valueStream().map(JsonNode::asText).toList()
: List.of();
}
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 BaGetter sidecar at " + encodedPath, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + encodedPath + " from the BaGetter sidecar: upstream "
+ "returned " + response.statusCode());
}
return Optional.of(response.body());
}
}
@@ -0,0 +1,122 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
/**
* Starts and stops one BaGetter container per CodeArtifact repository backing the {@code nuget}
* format, the same per-repository shape as Verdaccio (npm) and pypiserver (pypi) rather than
* Reposilite's one shared instance. The HTTP protocol lives in {@link BagetterSidecarClient}.
* Implements {@link ContainerTeardown} so reset, nuke, and shutdown stop every container this
* manager started.
*
* <p>Configured with {@code ApiKey} left empty, matching the image's own shipped default: BaGetter
* treats an empty configured key as "no key configured" and authenticates every request
* unconditionally in that case (traced directly in BaGetter's own {@code ApiKeyAuthenticationService}
* before relying on it). Real CodeArtifact authorization already happens once at Floci's proxy
* layer, {@code CodeArtifactNuGetController}, before a request ever reaches this container, the
* same reasoning Verdaccio's open {@code $all} access and pypiserver's {@code -a . -P .} already
* rely on. {@code PackageDeletionBehavior} is overridden to {@code HardDelete}: the image's own
* default, {@code Unlist}, only hides a package from listings while leaving its content in place,
* which would leave {@code DeletePackage} unable to make a later republish of the same version
* succeed and would leave {@code GetPackageVersionAsset} still able to fetch a "deleted" asset.
*/
@ApplicationScoped
public class BagetterSidecarManager implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(BagetterSidecarManager.class);
// The pinned image's base (mcr.microsoft.com/dotnet/aspnet:9.0-alpine) sets
// ASPNETCORE_HTTP_PORTS=8080 itself (confirmed directly against the image's own env, the
// documented .NET 8+ convention of listening on 8080 rather than 80 in a non-root container),
// and BagetterEndpointBuilder maps a dedicated /health route Floci uses as the readiness check.
private static final int BAGETTER_PORT = 8080;
private static final String HEALTH_PATH = "/health";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private final PerKeyContainerPool pool;
@Inject
public BagetterSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
}
/**
* Base URL of a ready BaGetter instance for this nuget repository, starting its container if this
* is the first use. {@code publicUrl} is unused: BaGetter's own responses that could otherwise
* embed a self-referential URL (its service index, registration, and search resources) are
* never proxied verbatim by {@link CodeArtifactNuGetController}, which authors the service
* index itself and does not implement registration or search, so there is nothing here for an
* internal, client-unreachable address to leak into.
*/
public String ensureReady(String nugetRepositoryId, String publicUrl) {
return pool.ensureReady(nugetRepositoryId, () -> startContainer(nugetRepositoryId));
}
/** Stops and removes the container for one nuget repository, if one was ever started. */
public void release(String nugetRepositoryId) {
pool.stopContainer(nugetRepositoryId);
}
private PerKeyContainerPool.StartedContainer startContainer(String nugetRepositoryId) {
String image = config.services().codeartifact().nugetImage();
String containerName = ContainerStorageHelper.dockerName(config, "floci-bagetter-" + nugetRepositoryId);
lifecycleManager.removeIfExists(containerName);
// Loopback-only: this container authenticates nothing on its own (ApiKey left empty
// below), so the Bearer/Basic check in CodeArtifactNuGetController is the only thing
// standing between a client and the backing storage. Publishing this to every interface
// would let anyone who can reach the host bypass that check entirely, the same reasoning
// as Verdaccio's and pypiserver's own loopback binding.
// Storage/Database are left unconfigured here: the pinned image's own Dockerfile already
// sets Storage__Path=/data, Database__Type=Sqlite, and Database__ConnectionString to a
// writable path under /data (confirmed directly against the image's build), so there is
// no empty or unwritable default here to guard against the way pypiserver's "-P ." needs
// an explicit path.
ContainerSpec spec = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv("ApiKey", "")
// Already the image's own shipped default; set explicitly so a future image
// default change can't quietly start resolving packages from the real nuget.org,
// matching the Maven, npm, and pypi proxies' own deliberate choice not to resolve
// upstream repositories or external connections.
.withEnv("Mirror__Enabled", "false")
.withEnv("PackageDeletionBehavior", "HardDelete")
.withLoopbackPortBinding(BAGETTER_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(BAGETTER_PORT);
String url = "http://" + endpoint;
LOG.infov("BaGetter sidecar for nuget repository {0} is ready at {1}", nugetRepositoryId, url);
return new PerKeyContainerPool.StartedContainer(containerId, url);
} catch (RuntimeException e) {
lifecycleManager.stopAndRemove(containerId, null);
throw e;
}
}
@Override
public void stopManagedContainers() {
pool.stopAll();
}
}
@@ -0,0 +1,322 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.MultipartFormParser;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.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.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.time.Duration;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
/**
* Serves the real NuGet V3 wire protocol behind the URL {@code GetRepositoryEndpoint} returns for
* the {@code nuget} format: the same source a real {@code nuget}/{@code dotnet} client speaks
* against once {@code v3/index.json} is appended to it (AWS's own documented requirement, "The
* source URL must end in /v3/index.json"), not a CodeArtifact API action. Backed by one BaGetter
* container per repository, provisioned on first use.
*
* <p>Authors its own service index rather than proxying BaGetter's own: BaGetter's real {@code
* v3/index.json} response embeds self-referential absolute URLs for every resource (its own base
* address, exactly the problem {@link RepositorySidecarManager#ensureReady}'s {@code publicUrl}
* parameter exists for), and this only ever needs two of those resources (see below), so
* authoring them directly avoids rewriting BaGetter's response the way {@code
* CodeArtifactPypiController} has to rewrite pypiserver's. Advertises only {@code
* PackageBaseAddress/3.0.0} (install) and {@code PackagePublish/2.0.0} (push): deliberately omits
* {@code RegistrationsBaseUrl} and {@code SearchQueryService} (see {@code BagetterSidecarClient}'s
* own javadoc for why neither is needed for {@code nuget install}/{@code restore} to work, and
* AWS's own docs call {@code nuget list}, the one command that would need search, unsupported
* against CodeArtifact regardless).
*
* <p>Requires the bearer token real CodeArtifact requires here, obtained from {@code
* GetAuthorizationToken}: AWS's own NuGet CLI configuration doc has the client authenticate with
* HTTP Basic ({@code username=aws, password=<token>}), the same convention Maven's HTTP wagon and
* pip/twine use, not npm's Bearer-only {@code _authToken}; {@link CodeArtifactTokenExtractor}
* accepts either scheme.
*
* <p>Unlike Maven and npm, and like pypi, this rejects a re-push of a package version BaGetter has
* already indexed itself, since BaGetter's own {@code AllowPackageOverwrites: false} default rejects
* even a byte-identical retry (confirmed directly against its push controller): a pre-upload
* check against BaGetter's own flat container and the existing version's own bytes is what gives
* CodeArtifact's documented idempotent-republish exception ("Overwriting package assets": a
* same-coordinate upload with identical content succeeds) to a sidecar that otherwise has none.
*/
@Path("/codeartifact/nuget/{domain}/{repository}")
public class CodeArtifactNuGetController {
private final CodeArtifactService service;
private final BagetterSidecarClient bagetter;
private final HttpClient httpClient;
@Inject
public CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter) {
this(service, bagetter, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter, HttpClient httpClient) {
this.service = service;
this.bagetter = bagetter;
this.httpClient = httpClient;
}
private record RepositoryHandle(String repoId, String baseUrl, String publicBaseUrl, String region,
String owner) {
}
@GET
@Path("v3/index.json")
@Produces(MediaType.APPLICATION_JSON)
public Response serviceIndex(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository) {
RepositoryHandle handle = requireRepository(headers, domain, repository);
// domain and repository are free to embed here unescaped: requireRepository above only
// returns once CodeArtifactService has confirmed a repository by this exact name already
// exists, which it could only do if that name already passed CreateRepository's own
// DOMAIN_NAME/REPOSITORY_NAME validation, a character set with no '"', '\', or control
// character either pattern allows through.
String body = """
{
"version": "3.0.0",
"resources": [
{ "@id": "%1$s/v3/package/", "@type": "PackageBaseAddress/3.0.0" },
{ "@id": "%1$s/api/v2/package", "@type": "PackagePublish/2.0.0" }
]
}
""".formatted(handle.publicBaseUrl());
return Response.status(200).entity(body).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("v3/package/{id}/index.json")
@Produces(MediaType.APPLICATION_JSON)
public Response packageVersions(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository, @PathParam("id") String id) {
String baseUrl = requireRepository(headers, domain, repository).baseUrl();
return proxyGet(baseUrl, "/v3/package/" + SidecarUriUtils.encodeSegment(id) + "/index.json",
MediaType.APPLICATION_JSON);
}
/**
* One route for the nupkg, nuspec, and readme downloads: all three share the same {@code
* {id}/{version}/<file>} shape, and BaGetter itself doesn't validate the literal file name
* segment against the real one either (confirmed directly against its package content
* controller, which only binds {@code id} and {@code version} from the route; the AWS NuGet
* API spec's push side documents the same disregard, "The file name ... [is] ignored"),
* so dispatching on {@code filename}'s suffix here is exactly as faithful as BaGetter's own
* routing.
*/
@GET
@Path("v3/package/{id}/{version}/{filename}")
@Produces(MediaType.WILDCARD)
public Response packageContent(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository, @PathParam("id") String id,
@PathParam("version") String version, @PathParam("filename") String filename) {
String baseUrl = requireRepository(headers, domain, repository).baseUrl();
String lowerId = SidecarUriUtils.encodeSegment(id.toLowerCase(Locale.ROOT));
String encodedVersion = SidecarUriUtils.encodeSegment(version);
String lowerFilename = filename.toLowerCase(Locale.ROOT);
if ("readme".equals(lowerFilename)) {
return proxyGet(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/readme",
"text/markdown");
}
if (lowerFilename.endsWith(".nuspec")) {
return proxyGet(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/"
+ lowerId + ".nuspec", "text/xml");
}
if (lowerFilename.endsWith(".nupkg")) {
return proxyGet(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/"
+ lowerId + "." + SidecarUriUtils.encodeSegment(version.toLowerCase(Locale.ROOT)) + ".nupkg",
MediaType.APPLICATION_OCTET_STREAM);
}
return Response.status(404).build();
}
/**
* Handles a {@code nuget push}/{@code dotnet nuget push}: {@code PUT} to the repository's
* {@code api/v2/package}, {@code multipart/form-data} whose first part is the raw bytes of
* the {@code .nupkg} (the real NuGet push protocol's own documented shape; unlike twine's
* upload, there is no separate {@code name}/{@code version} form field, so those are read
* from the uploaded package's own embedded {@code .nuspec} instead).
*
* <p>The existence check and the forwarded push run inside a lock keyed by this repository's
* id, the same reason {@code CodeArtifactPypiController#upload} does: without it, two pushes
* racing the same new id/version could both observe "not published yet" before either one's
* write actually lands.
*/
@PUT
@Path("api/v2/package")
@Consumes(MediaType.WILDCARD)
public Response push(@Context HttpHeaders headers, @PathParam("domain") String domain,
@PathParam("repository") String repository, byte[] body) {
byte[] content = body != null ? body : new byte[0];
// Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy
// Reactive has already buffered the full body into this byte[] before this method runs,
// so this rejects anything that made it this far rather than bounding memory use upfront.
if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) {
return Response.status(413).build();
}
RepositoryHandle handle = requireRepository(headers, domain, repository);
String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
String boundary = MultipartFormParser.extractBoundary(contentType).orElse(null);
if (boundary == null) {
return Response.status(400).entity("Could not determine multipart boundary from Content-Type.").build();
}
MultipartFormParser.ParsedForm form = MultipartFormParser.parse(content, boundary);
Optional<MultipartFormParser.FilePart> file = form.file();
if (file.isEmpty()) {
return Response.status(400).entity("Upload must include the package file.").build();
}
byte[] nupkgBytes = file.get().content();
NuspecXml.Metadata nuspec;
try {
nuspec = NuspecXml.extractFromNupkg(nupkgBytes);
} catch (RuntimeException e) {
return Response.status(400).entity("Could not read the uploaded package: " + e.getMessage()).build();
}
String packageName = nuspec.id().toLowerCase(Locale.ROOT);
String version = NuGetVersions.normalize(nuspec.version());
// The exact same lock BagetterSidecarClient#deletePackage takes for this repository, not
// a private one: without sharing it, a DeletePackage racing this push could still list
// its versions before this push lands and miss it, the one case a private lock here
// could never close no matter how it synchronized with itself.
synchronized (bagetter.lockFor(handle.repoId())) {
Optional<byte[]> existing = existingNupkgContent(handle.baseUrl(), packageName, version);
if (existing.isPresent()) {
if (Arrays.equals(existing.get(), nupkgBytes)) {
return Response.status(200).build();
}
return Response.status(409)
.entity("A package with this id and version already exists.")
.build();
}
// Snapshotted before the real write, not after: see
// CodeArtifactService#currentContainerBackedPackageFence's own javadoc for why the
// order matters.
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
repository, "nuget", null, packageName);
Response response = forwardPush(handle.baseUrl(), contentType, content);
boolean pushSucceeded = response.getStatus() == 200 || response.getStatus() == 201
|| response.getStatus() == 202;
if (pushSucceeded) {
service.recordContainerBackedAssetBytes(handle.region(), domain, handle.owner(), repository,
"nuget", null, packageName, nupkgBytes.length, fenceSnapshot);
}
return response;
}
}
/**
* {@code empty()} when {@code packageName}/{@code version} isn't published on BaGetter yet, its
* actual bytes otherwise. A connectivity failure here throws rather than returning {@code
* empty()}, the same fail-safe reasoning as {@code CodeArtifactPypiController
* #existingFileContent}: letting a push with different content through to BaGetter during
* exactly the moment this check is unavailable would be the opposite of fail-safe, and BaGetter's
* own {@code AllowPackageOverwrites: false} would reject it anyway, just with a response this
* proxy no longer controls.
*/
private Optional<byte[]> existingNupkgContent(String baseUrl, String packageName, String version) {
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/v3/package/"
+ SidecarUriUtils.encodeSegment(packageName) + "/" + SidecarUriUtils.encodeSegment(version) + "/"
+ SidecarUriUtils.encodeSegment(packageName) + "." + SidecarUriUtils.encodeSegment(version)
+ ".nupkg");
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> response;
try {
response = httpClient.send(request, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException(
"Could not check nuget package " + packageName + " " + version + " for an existing push", e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException(
"Could not check nuget package " + packageName + " " + version + ": upstream returned "
+ response.statusCode());
}
return Optional.of(response.body());
}
private Response forwardPush(String baseUrl, String contentType, byte[] content) {
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/api/v2/package"))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", contentType)
.PUT(BodyPublishers.ofByteArray(content))
.build();
HttpResponse<Void> response;
try {
response = httpClient.send(request, BodyHandlers.discarding());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the BaGetter sidecar to push this package", e);
}
return Response.status(response.statusCode()).build();
}
/**
* {@code encodedPath} must already be fully percent-encoded: see {@link SidecarUriUtils
* #combine} for why a raw {@code URI.create(baseUrl + path)} concatenation isn't safe here.
*/
private Response proxyGet(String baseUrl, String encodedPath, String fallbackContentType) {
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 BaGetter sidecar at " + encodedPath, e);
}
if (response.statusCode() == 404) {
return Response.status(404).build();
}
String contentType = response.headers().firstValue("Content-Type").orElse(fallbackContentType);
return Response.status(response.statusCode()).entity(response.body()).type(contentType).build();
}
private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) {
String token = CodeArtifactTokenExtractor.extractToken(headers);
AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain)
.orElseThrow(() -> new NotAuthorizedException("Basic realm=\"floci-codeartifact\""));
String repoId;
try {
repoId = service.ensureFormatContainerId("nuget", scope.region(), domain, scope.owner(), repository);
} catch (AwsException e) {
throw new NotFoundException();
}
String baseUrl = bagetter.ensureReady(repoId, null);
// The real GetRepositoryEndpoint value, not just this controller's own path: a NuGet
// client's own service-index parser only keeps a resource whose @id parses as an
// absolute URI (confirmed directly against NuGet.Protocol's own ServiceIndexResourceV3,
// and the official NuGet API docs' own wording, "each resource's @id must be an absolute
// URL with an HTTP or HTTPS scheme"), so the index this controller authors has to embed
// the same scheme/host (and any configured path prefix) real clients already reach this
// controller through, not a bare path with neither.
String endpoint = service.getRepositoryEndpoint(scope.region(), domain, scope.owner(), repository, "nuget",
null);
String publicBaseUrl = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
return new RepositoryHandle(repoId, baseUrl, publicBaseUrl, scope.region(), scope.owner());
}
}
@@ -77,7 +77,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");
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi", "nuget");
private static final Set<String> ORIGIN_RESTRICTION_VALUES = Set.of("ALLOW", "BLOCK");
/**
* Formats AWS documents as valid for {@code GetPackageVersionReadme} specifically: the
@@ -143,12 +143,12 @@ public class CodeArtifactService implements Resettable {
// currentContainerBackedPackageFence's own javadoc for what this protects against.
private final ConcurrentHashMap<String, Long> containerBackedPackageDeletionFence = new ConcurrentHashMap<>();
private final AtomicLong containerBackedPackageDeletionCounter = new AtomicLong();
// Maven, npm, and pypi publishes go straight to their own sidecar and never create a
// Maven, npm, pypi, and nuget publishes go straight to their own sidecar and never create a
// packageVersions record (see CONTAINER_BACKED_FORMATS), so DescribeDomain's assetSizeBytes
// can't see their bytes by summing packageVersions the way it does for generic. Each format's
// own proxy reports a successful, non-idempotent publish's size here instead, keyed exactly
// like packageOriginConfigs (region/domain/repository/format/namespace/package, no version).
// In memory only, like the fence above, not through StorageFactory: the Maven/npm/pypi
// In memory only, like the fence above, not through StorageFactory: the Maven/npm/pypi/nuget
// content these bytes count lives in the sidecar containers themselves, which do not survive
// a Floci restart either (no volume attached, removed on shutdown; see this service's own
// Known limitations doc). Persisting the count but not the content it describes would leave
@@ -385,7 +385,7 @@ public class CodeArtifactService implements Resettable {
.filter(k -> k.startsWith(originPrefix))
.forEach(k -> packageOriginConfigs.deleteForAccount(owner, k));
// Keyed the same way: without this, a repository recreated under the same name would
// inherit the previous one's Maven/npm/pypi byte counts into DescribeDomain's total.
// inherit the previous one's Maven/npm/pypi/nuget byte counts into DescribeDomain's total.
String ownerScopedOriginPrefix = ownerScopedKey(owner, originPrefix);
containerBackedAssetBytes.keySet().stream()
.filter(k -> k.startsWith(ownerScopedOriginPrefix))
@@ -854,7 +854,7 @@ public class CodeArtifactService implements Resettable {
// it with no versions (its own documented behavior): a stored config, even with zero
// versions behind it, already proves the package exists, and the && below must short-circuit
// on originConfig.isEmpty() before packageExistsViaVersionsOrSidecar ever runs. For a
// container-backed format that call would otherwise start the real Maven/npm/pypi sidecar
// container-backed format that call would otherwise start the real Maven/npm/pypi/nuget sidecar
// container (its own ensureReady lazily provisions one) just to answer a DescribePackage for
// a package nothing was ever actually published to.
if (originConfig.isEmpty()
@@ -1038,10 +1038,11 @@ public class CodeArtifactService implements Resettable {
/**
* Each sidecar's delete capability differs enough that there is no honest shared implementation:
* Verdaccio and Reposilite remove a whole package in one call, while pypiserver's own management
* endpoint only deletes one exact name/version pair per call, so {@code PypiserverSidecarClient}
* lists every file first and removes each one in turn; all three are confirmed against live
* containers. {@link RepositorySidecarManager#deletePackage}'s default still throws
* Verdaccio and Reposilite remove a whole package in one call, while pypiserver's and BaGetter's
* own management endpoints only delete one exact name/version pair per call, so {@code
* PypiserverSidecarClient} and {@code BagetterSidecarClient} each list every file or version first
* and remove each one in turn; all four are confirmed against live containers.
* {@link RepositorySidecarManager#deletePackage}'s default still throws
* {@link UnsupportedOperationException} for a sidecar that genuinely cannot do this, rather than
* silently leaving the package in place or claiming a success it cannot back up; that becomes a
* real, if deliberately blunt, AWS error here instead of an unhandled 500.
@@ -1109,8 +1110,8 @@ public class CodeArtifactService implements Resettable {
}
String owner = effectiveOwner(domainOwner);
// Maven, npm, and pypi are metadata-free passthroughs straight to their own sidecar
// (ReposiliteSidecarClient/VerdaccioSidecarClient/PypiserverSidecarClient): publish for
// Maven, npm, pypi, and nuget are metadata-free passthroughs straight to their own sidecar
// (ReposiliteSidecarClient/VerdaccioSidecarClient/PypiserverSidecarClient/BagetterSidecarClient): publish for
// these formats never goes through publishPackageVersion (it only ever accepts "generic"),
// so packageVersions can never hold a record for them. Bridge straight to the sidecar
// that actually has the asset instead of always 404ing here.
@@ -1179,7 +1180,7 @@ public class CodeArtifactService implements Resettable {
* identical coordinates) from ever synthesizing the same revision.
*
* <p>Shared by {@link #getContainerBackedPackageVersionAsset}, {@link
* #describeContainerBackedPackageVersion}, and {@link #getPackageVersionReadme}'s npm/pypi
* #describeContainerBackedPackageVersion}, and {@link #getPackageVersionReadme}'s npm/pypi/nuget
* answers, so a client calling any two of them for the same version coordinate always sees one
* consistent revision rather than independently-computed stand-ins that happen to differ.
* Doesn't change when a new asset is published to the version afterward, unlike a real stored
@@ -1217,10 +1218,11 @@ public class CodeArtifactService implements Resettable {
* action); see {@link #recordPublishedPackageVersionReadme}, the only place either is ever
* captured.
*
* <p>nuget is accepted, since AWS documents it as valid, but never finds anything: nothing in
* Floci today implements the real NuGet wire protocol, so no nuget package version can ever
* actually exist here. This 404s for it exactly the same way as any npm/pypi version nothing
* ever published, rather than special-casing a format with no data behind it either way.
* <p>nuget differs from both: BaGetter keeps every version's own readme (and nuspec {@code
* description} fallback) addressable by exact version for as long as that version exists
* (confirmed directly against its package content controller), so this answers nuget live
* against the sidecar, through {@link RepositorySidecarManager#fetchPackageVersionReadme},
* rather than from a record captured at publish time the way npm and pypi need to.
*/
public PackageVersionReadmeResult getPackageVersionReadme(String region, String domain, String domainOwner,
String repository, String format, String namespace, String packageName, String version) {
@@ -1231,25 +1233,31 @@ public class CodeArtifactService implements Resettable {
requireNonBlank(repository, "repository");
requireNonBlank(packageName, "package");
requireNonBlank(version, "packageVersion");
validatePackageToken("package", packageName);
validatePackageToken("packageVersion", version);
if (namespace != null) {
validatePackageToken("namespace", namespace);
}
// Found by Qodo review: this used to only check namespace's token syntax, never whether
// pypi or nuget (neither of which has one) was even given one; a caller-supplied
// namespace for an existing pypi/nuget version could resolve a readme under a coordinate
// that format can't actually have, instead of a ValidationException.
validatePackageCoordinates(format, namespace, packageName, "reading the readme of");
String owner = effectiveOwner(domainOwner);
requireRepository(owner, repositoryKey(region, domain, repository), repository);
// npm, pypi, and nuget alike: none of the three can be answered live (see this method's
// own javadoc), so a version that was never captured here means it was never published,
// including every nuget version, since nothing ever publishes one. Checked before
// ensureFormatContainerId below so a nuget request, which can only ever 404, never mints
// and persists a sidecar container id for a format with no sidecar at all.
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
String revision = synthesizeContainerBackedRevision(repoId, namespace, packageName, version);
if ("nuget".equals(format)) {
String readme = sidecarRegistry.forFormat(format)
.flatMap(manager -> manager.fetchPackageVersionReadme(repoId, domain, repository, namespace,
packageName, version))
.orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName
+ "' was not found.", version, "package-version"));
return new PackageVersionReadmeResult(format, namespace, packageName, version, revision, readme);
}
// npm and pypi: neither can be answered live (see this method's own javadoc), so a
// version that was never captured here means it was never published.
String key = packageVersionKey(region, domain, repository, format, namespace,
accountingPackageName(format, packageName), version);
String readme = Optional.ofNullable(packageVersionReadmes.get(ownerScopedKey(owner, key)))
.orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName
+ "' was not found.", version, "package-version"));
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
String revision = synthesizeContainerBackedRevision(repoId, namespace, packageName, version);
return new PackageVersionReadmeResult(format, namespace, packageName, version, revision, readme);
}
@@ -1474,7 +1482,7 @@ public class CodeArtifactService implements Resettable {
/**
* Sums every stored {@link PackageAsset}'s size across the domain's repositories, plus
* whatever each repository's Maven/npm/pypi proxy has reported through
* whatever each repository's Maven/npm/pypi/nuget proxy has reported through
* {@link #recordContainerBackedAssetBytes}, for {@code DescribeDomain}'s {@code
* assetSizeBytes}.
*
@@ -1541,9 +1549,14 @@ public class CodeArtifactService implements Resettable {
/**
* Adds {@code bytes} to the running total CodeArtifact's own storage tracks for one
* Maven/npm/pypi package, independent of whatever that sidecar could report back later: none
* of the three expose an enumeration cheap enough for {@link #assetSizeBytesForDomain} to
* query live (the same reason {@link #describePackageVersion} can't bridge to them either).
* Maven/npm/pypi/nuget package, independent of whatever that sidecar could report back later:
* Maven, npm, and pypi expose no enumeration cheap enough for {@link #assetSizeBytesForDomain}
* to query live (the same reason {@link #describePackageVersion} can't bridge to any of the
* three either). nuget's BaGetter sidecar actually could answer a per-package byte total cheaply
* through its own flat container listing, but this stays the uniform mechanism across every
* container-backed format rather than special-casing the one sidecar that happens to support
* it, the same reasoning {@link #deleteContainerBackedPackageIfPresent} already applies by
* always asking the sidecar instead of trusting a stored shortcut.
* Called by each format's own proxy only once it has already decided, in its own terms, that a
* real write just happened: never for an idempotent short-circuit (nothing new was written) or
* a rejected conflict (Reposilite's {@code redeployment: false}, Verdaccio's native reject, or
@@ -1676,7 +1689,16 @@ public class CodeArtifactService implements Resettable {
* that mismatch is pre-existing and unrelated to the byte accounting this method guards.
*/
private static String accountingPackageName(String format, String packageName) {
return "pypi".equals(format) ? packageName.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-") : packageName;
if ("pypi".equals(format)) {
return packageName.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-");
}
// AWS's own NuGet normalization doc: "CodeArtifact normalizes NuGet package names by
// converting all letters to lowercase," with no further collapsing the way pypi's PEP 503
// normalization does, so this never needs anything beyond a case change.
if ("nuget".equals(format)) {
return packageName.toLowerCase(Locale.ROOT);
}
return packageName;
}
private int domainCountForAccount(String owner, String region) {
@@ -1835,8 +1857,8 @@ 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) && namespace != null) {
throw validation("pypi packages do not have a namespace.");
if (("pypi".equals(format) || "nuget".equals(format)) && namespace != null) {
throw validation(format + " packages do not have a namespace.");
}
}
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.codeartifact;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* NuGet's own version normalization, exactly as AWS's CodeArtifact User Guide documents it for
* the {@code nuget} format ("NuGet package name, version, and asset name normalization"):
* leading zeroes removed from each numeric segment, a trailing zero fourth segment omitted, and
* SemVer 2.0.0 build metadata removed. Used to match a caller-supplied version against the
* already-normalized, lowercased version strings BaGetter itself returns (its own package content
* controller normalizes the same way, via {@code NuGetVersion.ToNormalizedString()}), not to
* reimplement NuGet's full version model: a version this cannot parse as a plain dotted-numeric
* release, with an optional prerelease label, is left exactly as given rather than guessed at,
* so it simply fails to match anything BaGetter lists instead of silently normalizing it wrong.
*
* <p>Always pads a short release up to at least three segments (AWS's own worked example, "1.00
* is treated as 1.0", doesn't; real {@code NuGetVersion.ToNormalizedString()} does, always
* emitting at least Major.Minor.Patch), since matching what BaGetter's version list actually
* contains is the entire point here, not reproducing AWS's own doc text byte-for-byte.
*/
final class NuGetVersions {
private NuGetVersions() {
}
static String normalize(String version) {
String withoutMetadata = version.split("\\+", 2)[0];
int dash = withoutMetadata.indexOf('-');
String release = dash < 0 ? withoutMetadata : withoutMetadata.substring(0, dash);
String prerelease = dash < 0 ? null : withoutMetadata.substring(dash + 1);
// -1: a plain split() silently drops a trailing empty string, so "1.0.0." (a real
// version has no empty segment) would otherwise normalize identically to "1.0.0" and
// match a genuinely published version under a caller-supplied, malformed one.
String[] rawSegments = release.split("\\.", -1);
List<String> segments = new ArrayList<>();
for (String rawSegment : rawSegments) {
if (!rawSegment.matches("[0-9]+")) {
// Not a plain numeric segment (or not numeric at all, or empty, see above): give
// up on normalizing and let the caller's own text through unchanged, so this only
// ever actively changes a string it is sure it understood correctly.
return version;
}
try {
segments.add(String.valueOf(Long.parseLong(rawSegment)));
} catch (NumberFormatException e) {
// A segment with more digits than fit in a long: NuGetVersion itself has no such
// limit, but nothing this talks to needs one either, so this is treated the same
// as any other segment it isn't confident it understood correctly.
return version;
}
}
while (segments.size() < 3) {
segments.add("0");
}
if (segments.size() > 4) {
return version;
}
if (segments.size() == 4 && "0".equals(segments.get(3))) {
segments.remove(3);
}
String normalized = String.join(".", segments);
if (prerelease != null && !prerelease.isEmpty()) {
normalized = normalized + "-" + prerelease;
}
return normalized.toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,122 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.XmlParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Pulls {@code id}, {@code version}, and {@code description} out of one {@code .nuspec} file's
* XML, the three elements every valid nuspec's {@code metadata} must declare, using the shared,
* hardened {@link XmlParser#parseDocument}. A real nuspec declares its elements under a default
* {@code xmlns} (the exact URI varies by schema version) and never prefixes them, so {@link
* Document#getElementsByTagName} still matches on the literal tag text even though that parser
* is namespace-aware: an unprefixed element's qualified name is just its local name.
*/
final class NuspecXml {
// A real nuspec is at most a few KB; this is generous headroom, not a realistic size, so a
// crafted entry that decompresses past it is rejected outright rather than exhausting the
// heap on a request that already passed the overall upload size check (that check measures
// the compressed request body, not what a ZIP entry inside it can expand to).
private static final int MAX_NUSPEC_BYTES = 1024 * 1024;
private NuspecXml() {
}
record Metadata(String id, String version, Optional<String> description) {
}
/**
* {@code content} is the raw bytes of a {@code .nuspec} file taken from inside a caller-supplied
* {@code .nupkg} upload, so this hardens the parser against XXE the same way any other
* caller-controlled XML parsed in this codebase must: no DOCTYPE at all ({@code
* disallow-doctype-decl}), which also rules out external entities and external DTDs without
* needing to disable each individually.
*/
static Metadata parse(byte[] content) {
Document document;
try {
document = XmlParser.parseDocument(new String(content, StandardCharsets.UTF_8));
} catch (Exception e) {
throw new IllegalStateException("Could not parse the uploaded package's .nuspec file.", e);
}
Element root = document.getDocumentElement();
NodeList metadataNodes = root.getElementsByTagName("metadata");
if (metadataNodes.getLength() == 0) {
throw new IllegalStateException("nuspec has no <metadata> element.");
}
Element metadata = (Element) metadataNodes.item(0);
String id = requireText(metadata, "id");
String version = requireText(metadata, "version");
Optional<String> description = optionalText(metadata, "description");
return new Metadata(id, version, description);
}
private static String requireText(Element metadata, String tagName) {
return optionalText(metadata, tagName)
.orElseThrow(() -> new IllegalStateException("nuspec is missing a <" + tagName + "> element."));
}
/**
* A {@code .nupkg} is a plain ZIP archive (not an OPC package; {@code NuGet.Packaging}'s own
* reader finds the manifest by extension, not by any OPC relationship), so this scans its
* entries with the JDK's own {@link ZipInputStream} for the one whose name both ends in
* {@code .nuspec} and has no {@code /} in it: the manifest always sits at the archive root,
* never nested, which keeps this from matching an unrelated {@code .nuspec}-suffixed entry a
* crafted upload could otherwise plant inside a subdirectory.
*/
static Metadata extractFromNupkg(byte[] nupkgBytes) {
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(nupkgBytes))) {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
String name = entry.getName();
if (!entry.isDirectory() && name.toLowerCase(Locale.ROOT).endsWith(".nuspec") && !name.contains("/")) {
return parse(readBounded(zip));
}
}
} catch (IOException e) {
throw new UncheckedIOException("Could not read the uploaded package as a .nupkg archive.", e);
}
throw new IllegalStateException("The uploaded package has no .nuspec manifest at its root.");
}
/**
* Reads the current entry of {@code zip} up to {@link #MAX_NUSPEC_BYTES}, throwing as soon as
* that limit is crossed rather than after buffering the whole thing: a highly-compressed
* entry can decompress to far more than the request's own, already-checked, compressed byte
* count, so the bound has to apply to the decompressed stream itself, not just the upload.
*/
private static byte[] readBounded(ZipInputStream zip) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] chunk = new byte[8192];
int read;
while ((read = zip.read(chunk)) != -1) {
if (buffer.size() + read > MAX_NUSPEC_BYTES) {
throw new IllegalStateException(
"The uploaded package's .nuspec manifest exceeds " + MAX_NUSPEC_BYTES + " bytes decompressed.");
}
buffer.write(chunk, 0, read);
}
return buffer.toByteArray();
}
private static Optional<String> optionalText(Element metadata, String tagName) {
NodeList nodes = metadata.getElementsByTagName(tagName);
if (nodes.getLength() == 0) {
return Optional.empty();
}
String text = nodes.item(0).getTextContent();
return text == null || text.isBlank() ? Optional.empty() : Optional.of(text.trim());
}
}
@@ -91,4 +91,26 @@ public interface RepositorySidecarManager {
String packageName) {
throw new UnsupportedOperationException(format() + " packages cannot be deleted through this sidecar");
}
/**
* Live readme/descriptive-text lookup for one package version, for a sidecar capable of
* answering this for a specific, possibly historical version after the fact. {@code empty()}
* by default: Verdaccio (npm) only ever exposes the most-recently-published version's readme,
* and pypiserver exposes none at all, so neither can implement this and {@code
* CodeArtifactService#getPackageVersionReadme} instead answers npm and pypi from a record
* captured at publish time ({@link CodeArtifactService#recordPublishedPackageVersionReadme}).
* {@code BagetterSidecarClient} overrides this: BaGetter keeps every version's own readme
* addressable by exact version for as long as that version exists, so nuget needs no such
* capture step.
*
* <p>Returning {@code empty()} here is read by the caller as "this sidecar cannot answer
* live", not "this version has no readme": an override distinguishes the two with {@code
* Optional.of("")} for a published version with nothing to show versus {@code empty()} for a
* version that was never published, the same convention {@link #fetchPackageVersionAsset}
* already uses for "found, but empty" versus "not found".
*/
default Optional<String> fetchPackageVersionReadme(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version) {
return Optional.empty();
}
}