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

+23 -11
View File
@@ -83,8 +83,11 @@ retained version's own origin checked against any later asset request for the sa
(rejecting one that would mix in a different connection's bytes), and a direct `mvn deploy` of a
version already present in the connection rejected with `ConflictException`. See the
upstream-resolution limitation further down for exactly what this does not yet cover (a
repository-to-repository `upstreams` chain, for any format including Maven; npm/pypi/nuget's own
external connections).
repository-to-repository `upstreams` chain, for any format including Maven). npm's own `public:npmjs`
external connection and NuGet's own `public:nuget-org` one resolve the same way, each against its
own format's one real public connection and documented rules; see their own repository endpoint
sections and the known-limitations entry below for exactly how. pypi's own external connection does
not yet.
`PublishPackageVersion` creates a package version in the `Unfinished` state when the `unfinished`
flag is set, and `Published` otherwise. While still `Unfinished`, publishing a new asset name is
@@ -340,11 +343,11 @@ state.
would mean isolating each sidecar on its own Docker network reachable only from Floci's own
process, a change that would need to apply uniformly across all four sidecar-backed formats, not
a one-off fix to any single proxy.
- **Only the Maven endpoint's own external connection actually resolves; nothing else does.**
- **The Maven, NuGet, and npm endpoints' own external connections resolve; pypi's does not.**
On real CodeArtifact, a repository with another repository configured as an upstream
(`UpdateRepository`'s `upstreams`) or with an `AssociateExternalConnection` to a public
repository serves packages from those sources too, not just its own. Floci's Maven endpoint
now does this for a direct external connection to one of the 5 real public Maven repositories
does this for a direct external connection to one of the 5 real public Maven repositories
(`public:maven-central`, `public:maven-clojars`, `public:maven-commonsware`,
`public:maven-googleandroid`, `public:maven-gradleplugins`): a GET/HEAD miss fetches and
retains the package version from the real public repository, following AWS's own documented
@@ -352,13 +355,22 @@ state.
name imported only on demand; a retained version's origin checked against any later asset
fetched for it, rejecting one from a different connection; `upstream: BLOCK` respected). A real
`mvn deploy` of a version already present in the external connection is also rejected (409),
matching AWS's documented publish-side behavior. None of this applies to a repository-to-
repository upstream (`UpdateRepository`'s `upstreams`, for any format including Maven, which is
a materially different mechanism, not yet built) or to npm, pypi, or nuget's own external
connections, which still 404 exactly as before: the pypi proxy's pypiserver container is
started with `--disable-fallback`, and the nuget proxy's BaGetter container with
`Mirror__Enabled=false`, specifically so neither ever silently redirects a missing package to
the real, public PyPI or nuget.org.
matching AWS's documented publish-side behavior. NuGet's own `public:nuget-org` external
connection works the same way, against its own one real public connection and its own
single-asset-per-version shape; a real `nuget push`/`dotnet nuget push` of a version already
present in the connection is rejected the same way. npm's own `public:npmjs` external connection
works differently, since `npm install <pkg>@<version>` never names a single version on the wire
the way Maven's GAV layout or NuGet's content route do, only the bare package: a packument read
merges the real registry's own versions and dist-tags into whatever this repository already
knows (never written back to Verdaccio itself, since its publish protocol has no way to record a
version's metadata without that version's real tarball bytes in the same call), and a tarball
download for a version not yet genuinely retained triggers the real fetch and retention, using
the same claim/fence/origin-tracking machinery. None of this applies to a repository-to-
repository upstream (`UpdateRepository`'s `upstreams`, for any format including Maven, NuGet,
and npm, which is a materially different mechanism, not yet built) or to pypi's own external
connection, which still 404s exactly as before: the pypi proxy's pypiserver container is started
with `--disable-fallback`, specifically so it never silently redirects a missing package to the
real, public PyPI.
- **Maven external-connection retention is the one place this emulator makes a real outbound
call to the public internet**, rather than only ever talking to a container it started itself.
An offline environment, or a real outage of the public repository being connected to, means a
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.core.exc.StreamConstraintsException;
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.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
@@ -71,6 +72,7 @@ public class CodeArtifactNpmDataPlane {
private final CodeArtifactService service;
private final VerdaccioSidecarClient verdaccioClient;
private final CodeArtifactNpmExternalConnectionImporter externalConnectionImporter;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient proxyClient;
@@ -80,9 +82,11 @@ public class CodeArtifactNpmDataPlane {
@Inject
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient,
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter,
ServiceConfigAccess serviceConfigAccess, Vertx vertx, ObjectMapper mapper) {
this.service = service;
this.verdaccioClient = verdaccioClient;
this.externalConnectionImporter = externalConnectionImporter;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
@@ -149,12 +153,45 @@ public class CodeArtifactNpmDataPlane {
context.request().pause();
String repoId = npmRepositoryId;
AuthorizationTokenScope tokenScope = scope.get();
Optional<PackageIdentity> packumentTarget = nativePackumentRequestTarget(context.request().method(),
npmRequest.rest());
if (packumentTarget.isPresent()) {
PackageIdentity identity = packumentTarget.get();
boolean fullMetadata = !acceptsCorgi(context.request().getHeader("Accept"));
vertx.<ObjectNode>executeBlocking(promise -> promise.complete(externalConnectionImporter.mergedPackument(
tokenScope.region(), npmRequest.domain(), tokenScope.owner(), npmRequest.repository(), repoId,
identity.namespace(), identity.packageName(), fullMetadata).orElse(null)), false).onComplete(
mergeResult -> {
if (mergeResult.succeeded() && mergeResult.result() != null) {
context.request().resume();
respondWithMergedPackument(context, mergeResult.result());
return;
}
proceedToProxy(context, npmRequest, repoId, tokenScope);
});
return;
}
proceedToProxy(context, npmRequest, repoId, tokenScope);
}
/**
* {@code packumentTarget}'s own fallback, and the only path for every request that isn't a
* bare packument GET to begin with: proxies straight to Verdaccio, importing a missing
* tarball from this repository's own npm external connection first (see {@link
* #tryImportMissingTarball}) when the requested download is one.
*/
private void proceedToProxy(RoutingContext context, NpmRequest npmRequest, String repoId,
AuthorizationTokenScope tokenScope) {
Optional<TarballDownloadRequest> tarballTarget = nativeTarballDownloadTarget(context.request().method(),
npmRequest.rest());
Optional<PackageIdentity> unpublishTarget = nativeUnpublishTarget(context.request().method(),
npmRequest.rest());
vertx.<String>executeBlocking(promise -> {
tarballTarget.ifPresent(target -> blockIfArchived(tokenScope, npmRequest, repoId, target));
tarballTarget.ifPresent(target -> {
tryImportMissingTarball(tokenScope, npmRequest, repoId, target);
blockIfArchived(tokenScope, npmRequest, repoId, target);
});
promise.complete(ensureBackendReady(repoId, npmRequest));
}).onComplete(result -> {
if (result.failed()) {
@@ -173,6 +210,94 @@ public class CodeArtifactNpmDataPlane {
});
}
/**
* Serves {@code merged} directly as this request's own response: the content {@link
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} computed is never written to
* Verdaccio (it only promises versions whose real tarball has not been fetched yet, which
* Verdaccio's own publish protocol has no way to record without that tarball's real bytes in
* the same call), so it has to be answered from here rather than by proxying to the sidecar
* the way every other request already is.
*/
private void respondWithMergedPackument(RoutingContext context, ObjectNode merged) {
if (context.response().ended() || context.response().closed()) {
return;
}
byte[] body;
try {
body = mapper.writeValueAsBytes(merged);
} catch (Exception e) {
context.response().setStatusCode(500).end();
return;
}
context.response().putHeader("Content-Type", "application/json").setStatusCode(200).end(Buffer.buffer(body));
}
/**
* {@code target}'s own filename is checked against the {@code <bareName>-<version>.tgz} shape
* {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument} always synthesizes for a
* version it has not yet fetched the real asset for: unlike {@link #blockIfArchived}'s own
* {@link VerdaccioSidecarClient#versionForTarballFilename}, which resolves a filename against
* whatever Verdaccio's own packument already has (and must never assume this shape for a real
* client's own arbitrarily-named publish), there is nothing stored locally to resolve against
* yet on a genuine miss, so the version has to be read back out of the one filename shape this
* importer itself ever hands out. A filename that doesn't fit (a real local publish's own,
* differently-named tarball that happens to 404 for an unrelated reason) is left alone: {@link
* VerdaccioSidecarClient#packageVersionExists} already found nothing to import, and {@link
* #proxy} below still answers with whatever Verdaccio itself says.
*/
private void tryImportMissingTarball(AuthorizationTokenScope tokenScope, NpmRequest npmRequest, String repoId,
TarballDownloadRequest target) {
String bareName = target.identity().packageName();
String filename = target.filename();
String prefix = bareName + "-";
String suffix = ".tgz";
if (!filename.startsWith(prefix) || !filename.endsWith(suffix)
|| filename.length() <= prefix.length() + suffix.length()) {
return;
}
String version = filename.substring(prefix.length(), filename.length() - suffix.length());
if (verdaccioClient.packageVersionExists(repoId, npmRequest.domain(), npmRequest.repository(),
target.identity().namespace(), bareName, version)) {
return;
}
externalConnectionImporter.tryImportAsset(tokenScope.region(), npmRequest.domain(), tokenScope.owner(),
npmRequest.repository(), repoId, target.identity().namespace(), bareName, version, filename);
}
/**
* A real npm packument read, bare ({@code GET /<name>}) only: unlike {@link #isPublish}'s own
* one-segment PUT shape, this excludes the registry's reserved {@code -}-prefixed meta routes
* ({@code /-/all}, {@code /-/package/...}), which npm package names can never collide with
* (the registry reserves that prefix outright). The documented single-version read ({@code
* GET /<name>/<version>}) is deliberately not matched here: real {@code npm install}, even
* for one pinned version, never sends it (confirmed against {@code pacote}'s own source,
* {@code RegistryFetcher#packumentUrl}, always the bare package path), so nothing exercises it
* on this emulator's own critical path either.
*/
private static Optional<PackageIdentity> nativePackumentRequestTarget(HttpMethod method, String rest) {
if (method != HttpMethod.GET || rest.length() <= 1 || rest.startsWith("/-") || rest.indexOf('/', 1) >= 0) {
return Optional.empty();
}
return Optional.of(packageIdentityFromPath(rest));
}
/**
* Whether {@code accept} is {@code pacote}'s own corgi-preferring value ({@code
* application/vnd.npm.install-v1+json}, confirmed against its own source as what a real
* {@code npm install} sends) rather than a plain {@code application/json} ({@code npm view
* <pkg> <field>}-style commands, confirmed the same way): decides whether {@link
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} fetches the real registry's
* cheaper abbreviated form or its full one (found by Greptile's review: the abbreviated form
* never carries a package's {@code readme}, so always using it regardless of what was asked
* silently dropped that field even for a request that explicitly wanted it). {@code null} (no
* header at all) is treated as wanting the full form, confirmed live against the real
* registry: with no {@code Accept} header at all (what a bare {@code curl} sends), it answers
* with the full document, corgi being a deliberately-requested trim, never the default.
*/
private static boolean acceptsCorgi(String accept) {
return accept != null && accept.contains("vnd.npm.install-v1+json");
}
/**
* A real {@code npm publish} is a {@code PUT} to the bare package path (no further path
* segments): {@code /<name>} unscoped, or {@code /@scope%2Fname} scoped, still one segment
@@ -0,0 +1,395 @@
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.ExternalConnection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Retains npm packages and package versions from the real public registry a repository's {@code
* public:npmjs} external connection names, the way real CodeArtifact does when an {@code npm}
* client requests a package that is not present locally yet. Confirmed against the User Guide's
* own "Connect a CodeArtifact repository to a public repository" and "Requesting packages from
* external connections" sections, not inferred:
*
* <ul>
* <li><b>One public connection, one asset per version.</b> AWS names {@code public:npmjs} as
* npm's only public connection, and states npm packages "only have one asset per package
* version", the same as NuGet: the real tarball itself is the only thing {@link
* #tryImportAsset} ever imports.</li>
* <li><b>No deterministic single-version request.</b> Unlike Maven's GAV layout and NuGet's
* {@code {id}/{version}/{filename}} content route, npm's own real protocol has no request
* shape naming one version: {@code npm install <pkg>@<version>} always fetches the bare
* package's full packument first and only picks the version out of its own {@code versions}
* map afterward (confirmed against {@code pacote}'s own source). {@link #mergedPackument} is
* this format's counterpart to {@code CodeArtifactMavenExternalConnectionImporter}'s own {@code
* maven-metadata.xml} merge: without it, a plain {@code npm install} could never even learn
* that an unretained version exists, let alone request its real asset.</li>
* <li><b>Checking asset origins.</b> A package version's retention origin, once confirmed,
* never changes (see {@link CodeArtifactService#claimRetainedVersionOrigin}'s own javadoc); an
* import attempt under a different connection than what is already claimed for that exact
* version is refused outright, and the claim stays reserved for as long as any concurrent
* attempt under the original connection is still in flight.</li>
* <li><b>Coordinated with this emulator's own deletion and disposal.</b> The real write, via
* {@link CodeArtifactService#retainAssetUnderVersionFence}, happens inside the exact same lock
* {@code DeletePackageVersions}/{@code DeletePackage}/{@code DeleteRepository}/{@code
* DisposePackageVersions} already hold for their entire duration, so the two can never
* interleave.</li>
* </ul>
*/
@ApplicationScoped
public class CodeArtifactNpmExternalConnectionImporter {
private static final Logger LOG = Logger.getLogger(CodeArtifactNpmExternalConnectionImporter.class);
/**
* Package-level fields the real registry's full packument carries that {@code npm view
* <pkg> <field>}-style commands read directly off the package, not off any one version
* (found by Greptile's review: {@code readme} specifically, confirmed live to never appear
* anywhere on the abbreviated form, or on any version's own entry even in the full form).
* Never includes {@code versions}/{@code dist-tags}/{@code name}/{@code _id}: those are
* merged by their own dedicated logic right below this list's own use, not by this
* blanket copy.
*/
private static final List<String> PACKAGE_LEVEL_DESCRIPTIVE_FIELDS = List.of("description", "readme",
"readmeFilename", "homepage", "license", "keywords", "author", "repository", "bugs", "maintainers");
private final CodeArtifactService service;
private final VerdaccioSidecarClient verdaccio;
private final NpmExternalConnectionClient externalConnectionClient;
private final ObjectMapper mapper;
@Inject
public CodeArtifactNpmExternalConnectionImporter(CodeArtifactService service, VerdaccioSidecarClient verdaccio,
NpmExternalConnectionClient externalConnectionClient, ObjectMapper mapper) {
this.service = service;
this.verdaccio = verdaccio;
this.externalConnectionClient = externalConnectionClient;
this.mapper = mapper;
}
/**
* Resolves {@code namespace}/{@code packageName}'s own packument through {@code repository}'s
* npm external connection, merging in whichever versions and dist-tags the real public
* registry names that are not already known locally. Returns {@code Optional#empty()} when
* there is no connection, retention is blocked, the real registry doesn't have this package at
* all, or the merge adds nothing beyond what is already known locally: a caller that gets
* {@code empty()} back should fall through to its own existing behavior exactly as if this
* method had never been called, since that already correctly serves (or 404s) whatever is
* known locally.
*
* <p>Every newly-merged version's {@code dist.tarball} is rewritten to this repository's own
* tarball URL, under the exact {@code <bareName>-<version>.tgz} shape {@link #tryImportAsset}
* itself expects back: the real asset is never fetched here, only promised, the same way
* {@code CodeArtifactMavenExternalConnectionImporter}'s own {@code maven-metadata.xml} merge
* only ever advertises release versions without fetching every jar up front. {@code
* dist.shasum}/{@code dist.integrity} are kept exactly as the real registry declared them,
* not recomputed here (there is no real content yet to hash): a client that later downloads
* this version verifies its bytes against these same values, and once {@link
* #tryImportAsset} actually fetches and stores the real tarball, the stored content is
* byte-for-byte the real registry's own, so the hashes it independently computes from that
* content agree with what was already promised here.
*
* <p>A dist-tag from the real registry is only ever written when it names a version this
* merge actually knows about, and only replaces whatever the sidecar already has locally for
* that same tag when the version that local tag currently names was itself only ever retained
* through an external connection, never a tag a genuine local publish set: Verdaccio's own
* first-ever publish to a package always points {@code dist-tags.latest} at that one version
* (confirmed live; nothing in the retention write below can suppress it), so without this
* check, retaining an old pinned version would leave {@code latest} stuck on it forever even
* once a newer version exists on the real registry (found by Greptile's review). Mirrors
* {@code CodeArtifactService#listPackageVersions}'s own identical check on {@code
* preferredDisplayVersion} for exactly the same reason, on the AWS-facing side of this same
* bug.
*
* <p>{@code fullMetadata} is the caller's own read of whether the real npm client actually
* asked for the full document (an {@code Accept} with no {@code vnd.npm.install-v1+json},
* the shape {@code npm view <pkg> readme}-style commands use) rather than the abbreviated
* form {@code npm install} itself sends: only then is the real registry's full packument
* fetched, and only then are its package-level, descriptive fields ({@code readme} among
* them, found by Greptile's review: the abbreviated form never carries it at all) copied in,
* never overriding a field already set locally. Honoring the caller's own request shape here,
* rather than always fetching the (cheaper) abbreviated form regardless of what was asked,
* keeps {@code npm install}'s own hot path exactly as cheap as before.
*/
public Optional<ObjectNode> mergedPackument(String region, String domain, String owner, String repository,
String repoId, String namespace, String packageName, boolean fullMetadata) {
String externalConnectionName = npmExternalConnectionName(region, domain, owner, repository);
if (externalConnectionName == null) {
return Optional.empty();
}
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) {
return Optional.empty();
}
Optional<NpmExternalConnectionClient.FetchedAsset> fetched;
try {
fetched = fullMetadata
? externalConnectionClient.fetchFullPackument(externalConnectionName, namespace, packageName)
: externalConnectionClient.fetchPackument(externalConnectionName, namespace, packageName);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not fetch {0}/{1}''s packument from {2} while resolving its versions through an "
+ "external connection; leaving it unresolved.", namespace, packageName, externalConnectionName);
return Optional.empty();
}
if (fetched.isEmpty()) {
return Optional.empty();
}
JsonNode external;
try {
external = mapper.readTree(fetched.get().content());
} catch (IOException e) {
LOG.warnv(e, "Could not parse {0}/{1}''s packument fetched from {2}; leaving it unresolved.", namespace,
packageName, externalConnectionName);
return Optional.empty();
}
// Re-checked here, right after the slow external fetch above and before this method ever
// touches the sidecar, not just once at this method's own start (found by Greptile's
// review): a DeleteRepository can finish its own cleanup while that fetch was still in
// flight, and calling ensureReady below against an id that cleanup already released would
// start a fresh container under a repository that no longer exists, one nothing can ever
// release again. Narrows the window back down to an ordinary, already-accepted
// check-then-act gap (the same one every other sidecar call here already has) rather than
// one stretched out by a real network round trip; closing it completely needs the sidecar
// itself to track in-flight use the way PypiserverSidecarManager's own container pool
// does, tracked separately as a follow-up since Verdaccio's manager does not.
try {
service.describeRepository(region, domain, owner, repository);
} catch (AwsException e) {
return Optional.empty();
}
// Two different base URLs, deliberately: containerBaseUrl is the sidecar's own reachable
// address, needed to actually read its stored packument, while publicBaseUrl (already
// ending in "/", see publicUrl's own javadoc) is what a real client reaches this
// repository's tarball route through and so the only one safe to embed in dist.tarball
// below; a client sent containerBaseUrl instead could never actually reach it.
String publicBaseUrl = verdaccio.publicUrl(domain, repository);
String containerBaseUrl = verdaccio.ensureReady(repoId, publicBaseUrl);
JsonNode local = verdaccio.fetchPackageDocument(containerBaseUrl, namespace, packageName).orElse(null);
ObjectNode merged = local != null ? ((ObjectNode) local).deepCopy() : mapper.createObjectNode();
String npmName = namespace == null ? packageName : "@" + namespace + "/" + packageName;
merged.put("name", npmName);
if (!merged.has("_id")) {
merged.put("_id", npmName);
}
boolean addedAnything = false;
if (fullMetadata) {
for (String field : PACKAGE_LEVEL_DESCRIPTIVE_FIELDS) {
if (!merged.has(field) && external.has(field)) {
merged.set(field, external.get(field));
addedAnything = true;
}
}
}
// Defaulted after the real external description had its own chance above: an empty
// string here is a last resort, never preferred over the real registry's own value.
if (!merged.has("description")) {
merged.put("description", "");
}
ObjectNode versions = merged.has("versions") && merged.get("versions").isObject()
? (ObjectNode) merged.get("versions") : merged.putObject("versions");
ObjectNode distTags = merged.has("dist-tags") && merged.get("dist-tags").isObject()
? (ObjectNode) merged.get("dist-tags") : merged.putObject("dist-tags");
for (Map.Entry<String, JsonNode> entry : external.path("versions").properties()) {
String version = entry.getKey();
if (versions.has(version)) {
continue;
}
// Raised by Greptile's review: DisposePackageVersions deletes a version's real
// Verdaccio content outright (see VerdaccioSidecarClient#deletePackageVersionAsset),
// so versions.has(version) alone cannot tell a genuinely new external version apart
// from one this repository already disposed of; the real registry's own listing has
// no idea either happened. Without this, a disposed version could be merged straight
// back in (and even land on dist-tags.latest below), only to have its own tarball
// download correctly, but confusingly, refused later by retentionWriteStillAllowed's
// own status check. Archived is excluded the same way: an archived version is still
// genuinely present locally, which versions.has already caught, so this only ever
// actually filters a disposed one in practice.
try {
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "npm",
namespace, packageName, version, repoId);
} catch (AwsException e) {
continue;
}
ObjectNode versionDoc = ((ObjectNode) entry.getValue()).deepCopy();
versionDoc.put("name", npmName);
versionDoc.put("version", version);
ObjectNode dist = versionDoc.has("dist") && versionDoc.get("dist").isObject()
? (ObjectNode) versionDoc.get("dist") : versionDoc.putObject("dist");
dist.put("tarball", publicBaseUrl + packagePath(namespace, packageName) + "/-/"
+ tarballFilename(packageName, version));
versions.set(version, versionDoc);
addedAnything = true;
}
for (Map.Entry<String, JsonNode> tag : external.path("dist-tags").properties()) {
String tagVersion = tag.getValue().asText(null);
if (tagVersion == null || !versions.has(tagVersion)) {
continue;
}
String currentLocalVersion = distTags.path(tag.getKey()).asText(null);
boolean currentlyUnset = currentLocalVersion == null;
boolean currentlyPointsAtARetainedVersion = currentLocalVersion != null
&& service.retainedVersionOriginConnection(region, domain, owner, repository, "npm", namespace,
packageName, currentLocalVersion).isPresent();
if (currentlyUnset || currentlyPointsAtARetainedVersion) {
distTags.set(tag.getKey(), tag.getValue());
addedAnything = true;
}
}
return addedAnything ? Optional.of(merged) : Optional.empty();
}
/**
* Attempts to retain {@code namespace}/{@code packageName}/{@code version}'s one real asset
* into {@code repoId} from {@code repository}'s own npm external connection. Returns {@code
* true} only when the asset is genuinely present under this connection's claim by the time
* this returns, whether because this attempt imported it or a concurrent one already had: a
* caller that gets {@code false} back should fall through to its own existing not-found
* response exactly as if this method had never been called.
*/
public boolean tryImportAsset(String region, String domain, String owner, String repository, String repoId,
String namespace, String packageName, String version, String assetName) {
String externalConnectionName = npmExternalConnectionName(region, domain, owner, repository);
if (externalConnectionName == null) {
return false;
}
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) {
return false;
}
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"npm", namespace, packageName);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"npm", namespace, packageName, version);
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
domain, owner, repository, "npm", namespace, packageName, version, externalConnectionName,
packageFenceSnapshot);
if (!claim.claimed()) {
return false;
}
boolean imported = false;
try {
if (verdaccio.packageVersionExists(repoId, domain, repository, namespace, packageName, version)) {
imported = service.retainedVersionOriginConnection(region, domain, owner, repository, "npm",
namespace, packageName, version).filter(externalConnectionName::equals).isPresent();
return imported;
}
Optional<NpmExternalConnectionClient.FetchedAsset> fetched;
try {
fetched = externalConnectionClient.fetchTarball(externalConnectionName, namespace, packageName,
version);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not fetch {0} {1} {2} from {3} while retaining an npm package through an "
+ "external connection.", namespace, packageName, version, externalConnectionName);
return false;
}
if (fetched.isEmpty()) {
return false;
}
byte[] content = fetched.get().content();
// Fetched again here, full rather than abbreviated, rather than reusing whatever
// mergedPackument already saw: that call is per-request and never keeps anything
// around between one request and the next, and this is the one real network call
// this whole import attempt pays for retrieving a version's dependencies/engines/
// scripts and the package's own readme (see ExternalPackumentDetails' own javadoc),
// paid at most once per version ever actually retained.
ExternalPackumentDetails details = fetchExternalPackumentDetails(externalConnectionName, namespace,
packageName, version);
if (details.versionDoc() == null) {
// Raised by hectorvent's review: storing now with no full-form document would
// retain this version with the minimal one storeRetainedVersionAsset falls back
// to (no dependencies/engines/scripts), and permanently so, since the merge above
// skips any version once versions.has(version) is true. Returning false instead
// abandons this attempt without writing anything, so a later download retries the
// full fetch rather than settling for a degraded document forever.
LOG.warnv("Not retaining {0}/{1}@{2} from {3} without its full-form version "
+ "document; a later download will retry.", namespace, packageName, version,
externalConnectionName);
return false;
}
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
domain, owner, repository, "npm", namespace, packageName, version, versionFenceSnapshot,
packageFenceSnapshot, claim.episodeId(), repoId, assetName, content,
() -> verdaccio.storeRetainedVersionAsset(repoId, domain, repository, namespace, packageName,
version, assetName, content, details.versionDoc()));
imported = result.fenceMatched() && result.wroteNewContent();
if (imported) {
// Raised by Greptile's review: without this, GetPackageVersionReadme 404s on an
// otherwise fully retained version, since npm (unlike nuget's BaGetter) answers
// that call from a capture taken at write time, never live from the sidecar; see
// CodeArtifactService#recordPublishedPackageVersionReadme's own javadoc for why
// versionFenceSnapshot, taken before this same write, is what it checks against.
service.recordPublishedPackageVersionReadme(region, domain, owner, repository, "npm", namespace,
packageName, version, details.readme(), versionFenceSnapshot);
}
return imported;
} finally {
if (imported) {
service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "npm", namespace,
packageName, packageFenceSnapshot);
}
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "npm", namespace,
packageName, version, claim.episodeId(), imported);
}
}
/**
* {@code versionDoc} is the real registry's own full-form entry for exactly this version
* (never missing/null, the shape {@link VerdaccioSidecarClient#storeRetainedVersionAsset}
* itself already falls back safely without), or {@code null} when the full packument fetch
* itself failed or no longer names this version; {@code readme} is the package-level readme
* the full form carries (confirmed live: never present on any one version, only once at the
* top of the whole document), or {@code ""} in either of those same failure cases, the same
* empty-string convention pypi's own upload path already uses for a package with no readme at
* all.
*/
private record ExternalPackumentDetails(JsonNode versionDoc, String readme) {}
private ExternalPackumentDetails fetchExternalPackumentDetails(String externalConnectionName, String namespace,
String packageName, String version) {
JsonNode full;
try {
Optional<NpmExternalConnectionClient.FetchedAsset> fetched = externalConnectionClient.fetchFullPackument(
externalConnectionName, namespace, packageName);
if (fetched.isEmpty()) {
return new ExternalPackumentDetails(null, "");
}
full = mapper.readTree(fetched.get().content());
} catch (RuntimeException | IOException e) {
LOG.warnv(e, "Could not fetch {0}/{1}''s full packument from {2} while retaining {3}; its dependencies "
+ "and readme will be unavailable.", namespace, packageName, externalConnectionName, version);
return new ExternalPackumentDetails(null, "");
}
JsonNode versionDoc = full.path("versions").path(version);
return new ExternalPackumentDetails(versionDoc.isMissingNode() || versionDoc.isNull() ? null : versionDoc,
full.path("readme").asText(""));
}
private static String packagePath(String namespace, String packageName) {
return namespace == null
? SidecarUriUtils.encodeSegment(packageName)
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
}
private static String tarballFilename(String packageName, String version) {
return packageName + "-" + version + ".tgz";
}
private String npmExternalConnectionName(String region, String domain, String owner, String repository) {
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
.filter(ec -> "npm".equals(ec.getPackageFormat()))
.map(ExternalConnection::getExternalConnectionName)
.findFirst()
.orElse(null);
}
}
@@ -139,7 +139,9 @@ public class CodeArtifactNuGetExternalConnectionImporter {
// methods already hold.
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot,
packageFenceSnapshot, claim.episodeId(), bagetter, repoId, assetName, content);
packageFenceSnapshot, claim.episodeId(), repoId, assetName, content,
() -> bagetter.storePackageVersionAsset(repoId, domain, repository, null, packageId, version,
assetName, content));
imported = result.fenceMatched() && result.wroteNewContent();
return imported;
} finally {
@@ -1257,7 +1257,18 @@ public class CodeArtifactService implements Resettable {
}
String preferredVersion = preferredDisplayVersion;
String defaultDisplayVersion = preferredVersion != null
// Raised by Greptile's review: npm's own Verdaccio sidecar always points its own
// dist-tags.latest at whichever version a package's very first-ever stored version
// happens to be, confirmed live, with no way for a caller's write to suppress that
// default. A version retained through an external connection (never a deliberate local
// publish) is excluded from being read as this preference for exactly that reason:
// downloading an old, specifically-pinned version must never change what an unpinned
// npm install resolves to, the same most-recently-published fallback this already uses
// when preferredDisplayVersion itself is unset.
boolean preferredVersionIsExternallyRetained = preferredVersion != null
&& entries.stream().anyMatch(e -> e.version().equals(preferredVersion)
&& "EXTERNAL".equals(e.originType()));
String defaultDisplayVersion = preferredVersion != null && !preferredVersionIsExternallyRetained
&& entries.stream().anyMatch(e -> e.version().equals(preferredVersion)
&& "Published".equals(e.status()))
? preferredVersion
@@ -3236,16 +3247,21 @@ public class CodeArtifactService implements Resettable {
/**
* Generic sibling of {@link #deployMavenAssetUnderVersionFence}, for npm/pypi/nuget's own
* external-connection importers to write a retained asset into their own sidecar
* ({@code sidecar.storePackageVersionAsset}) under the same fence/status/claim-episode
* protection Maven's own method already provides, inside the exact same lock {@code
* deletePackageVersions}/{@code deletePackage}/{@code deleteRepository}/{@code
* disposePackageVersions} hold for their own entire operation.
* external-connection importers to write a retained asset into their own sidecar under the
* same fence/status/claim-episode protection Maven's own method already provides, inside the
* exact same lock {@code deletePackageVersions}/{@code deletePackage}/{@code
* deleteRepository}/{@code disposePackageVersions} hold for their own entire operation.
*
* <p>Unlike {@link ReposiliteSidecarClient#deployArtifact}, {@link
* RepositorySidecarManager#storePackageVersionAsset} reports no status code or idempotent-match
* distinction of its own: it either succeeds (void) or throws. A caller that wants to avoid
* double-counting bytes on a retry should check {@link
* <p>{@code write} is the caller's own sidecar call, run only once the fence actually still
* allows it, inside this same {@code synchronized} method: a plain {@link Runnable} rather
* than a fixed {@code RepositorySidecarManager}/{@code storePackageVersionAsset} shape (found
* by Greptile's review of npm's own external-connection work) since npm's own write needs to
* reuse the real registry's own version document to avoid dropping {@code dependencies}/
* {@code engines}/{@code scripts}, something {@link RepositorySidecarManager#storePackageVersionAsset}'s
* fixed signature has no way to carry through; nuget's own call wraps the exact same plain
* {@code storePackageVersionAsset} call this method used to make itself. Reports no status
* code or idempotent-match distinction of its own: it either succeeds or throws. A caller
* that wants to avoid double-counting bytes on a retry should check {@link
* RepositorySidecarManager#fetchPackageVersionAsset} first and skip this call entirely when
* the asset is already there with matching content, the same way a direct upload's own
* idempotency check already does for this format's controller.
@@ -3253,14 +3269,13 @@ public class CodeArtifactService implements Resettable {
public synchronized AssetRetentionAttemptResult retainAssetUnderVersionFence(String region, String domain,
String domainOwner, String repository, String format, String namespace, String packageName,
String version, long versionFenceSnapshot, long packageFenceSnapshot, long episodeId,
RepositorySidecarManager sidecar, String repositoryContainerId, String assetName, byte[] content) {
String repositoryContainerId, String assetName, byte[] content, Runnable write) {
if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, format, namespace, packageName,
version, repositoryContainerId, versionFenceSnapshot, episodeId)) {
return new AssetRetentionAttemptResult(false, false);
}
try {
sidecar.storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName,
version, assetName, content);
write.run();
} catch (RuntimeException e) {
LOG.warnv(e, "Could not write {0} {1} {2}''s asset {3} while retaining it through an external "
+ "connection.", format, packageName, version, assetName);
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.codeartifact;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
/**
* A real outbound client for the one public npm repository CodeArtifact's {@code public:npmjs}
* external connection names: {@code https://registry.npmjs.org}, confirmed live, not inferred.
*
* <p>Unlike Maven's GAV layout and NuGet's {@code {id}/{version}/{filename}} content route,
* npm's own real wire protocol has no request shape that names a single package version: {@code
* npm install <pkg>@<version>} always fetches the bare package's full packument first (confirmed
* against npm's own {@code pacote} client source, {@code RegistryFetcher#packumentUrl}, which is
* always {@code <registry>/<escapedName>}, never a version-specific path) and only picks the
* requested version out of its {@code versions} map afterward. {@link
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} is what actually needs a version's
* metadata before any asset is ever fetched; {@link #fetchPackument} serves that, using the same
* {@code corgi} abbreviated format {@code pacote} itself requests by default, since every field
* this emulator's own merge needs ({@code versions[v].dist}, {@code dist-tags}) survives that
* trimming and a full packument can run to several megabytes for a popular package.
*
* <p>The real tarball path ({@link #fetchTarball}) is fetched by exact coordinate, not guessed:
* confirmed live that the real registry serves it at a deterministic {@code
* <packagePath>/-/<bareName>-<version>.tgz}, scope included in {@code packagePath} with a literal
* {@code /} (unlike the packument path below, which needs the scope separator percent-encoded as
* {@code %2F} to reach the single-package resource rather than a sub-path of it, also confirmed
* live). {@link CodeArtifactNpmExternalConnectionImporter} always synthesizes its own rewritten
* {@code dist.tarball} using this exact {@code <bareName>-<version>.tgz} shape, so this never
* needs to trust whatever filename the real packument itself declared.
*
* <p>Every failure mode (an unknown connection name, a real non-200 response, a network error)
* resolves to {@link Optional#empty()} rather than throwing: a caller here is always deciding
* whether to retain a package or a package version from an external source, and AWS's own
* documented behavior for an unreachable external repository is to behave exactly as if the
* asset were not found, with no special error surfaced to the client.
*/
@ApplicationScoped
public class NpmExternalConnectionClient {
private static final Logger LOG = Logger.getLogger(NpmExternalConnectionClient.class);
private static final String CORGI_ACCEPT = "application/vnd.npm.install-v1+json; q=1.0, "
+ "application/json; q=0.8, */*";
private static final String FULL_ACCEPT = "application/json";
private static final Map<String, String> BASE_URLS = Map.of(
"public:npmjs", "https://registry.npmjs.org");
private final HttpClient httpClient;
private final Map<String, String> baseUrls;
@Inject
public NpmExternalConnectionClient() {
this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(), BASE_URLS);
}
/** For tests: a fake base-URL map, so the wire contract can be exercised against a local
* {@code HttpServer} fake instead of the real public registry. */
NpmExternalConnectionClient(HttpClient httpClient, Map<String, String> baseUrls) {
this.httpClient = httpClient;
this.baseUrls = baseUrls;
}
/** One package's real packument, or one real tarball's bytes, fetched from the real registry. */
public record FetchedAsset(byte[] content) {}
/**
* Fetches {@code namespace}/{@code packageName}'s own real, abbreviated packument from the
* real public registry {@code externalConnectionName} names.
*/
public Optional<FetchedAsset> fetchPackument(String externalConnectionName, String namespace,
String packageName) {
return fetchPackument(externalConnectionName, namespace, packageName, CORGI_ACCEPT);
}
/**
* The real registry's full, uncompressed packument for {@code namespace}/{@code packageName}.
* Confirmed live against the same package and version: the abbreviated form {@link
* #fetchPackument} uses already carries a version's {@code dependencies}/{@code engines}, but
* drops its {@code scripts}, and carries no {@code readme} anywhere at all (not per version,
* and not even on the full form's own per-version entry: the real registry only ever keeps
* one {@code readme}, at the top of the full document). Used by {@link
* CodeArtifactNpmExternalConnectionImporter#tryImportAsset} once, per version ever actually
* retained, not on every packument read the way {@link #fetchPackument} is: the extra cost of
* the full form over the abbreviated one is paid at most once per version.
*/
public Optional<FetchedAsset> fetchFullPackument(String externalConnectionName, String namespace,
String packageName) {
return fetchPackument(externalConnectionName, namespace, packageName, FULL_ACCEPT);
}
private Optional<FetchedAsset> fetchPackument(String externalConnectionName, String namespace,
String packageName, String accept) {
String baseUrl = baseUrls.get(externalConnectionName);
if (baseUrl == null) {
return Optional.empty();
}
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packumentPathSegment(namespace, packageName));
return send(uri, accept, namespace, packageName);
}
/** Fetches {@code namespace}/{@code packageName}/{@code version}'s one real tarball. */
public Optional<FetchedAsset> fetchTarball(String externalConnectionName, String namespace, String packageName,
String version) {
String baseUrl = baseUrls.get(externalConnectionName);
if (baseUrl == null) {
return Optional.empty();
}
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), tarballPath(namespace, packageName, version));
return send(uri, "*/*", namespace, packageName);
}
private Optional<FetchedAsset> send(URI uri, String accept, String namespace, String packageName) {
try {
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(20))
.header("Accept", accept)
.GET()
.build();
HttpResponse<byte[]> response = httpClient.send(request, BodyHandlers.ofByteArray());
return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Optional.empty();
} catch (IOException e) {
LOG.warnv("Could not fetch {0} {1} from the public npm registry: {2}", namespace, packageName,
e.getMessage());
return Optional.empty();
}
}
/**
* The real registry's single-package resource path: a bare, percent-encoded package name, or
* for a scoped package, {@code @<namespace>%2F<packageName>} as one opaque segment with the
* scope separator escaped (confirmed live: an unescaped {@code /} there 404s the single-
* package endpoint instead of reaching it).
*/
private static String packumentPathSegment(String namespace, String packageName) {
String encodedName = SidecarUriUtils.encodeSegment(packageName);
return namespace == null ? encodedName : "@" + SidecarUriUtils.encodeSegment(namespace) + "%2F" + encodedName;
}
private static String tarballPath(String namespace, String packageName, String version) {
String encodedName = SidecarUriUtils.encodeSegment(packageName);
String packagePath = namespace == null ? encodedName
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + encodedName;
String tarballFilename = SidecarUriUtils.encodeSegment(packageName + "-" + version + ".tgz");
return "/" + packagePath + "/-/" + tarballFilename;
}
}
@@ -451,6 +451,28 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
sourceVersionDoc);
}
/**
* {@code CodeArtifactNpmExternalConnectionImporter}'s own destination write for a version
* retained through a {@code public:npmjs} external connection, the same reuse-the-source-
* document treatment {@link #copyPackageVersionAsset} already gives a version copied from
* another repository here, just sourced from the real public registry's own fetched packument
* instead of another Verdaccio-backed repository (found by Greptile's review of npm's own
* external-connection work: a plain {@link #storePackageVersionAsset} call builds a minimal
* document with no {@code dependencies}/{@code engines}/{@code scripts}, which a real {@code
* npm install} of this exact version needs). {@code externalVersionDoc} is {@code null} when
* the caller could not resolve the real registry's own version entry (should not normally
* happen once {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument} has already
* merged this exact version in, but defended the same way {@link #copyPackageVersionAsset}
* already is): falls back to the same minimal document {@link #storePackageVersionAsset}
* would have built.
*/
public void storeRetainedVersionAsset(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version, String assetName, byte[] content,
JsonNode externalVersionDoc) {
storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content,
externalVersionDoc);
}
private void storeVersion(String repositoryContainerId, String domain, String repository, String namespace,
String packageName, String version, String assetName, byte[] content, JsonNode sourceVersionDoc) {
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
@@ -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();
}
}