fix(codeartifact): enforce publish:BLOCK on native Maven, npm, pypi and NuGet publishes (#7304)

This commit is contained in:
David authored and GitHub committed 2026-11-03 14:24:23 -04:00
1 parent bb6f46c104
commit 0454c354f7
12 files changed
+627 -27

No files matched your search

@@ -18,7 +18,9 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
@@ -68,6 +70,18 @@ public class CodeArtifactMavenController {
}
MavenRequestScope scope = requireScope(headers, domain, repository);
Optional<String[]> coordinate = parseNamespaceAndPackageName(gav);
// A package whose origin configuration sets publish:BLOCK refuses every mvn deploy, the
// same way PublishPackageVersion refuses it for the generic format. The restriction is
// per package, so a bare maven-metadata.xml PUT (no version) is refused too, and it runs
// ahead of every check below, Reposilite's own byte-identical republish included.
try {
for (String[] checked : publishCheckedPackages(gav)) {
service.requireContainerBackedPackagePublishAllowed(scope.region(), domain, scope.owner(),
repository, "maven", checked[0], checked[1]);
}
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
// Raised by hectorvent's review: a real mvn deploy to a coordinate
// updatePackageVersionsStatus/disposePackageVersions left Archived or Disposed must be
// refused outright, the same way PublishPackageVersion already refuses it for the generic
@@ -143,28 +157,55 @@ public class CodeArtifactMavenController {
* {@link #isMavenMetadataFile}. Once that is known, the artifactId is always the segment
* directly before it, no version segment in between, so this takes one fewer trailing segment
* than the ordinary rule does, and the returned version is {@code null} rather than guessed.
* A versioned snapshot's own {@code .../<version>/maven-metadata.xml} is the one real path
* this still gets slightly wrong for the namespace/packageName pair, reading the version
* string itself as the package name instead of skipping over it; accepted rather than chased
* further, since that pair is only ever used for a byte count summed at the domain level
* (never read back by package), and this one rare case still adds its real byte count to the
* right total under a harmless, if misnamed, bucket nothing else will ever look up by that
* name. The version element has no such approximation to make: it is {@code null} exactly
* when there genuinely is no version in the path.
* The one exception is a snapshot's own version-level {@code
* .../<artifactId>/<version>-SNAPSHOT/maven-metadata.xml}, the only version directory a
* real {@code mvn deploy} writes metadata into: the {@code -SNAPSHOT} segment is the version,
* not the artifactId, so it resolves exactly like a versioned GAV. Raised by Greptile and
* pgermosen's review: the publish:BLOCK check reads this pair back by package, so reading
* the version as the package name would let a blocked snapshot's metadata through.
*/
static Optional<String[]> parseNamespaceAndPackageName(String gav) {
String[] segments = gav.split("/");
boolean metadataFile = isMavenMetadataFile(segments[segments.length - 1]);
int packageNameIndex = metadataFile ? segments.length - 2 : segments.length - 3;
boolean versionLevelMetadata = metadataFile && segments.length >= 4
&& segments[segments.length - 2].endsWith("-SNAPSHOT");
boolean bareMetadata = metadataFile && !versionLevelMetadata;
int packageNameIndex = bareMetadata ? segments.length - 2 : segments.length - 3;
if (packageNameIndex < 1) {
return Optional.empty();
}
String packageName = segments[packageNameIndex];
String namespace = String.join(".", Arrays.asList(segments).subList(0, packageNameIndex));
String version = metadataFile ? null : segments[packageNameIndex + 1];
String version = bareMetadata ? null : segments[packageNameIndex + 1];
return Optional.of(new String[] {namespace, packageName, version});
}
/**
* The (namespace, packageName) pairs the publish:BLOCK check runs against for {@code gav}:
* {@link #parseNamespaceAndPackageName}'s own pair, plus, for a {@code maven-metadata.xml}
* whose parent segment ends in {@code -SNAPSHOT}, the artifact-level reading as well. The
* layout alone cannot tell {@code com/example/widget/1.0-SNAPSHOT/maven-metadata.xml}, a
* snapshot's version metadata, from {@code com/example/widget-SNAPSHOT/maven-metadata.xml},
* the bare metadata of an artifact named {@code widget-SNAPSHOT}, so a block on either reading
* refuses it (Greptile and pgermosen's review).
*/
static List<String[]> publishCheckedPackages(String gav) {
Optional<String[]> coordinate = parseNamespaceAndPackageName(gav);
if (coordinate.isEmpty()) {
return List.of();
}
List<String[]> packages = new ArrayList<>();
packages.add(new String[] {coordinate.get()[0], coordinate.get()[1]});
String[] segments = gav.split("/");
int artifactIndex = segments.length - 2;
if (isMavenMetadataFile(segments[segments.length - 1]) && artifactIndex >= 2
&& segments[artifactIndex].endsWith("-SNAPSHOT")) {
packages.add(new String[] {String.join(".", Arrays.asList(segments).subList(0, artifactIndex)),
segments[artifactIndex]});
}
return packages;
}
private static boolean isMavenMetadataFile(String filename) {
return filename.equals("maven-metadata.xml") || filename.startsWith("maven-metadata.xml.");
}
@@ -742,9 +742,11 @@ public class CodeArtifactNpmDataPlane {
* twine sends no {@code description} field, so a published version without a readme is never
* mistaken for one that was never published at all.
*
* <p>{@code blockedMessage} is non-null exactly when some version in the envelope is Archived
* or Disposed (see {@link CodeArtifactService#requireContainerBackedVersionNotArchivedOrDisposed}),
* found while this check already has every version in hand; the caller refuses the whole
* <p>{@code blockedMessage} is non-null exactly when the package's origin configuration blocks
* direct publish (see {@link CodeArtifactService#requireContainerBackedPackagePublishAllowed}),
* or some version in the envelope is Archived or Disposed (see {@link
* CodeArtifactService#requireContainerBackedVersionNotArchivedOrDisposed}), found while this
* check already has every version in hand; the caller refuses the whole
* publish on it rather than reaching {@code confirmed} or forwarding anything, since the User
* Guide blocks both statuses unconditionally, byte-identical content included.
*
@@ -762,6 +764,17 @@ public class CodeArtifactNpmDataPlane {
private RepublishCheck checkRepublish(String backendBaseUrl, NpmRequest npmRequest, String spoolPath,
AuthorizationTokenScope scope) {
PackageIdentity identity = packageIdentityFromPath(npmRequest.rest());
// A package whose origin configuration sets publish:BLOCK refuses every npm publish, the
// same way PublishPackageVersion refuses it for the generic format. The restriction is per
// package, so it needs nothing from the envelope and runs ahead of every branch below:
// the confirmed byte-identical republish, and an envelope too malformed to scan, which is
// otherwise forwarded unchanged.
try {
service.requireContainerBackedPackagePublishAllowed(scope.region(), npmRequest.domain(), scope.owner(),
npmRequest.repository(), "npm", identity.namespace(), identity.packageName());
} catch (AwsException e) {
return new RepublishCheck(false, 0L, identity, Map.of(), e.getMessage(), Map.of());
}
NpmPublishEnvelopeScanner.Envelope envelope;
try (InputStream in = new BufferedInputStream(Files.newInputStream(Path.of(spoolPath)))) {
envelope = NpmPublishEnvelopeScanner.scan(in);
@@ -218,6 +218,18 @@ public class CodeArtifactNuGetController {
String packageName = nuspec.id().toLowerCase(Locale.ROOT);
String version = NuGetVersions.normalize(nuspec.version());
// A package whose origin configuration sets publish:BLOCK refuses every dotnet nuget push,
// the same way PublishPackageVersion refuses it for the generic format, ahead of the
// byte-identical shortcut below: a retry of bytes already stored is still a publish. Also
// the default for a package first retained from nuget.org (see
// CodeArtifactService#ensureRetainedPackageOriginDefault).
try {
service.requireContainerBackedPackagePublishAllowed(handle.region(), domain, handle.owner(), repository,
"nuget", null, packageName);
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
// Raised by hectorvent's review: a real dotnet nuget push to a coordinate
// updatePackageVersionsStatus/disposePackageVersions left Archived or Disposed must be
// refused outright, the same way PublishPackageVersion already refuses it for the generic
@@ -207,6 +207,22 @@ public class CodeArtifactPypiController {
.build();
}
// A package whose origin configuration sets publish:BLOCK refuses every twine upload, the
// same way PublishPackageVersion refuses it for the generic format, ahead of the
// byte-identical shortcut below: a retry of bytes already stored is still a publish.
// pypiserver files the upload under the name its own filename parser derives and never
// reads the form's name field, so that derived name is the one checked, version field or
// not (Greptile and pgermosen's review). A filename it cannot parse is one pypiserver
// rejects anyway; the form's name stands in for it then.
String publishCheckedName = PypiserverSidecarClient.guessPackageName(file.get().filename())
.orElse(packageName);
try {
service.requireContainerBackedPackagePublishAllowed(handle.region(), domain, handle.owner(), repository,
"pypi", null, publishCheckedName);
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
Object lock = uploadLocks.computeIfAbsent(handle.repoId(), k -> new Object());
synchronized (lock) {
// Raised by hectorvent's review: a real twine upload to a coordinate
@@ -901,19 +901,8 @@ public class CodeArtifactService implements Resettable {
// operation before any idempotency check below, the same way a real prerequisite failure
// would: a retry of already-published bytes is still a PublishPackageVersion call, and
// AWS's own documented behavior ("version 1.2 cannot be published" once Publish is set to
// Block) draws no bytes-already-match exception to it. accountingPackageName, not the raw
// packageName, so this sees the same config PutPackageOriginConfiguration/
// isUpstreamRetentionBlocked now key by for a format (nuget, pypi) whose names are
// case/punctuation normalized.
String originKey = packageKey(region, domain, repository, format, namespace,
accountingPackageName(format, packageName));
String publishRestriction = packageOriginConfigs.getForAccount(owner, originKey)
.map(PackageOriginConfig::getPublishRestriction)
.orElse("ALLOW");
if ("BLOCK".equals(publishRestriction)) {
throw conflict("Package '" + packageName + "' cannot be published because its origin configuration "
+ "blocks direct publish.", packageName, "package");
}
// Block) draws no bytes-already-match exception to it.
requireDirectPublishAllowed(owner, region, domain, repository, format, namespace, packageName);
String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version);
CodeArtifactPackageVersion pv = packageVersions.getForAccount(owner, key).orElse(null);
@@ -2248,6 +2237,44 @@ public class CodeArtifactService implements Resettable {
version);
}
/**
* The native publish paths' counterpart to the publish:BLOCK check {@link
* #publishPackageVersion} runs for the generic format: {@code mvn deploy}, {@code npm publish},
* {@code twine upload} and {@code dotnet nuget push} each reach their own controller rather
* than {@code PublishPackageVersion}, so each controller calls this before its real sidecar
* write and before its own byte-identical republish shortcut. The restriction is per package,
* not per version, so it applies whether or not the request names a version at all.
*
* <p>Covers a restriction set through {@link #putPackageOriginConfiguration} and the
* publish:BLOCK default {@link #ensureRetainedPackageOriginDefault} writes for a package first
* retained from an external connection. Retention itself never passes through here: each
* external connection importer writes to its sidecar directly.
*/
public synchronized void requireContainerBackedPackagePublishAllowed(String region, String domain,
String domainOwner, String repository, String format, String namespace, String packageName) {
requireDirectPublishAllowed(effectiveOwner(domainOwner), region, domain, repository, format, namespace,
packageName);
}
/**
* Keyed through {@link #accountingPackageName}, not the raw {@code packageName}, so this sees
* the same config {@link #putPackageOriginConfiguration} and {@link
* #isUpstreamRetentionBlocked} key by for a format (nuget, pypi) whose names are
* case/punctuation normalized.
*/
private void requireDirectPublishAllowed(String owner, String region, String domain, String repository,
String format, String namespace, String packageName) {
String originKey = packageKey(region, domain, repository, format, namespace,
accountingPackageName(format, packageName));
String publishRestriction = packageOriginConfigs.getForAccount(owner, originKey)
.map(PackageOriginConfig::getPublishRestriction)
.orElse("ALLOW");
if ("BLOCK".equals(publishRestriction)) {
throw conflict("Package '" + packageName + "' cannot be published because its origin configuration "
+ "blocks direct publish.", packageName, "package");
}
}
/**
* Raised by hectorvent's review of this same PR: {@link #forgetContainerBackedStatusOverride}
* only ever ran <em>after</em> each native proxy controller's real sidecar write already
@@ -24,6 +24,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -35,6 +36,16 @@ import java.util.regex.Pattern;
public class PypiserverSidecarClient implements RepositorySidecarManager {
private static final Pattern SIMPLE_INDEX_HREF = Pattern.compile("href=\"([^\"]*)\"");
// The three patterns below are pypiserver 2.4.2's own, from pypiserver/pkg_helpers.py, ported
// verbatim for guessPackageName.
private static final Pattern ARCHIVE_SUFFIX = Pattern.compile(
"(\\.zip|\\.tar\\.gz|\\.tgz|\\.tar\\.bz2|\\.tar\\.xz|-py[23]\\.\\d-.*|"
+ "\\.win-amd64-py[23]\\.\\d\\..*|\\.win32-py[23]\\.\\d\\..*|\\.egg)$",
Pattern.CASE_INSENSITIVE);
private static final Pattern WHEEL_FILE = Pattern.compile(
"^(?<namever>(?<name>.+?)-(?<ver>\\d.*?))"
+ "((-(?<build>\\d.*?))?-(?<pyver>.+?)-(?<abi>.+?)-(?<plat>.+?)\\.whl|\\.dist-info)$");
private static final Pattern PKGNAME_END = Pattern.compile("-\\d+[a-z_.!+]", Pattern.CASE_INSENSITIVE);
private final PypiserverSidecarManager manager;
private final ObjectMapper mapper;
@@ -565,6 +576,47 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
private static final List<String> PEP440_CONTINUATION_PREFIXES =
List.of("alpha", "beta", "preview", "pre", "post", "rev", "dev", "rc");
/**
* The package name pypiserver 2.4.2 files an upload of {@code filename} under: a port of its
* {@code guess_pkgname_and_version} (pypiserver/pkg_helpers.py), name part only. pypiserver
* stores an upload by its raw filename and never reads the form's {@code name} field, so this,
* not that field, is the package a publish:BLOCK check must name (pgermosen's review). Empty
* exactly when pypiserver itself rejects the filename as a bad one.
*
* <p>{@code rstrip(".asc")} is ported as Python runs it: it strips any trailing run of the
* characters {@code .}, {@code a}, {@code s} and {@code c}, not the suffix.
*/
static Optional<String> guessPackageName(String filename) {
String path = filename.substring(filename.lastIndexOf('/') + 1);
if (path.endsWith(".asc")) {
int end = path.length();
while (end > 0 && ".asc".indexOf(path.charAt(end - 1)) >= 0) {
end--;
}
path = path.substring(0, end);
}
if (path.endsWith(".whl")) {
Matcher wheel = WHEEL_FILE.matcher(path);
return wheel.find() ? Optional.of(wheel.group("name")) : Optional.empty();
}
if (!ARCHIVE_SUFFIX.matcher(path).find()) {
return Optional.empty();
}
path = ARCHIVE_SUFFIX.matcher(path).replaceAll("");
int dashes = path.length() - path.replace("-", "").length();
if (dashes == 0) {
return Optional.of(path);
}
if (dashes == 1) {
return Optional.of(path.substring(0, path.indexOf('-')));
}
if (path.indexOf('.') < 0) {
return Optional.of(path.substring(0, path.lastIndexOf('-')));
}
Matcher end = PKGNAME_END.matcher(path);
return Optional.of(end.find() ? path.substring(0, end.start()) : path);
}
/**
* Real PyPI filenames always embed their own version right after a {@code -} (PEP 427/517
* naming: {@code <name>-<version>.<ext>} for an sdist, {@code <name>-<version>-<tags>.whl}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.DeployOutcome;
import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
@@ -8,10 +10,15 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -21,7 +28,9 @@ import static org.mockito.Mockito.when;
* {@link CodeArtifactMavenController#fetch}'s own decision of when to ask {@link
* CodeArtifactMavenExternalConnectionImporter} to attempt an external-connection import at all,
* not the importer's or {@link ReposiliteSidecarClient}'s own logic, which each have their own
* tests. Both collaborators are mocked, so no real sidecar or network call ever happens here.
* tests, and {@link CodeArtifactMavenController#deploy}'s refusal of a package whose origin
* configuration blocks publish. Both collaborators are mocked, so no real sidecar or network call
* ever happens here.
*/
class CodeArtifactMavenControllerTest {
@@ -95,4 +104,111 @@ class CodeArtifactMavenControllerTest {
assertEquals(200, response.getStatus());
verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK must refuse a real mvn
* deploy the way PublishPackageVersion already refuses it for the generic format, before
* anything reaches Reposilite, so not even a byte-identical redeploy gets through.
*/
@Test
void aDeployToAPackageWhoseOriginConfigurationBlocksPublishIsRefusedWithoutReachingReposilite() {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, "com/example/widget/1.0/widget-1.0.jar",
"jar-bytes".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
/**
* The restriction is per package, not per version, so the bare maven-metadata.xml PUT every
* mvn deploy also sends (no version segment, so the Archived/Disposed guard skips it) is
* refused too.
*/
@Test
void aBareMetadataDeployToABlockedPackageIsRefusedToo() {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, METADATA_GAV,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
/**
* A snapshot's version-level maven-metadata.xml (and each checksum sibling) belongs to the
* artifact above its version directory, so a block on that artifact refuses it as well. Raised
* by Greptile and pgermosen's review: this path used to resolve to package {@code 1.0-SNAPSHOT}
* in namespace {@code com.example.widget}, which no block ever names.
*/
@Test
void aSnapshotVersionMetadataDeployToABlockedPackageIsRefusedToo() {
blockPublish("com.example", "widget");
for (String gav : List.of("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml",
"com/example/widget/1.0-SNAPSHOT/maven-metadata.xml.sha1")) {
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, gav,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus(), gav);
}
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
@Test
void parseNamespaceAndPackageNameResolvesSnapshotVersionMetadataToItsArtifact() {
String[] snapshot = CodeArtifactMavenController
.parseNamespaceAndPackageName("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml").orElseThrow();
String[] bare = CodeArtifactMavenController
.parseNamespaceAndPackageName("com/example/widget/maven-metadata.xml").orElseThrow();
assertArrayEquals(new String[] {"com.example", "widget", "1.0-SNAPSHOT"}, snapshot);
assertArrayEquals(new String[] {"com.example", "widget", null}, bare);
}
/**
* Greptile and pgermosen's review: {@code com/example/widget-SNAPSHOT/maven-metadata.xml} is
* also the bare metadata of an artifact named {@code widget-SNAPSHOT}, so a block on that
* artifact refuses it even though the path parses as a snapshot's version metadata.
*/
@Test
void bareMetadataOfAnArtifactWhoseNameEndsInSnapshotIsRefusedWhenThatArtifactIsBlocked() {
blockPublish("com.example", "widget-SNAPSHOT");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY,
"com/example/widget-SNAPSHOT/maven-metadata.xml", "<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
@Test
void publishCheckedPackagesNamesBothReadingsOnlyForAmbiguousMetadata() {
assertEquals(List.of("com.example:widget", "com.example.widget:1.0-SNAPSHOT"),
readings("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml.sha1"));
assertEquals(List.of("com.example:widget"), readings("com/example/widget/maven-metadata.xml"));
assertEquals(List.of("com.example:widget"),
readings("com/example/widget/1.0-SNAPSHOT/widget-1.0-SNAPSHOT.jar"));
}
private static List<String> readings(String gav) {
return CodeArtifactMavenController.publishCheckedPackages(gav).stream()
.map(pair -> pair[0] + ":" + pair[1])
.toList();
}
private void blockPublish(String namespace, String packageName) {
// What Reposilite would answer if the deploy got through, so a missing refusal fails on
// the status assertion rather than on a null outcome.
when(reposilite.deployArtifact(any(), any(), any()))
.thenReturn(new DeployOutcome(201, true));
doThrow(new AwsException("ConflictException", "Package '" + packageName + "' cannot be published because "
+ "its origin configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("maven"), eq(namespace), eq(packageName));
}
}
@@ -419,6 +419,78 @@ class CodeArtifactNpmDataPlaneTest {
any(), any(), any(), any());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK refuses an npm publish
* the way PublishPackageVersion already refuses it for the generic format, ahead of the
* byte-identical shortcut: Verdaccio already holds this exact tarball, which would otherwise
* answer 200 without forwarding.
*/
@Test
void aByteIdenticalRepublishToAPackageWhoseOriginConfigurationBlocksPublishIsRefused() throws Exception {
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
CodeArtifactService service = blockedPublishService(null, "my-pkg");
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
givenStoredVersion(verdaccioClient, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content));
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
/**
* The restriction needs nothing from the envelope, so a body too malformed to scan (which is
* otherwise forwarded unchanged for Verdaccio to reject) is refused too, scoped package
* included.
*/
@Test
void anUnscannablePublishToAScopedPackageWhoseOriginConfigurationBlocksPublishIsRefused() 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%2fmy-pkg",
"good-token", "{not json");
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
private HttpServer startUpstreamRecordingPuts(AtomicReference<Boolean> receivedPut) throws Exception {
return vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
receivedPut.set(true);
}
request.response().setStatusCode(201).end();
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
private static CodeArtifactService blockedPublishService(String namespace, String packageName) {
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 '" + packageName + "' cannot be published because "
+ "its origin configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), eq(namespace), eq(packageName));
return service;
}
/**
* Raised by Greptile's review: a real publish whose per-version {@code readme} exceeds
* {@code NpmPublishEnvelopeScanner}'s own stricter 1,000,000-character limit makes {@code
@@ -561,6 +561,61 @@ class CodeArtifactNuGetDockerIntegrationTest {
assertArrayEquals(nupkg, fetchedAfterUnarchive);
}
/**
* Issue #7116: publish:BLOCK set through the real PutPackageOriginConfiguration route used to
* stop only the generic format's PublishPackageVersion, never a real dotnet nuget push. Set
* under the nuspec id's own mixed-case spelling (the push path lowercases it), it now refuses
* a byte-identical re-push and a new version alike before BaGetter sees either, and lifting it
* lets the new version through. Its own package, so no other ordered test is disturbed.
*/
@Test
@Order(18)
void publishBlockedByOriginConfigurationRefusesARealPushUntilItIsLifted() {
String packageId = "Origin.Blocked.Package";
byte[] published = buildNupkg(packageId, VERSION, "Origin block throwaway.", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", published))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
setOriginRestrictions(packageId, "BLOCK");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", published))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(409)
.body(containsString("blocks direct publish"));
byte[] nextVersion = buildNupkg(packageId, "2.0.0", "Origin block throwaway.", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nextVersion))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(409);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/"
+ packageId.toLowerCase(Locale.ROOT) + "/index.json")
.then().statusCode(200)
.body("versions", equalTo(List.of(VERSION)));
setOriginRestrictions(packageId, "ALLOW");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nextVersion))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
}
private static void setOriginRestrictions(String packageId, String publish) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"" + publish + "\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package=" + packageId)
.then().statusCode(200)
.body("originConfiguration.restrictions.publish", equalTo(publish));
}
private static long describeDomainAssetSizeBytes() {
return given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
@@ -403,6 +403,111 @@ class CodeArtifactPypiControllerTest {
assertEquals(false, uploadReceived.get());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK refuses a twine upload
* the way PublishPackageVersion already refuses it for the generic format, ahead of the
* byte-identical shortcut above: the stored file here matches the upload exactly, and it is
* still a 409 with nothing forwarded.
*/
@Test
void uploadToAPackageWhoseOriginConfigurationBlocksPublishIsRefusedEvenForByteIdenticalContent() {
String sameContent = "same content";
backend.createContext("/simple/my-pkg/",
exchange -> respond(exchange, 200, "text/html", "<a href=\"my_pkg-1.0.tar.gz\">my_pkg-1.0.tar.gz</a>"));
backend.createContext("/packages/my_pkg-1.0.tar.gz",
exchange -> respond(exchange, 200, "application/octet-stream", sameContent));
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
// The name pypiserver files my_pkg-1.0.tar.gz under; the service normalizes it to my-pkg.
doThrow(new AwsException("ConflictException", "Package 'my_pkg' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("my_pkg"));
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", sameContent);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
/**
* Raised by Greptile and pgermosen's review: without a version field nothing ties the form's
* name to the filename pypiserver files the upload under, so a block on the package the
* filename names still refuses it when the form names an unrelated package.
*/
@Test
void uploadWithoutAVersionFieldIsCheckedAgainstThePackageItsFilenameNames() {
backend.createContext("/simple/other-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
doThrow(new AwsException("ConflictException", "Package 'my_pkg' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("my_pkg"));
byte[] body = multipartWithFile("boundary123", "other-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
}
/**
* pgermosen's review: pypiserver files {@code foo-1.0-bar-2.0.tar.gz} under {@code foo} even
* when the form names {@code foo-1.0-bar} at {@code 2.0}, so a block on {@code foo} refuses it.
*/
@Test
void uploadIsCheckedAgainstThePackagePypiserverFilesItUnderEvenWithAVersionField() {
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
doThrow(new AwsException("ConflictException", "Package 'foo' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("foo"));
byte[] body = multipartWithFileAndVersion("boundary123", "foo-1.0-bar", "2.0", "foo-1.0-bar-2.0.tar.gz",
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
}
/**
* Greptile's review: {@code demo-1.0-1-py3-none-any.whl} is a wheel of {@code demo} with build
* tag {@code 1}, so a block on {@code demo-1.0} must not refuse it.
*/
@Test
void aBuildTaggedWheelIsNotRefusedByABlockOnALongerName() {
backend.createContext("/simple/demo/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> respond(exchange, 200, "text/plain", ""));
doThrow(new AwsException("ConflictException", "Package 'demo-1.0' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("demo-1.0"));
byte[] body = multipartWithFile("boundary123", "demo", "demo-1.0-1-py3-none-any.whl", "wheel bytes");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(200, response.getStatus());
}
@Test
void uploadForwardsANewFileToTheBackendWhenNothingConflicts() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
@@ -840,6 +840,75 @@ class CodeArtifactServiceTest {
assertEquals("Published", published.packageVersion().getStatus());
}
/**
* The check each native publish path (mvn deploy, npm publish, twine upload, dotnet nuget
* push) runs before its sidecar write: refused exactly while the package's origin
* configuration says publish:BLOCK, the same rule publishPackageVersion applies to generic.
*/
@Test
void containerBackedPackagePublishIsRefusedOnlyWhilePublishIsBlocked() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget",
"BLOCK", "ALLOW");
AwsException blocked = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
assertEquals("ConflictException", blocked.getErrorCode());
// Scoped to that one package: a sibling in the same namespace still publishes.
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"other");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget",
"ALLOW", "ALLOW");
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
}
/**
* pypi and nuget names are case/punctuation insensitive, and PutPackageOriginConfiguration
* keys by the normalized spelling, so a restriction set under one spelling must block a
* publish that names the package under another (twine sends the name as typed in the
* project metadata, the nuget controller lowercases the nuspec id).
*/
@Test
void containerBackedPackagePublishBlockMatchesAnyNormalizedSpellingOfTheName() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", null, "My_Pkg", "BLOCK",
"BLOCK");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "nuget", null, "Demo.Package", "BLOCK",
"BLOCK");
assertThrows(AwsException.class, () -> service.requireContainerBackedPackagePublishAllowed(REGION, "dom",
null, "repo", "pypi", null, "my-pkg"));
assertThrows(AwsException.class, () -> service.requireContainerBackedPackagePublishAllowed(REGION, "dom",
null, "repo", "nuget", null, "demo.package"));
}
/**
* A package first retained from an external connection defaults to publish:BLOCK (the User
* Guide's "Default package origin control settings"), so a later direct publish of it is
* refused without anyone calling PutPackageOriginConfiguration.
*/
@Test
void containerBackedPackagePublishIsRefusedForAPackageFirstRetainedFromAnExternalConnection() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", "scope",
"left-pad");
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "npm", "scope", "left-pad", fence);
AwsException blocked = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "npm", "scope",
"left-pad"));
assertEquals("ConflictException", blocked.getErrorCode());
}
@Test
void createRepositoryAcceptsExistingUpstream() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -549,4 +549,26 @@ class PypiserverSidecarClientTest {
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
}
/**
* Each expected name is what pypiserver 2.4.2's own guess_pkgname_and_version returns for the
* same filename, run inside the pinned image: the port must file an upload under exactly the
* package pypiserver does, build-tagged wheels and names with a {@code -<digit>} run included.
*/
@Test
void guessPackageNameMatchesPypiserversOwnFilenameParser() {
assertEquals(Optional.of("my_pkg"), PypiserverSidecarClient.guessPackageName("my_pkg-1.0.tar.gz"));
assertEquals(Optional.of("foo"), PypiserverSidecarClient.guessPackageName("foo-1.0-bar-2.0.tar.gz"));
assertEquals(Optional.of("mypkg"), PypiserverSidecarClient.guessPackageName("mypkg-dev.tar.gz"));
assertEquals(Optional.of("demo"), PypiserverSidecarClient.guessPackageName("demo-1.0-1-py3-none-any.whl"));
assertEquals(Optional.of("demo"), PypiserverSidecarClient.guessPackageName("demo-1.0-py3-none-any.whl"));
assertEquals(Optional.of("My.Pkg"), PypiserverSidecarClient.guessPackageName("My.Pkg-2.0b1.zip"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0-py3.11-linux.egg"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0.win-amd64-py3.9.exe"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg.tar.gz"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0.tar.gz.asc"));
assertEquals(Optional.of("a-b"), PypiserverSidecarClient.guessPackageName("a-b-c.tgz"));
assertEquals(Optional.empty(), PypiserverSidecarClient.guessPackageName("notapackage.txt"));
assertEquals(Optional.empty(), PypiserverSidecarClient.guessPackageName("pkg-1.0.whl"));
}
}