feat(codeartifact): bridge CopyPackageVersions to every sidecar format (#5888)

CopyPackageVersions only covered the generic format; maven, npm, pypi, and
nuget each publish straight to their own sidecar and keep no
packageVersions record this action could read from or write to. Bridges
all four, each confirmed live against a real container: maven reuses
Reposilite's existing mvn-deploy write path, while npm/pypi/nuget each
speak their own real wire protocol directly (Verdaccio's packument PUT,
pypiserver's twine-shaped multipart upload, and BaGetter's NuGet push),
the same protocol each format's own data-plane proxy already forwards
unmodified for a native client. CopyPackageVersions now supports every
format CodeArtifact does, matching real AWS, which places no format
restriction on this action at all.

An overwrite deletes a conflicting existing asset immediately before
rewriting it for every format, since each sidecar rejects a plain
overwrite of differing content; a best-effort compensating cleanup
restores or removes whatever one version's write itself touched if a
later step in that same version fails, preserving the original error. A
copied Maven version is also merged into the destination's
maven-metadata.xml so real clients can discover it, and copied bytes feed
the same byte-accounting mechanism native publishes already use. A copied
npm or pypi version's readme is propagated from this service's own
captured-at-publish-time record, since neither sidecar can answer for one
after the fact. The synthesized revision for every container-backed
format is truncated to fit versionRevisions' own 50-character limit, so a
revision obtained from DescribePackageVersion can be handed straight back
into a revision-pinned copy.

Also closes a cross-version batch-write gap: source assets are verified
against the real sidecar before any destination write in the same batch,
the same split the generic path already uses.

Fixes two more real-sidecar quirks found on review: pypiserver's own
delete call removes every file sharing a release's exact name and
version, not just the one asset name it was asked to delete, so a release
carrying both an sdist and a wheel lost one of them on overwrite when
assets were deleted one at a time, interleaved with the writes. Every
destination asset a version already holds is now deleted up front, in its
own phase, before any new content is written, which changes nothing for
Maven/npm/nuget since their own deletes are already scoped to exactly the
asset (or, for npm/nuget, the single asset a version ever holds) being
removed. An npm copy also used to rebuild a minimal version document from
scratch, dropping dependencies and anything else npm's own protocol
carries beyond dist; it now reuses the source's own version entry
verbatim, with only dist itself rewritten to point at the copy.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-18 09:28:42 -05:00
1 parent c17bd49096
commit 5dcddc9dfa
14 files changed
+2124 -46

No files matched your search

@@ -460,6 +460,91 @@ class CodeArtifactMavenDockerIntegrationTest {
.then().statusCode(404);
}
/**
* The real-world gap this closes: {@code CopyPackageVersions} used to only support the
* generic format, since Maven, npm, pypi, and nuget all keep their published assets straight
* in their own sidecar rather than a {@code packageVersions} record. Confirms the bridge
* reads every asset from the real Reposilite sidecar (not a mock) and writes them to the
* destination repository's own Reposilite path, byte for byte. {@code other-repo} is the
* empty repository {@link #repositoriesAreIsolatedFromEachOther} already created and never
* published to.
*/
@Test
@Order(18)
void copyPackageVersionsBridgesToTheRealReposiliteSidecar() {
byte[] jarBytes = "copy-me-jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] pomBytes = "copy-me-pom-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken).body(jarBytes)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/copyme/1.0.0/copyme-1.0.0.jar")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken).body(pomBytes)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/copyme/1.0.0/copyme-1.0.0.pom")
.then().statusCode(200);
String revision = given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"]}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=maven&namespace=com.example&package=copyme")
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0))
.extract().jsonPath().getString("successfulVersions.'1.0.0'.revision");
assertTrue(revision != null && !revision.isBlank());
byte[] copiedJar = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/other-repo/com/example/copyme/1.0.0/copyme-1.0.0.jar")
.then().statusCode(200)
.extract().asByteArray();
byte[] copiedPom = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/other-repo/com/example/copyme/1.0.0/copyme-1.0.0.pom")
.then().statusCode(200)
.extract().asByteArray();
assertEquals("copy-me-jar-bytes", new String(copiedJar, StandardCharsets.UTF_8));
assertEquals("copy-me-pom-bytes", new String(copiedPom, StandardCharsets.UTF_8));
String metadata = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/other-repo/com/example/copyme/maven-metadata.xml")
.then().statusCode(200)
.extract().asString();
assertTrue(metadata.contains("<version>1.0.0</version>"), metadata);
assertTrue(metadata.contains("<latest>1.0.0</latest>"), metadata);
assertTrue(metadata.contains("<release>1.0.0</release>"), metadata);
}
/**
* The real-world bug this closes: the destination already had {@code copyme-overwrite-1.0.0.jar}
* under the exact same name with different bytes, and Reposilite's own {@code
* redeployment: false} setting (confirmed live against this same container earlier in this
* class) rejects a plain PUT over it. Without deleting the old one first, this copy's PUT
* would come back {@code 409} even though {@code allowOverwrite} was set.
*/
@Test
@Order(19)
void copyPackageVersionsOverwritesASameNamedAssetWithDifferentContentAtTheRealSidecar() {
byte[] oldJarBytes = "old-overwrite-jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] newJarBytes = "new-overwrite-jar-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken).body(oldJarBytes)
.put("/codeartifact/maven/" + DOMAIN + "/other-repo/com/example/copyover/1.0.0/copyover-1.0.0.jar")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken).body(newJarBytes)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/copyover/1.0.0/copyover-1.0.0.jar")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"],\"allowOverwrite\":true}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=maven&namespace=com.example&package=copyover")
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/other-repo/com/example/copyover/1.0.0/copyover-1.0.0.jar")
.then().statusCode(200)
.extract().asByteArray();
assertEquals("new-overwrite-jar-bytes", new String(copied, StandardCharsets.UTF_8));
}
/**
* 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
@@ -612,6 +612,138 @@ class CodeArtifactNpmDockerIntegrationTest {
.body("version", equalTo("1.0.0"));
}
/**
* The real-world gap this closes: {@code CopyPackageVersions} used to only support the
* generic and maven formats; npm keeps its published versions straight in Verdaccio's own
* packument rather than a {@code packageVersions} record. Confirms the bridge reads the
* tarball from the real sidecar (not a mock) and republishes it to the destination
* repository's own Verdaccio instance, byte for byte. {@code other-repo} is the empty
* repository {@link #repositoriesAreIsolatedFromEachOther} already created.
*/
@Test
@Order(17)
void copyPackageVersionsBridgesToTheRealVerdaccioSidecar() {
String packageName = "copyme-npm-pkg";
byte[] tarball = "copy-me-npm-tarball-bytes".getBytes(StandardCharsets.UTF_8);
String envelope = "{\"name\":\"" + packageName + "\",\"versions\":{\"1.0.0\":{\"name\":\"" + packageName
+ "\",\"version\":\"1.0.0\",\"readme\":\"# Copy Me Readme\",\"dist\":{\"tarball\":\"http://ignored/"
+ packageName + "-1.0.0.tgz\"}}},\"_attachments\":{\"" + packageName + "-1.0.0.tgz\":{"
+ "\"content_type\":\"application/octet-stream\",\"data\":\""
+ Base64.getEncoder().encodeToString(tarball) + "\",\"length\":" + tarball.length + "}}}";
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(envelope)
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"]}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=npm&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/other-repo/" + packageName + "/-/" + packageName
+ "-1.0.0.tgz")
.then().statusCode(200)
.extract().asByteArray();
assertEquals("copy-me-npm-tarball-bytes", new String(copied, StandardCharsets.UTF_8));
// The real-world gap this proves closed: Verdaccio's own packument never echoes a
// per-version readme back (see GetPackageVersionReadme's own javadoc), so this bridge has
// no way to read it from the destination sidecar after copying the tarball; it must be
// propagated from this service's own captured-at-publish-time record instead.
given().header("Authorization", AUTH)
.get("/v1/package/version/readme?domain=" + DOMAIN + "&repository=other-repo&format=npm&package="
+ packageName + "&version=1.0.0")
.then().statusCode(200).body("readme", equalTo("# Copy Me Readme"));
}
/**
* The real-world bug this would otherwise hit: Verdaccio rejects a plain republish of an
* already-published version outright (a real {@code 409}, confirmed live), even after its
* packument entry alone is removed, since the tarball file itself is still on disk. Confirms
* the bridge's delete-then-republish sequence (packument entry, then the tarball file, both
* confirmed live) actually clears the way for the new content.
*/
@Test
@Order(18)
void copyPackageVersionsOverwritesAnExistingNpmVersionWithDifferentContentAtTheRealSidecar() {
String packageName = "copyover-npm-pkg";
byte[] oldTarball = "old-overwrite-npm-tarball".getBytes(StandardCharsets.UTF_8);
byte[] newTarball = "new-overwrite-npm-tarball".getBytes(StandardCharsets.UTF_8);
String oldEnvelope = "{\"name\":\"" + packageName + "\",\"versions\":{\"1.0.0\":{\"name\":\"" + packageName
+ "\",\"version\":\"1.0.0\",\"dist\":{\"tarball\":\"http://ignored/" + packageName
+ "-1.0.0.tgz\"}}},\"_attachments\":{\"" + packageName + "-1.0.0.tgz\":{\"content_type\":"
+ "\"application/octet-stream\",\"data\":\"" + Base64.getEncoder().encodeToString(oldTarball)
+ "\",\"length\":" + oldTarball.length + "}}}";
String newEnvelope = oldEnvelope.replace(
Base64.getEncoder().encodeToString(oldTarball), Base64.getEncoder().encodeToString(newTarball))
.replace(String.valueOf(oldTarball.length), String.valueOf(newTarball.length));
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(oldEnvelope)
.put("/codeartifact/npm/" + DOMAIN + "/other-repo/" + packageName)
.then().statusCode(anyOf201Or200());
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(newEnvelope)
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"],\"allowOverwrite\":true}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=npm&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/other-repo/" + packageName + "/-/" + packageName
+ "-1.0.0.tgz")
.then().statusCode(200)
.extract().asByteArray();
assertEquals("new-overwrite-npm-tarball", new String(copied, StandardCharsets.UTF_8));
}
/**
* The real-world bug this would otherwise hit: the bridge used to build the copied version's
* packument entry from scratch (just {@code name}/{@code version}/{@code dist}), dropping
* {@code dependencies} and anything else the source's own version document carried. A real
* {@code npm install} against the copied destination would resolve zero dependencies for this
* version instead of what the project actually declares.
*/
@Test
@Order(19)
void copyPackageVersionsPreservesTheSourceVersionsDependenciesAtTheRealSidecar() throws IOException {
String packageName = "copydeps-npm-pkg";
byte[] tarball = "copy-deps-npm-tarball-bytes".getBytes(StandardCharsets.UTF_8);
String envelope = "{\"name\":\"" + packageName + "\",\"versions\":{\"1.0.0\":{\"name\":\"" + packageName
+ "\",\"version\":\"1.0.0\",\"dependencies\":{\"left-pad\":\"^1.3.0\"},\"dist\":{\"tarball\":"
+ "\"http://ignored/" + packageName + "-1.0.0.tgz\"}}},\"_attachments\":{\"" + packageName
+ "-1.0.0.tgz\":{\"content_type\":\"application/octet-stream\",\"data\":\""
+ Base64.getEncoder().encodeToString(tarball) + "\",\"length\":" + tarball.length + "}}}";
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(envelope)
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
.then().statusCode(anyOf201Or200());
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"]}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=npm&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
String metadataBody = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/npm/" + DOMAIN + "/other-repo/" + packageName)
.then().statusCode(200)
.extract().asString();
JsonNode copiedVersion = new ObjectMapper().readTree(metadataBody).path("versions").path("1.0.0");
assertEquals("^1.3.0", copiedVersion.path("dependencies").path("left-pad").asText());
// dist must still point at the copy's own tarball, not the source's.
assertTrue(copiedVersion.path("dist").path("tarball").asText().contains("other-repo"),
"copied dist.tarball must point back at the destination repository, was: "
+ copiedVersion.path("dist").path("tarball").asText());
}
/**
* Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -343,6 +344,85 @@ class CodeArtifactNuGetDockerIntegrationTest {
.then().statusCode(201);
}
/**
* The real-world gap this closes: {@code CopyPackageVersions} used to support only generic
* and maven; nuget keeps its pushed packages straight on BaGetter's own flat storage rather
* than a {@code packageVersions} record. Confirms the bridge reads the {@code .nupkg} from
* the real sidecar (not a mock) and republishes it to the destination repository's own
* BaGetter instance, byte for byte. {@code other-nuget-repo} is the empty repository {@link
* #repositoriesAreIsolatedFromEachOther} already created.
*/
@Test
@Order(13)
void copyPackageVersionsBridgesToTheRealBagetterSidecar() {
String packageId = "CopyMe.Package";
byte[] nupkg = buildNupkg(packageId, VERSION, "copy-me nuget package", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nupkg))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"" + VERSION + "\"]}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-nuget-repo&format=nuget&package=" + packageId)
.then().statusCode(200)
.body("successfulVersions.'" + VERSION + "'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/other-nuget-repo/v3/package/"
+ packageId.toLowerCase(Locale.ROOT) + "/" + VERSION + "/"
+ packageId.toLowerCase(Locale.ROOT) + "." + VERSION + ".nupkg")
.then().statusCode(200)
.extract().asByteArray();
assertArrayEquals(nupkg, copied);
}
/**
* The real-world bug this would otherwise hit: BaGetter rejects a plain re-push of an
* already-pushed id/version outright (a real {@code 409}, confirmed live and already proven
* by {@code repushingTheSameCoordinatesWithDifferentContentIsRejectedAndTheOriginalSurvives}
* for the native push path), even for an id/version whose packument entry alone was removed,
* since BaGetter's storage is content-addressed by id/version. Confirms the bridge's own
* delete-then-republish ({@code DELETE /api/v2/package/<id>/<version>}, then push, both
* confirmed live) actually clears the way for different content.
*/
@Test
@Order(14)
void copyPackageVersionsOverwritesAnExistingNuGetVersionWithDifferentContentAtTheRealSidecar() {
String packageId = "CopyOver.Package";
String lowerId = packageId.toLowerCase(Locale.ROOT);
byte[] oldNupkg = buildNupkg(packageId, VERSION, "old overwrite content", null, null);
byte[] newNupkg = buildNupkg(packageId, VERSION, "new overwrite content", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", oldNupkg))
.put("/codeartifact/nuget/" + DOMAIN + "/other-nuget-repo/api/v2/package")
.then().statusCode(201);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", newNupkg))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"" + VERSION + "\"],\"allowOverwrite\":true}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-nuget-repo&format=nuget&package=" + packageId)
.then().statusCode(200)
.body("successfulVersions.'" + VERSION + "'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/other-nuget-repo/v3/package/" + lowerId + "/" + VERSION
+ "/" + lowerId + "." + VERSION + ".nupkg")
.then().statusCode(200)
.extract().asByteArray();
assertArrayEquals(newNupkg, copied);
}
private static long describeDomainAssetSizeBytes() {
return given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
@@ -470,6 +470,151 @@ class CodeArtifactPypiDockerIntegrationTest {
.body("version", equalTo("1.0.0"));
}
/**
* The real-world gap this closes: {@code CopyPackageVersions} used to support only generic
* and maven; pypi keeps its uploaded files straight on pypiserver's own flat storage rather
* than a {@code packageVersions} record. Confirms the bridge reads the file from the real
* sidecar (not a mock) and republishes it to the destination repository's own pypiserver
* instance, byte for byte. {@code other-repo} is the empty repository {@link
* #repositoriesAreIsolatedFromEachOther} already created.
*/
@Test
@Order(15)
void copyPackageVersionsBridgesToTheRealPypiserverSidecar() {
String packageName = "copyme-pypi-pkg";
String filename = "copyme_pypi_pkg-1.0.0.tar.gz";
byte[] content = "copy-me-pypi-sdist-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, filename, content, "Copy me description"))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"]}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=pypi&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/other-repo/packages/" + filename)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("copy-me-pypi-sdist-bytes", new String(copied, StandardCharsets.UTF_8));
// The real-world gap this proves closed: pypiserver parses only a distribution's
// filename, never its embedded description (see GetPackageVersionReadme's own javadoc),
// so this bridge has no way to read it from the destination sidecar after copying the
// file; it must be propagated from this service's own captured-at-upload-time record.
given().header("Authorization", AUTH)
.get("/v1/package/version/readme?domain=" + DOMAIN + "&repository=other-repo&format=pypi&package="
+ packageName + "&version=1.0.0")
.then().statusCode(200).body("readme", equalTo("Copy me description"));
}
/**
* The real-world bug this would otherwise hit: pypiserver rejects a plain republish of an
* already-uploaded filename with a real {@code 409} (confirmed live, this container is
* started without pypiserver's own {@code --overwrite} flag, same as production), even though
* {@code reuploadingTheSameFileIsRejectedAndTheOriginalContentSurvives} already proves that
* for the native upload path; this confirms the bridge's own delete-then-republish ({@code
* remove_pkg}, then re-upload, both confirmed live) actually clears the way.
*/
@Test
@Order(16)
void copyPackageVersionsOverwritesAnExistingPypiFileWithDifferentContentAtTheRealSidecar() {
String packageName = "copyover-pypi-pkg";
String filename = "copyover_pypi_pkg-1.0.0.tar.gz";
byte[] oldContent = "old-overwrite-pypi-sdist".getBytes(StandardCharsets.UTF_8);
byte[] newContent = "new-overwrite-pypi-sdist".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, filename, oldContent))
.post("/codeartifact/pypi/" + DOMAIN + "/other-repo/")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, filename, newContent))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"],\"allowOverwrite\":true}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=pypi&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copied = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/other-repo/packages/" + filename)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("new-overwrite-pypi-sdist", new String(copied, StandardCharsets.UTF_8));
}
/**
* The real-world bug this would otherwise hit: pypiserver's own {@code remove_pkg} management
* call (confirmed live) deletes every file sharing a release's exact name and version, not just
* the one filename it was asked to delete, so a copy that deletes-then-rewrites one asset at a
* time mid-loop would wipe a sibling asset of the same release already rewritten earlier in
* that same loop — losing it even though the copy as a whole reported success. A real pypi
* release commonly carries both an sdist and a wheel for the exact same version, so this is not
* a contrived edge case.
*/
@Test
@Order(17)
void copyPackageVersionsOverwriteKeepsEveryAssetWhenAPypiReleaseHasBothAnSdistAndAWheel() {
String packageName = "copyover-multi-pypi-pkg";
String sdistFilename = "copyover_multi_pypi_pkg-1.0.0.tar.gz";
String wheelFilename = "copyover_multi_pypi_pkg-1.0.0-py3-none-any.whl";
byte[] oldSdist = "old-multi-pypi-sdist".getBytes(StandardCharsets.UTF_8);
byte[] newSdist = "new-multi-pypi-sdist".getBytes(StandardCharsets.UTF_8);
byte[] newWheel = "new-multi-pypi-wheel".getBytes(StandardCharsets.UTF_8);
// The destination already holds this version (just the sdist, enough to make this a real
// overwrite rather than a fresh publish) so the copy below has to delete-and-replace it.
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, sdistFilename, oldSdist))
.post("/codeartifact/pypi/" + DOMAIN + "/other-repo/")
.then().statusCode(200);
// The source carries both files for this same release, exactly as a real `twine upload
// dist/*` would have left it.
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, sdistFilename, newSdist))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(twineUploadBody("boundary123", packageName, wheelFilename, newWheel))
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"versions\":[\"1.0.0\"],\"allowOverwrite\":true}")
.post("/v1/package/versions/copy?domain=" + DOMAIN + "&source-repository=" + REPO
+ "&destination-repository=other-repo&format=pypi&package=" + packageName)
.then().statusCode(200)
.body("successfulVersions.'1.0.0'.status", equalTo("Published"))
.body("failedVersions.size()", equalTo(0));
byte[] copiedSdist = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/other-repo/packages/" + sdistFilename)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("new-multi-pypi-sdist", new String(copiedSdist, StandardCharsets.UTF_8));
byte[] copiedWheel = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/pypi/" + DOMAIN + "/other-repo/packages/" + wheelFilename)
.then().statusCode(200)
.extract().asByteArray();
assertEquals("new-multi-pypi-wheel", new String(copiedWheel, StandardCharsets.UTF_8));
}
/**
* Proves the actual mechanism, not just that {@code PypiserverSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactReposi
import io.github.hectorvent.floci.services.codeartifact.model.PackageOriginConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -41,6 +42,7 @@ 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.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -1429,8 +1431,8 @@ class CodeArtifactServiceTest {
assertEquals("my-artifact", pv.getPackageName());
assertEquals("1.0.0", pv.getVersion());
assertEquals("Published", pv.getStatus());
assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
pv.getRevision());
assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8))
.substring(0, 50), pv.getRevision());
}
@Test
@@ -2174,16 +2176,462 @@ class CodeArtifactServiceTest {
}
@Test
void copyPackageVersionsRejectsANonGenericFormat() {
void copyPackageVersionsRejectsAFormatThatIsNeitherGenericNorContainerBacked() {
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());
AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "npm", null, "my-pkg", List.of("1.0.0"), null, false, false));
"src", "dst", "swift", null, "my-pkg", List.of("1.0.0"), null, false, false));
assertEquals("ValidationException", e.getErrorCode());
}
/**
* npm, pypi, and nuget are now bridged the same as maven (each sidecar's own real wire
* protocol, confirmed against a live container in the respective {@code
* CodeArtifact*DockerIntegrationTest} class); the shared orchestration this test file already
* exercises thoroughly against the maven mock (NOT_FOUND, MISMATCHED_REVISION, the
* identical-content no-op, ALREADY_EXISTS, overwrite, rollback, byte accounting) is format-
* agnostic, so it is not re-duplicated here per format. This just confirms the format gate
* itself routes a container-backed format to the bridge rather than rejecting it outright.
*/
@Test
void copyPackageVersionsRoutesEveryContainerBackedFormatToTheSidecarBridge() {
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());
for (String format : List.of("npm", "pypi", "nuget")) {
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", format, null, "my-pkg", List.of("1.0.0"), null, false, false);
assertEquals("NOT_FOUND", result.failedVersions().get("1.0.0").errorCode());
}
}
/**
* The real-world gap this closes: {@code GetPackageVersionReadme} answers npm and pypi only
* from a record captured at publish time (see its own javadoc for why neither sidecar can
* answer for a specific version after the fact), which this bridge's own asset copy has no
* other way to reach. Without propagating it, a copied npm version's assets would land
* correctly while {@code GetPackageVersionReadme} 404s on it at the destination, even though
* the source genuinely has one.
*/
@Test
void copyPackageVersionsPropagatesTheSourceVersionsCapturedReadmeForNpm() {
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("npm");
String dstRepoId = dst.getSidecarContainerIds().get("npm");
byte[] tarball = "tarball-bytes".getBytes(StandardCharsets.UTF_8);
when(verdaccioClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
when(verdaccioClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(false);
when(verdaccioClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
when(verdaccioClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenReturn(Optional.of(tarball));
recordReadme("dom", "src", "npm", null, "my-pkg", "1.0.0", "# Real Readme");
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "npm", null, "my-pkg", List.of("1.0.0"),
null, false, false);
CodeArtifactService.PackageVersionReadmeResult readme = service.getPackageVersionReadme(REGION, "dom",
null, "dst", "npm", null, "my-pkg", "1.0.0");
assertEquals("# Real Readme", readme.readme());
}
/** Same propagation as npm's own, confirmed separately since pypi captures readmes independently. */
@Test
void copyPackageVersionsPropagatesTheSourceVersionsCapturedReadmeForPypi() {
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("pypi");
String dstRepoId = dst.getSidecarContainerIds().get("pypi");
byte[] sdist = "sdist-bytes".getBytes(StandardCharsets.UTF_8);
when(pypiserverClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
when(pypiserverClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(false);
when(pypiserverClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), isNull(),
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my_pkg-1.0.0.tar.gz"));
when(pypiserverClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my_pkg-1.0.0.tar.gz"))).thenReturn(Optional.of(sdist));
recordReadme("dom", "src", "pypi", null, "my-pkg", "1.0.0", "A pypi description");
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "pypi", null, "my-pkg", List.of("1.0.0"),
null, false, false);
CodeArtifactService.PackageVersionReadmeResult readme = service.getPackageVersionReadme(REGION, "dom",
null, "dst", "pypi", null, "my-pkg", "1.0.0");
assertEquals("A pypi description", readme.readme());
}
@Test
void copyPackageVersionsBridgesToReposiliteForMavenCopyingEveryListedAsset() {
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[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] pomBytes = "pom-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(false);
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"));
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(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
assertTrue(result.failedVersions().isEmpty());
assertEquals("Published", result.successfulVersions().get("1.0").status());
assertFalse(result.successfulVersions().get("1.0").revision().isBlank());
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(jarBytes));
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"), eq(pomBytes));
verify(reposiliteClient, never()).deletePackageVersionAsset(any(), any(), any(), any(), any(), any(),
any());
}
@Test
void copyPackageVersionsFailsNotFoundForAMavenVersionMissingFromTheSource() {
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());
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
assertEquals("NOT_FOUND", result.failedVersions().get("1.0").errorCode());
assertTrue(result.successfulVersions().isEmpty());
}
@Test
void copyPackageVersionsSkipsAMavenVersionThatWouldHaveSucceededWhenASiblingIsNotFound() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
String srcRepoId = src.getSidecarContainerIds().get("maven");
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("2.0"))).thenReturn(false);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0", "2.0"), null, false, false);
assertTrue(result.successfulVersions().isEmpty());
assertEquals("SKIPPED", result.failedVersions().get("1.0").errorCode());
assertEquals("NOT_FOUND", result.failedVersions().get("2.0").errorCode());
verify(reposiliteClient, never()).copyPackageVersionAsset(any(), any(), any(), any(), any(), any(), any(),
any(), any(), any());
}
@Test
void copyPackageVersionsTreatsAByteIdenticalMavenVersionAsANoOpNotListedEitherWay() {
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[] jarBytes = "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(jarBytes));
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(jarBytes.clone()));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
assertTrue(result.successfulVersions().isEmpty());
assertTrue(result.failedVersions().isEmpty());
verify(reposiliteClient, never()).copyPackageVersionAsset(any(), any(), any(), any(), any(), any(), any(),
any(), any(), any());
}
@Test
void copyPackageVersionsFailsAlreadyExistsForADifferentMavenVersionWithoutAllowOverwrite() {
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.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("source-bytes".getBytes(StandardCharsets.UTF_8)));
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("different-bytes".getBytes(StandardCharsets.UTF_8)));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
assertEquals("ALREADY_EXISTS", result.failedVersions().get("1.0").errorCode());
}
@Test
void copyPackageVersionsOverwritesADifferentMavenVersionAndRemovesAStaleAssetWhenAllowOverwriteIsTrue() {
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[] newJarBytes = "new-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", "stale-readme.txt"));
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(newJarBytes));
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("old-jar-bytes".getBytes(StandardCharsets.UTF_8)));
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());
// a-1.0.jar already exists at the destination with different content: Reposilite's own
// redeployment:false setting would reject a plain PUT over it (confirmed against a live
// container), so the old one must be deleted immediately before the new one is stored,
// never written straight over the existing path.
InOrder order = inOrder(reposiliteClient);
order.verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
order.verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(newJarBytes));
verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("stale-readme.txt"));
}
/**
* A later asset in the same version failing to write must not leave an earlier, otherwise
* successful asset of that same version sitting in a brand-new, half-copied state at the
* destination: the jar never existed there before this call, so the best-effort rollback
* deletes it outright rather than attempting to restore nonexistent prior content. The
* original {@code IllegalStateException} from the sidecar propagates unchanged, not masked
* by a rollback-time error.
*/
@Test
void copyPackageVersionsForMavenRollsBackANewlyWrittenAssetWhenALaterAssetInTheSameVersionFailsToWrite() {
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[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] pomBytes = "pom-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(false);
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"));
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(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
doThrow(new IllegalStateException("sidecar unreachable")).when(reposiliteClient).copyPackageVersionAsset(
eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId), eq("dst"), eq("com.example"), eq("a"), eq("1.0"),
eq("a-1.0.pom"), eq(pomBytes));
assertThrows(IllegalStateException.class, () -> service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false));
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(jarBytes));
verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"));
}
/**
* An overwritten asset that already existed at the destination must come back as it was, not
* get deleted outright, when a later asset in the same version fails: rollback distinguishes
* "newly created, so delete it" from "previously existed, so restore it" per asset.
*/
@Test
void copyPackageVersionsForMavenRestoresAnOverwrittenAssetsOriginalContentWhenALaterAssetFailsToWrite() {
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[] newJarBytes = "new-jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] oldJarBytes = "old-jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] newPomBytes = "new-pom-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", "a-1.0.pom"));
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(newJarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(newPomBytes));
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(oldJarBytes));
doThrow(new IllegalStateException("sidecar unreachable")).when(reposiliteClient).copyPackageVersionAsset(
eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId), eq("dst"), eq("com.example"), eq("a"), eq("1.0"),
eq("a-1.0.pom"), eq(newPomBytes));
assertThrows(IllegalStateException.class, () -> service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false));
verify(reposiliteClient).storePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(oldJarBytes));
}
@Test
void copyPackageVersionsForMavenRecordsTheNewVersionInTheDestinationsArtifactMetadata() {
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[] jarBytes = "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(false);
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.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "maven", "com.example", "a",
List.of("1.0"), null, false, false);
verify(reposiliteClient).recordVersionAvailable(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"));
}
@Test
void copyPackageVersionsForMavenIncreasesDescribeDomainsAssetSizeBytesByWhatWasCopied() {
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[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8);
byte[] pomBytes = "pom-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(false);
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"));
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(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
long before = service.describeDomain(REGION, "dom", null).assetSizeBytes();
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "maven", "com.example", "a",
List.of("1.0"), null, false, false);
long after = service.describeDomain(REGION, "dom", null).assetSizeBytes();
assertEquals(before + jarBytes.length + pomBytes.length, after);
}
@Test
void copyPackageVersionsFailsMismatchedRevisionForMavenWhenTheVersionRevisionsEntryDoesNotMatch() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
String srcRepoId = src.getSidecarContainerIds().get("maven");
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", null, Map.of("1.0", "wrong-revision"), false, false);
assertEquals("MISMATCHED_REVISION", result.failedVersions().get("1.0").errorCode());
}
@Test
void copyPackageVersionsFailsMismatchedRevisionForMavenOnAShapeValidButWrongValue() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of());
service.createRepository(REGION, "dom", null, "dst", null, null, Map.of());
String srcRepoId = src.getSidecarContainerIds().get("maven");
when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(true);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", null, Map.of("1.0", "a-shape-valid-revision"), false,
false);
assertEquals("MISMATCHED_REVISION", result.failedVersions().get("1.0").errorCode());
}
/**
* {@link CodeArtifactService#synthesizeContainerBackedRevision} is truncated to 50 hex
* characters specifically so a revision a caller obtained from {@code DescribePackageVersion}
* can be handed straight back into {@code versionRevisions} and actually match: confirms a
* real round trip through both APIs, not just that the two happen to be the same length.
*/
@Test
void copyPackageVersionsSucceedsForMavenWhenTheVersionRevisionsEntryIsTheOneDescribePackageVersionReturned() {
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[] jarBytes = "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(false);
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.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
String describedRevision = service.describePackageVersion(REGION, "dom", null, "src", "maven",
"com.example", "a", "1.0").getRevision();
assertTrue(describedRevision.length() <= 50);
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", null, Map.of("1.0", describedRevision), false, false);
assertTrue(result.failedVersions().isEmpty());
assertEquals("Published", result.successfulVersions().get("1.0").status());
}
@Test
void copyPackageVersionsFailsNotFoundForAVersionMissingFromTheSourceRepository() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -2536,8 +2984,8 @@ class CodeArtifactServiceTest {
"com.example", "my-artifact", "1.0.0", "my-artifact-1.0.0.jar", null);
assertEquals("jar bytes", new String(result.asset().getContent(), StandardCharsets.UTF_8));
assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
result.packageVersionRevision());
assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8))
.substring(0, 50), result.packageVersionRevision());
}
@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.XmlParser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -27,6 +28,7 @@ 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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -605,6 +607,165 @@ class ReposiliteSidecarClientTest {
"com.example", "weird"));
}
@Test
void listPackageVersionAssetNamesReturnsOnlyTheFileEntriesFromTheVersionDirectory() {
server.createContext("/api/maven/details/dom--repo/com/example/a/1.0",
exchange -> respond(exchange, 200, "{\"name\":\"1.0\",\"type\":\"DIRECTORY\",\"files\":["
+ "{\"name\":\"a-1.0.jar\",\"type\":\"FILE\"},"
+ "{\"name\":\"a-1.0.pom\",\"type\":\"FILE\"}]}"));
List<String> names = client.listPackageVersionAssetNames("dom--repo", "dom", "repo", "com.example", "a",
"1.0");
assertThat(names, equalTo(List.of("a-1.0.jar", "a-1.0.pom")));
}
@Test
void listPackageVersionAssetNamesIsEmptyForAMissingVersion() {
server.createContext("/api/maven/details/dom--repo/com/example/a/9.9",
exchange -> respond(exchange, 404, "{\"status\":404,\"message\":\"File not found\"}"));
assertThat(client.listPackageVersionAssetNames("dom--repo", "dom", "repo", "com.example", "a", "9.9"),
equalTo(List.of()));
}
@Test
void listPackageVersionAssetNamesThrowsOnAnUnexpectedStatus() {
server.createContext("/api/maven/details/dom--repo/com/example/a/1.0",
exchange -> respond(exchange, 500, "{\"status\":500,\"message\":\"internal error\"}"));
assertThrows(IllegalStateException.class,
() -> client.listPackageVersionAssetNames("dom--repo", "dom", "repo", "com.example", "a", "1.0"));
}
@Test
void storePackageVersionAssetPutsTheBytesDirectlyEvenWhenDifferingContentAlreadyExists() throws Exception {
// deployArtifact's own redeployment:false preflight would refuse this; storePackageVersionAsset
// never GETs first and must PUT unconditionally, the way CopyPackageVersions' own
// delete-then-store overwrite sequence relies on.
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
List<String> methodsSeen = new CopyOnWriteArrayList<>();
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
methodsSeen.add(exchange.getRequestMethod());
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
client.storePackageVersionAsset("dom--repo", "dom", "repo", "com.example", "a", "1.0", "a-1.0.jar",
"hello".getBytes(StandardCharsets.UTF_8));
assertThat(methodsSeen, equalTo(List.of("PUT")));
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), putBody.get());
}
@Test
void storePackageVersionAssetThrowsOnAnUnexpectedStatus() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> respond(exchange, 500, ""));
assertThrows(IllegalStateException.class, () -> client.storePackageVersionAsset("dom--repo", "dom", "repo",
"com.example", "a", "1.0", "a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8)));
}
@Test
void deletePackageVersionAssetDeletesTheExactGavPath() {
AtomicReference<String> deletedMethod = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
deletedMethod.set(exchange.getRequestMethod());
respond(exchange, 200, "");
});
client.deletePackageVersionAsset("dom--repo", "dom", "repo", "com.example", "a", "1.0", "a-1.0.jar");
assertThat(deletedMethod.get(), equalTo("DELETE"));
}
@Test
void deletePackageVersionAssetThrowsOnAnUnexpectedStatus() {
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> respond(exchange, 500, ""));
assertThrows(IllegalStateException.class, () -> client.deletePackageVersionAsset("dom--repo", "dom", "repo",
"com.example", "a", "1.0", "a-1.0.jar"));
}
@Test
void recordVersionAvailableCreatesANewMetadataFileWhenNoneExists() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 404, "");
} else {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
}
});
client.recordVersionAvailable("dom--repo", "dom", "repo", "com.example", "a", "1.0");
String xml = new String(putBody.get(), StandardCharsets.UTF_8);
assertEquals("com.example", XmlParser.extractFirst(xml, "groupId", null));
assertEquals("a", XmlParser.extractFirst(xml, "artifactId", null));
assertEquals("1.0", XmlParser.extractFirst(xml, "latest", null));
assertEquals("1.0", XmlParser.extractFirst(xml, "release", null));
assertEquals(List.of("1.0"), XmlParser.extractAll(xml, "version"));
assertTrue(XmlParser.extractFirst(xml, "lastUpdated", "").matches("\\d{14}"));
}
@Test
void recordVersionAvailableAppendsToExistingVersionsAndAdvancesReleaseForANonSnapshot() {
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>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
}
});
client.recordVersionAvailable("dom--repo", "dom", "repo", "com.example", "a", "2.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));
}
@Test
void recordVersionAvailableLeavesTheExistingReleaseUntouchedForASnapshotVersion() {
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>1.0</latest><release>1.0</release><versions><version>1.0</version></versions>"
+ "<lastUpdated>20260101000000</lastUpdated></versioning></metadata>";
AtomicReference<byte[]> putBody = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> {
if ("GET".equals(exchange.getRequestMethod())) {
respond(exchange, 200, existing);
} else {
putBody.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
}
});
client.recordVersionAvailable("dom--repo", "dom", "repo", "com.example", "a", "2.0-SNAPSHOT");
String xml = new String(putBody.get(), StandardCharsets.UTF_8);
assertEquals(List.of("1.0", "2.0-SNAPSHOT"), XmlParser.extractAll(xml, "version"));
assertEquals("2.0-SNAPSHOT", XmlParser.extractFirst(xml, "latest", null));
assertEquals("1.0", XmlParser.extractFirst(xml, "release", null));
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);