feat(codeartifact): retain npm packages from a public external connection (#7198)

npm's native registry route can now retain a missing package from a repository's own
public:npmjs external connection and serve it, instead of always 404ing, mirroring the
AWS-documented external-connection behavior already shipped for Maven (#6889) and NuGet (#7104).

Unlike Maven's GAV layout and NuGet's {id}/{version}/{filename} content route, npm's own real
wire protocol has no request shape that names one version: npm install <pkg>@<version> always
fetches the bare package's full packument first (confirmed against pacote's own source,
RegistryFetcher#packumentUrl, always the bare package path) and only picks the version out of
its own versions map afterward. So this does two things together, not just one:

- A bare packument read (the one every real npm install actually sends) merges the real
  registry's own versions and dist-tags into whatever Verdaccio already knows locally, computed
  fresh per request and never written to Verdaccio itself (its own publish protocol has no way
  to record a version's metadata without that version's real tarball bytes in the very same
  call, confirmed against a live container). Every newly-merged version's dist.tarball is
  rewritten to this repository's own proxy URL under a deterministic <bareName>-<version>.tgz
  shape; dist.shasum/dist.integrity are kept exactly as the real registry declared them, since
  there is no real content yet to hash locally.
- A tarball download for a version not yet genuinely retained triggers the real fetch, the
  same claim/fence/origin-tracking machinery Maven and NuGet already use (closing the same race
  against a concurrent DeletePackageVersions/direct push), reusing CodeArtifactService's
  already-generalized claimRetainedVersionOrigin/retainAssetUnderVersionFence methods directly.

New: NpmExternalConnectionClient (the outbound client for public:npmjs) and
CodeArtifactNpmExternalConnectionImporter (the merge and retention logic), wired into
CodeArtifactNpmDataPlane's existing raw proxy.

Deliberately scoped the same way Maven/NuGet's own base PRs were: no caching/TTL on the merge
fetch (a live check against the real registry on every packument read for a connected
repository, matching the same no-caching fidelity level Maven's own maven-metadata.xml merge
already ships with), and the documented but rarely-used single-version registry endpoint
(GET /<pkg>/<version>) is not specially handled, since real npm install never sends it either.

Update: fixed three issues Greptile's review caught, all specific to npm's own two-step
retention (a plain cache-miss asset fetch, as NuGet/Maven's retention already was, is not
enough here):
- retainAssetUnderVersionFence's own write was always the fixed RepositorySidecarManager#
  storePackageVersionAsset call, which builds a minimal version document with no dependencies/
  engines/scripts. Generalized it to take the actual write as a plain Runnable instead, so npm's
  own call can reuse the real registry's full-form version document verbatim (the same
  reuse-the-source-document treatment VerdaccioSidecarClient#copyPackageVersionAsset already
  gives a version copied from another repository), fetched once, only when a version is
  actually retained, via a new NpmExternalConnectionClient#fetchFullPackument. NuGet's own call
  site wraps the exact same plain storePackageVersionAsset call it always made.
- Verdaccio always points a fresh package's dist-tags.latest at whichever version was retained
  most recently (confirmed live, nothing a retention write sends can suppress it), so a plain
  retention could silently move what an unpinned npm install or ListPackageVersions'
  defaultDisplayVersion resolves to. Fixed on both sides of that same bug: the merge now only
  lets an external dist-tag replace a local one that itself points at an externally-retained
  version, and CodeArtifactService#listPackageVersions ignores preferredDisplayVersion the same
  way when it names one.
- A retained version's readme was never captured, so GetPackageVersionReadme 404ed on it even
  though the tarball existed; the full packument fetch above also captures the package's own
  readme (confirmed live: it only ever lives at the top of the full packument, never per
  version) the same way a native publish's own readme capture already works.

Verified two ways beyond the automated suite:
- A Docker-gated integration test retains a real package (is-even 1.0.0) from the real, live
  npmjs.com, through a real Verdaccio sidecar: a bare packument read merges the real version in
  without yet counting any bytes, a subsequent tarball fetch retains it and counts its bytes,
  a refetch does not double-count, mixed-case-irrelevant upstream-block enforcement blocks both
  the merge and the retention, a genuinely-missing package stays 404, the retained version's
  EXTERNAL origin reporting is confirmed against the real sidecar, and its real dependencies/
  engines and readme are confirmed readable back from the real sidecar afterward.
- Direct curl checks against the real registry.npmjs.org confirmed the exact packument/tarball
  URL shapes this client builds, including the %2F-escaped scope separator the packument
  endpoint specifically needs (unlike the tarball path, which uses a literal slash), and that
  the abbreviated packument form carries dependencies/engines but not scripts or any readme.

Update: fixed a fourth issue from the same re-review, found once the three fixes above landed:
mergedPackument always fetched the real registry's abbreviated form, even when the real npm
client's own Accept header asked for the full one (the shape npm view <pkg> readme-style
commands use), so a package the merge had not yet retained anything for showed no readme at
all. The merge now honors that header, fetching the real full packument only when the request
actually asked for it, and copies its package-level descriptive fields (readme among them) in
the same never-override-local way everything else here already merges, with no change to the
hot npm install path's own abbreviated fetch.

Update 3: fixed a fifth issue from the same re-review: mergedPackument's own real registry
fetch is a genuine network round trip, and nothing held any lock across it, so a
DeleteRepository finishing its own cleanup while that fetch was still in flight let the later
ensureReady call start a fresh container under an id the delete had already released, one
nothing would ever release again. Added a re-check that the repository still exists right
after that fetch, before this method ever touches the sidecar. This narrows the window back
down to an ordinary check-then-act gap rather than one stretched out by a real network round
trip, not a full fix: VerdaccioSidecarManager's own beginUse/endUse are no-ops today (unlike
PypiserverSidecarManager's), so nothing here can fully close this yet. Filed #7204 to track
giving it real in-flight-use tracking as its own, cross-cutting fix.

Update 4: fixed a sixth issue from the same re-review: DisposePackageVersions deletes a
version's real Verdaccio content outright, so versions.has(version) alone could not tell a
disposed version apart from one never retained at all, and the merge could add a disposed
version straight back in from the real registry's own still-unaware listing, even pointing
dist-tags.latest at it. An unpinned npm install could then select it, only to have the
download correctly, but confusingly, fail. The merge now excludes any externally-named version
this repository has marked Archived or Disposed, reusing the same
requireContainerBackedVersionDownloadable check the native download route itself already
enforces.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-01 17:17:12 -06:00
1 parent dfaab8ba4c
commit b3bee2d407
13 files changed
+2121 -35

No files matched your search

@@ -42,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -1056,6 +1057,241 @@ class CodeArtifactNpmDataPlaneTest {
any(), any(), any());
}
/**
* {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument} is only ever reached for
* the exact bare-packument shape {@link #aPlainPackageMetadataGetNeverConsultsTheDownloadGuard}
* already exercises against the download guard; here it actually has something to merge, and
* the merged document is served directly, never reaching Verdaccio at all.
*/
@Test
void aBarePackumentGetServesTheExternalConnectionImportersMergedDocumentWithoutProxying() throws Exception {
AtomicReference<Boolean> upstreamReceivedRequest = new AtomicReference<>(false);
upstream = vertx.createHttpServer()
.requestHandler(request -> {
upstreamReceivedRequest.set(true);
request.response().setStatusCode(200).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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
ObjectNode merged = JSON.createObjectNode().put("name", "my-pkg");
when(externalConnectionImporter.mergedPackument("us-east-1", DOMAIN, "000000000000", REPOSITORY,
NPM_REPOSITORY_ID, null, "my-pkg", true)).thenReturn(Optional.of(merged));
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token");
assertEquals(200, response.statusCode());
assertEquals("application/json", response.headers().get("content-type"));
assertEquals(merged, JSON.readTree(response.body()));
assertEquals(false, upstreamReceivedRequest.get());
}
/**
* Raised by Greptile's review: a real {@code npm install} sends {@code pacote}'s own corgi-
* preferring {@code Accept}, confirmed against its source, and must keep resolving the real
* registry's cheaper abbreviated form; a bare GET with no {@code Accept} header at all (what
* the sibling test above sends, and what a bare {@code curl} sends) is treated as wanting the
* full form instead, confirmed live against the real registry's own default.
*/
@Test
void aBarePackumentGetWithACorgiAcceptHeaderAsksForTheAbbreviatedForm() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
getWithAccept("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*");
verify(externalConnectionImporter).mergedPackument("us-east-1", DOMAIN, "000000000000", REPOSITORY,
NPM_REPOSITORY_ID, null, "my-pkg", false);
}
/**
* The same bare-packument shape, scoped: the namespace has to reach {@code mergedPackument}
* decoded, the same {@code %2F}/{@code %2f} handling every other native route here already
* applies before calling into {@code CodeArtifactService}.
*/
@Test
void aBarePackumentGetOfAScopedPackageDecodesTheNamespaceBeforeMerging() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@myscope%2fmy-pkg",
"good-token");
assertEquals(200, response.statusCode());
verify(externalConnectionImporter).mergedPackument("us-east-1", DOMAIN, "000000000000", REPOSITORY,
NPM_REPOSITORY_ID, "myscope", "my-pkg", true);
}
/**
* A registry meta route ({@code /-/all}, a dist-tags update, and so on) must never be mistaken
* for a one-segment package name: the registry itself reserves the whole {@code -} prefix, so
* nothing here ever merges or imports for it.
*/
@Test
void aRegistryMetaRouteIsNeverTreatedAsABarePackumentGet() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/-/all", "good-token");
assertEquals(200, response.statusCode());
verify(externalConnectionImporter, never()).mergedPackument(any(), any(), any(), any(), any(), any(), any(),
anyBoolean());
}
/**
* A tarball download missing from Verdaccio attempts an external-connection import first, the
* same cache-miss trigger {@code CodeArtifactNuGetController} already uses, before proxying:
* the version is read back out of the one {@code <bareName>-<version>.tgz} shape {@link
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} itself always synthesizes.
*/
@Test
void aTarballDownloadMissingLocallyAttemptsAnExternalConnectionImportBeforeProxying() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).end("tarball bytes"))
.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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
when(verdaccioClient.packageVersionExists(NPM_REPOSITORY_ID, DOMAIN, REPOSITORY, null, "my-pkg", "1.0.0"))
.thenReturn(false);
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg/-/my-pkg-1.0.0.tgz",
"good-token");
assertEquals(200, response.statusCode());
verify(externalConnectionImporter).tryImportAsset("us-east-1", DOMAIN, "000000000000", REPOSITORY,
NPM_REPOSITORY_ID, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz");
}
@Test
void aTarballDownloadAlreadyPresentLocallyNeverAttemptsAnExternalConnectionImport() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).end("tarball bytes"))
.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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
when(verdaccioClient.packageVersionExists(NPM_REPOSITORY_ID, DOMAIN, REPOSITORY, null, "my-pkg", "1.0.0"))
.thenReturn(true);
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg/-/my-pkg-1.0.0.tgz",
"good-token");
assertEquals(200, response.statusCode());
verify(externalConnectionImporter, never()).tryImportAsset(any(), any(), any(), any(), any(), any(), any(),
any(), any());
}
/**
* A tarball filename that does not fit the {@code <bareName>-<version>.tgz} shape this
* importer itself always synthesizes (a real local publish's own, differently-named tarball)
* is left alone entirely: there is no version to read back out of it for an import attempt,
* the same reasoning {@link CodeArtifactNpmExternalConnectionImporter}'s own javadoc gives for
* never guessing one.
*/
@Test
void aTarballFilenameNotMatchingTheSynthesizedShapeNeverAttemptsAnExternalConnectionImport() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(200).end("tarball bytes"))
.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);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, true);
HttpResponse response = get("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg/-/bundle.tgz",
"good-token");
assertEquals(200, response.statusCode());
verify(externalConnectionImporter, never()).tryImportAsset(any(), any(), any(), any(), any(), any(), any(),
any(), any());
verify(verdaccioClient, never()).packageVersionExists(any(), any(), any(), any(), any(), any());
}
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient)
throws Exception {
startDataPlane(service, verdaccioClient, true);
@@ -1063,12 +1299,25 @@ class CodeArtifactNpmDataPlaneTest {
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient,
boolean codeArtifactEnabled) throws Exception {
// A fresh, unstubbed mock: Mockito's own default answer for an unstubbed Optional-returning
// method is Optional.empty(), which every test here that never configures it relies on to
// mean "nothing to merge, proceed with the ordinary proxy" exactly as if this importer did
// not exist.
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter =
mock(CodeArtifactNpmExternalConnectionImporter.class);
startDataPlane(service, verdaccioClient, externalConnectionImporter, codeArtifactEnabled);
}
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient,
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter,
boolean codeArtifactEnabled) throws Exception {
when(verdaccioClient.publicUrl(DOMAIN, REPOSITORY)).thenReturn("http://localhost:4566/codeartifact/npm/"
+ DOMAIN + "/" + REPOSITORY + "/");
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
when(serviceConfigAccess.isEnabled("codeartifact")).thenReturn(codeArtifactEnabled);
Router router = Router.router(vertx);
new CodeArtifactNpmDataPlane(service, verdaccioClient, serviceConfigAccess, vertx, new ObjectMapper())
new CodeArtifactNpmDataPlane(service, verdaccioClient, externalConnectionImporter, serviceConfigAccess,
vertx, new ObjectMapper())
.register(router);
dataPlane = vertx.createHttpServer().requestHandler(router)
.listen(0, "127.0.0.1")
@@ -1079,6 +1328,10 @@ class CodeArtifactNpmDataPlaneTest {
return request(HttpMethod.GET, path, bearerToken, null);
}
private HttpResponse getWithAccept(String path, String bearerToken, String accept) throws Exception {
return request(HttpMethod.GET, path, bearerToken, null, accept);
}
private HttpResponse put(String path, String bearerToken, String body) throws Exception {
return request(HttpMethod.PUT, path, bearerToken, body);
}
@@ -1095,6 +1348,11 @@ class CodeArtifactNpmDataPlaneTest {
* leaves exactly one blocking {@code .get()} at the very end.
*/
private HttpResponse request(HttpMethod method, String path, String bearerToken, String body) throws Exception {
return request(method, path, bearerToken, body, null);
}
private HttpResponse request(HttpMethod method, String path, String bearerToken, String body, String accept)
throws Exception {
RequestOptions options = new RequestOptions()
.setHost("127.0.0.1")
.setPort(dataPlane.actualPort())
@@ -1105,6 +1363,9 @@ class CodeArtifactNpmDataPlaneTest {
if (bearerToken != null) {
req.putHeader("Authorization", "Bearer " + bearerToken);
}
if (accept != null) {
req.putHeader("Accept", accept);
}
return body != null ? req.send(body) : req.send();
})
.compose(resp -> resp.body().map(buffer -> {
@@ -0,0 +1,250 @@
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.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Retains a real npm package version from the real, live {@code public:npmjs} registry (not a
* local fake), through the native per-format route, the way a real {@code npm install} would.
* {@code is-even} is picked because it is tiny, stable, and unlikely to ever need republishing.
* A genuine network dependency, unlike every other sidecar-backed test here, which only ever
* talks to a container Floci itself started; see {@code CodeArtifactNpmExternalConnectionImporterTest}
* for the mocked, deterministic coverage of the merge/claim/fence logic this test does not
* re-exercise.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactNpmExternalConnectionDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "npm-external-connection-domain";
private static final String REPO = "npm-external-connection-repo";
private static final String BLOCKED_REPO = "npm-external-connection-blocked-repo";
private static final String PACKAGE_NAME = "is-even";
private static final String VERSION = "1.0.0";
private static String bearerToken;
@BeforeAll
static void setUp() {
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.npm-image");
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void createDomainRepositoriesConnectionAndToken() {
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);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
+ "&external-connection=public:npmjs")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
+ "&external-connection=public:npmjs")
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
/**
* A bare packument read merges the real registry's own versions in, rewriting {@code
* dist.tarball} to this repository's own proxy URL, without ever fetching the real tarball
* itself yet: {@code assetSizeBytes} must stay exactly where it started.
*/
@Test
@Order(1)
void aBarePackumentReadMergesTheRealVersionWithoutRetainingItsTarballYet() throws Exception {
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
String body = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.extract().asString();
JsonNode packument = new ObjectMapper().readTree(body);
JsonNode versionDoc = packument.path("versions").path(VERSION);
assertEquals(VERSION, versionDoc.path("version").asText());
String tarballUrl = versionDoc.path("dist").path("tarball").asText();
assertThat(tarballUrl, startsWith("http"));
assertThat(tarballUrl, containsString("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/"));
assertEquals(assetSizeBytesBefore, describeDomainAssetSizeBytes());
}
@Test
@Order(2)
void fetchingTheMergedTarballUrlRetainsItFromTheRealNpmjsConnectionAndCountsItsBytes() {
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME + "/-/" + PACKAGE_NAME + "-"
+ VERSION + ".tgz")
.then().statusCode(200)
.extract().asByteArray();
// A real .tgz is a real gzip stream: 0x1f 0x8b magic bytes, not asserting exact content
// since the real artifact is out of this test's control.
assertEquals((byte) 0x1f, fetched[0]);
assertEquals((byte) 0x8b, fetched[1]);
assertThat(fetched.length, greaterThan(50));
long assetSizeBytesAfter = describeDomainAssetSizeBytes();
assertEquals(assetSizeBytesBefore + fetched.length, assetSizeBytesAfter);
}
@Test
@Order(3)
void refetchingTheSameTarballServesItWithoutRetainingItAgain() {
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME + "/-/" + PACKAGE_NAME + "-"
+ VERSION + ".tgz")
.then().statusCode(200)
.extract().asByteArray();
assertEquals((byte) 0x1f, fetched[0]);
assertEquals(assetSizeBytesBefore, describeDomainAssetSizeBytes());
}
@Test
@Order(4)
void upstreamBlockPreventsBothTheMergeAndTheRetention() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"ALLOW\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=npm"
+ "&package=" + PACKAGE_NAME)
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + BLOCKED_REPO + "/" + PACKAGE_NAME)
.then().statusCode(404);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + BLOCKED_REPO + "/" + PACKAGE_NAME + "/-/" + PACKAGE_NAME
+ "-" + VERSION + ".tgz")
.then().statusCode(404);
}
@Test
@Order(5)
void aPackageTheRealRegistryDoesNotHaveIsNeverMerged() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO
+ "/floci-this-package-definitely-does-not-exist-on-npmjs")
.then().statusCode(404);
}
/**
* Confirms the fix against the real sidecar's own retained version from {@link
* #fetchingTheMergedTarballUrlRetainsItFromTheRealNpmjsConnectionAndCountsItsBytes}, not a
* mock, the same way {@code CodeArtifactNuGetExternalConnectionDockerIntegrationTest} proves
* its own equivalent origin-reporting fix.
*/
@Test
@Order(6)
void aRetainedVersionReportsAnExternalOriginNotInternal() {
given().header("Authorization", AUTH)
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm&package="
+ PACKAGE_NAME)
.then().statusCode(200)
.body("versions[0].version", equalTo(VERSION))
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
.body("versions[0].origin.domainEntryPoint.externalConnectionName", equalTo("public:npmjs"));
}
/**
* Found by Greptile's review: a retained version used to be written as a minimal document
* with no {@code dependencies}/{@code engines}/{@code scripts}, and its readme was never
* captured at all, so {@code GetPackageVersionReadme} 404ed on an otherwise fully retained
* version. Confirms both fixes against the real sidecar's own stored version from {@link
* #fetchingTheMergedTarballUrlRetainsItFromTheRealNpmjsConnectionAndCountsItsBytes}, reading
* it back the same way a real {@code npm install} and {@code aws codeartifact
* get-package-version-readme} would, not a mock.
*/
@Test
@Order(7)
void aRetainedVersionKeepsItsRealDependenciesAndReadme() throws Exception {
String body = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.extract().asString();
JsonNode versionDoc = new ObjectMapper().readTree(body).path("versions").path(VERSION);
assertThat(versionDoc.path("dependencies").has("is-odd"), equalTo(true));
assertThat(versionDoc.path("engines").has("node"), equalTo(true));
given().header("Authorization", AUTH)
.get("/v1/package/version/readme?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm&package="
+ PACKAGE_NAME + "&version=" + VERSION)
.then().statusCode(200)
.body("readme", startsWith("# is-even"));
}
/**
* Found by Greptile's review: {@code DisposePackageVersions} deletes a version's real
* Verdaccio content outright, so a bare packument read could not tell that apart from a
* version it had simply never retained, and would merge it straight back in from the real
* registry's own still-unaware listing. A distinct, never-before-retained version
* ({@code 0.1.2}) is retained here specifically to dispose of, so it never disturbs the
* other tests in this class that share {@link #PACKAGE_NAME}'s {@link #VERSION}.
*/
@Test
@Order(8)
void aDisposedVersionIsNeverMergedBackIn() throws Exception {
String disposedVersion = "0.1.2";
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME + "/-/" + PACKAGE_NAME + "-"
+ disposedVersion + ".tgz")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"" + disposedVersion + "\"]}")
.post("/v1/package/versions/dispose?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm&package="
+ PACKAGE_NAME)
.then().statusCode(200)
.body("successfulVersions['" + disposedVersion + "'].status", equalTo("Disposed"));
String body = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.extract().asString();
JsonNode packument = new ObjectMapper().readTree(body);
assertThat(packument.path("versions").has(disposedVersion), equalTo(false));
assertThat(packument.path("versions").has(VERSION), equalTo(true));
}
private static long describeDomainAssetSizeBytes() {
return given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
}
}
@@ -0,0 +1,636 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository;
import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link CodeArtifactNpmExternalConnectionImporter}'s own decision logic: when it attempts a real
* external-connection fetch at all, and what it writes back or merges. {@link
* VerdaccioSidecarClient} and {@link NpmExternalConnectionClient} are both mocked, so no real
* network or Verdaccio call ever happens here; their own wire contracts have their own tests.
*/
class CodeArtifactNpmExternalConnectionImporterTest {
private static final String REGION = "us-east-1";
private static final String DOMAIN = "dom";
private static final String OWNER = "123456789012";
private static final String REPOSITORY = "repo";
private static final String REPO_ID = "repo-id";
private static final String PACKAGE_NAME = "widget";
private static final String VERSION = "1.0.0";
private static final String ASSET_NAME = "widget-1.0.0.tgz";
private static final String BASE_URL = "http://localhost:4566/codeartifact/npm/dom/repo/";
private static final byte[] TARBALL_CONTENT = "tarball-content".getBytes();
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
private static final long EPISODE_ID = 7L;
private CodeArtifactService service;
private VerdaccioSidecarClient verdaccio;
private NpmExternalConnectionClient externalConnectionClient;
private CodeArtifactNpmExternalConnectionImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
verdaccio = mock(VerdaccioSidecarClient.class);
externalConnectionClient = mock(NpmExternalConnectionClient.class);
importer = new CodeArtifactNpmExternalConnectionImporter(service, verdaccio, externalConnectionClient,
new ObjectMapper());
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of(new ExternalConnection("public:npmjs", "npm", "AVAILABLE")));
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString())).thenReturn(false);
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString())).thenReturn(42L);
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString())).thenReturn(99L);
// Unstubbed by default: the claim succeeds, matching the common case of a first or
// same-connection retry. Tests for a conflicting claim override this per call.
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyString(), anyLong()))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
// Unstubbed by default: Verdaccio does not have the version yet, matching the data plane's
// own pre-check always calling tryImportAsset only on a miss.
when(verdaccio.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(false);
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
when(verdaccio.ensureReady(REPO_ID, BASE_URL)).thenReturn(BASE_URL);
when(verdaccio.publicUrl(DOMAIN, REPOSITORY)).thenReturn(BASE_URL);
}
@Test
void tryImportAssetImportsFromExternalConnectionWhenNotFoundLocally() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
// The real registry is reachable and genuinely has no readme for this package (unlike
// Optional.empty(), which models the full fetch itself failing, see
// tryImportAssetReturnsFalseAndRetriesLaterWhenTheFullPackumentFetchFails below).
ObjectMapper mapper = new ObjectMapper();
ObjectNode full = mapper.createObjectNode();
full.putObject("versions").putObject(VERSION);
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
full))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("npm"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq(ASSET_NAME), eq(TARBALL_CONTENT), any());
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, 42L);
verify(service).recordPublishedPackageVersionReadme(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, "", 99L);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
/**
* Raised by hectorvent's review: when the tarball fetch works but the full packument fetch
* fails, retaining anyway with the minimal document {@code storeRetainedVersionAsset} falls
* back to would lose this version's dependencies/engines/scripts for good, since the merge
* skips it from then on ({@code versions.has(version)}). Returning {@code false} here instead
* abandons the attempt, writing nothing, so a later download retries the full fetch.
*/
@Test
void tryImportAssetReturnsFalseAndRetriesLaterWhenTheFullPackumentFetchFails() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.empty());
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service, never()).recordPublishedPackageVersionReadme(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
/**
* The real registry's own full-form version document (dependencies/engines/scripts) and its
* package-level readme are both reused verbatim through to the sidecar write and the readme
* capture, rather than building a minimal document or recording an empty readme when the real
* registry actually has both.
*/
@Test
void tryImportAssetPreservesTheRealVersionDocumentAndReadme() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
ObjectMapper mapper = new ObjectMapper();
ObjectNode full = mapper.createObjectNode();
full.put("readme", "# Widget\nA real readme.");
ObjectNode versionDoc = full.putObject("versions").putObject(VERSION);
versionDoc.putObject("dependencies").put("left-pad", "^1.0.0");
versionDoc.putArray("scripts");
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
full))));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertTrue(imported);
verify(service).recordPublishedPackageVersionReadme(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, "# Widget\nA real readme.", 99L);
// retainAssetUnderVersionFence's own write happens through a Runnable this test cannot
// inspect without invoking it; the sidecar wire contract for storeRetainedVersionAsset
// itself (dependencies preserved, dist rewritten) is VerdaccioSidecarClient's own test's
// job, not this one's. What this test owns is confirming the real version document was
// actually fetched and handed to that call at all, which the readme capture above already
// proves happened on the very same code path.
}
@Test
void tryImportAssetReturnsFalseWhenNoNpmExternalConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of());
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void tryImportAssetReturnsFalseWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME))
.thenReturn(true);
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void tryImportAssetReturnsFalseWithoutFinishingWhenTheClaimIsRefused() {
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME,
VERSION, "public:npmjs", 42L))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(verdaccio, never()).packageVersionExists(anyString(), anyString(), anyString(), any(), anyString(),
anyString());
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
}
@Test
void tryImportAssetReturnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() {
when(verdaccio.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(true);
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.of("public:npmjs"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
/**
* {@code verdaccio.packageVersionExists} alone proves nothing about who put the content there:
* a real client's own direct publish can land between this attempt's own claim and this
* existence check, the same race {@code CodeArtifactNuGetExternalConnectionImporter}'s own
* test of the same name guards against.
*/
@Test
void tryImportAssetDoesNotMislabelAVersionADirectPushWroteDuringTheRaceAsExternallyRetained() {
when(verdaccio.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
.thenReturn(true);
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.empty());
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString());
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void tryImportAssetReturnsFalseAndFinishesWhenTheRealRegistryDoesNotHaveIt() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.empty());
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void tryImportAssetFetchThatThrowsIsTreatedLikeAMissingPackageRatherThanPropagating() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenThrow(new IllegalStateException("public registry unreachable"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void tryImportAssetReturnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
ObjectMapper mapper = new ObjectMapper();
ObjectNode full = mapper.createObjectNode();
full.putObject("versions").putObject(VERSION);
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
full))));
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertFalse(imported);
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void mergedPackumentReturnsEmptyWhenNoNpmExternalConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of());
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
verify(externalConnectionClient, never()).fetchPackument(anyString(), any(), anyString());
}
@Test
void mergedPackumentReturnsEmptyWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME))
.thenReturn(true);
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
verify(externalConnectionClient, never()).fetchPackument(anyString(), any(), anyString());
}
@Test
void mergedPackumentReturnsEmptyWhenTheRealRegistryDoesNotHaveThePackage() {
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
}
@Test
void mergedPackumentFetchThatThrowsIsTreatedAsUnresolvedRatherThanPropagating() {
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenThrow(new IllegalStateException("public registry unreachable"));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
}
/**
* Raised by Greptile's review: {@code ensureReady} can start a fresh container under a
* repository id that {@code DeleteRepository} already released while the real registry fetch
* above was still in flight, since nothing here held any lock across that real network round
* trip. Re-checking the repository still exists right after that fetch, before this method
* ever touches the sidecar, catches exactly that case.
*/
@Test
void mergedPackumentReturnsEmptyWhenTheRepositoryWasDeletedWhileTheExternalFetchWasInFlight() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode external = mapper.createObjectNode();
external.putObject("versions").putObject("2.0.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of(new ExternalConnection("public:npmjs", "npm", "AVAILABLE")));
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY))
.thenReturn(repository)
.thenThrow(new AwsException("ResourceNotFoundException", "no such repository", 404));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
verify(verdaccio, never()).ensureReady(anyString(), anyString());
}
/**
* A version the real registry names but Verdaccio does not have yet is added with its {@code
* dist.tarball} rewritten to this repository's own URL, under the exact {@code
* <bareName>-<version>.tgz} shape {@code CodeArtifactNpmDataPlane}'s own download-side import
* trigger expects back, while {@code dist.shasum}/{@code dist.integrity} are kept exactly as
* the real registry declared them.
*/
@Test
void mergedPackumentAddsANewVersionRewritingItsTarballToThisRepositorysOwnUrl() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode external = mapper.createObjectNode();
ObjectNode versions = external.putObject("versions");
ObjectNode versionDoc = versions.putObject("2.0.0");
versionDoc.put("name", "widget");
versionDoc.put("version", "2.0.0");
ObjectNode dist = versionDoc.putObject("dist");
dist.put("shasum", "real-shasum");
dist.put("integrity", "sha512-real");
dist.put("tarball", "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz");
external.putObject("dist-tags").put("latest", "2.0.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isPresent());
JsonNode mergedVersion = merged.get().path("versions").path("2.0.0");
assertEquals(BASE_URL + "widget/-/widget-2.0.0.tgz", mergedVersion.path("dist").path("tarball").asText());
assertEquals("real-shasum", mergedVersion.path("dist").path("shasum").asText());
assertEquals("sha512-real", mergedVersion.path("dist").path("integrity").asText());
assertEquals("2.0.0", merged.get().path("dist-tags").path("latest").asText());
}
@Test
void mergedPackumentWithCorgiFalseNeverFetchesTheFullPackument() {
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME)).thenReturn(
Optional.empty());
importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, false);
verify(externalConnectionClient).fetchPackument("public:npmjs", null, PACKAGE_NAME);
verify(externalConnectionClient, never()).fetchFullPackument(anyString(), any(), anyString());
}
/**
* Raised by Greptile's review: the abbreviated form {@code npm install} itself sends never
* carries a package's {@code readme} at all, so a request that actually asked for the full
* document ({@code npm view <pkg> readme}-style commands) must fetch the full form instead,
* and the merge has to carry the real readme through rather than only {@code versions}/
* {@code dist-tags}.
*/
@Test
void mergedPackumentWithFullMetadataCopiesThePackageLevelReadme() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode external = mapper.createObjectNode();
external.put("readme", "# Widget\nA real readme.");
ObjectNode versionDoc = external.putObject("versions").putObject("2.0.0");
versionDoc.putObject("dist").put("tarball", "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz");
external.putObject("dist-tags").put("latest", "2.0.0");
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, true);
assertTrue(merged.isPresent());
assertEquals("# Widget\nA real readme.", merged.get().path("readme").asText());
verify(externalConnectionClient, never()).fetchPackument(anyString(), any(), anyString());
}
/** A readme already set locally (a real local publish's own) is never overwritten. */
@Test
void mergedPackumentWithFullMetadataNeverOverridesAnAlreadySetLocalReadme() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode local = mapper.createObjectNode();
local.put("readme", "local readme");
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.of(local));
ObjectNode external = mapper.createObjectNode();
external.put("readme", "external readme");
external.putObject("versions");
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, true);
assertTrue(merged.isEmpty());
}
/**
* Raised by Greptile's review: Verdaccio always points a fresh package's {@code dist-tags.
* latest} at whichever version was retained most recently (confirmed live, nothing a
* retention write sends can suppress it), so a local tag pointing at a version with a
* confirmed external-retention claim is not a deliberate local choice at all and must still
* be replaced once the real registry names a different version for that same tag.
*/
@Test
void mergedPackumentOverridesALocalDistTagThatPointsAtAnExternallyRetainedVersion() throws Exception {
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME,
"1.0.0")).thenReturn(Optional.of("public:npmjs"));
ObjectMapper mapper = new ObjectMapper();
ObjectNode local = mapper.createObjectNode();
ObjectNode localVersions = local.putObject("versions");
localVersions.putObject("1.0.0").putObject("dist").put("tarball", BASE_URL + "widget/-/widget-1.0.0.tgz");
local.putObject("dist-tags").put("latest", "1.0.0");
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.of(local));
ObjectNode external = mapper.createObjectNode();
ObjectNode externalVersions = external.putObject("versions");
externalVersions.putObject("1.0.0");
externalVersions.putObject("2.0.0").putObject("dist")
.put("tarball", "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz");
external.putObject("dist-tags").put("latest", "2.0.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isPresent());
assertEquals("2.0.0", merged.get().path("dist-tags").path("latest").asText());
}
/**
* The exact opposite of {@link
* #mergedPackumentOverridesALocalDistTagThatPointsAtAnExternallyRetainedVersion}: a local tag
* pointing at a version with no retained-origin claim at all is a genuine local publish's own
* deliberate choice, and must never be replaced by the external source's own idea of it.
*/
@Test
void mergedPackumentNeverOverridesALocalDistTagThatPointsAtAGenuinelyLocalVersion() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode local = mapper.createObjectNode();
ObjectNode localVersions = local.putObject("versions");
localVersions.putObject("1.0.0").putObject("dist").put("tarball", BASE_URL + "widget/-/widget-1.0.0.tgz");
local.putObject("dist-tags").put("latest", "1.0.0");
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.of(local));
ObjectNode external = mapper.createObjectNode();
ObjectNode externalVersions = external.putObject("versions");
externalVersions.putObject("1.0.0");
externalVersions.putObject("2.0.0").putObject("dist")
.put("tarball", "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz");
external.putObject("dist-tags").put("latest", "2.0.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isPresent());
assertEquals("1.0.0", merged.get().path("dist-tags").path("latest").asText());
}
/**
* Raised by Greptile's review: {@code DisposePackageVersions} deletes a version's real
* Verdaccio content outright, so {@code versions.has(version)} alone cannot tell a disposed
* version apart from a genuinely new one the real registry still names; without excluding it,
* an unpinned {@code npm install} could select a disposed version as {@code latest} only to
* have the download itself correctly, but confusingly, refused afterward.
*/
@Test
void mergedPackumentNeverReAddsADisposedVersionOrPointsLatestAtIt() throws Exception {
doThrow(new AwsException("ResourceNotFoundException", "Package version '1.0.0' was not found.", 404))
.when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, REPOSITORY, "npm",
null, PACKAGE_NAME, "1.0.0", REPO_ID);
ObjectMapper mapper = new ObjectMapper();
ObjectNode external = mapper.createObjectNode();
ObjectNode versions = external.putObject("versions");
versions.putObject("1.0.0").putObject("dist")
.put("tarball", "https://registry.npmjs.org/widget/-/widget-1.0.0.tgz");
versions.putObject("2.0.0").putObject("dist")
.put("tarball", "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz");
external.putObject("dist-tags").put("latest", "1.0.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isPresent());
assertFalse(merged.get().path("versions").has("1.0.0"));
assertTrue(merged.get().path("versions").has("2.0.0"));
assertFalse(merged.get().path("dist-tags").has("latest"));
}
/** A version already known locally is never overwritten by the external source's own entry. */
@Test
void mergedPackumentNeverOverridesAVersionAlreadyKnownLocally() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode local = mapper.createObjectNode();
ObjectNode localVersions = local.putObject("versions");
ObjectNode localVersionDoc = localVersions.putObject("1.0.0");
localVersionDoc.putObject("dist").put("tarball", BASE_URL + "widget/-/widget-1.0.0.tgz");
local.putObject("dist-tags").put("latest", "1.0.0");
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.of(local));
ObjectNode external = mapper.createObjectNode();
ObjectNode externalVersionDoc = external.putObject("versions").putObject("1.0.0");
externalVersionDoc.putObject("dist").put("tarball", "https://registry.npmjs.org/widget/-/widget-1.0.0.tgz");
external.putObject("dist-tags").put("latest", "0.9.0");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
}
/** A dist-tag naming a version this merge does not actually know about is never added. */
@Test
void mergedPackumentNeverAddsADistTagForAVersionItDoesNotKnow() throws Exception {
ObjectMapper mapper = new ObjectMapper();
ObjectNode external = mapper.createObjectNode();
external.putObject("versions");
external.putObject("dist-tags").put("latest", "9.9.9");
when(externalConnectionClient.fetchPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
external))));
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, false);
assertTrue(merged.isEmpty());
}
}
@@ -78,7 +78,7 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
// CodeArtifactService method (see its own javadoc for why), so this mock is what every
// test configures instead.
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
}
@@ -91,8 +91,8 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("nuget"),
isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(bagetter), eq(REPO_ID),
eq("widget.1.0.0.nupkg"), eq(NUPKG_CONTENT));
isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq("widget.1.0.0.nupkg"), eq(NUPKG_CONTENT), any());
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, 42L);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
@@ -151,8 +151,8 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
assertTrue(imported);
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any());
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, true);
}
@@ -189,8 +189,8 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any());
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
@@ -212,7 +212,7 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
@@ -4484,6 +4484,44 @@ class CodeArtifactServiceTest {
assertEquals("1.0.0", result.defaultDisplayVersion());
}
/**
* Raised by Greptile's review of npm's own external-connection work: Verdaccio always points
* {@code dist-tags.latest} at whichever version was retained most recently, with no way for a
* retention write to suppress that default, so {@code preferredDisplayVersion} can name a
* version that was never a deliberate local choice at all. Unlike {@link
* #listPackageVersionsDefaultDisplayVersionPrefersNpmDistTagLatestOverMostRecentlyPublished},
* where the preferred version has no retained-origin claim and so is correctly honored even
* though it is not the most recently published, this version's claim (confirmed real via
* {@link CodeArtifactService#claimRetainedVersionOrigin}, the same mechanism a genuine {@code
* public:npmjs} retention uses) means it must be ignored here instead, falling back to
* whichever version really was published most recently.
*/
@Test
void listPackageVersionsDefaultDisplayVersionIgnoresDistTagLatestWhenItPointsAtAnExternallyRetainedVersion() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("npm");
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", null, "my-pkg");
CodeArtifactService.RetainedVersionOriginClaimOutcome outcome = service.claimRetainedVersionOrigin(REGION,
"dom", null, "repo", "npm", null, "my-pkg", "1.0.0", "public:npmjs", fence);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "npm", null, "my-pkg", "1.0.0",
outcome.episodeId(), true);
when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000)),
new RepositorySidecarManager.PackageVersionTimestamp("2.0.0", Instant.ofEpochSecond(2000))));
// Simulates Verdaccio's own forced default: real retention writes can never suppress it,
// confirmed live against the pinned image, so this is exactly what a genuine retention of
// 1.0.0 would have left behind regardless of 2.0.0 being the real, more recent version.
when(verdaccioClient.preferredDisplayVersion(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"))).thenReturn(Optional.of("1.0.0"));
CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null,
"repo", "npm", null, "my-pkg", null, null, null, null, null);
assertEquals("2.0.0", result.defaultDisplayVersion());
}
@Test
void listPackageVersionsRejectsAFormatAwsDoesNotSupport() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -0,0 +1,168 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The wire contract towards the real public npm registry, exercised against a local {@code
* HttpServer} fake standing in for it, named {@code fake} in these tests rather than the real
* {@code public:npmjs} connection name.
*/
class NpmExternalConnectionClientTest {
private HttpServer server;
private NpmExternalConnectionClient client;
@BeforeEach
void startServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.start();
Map<String, String> baseUrls = Map.of("fake", "http://127.0.0.1:" + server.getAddress().getPort());
client = new NpmExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(),
baseUrls);
}
@AfterEach
void stopServer() {
server.stop(0);
}
@Test
void fetchPackumentReturnsTheRealBytesOnA200ForAnUnscopedPackage() throws IOException {
byte[] content = "{\"name\":\"widget\"}".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NpmExternalConnectionClient.FetchedAsset> result = client.fetchPackument("fake", null, "widget");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
/**
* Confirmed live against the real registry: a scoped package's single-package resource needs
* its scope separator percent-encoded as {@code %2F} to reach the package itself rather than a
* sub-path of it ({@code @scope/name} with a literal slash 404s this exact endpoint there).
*/
@Test
void fetchPackumentEscapesTheScopeSeparatorForAScopedPackage() throws IOException {
byte[] content = "{\"name\":\"@scope/widget\"}".getBytes(StandardCharsets.UTF_8);
AtomicReference<String> rawPath = new AtomicReference<>();
// Registered at the decoded path: com.sun.net.httpserver.HttpServer matches a context
// against the exchange's own decoded URI.getPath(), not its raw, still-percent-encoded
// form, so a literal slash would reach this same context just as easily; the real
// assertion below is on the raw path this handler actually received, not on which context
// matched.
server.createContext("/@scope/widget", exchange -> {
rawPath.set(exchange.getRequestURI().getRawPath());
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NpmExternalConnectionClient.FetchedAsset> result = client.fetchPackument("fake", "scope", "widget");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
assertEquals("/@scope%2Fwidget", rawPath.get());
}
@Test
void fetchPackumentReturnsEmptyOnA404() throws IOException {
server.createContext("/widget", exchange -> respondEmpty(exchange, 404));
Optional<NpmExternalConnectionClient.FetchedAsset> result = client.fetchPackument("fake", null, "widget");
assertFalse(result.isPresent());
}
@Test
void fetchPackumentReturnsEmptyForAnUnknownConnectionName() {
Optional<NpmExternalConnectionClient.FetchedAsset> result =
client.fetchPackument("public:npmjs", null, "widget");
assertFalse(result.isPresent());
}
@Test
void fetchTarballReturnsTheRealBytesOnA200ForAnUnscopedPackage() throws IOException {
byte[] content = "tarball-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/-/widget-1.0.0.tgz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NpmExternalConnectionClient.FetchedAsset> result =
client.fetchTarball("fake", null, "widget", "1.0.0");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
/**
* Confirmed live against the real registry: unlike the packument path, the tarball path keeps
* a literal {@code /} between the scope and the bare name, and the filename itself never
* carries the scope at all.
*/
@Test
void fetchTarballUsesALiteralSlashAndTheBareNameForAScopedPackage() throws IOException {
byte[] content = "tarball-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/@scope/widget/-/widget-1.0.0.tgz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NpmExternalConnectionClient.FetchedAsset> result =
client.fetchTarball("fake", "scope", "widget", "1.0.0");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchTarballReturnsEmptyOnA404() throws IOException {
server.createContext("/widget/-/widget-1.0.0.tgz", exchange -> respondEmpty(exchange, 404));
Optional<NpmExternalConnectionClient.FetchedAsset> result =
client.fetchTarball("fake", null, "widget", "1.0.0");
assertFalse(result.isPresent());
}
@Test
void fetchTarballReturnsEmptyForAnUnknownConnectionName() {
Optional<NpmExternalConnectionClient.FetchedAsset> result =
client.fetchTarball("public:npmjs", null, "widget", "1.0.0");
assertFalse(result.isPresent());
}
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
exchange.sendResponseHeaders(status, -1);
exchange.close();
}
}