feat(codeartifact): retain Maven packages from a public external connection (#6889)

GetAuthorizationToken-authenticated Maven GET/HEAD requests now retain a
missing release version from the repository's own public:maven-* external
connection (Maven Central, Clojars, CommonsWare, Google Android, Gradle
Plugins), the way real CodeArtifact does, instead of always 404ing.

Follows AWS's own documented rules: release versions only (SNAPSHOT is
never imported through an external connection); the standard
pom/jar/-javadoc.jar/-sources.jar set imported together on a standard
request, a non-standard asset name imported individually and only on
demand; a retained version's own origin checked against any later asset
request for it, rejecting one from a different connection; package-level
upstream:BLOCK respected; and a direct mvn deploy of a version already
present in the connection rejected (ConflictException), matching AWS's
documented publish-side behavior.

Retained bytes are counted toward DescribeDomain's assetSizeBytes the
same way a direct deploy already is, gated on the real deploy outcome
rather than merely having fetched the bytes, and never double-counted on
an idempotent-match retry.

Verified against the real, live Maven Central in a Docker-gated
integration test (junit 4.13.2), and manually with a real mvn client
through a wildcard mirror.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 18:04:57 -05:00
1 parent 743bede481
commit a03e88b451
11 files changed
+2471 -46

No files matched your search

@@ -0,0 +1,154 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Retains a real Maven package version from the real, live {@code public:maven-central}
* repository (not a local fake), through the native per-format route, the way a real {@code mvn}/
* Gradle build would. junit 4.13.2 is picked because AWS's own User Guide uses it as its worked
* example and it's small, stable, and unlikely to ever be pulled from Maven Central. A genuine
* network dependency, unlike every other sidecar-backed test here, which only ever talks to a
* container Floci itself started; see {@code CodeArtifactMavenExternalConnectionImporterTest}
* for the mocked, deterministic coverage of the asset-selection and mixed-origin logic this test
* does not re-exercise.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactMavenExternalConnectionDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "maven-external-connection-domain";
private static final String REPO = "maven-external-connection-repo";
private static final String BLOCKED_REPO = "maven-external-connection-blocked-repo";
private static final String JUNIT_JAR = "junit/junit/4.13.2/junit-4.13.2.jar";
private static final String JUNIT_POM = "junit/junit/4.13.2/junit-4.13.2.pom";
private static String bearerToken;
@BeforeAll
static void setUp() {
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.maven-image");
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void createDomainRepositoriesConnectionAndToken() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
+ "&external-connection=public:maven-central")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
+ "&external-connection=public:maven-central")
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
@Test
@Order(1)
void fetchingAMissingJarRetainsItFromTheRealMavenCentralConnectionAndCountsItsBytes() {
long assetSizeBytesBefore = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(0L, assetSizeBytesBefore);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + JUNIT_JAR)
.then().statusCode(200)
.extract().asByteArray();
// A real jar is a real zip: "PK" magic bytes, not asserting exact content since the real
// artifact is out of this test's control.
assertEquals('P', (char) fetched[0]);
assertEquals('K', (char) fetched[1]);
assertThat(fetched.length, greaterThan(1000));
// Proves the retained bytes are actually counted toward DescribeDomain's assetSizeBytes,
// the same way a direct mvn deploy already is: at least the jar's own length, since the
// standard-asset import also retains the pom (and possibly javadoc/sources) alongside it.
long assetSizeBytesAfter = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertThat(assetSizeBytesAfter, greaterThan((long) fetched.length));
}
@Test
@Order(2)
void theStandardPomSiblingWasRetainedInTheSameAttemptNotJustTheRequestedJar() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.delete("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
+ "&external-connection=public:maven-central")
.then().statusCode(200);
// With the external connection now gone, a fresh retention attempt is impossible: this can
// only succeed because the standard-asset import on order(1)'s own jar request already
// retained the pom alongside it.
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + JUNIT_POM)
.then().statusCode(200);
}
@Test
@Order(3)
void republishingAVersionAlreadyPresentInTheExternalConnectionIsRejected() {
given().header("Authorization", "Bearer " + bearerToken)
.body("not-the-real-bytes".getBytes(StandardCharsets.UTF_8))
.put("/codeartifact/maven/" + DOMAIN + "/" + BLOCKED_REPO + "/" + JUNIT_JAR)
.then().statusCode(409);
}
@Test
@Order(4)
void upstreamBlockPreventsRetentionEvenThoughTheRealArtifactExists() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"ALLOW\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=maven"
+ "&namespace=junit&package=junit")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + BLOCKED_REPO + "/" + JUNIT_JAR)
.then().statusCode(404);
}
@Test
@Order(5)
void aSnapshotVersionIsNeverRetainedFromAnExternalConnection() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO
+ "/com/example/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar")
.then().statusCode(404);
}
}
@@ -0,0 +1,396 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository;
import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link CodeArtifactMavenExternalConnectionImporter}'s own decision logic: when it attempts a
* real external-connection fetch at all, which asset names it tries, and what it writes back.
* {@link ReposiliteSidecarClient} and {@link MavenExternalConnectionClient} are both mocked, so
* no real network or Reposilite call ever happens here; their own wire contracts have their own
* tests.
*/
class CodeArtifactMavenExternalConnectionImporterTest {
private static final String REGION = "us-east-1";
private static final String DOMAIN = "dom";
private static final String OWNER = "123456789012";
private static final String REPOSITORY = "repo";
private static final String REPO_ID = "repo-id";
private CodeArtifactService service;
private ReposiliteSidecarClient reposilite;
private MavenExternalConnectionClient externalConnectionClient;
private CodeArtifactMavenExternalConnectionImporter importer;
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
private static final long EPISODE_ID = 7L;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
reposilite = mock(ReposiliteSidecarClient.class);
externalConnectionClient = mock(MavenExternalConnectionClient.class);
importer = new CodeArtifactMavenExternalConnectionImporter(service, reposilite, externalConnectionClient);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(
List.of(new ExternalConnection("public:maven-central", "maven", "AVAILABLE")));
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
when(service.mavenRetainedVersionOriginConnection(anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString())).thenReturn(Optional.empty());
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString())).thenReturn(42L);
// Unstubbed by default: the claim succeeds, matching the common case of a first or
// same-connection retry. Tests for a conflicting claim override this per call.
when(service.claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), any(),
anyString(), anyString(), anyString(), anyLong()))
.thenReturn(new CodeArtifactService.MavenClaimOutcome(true, EPISODE_ID));
// Unstubbed by default: a constant snapshot, so a version-fence mismatch only ever
// happens where a test deliberately stubs deployMavenAssetUnderVersionFence to report
// one. The dispose-race test below overrides this per call.
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString())).thenReturn(99L);
// Unstubbed by default: the fence matched and the write landed (201), matching the
// common case. The real deploy/fence check this stands in for is inside
// deployMavenAssetUnderVersionFence itself, a synchronized CodeArtifactService method
// (see its own javadoc for why), so this mock is what every test configures instead.
// Tests for the idempotent-match, conflict, fence-mismatch, and error cases override
// this per call via stubDeploy.
when(service.deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(true,
new ReposiliteSidecarClient.DeployOutcome(201, true)));
}
/**
* Stubs the single candidate named by {@code gav}/{@code content}; every other candidate
* keeps the default stub from {@link #setUp}.
*/
private void stubDeploy(String gav, byte[] content, CodeArtifactService.MavenDeployAttemptResult result) {
when(service.deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq(gav), eq(content))).thenReturn(result);
}
/** Verifies the call for {@code gav}/{@code content} also passed the package fence through. */
private void verifyDeployPassedPackageFence(String gav, byte[] content, long packageFenceSnapshot) {
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), eq(packageFenceSnapshot), anyLong(), eq(reposilite),
eq(REPO_ID), eq(gav), eq(content));
}
@Test
void doesNothingForABareMavenMetadataPath() {
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/maven-metadata.xml");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
}
@Test
void doesNothingForASnapshotVersion() {
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
}
@Test
void doesNothingWhenTheRepositoryHasNoMavenExternalConnection() {
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(new CodeArtifactRepository());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
}
@Test
void doesNothingWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example",
"widget")).thenReturn(true);
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
}
@Test
void doesNothingWhenTheVersionWasAlreadyRetainedFromADifferentConnection() {
// The real service refuses the claim outright when a different connection already holds
// it (see claimMavenRetainedVersionOrigin's own javadoc); the mock stands in for that here.
when(service.claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget",
"1.0", "public:maven-central", 42L))
.thenReturn(new CodeArtifactService.MavenClaimOutcome(false, 0L));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
}
@Test
void aStandardAssetNameImportsAllFourStandardAssetsBestEffort() {
byte[] pomBytes = "pom-content".getBytes();
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertTrue(imported);
// packageFenceSnapshot (42L) is passed through so deployMavenAssetUnderVersionFence can
// record bytes atomically with the write itself; see its own javadoc, and
// CodeArtifactServiceTest for the byte-accounting behavior this stands in for here.
verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.pom", pomBytes, 42L);
verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.jar", jarBytes, 42L);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any());
verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget",
"1.0", "public:maven-central", 42L);
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example",
"widget", 42L);
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, true);
}
/**
* Taking the version-fence snapshot after the claim instead of before it would leave a gap
* where a DisposePackageVersions completing in between would already have bumped the fence by
* the time the snapshot read ran, so that read would capture the post-disposal value as
* though it were the normal starting point, and the later locked write would never notice
* anything was amiss. The snapshot must be taken first, so any disposal landing anywhere after
* it, including during the claim call itself, is guaranteed to bump the fence to a value the
* later check can actually detect as different.
*/
@Test
void takesTheVersionFenceSnapshotBeforeClaimingNotAfter() {
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/1.0/widget-1.0.jar");
InOrder order = inOrder(service);
order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "maven",
"com.example", "widget", "1.0");
order.verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", "public:maven-central", 42L);
}
@Test
void anIdempotentMatchCountsAsImportedButIsNotDoubleCountedInByteAccounting() {
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
// deployArtifact's own idempotent-match short-circuit: status 200, wroteNewContent false,
// because the exact same bytes were already there (e.g. a sibling asset imported it moments
// earlier in a race with another request for the same version).
stubDeploy("com/example/widget/1.0/widget-1.0.jar", jarBytes,
new CodeArtifactService.MavenDeployAttemptResult(true,
new ReposiliteSidecarClient.DeployOutcome(200, false)));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertTrue(imported);
verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget",
"1.0", "public:maven-central", 42L);
// Something was genuinely retained (the idempotent match is still a real asset present
// either way), so the claim is finished as confirmed, not released. Whether the
// idempotent match itself double-counts bytes is deployMavenAssetUnderVersionFence's own
// concern now, covered in CodeArtifactServiceTest.
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, true);
}
@Test
void aRealDeployConflictOnTheRequestedAssetCountsAsNotImported() {
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
stubDeploy("com/example/widget/1.0/widget-1.0.jar", jarBytes,
new CodeArtifactService.MavenDeployAttemptResult(true,
new ReposiliteSidecarClient.DeployOutcome(409, false)));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
// Nothing was actually retained (the only candidate's deploy hit a real conflict), so the
// claim this attempt took is finished as unconfirmed, never left dangling to block a
// later attempt.
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, false);
}
@Test
void aLaterCandidateThatThrowsStillFinalizesWhatAnEarlierCandidateGenuinelyWrote() {
byte[] pomBytes = "pom-content".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
// The POM deploy succeeds, but the JAR deploy (the requested asset) fails inside the
// sidecar call itself, e.g. it going unreachable mid-import: deployMavenAssetUnderVersionFence
// catches that on the real path and reports a matched fence with no outcome, exactly as
// stubbed here.
stubDeploy("com/example/widget/1.0/widget-1.0.jar", "jar".getBytes(),
new CodeArtifactService.MavenDeployAttemptResult(true, null));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
// The requested asset itself never landed, but what the POM candidate genuinely wrote
// before the JAR candidate threw is still finalized, not silently dropped.
assertFalse(imported);
verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.pom", pomBytes, 42L);
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example",
"widget", 42L);
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, true);
}
@Test
void aCandidateFetchThatThrowsIsTreatedLikeAMissingCandidateRatherThanAbortingTheWholeAttempt() {
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenThrow(new IllegalStateException("public repository unreachable"));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertTrue(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0.pom"), any());
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq("com/example/widget/1.0/widget-1.0.jar"), eq("jar".getBytes()));
}
@Test
void aDisposalLandingWhileAFetchIsInFlightStopsEveryLaterWriteForThisAttempt() {
byte[] pomBytes = "pom-content".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
// A DisposePackageVersions landed on this exact version while the first candidate's
// (the pom's) fetch was in flight: deployMavenAssetUnderVersionFence detects the fence
// mismatch itself (inside its own lock) and reports it rather than writing anything, so
// every later candidate, including the requested jar, is never even fetched.
stubDeploy("com/example/widget/1.0/widget-1.0.pom", pomBytes,
new CodeArtifactService.MavenDeployAttemptResult(false, null));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0.jar"), any());
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, false);
}
@Test
void aNonStandardAssetNameOnlyImportsTheExactRequestedAsset() {
String nonStandardGav = "com/example/widget/1.0/widget-1.0-windows.jar";
when(externalConnectionClient.fetchAsset("public:maven-central", nonStandardGav))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("windows-jar".getBytes())));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, nonStandardGav);
assertTrue(imported);
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq(nonStandardGav), eq("windows-jar".getBytes()));
verify(externalConnectionClient, never()).fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0.pom"));
}
@Test
void returnsFalseWhenTheRequestedAssetItselfIsNotFoundEvenIfItWouldHaveBeenAStandardImport() {
when(externalConnectionClient.fetchAsset(anyString(), anyString())).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), anyString(), any());
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, false);
}
@Test
void existsInExternalConnectionChecksTheRealPublicRepositoryForAReleaseVersion() {
// Checks the version's own standard POM, not the literal requested filename: every real
// published Maven version has one, while a non-standard classifier asset may not.
when(externalConnectionClient.exists("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(true);
assertTrue(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY,
"com/example/widget/1.0/widget-1.0.jar"));
}
@Test
void existsInExternalConnectionIsTrueWhenTheVersionIsAlreadyClaimedUnderThisConnectionLocally() {
when(service.mavenRetainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget",
"1.0")).thenReturn(Optional.of("public:maven-central"));
assertTrue(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY,
"com/example/widget/1.0/widget-1.0-windows.jar"));
verify(externalConnectionClient, never()).exists(anyString(), anyString());
}
@Test
void existsInExternalConnectionNeverChecksASnapshotVersion() {
assertFalse(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY,
"com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar"));
verify(externalConnectionClient, never()).exists(anyString(), anyString());
}
}
@@ -1820,6 +1820,527 @@ class CodeArtifactServiceTest {
assertEquals("BLOCK", second.upstreamRestriction());
}
@Test
void isUpstreamRetentionBlockedIsFalseWithNoConfigurationAtAll() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
}
@Test
void isUpstreamRetentionBlockedReflectsAnExplicitUpstreamBlock() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", "ALLOW",
"BLOCK");
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
}
/**
* A standard import writes
* its first asset (making the package's real content exist) well before its own {@code
* finally} block saves {@code upstream: ALLOW} as the package's default, once every candidate
* is done. A concurrent request for a different file or version of that same in-progress
* import must not read that in-between state as a directly-published package and get wrongly
* refused, even though no configuration has been saved for it yet either.
*/
@Test
void isUpstreamRetentionBlockedIsFalseWhileASiblingVersionsImportIsStillInFlight() {
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 first candidate of this same in-progress import already wrote real content, the
// same way packageExistsViaVersionsOrSidecar would see it mid-import.
when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true);
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
// Simulates tryImport's own claim for this version, still in flight (never finished): no
// configuration is saved yet, but real content from this same in-progress import exists.
service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
"public:maven-central", fence);
assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
}
/**
* The other side of the same fix: a package that really was directly published (real content,
* no claim ever taken for any version) must still default to blocked with no configuration
* saved, exactly as {@link #isUpstreamRetentionBlockedReflectsAnExplicitUpstreamBlock}'s own
* sibling test already covers for an explicit block.
*/
@Test
void isUpstreamRetentionBlockedIsStillTrueForADirectlyPublishedPackageWithNoClaimAtAll() {
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.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true);
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
}
@Test
void ensureRetainedPackageOriginDefaultWritesTheIngestedFirstVersionDefault() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget",
fence);
CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo",
"maven", "com.example", "widget");
assertEquals("BLOCK", described.publishRestriction());
assertEquals("ALLOW", described.upstreamRestriction());
}
@Test
void ensureRetainedPackageOriginDefaultNeverOverwritesAnExistingConfiguration() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", "ALLOW",
"BLOCK");
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget",
fence);
CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo",
"maven", "com.example", "widget");
assertEquals("ALLOW", described.publishRestriction());
assertEquals("BLOCK", described.upstreamRestriction());
}
@Test
void ensureRetainedPackageOriginDefaultIsANoOpWhenTheFenceHasMoved() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long currentFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
// A fence snapshot that no longer matches "current" simulates a DeletePackage/
// DeleteRepository that completed after the snapshot was taken, before this call runs.
long staleFence = currentFence + 1;
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget",
staleFence);
AwsException e = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo",
"maven", "com.example", "widget"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
/**
* {@code DeleteRepository} never bumps {@code containerBackedPackageDeletionFence}; it
* removes {@code packageOriginConfigs} entries directly instead, so the fence snapshot taken
* before an import started would still match after the repository was deleted. An import
* finishing in that gap must not write a dangling origin config that outlives the deleted
* repository and resurfaces the moment a repository is recreated under the same name: the
* repository-existence check this method also makes is what actually catches it.
*/
@Test
void ensureRetainedPackageOriginDefaultIsANoOpOnceTheRepositoryIsDeleted() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
service.deleteRepository(REGION, "dom", null, "repo");
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget",
fence);
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo",
"maven", "com.example", "widget"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void claimMavenRetainedVersionOriginIsAtomicPerVersion() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo",
"com.example", "widget", "1.0"));
CodeArtifactService.MavenClaimOutcome first = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"repo", "com.example", "widget", "1.0", "public:maven-central", fence);
assertTrue(first.claimed());
// Same connection claiming again (an idempotent retry, or a concurrent request for the
// same version and source) succeeds too, and shares the same episode.
CodeArtifactService.MavenClaimOutcome second = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"repo", "com.example", "widget", "1.0", "public:maven-central", fence);
assertTrue(second.claimed());
assertEquals(first.episodeId(), second.episodeId());
// A different connection trying to claim the same version loses: the origin never moves.
assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-clojars", fence).claimed());
// Not reported as retained yet: two attempts are still in flight and neither has finished.
assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo",
"com.example", "widget", "1.0"));
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
first.episodeId(), true);
assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "repo", "com.example", "widget", "1.0"));
}
@Test
void claimMavenRetainedVersionOriginFailsWhenTheFenceHasMoved() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long currentFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
// A fence snapshot that no longer matches "current" simulates a DeletePackage/
// DeleteRepository that completed after the snapshot was taken, before this call runs.
long staleFence = currentFence + 1;
assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-central", staleFence).claimed());
assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo",
"com.example", "widget", "1.0"));
}
@Test
void finishMavenRetainedVersionOriginAttemptRemovesAnUnconfirmedClaimOnlyOnceEveryAttemptHasFinished() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
// Two concurrent attempts under the same connection, both still in flight, same episode.
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", fence).episodeId();
service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
"public:maven-central", fence);
// The first attempt finishes having retained nothing; the second is still mid-fetch.
// A plain claim-or-reject check would let this exact finish remove the shared claim
// outright, opening a window for a third
// attempt to claim the version under a newly-swapped connection while the second attempt
// was still relying on the original one.
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
episodeId, false);
assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-clojars", fence).claimed());
// The second attempt finishes, also empty: now nothing is left relying on the claim, and
// nothing was ever confirmed, so it is finally free for a different connection.
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
episodeId, false);
assertTrue(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-clojars", fence).claimed());
}
@Test
void finishMavenRetainedVersionOriginAttemptKeepsAConfirmedClaimEvenOnceEveryAttemptHasFinished() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", fence).episodeId();
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
episodeId, true);
assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "repo", "com.example", "widget", "1.0"));
// A real retention happened under this connection: a different connection can never claim
// this exact version afterward, no matter how long ago every attempt finished.
assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-clojars", fence).claimed());
}
@Test
void finishMavenRetainedVersionOriginAttemptIgnoresAStaleEpisode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
long realEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", fence).episodeId();
// A finish call carrying an episodeId that never matched any claim (made up here to
// stand in for one whose own episode was already torn down and replaced by this one)
// must not disturb the real claim.
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
realEpisodeId + 1000, false);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
realEpisodeId, true);
assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "repo", "com.example", "widget", "1.0"));
}
/**
* Attempt A claims under X and stalls; a sibling under X finishes empty,
* leaving A as the only one still holding the episode; the whole episode is then torn down
* from under A (simulating a DeletePackageVersions wiping the map entry outright, the one
* path that does not go through finishMavenRetainedVersionOriginAttempt's own bookkeeping at
* all); a brand new attempt claims fresh under the exact same connection name X. A's own,
* long-stale finish call, carrying its original episodeId, must never be able to touch that
* brand new episode just because the connection name happens to match.
*/
@Test
void aStaleFinishCanNeverReleaseAReplacementEpisodeClaimedUnderTheSameConnectionName() {
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");
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", fence).episodeId();
// The old episode is torn down entirely, not through a finish call: some real content
// already exists for this package (however it got there), so DeletePackage finds
// something real to delete and, as part of its own ordinary cleanup, wipes the origin map
// entry outright, the same way it already does today, regardless of any in-flight count.
when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true);
service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget");
// A brand new episode is claimed fresh under the exact same connection name.
long freshFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long freshEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", freshFence).episodeId();
assertNotEquals(staleEpisodeId, freshEpisodeId);
// The old attempt's finish call, arriving late and carrying its own stale episodeId, must
// not release the fresh episode, even though both share the same connection name.
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
staleEpisodeId, false);
assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget",
"1.0", "public:maven-clojars", freshFence).claimed());
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
freshEpisodeId, true);
assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "repo", "com.example", "widget", "1.0"));
}
@Test
void deployMavenAssetUnderVersionFenceRecordsBytesAtomicallyWithTheWriteItself() {
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");
byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8);
String gav = "com/example/widget/1.0/widget-1.0.jar";
when(reposiliteClient.deployArtifact(repoId, gav, content))
.thenReturn(new ReposiliteSidecarClient.DeployOutcome(201, true));
long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget", "1.0");
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION,
"dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, episodeId,
reposiliteClient, repoId, gav, content);
assertTrue(result.fenceMatched());
assertEquals(201, result.outcome().status());
// This must be true the instant this call returns, not after some separate later call,
// since byte accounting now happens inside this exact same locked call as the write itself.
assertEquals(content.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
@Test
void deployMavenAssetUnderVersionFenceDoesNotRecordBytesOnAnIdempotentMatch() {
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");
byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8);
String gav = "com/example/widget/1.0/widget-1.0.jar";
when(reposiliteClient.deployArtifact(repoId, gav, content))
.thenReturn(new ReposiliteSidecarClient.DeployOutcome(200, false));
long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget", "1.0");
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
versionFence, packageFence, episodeId, reposiliteClient, repoId, gav, content);
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
@Test
void deployMavenAssetUnderVersionFenceWritesNothingWhenTheVersionFenceHasMoved() {
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");
String gav = "com/example/widget/1.0/widget-1.0.jar";
long currentVersionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget", "1.0");
long staleVersionFence = currentVersionFence + 1;
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION,
"dom", null, "repo", "com.example", "widget", "1.0", staleVersionFence, packageFence, episodeId,
reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
}
/**
* The fence comparison alone only proves nothing changed since the caller's own snapshot, not
* that the version was not already Disposed before that snapshot was ever taken, the one
* case a plain delete and reimport can never produce (a fresh fence value with no override
* at all). A request the controller's own isDownloadable check let through before this exact
* disposal landed, then delayed past it by the real public fetch, takes its own version-fence
* snapshot only after reaching this far, so the snapshot matches perfectly even though the
* version is already Disposed; the fence alone would wrongly let the write through.
*/
@Test
void deployMavenAssetUnderVersionFenceRefusesToWriteIntoAnAlreadyDisposedVersionEvenWhenTheFenceMatches() {
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("widget"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("widget"), eq("1.0"))).thenReturn(List.of());
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "widget",
List.of("1.0"), null, null);
// Taken only after the disposal above, the same way an admitted-but-delayed download's
// own snapshot would be if it reached this far only after disposal already finished.
long versionFenceAfterDisposal = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo",
"maven", "com.example", "widget", "1.0");
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
String gav = "com/example/widget/1.0/widget-1.0.jar";
CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION,
"dom", null, "repo", "com.example", "widget", "1.0", versionFenceAfterDisposal, packageFence,
episodeId, reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
}
/**
* The end-to-end proof for the same fix: before it, a write's byte accounting ran in a
* separate call after the lock this method now holds was already released, so a dispose
* landing in that exact gap could subtract these same bytes (as part of its own ordinary
* accounting) before the separate call added them, leaving the total permanently
* over-counted for an asset that, by then, no longer existed. With the write and the
* accounting now one atomic call, a dispose that runs any time after this one returns always
* sees the bytes it is actually supposed to subtract, so the net total lands at exactly zero.
*/
@Test
void disposingAVersionJustDeployedThroughThisMethodNeverLeavesItsBytesOverCounted() {
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");
byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8);
String gav = "com/example/widget/1.0/widget-1.0.jar";
when(reposiliteClient.deployArtifact(repoId, gav, content))
.thenReturn(new ReposiliteSidecarClient.DeployOutcome(201, true));
long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget", "1.0");
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
versionFence, packageFence, episodeId, reposiliteClient, repoId, gav, content);
assertEquals(content.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
when(reposiliteClient.listPackageVersions(repoId, "dom", "repo", "com.example", "widget")).thenReturn(
List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
when(reposiliteClient.listPackageVersionAssetNames(repoId, "dom", "repo", "com.example", "widget", "1.0"))
.thenReturn(List.of("widget-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(repoId, "dom", "repo", "com.example", "widget", "1.0",
"widget-1.0.jar")).thenReturn(Optional.of(content));
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "widget",
List.of("1.0"), null, null);
verify(reposiliteClient).deletePackageVersionAsset(repoId, "dom", "repo", "com.example", "widget", "1.0",
"widget-1.0.jar");
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
}
/**
* DeletePackage on a package with no real content yet (nothing a stalled import has written
* back) removes the origin claim outright but, having deleted nothing, never bumps the package
* fence. A sibling attempt still mid-fetch under that now-removed claim takes its
* versionFenceSnapshot/packageFenceSnapshot before the delete, so neither fence alone would
* ever catch the delete happening in between; a fresh claim made afterward under a different
* connection must still be shielded from that sibling's own stale write.
*/
@Test
void deployMavenAssetUnderVersionFenceRefusesAStaleEpisodeAfterAnEmptyPackageDeleteAndFreshClaim() {
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");
// An origin configuration (e.g. from an earlier PutPackageOriginConfiguration) is what
// lets deletePackage find this package at all despite no real content ever landing for
// it; without one, deletePackage would 404 outright rather than reaching the empty-content
// path this test is exercising.
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget",
"ALLOW", "ALLOW");
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget");
long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget", "1.0");
// The stalled attempt: claims under the first connection, then takes no further action
// until after the delete and fresh claim below (simulating a fetch still in flight).
long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example",
"widget", "1.0", "public:maven-central", packageFence).episodeId();
// No real content exists for this package yet, so this delete finds nothing to remove and
// never bumps the package fence, even though it does wipe the origin claim above.
when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(false);
service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget");
assertEquals(packageFence, service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "widget"));
// A fresh claim, under a different connection, succeeds because the old claim is gone.
service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0",
"public:maven-clojars", packageFence);
// The stalled attempt's fetch finally returns and tries to write under its own stale
// episode: both fences still match (neither was ever bumped), so only the episode check
// can refuse this write.
String gav = "com/example/widget/1.0/widget-1.0.jar";
CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION,
"dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, staleEpisodeId,
reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
}
/**
* Same coordinate-boundary collision as above, but for published version content rather than
* origin configuration: without escaping, the second publish's bytes would be stored under the
@@ -2318,6 +2839,142 @@ class CodeArtifactServiceTest {
any());
}
/**
* {@code copyContainerBackedPackageVersions} copies a version's real asset bytes without
* copying the source's own Maven retention claim, so without carrying it across separately,
* a copied EXTERNAL version would otherwise report INTERNAL at the destination even though
* its bytes genuinely came from a public connection.
*/
@Test
void copyPackageVersionsCarriesTheSourcesMavenRetentionOriginToTheDestination() {
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));
long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"src", "com.example", "a", "1.0", "public:maven-central", srcPackageFence);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "src", "com.example", "a", "1.0",
srcClaim.episodeId(), true);
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(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "dst", "com.example", "a", "1.0"));
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))));
CodeArtifactService.ListPackageVersionsResult listed = service.listPackageVersions(REGION, "dom", null,
"dst", "maven", "com.example", "a", null, null, null, null, null);
CodeArtifactService.PackageVersionSummary copied = listed.versions().stream()
.filter(v -> "1.0".equals(v.version())).findFirst().orElseThrow();
assertEquals("EXTERNAL", copied.originType());
assertEquals("public:maven-central", copied.externalConnectionName());
}
/**
* Overwriting a destination version already retained under one connection with a source
* retained under a different one must not leave the old connection recorded: the real bytes
* just became the source's, so the destination's origin has to follow them, not stay pointing
* at content that is no longer actually there.
*/
@Test
void copyPackageVersionsOverwritingADifferentlyRetainedDestinationReplacesItsOriginRatherThanLeavingItStale() {
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"));
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)));
long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"src", "com.example", "a", "1.0", "public:maven-clojars", srcPackageFence);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "src", "com.example", "a", "1.0",
srcClaim.episodeId(), true);
long dstPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "dst", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome dstClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"dst", "com.example", "a", "1.0", "public:maven-central", dstPackageFence);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0",
dstClaim.episodeId(), true);
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(Optional.of("public:maven-clojars"), service.mavenRetainedVersionOriginConnection(REGION, "dom",
null, "dst", "com.example", "a", "1.0"));
}
/**
* Overwriting a destination version retained under a connection with a source that was never
* retained from anywhere (a plain direct publish) must clear the destination's stale claim,
* not leave it reporting a connection whose bytes were just replaced by a direct publish.
*/
@Test
void copyPackageVersionsOverwritingARetainedDestinationWithADirectlyPublishedSourceClearsItsOrigin() {
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"));
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)));
long dstPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "dst", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome dstClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"dst", "com.example", "a", "1.0", "public:maven-central", dstPackageFence);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0",
dstClaim.episodeId(), true);
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(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "dst",
"com.example", "a", "1.0"));
}
/**
* 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
@@ -3451,6 +4108,42 @@ class CodeArtifactServiceTest {
assertTrue(page2.nextToken() == null);
}
/**
* AWS's own {@code DomainEntryPoint} reference: a package ingested from an external source
* reports {@code externalConnectionName}, never {@code repositoryName}, which is reserved for
* one published directly. {@code ListPackageVersions} must surface which of the two applies
* per version, not just the {@code originType} flag.
*/
@Test
void listPackageVersionsReportsTheExternalConnectionNameOnlyForARetainedVersion() {
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(2000))));
long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome claim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
"repo", "com.example", "a", "2.0", "public:maven-central", packageFence);
service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "a", "2.0",
claim.episodeId(), true);
CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null,
"repo", "maven", "com.example", "a", null, null, null, null, null);
CodeArtifactService.PackageVersionSummary retained = result.versions().stream()
.filter(v -> "2.0".equals(v.version())).findFirst().orElseThrow();
assertEquals("EXTERNAL", retained.originType());
assertEquals("public:maven-central", retained.externalConnectionName());
CodeArtifactService.PackageVersionSummary direct = result.versions().stream()
.filter(v -> "1.0".equals(v.version())).findFirst().orElseThrow();
assertEquals("INTERNAL", direct.originType());
assertEquals(null, direct.externalConnectionName());
}
/**
* A sidecar that could not supply a timestamp for any version (every {@code
* PackageVersionTimestamp.publishedTime} is {@code null}) must still report a deterministic
@@ -4022,6 +4715,32 @@ class CodeArtifactServiceTest {
assertEquals("Disposed", listed.versions().get(0).status());
}
/**
* Disposing a container-backed version must invalidate any write already snapshotted against
* it, the same way deleting
* one already does, so a Maven external-connection import whose fetch was in flight when
* this runs can detect it and refuse to write the disposed version's bytes back.
*/
@Test
void disposePackageVersionsBumpsThisVersionsOwnFenceOnceItActuallyDeletesRealAssets() {
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"));
long fenceSnapshot = service.currentContainerBackedVersionFence(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);
assertNotEquals(fenceSnapshot, service.currentContainerBackedVersionFence(REGION, "dom", null, "repo",
"maven", "com.example", "a", "1.0"));
}
/**
* Raised by Greptile's review: {@code applyContainerBackedStatusChange} writes the override
* {@code Disposed} before deleting any real assets, so a sidecar failure partway through that
@@ -0,0 +1,156 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
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.assertTrue;
/**
* The wire contract towards a public Maven repository, exercised against a local {@code
* HttpServer} fake standing in for one, named {@code fake} in these tests rather than any of the
* 5 real {@code public:maven-*} connection names.
*/
class MavenExternalConnectionClientTest {
private HttpServer server;
private MavenExternalConnectionClient client;
@BeforeEach
void startServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.start();
Map<String, String> baseUrls = Map.of("fake", "http://127.0.0.1:" + server.getAddress().getPort());
client = new MavenExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(),
baseUrls);
}
@AfterEach
void stopServer() {
server.stop(0);
}
@Test
void fetchAssetReturnsTheRealBytesOnA200() throws IOException {
byte[] content = "pom-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/com/example/widget/1.0/widget-1.0.pom", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<MavenExternalConnectionClient.FetchedAsset> result =
client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.pom");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchAssetReturnsEmptyOnA404() throws IOException {
server.createContext("/com/example/widget/1.0/widget-1.0.pom",
exchange -> respondEmpty(exchange, 404));
Optional<MavenExternalConnectionClient.FetchedAsset> result =
client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.pom");
assertFalse(result.isPresent());
}
@Test
void fetchAssetReturnsEmptyForAnUnknownConnectionName() {
Optional<MavenExternalConnectionClient.FetchedAsset> result =
client.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom");
assertFalse(result.isPresent());
}
@Test
void existsReturnsTrueOnA200HeadResponse() throws IOException {
server.createContext("/com/example/widget/1.0/widget-1.0.jar",
exchange -> respondEmpty(exchange, 200));
assertTrue(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar"));
}
@Test
void existsReturnsFalseOnA404HeadResponse() throws IOException {
server.createContext("/com/example/widget/1.0/widget-1.0.jar",
exchange -> respondEmpty(exchange, 404));
assertFalse(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar"));
}
@Test
void fetchAssetEncodesAFragmentCharacterInTheFilenameInsteadOfTruncatingThePath() throws IOException {
byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/", exchange -> {
if (exchange.getRequestURI().getRawPath().contains("%23")) {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
} else {
exchange.sendResponseHeaders(404, -1);
}
exchange.close();
});
Optional<MavenExternalConnectionClient.FetchedAsset> result =
client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0#build.jar");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchAssetFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
byte[] content = "redirected-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/com/example/widget/1.0/widget-1.0.jar", exchange -> {
exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.jar");
exchange.sendResponseHeaders(301, -1);
exchange.close();
});
server.createContext("/moved/widget-1.0.jar", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<MavenExternalConnectionClient.FetchedAsset> result =
client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.jar");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void existsFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
server.createContext("/com/example/widget/1.0/widget-1.0.jar", exchange -> {
exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.jar");
exchange.sendResponseHeaders(301, -1);
exchange.close();
});
server.createContext("/moved/widget-1.0.jar", exchange -> respondEmpty(exchange, 200));
assertTrue(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar"));
}
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
exchange.sendResponseHeaders(status, -1);
exchange.close();
}
}