feat(codeartifact): retain NuGet packages from a public external connection (#7104)

NuGet's native v3/package route can now retain a missing package version
from a repository's own public:nuget-org external connection and serve
it, instead of always 404ing, matching AWS's documented external-
connection behavior already shipped for Maven.

- A version's retention origin is claimed atomically before any fetch
  happens, rejecting a later attempt under a different connection
  outright ("checking asset origins").
- Package-level upstream: BLOCK is respected, including when the
  restriction and the request spell the package name differently
  (nuget/pypi names are case/punctuation normalized everywhere this
  service tracks a package; PackageOriginConfig now keys by that same
  normalization too, instead of the caller's raw spelling).
- A retained version reports originType: EXTERNAL and its source
  connection through DescribePackageVersion/ListPackageVersions, for
  any format that retains (not just Maven).
- A concurrent retention attempt racing a real client's own direct
  push is never mislabeled as an external import: existence in the
  real sidecar alone no longer implies success, only a confirmed claim
  under the exact same connection does.
- Retained bytes are counted toward DescribeDomain's assetSizeBytes,
  never double-counted on a concurrent retry.
- A real HTTP redirect from the public repository is followed instead
  of being treated as a 404.
- Fixed-version retention only; resolving a floating/omitted version by
  merging in nuget.org's own version listing is left for a follow-up,
  the same baseline scope Maven's own external-connection work shipped
  first.

New: NuGetExternalConnectionClient (the outbound client for
public:nuget-org) and CodeArtifactNuGetExternalConnectionImporter (the
retention decision logic), wired into CodeArtifactNuGetController.

The claim/fence/deploy machinery CodeArtifactService already used for
Maven's own external-connection retention is generalized into
format-parameterized methods so npm and pypi can reuse it too, with
Maven's own public methods kept as thin, behavior-identical delegates
over the generic ones.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-31 16:16:06 -05:00
1 parent 2b6a8b4e66
commit 300e62a0ed
8 files changed
+1239 -132

No files matched your search

@@ -0,0 +1,212 @@
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 static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Retains a real NuGet package version from the real, live {@code public:nuget-org} repository
* (not a local fake), through the native per-format route, the way a real {@code dotnet restore}/
* {@code nuget install} would. {@code Newtonsoft.Json} 13.0.3 is picked because it is small,
* stable, and unlikely to ever be pulled from nuget.org. A genuine network dependency, unlike
* every other sidecar-backed test here, which only ever talks to a container Floci itself
* started; see {@code CodeArtifactNuGetExternalConnectionImporterTest} for the mocked,
* deterministic coverage of the claim/fence/mixed-origin logic this test does not re-exercise.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactNuGetExternalConnectionDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "nuget-external-connection-domain";
private static final String REPO = "nuget-external-connection-repo";
private static final String BLOCKED_REPO = "nuget-external-connection-blocked-repo";
private static final String PACKAGE_ID = "Newtonsoft.Json";
private static final String LOWER_ID = "newtonsoft.json";
private static final String VERSION = "13.0.3";
private static String bearerToken;
@BeforeAll
static void setUp() {
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.nuget-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:nuget-org")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
+ "&external-connection=public:nuget-org")
.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 fetchingAMissingNupkgRetainsItFromTheRealNuGetOrgConnectionAndCountsItsBytes() {
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/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
+ LOWER_ID + "." + VERSION + ".nupkg")
.then().statusCode(200)
.extract().asByteArray();
// A real .nupkg 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 nuget push already is.
long assetSizeBytesAfter = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(assetSizeBytesBefore + fetched.length, assetSizeBytesAfter);
}
@Test
@Order(2)
void refetchingTheSameVersionServesItWithoutRetainingItAgain() {
long assetSizeBytesBefore = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
+ LOWER_ID + "." + VERSION + ".nupkg")
.then().statusCode(200)
.extract().asByteArray();
assertEquals('P', (char) fetched[0]);
assertEquals('K', (char) fetched[1]);
long assetSizeBytesAfter = given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getLong("domain.assetSizeBytes");
assertEquals(assetSizeBytesBefore, assetSizeBytesAfter);
}
/**
* Found by Greptile's review: {@code PackageOriginConfig} used to be keyed by whatever raw
* spelling a caller used, so a restriction set through one casing silently never matched a
* request spelled another way. Deliberately mixed-case here ({@link #PACKAGE_ID}) against the
* native route's own lowercase spelling, the exact mismatch the fix closes: an operator
* blocking upstream retention through the management API is not required to already know (or
* guess at) the normalized spelling nuget's own URL convention happens to use.
*/
@Test
@Order(3)
void upstreamBlockPreventsRetentionEvenThoughTheRealPackageExists() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"ALLOW\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=nuget"
+ "&package=" + PACKAGE_ID)
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + BLOCKED_REPO + "/v3/package/" + LOWER_ID + "/" + VERSION
+ "/" + LOWER_ID + "." + VERSION + ".nupkg")
.then().statusCode(404);
// The block itself is visible under either spelling too, not just enforced: proves the
// fix is a real normalization, not a one-off match on this test's own two spellings.
given().header("Authorization", AUTH)
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=nuget&package="
+ LOWER_ID)
.then().statusCode(200)
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
}
@Test
@Order(4)
void aVersionTheRealRepositoryDoesNotHaveIsNeverRetained() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID
+ "/999.999.999/" + LOWER_ID + ".999.999.999.nupkg")
.then().statusCode(404);
}
/**
* Found by Greptile's review: a successfully retained version used to still report {@code
* originType: INTERNAL}, since {@code versionOrigin} special-cased Maven only. Confirms the
* fix against the real sidecar's own retained version from {@link
* #fetchingAMissingNupkgRetainsItFromTheRealNuGetOrgConnectionAndCountsItsBytes}, not a mock.
*/
@Test
@Order(5)
void aRetainedVersionReportsAnExternalOriginNotInternal() {
given().header("Authorization", AUTH)
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package="
+ LOWER_ID)
.then().statusCode(200)
.body("versions[0].version", equalTo(VERSION))
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
.body("versions[0].origin.domainEntryPoint.externalConnectionName",
equalTo("public:nuget-org"));
}
/**
* Found by Greptile's review: the outbound request to the real public repository only
* lowercased the version instead of fully normalizing it, so a request spelled equivalently
* but not canonically (AWS's own worked example, {@code 1.00} for {@code 1.0.0}) built a path
* the real {@code api.nuget.org/v3-flatcontainer} storage has nothing under and 404s on,
* confirmed directly against it, even though the exact same real package version exists under
* its canonical spelling. A distinct, never-before-retained version ({@code 9.0.1}) proves the
* fetch itself succeeds under the equivalent spelling, not just that local matching tolerates
* it once something is already retained.
*/
@Test
@Order(6)
void fetchingAnEquivalentlySpelledVersionStillRetainsItFromTheRealNuGetOrgConnection() {
String equivalentVersion = "9.00.1";
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/"
+ equivalentVersion + "/" + LOWER_ID + "." + equivalentVersion + ".nupkg")
.then().statusCode(200)
.extract().asByteArray();
assertEquals('P', (char) fetched[0]);
assertEquals('K', (char) fetched[1]);
assertThat(fetched.length, greaterThan(1000));
}
}
@@ -0,0 +1,226 @@
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 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.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link CodeArtifactNuGetExternalConnectionImporter}'s own decision logic: when it attempts a
* real external-connection fetch at all, and what it writes back. {@link BagetterSidecarClient}
* and {@link NuGetExternalConnectionClient} are both mocked, so no real network or BaGetter call
* ever happens here; their own wire contracts have their own tests.
*/
class CodeArtifactNuGetExternalConnectionImporterTest {
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 static final String PACKAGE_ID = "Widget";
private static final String VERSION = "1.0.0";
private static final byte[] NUPKG_CONTENT = "nupkg-content".getBytes();
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
private static final long EPISODE_ID = 7L;
private CodeArtifactService service;
private BagetterSidecarClient bagetter;
private NuGetExternalConnectionClient externalConnectionClient;
private CodeArtifactNuGetExternalConnectionImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
bagetter = mock(BagetterSidecarClient.class);
externalConnectionClient = mock(NuGetExternalConnectionClient.class);
importer = new CodeArtifactNuGetExternalConnectionImporter(service, bagetter, externalConnectionClient);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(
List.of(new ExternalConnection("public:nuget-org", "nuget", "AVAILABLE")));
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString())).thenReturn(false);
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString())).thenReturn(42L);
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString())).thenReturn(99L);
// 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.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyString(), anyLong()))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
// Unstubbed by default: BaGetter does not have the version yet, matching the controller's
// own pre-check always calling tryImport only on a miss. Tests for the already-retained
// race override this per call.
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
.thenReturn(false);
// Unstubbed by default: the fence matched and the write landed. The real check this
// stands in for is inside retainAssetUnderVersionFence itself, a synchronized
// CodeArtifactService method (see its own javadoc for why), so this mock is what every
// test configures instead.
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
}
@Test
void importsFromExternalConnectionWhenNotFoundLocally() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("nuget"),
isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(bagetter), eq(REPO_ID),
eq("widget.1.0.0.nupkg"), eq(NUPKG_CONTENT));
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, 42L);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, true);
}
@Test
void returnsFalseWhenNoNuGetExternalConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setExternalConnections(List.of());
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void returnsFalseWhenUpstreamRetentionIsBlocked() {
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID))
.thenReturn(true);
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
}
@Test
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
VERSION, "public:nuget-org", 42L))
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(bagetter, never()).packageVersionExists(anyString(), anyString(), anyString(), any(), anyString(),
anyString());
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
}
@Test
void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() {
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
.thenReturn(true);
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
VERSION)).thenReturn(Optional.of("public:nuget-org"));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, true);
}
/**
* Found by Greptile's review: {@code bagetter.packageVersionExists} alone proves nothing about
* who put the content there. A real client's own direct push can land between this attempt's
* own claim and this existence check; treating that as "a sibling import already retained it"
* would wrongly mark a privately-pushed version EXTERNAL and overwrite its origin defaults.
*/
@Test
void doesNotMislabelAVersionADirectPushWroteDuringTheRaceAsExternallyRetained() {
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
.thenReturn(true);
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
VERSION)).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
@Test
void returnsFalseAndFinishesWhenTheRealRepositoryDoesNotHaveIt() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
@Test
void aFetchThatThrowsIsTreatedLikeAMissingPackageRatherThanPropagating() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenThrow(new IllegalStateException("public repository unreachable"));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
@Test
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
}
@@ -5299,6 +5299,40 @@ class CodeArtifactServiceTest {
eq("1.00"), eq("my-pkg.1.00.nupkg"));
}
/**
* Raised by Greptile's review: this method's own claimed-origin cleanup removed the record
* keyed by the caller's raw version, but {@link CodeArtifactService#retainedVersionOriginConnection}'s
* own claim is keyed by its normalized spelling. Deleting a retained nuget version under an
* equivalent-but-different spelling (AWS's own worked example, {@code 1.00} against {@code
* 1.0.0}) removed the real asset but left the claim behind, so a later direct push of the
* same real version would still read back as {@code EXTERNAL} under the stale connection.
*/
@Test
void deletePackageVersionsClearsARetainedClaimEvenUnderAnEquivalentNuGetVersionSpelling() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("nuget");
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "nuget", null,
"my-pkg");
CodeArtifactService.RetainedVersionOriginClaimOutcome outcome = service.claimRetainedVersionOrigin(REGION,
"dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", "public:nuget-org", fence);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0",
outcome.episodeId(), true);
assertEquals("public:nuget-org", service.retainedVersionOriginConnection(REGION, "dom", null, "repo",
"nuget", null, "my-pkg", "1.0.0").orElseThrow());
when(bagetterClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
.thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.00",
Instant.ofEpochSecond(1000))));
when(bagetterClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.00"))).thenReturn(List.of("my-pkg.1.00.nupkg"));
service.deletePackageVersions(REGION, "dom", null, "repo", "nuget", null, "my-pkg", List.of("1.00"), null);
assertTrue(service.retainedVersionOriginConnection(REGION, "dom", null, "repo", "nuget", null, "my-pkg",
"1.0.0").isEmpty());
}
@Test
void deletePackageVersionsFailsNotFoundForAContainerBackedVersionThatWasNeverPublished() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -0,0 +1,157 @@
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The wire contract towards the real public NuGet repository, exercised against a local {@code
* HttpServer} fake standing in for it, named {@code fake} in these tests rather than the real
* {@code public:nuget-org} connection name.
*/
class NuGetExternalConnectionClientTest {
private HttpServer server;
private NuGetExternalConnectionClient 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 NuGetExternalConnectionClient(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build(),
baseUrls);
}
@AfterEach
void stopServer() {
server.stop(0);
}
@Test
void fetchPackageReturnsTheRealBytesOnA200() throws IOException {
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "Widget", "1.0.0");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchPackageLowercasesTheIdAndVersionInThePath() throws IOException {
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/1.0.0-beta/widget.1.0.0-beta.nupkg", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
client.fetchPackage("fake", "WIDGET", "1.0.0-BETA");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
/**
* Raised by Greptile's review: the real {@code api.nuget.org/v3-flatcontainer} only ever
* stores one canonical path per version and 404s on an equivalent-but-not-canonical spelling
* (confirmed directly against it: {@code 13.00.3} 404s where {@code 13.0.3} 200s), the same
* normalization {@code NuGetVersions#normalize} already applies for matching BaGetter's own
* listing. Requesting {@code 1.00.0} must still build the canonical {@code 1.0.0} path, not
* the merely-lowercased {@code 1.00.0} the old code sent.
*/
@Test
void fetchPackageNormalizesAnEquivalentVersionSpellingToTheCanonicalPath() throws IOException {
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
client.fetchPackage("fake", "widget", "1.00.0");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
@Test
void fetchPackageReturnsEmptyOnA404() throws IOException {
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 404));
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "widget", "1.0.0");
assertFalse(result.isPresent());
}
@Test
void fetchPackageReturnsEmptyForAnUnknownConnectionName() {
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
client.fetchPackage("public:nuget-org", "widget", "1.0.0");
assertFalse(result.isPresent());
}
@Test
void existsReturnsTrueOnA200HeadResponse() throws IOException {
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 200));
assertTrue(client.exists("fake", "widget", "1.0.0"));
}
@Test
void existsReturnsFalseOnA404HeadResponse() throws IOException {
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 404));
assertFalse(client.exists("fake", "widget", "1.0.0"));
}
@Test
void fetchPackageFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
byte[] content = "redirected-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
exchange.getResponseHeaders().add("Location", "/moved/widget.1.0.0.nupkg");
exchange.sendResponseHeaders(301, -1);
exchange.close();
});
server.createContext("/moved/widget.1.0.0.nupkg", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "widget", "1.0.0");
assertTrue(result.isPresent());
assertArrayEquals(content, result.get().content());
}
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
exchange.sendResponseHeaders(status, -1);
exchange.close();
}
}