feat(codeartifact): add UpdatePackageVersionsStatus and DisposePackageVersions (#6435)

Moves package versions between Published/Unlisted/Archived (UpdatePackageVersionsStatus)
or permanently to Disposed with real asset deletion (DisposePackageVersions), for generic
and every container-backed format. Both share the same all-or-nothing batch semantics,
NOT_FOUND/MISMATCHED_REVISION/MISMATCHED_STATUS/NOT_ALLOWED error codes, and SKIPPED
fallback confirmed against the User Guide's own worked examples.

Container-backed formats (maven/npm/pypi/nuget) get a new in-memory status-override store,
since none of their sidecars have a native status concept beyond existing-or-not; generic
already had status/revision on its own record. GetPackageVersionAsset now 404s for
Archived/Disposed versions (assets undownloadable per the User Guide), and
ListPackageVersions correctly surfaces real Archived/Disposed/Unlisted data instead of the
previously-unreachable filtering branch.

Verified end to end against all four real sidecar containers, not just mocks.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-24 22:14:01 -05:00
1 parent 64f4f9e489
commit 3053b35b84
20 files changed
+3409 -112

No files matched your search

@@ -19,6 +19,11 @@ public final class Digests {
}
}
/** The MD5 digest of {@code data} as lowercase hex. */
public static String md5Hex(byte[] data) {
return HexFormat.of().formatHex(md5(data));
}
public static byte[] sha1(byte[] data) {
try {
return MessageDigest.getInstance("SHA-1").digest(data);
@@ -541,6 +541,58 @@ public class CodeArtifactController {
return ok(response);
}
@POST
@Path("/v1/package/versions/update_status")
public Response updatePackageVersionsStatus(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("repository") String repository,
@QueryParam("format") String format,
@QueryParam("namespace") String namespace,
@QueryParam("package") String packageName, String body) {
JsonNode req = readTree(body);
String region = regionResolver.resolveRegion(headers);
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(region,
domain, domainOwner, repository, format, namespace, packageName,
readStringArray(req.get("versions"), "versions"), readStringMap(req.get("versionRevisions")),
req.path("expectedStatus").asText(null), req.path("targetStatus").asText(null));
return ok(packageVersionStatusChangeResponse(result));
}
@POST
@Path("/v1/package/versions/dispose")
public Response disposePackageVersions(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("repository") String repository,
@QueryParam("format") String format,
@QueryParam("namespace") String namespace,
@QueryParam("package") String packageName, String body) {
JsonNode req = readTree(body);
String region = regionResolver.resolveRegion(headers);
CodeArtifactService.PackageVersionStatusChangeResult result = service.disposePackageVersions(region, domain,
domainOwner, repository, format, namespace, packageName,
readStringArray(req.get("versions"), "versions"), readStringMap(req.get("versionRevisions")),
req.path("expectedStatus").asText(null));
return ok(packageVersionStatusChangeResponse(result));
}
private ObjectNode packageVersionStatusChangeResponse(CodeArtifactService.PackageVersionStatusChangeResult
result) {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode successfulVersions = response.putObject("successfulVersions");
result.successfulVersions().forEach((version, outcome) -> {
ObjectNode node = successfulVersions.putObject(version);
node.put("revision", outcome.revision());
node.put("status", outcome.status());
});
ObjectNode failedVersions = response.putObject("failedVersions");
result.failedVersions().forEach((version, failure) -> {
ObjectNode node = failedVersions.putObject(version);
node.put("errorCode", failure.errorCode());
node.put("errorMessage", failure.errorMessage());
});
return response;
}
// -------------------------------------------------------------------- tags
@POST
@@ -65,6 +65,26 @@ public class CodeArtifactMavenController {
}
MavenRequestScope scope = requireScope(headers, domain, repository);
Optional<String[]> coordinate = parseNamespaceAndPackageName(gav);
// 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
// format, not accepted and then have forgetContainerBackedStatusOverride below silently
// un-block it afterward. Checked before the real write, not after; the version element is
// null for a bare maven-metadata.xml PUT (see this coordinate's own javadoc), which never
// represents a specific version to block either way. The returned revision (or null) is
// held onto below: raised by Greptile's review, a concurrent status change landing between
// this check and the clear below must not be erased by it (see
// CodeArtifactService#forgetContainerBackedStatusOverrideIfUnchanged's own javadoc).
String beforeRevision = null;
if (coordinate.filter(c -> c[2] != null).isPresent()) {
String[] c = coordinate.get();
try {
beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(scope.region(), domain,
scope.owner(), repository, "maven", c[0], c[1], c[2]);
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
}
// Snapshotted before the real write, not after: see
// CodeArtifactService#currentContainerBackedPackageFence's own javadoc for why the order
// matters.
@@ -74,17 +94,31 @@ public class CodeArtifactMavenController {
if (outcome.wroteNewContent()) {
coordinate.ifPresent(c -> service.recordContainerBackedAssetBytes(scope.region(), domain, scope.owner(),
repository, "maven", c[0], c[1], content.length, fenceSnapshot.get()));
// Found by Qodo review: a real mvn deploy to a coordinate updatePackageVersionsStatus/
// disposePackageVersions previously archived or disposed would still have its fresh
// content blocked by that stale override, since nothing before this cleared it for a
// native publish the way copyPackageVersions now does for its own overwrite path. The
// version element is null for a bare maven-metadata.xml PUT (see this coordinate's own
// javadoc), which never represents a specific version to clear an override for anyway.
// By this point the guard above has already refused an Archived/Disposed coordinate,
// so the only override left to clear here is Unlisted (or none), and only if it is
// still exactly what the guard above saw.
String beforeRevisionFinal = beforeRevision;
coordinate.filter(c -> c[2] != null).ifPresent(c -> service.forgetContainerBackedStatusOverrideIfUnchanged(
scope.region(), domain, scope.owner(), repository, "maven", c[0], c[1], c[2],
beforeRevisionFinal));
}
return Response.status(outcome.status()).build();
}
/**
* Splits a GAV path ({@code <groupId-as-slashes>/<artifactId>/<version>/<filename>}, the real
* Maven repository layout) into CodeArtifact's Maven namespace (dot-joined groupId) and
* package name (artifactId), the inverse of what {@code ReposiliteSidecarClient}'s own
* namespace/packageName-aware methods already build. Only ever used for byte accounting, a
* side channel that must never fail a publish that would otherwise succeed, so a path with too
* few segments to be a well-formed GAV is reported as unknown rather than thrown.
* Maven repository layout) into CodeArtifact's Maven namespace (dot-joined groupId), package
* name (artifactId), and version: the inverse of what {@code ReposiliteSidecarClient}'s own
* namespace/packageName-aware methods already build. The namespace/packageName pair is used
* for byte accounting, a side channel that must never fail a publish that would otherwise
* succeed, so a path with too few segments to be a well-formed GAV is reported as unknown
* rather than thrown.
*
* <p>{@code maven-metadata.xml} (and its {@code .sha1}/{@code .md5}/{@code .sha256} checksum
* siblings) needs its own rule, not the ordinary one below: every real {@code mvn deploy} also
@@ -94,23 +128,27 @@ public class CodeArtifactMavenController {
* alone can't tell the two apart; the filename itself can, and already does, via
* {@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. A versioned snapshot's own {@code .../<version>/
* maven-metadata.xml} is the one real path this still gets slightly wrong, reading the version
* 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 this is a byte count summed at the domain level only (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.
* 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.
*/
private static Optional<String[]> parseNamespaceAndPackageName(String gav) {
String[] segments = gav.split("/");
int packageNameIndex = isMavenMetadataFile(segments[segments.length - 1])
? segments.length - 2 : segments.length - 3;
boolean metadataFile = isMavenMetadataFile(segments[segments.length - 1]);
int packageNameIndex = metadataFile ? 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));
return Optional.of(new String[] {namespace, packageName});
String version = metadataFile ? null : segments[packageNameIndex + 1];
return Optional.of(new String[] {namespace, packageName, version});
}
private static boolean isMavenMetadataFile(String filename) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.core.exc.StreamConstraintsException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -285,7 +286,8 @@ public class CodeArtifactNpmDataPlane {
}
String backendBaseUrl = readyResult.result();
vertx.<RepublishCheck>executeBlocking(promise ->
promise.complete(checkRepublish(backendBaseUrl, npmRequest, path)),
promise.complete(checkRepublish(backendBaseUrl, npmRequest, path,
scope)),
false)
.onComplete(checkResult -> {
if (context.response().closed()) {
@@ -294,7 +296,28 @@ public class CodeArtifactNpmDataPlane {
}
RepublishCheck check = checkResult.succeeded() ? checkResult.result()
: new RepublishCheck(false, 0L,
packageIdentityFromPath(npmRequest.rest()), Map.of());
packageIdentityFromPath(npmRequest.rest()), Map.of(),
null, Map.of());
// Raised by hectorvent's review: a real npm publish to a
// coordinate updatePackageVersionsStatus/
// disposePackageVersions left Archived or Disposed must be
// refused outright, the same way PublishPackageVersion
// already refuses it for the generic format, not accepted
// and then have forgetContainerBackedStatusOverride below
// silently un-block it afterward. Checked ahead of the
// idempotent-republish shortcut too: that shortcut only
// ever matches when Verdaccio's own stored content is
// still byte-identical, which archiving (unlike disposing)
// never changes, and the User Guide draws no
// byte-identical exception for either status.
if (check.blockedMessage() != null) {
context.response().putHeader("Content-Type", "application/json")
.setStatusCode(409)
.end("{\"error\":\"forbidden\",\"reason\":\""
+ check.blockedMessage() + "\"}");
finish.run();
return;
}
if (check.confirmed()) {
// "ok" is a message string in a real Verdaccio response
// (e.g. "created new package"), not a boolean; matching
@@ -333,7 +356,8 @@ public class CodeArtifactNpmDataPlane {
reopened.result(), scope, npmRequest.domain(),
npmRequest.repository(), check.identity(),
check.totalAttachmentBytes(), fenceSnapshot,
check.readmeByVersion());
check.readmeByVersion(),
check.beforeRevisionByVersion());
});
});
});
@@ -442,25 +466,83 @@ public class CodeArtifactNpmDataPlane {
* into {@code ""}, the same empty-string answer pypi's own upload path already records when
* 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
* publish on it rather than reaching {@code confirmed} or forwarding anything, since the User
* Guide blocks both statuses unconditionally, byte-identical content included.
*
* <p>{@code beforeRevisionByVersion} carries what {@link
* CodeArtifactService#requireContainerBackedVersionNotArchivedOrDisposed} returned for each
* version while that same guard ran (the same key set as {@code readmeByVersion}, minus any
* version a {@code blockedMessage} short-circuited before its own turn); the caller passes it
* straight into {@link CodeArtifactService#forgetContainerBackedStatusOverrideIfUnchanged} once
* its own forward succeeds, so a status change that lands after this check ran is never erased
* (Greptile review).
*/
private record RepublishCheck(boolean confirmed, long totalAttachmentBytes, PackageIdentity identity,
Map<String, String> readmeByVersion) {}
Map<String, String> readmeByVersion, String blockedMessage, Map<String, String> beforeRevisionByVersion) {}
private RepublishCheck checkRepublish(String backendBaseUrl, NpmRequest npmRequest, String spoolPath) {
private RepublishCheck checkRepublish(String backendBaseUrl, NpmRequest npmRequest, String spoolPath,
AuthorizationTokenScope scope) {
PackageIdentity identity = packageIdentityFromPath(npmRequest.rest());
NpmPublishEnvelopeScanner.Envelope envelope;
try (InputStream in = new BufferedInputStream(Files.newInputStream(Path.of(spoolPath)))) {
envelope = NpmPublishEnvelopeScanner.scan(in);
} catch (StreamConstraintsException e) {
LOG.debugv(e, "Publish for {0}/{1} is not a confirmable republish: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
// Raised by Greptile's review: forwarding unconditionally on any scan failure, as
// the catch block below still does for anything else, would also skip the
// Archived/Disposed guard entirely for a publish that failed only
// NpmPublishEnvelopeScanner#scan's own stricter limit (an oversized readme, see
// NpmPublishEnvelopeScanner#scanLeniently's own javadoc), not because anything is
// actually wrong with it; StreamConstraintsException is specifically that case, not
// genuinely malformed JSON (a plain JsonParseException, handled below exactly as
// before). That second, far-more-tolerant pass recovers just the version names so the
// guard can still run; if even that fails, there is no safe way left to know what
// this publish names, so it is refused outright instead of silently forwarded with no
// guard having run.
Set<String> versionsFromLenientScan;
try (InputStream in = new BufferedInputStream(Files.newInputStream(Path.of(spoolPath)))) {
versionsFromLenientScan = NpmPublishEnvelopeScanner.scanLeniently(in).versions().keySet();
} catch (IOException lenientFailure) {
return new RepublishCheck(false, 0L, identity, Map.of(),
"Could not determine which version(s) this publish names.", Map.of());
}
for (String version : versionsFromLenientScan) {
try {
service.requireContainerBackedVersionNotArchivedOrDisposed(scope.region(), npmRequest.domain(),
scope.owner(), npmRequest.repository(), "npm", identity.namespace(),
identity.packageName(), version);
} catch (AwsException blocked) {
return new RepublishCheck(false, 0L, identity, Map.of(), blocked.getMessage(), Map.of());
}
}
return new RepublishCheck(false, 0L, identity, Map.of(), null, Map.of());
} catch (IOException e) {
LOG.debugv(e, "Publish for {0}/{1} is not a confirmable republish: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return new RepublishCheck(false, 0L, identity, Map.of());
return new RepublishCheck(false, 0L, identity, Map.of(), null, Map.of());
}
long totalAttachmentBytes = envelope.attachments().values().stream()
.mapToLong(NpmPublishEnvelopeScanner.Attachment::size)
.sum();
Map<String, String> readmeByVersion = new HashMap<>();
envelope.versions().forEach((version, v) -> readmeByVersion.put(version, v.readme()));
Map<String, String> beforeRevisionByVersion = new HashMap<>();
for (String version : readmeByVersion.keySet()) {
try {
String beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(scope.region(),
npmRequest.domain(), scope.owner(), npmRequest.repository(), "npm", identity.namespace(),
identity.packageName(), version);
beforeRevisionByVersion.put(version, beforeRevision);
} catch (AwsException e) {
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion, e.getMessage(),
beforeRevisionByVersion);
}
}
Optional<JsonNode> storedDocument;
try {
storedDocument = verdaccioClient.fetchPackageDocument(backendBaseUrl, identity.namespace(),
@@ -468,25 +550,30 @@ public class CodeArtifactNpmDataPlane {
} catch (IllegalStateException e) {
LOG.warnv(e, "Could not check {0}/{1} for an existing match before publishing: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion);
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion, null,
beforeRevisionByVersion);
}
if (storedDocument.isEmpty() || !isConfirmedRepublish(envelope, storedDocument.get(), identity)) {
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion);
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion, null,
beforeRevisionByVersion);
}
for (NpmPublishEnvelopeScanner.Version version : envelope.versions().values()) {
try {
Optional<String> stored = verdaccioClient.storedTarballIntegrity(backendBaseUrl,
identity.namespace(), identity.packageName(), tarballFilename(version.tarball()));
if (stored.isEmpty() || !stored.get().equals(version.integrity())) {
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion);
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion, null,
beforeRevisionByVersion);
}
} catch (IllegalStateException e) {
LOG.warnv(e, "Could not verify the stored tarball of {0}/{1} before publishing: {2}",
npmRequest.domain(), npmRequest.repository(), e.getMessage());
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion);
return new RepublishCheck(false, totalAttachmentBytes, identity, readmeByVersion, null,
beforeRevisionByVersion);
}
}
return new RepublishCheck(true, totalAttachmentBytes, identity, readmeByVersion);
return new RepublishCheck(true, totalAttachmentBytes, identity, readmeByVersion, null,
beforeRevisionByVersion);
}
private static boolean isConfirmedRepublish(NpmPublishEnvelopeScanner.Envelope envelope, JsonNode stored,
@@ -581,7 +668,7 @@ public class CodeArtifactNpmDataPlane {
private void forwardSpooled(RoutingContext context, String backendBaseUrl, String backendPath,
ReadStream<Buffer> body, AuthorizationTokenScope scope, String domain, String repository,
PackageIdentity identity, long totalAttachmentBytes, long fenceSnapshot,
Map<String, String> readmeByVersion) {
Map<String, String> readmeByVersion, Map<String, String> beforeRevisionByVersion) {
URI backend = URI.create(backendBaseUrl);
RequestOptions options = new RequestOptions()
.setHost(backend.getHost())
@@ -639,6 +726,19 @@ public class CodeArtifactNpmDataPlane {
service.recordPublishedPackageVersionReadme(scope.region(), domain,
scope.owner(), repository, "npm", identity.namespace(),
identity.packageName(), version, readme, fenceSnapshot));
// Found by Qodo review: readmeByVersion's own keys are every version in
// this publish envelope, independent of whether any of them actually
// carried a readme, so reusing it here clears a stale Archived/Disposed
// override for exactly the versions this publish just wrote real content
// for, the same way the Maven/pypi native publish paths now do. Cleared
// only if still unchanged since checkRepublish's own guard ran (Greptile
// review): a status change that landed while the forward was in flight
// must not be erased by this.
readmeByVersion.keySet().forEach(version ->
service.forgetContainerBackedStatusOverrideIfUnchanged(scope.region(), domain,
scope.owner(), repository, "npm", identity.namespace(),
identity.packageName(), version,
beforeRevisionByVersion.get(version)));
}
promise.complete();
}, false).onComplete(result -> {
@@ -197,6 +197,39 @@ public class CodeArtifactNuGetController {
String packageName = nuspec.id().toLowerCase(Locale.ROOT);
String version = NuGetVersions.normalize(nuspec.version());
// 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
// format, not accepted and then have forgetContainerBackedStatusOverride below silently
// un-block it afterward. Checked before even the existence check below, let alone the real
// write, the same way CodeArtifactNpmDataPlane's own guard already runs ahead of its
// byte-identical shortcut (Greptile review: an archived coordinate re-pushed byte-identical
// must still be refused, not quietly accepted as "nothing changed").
String beforeRevision;
try {
beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(handle.region(), domain,
handle.owner(), repository, "nuget", null, packageName, version);
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
// Raised by Greptile's review: DisposePackageVersions holds CodeArtifactService's own
// lock for its whole call, and its container-backed asset deletion (see
// CodeArtifactService#deleteContainerBackedVersionAssets) acquires this exact same
// per-repository BaGetter lock from inside that hold. Calling any synchronized
// CodeArtifactService method (recordContainerBackedAssetBytes/
// forgetContainerBackedStatusOverride below) from inside this lock, as both used to, would
// let a push and a concurrent dispose of the same version each wait forever on the other's
// lock. Neither call needs this lock at all: BaGetter's own content is already finalized by
// the time forwardPush below returns, so both bookkeeping calls run after this block
// releases it instead. currentContainerBackedPackageFence is exempt from this concern: it
// is deliberately lock-free (see its own javadoc), not a synchronized CodeArtifactService
// method, so taking the snapshot before entering the lock changes nothing it protects
// against.
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
repository, "nuget", null, packageName);
Response response;
boolean pushSucceeded;
// The exact same lock BagetterSidecarClient#deletePackage takes for this repository, not
// a private one: without sharing it, a DeletePackage racing this push could still list
// its versions before this push lands and miss it, the one case a private lock here
@@ -211,21 +244,23 @@ public class CodeArtifactNuGetController {
.entity("A package with this id and version already exists.")
.build();
}
// Snapshotted before the real write, not after: see
// CodeArtifactService#currentContainerBackedPackageFence's own javadoc for why the
// order matters.
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
repository, "nuget", null, packageName);
Response response = forwardPush(handle.baseUrl(), contentType, content);
boolean pushSucceeded = response.getStatus() == 200 || response.getStatus() == 201
response = forwardPush(handle.baseUrl(), contentType, content);
pushSucceeded = response.getStatus() == 200 || response.getStatus() == 201
|| response.getStatus() == 202;
if (pushSucceeded) {
service.recordContainerBackedAssetBytes(handle.region(), domain, handle.owner(), repository,
"nuget", null, packageName, nupkgBytes.length, fenceSnapshot);
}
return response;
}
if (pushSucceeded) {
service.recordContainerBackedAssetBytes(handle.region(), domain, handle.owner(), repository,
"nuget", null, packageName, nupkgBytes.length, fenceSnapshot);
// Found by Qodo review: a real dotnet nuget push that republishes a coordinate an
// earlier updatePackageVersionsStatus/disposePackageVersions call left Archived or
// Disposed would otherwise still have its fresh content blocked by that stale
// override, the same gap closed for Maven/npm/pypi's own native publish paths. Cleared
// only if still unchanged since the guard above ran (Greptile review): a status change
// that landed while forwardPush was in flight must not be erased by this.
service.forgetContainerBackedStatusOverrideIfUnchanged(handle.region(), domain, handle.owner(),
repository, "nuget", null, packageName, version, beforeRevision);
}
return response;
}
/**
@@ -169,9 +169,42 @@ public class CodeArtifactPypiController {
if (packageName == null || packageName.isBlank() || file.isEmpty()) {
return Response.status(400).entity("Upload must include name and content fields.").build();
}
// Raised by Greptile's review: pypiserver files an upload under the identity its own
// filename embeds, not under whatever this form's name/version fields happen to say
// (PypiserverSidecarClient#filenameEmbedsVersion's own javadoc explains why that
// boundary check, not these fields, is the real source of truth). Everything below this
// point, the Archived/Disposed guard included, runs against these fields; a mismatched
// version field would let the guard see an unrelated, harmless coordinate while the real
// upload still lands under whatever the filename actually names.
if (version != null && !version.isBlank()
&& !PypiserverSidecarClient.filenameEmbedsVersion(file.get().filename(), packageName, version)) {
return Response.status(400)
.entity("The upload's name and version fields do not match its filename.")
.build();
}
Object lock = uploadLocks.computeIfAbsent(handle.repoId(), k -> new Object());
synchronized (lock) {
// Raised by hectorvent's review: a real twine upload to a coordinate
// updatePackageVersionsStatus/disposePackageVersions left Archived or Disposed must be
// refused outright, the same way PublishPackageVersion already refuses it for the
// generic format, not accepted and then have forgetContainerBackedStatusOverride below
// silently un-block it afterward. Checked ahead of the byte-identical shortcut right
// below too, not just the real write: archiving leaves the stored bytes themselves
// unchanged, so a byte-identical re-upload of an archived version would otherwise
// short-circuit to 200 before ever reaching this guard (Greptile review). A
// missing/blank version is the same case the override-clearing call below already
// skips: no coordinate to block either way.
String beforeRevision = null;
if (version != null && !version.isBlank()) {
try {
beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(handle.region(),
domain, handle.owner(), repository, "pypi", null, packageName, version);
} catch (AwsException e) {
return Response.status(409).entity(e.getMessage()).build();
}
}
Optional<byte[]> existing = existingFileContent(handle.baseUrl(), packageName, file.get().filename());
if (existing.isPresent()) {
if (Arrays.equals(existing.get(), file.get().content())) {
@@ -193,6 +226,17 @@ public class CodeArtifactPypiController {
if (uploadSucceeded) {
service.recordContainerBackedAssetBytes(handle.region(), domain, handle.owner(), repository,
"pypi", null, packageName, file.get().content().length, fenceSnapshot);
// Found by Qodo review: a real twine upload that republishes a coordinate an
// earlier updatePackageVersionsStatus/disposePackageVersions call left Archived or
// Disposed would otherwise still have its fresh content blocked by that stale
// override. A missing/blank version is the same case the readme capture below
// already skips: no coordinate to clear an override for. Cleared only if still
// unchanged since the guard above ran (Greptile review): a status change that
// landed while forwardUpload was in flight must not be erased by this.
if (version != null && !version.isBlank()) {
service.forgetContainerBackedStatusOverrideIfUnchanged(handle.region(), domain, handle.owner(),
repository, "pypi", null, packageName, version, beforeRevision);
}
}
// Only for a real new publish, never the byte-identical-retry short-circuit above
// (nothing new was written there either): the "description" field is the real PyPI
File diff suppressed because it is too large. Load diff
@@ -53,6 +53,29 @@ final class NpmPublishEnvelopeScanner {
.build())
.build();
/**
* Raised by Greptile's review: {@link CodeArtifactNpmDataPlane#checkRepublish}'s own
* Archived/Disposed guard needs to know which versions a publish names even when {@link
* #FACTORY}'s own stricter limit throws, the real way a legitimate publish whose per-version
* {@code readme} exceeds {@code maxStringLength} (1,000,000 characters is generous for
* almost any real README, but not unbounded) reaches that catch block. Jackson's own
* {@code maxStringLength} enforcement happens while the tokenizer itself scans a string
* token to find its end, during {@code nextToken()}, not lazily when a caller later reads
* its value, so there is no way to skip past an oversized field with {@link #FACTORY}'s own
* limit still in force; only a parse with a higher one can get past it at all. This ceiling
* is still bounded, not unlimited, specifically so a truly pathological payload still fails
* both this and {@link #FACTORY}'s own parse and is rejected outright by the caller rather
* than silently forwarded with no guard having run at all.
*/
private static final JsonFactory LENIENT_FACTORY = JsonFactory.builder()
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.streamReadConstraints(StreamReadConstraints.builder()
.maxNestingDepth(32)
.maxNumberLength(1_000_000)
.maxStringLength(64_000_000)
.build())
.build();
@FunctionalInterface
private interface FieldHandler {
void accept(String fieldName) throws IOException;
@@ -69,7 +92,25 @@ final class NpmPublishEnvelopeScanner {
}
static Envelope scan(InputStream in) throws IOException {
try (JsonParser parser = FACTORY.createParser(in)) {
return scan(in, FACTORY);
}
/**
* {@link #LENIENT_FACTORY}'s own fallback parse, for a caller ({@link
* CodeArtifactNpmDataPlane#checkRepublish}) that still needs {@code versions()}' own key set
* once {@link #scan} itself has already thrown; see that factory's own javadoc for why a
* second, more tolerant pass is the only way to recover it at all. Its {@code readme} and
* {@code attachments} are not meant to be trusted the way {@link #scan}'s own result is (the
* whole reason this parse exists is that {@link #scan} itself refused to vouch for one of
* those same fields), so a caller must only ever read {@code versions().keySet()} from this,
* never anything else about the Envelope it returns.
*/
static Envelope scanLeniently(InputStream in) throws IOException {
return scan(in, LENIENT_FACTORY);
}
private static Envelope scan(InputStream in, JsonFactory factory) throws IOException {
try (JsonParser parser = factory.createParser(in)) {
NpmPublishEnvelopeScanner scanner = new NpmPublishEnvelopeScanner(parser);
scanner.parseEnvelope();
return scanner.envelope();
@@ -538,8 +538,19 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
* at version {@code 2.0} produces {@code foo-1.0-bar-2.0.tar.gz}, and the text {@code -1.0-}
* inside that name would otherwise look like a complete, valid version {@code 1.0} to a
* caller who asked for the wrong one.
*
* <p>Not {@code private} for exactly one other reason (Greptile's review of this PR):
* {@code CodeArtifactPypiController#upload} calls this on the way in, the opposite direction
* from every other caller here. pypiserver itself files an upload under the identity this
* same boundary logic derives from its filename, never from the multipart form's own
* {@code name}/{@code version} fields; those fields are only ever used, until this check
* existed, to pick which coordinate the Archived/Disposed guard and the override-clearing
* call afterward run against. A form whose fields name an unrelated (unused, never
* Archived/Disposed) coordinate while the real filename matches a disposed one would let the
* guard see the harmless coordinate, the real upload land under the disposed one regardless,
* and the override-clearing call afterward operate on the wrong version too.
*/
private static boolean filenameEmbedsVersion(String assetName, String packageName, String version) {
static boolean filenameEmbedsVersion(String assetName, String packageName, String version) {
String normalizedPackageName = normalizePackageName(packageName);
String marker = "-" + version;
for (int idx = assetName.indexOf(marker); idx >= 0; idx = assetName.indexOf(marker, idx + 1)) {
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import jakarta.enterprise.context.ApplicationScoped;
@@ -54,6 +55,14 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
/** Real Maven metadata's own documented {@code lastUpdated} shape: UTC, {@code yyyyMMddHHmmss}. */
private static final DateTimeFormatter METADATA_TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
.withZone(ZoneOffset.UTC);
/**
* The two checksum extensions a real {@code mvn deploy} always PUTs alongside {@code
* maven-metadata.xml} itself (confirmed against a real deploy's own request log): SHA-1 and
* MD5, Maven's two long-standing defaults. SHA-256/SHA-512 are a newer, still-optional addition
* no client this repository's own integration tests exercise ever sends, so neither is handled
* by {@link #recordVersionDisposed}'s own checksum upkeep.
*/
private static final List<String> METADATA_CHECKSUM_EXTENSIONS = List.of("sha1", "md5");
private final ReposiliteSidecarManager manager;
private final ObjectMapper mapper;
@@ -469,6 +478,201 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
deployArtifact(repositoryContainerId, gav, metadata.build().getBytes(StandardCharsets.UTF_8));
}
/**
* {@link #recordVersionAvailable}'s dispose-time counterpart (found missing by Qodo review on
* the PR that added {@code DisposePackageVersions}): without this, a disposed Maven version's
* real asset files are gone from its own version directory, but {@code mvn}/{@code gradle}
* resolving dependencies straight against the artifact-level {@code maven-metadata.xml} (not
* through this emulator's own {@code ListPackageVersions}, which already reads the override
* store and correctly stops reporting it) would keep seeing it listed as available. Removes
* {@code version} from the metadata's own {@code versions} list and recomputes {@code latest}/
* {@code release} from whatever remains, in the same append order the metadata already
* preserves: the list is never re-sorted, so its last surviving entry is still the most
* recently deployed one, exactly the same invariant {@link #recordVersionAvailable} relies on
* when adding to it. A metadata file that would end up with no versions left is deleted
* outright rather than written back empty, matching how a package that never had a version
* published has no metadata file at all. A missing metadata file, or one that never named this
* version to begin with (both possible if this is called more than once, or for a version
* recorded before {@code maven-metadata.xml} existed), is a no-op either way.
*
* <p>Raised by Greptile's review: both the DELETE below (when no version is left to list) and
* the rewrite ({@link #deployArtifact}) ignored whatever Reposilite actually answered, so a
* disposal could report success while the metadata on disk still named the just-deleted
* version. Checked against the exact same {@code IllegalStateException}-on-failure convention
* {@link #deletePackageVersionAsset} already uses for the asset deletes this runs after (see
* {@code CodeArtifactService#deleteContainerBackedVersionAssets}'s own javadoc for why this
* runs last): a thrown exception here propagates the same way a failed asset delete already
* does, rather than this method silently reporting a metadata update that never actually took.
*
* <p>Also raised by Greptile's review: a real {@code mvn deploy} always PUTs {@code
* maven-metadata.xml.sha1}/{@code .md5} right alongside the metadata file itself, so this
* method's own server-side rewrite (or removal) of the metadata content must carry those two
* checksum siblings along with it ({@link #METADATA_CHECKSUM_EXTENSIONS}): left untouched, a
* Maven client verifying the checksum of the metadata it just fetched would see it disagree
* with content this method itself just changed underneath it.
*
* <p>Raised again by Greptile's review, once a dispose retry (see {@code
* CodeArtifactService#checkStatusTransitionAllowed}'s own javadoc) became possible: a retry
* whose first attempt already finished the metadata rewrite or removal, but then failed on
* exactly a checksum write or delete, used to hit one of the two early returns below and
* report success without ever repairing that stale checksum, since neither {@code existing}
* being empty nor {@code version} being already absent from it means the checksums are
* actually right. Both early-return branches now repair the checksums too, every time, not
* just on the one call that happened to also touch the metadata itself.
*
* <p>Raised again by Greptile's review: {@link #fetchArtifact} itself returns {@code empty()}
* for every non-200 response, 500/503 included, the same conflation {@link
* #deleteArtifactIfPresent}'s own existence check already had fixed for it. A transient read
* failure here looked identical to "the metadata file genuinely does not exist," which would
* delete the checksums and report a successful disposal while the metadata on disk still
* named the version this was supposed to remove. Reads the metadata through a dedicated check
* that only takes the empty branch on a confirmed 404, throwing on anything else, the same
* convention {@link #deleteArtifactIfPresent}'s own HEAD check already uses.
*
* <p>Known, documented gap left out of scope (also raised by Greptile's review): this
* method's own read-modify-write of {@code maven-metadata.xml} has no lock around it, so a
* concurrent {@link #recordVersionAvailable} (a native {@code mvn deploy} adding a different
* version to the same artifact) that reads the file between this method's own read and write
* can have its update silently overwritten by this call's stale copy, or removed outright if
* this call's own last-version branch deletes the file instead. This is not new: {@link
* #recordVersionAvailable} already has the identical unlocked read-modify-write shape on its
* own, so two concurrent deploys of different versions to the same artifact can already lose
* one's update today, with no disposal involved at all. This method is simply a second
* caller that inherits that same pre-existing hole rather than one that introduces it.
* Coordinating every writer of this one file (a lock keyed by repository and artifact,
* shared across every caller) is a real fix, just not one scoped to adding {@code
* DisposePackageVersions} itself; tracked separately rather than folded in here.
*/
@Override
public void recordVersionDisposed(String repositoryContainerId, String namespace, String packageName,
String version) {
String gav = artifactMetadataGav(namespace, packageName);
Optional<FetchedArtifact> existing = fetchArtifactConfirmingMissing(repositoryContainerId, gav);
if (existing.isEmpty()) {
for (String extension : METADATA_CHECKSUM_EXTENSIONS) {
deleteArtifactIfPresent(repositoryContainerId, gav + "." + extension);
}
return;
}
String xml = new String(existing.get().content(), StandardCharsets.UTF_8);
List<String> versions = new ArrayList<>(XmlParser.extractAll(xml, "version"));
if (!versions.remove(version)) {
writeMetadataChecksum(repositoryContainerId, gav + ".sha1", Digests.sha1Hex(existing.get().content()));
writeMetadataChecksum(repositoryContainerId, gav + ".md5", Digests.md5Hex(existing.get().content()));
return;
}
String baseUrl = manager.ensureReady();
if (versions.isEmpty()) {
HttpRequest request = authenticated(baseUrl, repositoryContainerId, gav).DELETE().build();
HttpResponse<Void> response = send(request, BodyHandlers.discarding());
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not remove " + packageName + "'s maven-metadata.xml from "
+ "the Reposilite sidecar after disposing its last version " + version
+ ": upstream returned " + response.statusCode());
}
for (String extension : METADATA_CHECKSUM_EXTENSIONS) {
deleteArtifactIfPresent(repositoryContainerId, gav + "." + extension);
}
return;
}
String groupId = XmlParser.extractFirst(xml, "groupId", namespace);
String artifactId = XmlParser.extractFirst(xml, "artifactId", packageName);
String latest = versions.get(versions.size() - 1);
String release = null;
for (int i = versions.size() - 1; i >= 0; i--) {
if (!versions.get(i).endsWith("-SNAPSHOT")) {
release = versions.get(i);
break;
}
}
XmlBuilder metadata = new XmlBuilder().start("metadata")
.elem("groupId", groupId)
.elem("artifactId", artifactId)
.start("versioning")
.elem("latest", latest)
.elem("release", release)
.start("versions");
for (String v : versions) {
metadata.elem("version", v);
}
metadata.end("versions")
.elem("lastUpdated", METADATA_TIMESTAMP.format(Instant.now()))
.end("versioning")
.end("metadata");
byte[] metadataBytes = metadata.build().getBytes(StandardCharsets.UTF_8);
DeployOutcome outcome = deployArtifact(repositoryContainerId, gav, metadataBytes);
if (!outcome.wroteNewContent()) {
throw new IllegalStateException("Could not update " + packageName + "'s maven-metadata.xml on the "
+ "Reposilite sidecar after disposing version " + version + ": upstream returned "
+ outcome.status());
}
writeMetadataChecksum(repositoryContainerId, gav + ".sha1", Digests.sha1Hex(metadataBytes));
writeMetadataChecksum(repositoryContainerId, gav + ".md5", Digests.md5Hex(metadataBytes));
}
/** {@link #recordVersionDisposed}'s own checksum-rewrite counterpart to {@link #deployArtifact}. */
/**
* Raised by Greptile's review: {@code wroteNewContent()} is {@code false} both for a genuine
* failure and for {@link #deployArtifact}'s own idempotent short-circuit (the checksum
* already on the sidecar matches {@code hex} byte for byte, so nothing needed to be sent at
* all), and checking it alone could not tell the two apart. A disposal retry whose {@code
* .sha1} write already landed on an earlier attempt, but then failed on {@code .md5}, would
* see that already-correct {@code .sha1} hit this exact short-circuit every time, getting
* flagged as a failure that stopped the retry before it ever reached {@code .md5} again. Only
* the real HTTP status is checked now, the same success codes {@link #deployArtifact} itself
* already treats as success.
*/
private void writeMetadataChecksum(String repositoryContainerId, String checksumGav, String hex) {
DeployOutcome outcome = deployArtifact(repositoryContainerId, checksumGav,
hex.getBytes(StandardCharsets.UTF_8));
if (outcome.status() != 200 && outcome.status() != 201) {
throw new IllegalStateException("Could not update checksum " + checksumGav + " on the Reposilite "
+ "sidecar: upstream returned " + outcome.status());
}
}
/**
* {@link #recordVersionDisposed}'s own checksum-removal counterpart, for the case where the
* metadata file itself is removed outright rather than rewritten. A checksum that was never
* there to begin with (a client that only ever pushed one of the two, or a sidecar restored
* from a snapshot older than this method) is a no-op, the same tolerance {@link
* #recordVersionDisposed} already extends to a metadata file missing version to begin with.
*
* <p>Checks existence with a HEAD first rather than guessing at a "not found" status for the
* DELETE itself: confirmed against a real Reposilite instance, deleting a path that was never
* there returns 500, not 404, so treating 404 as the tolerated case (as an earlier version of
* this method did) still threw on the common case of a checksum a real {@code mvn deploy}
* simply never pushed.
*
* <p>Raised by Greptile's review: {@link #artifactExists} itself treats every non-200 HEAD
* response as "absent," 500/503 included, which would let a genuine sidecar failure here look
* identical to a confirmed-missing checksum and silently skip the delete instead of surfacing
* it. This checks the HEAD status directly instead, so only a confirmed 404 is tolerated as
* absent; anything else (a real error, not a clean answer either way) throws, the same
* {@code IllegalStateException}-on-failure convention this method's own DELETE already uses,
* so a caller can tell a skipped-because-confirmed-gone checksum apart from one this could not
* even check.
*/
private void deleteArtifactIfPresent(String repositoryContainerId, String gav) {
String baseUrl = manager.ensureReady();
HttpRequest headRequest = authenticated(baseUrl, repositoryContainerId, gav)
.method("HEAD", BodyPublishers.noBody()).build();
int headStatus = send(headRequest, BodyHandlers.discarding()).statusCode();
if (headStatus == 404) {
return;
}
if (headStatus != 200) {
throw new IllegalStateException("Could not check whether " + gav + " exists on the Reposilite "
+ "sidecar before deleting it: upstream returned " + headStatus);
}
HttpRequest request = authenticated(baseUrl, repositoryContainerId, gav).DELETE().build();
HttpResponse<Void> response = send(request, BodyHandlers.discarding());
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not delete " + gav + " from the Reposilite sidecar: upstream "
+ "returned " + response.statusCode());
}
}
private static String artifactMetadataGav(String namespace, String packageName) {
return namespace.replace('.', '/') + "/" + packageName + "/maven-metadata.xml";
}
@@ -712,6 +916,28 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
return fetchArtifact(manager.ensureReady(), repoId, gav);
}
/**
* {@link #recordVersionDisposed}'s own counterpart to {@link #fetchArtifact}: that method's
* {@code empty()} is not safe to read as "confirmed absent" everywhere, since it also means
* "any non-200," 500/503 included. This only takes the empty branch on an actual 404,
* throwing on anything else so a transient read failure is surfaced rather than treated as
* the file never having existed.
*/
private Optional<FetchedArtifact> fetchArtifactConfirmingMissing(String repositoryContainerId, String gav) {
String baseUrl = manager.ensureReady();
HttpRequest request = authenticated(baseUrl, repositoryContainerId, gav).GET().build();
HttpResponse<byte[]> response = send(request, BodyHandlers.ofByteArray());
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not read " + gav + " from the Reposilite sidecar: upstream "
+ "returned " + response.statusCode());
}
String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream");
return Optional.of(new FetchedArtifact(response.body(), contentType));
}
private Optional<FetchedArtifact> fetchArtifact(String baseUrl, String repoId, String gav) {
HttpRequest request = authenticated(baseUrl, repoId, gav).GET().build();
HttpResponse<byte[]> response = send(request, BodyHandlers.ofByteArray());
@@ -236,6 +236,19 @@ public interface RepositorySidecarManager {
default void endUse(String repositoryContainerId) {
}
/**
* Called once per version, after every one of its assets has already been removed through
* {@link #deletePackageVersionAsset}, for a sidecar whose own native listing can name a
* version somewhere other than the per-version assets {@link #listPackageVersionAssetNames}
* already enumerates: Maven's artifact-level {@code maven-metadata.xml}, which {@code
* ReposiliteSidecarClient} overrides this to rewrite. Default is a no-op: a sidecar with no
* such separate listing (every format {@code DisposePackageVersions} supports besides Maven)
* already has nothing left to say the version ever existed once its assets are gone.
*/
default void recordVersionDisposed(String repositoryContainerId, String namespace, String packageName,
String version) {
}
/**
* This format's own preferred "default display" version for a package, independent of publish
* recency, for {@code ListPackageVersions}' {@code defaultDisplayVersion}. {@code empty()} by