fix(codeartifact): route a literal slash scoped npm publish through the publish guards (#7445)

isPublish only took a PUT to one path segment, so a scoped publish sent as
PUT /@scope/name (two segments) fell through to the plain proxy. Verdaccio
accepts that shape, so the publish landed without the publish:BLOCK check,
the Archived/Disposed guard, the byte identical republish shortcut or the
byte accounting that follow a publish.

Also treat exactly /@scope/name as a publish. packageIdentityFromPath already
resolves it, and the request is still forwarded to Verdaccio as sent. Longer
paths, such as dist-tag updates, are still proxied unchanged.

Closes #7439
This commit is contained in:
David authored and GitHub committed 2026-11-03 16:48:44 -04:00
1 parent fad0493169
commit 342c79806d
3 files changed
+190 -5

No files matched your search

@@ -348,7 +348,11 @@ public class CodeArtifactNpmDataPlane {
/**
* A real {@code npm publish} is a {@code PUT} to the bare package path (no further path
* segments): {@code /<name>} unscoped, or {@code /@scope%2Fname} scoped, still one segment
* since the slash between scope and name arrives URL-encoded. {@code npm deprecate} is a
* since the slash between scope and name arrives URL-encoded. A scoped package may also be
* sent with a literal slash, {@code /@scope/name} (the shape {@code VerdaccioSidecarClient}
* itself publishes with, and one Verdaccio accepts): two segments, the first an {@code @}
* scope, which is the same publish and must take the same guarded route (issue #7439).
* {@code npm deprecate} is a
* {@code PUT} at this same bare-package shape (a dist-tag update is not: that always goes to
* {@code /-/package/<name>/dist-tags/<tag>}, a different, multi-segment path {@link #isPublish}
* already excludes), but {@link #confirmedRepublish} only ever short-circuits when it can
@@ -357,7 +361,14 @@ public class CodeArtifactNpmDataPlane {
* proxy path unaffected.
*/
private static boolean isPublish(HttpMethod method, String rest) {
return method == HttpMethod.PUT && rest.length() > 1 && rest.indexOf('/', 1) < 0;
if (method != HttpMethod.PUT || rest.length() <= 1) {
return false;
}
int slash = rest.indexOf('/', 1);
if (slash < 0) {
return true;
}
return rest.startsWith("/@") && slash > 2 && slash < rest.length() - 1 && rest.indexOf('/', slash + 1) < 0;
}
/**
@@ -927,9 +938,9 @@ public class CodeArtifactNpmDataPlane {
/**
* {@code namespace} is the npm scope without its leading {@code @}, or {@code null} for an
* unscoped package, the same shape {@link RepositorySidecarManager#fetchPackageVersionAsset}
* takes everywhere else. {@code rest} is a bare-package publish path, exactly one segment
* ({@link #isPublish} already confirmed that): {@code /<name>} unscoped, or {@code
* /@scope%2Fname} scoped, with the scope separator arriving percent-encoded since Netty
* takes everywhere else. {@code rest} is a bare-package publish path ({@link #isPublish}
* already confirmed that): {@code /<name>} unscoped, or {@code /@scope/name} scoped, or
* {@code /@scope%2Fname}, with the scope separator arriving percent-encoded since Netty
* leaves a {@code %2F} undecoded in {@link HttpServerRequest#path()}
* specifically so it is never confused with a real path separator. The one, targeted decode
* here undoes exactly that, and only that: every other npm package-name character is already
@@ -47,6 +47,7 @@ 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.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -466,6 +467,115 @@ class CodeArtifactNpmDataPlaneTest {
assertEquals(false, upstreamReceivedPut.get());
}
/**
* Issue #7439: a scoped publish may name its package with a literal slash ({@code PUT
* /@scope/name}, the shape VerdaccioSidecarClient itself publishes with) instead of {@code
* %2F}. It is the same publish, so a blocked package refuses it the same way.
*/
@Test
void aLiteralSlashScopedPublishToABlockedPackageIsRefused() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
CodeArtifactService service = blockedPublishService("scope", "my-pkg");
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@scope/my-pkg", "good-token",
publishEnvelope("@scope/my-pkg", "1.0.0", "my-pkg-1.0.0.tgz",
"fresh bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
/**
* Issue #7439: the literal slash form reaches the Archived/Disposed guard too.
*/
@Test
void aLiteralSlashScopedPublishToAnArchivedVersionIsRefused() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
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);
doThrow(new AwsException("ConflictException", "Package version '1.0.0' of package 'my-pkg' is Archived "
+ "and cannot be republished.", 409))
.when(service).requireContainerBackedVersionNotArchivedOrDisposed(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), eq("scope"), eq("my-pkg"), eq("1.0.0"));
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@scope/my-pkg", "good-token",
publishEnvelope("@scope/my-pkg", "1.0.0", "my-pkg-1.0.0.tgz",
"fresh bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
/**
* An allowed literal slash publish still reaches Verdaccio at the path the client sent, and
* its bytes are counted under the scope and name that path carries.
*/
@Test
void aLiteralSlashScopedPublishIsForwardedAsSentAndAccountedUnderItsScope() throws Exception {
AtomicReference<String> upstreamPutPath = new AtomicReference<>();
upstream = vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
upstreamPutPath.set(request.path());
}
request.response().setStatusCode(201).end();
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@scope/my-pkg", "good-token",
publishEnvelope("@scope/my-pkg", "1.0.0", "my-pkg-1.0.0.tgz",
"fresh bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(201, response.statusCode());
assertEquals("/@scope/my-pkg", upstreamPutPath.get());
verify(service, timeout(2000)).recordContainerBackedAssetBytes(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), eq("scope"), eq("my-pkg"), anyLong(), anyLong());
}
/**
* Only the bare scoped package path is a publish: a dist-tag update to a blocked package is a
* multi-segment {@code /-/package/...} PUT and is still proxied as before.
*/
@Test
void aDistTagPutToABlockedPackageIsStillProxied() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
CodeArtifactService service = blockedPublishService("scope", "my-pkg");
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY
+ "/-/package/@scope%2fmy-pkg/dist-tags/latest", "good-token", "\"1.0.0\"");
assertEquals(201, response.statusCode());
assertEquals(true, upstreamReceivedPut.get());
}
private HttpServer startUpstreamRecordingPuts(AtomicReference<Boolean> receivedPut) throws Exception {
return vertx.createHttpServer()
.requestHandler(request -> {
@@ -32,8 +32,11 @@ import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -873,6 +876,67 @@ class CodeArtifactNpmDockerIntegrationTest {
assertArrayEquals(tarball, fetchedAfterUnarchive);
}
/**
* Issue #7439, against the real Verdaccio: a scoped publish sent with a literal slash ({@code
* PUT /@scope/name}) is accepted by Verdaccio as is, so it must take the guarded publish route.
* Its bytes are counted, a publish:BLOCK origin configuration refuses the next version, and
* lifting the block lets that version through.
*/
@Test
@Order(23)
void aLiteralSlashScopedPublishIsCountedAndRespectsAPublishBlock() {
String scope = "flociscope";
String packageName = "literal-slash-pkg";
String literalPath = "/codeartifact/npm/" + DOMAIN + "/" + REPO + "/@" + scope + "/" + packageName;
byte[] firstTarball = "literal slash throwaway tarball 1".getBytes(StandardCharsets.UTF_8);
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
given().urlEncodingEnabled(false).header("Authorization", "Bearer " + bearerToken)
.contentType("application/json").body(scopedEnvelope(scope, packageName, "1.0.0", firstTarball))
.put(literalPath)
.then().statusCode(anyOf201Or200());
assertEquals(assetSizeBytesBefore + firstTarball.length, describeDomainAssetSizeBytes());
setNpmOriginRestrictions(scope, packageName, "BLOCK");
String secondVersion = scopedEnvelope(scope, packageName, "2.0.0",
"literal slash throwaway tarball 2".getBytes(StandardCharsets.UTF_8));
given().urlEncodingEnabled(false).header("Authorization", "Bearer " + bearerToken)
.contentType("application/json").body(secondVersion)
.put(literalPath)
.then().statusCode(409)
.body(containsString("blocks direct publish"));
given().urlEncodingEnabled(false).header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/@" + scope + "%2F" + packageName)
.then().statusCode(200)
.body("versions", hasKey("1.0.0"))
.body("versions", not(hasKey("2.0.0")));
setNpmOriginRestrictions(scope, packageName, "ALLOW");
given().urlEncodingEnabled(false).header("Authorization", "Bearer " + bearerToken)
.contentType("application/json").body(secondVersion)
.put(literalPath)
.then().statusCode(anyOf201Or200());
}
private static String scopedEnvelope(String scope, String packageName, String version, byte[] tarball) {
String npmName = "@" + scope + "/" + packageName;
String assetName = packageName + "-" + version + ".tgz";
return "{\"name\":\"" + npmName + "\",\"versions\":{\"" + version + "\":{\"name\":\"" + npmName
+ "\",\"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 setNpmOriginRestrictions(String scope, String packageName, String publish) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"" + publish + "\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm&namespace=" + scope
+ "&package=" + packageName)
.then().statusCode(200)
.body("originConfiguration.restrictions.publish", equalTo(publish));
}
/**
* Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on