feat(codeartifact): serve the npm format through a real Verdaccio proxy (#4336)

GetRepositoryEndpoint for format=npm now returns a working registry
endpoint: real npm/yarn/pnpm clients can publish to and install from it,
proxied straight through to a real Verdaccio instance rather than
reimplemented. Every request needs Authorization: Bearer <token> from
GetAuthorizationToken, matching npm's own _authToken config and, unlike
Maven's HTTP Basic support, Bearer only.

Unlike Reposilite, Verdaccio has no native concept of multiple named
repositories inside one instance, so each CodeArtifact repository gets
its own container instead of sharing one, started lazily on first use
and identified by a fresh id assigned at CreateRepository time so a
repository deleted and recreated under the same name never inherits the
previous one's packages. Each container is started with
VERDACCIO_PUBLIC_URL set to that repository's own proxy URL so package
metadata it returns (dist.tarball) points back through Floci instead of
the container's own internal, client-unreachable address.

VerdaccioSidecarManager implements the RepositorySidecarManager
interface CodeArtifactService already generalized DeleteRepository's
cleanup over, so a deleted repository's Verdaccio container is stopped
and removed the same generic way Maven's Reposilite storage is released.
The per-key container lifecycle (map of running containers, per-key
start lock, health poll, restart-on-unhealthy, stop-all) has nothing
Verdaccio-specific in it, so it is pulled out into PerKeyContainerPool
for a future per-repository sidecar to reuse directly.

CodeArtifactNpmDataPlane is a raw streaming proxy rather than a JAX-RS
controller, since npm's wire protocol has no fixed path shape the way
Maven's GAV layout does; Verdaccio already speaks that protocol
correctly, so this only needs to authenticate the request and forward
it. The publish/fetch integration test replays a real request the npm
CLI sent during manual verification, captured with a tiny Node.js
capture server, so it exercises the exact envelope shape (including a
real gzip tarball attachment) npm publish actually produces; the full
round trip was additionally verified by hand with the real npm CLI
against a live Floci instance.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-25 07:40:58 -05:00
1 parent d2c0705ea9
commit 3e6c7a3472
17 files changed
+1554 -71

No files matched your search

@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.core.common.docker;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool.StartedContainer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Covers the per-key container lifecycle (caching, restart-on-unhealthy, teardown, and the
* concurrent-first-use guarantee) that every per-repository sidecar manager needs, independent of
* what kind of container it actually starts.
*/
class PerKeyContainerPoolTest {
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
private final PerKeyContainerPool pool = new PerKeyContainerPool(lifecycleManager, "/ping");
private final List<HttpServer> fakeContainers = new ArrayList<>();
@AfterEach
void stopFakeContainers() {
fakeContainers.forEach(server -> server.stop(0));
}
@Test
void ensureReadyStartsAContainerOnFirstUse() throws IOException {
String url = startFakePing(200);
AtomicInteger starterCalls = new AtomicInteger();
String result = pool.ensureReady("key-1", () -> {
starterCalls.incrementAndGet();
return new StartedContainer("container-1", url);
});
assertEquals(url, result);
assertEquals(1, starterCalls.get());
}
@Test
void ensureReadyReturnsTheCachedUrlWithoutCallingTheStarterWhenAlreadyHealthy() throws IOException {
String url = startFakePing(200);
pool.ensureReady("key-1", () -> new StartedContainer("container-1", url));
String result = pool.ensureReady("key-1", () -> {
throw new AssertionError("starter must not be called for a healthy, already-started container");
});
assertEquals(url, result);
verifyNoInteractions(lifecycleManager);
}
@Test
void ensureReadyRestartsAnUnhealthyContainer() throws IOException {
String staleUrl = startFakePing(200);
pool.ensureReady("key-1", () -> new StartedContainer("stale-container", staleUrl));
// Only now does the first container stop being healthy: ensureReady's first call for a
// key always waits for its just-started container to actually come up, so seeding with a
// container that was never reachable at all would hang on that wait instead of exercising
// the restart path this test is for.
fakeContainers.forEach(server -> server.stop(0));
String freshUrl = startFakePing(200);
String result = pool.ensureReady("key-1", () -> new StartedContainer("fresh-container", freshUrl));
assertEquals(freshUrl, result);
verify(lifecycleManager).stopAndRemove("stale-container", null);
}
@Test
void stopContainerStopsAndForgetsATrackedContainer() throws IOException {
String url = startFakePing(200);
pool.ensureReady("key-1", () -> new StartedContainer("container-1", url));
pool.stopContainer("key-1");
verify(lifecycleManager).stopAndRemove("container-1", null);
// A second ensureReady must start a new container: the old one is genuinely forgotten,
// not just marked unhealthy.
AtomicInteger starterCalls = new AtomicInteger();
pool.ensureReady("key-1", () -> {
starterCalls.incrementAndGet();
return new StartedContainer("container-2", url);
});
assertEquals(1, starterCalls.get());
}
@Test
void stopContainerIsANoOpForAnUntrackedOrNullKey() {
pool.stopContainer("never-started");
pool.stopContainer(null);
verifyNoInteractions(lifecycleManager);
}
@Test
void stopContainerWaitsForAConcurrentFirstUseOfTheSameKeyRatherThanMissingIt() throws Exception {
String url = startFakePing(200);
CountDownLatch starterEntered = new CountDownLatch(1);
CountDownLatch releaseStarter = new CountDownLatch(1);
ExecutorService pool2 = Executors.newFixedThreadPool(2);
try {
Future<String> startFuture = pool2.submit(() -> pool.ensureReady("key-1", () -> {
starterEntered.countDown();
try {
assertTrue(releaseStarter.await(5, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new StartedContainer("container-1", url);
}));
// Once this fires, ensureReady is inside its synchronized block, holding key-1's
// lock: stopContainer below is guaranteed to block behind it, not race it, with no
// sleep needed to line the two threads up.
assertTrue(starterEntered.await(5, TimeUnit.SECONDS));
Future<?> stopFuture = pool2.submit(() -> pool.stopContainer("key-1"));
releaseStarter.countDown();
assertEquals(url, startFuture.get(5, TimeUnit.SECONDS));
stopFuture.get(5, TimeUnit.SECONDS);
} finally {
pool2.shutdown();
assertTrue(pool2.awaitTermination(30, TimeUnit.SECONDS));
}
// The container was tracked (by ensureReady, before stopContainer could run) and then
// removed (by stopContainer, once it got the lock): the race does not orphan it.
verify(lifecycleManager).stopAndRemove("container-1", null);
}
@Test
void stopAllStopsEveryTrackedContainerAndForgetsThem() throws IOException {
String urlA = startFakePing(200);
String urlB = startFakePing(200);
pool.ensureReady("key-a", () -> new StartedContainer("container-a", urlA));
pool.ensureReady("key-b", () -> new StartedContainer("container-b", urlB));
pool.stopAll();
verify(lifecycleManager).stopAndRemove("container-a", null);
verify(lifecycleManager).stopAndRemove("container-b", null);
verifyNoMoreInteractions(lifecycleManager);
}
@Test
void stopAllIsANoOpWhenNothingWasEverStarted() {
pool.stopAll();
verifyNoInteractions(lifecycleManager);
}
@Test
void concurrentFirstUseOfTheSameKeyOnlyStartsOneContainer() throws Exception {
String url = startFakePing(200);
AtomicInteger starterCalls = new AtomicInteger();
int attempts = 8;
ExecutorService pool2 = Executors.newFixedThreadPool(attempts);
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
List<String> results = new CopyOnWriteArrayList<>();
try {
for (int i = 0; i < attempts; i++) {
pool2.submit(() -> {
ready.countDown();
try {
go.await();
results.add(pool.ensureReady("shared-key", () -> {
starterCalls.incrementAndGet();
return new StartedContainer("container-shared", url);
}));
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
});
}
ready.await(5, TimeUnit.SECONDS);
go.countDown();
} finally {
pool2.shutdown();
assertTrue(pool2.awaitTermination(30, TimeUnit.SECONDS));
}
assertEquals(1, starterCalls.get());
assertEquals(attempts, results.size());
results.forEach(r -> assertEquals(url, r));
}
private String startFakePing(int status) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/ping", exchange -> {
byte[] bytes = "{}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
server.start();
fakeContainers.add(server);
return "http://127.0.0.1:" + server.getAddress().getPort();
}
}
@@ -238,6 +238,21 @@ class CodeArtifactIntegrationTest {
.then().statusCode(400).body("__type", equalTo("ValidationException"));
}
/**
* Proves the npm route is genuinely wired into the running instance ({@code @Observes
* Router} registration, the {@code ServiceConfigAccess} enablement check, and the token
* check), the one thing {@code CodeArtifactNpmDataPlaneTest} cannot: it builds the class by
* hand rather than through CDI, so it proves nothing about whether the observer actually
* registers. A missing token is rejected before the named domain or repository is looked up,
* so this needs neither to exist, and needs no Docker.
*/
@Test
void npmEndpointRejectsAMissingTokenWithoutADomainOrRepositoryExisting() {
given().get("/codeartifact/npm/no-such-domain/no-such-repo/lodash")
.then().statusCode(401)
.header("WWW-Authenticate", equalTo("Bearer"));
}
private static String sha256Hex(byte[] content) {
try {
return SigV4RequestValidator.sha256Hex(content);
@@ -0,0 +1,255 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.RequestOptions;
import io.vertx.ext.web.Router;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for routing npm registry traffic through Floci's data plane to the per-repository
* Verdaccio container. {@link VerdaccioSidecarManager} is mocked throughout, so no container ever
* actually starts; the round-trip proxy tests point it at a fake upstream HTTP server instead. The
* real container-creation path (config injection, {@code VERDACCIO_PUBLIC_URL}) is covered by the
* Docker-gated npm client integration test.
*/
class CodeArtifactNpmDataPlaneTest {
private static final String DOMAIN = "dom";
private static final String REPOSITORY = "repo";
private static final String NPM_REPOSITORY_ID = "npm-repo-id-1";
private Vertx vertx;
private HttpServer upstream;
private HttpServer dataPlane;
private HttpClient client;
@BeforeEach
void setUp() {
vertx = Vertx.vertx();
client = vertx.createHttpClient();
}
@AfterEach
void tearDown() throws Exception {
if (dataPlane != null) {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
if (upstream != null) {
upstream.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
vertx.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
@Test
void requestForParsesDomainRepositoryAndRest() {
CodeArtifactNpmDataPlane.NpmRequest request =
CodeArtifactNpmDataPlane.requestFor("/codeartifact/npm/dom/repo/lodash").orElseThrow();
assertEquals("dom", request.domain());
assertEquals("repo", request.repository());
assertEquals("/lodash", request.rest());
}
@Test
void requestForDefaultsToRootForTheBareRepositoryPath() {
CodeArtifactNpmDataPlane.NpmRequest request =
CodeArtifactNpmDataPlane.requestFor("/codeartifact/npm/dom/repo").orElseThrow();
assertEquals("/", request.rest());
}
@Test
void requestForRejectsAPathOutsideTheNpmPrefix() {
assertTrue(CodeArtifactNpmDataPlane.requestFor("/codeartifact/maven/dom/repo/x").isEmpty());
}
@Test
void missingTokenIsRejectedWithoutStartingAContainer() throws Exception {
CodeArtifactService service = mock(CodeArtifactService.class);
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
startDataPlane(service, verdaccioManager);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/lodash", null);
assertEquals(401, response.statusCode());
assertEquals("Bearer", response.headers().get("www-authenticate"));
}
@Test
void disabledCodeArtifactServiceIsNotServedByThisRoute() throws Exception {
CodeArtifactService service = mock(CodeArtifactService.class);
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
startDataPlane(service, verdaccioManager, false);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/lodash", "good-token");
assertEquals(404, response.statusCode());
verifyNoInteractions(service, verdaccioManager);
}
@Test
void invalidTokenIsRejected() throws Exception {
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken(anyString(), anyString())).thenReturn(Optional.empty());
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
startDataPlane(service, verdaccioManager);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/lodash", "not-a-real-token");
assertEquals(401, response.statusCode());
}
@Test
void unknownRepositoryIsNotFound() throws Exception {
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenThrow(new AwsException("ResourceNotFoundException", "no such repository", 404));
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
startDataPlane(service, verdaccioManager);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/lodash", "good-token");
assertEquals(404, response.statusCode());
}
@Test
void aValidRequestIsProxiedToTheRepositorysContainerWithTheClientAuthorizationStripped() throws Exception {
AtomicReference<String> upstreamPath = new AtomicReference<>();
AtomicReference<String> upstreamAuthHeader = new AtomicReference<>();
upstream = vertx.createHttpServer()
.requestHandler(request -> {
upstreamPath.set(request.path() + (request.query() != null ? "?" + request.query() : ""));
upstreamAuthHeader.set(request.getHeader("Authorization"));
request.response().putHeader("Content-Type", "application/json")
.setStatusCode(200).end("{\"name\":\"lodash\"}");
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioManager);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/lodash", "good-token");
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"lodash\"}", response.body());
assertEquals("/lodash", upstreamPath.get());
assertNull(upstreamAuthHeader.get());
}
@Test
void aPublishPutStreamsTheBodyThrough() throws Exception {
AtomicReference<String> upstreamBody = new AtomicReference<>();
AtomicReference<HttpMethod> upstreamMethod = new AtomicReference<>();
upstream = vertx.createHttpServer()
.requestHandler(request -> {
upstreamMethod.set(request.method());
request.bodyHandler(body -> {
upstreamBody.set(body.toString());
request.response().setStatusCode(201).end();
});
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioManager);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
"{\"name\":\"my-pkg\"}");
assertEquals(201, response.statusCode());
assertEquals(HttpMethod.PUT, upstreamMethod.get());
assertEquals("{\"name\":\"my-pkg\"}", upstreamBody.get());
}
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager)
throws Exception {
startDataPlane(service, verdaccioManager, true);
}
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager,
boolean codeArtifactEnabled) throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
when(serviceConfigAccess.isEnabled("codeartifact")).thenReturn(codeArtifactEnabled);
Router router = Router.router(vertx);
new CodeArtifactNpmDataPlane(service, verdaccioManager, serviceConfigAccess, config, vertx).register(router);
dataPlane = vertx.createHttpServer().requestHandler(router)
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
private HttpResponse get(String path, String bearerToken) throws Exception {
return request(HttpMethod.GET, path, bearerToken, null);
}
private HttpResponse put(String path, String bearerToken, String body) throws Exception {
return request(HttpMethod.PUT, path, bearerToken, body);
}
private HttpResponse request(HttpMethod method, String path, String bearerToken, String body) throws Exception {
RequestOptions options = new RequestOptions()
.setHost("127.0.0.1")
.setPort(dataPlane.actualPort())
.setMethod(method)
.setURI(path);
HttpClientRequest req = client.request(options).toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
if (bearerToken != null) {
req.putHeader("Authorization", "Bearer " + bearerToken);
}
HttpClientResponse resp = (body != null
? req.send(body)
: req.send())
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
String responseBody = resp.body().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS)
.toString(StandardCharsets.UTF_8);
Map<String, String> headers = new HashMap<>();
resp.headers().forEach(h -> headers.put(h.getKey().toLowerCase(), h.getValue()));
return new HttpResponse(resp.statusCode(), responseBody, headers);
}
private record HttpResponse(int statusCode, String body, Map<String, String> headers) {}
}
@@ -0,0 +1,282 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Runs a real npm-shaped publish/fetch round trip against a live, per-repository Verdaccio
* container, started by {@link VerdaccioSidecarManager} exactly as in production. The publish
* body is a real request the actual npm CLI sent during manual verification (captured with a tiny
* Node.js capture server, see {@code npm-publish-fixture.json}), not a hand-rolled approximation,
* so this test exercises the exact envelope shape (including a real gzip tarball attachment) a
* real {@code npm publish} produces. The full round trip was additionally verified by hand with
* the real npm CLI against a live Floci instance ({@code GetAuthorizationToken} through to
* {@code npm install}), which is what first caught that {@code VERDACCIO_PUBLIC_URL} is required:
* without it, {@code dist.tarball} in the metadata response points at the container's own
* internal, client-unreachable address instead of back through this proxy.
*/
@QuarkusTest
@TestProfile(CodeArtifactNpmSidecarProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactNpmDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "npm-sidecar-domain";
private static final String REPO = "npm-sidecar-repo";
private static final String PACKAGE_NAME = "floci-verdaccio-spike";
private static String bearerToken;
private static byte[] publishFixture;
private static byte[] expectedTarballBytes;
@BeforeAll
static void setUp() throws IOException {
CodeArtifactNpmSidecarProfile.requireDockerAndTheSidecarImage();
RestAssuredJsonUtils.configureAwsContentTypes();
ObjectMapper mapper = new ObjectMapper();
try (InputStream in = CodeArtifactNpmDockerIntegrationTest.class
.getResourceAsStream("/codeartifact/npm-publish-fixture.json")) {
publishFixture = in.readAllBytes();
}
JsonNode fixture = mapper.readTree(publishFixture);
String base64Tarball = fixture.path("_attachments").path(PACKAGE_NAME + "-1.0.0.tgz").path("data").asText();
expectedTarballBytes = Base64.getDecoder().decode(base64Tarball);
}
@Test
@Order(0)
void createDomainRepositoryAndAuthorizationToken() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
@Test
@Order(1)
void publishThenFetchRoundTripsTheRealNpmEnvelope() throws IOException {
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(publishFixture)
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(anyOf201Or200());
String metadataBody = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.extract().asString();
String tarballUrl = new ObjectMapper().readTree(metadataBody)
.path("versions").path("1.0.0").path("dist").path("tarball").asText();
// Pins VERDACCIO_PUBLIC_URL: without it this would be the container's own internal,
// client-unreachable address instead of a URL back through this same proxy.
assertTrue(tarballUrl.startsWith("http://localhost:4566/codeartifact/npm/" + DOMAIN + "/" + REPO + "/"),
"tarball URL must point back through the proxy, was: " + tarballUrl);
byte[] fetchedTarball = given().header("Authorization", "Bearer " + bearerToken)
.get(tarballUrl.substring("http://localhost:4566".length()))
.then().statusCode(200)
.extract().asByteArray();
assertArrayEquals(expectedTarballBytes, fetchedTarball);
}
@Test
@Order(2)
void missingPackageAndMissingRepositoryAreNotFound() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/does-not-exist")
.then().statusCode(404);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/no-such-repo/does-not-exist")
.then().statusCode(404);
}
@Test
@Order(3)
void repositoriesAreIsolatedFromEachOther() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-repo")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/other-repo/" + PACKAGE_NAME)
.then().statusCode(404);
}
@Test
@Order(4)
void missingOrWrongDomainTokensAreUnauthorized() {
given().get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(401)
.header("WWW-Authenticate", startsWith("Bearer"));
given().header("Authorization", "Bearer not-a-real-token")
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(401);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=other-npm-token-domain")
.then().statusCode(200);
String otherDomainToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=other-npm-token-domain")
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + otherDomainToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(401);
}
@Test
@Order(5)
void concurrentFirstUseOfANewRepositoryOnlyStartsOneContainer() throws InterruptedException {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=concurrent-repo")
.then().statusCode(200);
int attempts = 8;
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger notFoundResponses = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
pool.submit(() -> {
ready.countDown();
try {
go.await();
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/concurrent-repo/does-not-exist")
.then().statusCode(404);
notFoundResponses.incrementAndGet();
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
});
}
ready.await(5, TimeUnit.SECONDS);
go.countDown();
} finally {
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
}
assertEquals(attempts, notFoundResponses.get());
}
@Test
@Order(6)
void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesPackages() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(publishFixture)
.put("/codeartifact/npm/" + DOMAIN + "/reused-name/" + PACKAGE_NAME)
.then().statusCode(anyOf201Or200());
given().header("Authorization", AUTH)
.delete("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/reused-name/" + PACKAGE_NAME)
.then().statusCode(404);
}
@Test
@Order(7)
void aDomainCreatedInANonDefaultRegionIsServedThroughTheTokensOwnRegion() {
String nonDefaultRegionAuth =
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-west-2/codeartifact/aws4_request";
String domain = "npm-sidecar-non-default-region-domain";
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=" + REPO)
.then().statusCode(200);
String token = given().header("Authorization", nonDefaultRegionAuth)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + token).contentType("application/json")
.body(publishFixture)
.put("/codeartifact/npm/" + domain + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(anyOf201Or200());
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/npm/" + domain + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200);
}
@Test
@Order(8)
void aDomainCreatedUnderANonDefaultAccountIsServedThroughTheTokensOwnAccount() {
String otherAccountAuth = "AWS4-HMAC-SHA256 Credential=111122223333/20260904/us-east-1/codeartifact/aws4_request";
String domain = "npm-sidecar-cross-account-domain";
given().contentType("application/json").header("Authorization", otherAccountAuth).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", otherAccountAuth).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=" + REPO)
.then().statusCode(200);
String token = given().header("Authorization", otherAccountAuth)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + token).contentType("application/json")
.body(publishFixture)
.put("/codeartifact/npm/" + domain + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(anyOf201Or200());
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/npm/" + domain + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200);
}
private static Matcher<Integer> anyOf201Or200() {
return anyOf(is(200), is(201));
}
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.quarkus.test.junit.QuarkusTestProfile;
import org.eclipse.microprofile.config.ConfigProvider;
import org.junit.jupiter.api.Assumptions;
import java.util.Map;
/**
* Shared by every CodeArtifact integration test that needs a real Verdaccio sidecar container,
* started by {@link VerdaccioSidecarManager} exactly as in production. Namespaces containers as
* {@code floci-codeartifact-npm-test-*} so the manager's remove-before-start never touches a
* developer's real running Floci. Needs Docker; skipped without it. Locally it is also skipped
* when the pinned image is not present, so a developer without registry access is not stuck; in
* CI a missing image is a failure, since a vanished tag must not pass silently.
*/
public class CodeArtifactNpmSidecarProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.docker.resource-namespace", "codeartifact-npm-test");
}
public static void requireDockerAndTheSidecarImage() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for CodeArtifact npm "
+ "sidecar integration tests");
String image = ConfigProvider.getConfig().getValue("floci.services.codeartifact.npm-image", String.class);
Assumptions.assumeTrue(imageUsable(image), "Verdaccio sidecar image " + image + " is not present locally");
}
private static boolean isDockerAvailable() {
return run("docker", "version", "--format", "{{.Server.Version}}");
}
private static boolean imageUsable(String image) {
if ("true".equals(System.getenv("CI"))) {
return true;
}
return run("docker", "image", "inspect", image);
}
private static boolean run(String... command) {
try {
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
return process.waitFor() == 0;
} catch (Exception ignored) {
// Docker (or the image) isn't available; the caller turns this into a skipped test,
// not a failure, so there is nothing more useful to log here.
return false;
}
}
}
@@ -49,6 +49,7 @@ class CodeArtifactServiceTest {
private CodeArtifactService service;
private RegionResolver regionResolver;
private AccountAwareStorageBackend<CodeArtifactRepository> repoStore;
private VerdaccioSidecarManager verdaccioManager;
private ReposiliteSidecarClient reposiliteClient;
@BeforeEach
@@ -67,10 +68,12 @@ class CodeArtifactServiceTest {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
verdaccioManager = mock(VerdaccioSidecarManager.class);
when(verdaccioManager.format()).thenReturn("npm");
reposiliteClient = mock(ReposiliteSidecarClient.class);
when(reposiliteClient.format()).thenReturn("maven");
service = new CodeArtifactService(domainStore, repoStore, packageVersionStore, regionResolver, config,
true, null, new CodeArtifactSidecarRegistry(List.of(reposiliteClient)));
true, null, new CodeArtifactSidecarRegistry(List.of(verdaccioManager, reposiliteClient)));
}
// -------------------------------------------------------------- domains
@@ -297,7 +300,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertEquals(Set.of("maven"), created.getSidecarContainerIds().keySet());
assertEquals(Set.of("maven", "npm"), created.getSidecarContainerIds().keySet());
created.getSidecarContainerIds().values()
.forEach(id -> assertTrue(id != null && !id.isBlank()));
}
@@ -310,9 +313,12 @@ class CodeArtifactServiceTest {
service.deleteRepository(REGION, "dom", null, "repo");
CodeArtifactRepository recreated = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertTrue(!first.getSidecarContainerIds().get("maven").equals(recreated.getSidecarContainerIds().get("maven")),
"a recreated repository must never reuse the previous one's container id for a format, "
+ "or it would inherit its leftover artifacts");
for (String format : Set.of("maven", "npm")) {
assertTrue(
!first.getSidecarContainerIds().get(format).equals(recreated.getSidecarContainerIds().get(format)),
"a recreated repository must never reuse the previous one's container id for a format, "
+ "or it would inherit its leftover artifacts");
}
}
@Test
@@ -331,6 +337,24 @@ class CodeArtifactServiceTest {
service.describeRepository(REGION, "dom", null, "repo").getSidecarContainerIds().get("maven"));
}
@Test
void ensureFormatContainerIdBackfillsALegacyRepositoryMissingTheNpmFormat() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
// Simulates a repository persisted before the npm format's proxy existed: Jackson would
// deserialize a missing map entry exactly like this.
Map<String, String> withoutNpm = new HashMap<>(created.getSidecarContainerIds());
withoutNpm.remove("npm");
created.setSidecarContainerIds(withoutNpm);
repoStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo", created);
String backfilled = service.ensureFormatContainerId("npm", REGION, "dom", null, "repo");
assertTrue(backfilled != null && !backfilled.isBlank());
assertEquals(backfilled,
service.describeRepository(REGION, "dom", null, "repo").getSidecarContainerIds().get("npm"));
}
@Test
void ensureFormatContainerIdIsIdempotentForAnAlreadyAssignedFormat() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -341,6 +365,16 @@ class CodeArtifactServiceTest {
assertEquals(created.getSidecarContainerIds().get("maven"), result);
}
@Test
void ensureFormatContainerIdIsIdempotentForAnAlreadyAssignedNpmFormat() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String result = service.ensureFormatContainerId("npm", REGION, "dom", null, "repo");
assertEquals(created.getSidecarContainerIds().get("npm"), result);
}
@Test
void ensureFormatContainerIdRequiresExistingRepository() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -356,21 +390,55 @@ class CodeArtifactServiceTest {
service.deleteRepository(REGION, "dom", null, "repo");
verify(verdaccioManager).release(created.getSidecarContainerIds().get("npm"));
verify(reposiliteClient).release(created.getSidecarContainerIds().get("maven"));
}
@Test
void deleteRepositorySucceedsEvenWhenSidecarReleaseFails() {
void beforeResetReleasesEveryRepositorysSidecarStorageAcrossEveryAccount() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository first = service.createRepository(REGION, "dom", null, "repo-1", null, null, Map.of());
CodeArtifactRepository second = service.createRepository(REGION, "dom", null, "repo-2", null, null, Map.of());
service.beforeReset();
verify(verdaccioManager).release(first.getSidecarContainerIds().get("npm"));
verify(reposiliteClient).release(first.getSidecarContainerIds().get("maven"));
verify(verdaccioManager).release(second.getSidecarContainerIds().get("npm"));
verify(reposiliteClient).release(second.getSidecarContainerIds().get("maven"));
}
@Test
void beforeResetToleratesASidecarReleaseFailureAndStillReleasesTheRest() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository first = service.createRepository(REGION, "dom", null, "repo-1", null, null, Map.of());
CodeArtifactRepository second = service.createRepository(REGION, "dom", null, "repo-2", null, null, Map.of());
doThrow(new IllegalStateException("Reposilite unreachable")).when(reposiliteClient)
.release(first.getSidecarContainerIds().get("maven"));
// A reset must not abort partway through and leave later repositories' containers running
// just because one repository's release failed.
service.beforeReset();
verify(reposiliteClient).release(second.getSidecarContainerIds().get("maven"));
verify(verdaccioManager).release(first.getSidecarContainerIds().get("npm"));
verify(verdaccioManager).release(second.getSidecarContainerIds().get("npm"));
}
@Test
void deleteRepositorySucceedsEvenWhenOneFormatsSidecarReleaseFails() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
doThrow(new IllegalStateException("Reposilite unreachable")).when(reposiliteClient).release(anyString());
// The metadata delete already committed; a sidecar failure must not turn that into a
// caller-visible error, and must not leave the caller unable to ever get a clean response
// for this repository (a retry would just 404, since the record is already gone).
// for this repository (a retry would just 404, since the record is already gone). npm's
// release still runs for the same repository even though maven's threw first.
CodeArtifactRepository deleted = service.deleteRepository(REGION, "dom", null, "repo");
assertEquals("repo", deleted.getName());
verify(verdaccioManager).release(deleted.getSidecarContainerIds().get("npm"));
AwsException e = assertThrows(AwsException.class,
() -> service.describeRepository(REGION, "dom", null, "repo"));
assertEquals("ResourceNotFoundException", e.getErrorCode());