fix(codeartifact): make npm republish of identical content idempotent (#5163)

Real AWS CodeArtifact documents PublishPackageVersion as idempotent: republishing
an existing asset with identical content succeeds. Verdaccio, which backs the npm
data plane, and real npm registries reject every republish of an existing version
with 409, even for byte-identical content, so Floci inherited that behavior.

A PUT to a bare package path is now spooled to a temp file in bounded chunks and
scanned as a stream. Each attachment's base64 data is hashed as it passes, and the
publish answers 200 without reaching Verdaccio only when every version's integrity
matches the stored packument, every dist-tag the publish sends already points where
it says, and no attachment is left unaccounted for. Anything else forwards the
spooled body unchanged, so Verdaccio's response stays authoritative. Envelope size
never has to fit on heap.

At most four publishes run this check at once; a publish beyond that waits in a
bounded queue, and when the queue is full it is answered 429 with Retry-After.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-06 20:31:50 -05:00
1 parent a5db3975c4
commit 2cf011f726
6 files changed
+1372 -44

No files matched your search

@@ -1,25 +1,44 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.streams.ReadStream;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Proxies the real npm registry protocol through Floci to the per-repository Verdaccio container
@@ -37,9 +56,12 @@ import java.util.Set;
@ApplicationScoped
public class CodeArtifactNpmDataPlane {
private static final Logger LOG = Logger.getLogger(CodeArtifactNpmDataPlane.class);
private static final String PREFIX = "/codeartifact/npm/";
private static final String SERVICE_KEY = "codeartifact";
private static final String BEARER_PREFIX = "Bearer ";
private static final int MAX_CONCURRENT_PREFLIGHTS = 4;
private static final int MAX_QUEUED_PREFLIGHTS = 64;
private static final Set<String> HOP_BY_HOP_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"te", "trailers", "transfer-encoding", "upgrade", "authorization", "host");
@@ -47,21 +69,23 @@ public class CodeArtifactNpmDataPlane {
private final CodeArtifactService service;
private final VerdaccioSidecarManager verdaccioManager;
private final ServiceConfigAccess serviceConfigAccess;
private final EmulatorConfig config;
private final Vertx vertx;
private final HttpClient proxyClient;
private final ObjectMapper mapper;
/** Bounds concurrent spooled publishes, which each hold a temp file and a scan in progress. */
private final PreflightGate preflights = new PreflightGate(MAX_CONCURRENT_PREFLIGHTS, MAX_QUEUED_PREFLIGHTS);
@Inject
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager,
ServiceConfigAccess serviceConfigAccess, EmulatorConfig config, Vertx vertx) {
ServiceConfigAccess serviceConfigAccess, Vertx vertx, ObjectMapper mapper) {
this.service = service;
this.verdaccioManager = verdaccioManager;
this.serviceConfigAccess = serviceConfigAccess;
this.config = config;
this.vertx = vertx;
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
.setConnectTimeout(5_000)
.setKeepAlive(true));
this.mapper = mapper;
}
void register(@Observes Router router) {
@@ -103,11 +127,25 @@ public class CodeArtifactNpmDataPlane {
return;
}
if (isPublish(context.request().method(), npmRequest.rest())) {
context.request().pause();
Context eventLoop = vertx.getOrCreateContext();
AtomicReference<PreflightGate.Waiter> queued = new AtomicReference<>();
context.response().closeHandler(ignored -> preflights.abandon(queued.get()));
PreflightGate.Waiter waiter = preflights.acquire(() -> eventLoop.runOnContext(ignored ->
handlePublish(context, npmRequest, npmRepositoryId)));
if (waiter == null) {
context.request().resume();
context.response().putHeader("Retry-After", "1").setStatusCode(429).end();
return;
}
queued.set(waiter);
return;
}
context.request().pause();
String publicUrl = config.effectiveBaseUrl() + PREFIX + npmRequest.domain() + "/" + npmRequest.repository()
+ "/";
String repoId = npmRepositoryId;
vertx.<String>executeBlocking(promise -> promise.complete(verdaccioManager.ensureReady(repoId, publicUrl)))
vertx.<String>executeBlocking(promise -> promise.complete(ensureBackendReady(repoId, npmRequest)))
.onComplete(result -> {
if (result.failed()) {
context.request().resume();
@@ -118,6 +156,339 @@ public class CodeArtifactNpmDataPlane {
});
}
/**
* A real {@code npm publish} is a {@code PUT} to the bare package path (no further path
* segments): {@code /<name>} unscoped, or {@code /@scope%2Fname} scoped, still one segment
* since the slash between scope and name arrives URL-encoded. {@code npm deprecate} is a
* {@code PUT} at this same bare-package shape (a dist-tag update is not: that always goes to
* {@code /-/package/<name>/dist-tags/<tag>}, a different, multi-segment path {@link #isPublish}
* already excludes), but {@link #confirmedRepublish} only ever short-circuits when it can
* positively confirm every version in the body already exists with byte-identical content, so
* a deprecate call (which carries no new {@code _attachments}) falls through to the normal
* proxy path unaffected.
*/
private static boolean isPublish(HttpMethod method, String rest) {
return method == HttpMethod.PUT && rest.length() > 1 && rest.indexOf('/', 1) < 0;
}
/**
* Real npm registries and the pinned Verdaccio image both reject a republish of an existing
* version with 409, even for byte-identical content. The AWS CodeArtifact User Guide states the
* opposite for package assets in general: republishing an existing asset with identical content
* succeeds because the operation is idempotent. This applies that rule to npm, which has one
* tarball asset per version. The envelope is spooled to disk in bounded chunks and scanned as a
* stream, so its size never costs heap. Only when every version and dist-tag matches does this
* answer 200 without reaching Verdaccio; anything else forwards the spooled body unchanged.
*/
private void handlePublish(RoutingContext context, NpmRequest npmRequest, String npmRepositoryId) {
AtomicBoolean finished = new AtomicBoolean();
AtomicReference<String> spool = new AtomicReference<>();
AtomicReference<AsyncFile> reading = new AtomicReference<>();
Runnable finish = () -> {
if (finished.compareAndSet(false, true)) {
if (reading.get() != null) {
reading.get().close();
}
if (spool.get() != null) {
vertx.fileSystem().delete(spool.get());
}
preflights.release();
}
};
if (context.response().ended() || context.response().closed()) {
finish.run();
return;
}
vertx.fileSystem().createTempFile("npm-publish-", ".json").onComplete(created -> {
if (created.failed()) {
finish.run();
respondUnlessGone(context, 500);
return;
}
String path = created.result();
spool.set(path);
if (finished.get()) {
vertx.fileSystem().delete(path);
return;
}
vertx.fileSystem().open(path, new OpenOptions().setWrite(true)).onComplete(opened -> {
if (opened.failed()) {
finish.run();
respondUnlessGone(context, 500);
return;
}
context.request().pipeTo(opened.result()).onComplete(piped -> {
if (piped.failed()) {
finish.run();
respondUnlessGone(context, 400);
return;
}
vertx.<String>executeBlocking(promise ->
promise.complete(ensureBackendReady(npmRepositoryId, npmRequest)), false)
.onComplete(readyResult -> {
if (readyResult.failed()) {
finish.run();
respondUnlessGone(context, 503);
return;
}
String backendBaseUrl = readyResult.result();
vertx.<Boolean>executeBlocking(promise ->
promise.complete(confirmedRepublish(backendBaseUrl, npmRequest, path)),
false)
.onComplete(matchResult -> {
if (context.response().closed()) {
finish.run();
return;
}
if (matchResult.succeeded() && matchResult.result()) {
// "ok" is a message string in a real Verdaccio response
// (e.g. "created new package"), not a boolean; matching
// that shape in case any client inspects it for display
// rather than just checking truthiness.
context.response().putHeader("Content-Type", "application/json")
.setStatusCode(200)
.end("{\"ok\":\"accepted, content already published\","
+ "\"success\":true}");
finish.run();
return;
}
vertx.fileSystem().open(path, new OpenOptions().setRead(true))
.onComplete(reopened -> {
if (reopened.failed()) {
finish.run();
respondUnlessGone(context, 500);
return;
}
reading.set(reopened.result());
context.addEndHandler(ended -> finish.run());
context.response().closeHandler(ignored -> finish.run());
forwardSpooled(context, backendBaseUrl,
npmRequest.rest() + querySuffix(context),
reopened.result());
});
});
});
});
});
});
}
private static void respondUnlessGone(RoutingContext context, int status) {
if (!context.response().ended() && !context.response().closed()) {
context.response().setStatusCode(status).end();
}
}
/**
* Admits at most {@code permits} publish preflights at once. Waiters queue here rather than
* blocking a worker thread, and each one resumes on the event loop it arrived on.
*/
private static final class PreflightGate {
private final int maxQueued;
private final Deque<Waiter> waiting = new ArrayDeque<>();
private int available;
PreflightGate(int permits, int maxQueued) {
this.available = permits;
this.maxQueued = maxQueued;
}
/** The waiter to abandon if the client leaves; {@code null} when the queue is already full. */
Waiter acquire(Runnable onAcquired) {
Waiter waiter = new Waiter(onAcquired);
synchronized (this) {
if (available > 0) {
available--;
} else if (waiting.size() < maxQueued) {
waiting.add(waiter);
return waiter;
} else {
return null;
}
}
onAcquired.run();
return waiter;
}
void abandon(Waiter waiter) {
if (waiter == null) {
return;
}
synchronized (this) {
waiting.remove(waiter);
}
}
void release() {
Waiter next;
synchronized (this) {
next = waiting.poll();
if (next == null) {
available++;
return;
}
}
next.onAcquired.run();
}
private static final class Waiter {
private final Runnable onAcquired;
Waiter(Runnable onAcquired) {
this.onAcquired = onAcquired;
}
}
}
private String ensureBackendReady(String npmRepositoryId, NpmRequest npmRequest) {
return verdaccioManager.ensureReady(npmRepositoryId,
verdaccioManager.publicUrl(npmRequest.domain(), npmRequest.repository()));
}
/**
* {@code true} only when every version in the publish envelope already exists on Verdaccio with
* the same integrity, every dist-tag the envelope sends already points where it says, and every
* attachment in the envelope is one of those versions' tarballs. Client bytes are checked against
* the integrity the client itself claims, so a mismatch between the two falls through too.
* Anything unreadable or inconsistent is not confirmable and forwards unchanged.
*/
private boolean confirmedRepublish(String backendBaseUrl, NpmRequest npmRequest, String spoolPath) {
PackageIdentity identity = packageIdentityFromPath(npmRequest.rest());
NpmPublishEnvelopeScanner.Envelope envelope;
try (InputStream in = new BufferedInputStream(Files.newInputStream(Path.of(spoolPath)))) {
envelope = NpmPublishEnvelopeScanner.scan(in);
} catch (IOException e) {
LOG.debugv(e, "Publish for {0}/{1} is not a confirmable republish: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return false;
}
Optional<JsonNode> storedDocument;
try {
storedDocument = verdaccioManager.fetchPackageDocument(backendBaseUrl, identity.namespace(),
identity.packageName());
} catch (IllegalStateException e) {
LOG.warnv(e, "Could not check {0}/{1} for an existing match before publishing: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return false;
}
if (storedDocument.isEmpty() || !isConfirmedRepublish(envelope, storedDocument.get(), identity)) {
return false;
}
for (NpmPublishEnvelopeScanner.Version version : envelope.versions().values()) {
try {
Optional<String> stored = verdaccioManager.storedTarballIntegrity(backendBaseUrl,
identity.namespace(), identity.packageName(), tarballFilename(version.tarball()));
if (stored.isEmpty() || !stored.get().equals(version.integrity())) {
return false;
}
} catch (IllegalStateException e) {
LOG.warnv(e, "Could not verify the stored tarball of {0}/{1} before publishing: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return false;
}
}
return true;
}
private static boolean isConfirmedRepublish(NpmPublishEnvelopeScanner.Envelope envelope, JsonNode stored,
PackageIdentity identity) {
if (envelope.name() != null && !envelope.name().equals(identity.fullName())) {
return false;
}
if (envelope.versions().isEmpty()) {
return false;
}
for (Map.Entry<String, String> tag : envelope.distTags().entrySet()) {
JsonNode storedTag = stored.path("dist-tags").get(tag.getKey());
if (storedTag == null || !storedTag.asText("").equals(tag.getValue())) {
return false;
}
}
Set<String> tarballs = new HashSet<>();
for (Map.Entry<String, NpmPublishEnvelopeScanner.Version> entry : envelope.versions().entrySet()) {
NpmPublishEnvelopeScanner.Version sent = entry.getValue();
if (sent.tarball() == null || sent.integrity() == null) {
return false;
}
String filename = tarballFilename(sent.tarball());
JsonNode storedVersion = stored.path("versions").get(entry.getKey());
if (storedVersion == null
|| !filename.equals(tarballFilename(storedVersion.path("dist").path("tarball").asText("")))
|| !sent.integrity().equals(storedVersion.path("dist").path("integrity").asText(""))) {
return false;
}
if (!sent.integrity().equals(envelope.attachmentIntegrity().get(filename))) {
return false;
}
tarballs.add(filename);
}
for (String attachment : envelope.attachmentIntegrity().keySet()) {
if (!tarballs.contains(attachment)) {
return false;
}
}
return true;
}
private static String tarballFilename(String tarballUrl) {
return tarballUrl.substring(tarballUrl.lastIndexOf('/') + 1);
}
/**
* {@code namespace} is the npm scope without its leading {@code @}, or {@code null} for an
* unscoped package, the same shape {@link RepositorySidecarManager#fetchPackageVersionAsset}
* takes everywhere else. {@code rest} is a bare-package publish path, exactly one segment
* ({@link #isPublish} already confirmed that): {@code /<name>} unscoped, or {@code
* /@scope%2Fname} scoped, with the scope separator arriving percent-encoded since Netty
* leaves a {@code %2F} undecoded in {@link HttpServerRequest#path()}
* specifically so it is never confused with a real path separator. The one, targeted decode
* here undoes exactly that, and only that: every other npm package-name character is already
* unreserved and needs no decoding.
*/
private static PackageIdentity packageIdentityFromPath(String rest) {
String decoded = rest.substring(1).replace("%2F", "/").replace("%2f", "/");
if (decoded.startsWith("@")) {
int slash = decoded.indexOf('/');
if (slash > 0) {
return new PackageIdentity(decoded.substring(1, slash), decoded.substring(slash + 1));
}
}
return new PackageIdentity(null, decoded);
}
private record PackageIdentity(String namespace, String packageName) {
String fullName() {
return namespace == null ? packageName : "@" + namespace + "/" + packageName;
}
}
private void forwardSpooled(RoutingContext context, String backendBaseUrl, String backendPath,
ReadStream<Buffer> body) {
URI backend = URI.create(backendBaseUrl);
RequestOptions options = new RequestOptions()
.setHost(backend.getHost())
.setPort(backend.getPort())
.setURI(backendPath)
.setMethod(context.request().method());
proxyClient.request(options).onComplete(upstreamRequest -> {
if (upstreamRequest.failed()) {
respondUnlessGone(context, 503);
return;
}
HttpClientRequest clientReq = upstreamRequest.result();
copyRequestHeaders(context, clientReq);
clientReq.response().onComplete(upstreamResponse -> {
if (upstreamResponse.failed()) {
respondUnlessGone(context, 502);
return;
}
copyResponseHeaders(context, upstreamResponse.result());
upstreamResponse.result().pipeTo(context.response());
});
clientReq.send(body).onFailure(ignored -> respondUnlessGone(context, 502));
});
}
private void proxy(RoutingContext context, String backendBaseUrl, String backendPath) {
URI backend = URI.create(backendBaseUrl);
RequestOptions options = new RequestOptions()
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.core.StreamReadFeature;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* Reads an npm publish envelope as a stream and keeps only what the republish check needs. Jackson
* decodes each attachment's base64 {@code data} straight into a SHA-512 digest, so the tarball is never
* held in memory. Any structure this scanner does not expect throws, and callers treat a throw as not
* confirmable and forward the request unchanged.
*/
final class NpmPublishEnvelopeScanner {
record Version(String tarball, String integrity) {}
record Envelope(String name, Map<String, String> distTags, Map<String, Version> versions,
Map<String, String> attachmentIntegrity) {}
private static final JsonFactory FACTORY = JsonFactory.builder()
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.streamReadConstraints(StreamReadConstraints.builder()
.maxNestingDepth(32)
.maxNumberLength(1_000_000)
.maxStringLength(1_000_000)
.build())
.build();
@FunctionalInterface
private interface FieldHandler {
void accept(String fieldName) throws IOException;
}
private final JsonParser parser;
private String name;
private final Map<String, String> distTags = new HashMap<>();
private final Map<String, Map<String, String>> versionFields = new HashMap<>();
private final Map<String, String> attachmentIntegrity = new HashMap<>();
private NpmPublishEnvelopeScanner(JsonParser parser) {
this.parser = parser;
}
static Envelope scan(InputStream in) throws IOException {
try (JsonParser parser = FACTORY.createParser(in)) {
NpmPublishEnvelopeScanner scanner = new NpmPublishEnvelopeScanner(parser);
scanner.parseEnvelope();
return scanner.envelope();
}
}
private void parseEnvelope() throws IOException {
parser.nextToken();
requireToken(JsonToken.START_OBJECT);
while (parser.nextToken() == JsonToken.FIELD_NAME) {
String key = parser.currentName();
parser.nextToken();
switch (key) {
case "name" -> name = stringValue();
case "dist-tags" -> forEachField(tag -> distTags.put(tag, stringValue()));
case "versions" -> forEachField(this::readVersion);
case "_attachments" -> forEachField(filename ->
forEachField(attachmentField -> {
if (attachmentField.equals("data")) {
attachmentIntegrity.put(filename, hashBase64());
} else {
parser.skipChildren();
}
}));
default -> parser.skipChildren();
}
}
requireToken(JsonToken.END_OBJECT);
if (parser.nextToken() != null) {
throw invalid("trailing data after the publish envelope");
}
}
private void readVersion(String version) throws IOException {
Map<String, String> fields = new HashMap<>();
forEachField(field -> {
if (field.equals("dist")) {
forEachField(distField -> {
if (distField.equals("tarball") || distField.equals("integrity")) {
fields.put(distField, stringValue());
} else {
parser.skipChildren();
}
});
} else {
parser.skipChildren();
}
});
versionFields.put(version, fields);
}
/**
* Walks the object the parser is currently on, handing each field name to {@code handler} with the
* parser positioned on that field's value. Leaves the parser on the object's END_OBJECT.
*/
private void forEachField(FieldHandler handler) throws IOException {
requireToken(JsonToken.START_OBJECT);
while (parser.nextToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.currentName();
parser.nextToken();
handler.accept(fieldName);
}
requireToken(JsonToken.END_OBJECT);
}
private String stringValue() throws IOException {
requireToken(JsonToken.VALUE_STRING);
return parser.getText();
}
private String hashBase64() throws IOException {
requireToken(JsonToken.VALUE_STRING);
MessageDigest digest = sha512();
try (OutputStream sink = new DigestOutputStream(OutputStream.nullOutputStream(), digest)) {
parser.readBinaryValue(sink);
} catch (IllegalArgumentException e) {
throw invalid("attachment data is not plain base64");
}
return "sha512-" + Base64.getEncoder().encodeToString(digest.digest());
}
private void requireToken(JsonToken expected) throws IOException {
if (parser.currentToken() != expected) {
throw invalid("expected " + expected + " but found " + parser.currentToken());
}
}
private Envelope envelope() {
Map<String, Version> versions = new HashMap<>();
for (Map.Entry<String, Map<String, String>> entry : versionFields.entrySet()) {
Map<String, String> fields = entry.getValue();
versions.put(entry.getKey(), new Version(fields.get("tarball"), fields.get("integrity")));
}
return new Envelope(name, distTags, versions, attachmentIntegrity);
}
private static MessageDigest sha512() {
try {
return MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-512 is required by every Java runtime", e);
}
}
private static IOException invalid(String reason) {
return new IOException("Not a publish envelope this check can confirm: " + reason);
}
}
@@ -20,13 +20,17 @@ import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
/**
@@ -152,29 +156,16 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
@Override
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version, String assetName) {
String publicUrl = config.effectiveBaseUrl() + "/codeartifact/npm/" + domain + "/" + repository + "/";
String baseUrl = ensureReady(repositoryContainerId, publicUrl);
String packagePath = packagePath(namespace, packageName);
if (!versionHasAsset(baseUrl, packagePath, version, assetName)) {
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
if (!versionHasAsset(baseUrl, packagePath(namespace, packageName), version, assetName)) {
return Optional.empty();
}
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath + "/-/"
+ SidecarUriUtils.encodeSegment(assetName));
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 reach the Verdaccio sidecar to fetch " + packagePath, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + packagePath + "/-/" + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
return Optional.of(response.body());
return fetchTarball(baseUrl, namespace, packageName, assetName);
}
/** The public URL a Verdaccio sidecar is told to advertise for one npm repository. */
public String publicUrl(String domain, String repository) {
return config.effectiveBaseUrl() + "/codeartifact/npm/" + domain + "/" + repository + "/";
}
private static String packagePath(String namespace, String packageName) {
@@ -183,7 +174,81 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
}
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
/**
* The package's metadata document as Verdaccio serves it, or empty when the package isn't
* there. {@code baseUrl} is a backend already made ready by {@link #ensureReady}, so repeated
* calls for one publish don't each pay another readiness probe.
*/
public Optional<JsonNode> fetchPackageDocument(String baseUrl, String namespace, String packageName) {
return packageDocument(baseUrl, packagePath(namespace, packageName));
}
/** One tarball by its filename, from a backend already made ready by {@link #ensureReady}. */
public Optional<byte[]> fetchTarball(String baseUrl, String namespace, String packageName, String assetName) {
HttpRequest request = tarballRequest(baseUrl, namespace, packageName, assetName);
HttpResponse<byte[]> response;
try {
response = httpClient.send(request, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to fetch " + assetName, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
return Optional.of(response.body());
}
/**
* The SHA-512 integrity of a stored tarball, computed by streaming its bytes so the file never
* sits in memory. Empty when the tarball is not there.
*/
public Optional<String> storedTarballIntegrity(String baseUrl, String namespace, String packageName,
String assetName) {
HttpResponse<InputStream> response;
try {
response = httpClient.send(tarballRequest(baseUrl, namespace, packageName, assetName),
BodyHandlers.ofInputStream());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to hash " + assetName, e);
}
try (InputStream body = response.body()) {
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
MessageDigest digest = sha512();
byte[] chunk = new byte[64 * 1024];
for (int read = body.read(chunk); read != -1; read = body.read(chunk)) {
digest.update(chunk, 0, read);
}
return Optional.of("sha512-" + Base64.getEncoder().encodeToString(digest.digest()));
} catch (IOException e) {
throw new IllegalStateException("Could not read " + assetName + " from the Verdaccio sidecar", e);
}
}
private HttpRequest tarballRequest(String baseUrl, String namespace, String packageName, String assetName) {
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath(namespace, packageName) + "/-/"
+ SidecarUriUtils.encodeSegment(assetName));
return HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
}
private static MessageDigest sha512() {
try {
return MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-512 is required by every Java runtime", e);
}
}
private Optional<JsonNode> packageDocument(String baseUrl, String packagePath) {
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
@@ -193,18 +258,25 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
throw new IllegalStateException("Could not reach the Verdaccio sidecar to look up " + packagePath, e);
}
if (response.statusCode() == 404) {
return false;
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not look up " + packagePath + " on the Verdaccio sidecar: "
+ "upstream returned " + response.statusCode());
}
JsonNode versionNode;
try {
versionNode = mapper.readTree(response.body()).path("versions").path(version);
return Optional.of(mapper.readTree(response.body()));
} catch (Exception e) {
throw new IllegalStateException("Could not parse Verdaccio's package metadata for " + packagePath, e);
}
}
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
Optional<JsonNode> document = packageDocument(baseUrl, packagePath);
if (document.isEmpty()) {
return false;
}
JsonNode versionNode = document.get().path("versions").path(version);
if (versionNode.isMissingNode()) {
return false;
}