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

@@ -30,6 +30,7 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.LogRecord;
import java.util.stream.Stream;
@@ -455,6 +456,102 @@ class CodeArtifactAssetPersistenceTest {
assertEquals("ResourceNotFoundException", gone.getErrorCode());
}
/**
* Qodo review finding on the PR that added {@code DisposePackageVersions}: unlike {@code
* deletePackage} (whose version record is already gone by the time its own best-effort asset
* cleanup runs, so a failure there can never be reached again), a disposed version's record
* is kept around: {@code DescribePackageVersion} must keep answering for it. The dispose path
* used to catch and log a failed delete the same way {@code deletePackage} does, then still
* mark the version Disposed and clear its asset map regardless, permanently orphaning bytes
* that record could no longer point back to. The same {@link DirectoryNotEmptyException} trick
* as {@link #deletingAnAssetsBytesFailingStillRemovesTheVersionRecordAndCleansUpTheOtherAsset}
* forces a real delete failure.
*
* <p>Raised again by Greptile's review: this now also proves the status write itself runs
* <em>before</em> the delete, not after (see {@code applyGenericStatusChange}'s own javadoc).
* The version reads {@code Disposed} (blocking downloads immediately) rather than staying
* {@code Published} with a broken asset still reachable, even though this one real asset's
* own delete never actually succeeded.
*/
@Test
void disposePackageVersionsPropagatesAFailedAssetDeletionInsteadOfReportingSuccess(@TempDir Path dir)
throws IOException {
CodeArtifactService service = newService(dir);
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
assetFile = paths.filter(Files::isRegularFile).filter(p -> matchesContent(p, content))
.findFirst().orElseThrow();
}
Files.delete(assetFile);
Files.createDirectory(assetFile);
Files.createFile(assetFile.resolve("not-empty"));
UncheckedIOException e = assertThrows(UncheckedIOException.class, () -> service.disposePackageVersions(
REGION, "dom", null, "repo", "generic", "ns", "pkg", List.of("1.0.0"), null, null));
assertTrue(e.getCause() instanceof DirectoryNotEmptyException, "expected the real delete failure to "
+ "propagate rather than being swallowed, got cause: " + e.getCause());
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"pkg", "1.0.0");
assertEquals("Disposed", pv.getStatus(), "the status write runs before the delete, so a failed delete "
+ "must still leave the version blocked rather than reading as the untouched Published it no "
+ "longer really is");
assertEquals(1, pv.getAssets().size(), "the one asset whose own delete failed is never removed from the "
+ "record (only a successfully deleted asset is), but is still unreachable through downloads "
+ "now that the version itself reads Disposed");
AwsException blocked = assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom",
null, "repo", "generic", "ns", "pkg", "1.0.0", "a.txt", null));
assertEquals("ResourceNotFoundException", blocked.getErrorCode());
}
/**
* Raised by Greptile's review: proves the per-asset bookkeeping, not just the upfront status
* write above. With two assets, one whose delete succeeds and one whose delete then fails,
* the record must name only the one that genuinely never got deleted, not the one already
* gone, so a retry (now let through for an already-{@code Disposed} version, see {@code
* checkStatusTransitionAllowed}'s own javadoc) picks up exactly where this attempt stopped.
*/
@Test
void disposePackageVersionsRemovesEachAssetFromTheRecordRightAfterItsOwnSuccessfulDelete(@TempDir Path dir)
throws IOException {
CodeArtifactService service = newService(dir);
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] contentA = "content of a".getBytes(StandardCharsets.UTF_8);
byte[] contentB = "content of b".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
Digests.sha256Hex(contentA), "true", contentA);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "b.txt",
Digests.sha256Hex(contentB), "true", contentB);
Path assetFileA;
Path assetFileB;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
List<Path> files = paths.filter(Files::isRegularFile).toList();
assetFileA = files.stream().filter(p -> matchesContent(p, contentA)).findFirst().orElseThrow();
assetFileB = files.stream().filter(p -> matchesContent(p, contentB)).findFirst().orElseThrow();
}
Files.delete(assetFileB);
Files.createDirectory(assetFileB);
Files.createFile(assetFileB.resolve("not-empty"));
assertThrows(UncheckedIOException.class, () -> service.disposePackageVersions(REGION, "dom", null, "repo",
"generic", "ns", "my-pkg", List.of("1.0.0"), null, null));
assertFalse(Files.exists(assetFileA), "the asset whose own delete succeeded must still be gone");
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0");
assertEquals("Disposed", pv.getStatus());
assertEquals(Set.of("b.txt"), pv.getAssets().keySet(), "only the asset whose delete never actually "
+ "succeeded should still be named in the record");
}
private static boolean matchesContent(Path file, byte[] expected) {
try {
return Arrays.equals(Files.readAllBytes(file), expected);
@@ -467,7 +564,7 @@ class CodeArtifactAssetPersistenceTest {
* Found by Qodo review: {@code copyPackageVersions} used to read and write each version's
* assets inline inside its own commit loop, so a later version's corrupted source bytes
* would be discovered only after an earlier, otherwise-valid version in the same batch was
* already committed to the destination — the per-call all-or-nothing contract AWS documents
* already committed to the destination, the per-call all-or-nothing contract AWS documents
* for the caller-visible failure codes, silently broken for this emulator-internal one.
* Every pending version's source assets are now verified against their persisted hashes
* before any version in the batch has anything written to the destination at all.
@@ -632,6 +632,43 @@ class CodeArtifactMavenDockerIntegrationTest {
+ defaultDisplayVersion);
}
/**
* A throwaway groupId/artifactId, not {@link #GAV}: disposing it is destructive (the real
* assets are gone afterward), and must not disturb the artifact every other test in this class
* shares. Confirms the whole real round trip: {@code DisposePackageVersions} deletes the real
* jar/pom through Reposilite's own asset-delete endpoint, a subsequent fetch 404s, and
* {@code ListPackageVersions} still reports the version, by status {@code Disposed} alone,
* since the real sidecar listing no longer names it at all once its content is gone.
*/
@Test
@Order(23)
void disposePackageVersionsDeletesTheRealReposiliteAssetsAndKeepsListingTheVersionAsDisposed() {
byte[] content = "dispose-me-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken).body(content)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/disposeme/1.0.0/disposeme-1.0.0.jar")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"]}")
.post("/v1/package/versions/dispose?domain=" + DOMAIN + "&repository=" + REPO + "&format=maven"
+ "&namespace=com.example&package=disposeme")
.then().statusCode(200)
.body("successfulVersions['1.0.0'].status", equalTo("Disposed"))
.body("failedVersions.size()", equalTo(0));
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/disposeme/1.0.0/disposeme-1.0.0.jar")
.then().statusCode(404);
given().header("Authorization", AUTH)
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=maven"
+ "&namespace=com.example&package=disposeme&status=Disposed")
.then().statusCode(200)
.body("versions.size()", equalTo(1))
.body("versions[0].version", equalTo("1.0.0"))
.body("versions[0].status", equalTo("Disposed"));
}
/**
* A throwaway groupId/artifactId, not {@link #GAV}: deleting it exercises Reposilite's real
* directory delete (confirmed live before this was built: a single {@code DELETE} on the
@@ -41,10 +41,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -332,6 +336,130 @@ class CodeArtifactNpmDataPlaneTest {
assertEquals(true, upstreamReceivedPut.get());
}
/**
* Qodo review finding: a real npm publish that republishes a coordinate an earlier
* updatePackageVersionsStatus/disposePackageVersions call left Archived or Disposed must not
* leave that override standing over the fresh content this publish just forwarded.
*/
@Test
void aPublishOfANewVersionClearsAnyStaleStatusOverrideForThatVersion() throws Exception {
upstream = vertx.createHttpServer()
.requestHandler(request -> request.response().setStatusCode(201).end())
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz",
"fresh bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(201, response.statusCode());
verify(service).forgetContainerBackedStatusOverrideIfUnchanged(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), isNull(), eq("my-pkg"), eq("1.0.0"), isNull());
}
/**
* hectorvent's review of this PR: the fix above only cleared a stale Archived/Disposed
* override after Verdaccio had already accepted the republished content, which the User
* Guide rules out unconditionally for both statuses. The publish must now be refused before it
* ever reaches Verdaccio.
*/
@Test
void aPublishToAnArchivedOrDisposedVersionIsRejectedWithoutForwarding() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
upstreamReceivedPut.set(true);
}
request.response().setStatusCode(201).end();
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
doThrow(new AwsException("ConflictException", "Package version '1.0.0' of package 'my-pkg' is Archived "
+ "and cannot be republished.", 409))
.when(service).requireContainerBackedVersionNotArchivedOrDisposed(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), isNull(), eq("my-pkg"), eq("1.0.0"));
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz",
"fresh bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
verify(service, never()).forgetContainerBackedStatusOverrideIfUnchanged(any(), any(), any(), any(), any(),
any(), any(), any(), any());
}
/**
* 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
* checkRepublish}'s primary scan throw, the one case that used to forward unconditionally
* with no guard having run at all (nothing before this fix recovered the version names any
* other way). The lenient fallback scan must still let the guard see this exact version and
* refuse it, the same as a normal publish envelope already does.
*/
@Test
void aPublishWhoseReadmeOverflowsTheStrictScanStillRunsTheGuard() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
upstreamReceivedPut.set(true);
}
request.response().setStatusCode(201).end();
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
doThrow(new AwsException("ConflictException", "Package version '1.0.0' of package 'my-pkg' is Disposed "
+ "and cannot be republished.", 409))
.when(service).requireContainerBackedVersionNotArchivedOrDisposed(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), isNull(), eq("my-pkg"), eq("1.0.0"));
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
byte[] content = "fresh bytes".getBytes(StandardCharsets.UTF_8);
String oversizedReadme = "x".repeat(1_000_001);
String envelope = "{\"name\":\"my-pkg\",\"versions\":{\"1.0.0\":{\"name\":\"my-pkg\",\"version\":\"1.0.0\","
+ "\"readme\":\"" + oversizedReadme + "\",\"dist\":{\"tarball\":\"http://ignored/my-pkg-1.0.0.tgz\","
+ "\"integrity\":\"" + integrity(content) + "\"}}},\"_attachments\":{\"my-pkg-1.0.0.tgz\":{"
+ "\"content_type\":\"application/octet-stream\",\"data\":\""
+ Base64.getEncoder().encodeToString(content) + "\",\"length\":" + content.length + "}}}";
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
envelope);
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
/**
* The identity used to look up an existing match comes from the URL the publish was sent to,
* not the envelope's own {@code name} field. A mismatched body must not be checked against
@@ -30,9 +30,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
@@ -353,6 +358,99 @@ class CodeArtifactPypiControllerTest {
assertTrue(receivedBody.get().contains("new content"));
}
/**
* Qodo review finding: a real twine upload that republishes a coordinate an earlier
* updatePackageVersionsStatus/disposePackageVersions call left Archived or Disposed must not
* leave that override standing over the fresh content this upload just forwarded.
*/
@Test
void uploadWithAVersionFieldClearsAnyStaleStatusOverrideAfterForwardingSucceeds() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> respond(exchange, 200, "text/plain", ""));
byte[] body = multipartWithFileAndVersion("boundary123", "my-pkg", "1.0.0", "my_pkg-1.0.0.tar.gz",
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(200, response.getStatus());
verify(service).forgetContainerBackedStatusOverrideIfUnchanged(any(), eq(DOMAIN), any(), eq(REPOSITORY),
eq("pypi"), isNull(), eq("my-pkg"), eq("1.0.0"), isNull());
}
/**
* Raised by Greptile's review: pypiserver files an upload under the identity its own filename
* embeds, never under whatever the form's own name/version fields say. A version field naming
* an unrelated coordinate (one that is not Archived/Disposed) while the real filename embeds
* a different version must be refused outright, not let the guard check the harmless
* coordinate while the real upload lands under the mismatched one regardless.
*/
@Test
void uploadRejectsAVersionFieldThatDoesNotMatchTheFilename() {
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
byte[] body = multipartWithFileAndVersion("boundary123", "my-pkg", "9.9.9", "my_pkg-1.0.0.tar.gz",
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(400, response.getStatus());
assertEquals(false, uploadReceived.get());
verify(service, never()).requireContainerBackedVersionNotArchivedOrDisposed(any(), any(), any(), any(),
any(), any(), any(), any());
}
/**
* hectorvent's review of this PR: the fix above only cleared a stale Archived/Disposed
* override after the sidecar had already accepted the republished content, which the User
* Guide rules out unconditionally for both statuses. The upload must now be refused before it
* ever reaches pypiserver.
*/
@Test
void uploadRejectsAnArchivedOrDisposedVersionWithoutForwarding() {
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
doThrow(new AwsException("ConflictException", "Package version '1.0.0' of package 'my-pkg' is Disposed "
+ "and cannot be republished.", 409))
.when(service).requireContainerBackedVersionNotArchivedOrDisposed(any(), eq(DOMAIN), any(),
eq(REPOSITORY), eq("pypi"), isNull(), eq("my-pkg"), eq("1.0.0"));
byte[] body = multipartWithFileAndVersion("boundary123", "my-pkg", "1.0.0", "my_pkg-1.0.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());
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
/** A missing version field, same as the readme capture right below it, has no coordinate to clear. */
@Test
void uploadWithNoVersionFieldNeverClearsAnyStatusOverride() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> respond(exchange, 200, "text/plain", ""));
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
controller.upload(headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
body);
verify(service, never()).forgetContainerBackedStatusOverrideIfUnchanged(any(), any(), any(), any(), any(),
any(), any(), any(), any());
verify(service, never()).requireContainerBackedVersionNotArchivedOrDisposed(any(), any(), any(), any(),
any(), any(), any(), any());
}
@Test
void uploadFailsClosedWhenTheExistenceCheckCannotReachTheBackend() {
// Nothing listens on this port: the existence check's own connect attempt fails, which
@@ -451,6 +549,22 @@ class CodeArtifactPypiControllerTest {
return body.getBytes(StandardCharsets.UTF_8);
}
private static byte[] multipartWithFileAndVersion(String boundary, String packageName, String version,
String filename, String content) {
String body = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"name\"\r\n\r\n"
+ packageName + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
+ version + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"content\"; filename=\"" + filename + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n"
+ content + "\r\n"
+ "--" + boundary + "--\r\n";
return body.getBytes(StandardCharsets.UTF_8);
}
private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String contentType,
String body) throws java.io.IOException {
respond(exchange, status, contentType, body.getBytes(StandardCharsets.UTF_8));
@@ -751,7 +751,7 @@ class CodeArtifactPypiDockerIntegrationTest {
byte[] content = ("many-versions-sdist-bytes-" + i).getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, filename, content))
.body(twineUploadBody("boundary123", packageName, version, filename, content, null))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
}
@@ -851,7 +851,7 @@ class CodeArtifactPypiDockerIntegrationTest {
* {@code name} and the {@code content} file part, so the rest are included for realism only.
*/
private static byte[] twineUploadBody(String boundary, String packageName, String filename, byte[] content) {
return twineUploadBody(boundary, packageName, filename, content, null);
return twineUploadBody(boundary, packageName, "1.0.0", filename, content, null);
}
/**
@@ -861,6 +861,19 @@ class CodeArtifactPypiDockerIntegrationTest {
*/
private static byte[] twineUploadBody(String boundary, String packageName, String filename, byte[] content,
String description) {
return twineUploadBody(boundary, packageName, "1.0.0", filename, content, description);
}
/**
* Full shape, with an explicit {@code version} field: every other overload above hardcodes
* {@code 1.0.0}, which happens to match every other test's own fixed filename in this class,
* but {@code CodeArtifactPypiController#upload} now checks the version field against the
* real filename (Greptile's review of this PR), so a caller whose filename embeds a different
* version (see {@link #listPackageVersionsFetchesManyVersionsPublishTimesCorrectly}'s own
* loop) must pass the matching one here instead.
*/
private static byte[] twineUploadBody(String boundary, String packageName, String version, String filename,
byte[] content, String description) {
String preamble = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\":action\"\r\n\r\n"
+ "file_upload\r\n"
@@ -872,7 +885,7 @@ class CodeArtifactPypiDockerIntegrationTest {
+ packageName + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
+ "1.0.0\r\n"
+ version + "\r\n"
+ "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"filetype\"\r\n\r\n"
+ "sdist\r\n"
@@ -33,12 +33,18 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -46,10 +52,12 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -2308,6 +2316,46 @@ class CodeArtifactServiceTest {
any());
}
/**
* Raised by Greptile's review: a Maven dispose failing partway through its own asset-deletion
* loop leaves the source override reading {@code Disposed} while real files genuinely still
* remain in the version's own directory, so {@code packageVersionExists} alone cannot tell a
* healthy source apart from a partly-disposed one. With {@code allowOverwrite=true}, copying
* that partly-disposed source over a healthy destination must still be refused, not replace
* the destination's real content with the incomplete release and report {@code Published}.
*/
@Test
void copyPackageVersionsFailsNotAllowedWhenTheMavenSourceIsPartlyDisposed() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
String srcRepoId = src.getSidecarContainerIds().get("maven");
String dstRepoId = dst.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar", "a-1.0.pom"));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(reposiliteClient).deletePackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"));
assertThrows(IllegalStateException.class, () -> service.disposePackageVersions(REGION, "dom", null, "src",
"maven", "com.example", "a", List.of("1.0"), null, null));
// The pom's delete never actually succeeded, so it is still genuinely there.
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
when(reposiliteClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false);
assertTrue(result.successfulVersions().isEmpty());
assertEquals("NOT_ALLOWED", result.failedVersions().get("1.0").errorCode());
verify(reposiliteClient, never()).copyPackageVersionAsset(any(), any(), any(), any(), any(), any(), any(),
any(), any(), any());
}
@Test
void copyPackageVersionsFailsNotFoundForAMavenVersionMissingFromTheSource() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -2712,6 +2760,59 @@ class CodeArtifactServiceTest {
assertEquals("ALREADY_EXISTS", result.failedVersions().get("1.0.0").errorCode());
}
/**
* Raised by hectorvent's review of this PR, matching copyContainerBackedPackageVersions's own
* Disposed-destination guard: disposePackageVersions empties a generic version's asset map but
* keeps its record (so DescribePackageVersion keeps answering), so without a dedicated check an
* allowOverwrite copy would have nothing to compare against, fall through as though the
* destination were simply a different version, and resurrect a coordinate the User Guide says
* "can no longer be used."
*/
@Test
void copyPackageVersionsFailsNotAllowedWhenTheDestinationIsAlreadyDisposed() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
publishGeneric("src", "my-pkg", "1.0.0", "source-bytes".getBytes(StandardCharsets.UTF_8));
publishGeneric("dst", "my-pkg", "1.0.0", "different-bytes".getBytes(StandardCharsets.UTF_8));
service.disposePackageVersions(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null,
null);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, true, false);
assertTrue(result.successfulVersions().isEmpty());
assertEquals("NOT_ALLOWED", result.failedVersions().get("1.0.0").errorCode());
}
/**
* Raised by Greptile's review: {@code disposePackageVersions} empties a generic version's
* asset map but keeps its record around, the same reason the destination-side guard above
* exists. Without a matching guard on the source, copying a disposed source with
* {@code allowOverwrite=true} over a healthy destination would overwrite that destination's
* real content and status with the disposed source's empty one while reporting success,
* destroying assets the disposal never touched.
*/
@Test
void copyPackageVersionsFailsNotAllowedWhenTheSourceIsAlreadyDisposed() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
publishGeneric("src", "my-pkg", "1.0.0", "source-bytes".getBytes(StandardCharsets.UTF_8));
publishGeneric("dst", "my-pkg", "1.0.0", "healthy-bytes".getBytes(StandardCharsets.UTF_8));
service.disposePackageVersions(REGION, "dom", null, "src", "generic", "ns", "my-pkg", List.of("1.0.0"), null,
null);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, true, false);
assertTrue(result.successfulVersions().isEmpty());
assertEquals("NOT_ALLOWED", result.failedVersions().get("1.0.0").errorCode());
PackageVersionAssetResult stillHealthy = service.getPackageVersionAsset(REGION, "dom", null, "dst",
"generic", "ns", "my-pkg", "1.0.0", "a.txt", null);
assertEquals("healthy-bytes", new String(stillHealthy.asset().getContent(), StandardCharsets.UTF_8));
}
@Test
void copyPackageVersionsOverwritesADifferentExistingVersionWhenAllowOverwriteIsTrue() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -3625,6 +3726,815 @@ class CodeArtifactServiceTest {
assertEquals("ValidationException", badOriginType.getErrorCode());
}
// ------------------------------------- updatePackageVersionsStatus / disposePackageVersions
@Test
void updatePackageVersionsStatusArchivesAGenericVersionAndChangesItsRevision() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
// Captured as a plain string, not the live CodeArtifactPackageVersion object: the test
// storage backend hands back the same mutable instance on every read, so holding onto the
// object itself would see it change underneath this assertion once the update below
// mutates it in place.
String revisionBeforeUpdate = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0").getRevision();
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, null, "Archived");
assertEquals(1, result.successfulVersions().size());
assertEquals("Archived", result.successfulVersions().get("1.0.0").status());
assertNotEquals(revisionBeforeUpdate, result.successfulVersions().get("1.0.0").revision());
assertTrue(result.failedVersions().isEmpty());
assertEquals("Archived", service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0").getStatus());
}
/**
* Raised by Greptile's review: {@code UPDATE_TARGET_STATUSES} allows targeting {@code
* Published} from {@code Unfinished} (nothing in {@code checkStatusTransitionAllowed} blocks
* it), the real way a version can finalize through this action instead of through {@code
* publishPackageVersion}'s own normal path, which already sets {@code publishedTime} on the
* identical condition. Left unset, the version would sort as though never published at all.
*/
@Test
void updatePackageVersionsStatusSetsPublishedTimeWhenFinalizingAnUnfinishedGenericVersion() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "a".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0").getStatus());
assertNull(service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0")
.getPublishedTime());
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "generic", "ns", "my-pkg",
List.of("1.0.0"), null, null, "Published");
assertNotNull(service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg",
"1.0.0").getPublishedTime());
}
@Test
void updatePackageVersionsStatusSkipsEveryOtherwiseEligibleVersionWhenOneFails() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0", "9.9.9"), null, null, "Archived");
assertTrue(result.successfulVersions().isEmpty());
assertEquals("NOT_FOUND", result.failedVersions().get("9.9.9").errorCode());
assertEquals("SKIPPED", result.failedVersions().get("1.0.0").errorCode());
// Confirms the all-or-nothing rule actually held: 1.0.0 would have succeeded on its own.
assertEquals("Published", service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0").getStatus());
}
@Test
void updatePackageVersionsStatusFailsMismatchedRevisionAndMismatchedStatus() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
CodeArtifactService.PackageVersionStatusChangeResult revisionMismatch = service.updatePackageVersionsStatus(
REGION, "dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"),
Map.of("1.0.0", "not-the-real-revision"), null, "Archived");
assertEquals("MISMATCHED_REVISION", revisionMismatch.failedVersions().get("1.0.0").errorCode());
CodeArtifactService.PackageVersionStatusChangeResult statusMismatch = service.updatePackageVersionsStatus(
REGION, "dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, "Unlisted",
"Archived");
assertEquals("MISMATCHED_STATUS", statusMismatch.failedVersions().get("1.0.0").errorCode());
assertTrue(statusMismatch.failedVersions().get("1.0.0").errorMessage().contains("current status: Published"));
}
@Test
void updatePackageVersionsStatusCannotMoveAwayFromDisposed() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
service.disposePackageVersions(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"),
null, null);
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, null, "Unlisted");
assertEquals("NOT_ALLOWED", result.failedVersions().get("1.0.0").errorCode());
}
/**
* Raised by Greptile's review: the batch actions' own existence/override matching used the
* raw requested version string, so archiving a NuGet version and then calling
* {@code UpdatePackageVersionsStatus} again with an equivalent spelling (AWS's own worked
* example, {@code 1.00} and {@code 1.0.0}) found the version real but missed its override,
* silently defaulting to {@code Published} and failing {@code MISMATCHED_STATUS} against an
* {@code expectedStatus=Archived} that was, in reality, already true.
*/
@Test
void updatePackageVersionsStatusMatchesAnEquivalentNuGetVersionSpellingAgainstAnExistingOverride() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("nuget");
when(bagetterClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0.0",
Instant.ofEpochSecond(1000))));
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "nuget", null, "my-pkg",
List.of("1.0.0"), null, null, "Archived");
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "nuget", null, "my-pkg", List.of("1.00"), null, "Archived", "Unlisted");
assertEquals("Unlisted", result.successfulVersions().get("1.00").status());
}
@Test
void updatePackageVersionsStatusRejectsUnfinishedDisposedOrDeletedAsTargetStatus() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
for (String badTarget : List.of("Unfinished", "Disposed", "Deleted", "NotAStatus")) {
AwsException e = assertThrows(AwsException.class, () -> service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, null, badTarget));
assertEquals("ValidationException", e.getErrorCode());
}
}
@Test
void updatePackageVersionsStatusRejectsDisposedAsExpectedStatusButDisposeAcceptsIt() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
AwsException e = assertThrows(AwsException.class, () -> service.updatePackageVersionsStatus(REGION, "dom",
null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, "Disposed", "Archived"));
assertEquals("ValidationException", e.getErrorCode());
// DisposePackageVersionsRequest.expectedStatus's own wider valid set accepts "Disposed"
// itself (confirmed against the API reference): the version isn't actually Disposed yet,
// so this still fails, but on the per-version MISMATCHED_STATUS check, not request
// validation.
CodeArtifactService.PackageVersionStatusChangeResult result = service.disposePackageVersions(REGION, "dom",
null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, "Disposed");
assertEquals("MISMATCHED_STATUS", result.failedVersions().get("1.0.0").errorCode());
}
@Test
void updatePackageVersionsStatusRequiresVersionsAndCapsAtOneHundred() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
AwsException missing = assertThrows(AwsException.class, () -> service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", List.of(), null, null, "Archived"));
assertEquals("ValidationException", missing.getErrorCode());
List<String> tooMany = IntStream.range(0, 101).mapToObj(i -> "1.0." + i).toList();
AwsException overLimit = assertThrows(AwsException.class, () -> service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "generic", "ns", "my-pkg", tooMany, null, null, "Archived"));
assertEquals("ValidationException", overLimit.getErrorCode());
}
@Test
void disposePackageVersionsDeletesGenericAssetBytesAndBlocksFurtherDownload() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
publishGeneric("repo", "my-pkg", "1.0.0", "a".getBytes(StandardCharsets.UTF_8));
CodeArtifactService.PackageVersionStatusChangeResult result = service.disposePackageVersions(REGION, "dom",
null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, null);
assertEquals("Disposed", result.successfulVersions().get("1.0.0").status());
AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null,
"repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", null));
assertEquals("ResourceNotFoundException", e.getErrorCode());
// DescribePackageVersion still answers for a disposed version (per the User Guide: "To
// view information about a disposed package version, use DescribePackageVersion"), it
// just reports no assets left.
CodeArtifactPackageVersion described = service.describePackageVersion(REGION, "dom", null, "repo", "generic",
"ns", "my-pkg", "1.0.0");
assertEquals("Disposed", described.getStatus());
assertTrue(described.getAssets().isEmpty());
}
/**
* A sidecar that cannot supply a timestamp for one of its versions reports it as a {@code
* null} {@code publishedTime} (the same possibility {@code listPackageVersions} itself
* already handles); building the per-call publish-time lookup with {@code Collectors.toMap}
* would throw a {@code NullPointerException} on that null value (it uses {@code Map.merge}
* internally, which rejects one), so this must still succeed.
*/
@Test
void updatePackageVersionsStatusSucceedsWhenTheSidecarHasNoTimestampForTheVersion() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0", null)));
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "maven", "com.example", "a", List.of("1.0"), null, null, "Archived");
assertEquals("Archived", result.successfulVersions().get("1.0").status());
assertTrue(result.failedVersions().isEmpty());
}
@Test
void updatePackageVersionsStatusArchivesAMavenVersionThroughTheSidecarOverrideAndGetAssetIsBlocked() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a.jar"))).thenReturn(Optional.of("jar-bytes".getBytes(StandardCharsets.UTF_8)));
CodeArtifactService.PackageVersionStatusChangeResult result = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "maven", "com.example", "a", List.of("1.0"), null, null, "Archived");
assertEquals("Archived", result.successfulVersions().get("1.0").status());
CodeArtifactService.ListPackageVersionsResult listed = service.listPackageVersions(REGION, "dom", null,
"repo", "maven", "com.example", "a", "Archived", null, null, null, null);
assertEquals(1, listed.versions().size());
assertEquals("Archived", listed.versions().get(0).status());
AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null,
"repo", "maven", "com.example", "a", "1.0", "a.jar", null));
assertEquals("ResourceNotFoundException", e.getErrorCode());
verify(reposiliteClient, never()).fetchPackageVersionAsset(any(), any(), any(), any(), any(), any(), any());
}
@Test
void disposePackageVersionsDeletesEveryRealAssetAndKeepsListingTheVersionAsDisposed() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar", "a-1.0.pom"));
CodeArtifactService.PackageVersionStatusChangeResult result = service.disposePackageVersions(REGION, "dom",
null, "repo", "maven", "com.example", "a", List.of("1.0"), null, null);
assertEquals("Disposed", result.successfulVersions().get("1.0").status());
verify(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"));
verify(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"));
// The sidecar no longer lists the disposed version at all (its content is gone), yet
// ListPackageVersions still reports it, by status=Disposed, from the override alone.
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of());
CodeArtifactService.ListPackageVersionsResult listed = service.listPackageVersions(REGION, "dom", null,
"repo", "maven", "com.example", "a", "Disposed", null, null, null, null);
assertEquals(1, listed.versions().size());
assertEquals("1.0", listed.versions().get(0).version());
assertEquals("Disposed", listed.versions().get(0).status());
}
/**
* Raised by Greptile's review: {@code applyContainerBackedStatusChange} writes the override
* {@code Disposed} before deleting any real assets, so a sidecar failure partway through that
* deletion loop left the version Disposed with some assets still real, and the unconditional
* {@code NOT_ALLOWED} on an already-{@code Disposed} version meant no further
* {@code DisposePackageVersions} call could ever finish that cleanup. A retry targeting
* {@code Disposed} again must now succeed and delete whatever the sidecar still lists.
*
* <p>Also proves Greptile's own follow-up finding on that same fix: the jar's bytes, freed by
* the first (overall failed) attempt, must still count against {@code
* DescribeDomain.assetSizeBytes} once the retry finishes the pom, not just the pom's own bytes
* freed by the retry itself; {@link #deleteContainerBackedVersionAssets} subtracts each
* asset's bytes right after that asset's own delete, not batched at the end, specifically so a
* failure between two deletes never loses the first one's already-freed bytes.
*/
@Test
void disposePackageVersionsRetriesAfterAPartialAssetDeletionFailureAndFinishesCleanup() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
recordBytes("dom", "repo", "maven", "com.example", "a", 100L);
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar", "a-1.0.pom"));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(new byte[25]));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"));
assertThrows(IllegalStateException.class, () -> service.disposePackageVersions(REGION, "dom", null, "repo",
"maven", "com.example", "a", List.of("1.0"), null, null));
// The override already reads Disposed (written before the failed delete), so downloads
// are already blocked even though the pom never actually got deleted.
assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null, "repo", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null));
verify(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"));
assertEquals(60L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
// The sidecar recovers; its own listing now only names the pom (the jar's delete already
// completed on the first attempt), the same self-correcting signal a real retry relies on.
doNothing().when(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"));
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.pom"));
CodeArtifactService.PackageVersionStatusChangeResult retry = service.disposePackageVersions(REGION, "dom",
null, "repo", "maven", "com.example", "a", List.of("1.0"), null, null);
assertEquals("Disposed", retry.successfulVersions().get("1.0").status());
// Twice in total across both attempts: the first one threw (counted on the mock
// regardless), the retry's own call is the one that actually finished the delete.
verify(reposiliteClient, times(2)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"));
assertEquals(35L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
/**
* Raised by Greptile's review: unlike Maven, an npm disposal retry cannot rely on a fresh
* {@code listPackageVersionAssetNames} call to tell it what is still left to delete.
* {@code VerdaccioSidecarClient#deletePackageVersionAsset} removes the version from the
* packument before the tarball delete even runs (Verdaccio's own real two-step unpublish,
* confirmed live, see that method's own javadoc), so once that update lands, a fresh listing
* can never again answer "what is left:" it already reads empty, exactly as simulated here by
* re-stubbing it to return nothing after the first (failed) attempt. The retry must still
* finish deleting the tarball, which it can only do by reading the override's own {@code
* pendingAssetNames} instead of asking the sidecar again.
*/
@Test
void disposePackageVersionsRetriesAnNpmTarballDeleteEvenAfterTheSidecarsOwnListingGoesEmpty() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("npm");
when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
assertThrows(IllegalStateException.class, () -> service.disposePackageVersions(REGION, "dom", null, "repo",
"npm", null, "my-pkg", List.of("1.0.0"), null, null));
// Simulates exactly what Greptile's review describes: Verdaccio's own packument update
// already landed, so a fresh listing now reads empty even though the tarball itself
// never actually got deleted.
when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of());
doNothing().when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
CodeArtifactService.PackageVersionStatusChangeResult retry = service.disposePackageVersions(REGION, "dom",
null, "repo", "npm", null, "my-pkg", List.of("1.0.0"), null, null);
assertEquals("Disposed", retry.successfulVersions().get("1.0.0").status());
// Twice in total across both attempts: the first one threw (counted on the mock
// regardless), the retry's own call is the one that actually finished the delete.
verify(verdaccioClient, times(2)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
}
@Test
void disposePackageVersionsRejectsAnExpectedStatusUpdateDoesNotAllow() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service.disposePackageVersions(REGION, "dom", null,
"repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, "NotAStatus"));
assertEquals("ValidationException", e.getErrorCode());
}
/**
* Qodo review finding on this PR: {@code DescribeDomain.assetSizeBytes} kept counting a
* container-backed version's bytes forever after disposal, since the per-package running
* total was never reduced when its real sidecar assets were deleted.
*/
@Test
void disposePackageVersionsReducesTheDomainAssetSizeByTheRealDeletedBytes() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
recordBytes("dom", "repo", "maven", "com.example", "a", 100L);
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"),
null, null);
assertEquals(60L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
/**
* Raised by Greptile's review: {@code PypiserverSidecarClient#deletePackageVersionAsset}
* removes every file sharing the same raw package name and version in one call (confirmed
* live, the same quirk {@code copyContainerBackedPackageVersions}'s own write path already
* works around), so a release's second file could already be gone by the time the old
* interleaved fetch-then-delete loop got to measuring it, undercounting the bytes {@code
* DescribeDomain.assetSizeBytes} should have freed. Both assets are now measured before
* either is deleted, so the collateral deletion below (simulated by having the sdist's own
* delete flip the wheel's fetch to empty, exactly like the real sidecar's own side effect)
* no longer loses its byte count.
*/
@Test
void disposePackageVersionsMeasuresEveryAssetBeforeDeletingAnyOfThemSoACollateralDeleteDoesNotLoseItsBytes() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("pypi");
recordBytes("dom", "repo", "pypi", null, "my-pkg", 100L);
when(pypiserverClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(pypiserverClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0"))).thenReturn(List.of("my-pkg-1.0.tar.gz", "my_pkg-1.0-py3-none-any.whl"));
AtomicBoolean sdistDeleted = new AtomicBoolean();
when(pypiserverClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0"), eq("my-pkg-1.0.tar.gz"))).thenReturn(Optional.of(new byte[40]));
when(pypiserverClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0"), eq("my_pkg-1.0-py3-none-any.whl"))).thenAnswer(invocation ->
sdistDeleted.get() ? Optional.empty() : Optional.of(new byte[25]));
doAnswer(invocation -> {
sdistDeleted.set(true);
return null;
}).when(pypiserverClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0"), eq("my-pkg-1.0.tar.gz"));
service.disposePackageVersions(REGION, "dom", null, "repo", "pypi", null, "my-pkg", List.of("1.0"), null,
null);
assertEquals(35L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
/**
* Qodo review finding on this PR: {@code ListPackageVersionAssets} and {@code
* GetPackageVersionReadme} still computed a container-backed version's revision with the raw,
* coordinate-derived {@code synthesizeContainerBackedRevision} formula, disagreeing with the
* fresh revision {@code updatePackageVersionsStatus}/{@code DescribePackageVersion}/{@code
* ListPackageVersions} report once a status override exists for that version.
*/
@Test
void listPackageVersionAssetsAndGetPackageVersionReadmeAgreeWithTheOverrideRevisionAfterArchiving() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("npm");
when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
when(verdaccioClient.packageVersionExists(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
when(verdaccioClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenReturn(Optional.of("tgz-bytes".getBytes(
StandardCharsets.UTF_8)));
recordReadme("dom", "repo", "npm", null, "my-pkg", "1.0.0", "hello");
CodeArtifactService.PackageVersionStatusChangeResult changed = service.updatePackageVersionsStatus(REGION,
"dom", null, "repo", "npm", null, "my-pkg", List.of("1.0.0"), null, null, "Archived");
String overrideRevision = changed.successfulVersions().get("1.0.0").revision();
CodeArtifactService.PackageVersionAssetsListResult assets = service.listPackageVersionAssets(REGION, "dom",
null, "repo", "npm", null, "my-pkg", "1.0.0", null, null);
assertEquals(overrideRevision, assets.versionRevision());
CodeArtifactService.PackageVersionReadmeResult readme = service.getPackageVersionReadme(REGION, "dom", null,
"repo", "npm", null, "my-pkg", "1.0.0");
assertEquals(overrideRevision, readme.versionRevision());
}
/**
* Qodo review finding on this PR: copying new content over a destination version that an
* earlier {@code updatePackageVersionsStatus} had archived left the old override in place,
* so the fresh content this copy just wrote would still read back as Archived and {@code
* GetPackageVersionAsset} would keep 404ing on it, contradicting the copy's own response
* (which reports Published).
*/
@Test
void copyPackageVersionsClearsAStaleArchivedOverrideAtTheDestinationAndUnblocksDownload() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
String srcRepoId = src.getSidecarContainerIds().get("maven");
String dstRepoId = dst.getSidecarContainerIds().get("maven");
byte[] newJar = "new-jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] oldJar = "old-jar-bytes".getBytes(StandardCharsets.UTF_8);
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
when(reposiliteClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
when(reposiliteClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJar));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJar));
when(reposiliteClient.listPackageVersions(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
service.updatePackageVersionsStatus(REGION, "dom", null, "dst", "maven", "com.example", "a", List.of("1.0"),
null, null, "Archived");
assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null, "dst", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false);
assertTrue(result.failedVersions().isEmpty());
assertEquals("Published", result.successfulVersions().get("1.0").status());
PackageVersionAssetResult downloaded = service.getPackageVersionAsset(REGION, "dom", null, "dst", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null);
assertEquals(oldJar.length, downloaded.asset().getSize());
}
/**
* Qodo review's remaining half of the same finding: {@code copyContainerBackedPackageVersions}
* clears a stale override on its own overwrite path, but nothing cleared one for a native
* publish: every container-backed proxy controller (Maven, npm, pypi, nuget) now calls
* {@code forgetContainerBackedStatusOverride} right alongside its existing byte-accounting
* call once a native publish actually writes something. This proves the shared primitive those
* four call sites all delegate to.
*/
@Test
void forgetContainerBackedStatusOverrideClearsItAndUnblocksDownload() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of("jar-bytes".getBytes(
StandardCharsets.UTF_8)));
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "maven", "com.example", "a",
List.of("1.0"), null, null, "Archived");
assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null, "repo", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null));
service.forgetContainerBackedStatusOverride(REGION, "dom", null, "repo", "maven", "com.example", "a", "1.0");
PackageVersionAssetResult downloaded = service.getPackageVersionAsset(REGION, "dom", null, "repo", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null);
assertEquals("jar-bytes".getBytes(StandardCharsets.UTF_8).length, downloaded.asset().getSize());
}
/**
* Raised by hectorvent's review of this PR: {@code forgetContainerBackedStatusOverride} above
* only ever clears an Archived/Disposed override after a native proxy controller's real
* sidecar write already succeeded, which would let a package-manager republish silently
* resurrect either status. Every native proxy controller now calls this guard first, before
* issuing that write, and must see it refuse exactly the two statuses the User Guide blocks
* unconditionally: Published, Unlisted, and a coordinate with no override at all must all
* sail through untouched.
*/
@Test
void requireContainerBackedVersionNotArchivedOrDisposedBlocksOnlyThoseTwoStatuses() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)),
new RepositorySidecarManager.PackageVersionTimestamp("2.0", Instant.ofEpochSecond(1000)),
new RepositorySidecarManager.PackageVersionTimestamp("3.0", Instant.ofEpochSecond(1000))));
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "maven", "com.example", "a",
List.of("1.0"), null, null, "Archived");
AwsException archivedError = assertThrows(AwsException.class,
() -> service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null, "repo",
"maven", "com.example", "a", "1.0"));
assertEquals("ConflictException", archivedError.getErrorCode());
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("2.0"),
null, null);
AwsException disposedError = assertThrows(AwsException.class,
() -> service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null, "repo",
"maven", "com.example", "a", "2.0"));
assertEquals("ConflictException", disposedError.getErrorCode());
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "maven", "com.example", "a",
List.of("3.0"), null, null, "Unlisted");
assertDoesNotThrow(() -> service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null,
"repo", "maven", "com.example", "a", "3.0"));
assertDoesNotThrow(() -> service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null,
"repo", "maven", "com.example", "a", "4.0-never-touched"));
}
/**
* Raised by Greptile's review: {@code requireContainerBackedVersionNotArchivedOrDisposed}'s
* guard, the real sidecar write, and this call are necessarily three separate steps (the
* write sits in between, with no lock held across it), so a concurrent
* {@code disposePackageVersions} landing in that gap already deleted the real content before
* the publish's own write restored it. Leaving the override alone (it correctly already does)
* is not enough on its own: a native per-format download route never consults the override at
* all, so the restored bytes stayed live even with the override still reading {@code
* Disposed}. This must now also undo that restoration by re-running the real asset deletion.
*/
@Test
void forgetContainerBackedStatusOverrideIfUnchangedRedeletesRestoredAssetsWhenAConcurrentDisposeWonTheRace() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
// The publish's own guard ran first, before anything (the real write or the race) has
// happened yet: no override exists, so this is the snapshot it carries into its own
// later forgetContainerBackedStatusOverrideIfUnchanged call.
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
String beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null,
"repo", "maven", "com.example", "a", "1.0");
assertNull(beforeRevision);
// A concurrent dispose lands in the gap between that guard and the publish's own real
// write landing. Nothing is stubbed to list any assets yet, so this dispose finds (and
// deletes) nothing real, the same as if the publish's write genuinely had not landed yet.
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"),
null, null);
// The publish's own write now lands after the dispose already finished, restoring real
// content the sidecar reports back from here on.
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[10]));
service.forgetContainerBackedStatusOverrideIfUnchanged(REGION, "dom", null, "repo", "maven",
"com.example", "a", "1.0", beforeRevision);
verify(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"));
assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, "dom", null, "repo", "maven",
"com.example", "a", "1.0", "a-1.0.jar", null));
}
/**
* Raised by Greptile's review of the fix above: the restored asset names were only ever
* recorded into the override's own {@code pendingAssetNames} as each one's own delete
* succeeded, never upfront before the first attempt. A failure on the very first restored
* asset's delete therefore left {@code pendingAssetNames} exactly as the already-completed
* disposal before it left it, almost always empty, so a later {@code DisposePackageVersions}
* retry saw nothing pending and reported success with the restored file still real.
*/
@Test
void forgetContainerBackedStatusOverrideIfUnchangedSavesRestoredAssetNamesBeforeDeletingSoARetryCanFinish() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("maven");
when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
String beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null,
"repo", "maven", "com.example", "a", "1.0");
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"),
null, null);
// The publish's own write restores real content after the dispose above already
// finished, but this attempt to undo it fails on the restored asset's own delete.
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
assertThrows(IllegalStateException.class, () -> service.forgetContainerBackedStatusOverrideIfUnchanged(
REGION, "dom", null, "repo", "maven", "com.example", "a", "1.0", beforeRevision));
// The sidecar recovers; a fresh listing now reads empty (the same ambiguous signal a
// real Reposilite instance could give here), so only the override's own saved
// pendingAssetNames can tell a retry the restored file is still real.
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of());
doNothing().when(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
CodeArtifactService.PackageVersionStatusChangeResult retry = service.disposePackageVersions(REGION, "dom",
null, "repo", "maven", "com.example", "a", List.of("1.0"), null, null);
assertEquals("Disposed", retry.successfulVersions().get("1.0").status());
verify(reposiliteClient, times(2)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
}
/**
* Raised by Greptile's review of the fix above, for npm specifically: once a concurrent
* disposal's own packument-removal half has already landed (Verdaccio's real two-step
* unpublish, see {@code VerdaccioSidecarClient#deletePackageVersionAsset}'s own javadoc), a
* fresh {@code listPackageVersionAssetNames} call goes blind to the tarball even though that
* disposal's own {@code pendingAssetNames} still correctly names it (its own tarball delete
* is what actually failed). Overwriting {@code pendingAssetNames} with only the fresh
* (now-empty) list here would lose that name outright; the union of both must still name the
* tarball for cleanup.
*/
@Test
void forgetContainerBackedStatusOverrideIfUnchangedMergesTheFreshListingWithWhatTheOverrideAlreadyKnows() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("npm");
when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
String beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(REGION, "dom", null,
"repo", "npm", null, "my-pkg", "1.0.0");
when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
assertThrows(IllegalStateException.class, () -> service.disposePackageVersions(REGION, "dom", null, "repo",
"npm", null, "my-pkg", List.of("1.0.0"), null, null));
// Verdaccio's own packument no longer lists the version at all (its removal half of the
// two-step unpublish already landed, even though the tarball delete above failed), so a
// fresh listing now reads empty, exactly the ambiguous signal Greptile's review describes.
when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of());
doNothing().when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
service.forgetContainerBackedStatusOverrideIfUnchanged(REGION, "dom", null, "repo", "npm", null, "my-pkg",
"1.0.0", beforeRevision);
// Twice in total: the setup dispose above threw (counted on the mock regardless), this
// call's own redispose is the one that actually finishes deleting the tarball.
verify(verdaccioClient, times(2)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
}
/**
* Qodo review finding on this PR: a generic {@code publishPackageVersion} treated every
* existing version whose status was not Published (including Disposed and Archived) exactly
* like a brand new or Unfinished one, letting a publish silently resurrect a version the
* User Guide says can never move back to Published once either status applies.
*/
@Test
void publishPackageVersionRejectsRepublishOfADisposedOrArchivedGenericVersion() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "archived-pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "generic", "ns", "archived-pkg",
List.of("1.0.0"), null, null, "Archived");
AwsException archivedError = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION,
"dom", null, "repo", "generic", "ns", "archived-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content),
"false", content));
assertEquals("ConflictException", archivedError.getErrorCode());
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "disposed-pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
service.disposePackageVersions(REGION, "dom", null, "repo", "generic", "ns", "disposed-pkg",
List.of("1.0.0"), null, null);
AwsException disposedError = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION,
"dom", null, "repo", "generic", "ns", "disposed-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content),
"false", content));
assertEquals("ConflictException", disposedError.getErrorCode());
}
/**
* Unlisted only hides a version from listings, and the User Guide never says republishing it
* is blocked the way it does for Archived/Disposed, so this folds into the same
* idempotent-replay rule Published already has: an exact byte-identical retry is a no-op, but
* genuinely different content is still rejected, rather than silently rebuilding it as though
* no version existed there at all (which the Unfinished fallthrough would otherwise do).
*/
@Test
void publishPackageVersionReplaysAnUnlistedVersionIdempotentlyButRejectsDifferentContent() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
service.updatePackageVersionsStatus(REGION, "dom", null, "repo", "generic", "ns", "pkg", List.of("1.0.0"),
null, null, "Unlisted");
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "pkg", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"pkg", "1.0.0");
assertEquals("Unlisted", pv.getStatus());
byte[] different = "v2".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", "ns", "pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "false", different));
assertEquals("ConflictException", e.getErrorCode());
}
// --------------------------------------------- NuGet revision normalization
@Test
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.XmlParser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -22,14 +23,17 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -784,6 +788,439 @@ class ReposiliteSidecarClientTest {
assertEquals("1.0", XmlParser.extractFirst(xml, "release", null));
}
/**
* {@link io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient#recordVersionDisposed}'s
* dispose-time counterpart to {@link #recordVersionAvailableAppendsToExistingVersionsAndAdvancesReleaseForANonSnapshot}:
* removing a non-latest version must leave {@code latest}/{@code release} exactly as they
* were, since the metadata's own append-order list is untouched past the removed entry.
*/
@Test
void recordVersionDisposedRemovesTheVersionAndLeavesLatestAndReleaseUntouchedWhenItWasNeitherOne() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>2.0</latest><release>2.0</release><versions><version>1.0</version>"
+ "<version>2.0</version></versions><lastUpdated>20260101000000</lastUpdated></versioning>"
+ "</metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else if (metadataPath.equals(exchange.getRequestURI().getPath())) {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
} else {
// This context path-matches the checksum siblings this emulator now also
// rewrites alongside the metadata file itself (see
// ReposiliteSidecarClient#recordVersionDisposed), so only the exact metadata
// path's own PUT is captured into putBody.
respond(exchange, 200, "");
}
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
String xml = new String(putBody.get(), StandardCharsets.UTF_8);
assertEquals(List.of("2.0"), XmlParser.extractAll(xml, "version"));
assertEquals("2.0", XmlParser.extractFirst(xml, "latest", null));
assertEquals("2.0", XmlParser.extractFirst(xml, "release", null));
}
/**
* Removing the current {@code latest}/{@code release} version itself must recompute both from
* whatever remains, in the same append order the metadata already preserves: the last
* surviving entry becomes the new {@code latest}, and the last surviving non-{@code -SNAPSHOT}
* entry becomes the new {@code release} (here, that is the same entry since neither remaining
* version is a snapshot).
*/
@Test
void recordVersionDisposedRecomputesLatestAndReleaseWhenTheDisposedVersionWasTheLatest() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>3.0</latest><release>3.0</release><versions><version>1.0</version>"
+ "<version>2.0</version><version>3.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else if (metadataPath.equals(exchange.getRequestURI().getPath())) {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
} else {
// This context path-matches the checksum siblings this emulator now also
// rewrites alongside the metadata file itself (see
// ReposiliteSidecarClient#recordVersionDisposed), so only the exact metadata
// path's own PUT is captured into putBody.
respond(exchange, 200, "");
}
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "3.0");
String xml = new String(putBody.get(), StandardCharsets.UTF_8);
assertEquals(List.of("1.0", "2.0"), XmlParser.extractAll(xml, "version"));
assertEquals("2.0", XmlParser.extractFirst(xml, "latest", null));
assertEquals("2.0", XmlParser.extractFirst(xml, "release", null));
}
/**
* {@code release} skips back past a surviving {@code -SNAPSHOT} entry to the last real release,
* the same rule {@link #recordVersionAvailableLeavesTheExistingReleaseUntouchedForASnapshotVersion}
* already proves for the add path.
*/
@Test
void recordVersionDisposedSkipsASnapshotWhenRecomputingRelease() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>2.0-SNAPSHOT</latest><release>1.0</release><versions><version>1.0</version>"
+ "<version>2.0-SNAPSHOT</version></versions><lastUpdated>20260101000000</lastUpdated>"
+ "</versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else if (metadataPath.equals(exchange.getRequestURI().getPath())) {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
} else {
// This context path-matches the checksum siblings this emulator now also
// rewrites alongside the metadata file itself (see
// ReposiliteSidecarClient#recordVersionDisposed), so only the exact metadata
// path's own PUT is captured into putBody.
respond(exchange, 200, "");
}
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
String xml = new String(putBody.get(), StandardCharsets.UTF_8);
assertEquals(List.of("2.0-SNAPSHOT"), XmlParser.extractAll(xml, "version"));
assertEquals("2.0-SNAPSHOT", XmlParser.extractFirst(xml, "latest", null));
assertNull(XmlParser.extractFirst(xml, "release", null), "no real release survives, so release must be "
+ "omitted rather than naming a snapshot");
}
/**
* Raised by Greptile's review: a real {@code mvn deploy} always also PUTs {@code
* maven-metadata.xml.sha1}/{@code .md5}, so {@link
* io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient#recordVersionDisposed}'s
* own rewrite of the metadata must carry fresh checksums of whatever it just wrote, not leave
* the pre-dispose checksums standing over content that no longer matches them.
*/
@Test
void recordVersionDisposedRewritesTheSha1AndMd5ChecksumsToMatchTheNewMetadata() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>2.0</latest><release>2.0</release><versions><version>1.0</version>"
+ "<version>2.0</version></versions><lastUpdated>20260101000000</lastUpdated></versioning>"
+ "</metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
AtomicReference<byte[]> putBody = new AtomicReference<>();
AtomicReference<byte[]> sha1Body = new AtomicReference<>();
AtomicReference<byte[]> md5Body = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else if (metadataPath.equals(exchange.getRequestURI().getPath())) {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> {
sha1Body.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
server.createContext(metadataPath + ".md5", exchange -> {
md5Body.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
assertEquals(Digests.sha1Hex(putBody.get()), new String(sha1Body.get(), StandardCharsets.UTF_8));
assertEquals(Digests.md5Hex(putBody.get()), new String(md5Body.get(), StandardCharsets.UTF_8));
}
/** The counterpart to the rewrite case above: the metadata PUT itself failing must not be swallowed. */
@Test
void recordVersionDisposedThrowsWhenTheMetadataRewriteItselfFails() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>2.0</latest><release>2.0</release><versions><version>1.0</version>"
+ "<version>2.0</version></versions><lastUpdated>20260101000000</lastUpdated></versioning>"
+ "</metadata>";
server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
respond(exchange, 500, "");
}
});
assertThrows(IllegalStateException.class,
() -> client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0"));
}
/**
* Greptile's review again: {@link
* io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient#recordVersionDisposed}
* also removes the two checksum siblings when the metadata file itself is removed outright
* (every version disposed), not just the metadata file.
*/
@Test
void recordVersionDisposedDeletesTheChecksumSiblingsWhenTheMetadataFileIsDeleted() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
List<String> deletedPaths = new CopyOnWriteArrayList<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
deletedPaths.add(exchange.getRequestURI().getPath());
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> {
// deleteArtifactIfPresent checks existence with a HEAD first; only the real DELETE
// that follows is the one this test cares about recording.
if ("DELETE".equals(exchange.getRequestMethod())) {
deletedPaths.add(exchange.getRequestURI().getPath());
}
respond(exchange, 200, "");
});
server.createContext(metadataPath + ".md5", exchange -> {
if ("DELETE".equals(exchange.getRequestMethod())) {
deletedPaths.add(exchange.getRequestURI().getPath());
}
respond(exchange, 200, "");
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
assertThat(deletedPaths, containsInAnyOrder(metadataPath, metadataPath + ".sha1", metadataPath + ".md5"));
}
/** A checksum sibling missing entirely (never pushed, or a sidecar restored from an older snapshot) is a no-op. */
@Test
void recordVersionDisposedToleratesAMissingChecksumSiblingOnDelete() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> respond(exchange, 404, ""));
server.createContext(metadataPath + ".md5", exchange -> respond(exchange, 404, ""));
assertDoesNotThrow(() -> client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0"));
}
/**
* Raised by Greptile's review: a HEAD failing with something other than a confirmed 404 (a
* genuine sidecar error, not a clean "it's not there" answer) must not be treated the same as
* a confirmed-absent checksum; silently skipping the delete there would report a successful
* disposal while the sidecar's own real error was never surfaced or retried.
*/
@Test
void recordVersionDisposedThrowsWhenTheChecksumExistenceCheckFails() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> respond(exchange, 500, ""));
server.createContext(metadataPath + ".md5", exchange -> respond(exchange, 200, ""));
assertThrows(IllegalStateException.class,
() -> client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0"));
}
/**
* Raised by Greptile's review: a retry whose first attempt already deleted the metadata file
* itself, but then failed on exactly a checksum delete, used to hit the {@code existing.isEmpty()}
* early return and report success leaving that checksum behind, since there was no metadata
* left for it to compare against. The checksum siblings are now cleaned up on this path too.
*/
@Test
void recordVersionDisposedCleansUpLingeringChecksumsEvenWhenTheMetadataFileIsAlreadyGone() {
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
List<String> deletedPaths = new CopyOnWriteArrayList<>();
server.createContext(metadataPath, exchange -> respond(exchange, 404, ""));
server.createContext(metadataPath + ".sha1", exchange -> {
// deleteArtifactIfPresent checks existence with a HEAD first; only the real DELETE
// that follows is the one this test cares about recording.
if ("DELETE".equals(exchange.getRequestMethod())) {
deletedPaths.add(exchange.getRequestURI().getPath());
}
respond(exchange, 200, "");
});
server.createContext(metadataPath + ".md5", exchange -> {
if ("DELETE".equals(exchange.getRequestMethod())) {
deletedPaths.add(exchange.getRequestURI().getPath());
}
respond(exchange, 200, "");
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
assertThat(deletedPaths, containsInAnyOrder(metadataPath + ".sha1", metadataPath + ".md5"));
}
/**
* Raised by Greptile's review: {@code fetchArtifact} itself returns empty for every non-200
* response, 500 included, which must not be read as "the metadata file is confirmed gone."
* A transient read failure here must surface, not silently report a successful disposal while
* the metadata on disk still lists the version this was supposed to remove.
*/
@Test
void recordVersionDisposedThrowsWhenTheMetadataReadFails() {
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
server.createContext(metadataPath, exchange -> respond(exchange, 500, ""));
assertThrows(IllegalStateException.class,
() -> client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0"));
}
/**
* A metadata file that would end up naming no versions at all is deleted outright, matching
* how a package that never had a version published has no metadata file at all.
*/
@Test
void recordVersionDisposedDeletesTheMetadataFileWhenNoVersionsAreLeft() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
AtomicReference<String> deletedMethod = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
deletedMethod.set(exchange.getRequestMethod());
respond(exchange, 200, "");
}
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "1.0");
assertEquals("DELETE", deletedMethod.get());
}
/**
* A version the metadata never named to begin with (already removed by an earlier call, or
* disposed before {@code maven-metadata.xml} ever existed) leaves the metadata itself
* untouched: nothing is written back to that exact path.
*
* <p>Raised by Greptile's review: this same early return used to skip the checksum siblings
* too, so a retry whose first attempt removed the version but then failed on exactly the
* checksum write never got another chance to repair it. The checksums are now repaired every
* time this returns here, idempotently (the metadata content itself did not change), not just
* the one call that happened to also rewrite the metadata.
*/
@Test
void recordVersionDisposedIsANoOpWhenTheMetadataNeverNamedTheVersion() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
AtomicReference<String> writeMethod = new AtomicReference<>();
AtomicReference<byte[]> sha1Body = new AtomicReference<>();
AtomicReference<byte[]> md5Body = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else if (metadataPath.equals(exchange.getRequestURI().getPath())) {
writeMethod.set(exchange.getRequestMethod());
respond(exchange, 200, "");
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> {
sha1Body.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
server.createContext(metadataPath + ".md5", exchange -> {
md5Body.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
client.recordVersionDisposed("dom--repo", "com.example", "a", "9.9");
assertNull(writeMethod.get(), "expected no PUT/DELETE of the metadata file itself");
assertEquals(Digests.sha1Hex(existing.getBytes(StandardCharsets.UTF_8)),
new String(sha1Body.get(), StandardCharsets.UTF_8));
assertEquals(Digests.md5Hex(existing.getBytes(StandardCharsets.UTF_8)),
new String(md5Body.get(), StandardCharsets.UTF_8));
}
/**
* Raised by Greptile's review: {@code deployArtifact}'s own idempotent short-circuit (the
* checksum already on the sidecar matches byte for byte, so nothing is actually sent) also
* reports {@code wroteNewContent() == false}, the exact same signal a genuine failure gives.
* A disposal retry whose {@code .sha1} already landed on an earlier attempt, but then failed
* on {@code .md5}, must not treat that already-correct, unchanged {@code .sha1} as a failure
* all over again: that would stop the retry before it ever reached {@code .md5} a second
* time, getting stuck on the one checksum that was already fine.
*/
@Test
void recordVersionDisposedRepairsTheRemainingChecksumEvenWhenTheOtherAlreadyMatches() {
String existing = "<metadata><groupId>com.example</groupId><artifactId>a</artifactId><versioning>"
+ "<latest>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml";
String correctSha1 = Digests.sha1Hex(existing.getBytes(StandardCharsets.UTF_8));
AtomicReference<byte[]> md5Body = new AtomicReference<>();
server.createContext(metadataPath, exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".sha1", exchange -> {
// Already correct: a GET returns exactly what the retry is about to compute and PUT,
// so deployArtifact's own existingArtifactMatches short-circuits (200, wroteNewContent
// false) without ever reaching a real PUT here.
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, correctSha1);
} else {
respond(exchange, 200, "");
}
});
server.createContext(metadataPath + ".md5", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 404, "");
} else {
md5Body.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
}
});
assertDoesNotThrow(() -> client.recordVersionDisposed("dom--repo", "com.example", "a", "9.9"));
assertEquals(Digests.md5Hex(existing.getBytes(StandardCharsets.UTF_8)),
new String(md5Body.get(), StandardCharsets.UTF_8));
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);