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}