fix(codeartifact): stop npm retention from clobbering a real local dist-tags.latest (#7510)

storeVersion (the one write path storePackageVersionAsset/copyPackageVersionAsset/
storeRetainedVersionAsset all go through) always sent dist-tags.latest pointed at
whichever version it was writing, so copying or retaining any other version,
even an old one, silently moved what an unpinned npm install resolves to.

Confirmed live against the pinned Verdaccio image that this was never actually
needed: a PUT that omits dist-tags entirely leaves an existing package's own
dist-tags.latest untouched, while a package's genuinely first-ever version still
gets it set by Verdaccio's own default (there is nothing yet to preserve). So
this write simply stops sending the field at all, rather than needing its own
"is this the right version to call latest" decision.

Corrected two test comments that had over-generalized this as "no retention
write can ever suppress it" to the narrower, now-verified truth: only a
package's very first-ever version is forced.

Also confirmed live, specifically because CopyPackageVersions' own overwrite
path deletes a conflicting version before recreating it (clearing dist-tags.latest
if it pointed there): Verdaccio auto-recomputes latest from whatever versions
remain once it's cleared, rather than leaving the package tagless, so this
write's own change plays correctly with that existing delete-time behavior.
Added a live regression test for exactly that interaction (overwriting the
current latest version while a sibling version exists must neither lose latest
nor wrongly hand it back to the version just overwritten).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-04 17:09:49 -06:00
1 parent 26cd74e6f8
commit 09132855a6
6 files changed
+238 -19

No files matched your search

@@ -425,15 +425,16 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
/**
* Publishes {@code version} straight to this sidecar's own packument, the real npm registry
* wire shape confirmed against a live Verdaccio container: a {@code PUT} to the package path
* carrying just the new version's metadata, its tarball as a base64 {@code _attachments}
* entry, and {@code dist-tags.latest} pointed at it. Verdaccio merges this into whatever
* {@code versions} the package already has rather than requiring the caller to resend them
* (also confirmed live), so this never needs to read the existing packument first the way
* {@link #deletePackageVersionAsset} does. Rejected outright (a real {@code 409}, "this
* package is already present") if {@code version} already exists, even if its content is
* identical: the caller ({@code CodeArtifactService#copyContainerBackedPackageVersions}) is
* expected to have already deleted a conflicting existing version first for an overwrite, the
* same reason {@code ReposiliteSidecarClient#storePackageVersionAsset} documents for Maven.
* carrying just the new version's metadata and its tarball as a base64 {@code _attachments}
* entry, deliberately with no {@code dist-tags} of its own (see {@link #storeVersion}'s own
* javadoc for why). Verdaccio merges this into whatever {@code versions} the package already
* has rather than requiring the caller to resend them (also confirmed live), so this never
* needs to read the existing packument first the way {@link #deletePackageVersionAsset} does.
* Rejected outright (a real {@code 409}, "this package is already present") if {@code
* version} already exists, even if its content is identical: the caller ({@code
* CodeArtifactService#copyContainerBackedPackageVersions}) is expected to have already
* deleted a conflicting existing version first for an overwrite, the same reason {@code
* ReposiliteSidecarClient#storePackageVersionAsset} documents for Maven.
*/
@Override
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
@@ -488,6 +489,18 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
externalVersionDoc);
}
/**
* The one real write every {@code storePackageVersionAsset}/{@code copyPackageVersionAsset}/
* {@code storeRetainedVersionAsset} call goes through. Sends no {@code dist-tags} of its own
* (found by hectorvent's review of the npm external-connection work: the unconditional {@code
* dist-tags.latest} this used to always send clobbered a real local {@code latest} the moment
* any other version was copied or retained). Confirmed live against the pinned image: a PUT
* that omits {@code dist-tags} entirely leaves an existing package's own {@code dist-tags.
* latest} untouched, while a package's genuinely first-ever version still gets it set to that
* version by Verdaccio's own default (there is nothing yet to preserve), so omitting it here
* is always correct, and this method never needs its own "is this the right version to call
* latest" decision.
*/
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));
@@ -506,11 +519,11 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
dist.put("integrity", "sha512-" + Base64.getEncoder().encodeToString(sha512().digest(content)));
dist.put("tarball", tarballUrl);
// No dist-tags sent: see this method's own javadoc for why.
ObjectNode body = mapper.createObjectNode();
body.put("_id", npmName);
body.put("name", npmName);
body.put("description", "");
body.putObject("dist-tags").put("latest", version);
body.putObject("versions").set(version, versionDoc);
ObjectNode attachment = body.putObject("_attachments").putObject(assetName);
attachment.put("content_type", "application/octet-stream");
@@ -922,6 +922,99 @@ class CodeArtifactNpmDockerIntegrationTest {
.then().statusCode(anyOf201Or200());
}
/**
* Found while self-reviewing the fix that stopped {@code VerdaccioSidecarClient#storeVersion}
* from always sending its own {@code dist-tags.latest}: {@code CopyPackageVersions}'s own
* overwrite path ({@code deletePackageVersionAsset} then {@code copyPackageVersionAsset}, both
* confirmed live) deletes the conflicting version's packument entry first, which clears {@code
* latest} if it pointed there, and, confirmed live against the pinned image, Verdaccio then
* auto-recomputes a new {@code latest} from whatever versions remain, rather than leaving the
* package tagless. The worry this proves unfounded: that the recreate step, now sending no
* {@code dist-tags} of its own, would leave the overwritten version's package without any
* {@code latest} at all, or wrongly hand {@code latest} back to the version just overwritten
* instead of the one Verdaccio already re-picked. Neither happens: overwriting {@code 1.0.0}
* (the current {@code latest}) while {@code 2.0.0} also exists leaves {@code latest} on {@code
* 2.0.0} throughout, exactly as it was the moment {@code 1.0.0}'s own entry was removed.
*/
@Test
@Order(24)
void copyPackageVersionsOverwritingTheCurrentLatestVersionNeverLosesOrWronglyReclaimsLatest() {
String packageName = "multiver-overwrite-pkg";
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=overwrite-dest-repo")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=overwrite-source-repo")
.then().statusCode(200);
// Two real versions published directly to REPO, the source for both copies below.
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(scopelessEnvelope(packageName, "1.0.0", "original 1.0.0 bytes".getBytes(StandardCharsets.UTF_8)))
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(scopelessEnvelope(packageName, "2.0.0", "the 2.0.0 bytes".getBytes(StandardCharsets.UTF_8)))
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
// Copying 1.0.0 into a brand new destination package makes it latest (Verdaccio's own
// first-ever-version default); copying 2.0.0 in afterward must not steal that tag.
copyNpmVersion(REPO, "overwrite-dest-repo", packageName, "1.0.0", false);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/overwrite-dest-repo/" + packageName)
.then().statusCode(200).body("dist-tags.latest", equalTo("1.0.0"));
copyNpmVersion(REPO, "overwrite-dest-repo", packageName, "2.0.0", false);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/overwrite-dest-repo/" + packageName)
.then().statusCode(200).body("dist-tags.latest", equalTo("1.0.0"));
// A different real 1.0.0 (different bytes) published to a third repository, so the
// overwrite below has genuinely different content to copy in, the same way the existing
// copyPackageVersionsOverwritesAnExistingNpmVersionWithDifferentContentAtTheRealSidecar
// test sources its own "new" content from a different repository than the "old" one.
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(scopelessEnvelope(packageName, "1.0.0", "overwritten 1.0.0 bytes".getBytes(StandardCharsets.UTF_8)))
.put("/codeartifact/npm/" + DOMAIN + "/overwrite-source-repo/" + packageName)
.then().statusCode(anyOf201Or200());
// Overwrites 1.0.0, the destination's own current latest, while 2.0.0 still exists there.
copyNpmVersion("overwrite-source-repo", "overwrite-dest-repo", packageName, "1.0.0", true);
byte[] overwritten = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/overwrite-dest-repo/" + packageName + "/-/" + packageName
+ "-1.0.0.tgz")
.then().statusCode(200)
.extract().asByteArray();
assertEquals("overwritten 1.0.0 bytes", new String(overwritten, StandardCharsets.UTF_8));
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/overwrite-dest-repo/" + packageName)
.then().statusCode(200)
.body("versions", hasKey("1.0.0"))
.body("versions", hasKey("2.0.0"))
.body("dist-tags.latest", equalTo("2.0.0"));
}
private static String scopelessEnvelope(String packageName, String version, byte[] tarball) {
String assetName = packageName + "-" + version + ".tgz";
return "{\"name\":\"" + packageName + "\",\"versions\":{\"" + version + "\":{\"name\":\"" + packageName
+ "\",\"version\":\"" + version + "\",\"dist\":{\"tarball\":\"http://ignored/" + assetName + "\"}}},"
+ "\"_attachments\":{\"" + assetName + "\":{\"content_type\":\"application/octet-stream\","
+ "\"data\":\"" + Base64.getEncoder().encodeToString(tarball) + "\",\"length\":" + tarball.length
+ "}}}";
}
private static void copyNpmVersion(String sourceRepository, String destinationRepository, String packageName,
String version, boolean allowOverwrite) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"" + version + "\"],\"allowOverwrite\":" + allowOverwrite + "}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + sourceRepository
+ "&destination-repository=" + destinationRepository + "&format=npm&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'" + version + "'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
}
/**
* Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
@@ -2,6 +2,8 @@ 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.Digests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
@@ -12,9 +14,14 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import static io.github.hectorvent.floci.testing.CodeArtifactRequests.putPackageOriginConfiguration;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
@@ -39,6 +46,7 @@ class CodeArtifactNpmExternalConnectionDockerIntegrationTest {
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 LATEST_REPO = "npm-external-connection-latest-repo";
private static final String PACKAGE_NAME = "is-even";
private static final String VERSION = "1.0.0";
@@ -62,6 +70,9 @@ class CodeArtifactNpmExternalConnectionDockerIntegrationTest {
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?domain=" + DOMAIN + "&repository=" + LATEST_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")
@@ -70,6 +81,10 @@ class CodeArtifactNpmExternalConnectionDockerIntegrationTest {
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
+ "&external-connection=public:npmjs")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + LATEST_REPO
+ "&external-connection=public:npmjs")
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
@@ -238,6 +253,69 @@ class CodeArtifactNpmExternalConnectionDockerIntegrationTest {
assertThat(packument.path("versions").has(VERSION), equalTo(true));
}
/**
* Found by hectorvent's review: the retention write used to send its own {@code dist-tags.
* latest}, so retaining any real external version at all, even an old one, would clobber a
* genuine local {@code latest} a direct publish had already set. {@code is-even}'s own real
* {@code 0.1.2} (older than the real registry's own actual latest, {@link #VERSION}) is
* retained here specifically, into a repository whose own local publish already claims {@code
* latest} for a version number ({@code 9.9.9}) the real registry could never have, so there is
* no ambiguity about which one is the genuine local choice. A separate repository from {@link
* #REPO}: this one's own local publish must not interact with the other ordered tests there.
*/
@Test
@Order(9)
void retainingAnOlderRealVersionNeverClobbersAGenuineLocalLatest() throws Exception {
byte[] localContent = "a-genuine-local-publish".getBytes(StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
ObjectNode localVersionDoc = mapper.createObjectNode();
localVersionDoc.put("name", PACKAGE_NAME);
localVersionDoc.put("version", "9.9.9");
ObjectNode localDist = localVersionDoc.putObject("dist");
localDist.put("shasum", Digests.sha1Hex(localContent));
localDist.put("integrity", "sha512-" + Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-512").digest(localContent)));
ObjectNode publishBody = mapper.createObjectNode();
publishBody.put("_id", PACKAGE_NAME);
publishBody.put("name", PACKAGE_NAME);
publishBody.put("description", "");
publishBody.putObject("dist-tags").put("latest", "9.9.9");
publishBody.putObject("versions").set("9.9.9", localVersionDoc);
ObjectNode attachment = publishBody.putObject("_attachments").putObject(PACKAGE_NAME + "-9.9.9.tgz");
attachment.put("content_type", "application/octet-stream");
attachment.put("data", Base64.getEncoder().encodeToString(localContent));
attachment.put("length", localContent.length);
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
.body(mapper.writeValueAsString(publishBody))
.put("/codeartifact/npm/" + DOMAIN + "/" + LATEST_REPO + "/" + PACKAGE_NAME)
.then().statusCode(anyOf(equalTo(200), equalTo(201)));
// AWS's own documented default: a package that already has a real, directly-published
// version defaults to upstream: BLOCK unless a caller explicitly sets ALLOW, exactly the
// scenario hectorvent's own finding names ("with upstream: ALLOW on a locally published
// package, retention can lose a real local latest"). Without this, the retention attempt
// below would simply be refused rather than exercising the dist-tags bug at all.
putPackageOriginConfiguration(AUTH, DOMAIN, LATEST_REPO, "npm", null, PACKAGE_NAME, "ALLOW", "ALLOW");
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + LATEST_REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.body("dist-tags.latest", equalTo("9.9.9"));
String olderRealVersion = "0.1.2";
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + LATEST_REPO + "/" + PACKAGE_NAME + "/-/" + PACKAGE_NAME
+ "-" + olderRealVersion + ".tgz")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + LATEST_REPO + "/" + PACKAGE_NAME)
.then().statusCode(200)
.body("dist-tags.latest", equalTo("9.9.9"))
.body("versions['" + olderRealVersion + "'].version", equalTo(olderRealVersion));
}
private static long describeDomainAssetSizeBytes() {
return given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
@@ -489,9 +489,10 @@ class CodeArtifactNpmExternalConnectionImporterTest {
}
/**
* 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
* Raised by Greptile's review: Verdaccio points a package's dist-tags.latest at its very
* first-ever stored version with no way to suppress that one-time default (confirmed live;
* see {@code VerdaccioSidecarClient#storeVersion}'s own javadoc for the full story, including
* why a later write no longer clobbers 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.
*/
@@ -4956,9 +4956,13 @@ class CodeArtifactServiceTest {
/**
* 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
* {@code dist-tags.latest} at whichever version happens to be a package's very first-ever
* stored version, with no way for a write to suppress that one-time default (confirmed live
* against the pinned image; a later write that omits {@code dist-tags} leaves an existing
* {@code latest} alone instead, see {@code VerdaccioSidecarClient#storeVersion}'s own
* javadoc). So {@code preferredDisplayVersion} can still name a version that was never a
* deliberate local choice at all, specifically when a package's first version ever retained
* happens not to be the real registry's own latest. 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
@@ -4980,9 +4984,10 @@ class CodeArtifactServiceTest {
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.
// Simulates Verdaccio's own one-time forced default on a package's very first-ever
// version: 1.0.0 was retained before any other version of this package ever existed, so
// this is exactly what that genuine retention 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"));
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -198,6 +199,34 @@ class VerdaccioSidecarClientTest {
assertEquals("/%2E%2E", observedRawPath.get());
}
/**
* Found by hectorvent's review of the npm external-connection work: an unconditional {@code
* dist-tags.latest} in every write's own PUT body used to clobber a real local {@code latest}
* the moment any other version was copied or retained (confirmed live against the pinned
* image: Verdaccio preserves an existing package's own {@code dist-tags.latest} when a write
* omits the field, see {@code VerdaccioSidecarClient#storeVersion}'s own javadoc). This reads
* the exact body this client sends, not just the end-to-end result, so a future caller that
* reintroduces a hardcoded {@code dist-tags.latest} fails here directly rather than only ever
* showing up as a flaky-looking order-dependent symptom in a live test.
*/
@Test
void storePackageVersionAssetSendsNoDistTagsOfItsOwn() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", backendUrl);
AtomicReference<String> observedBody = new AtomicReference<>();
backend.createContext("/demo-pkg", exchange -> {
observedBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
client(manager).storePackageVersionAsset("npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0",
"demo-pkg-1.0.0.tgz", "tarball bytes".getBytes(StandardCharsets.UTF_8));
JsonNode sentBody = new ObjectMapper().readTree(observedBody.get());
assertTrue(sentBody.path("dist-tags").isMissingNode(), "must not send its own dist-tags: " + observedBody.get());
}
/**
* Mirrors the real npm unpublish mechanism, confirmed against a live Verdaccio container: GET
* the packument for its {@code _rev}, then {@code DELETE} the package path with that revision