mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(codeartifact): add NuGet/BaGetter sidecar for the nuget format (#5790)
Bridges the nuget package format to a real per-repository BaGetter container, the same Manager/Client sidecar shape already established for Maven (Reposilite), npm (Verdaccio), and pypi (pypiserver): a real NuGet V3 push/install round trip through CodeArtifactNuGetController, GetPackageVersionAsset and GetPackageVersionReadme bridged to the live sidecar, and DeletePackage wired through the same CONTAINER_BACKED_FORMATS dispatch the other three formats use. GetPackageVersionReadme is answered live against BaGetter (its own readme-file and nuspec-description endpoints) rather than captured at publish time, since unlike Verdaccio and pypiserver, BaGetter can answer for a specific historical version after the fact. Pins bagetter/bagetter, the actively maintained fork of the original, long-stale loic-sharma/BaGet (no commits since mid-2024, every one of its own releases tagged -preview/-prerelease), confirmed directly against a live container for push/download/readme/delete semantics before relying on them.
This commit is contained in:
1 parent
feafbfe083
commit
3db18d58a5
17 files changed
+2180
-87
No files matched your search
+309
@@ -0,0 +1,309 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Wire-contract tests for {@link BagetterSidecarClient} against a JDK {@code HttpServer} standing in
|
||||
* for a running BaGetter container. The container is registered in the manager's pool directly, so
|
||||
* readiness resolves to the fake server without any Docker daemon.
|
||||
*/
|
||||
class BagetterSidecarClientTest {
|
||||
|
||||
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
|
||||
private HttpServer backend;
|
||||
private String backendUrl;
|
||||
|
||||
@BeforeEach
|
||||
void setUpBackend() throws Exception {
|
||||
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
backend.createContext("/health", exchange -> {
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
backend.start();
|
||||
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDownBackend() {
|
||||
backend.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetGetsTheFlatContainerNupkgPath() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.1.0.0.nupkg", exchange -> {
|
||||
byte[] body = "nupkg bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.0.0", "demo-pkg.1.0.0.nupkg");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("nupkg bytes", new String(result.get(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS normalizes NuGet versions (leading zeroes removed): a caller asking for {@code 1.00.0}
|
||||
* must still find the version BaGetter itself lists as {@code 1.0.0}.
|
||||
*/
|
||||
@Test
|
||||
void fetchPackageVersionAssetMatchesANonNormalizedRequestedVersion() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.1.0.0.nupkg", exchange -> {
|
||||
byte[] body = "nupkg bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.00.0", "demo-pkg.1.0.0.nupkg");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
}
|
||||
|
||||
/**
|
||||
* The asset name must equal the one deterministic name AWS documents for a given package and
|
||||
* version; any other requested name (even a real file that happens to exist under a different
|
||||
* name) is empty.
|
||||
*/
|
||||
@Test
|
||||
void fetchPackageVersionAssetReturnsEmptyWhenTheAssetNameDoesNotMatchTheNormalizedForm() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.0.0", "demo-pkg.nupkg");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetReturnsEmptyWhenTheVersionWasNeverPublished() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "9.9.9", "demo-pkg.9.9.9.nupkg");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageExistsTrueWhenTheFlatContainerListsAtLeastOneVersion() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
assertTrue(client(manager).packageExists("nuget-repo-1", "dom", "repo", null, "demo-pkg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageExistsFalseWhenTheFlatContainerHasNeverHeardOfIt() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
backend.createContext("/v3/package/never-published/index.json", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertFalse(client(manager).packageExists("nuget-repo-1", "dom", "repo", null, "never-published"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsMatchesANonNormalizedRequestedVersion() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
assertTrue(client(manager).packageVersionExists("nuget-repo-1", "dom", "repo", null, "demo-pkg", "1.00.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsFalseForAVersionThatWasNeverPublished() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
assertFalse(client(manager).packageVersionExists("nuget-repo-1", "dom", "repo", null, "demo-pkg", "9.9.9"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code CodeArtifactNuGetController}'s push handler synchronizes on this exact object for a
|
||||
* repository, the same one {@link BagetterSidecarClient#deletePackage} itself takes, so a
|
||||
* push and a delete for the same repository can never interleave; a different repository
|
||||
* must still get its own lock rather than blocking behind an unrelated one.
|
||||
*/
|
||||
@Test
|
||||
void lockForReturnsTheSameObjectForOneRepositoryAndDifferentObjectsForDifferentOnes() {
|
||||
BagetterSidecarClient client = client(manager());
|
||||
|
||||
Object repo1Again = client.lockFor("nuget-repo-1");
|
||||
|
||||
assertSame(client.lockFor("nuget-repo-1"), repo1Again);
|
||||
assertNotSame(client.lockFor("nuget-repo-1"), client.lockFor("nuget-repo-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageDeletesEveryVersionTheFlatContainerLists() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0", "2.0.0");
|
||||
List<String> deletedPaths = new CopyOnWriteArrayList<>();
|
||||
backend.createContext("/api/v2/package/demo-pkg", exchange -> {
|
||||
deletedPaths.add(exchange.getRequestURI().getPath());
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).deletePackage("nuget-repo-1", "dom", "repo", null, "demo-pkg");
|
||||
|
||||
assertEquals(List.of("/api/v2/package/demo-pkg/1.0.0", "/api/v2/package/demo-pkg/2.0.0"),
|
||||
deletedPaths.stream().sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionReadmeReturnsTheEmbeddedReadmeFileWhenOneExists() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/readme", exchange -> {
|
||||
byte[] body = "# Real readme".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<String> result = client(manager).fetchPackageVersionReadme("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.0.0");
|
||||
|
||||
assertEquals(Optional.of("# Real readme"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionReadmeFallsBackToTheNuspecDescriptionWhenNoReadmeFileIsEmbedded() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/readme", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>demo-pkg</id><version>1.0.0</version>"
|
||||
+ "<description>A long description.</description></metadata></package>";
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.nuspec", exchange -> {
|
||||
byte[] body = nuspec.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<String> result = client(manager).fetchPackageVersionReadme("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.0.0");
|
||||
|
||||
assertEquals(Optional.of("A long description."), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionReadmeReturnsEmptyStringWhenNeitherReadmeNorNuspecAreReachable() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/readme", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.nuspec", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<String> result = client(manager).fetchPackageVersionReadme("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "1.0.0");
|
||||
|
||||
assertEquals(Optional.of(""), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionReadmeReturnsEmptyWhenTheVersionWasNeverPublished() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
|
||||
respondWithVersions("demo-pkg", "1.0.0");
|
||||
|
||||
Optional<String> result = client(manager).fetchPackageVersionReadme("nuget-repo-1", "dom", "repo", null,
|
||||
"demo-pkg", "9.9.9");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
private void respondWithVersions(String packageName, String... versions) {
|
||||
String json = "{\"versions\":[" + String.join(",",
|
||||
java.util.Arrays.stream(versions).map(v -> "\"" + v + "\"").toArray(String[]::new)) + "]}";
|
||||
backend.createContext("/v3/package/" + packageName + "/index.json", exchange -> {
|
||||
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private BagetterSidecarManager manager() {
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
private BagetterSidecarClient client(BagetterSidecarManager manager) {
|
||||
return new BagetterSidecarClient(manager, new ObjectMapper(), HttpClient.newHttpClient());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(BagetterSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = BagetterSidecarManager.class.getDeclaredField("pool");
|
||||
poolField.setAccessible(true);
|
||||
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
|
||||
|
||||
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
|
||||
containersField.setAccessible(true);
|
||||
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
|
||||
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
|
||||
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* {@link BagetterSidecarManager#stopManagedContainers()} is a thin delegation to
|
||||
* {@link PerKeyContainerPool#stopAll()}, whose own behavior is covered by {@code
|
||||
* PerKeyContainerPoolTest}. What matters here is the wiring: that the manager implements
|
||||
* {@link ContainerTeardown} (so {@code ContainerTeardowns.stopAll} finds it on reset, nuke, and
|
||||
* shutdown) and that it stops the containers it actually started. A container is seeded straight
|
||||
* into the pool by reflection, so this needs no Docker daemon.
|
||||
*/
|
||||
class BagetterSidecarManagerTest {
|
||||
|
||||
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
|
||||
@Test
|
||||
void implementsContainerTeardownSoStateResetAndNukeCanFindIt() {
|
||||
assertInstanceOf(ContainerTeardown.class, manager());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopManagedContainersStopsEveryContainerThePoolIsTracking() throws Exception {
|
||||
BagetterSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", "http://127.0.0.1:1");
|
||||
seedPooledContainer(manager, "nuget-repo-2", "tracked-bagetter-2", "http://127.0.0.1:1");
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("tracked-bagetter-1", null);
|
||||
verify(lifecycleManager).stopAndRemove("tracked-bagetter-2", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
|
||||
BagetterSidecarManager manager = manager();
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
}
|
||||
|
||||
private BagetterSidecarManager manager() {
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(BagetterSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = BagetterSidecarManager.class.getDeclaredField("pool");
|
||||
poolField.setAccessible(true);
|
||||
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
|
||||
|
||||
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
|
||||
containersField.setAccessible(true);
|
||||
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
|
||||
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
|
||||
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
|
||||
}
|
||||
}
|
||||
+402
@@ -0,0 +1,402 @@
|
||||
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.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Runs a real NuGet V3 push/install round trip against a live, per-repository BaGetter container,
|
||||
* started by {@link BagetterSidecarManager} exactly as in production. The pushed {@code .nupkg}
|
||||
* files are hand-built with the JDK's own {@code java.util.zip} (a real nuspec manifest at the
|
||||
* archive root plus, for one test, an embedded readme file), not a captured fixture: what this
|
||||
* class needs to prove is the real container's behavior, not a client library's fidelity to the
|
||||
* wire format.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactNuGetDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "nuget-sidecar-domain";
|
||||
private static final String REPO = "nuget-sidecar-repo";
|
||||
private static final String PACKAGE_ID = "Demo.Package";
|
||||
private static final String LOWER_ID = "demo.package";
|
||||
private static final String VERSION = "1.0.0";
|
||||
|
||||
private static String bearerToken;
|
||||
// A fresh ZipEntry carries the current wall-clock time in its DOS-format timestamp field
|
||||
// whenever one isn't set explicitly, so two separate buildNupkg(...) calls with otherwise
|
||||
// identical inputs are never byte-identical; every "same bytes" assertion below reuses this
|
||||
// one build from the original push rather than reconstructing it.
|
||||
private static byte[] originalNupkg;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.nuget-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(0)
|
||||
void createDomainRepositoryAndAuthorizationToken() {
|
||||
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);
|
||||
|
||||
bearerToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void pushThenInstallRoundTripsTheExactBytesThroughTheFlatContainer() {
|
||||
originalNupkg = buildNupkg(PACKAGE_ID, VERSION, "A description.", null, null);
|
||||
long assetSizeBytesBeforePush = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(pushBody("boundary123", originalNupkg))
|
||||
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
|
||||
.then().statusCode(201);
|
||||
|
||||
// assetSizeBytes used to have no bridge for nuget at all; this is the real round trip
|
||||
// proving a real push now counts, the same way the other three formats already do.
|
||||
assertEquals(assetSizeBytesBeforePush + originalNupkg.length, describeDomainAssetSizeBytes());
|
||||
|
||||
// Found by Qodo review: the index used to advertise bare paths instead of absolute
|
||||
// URLs, which a real NuGet client's own service-index parser silently drops (it only
|
||||
// keeps a resource whose @id parses as an absolute URI). Both resources must be rooted
|
||||
// at the exact endpoint GetRepositoryEndpoint itself returns.
|
||||
String repositoryEndpoint = given().header("Authorization", AUTH)
|
||||
.get("/v1/repository/endpoint?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("repositoryEndpoint");
|
||||
String endpointNoTrailingSlash = repositoryEndpoint.substring(0, repositoryEndpoint.length() - 1);
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/index.json")
|
||||
.then().statusCode(200)
|
||||
.body(containsString(endpointNoTrailingSlash + "/v3/package/"))
|
||||
.body(containsString(endpointNoTrailingSlash + "/api/v2/package"));
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/index.json")
|
||||
.then().statusCode(200)
|
||||
.body("versions", org.hamcrest.Matchers.hasItem(VERSION));
|
||||
|
||||
byte[] fetchedNupkg = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
|
||||
+ LOWER_ID + "." + VERSION + ".nupkg")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalNupkg, fetchedNupkg);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
|
||||
+ LOWER_ID + ".nuspec")
|
||||
.then().statusCode(200)
|
||||
.body(containsString(PACKAGE_ID));
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package=" + PACKAGE_ID)
|
||||
.then().statusCode(200).body("package.name", equalTo(PACKAGE_ID))
|
||||
.body("package.originConfiguration.restrictions.publish", equalTo("ALLOW"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The real-world gap this closes: {@code GetPackageVersionAsset} used to 404 for every
|
||||
* nuget-published file since there was no nuget sidecar at all. Proves the JSON API bridges
|
||||
* to the same file {@link #pushThenInstallRoundTripsTheExactBytesThroughTheFlatContainer}
|
||||
* already confirmed is really there, through the real sidecar, not a mock. No namespace:
|
||||
* NuGet packages don't have one.
|
||||
*/
|
||||
@Test
|
||||
@Order(2)
|
||||
void getPackageVersionAssetBridgesToTheRealBagetterSidecar() {
|
||||
String assetName = LOWER_ID + "." + VERSION + ".nupkg";
|
||||
byte[] fetched = given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget"
|
||||
+ "&package=" + PACKAGE_ID + "&version=" + VERSION + "&asset=" + assetName)
|
||||
.then().statusCode(200)
|
||||
.header("X-AssetName", equalTo(assetName))
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalNupkg, fetched);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void getPackageVersionAssetReturns404ForAnAssetNameThatIsNotTheNormalizedForm() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget"
|
||||
+ "&package=" + PACKAGE_ID + "&version=" + VERSION + "&asset=" + PACKAGE_ID + ".nupkg")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real-world gap this closes: {@code DescribePackageVersion} used to 404 for every
|
||||
* nuget-uploaded version the same reason {@code GetPackageVersionAsset} did before it was
|
||||
* bridged. Confirms the bridge reads the real BaGetter container's own flat-container
|
||||
* version listing (not a mock) to confirm the version exists, and 404s for one that was
|
||||
* never pushed.
|
||||
*/
|
||||
@Test
|
||||
@Order(4)
|
||||
void describePackageVersionBridgesToTheRealBagetterSidecar() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget"
|
||||
+ "&package=" + PACKAGE_ID + "&version=" + VERSION)
|
||||
.then().statusCode(200)
|
||||
.body("packageVersion.status", equalTo("Published"))
|
||||
.body("packageVersion.packageName", equalTo(PACKAGE_ID))
|
||||
.body("packageVersion.version", equalTo(VERSION));
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget"
|
||||
+ "&package=" + PACKAGE_ID + "&version=9.9.9")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* No readme file was embedded in the pushed package, so this must fall back to the nuspec's
|
||||
* own {@code <description>} rather than 404ing for a version that genuinely exists.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void getPackageVersionReadmeFallsBackToTheNuspecDescription() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/readme?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package="
|
||||
+ PACKAGE_ID + "&version=" + VERSION)
|
||||
.then().statusCode(200)
|
||||
.body("readme", equalTo("A description."))
|
||||
.body("package", equalTo(PACKAGE_ID))
|
||||
.body("version", equalTo(VERSION));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS's own documented idempotent-republish exception ("Overwriting package assets"): a
|
||||
* byte-identical re-push succeeds without BaGetter's own {@code AllowPackageOverwrites: false}
|
||||
* ever rejecting it, since Floci's proxy short-circuits before forwarding anything.
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void repushingTheExactSameBytesSucceedsIdempotently() {
|
||||
long assetSizeBytesBeforeRepush = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(pushBody("boundary123", originalNupkg))
|
||||
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
|
||||
.then().statusCode(200);
|
||||
|
||||
// The idempotent-match short-circuit never forwards to BaGetter, so no new bytes were
|
||||
// written; assetSizeBytes must not count this push a second time.
|
||||
assertEquals(assetSizeBytesBeforeRepush, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void repushingTheSameCoordinatesWithDifferentContentIsRejectedAndTheOriginalSurvives() {
|
||||
byte[] differentNupkg = buildNupkg(PACKAGE_ID, VERSION, "A different description.", null, null);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(pushBody("boundary123", differentNupkg))
|
||||
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
|
||||
.then().statusCode(409);
|
||||
|
||||
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();
|
||||
assertArrayEquals(originalNupkg, fetched);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void missingPackageAndMissingRepositoryAreNotFound() {
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/does-not-exist/index.json")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/no-such-repo/v3/index.json")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package=does-not-exist")
|
||||
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void repositoriesAreIsolatedFromEachOther() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-nuget-repo")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/other-nuget-repo/v3/package/" + LOWER_ID + "/index.json")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void missingOrWrongDomainTokensAreUnauthorized() {
|
||||
// Challenges as Basic, not Bearer: AWS's own NuGet CLI configuration doc has the client
|
||||
// authenticate with Basic (username=aws, password=<token>), so this is the scheme a
|
||||
// retry would actually honor.
|
||||
given().get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/index.json")
|
||||
.then().statusCode(401)
|
||||
.header("WWW-Authenticate", startsWith("Basic"));
|
||||
|
||||
given().header("Authorization", "Bearer not-a-real-token")
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/index.json")
|
||||
.then().statusCode(401);
|
||||
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/domain?domain=other-nuget-token-domain")
|
||||
.then().statusCode(200);
|
||||
String otherDomainToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=other-nuget-token-domain")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
given().header("Authorization", "Bearer " + otherDomainToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/index.json")
|
||||
.then().statusCode(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate package, with a {@code <readme>} element and its referenced file both packed
|
||||
* in: the readme file must win over the description, proving the two-tier fallback really
|
||||
* prefers the embedded file when one exists rather than always falling back.
|
||||
*/
|
||||
@Test
|
||||
@Order(11)
|
||||
void getPackageVersionReadmePrefersTheEmbeddedReadmeFileOverTheDescription() {
|
||||
String packageId = "Readme.Spike";
|
||||
String readmeText = "# Real Readme\n\nPacked alongside the nuspec.";
|
||||
byte[] nupkg = buildNupkg(packageId, "1.0.0", "A description nobody should see.", "README.md", readmeText);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(pushBody("boundary123", nupkg))
|
||||
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
|
||||
.then().statusCode(201);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/readme?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package="
|
||||
+ packageId + "&version=1.0.0")
|
||||
.then().statusCode(200)
|
||||
.body("readme", equalTo(readmeText));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void deletePackageRemovesTheFileFromTheRealBagetterSidecarAndAllowsARepublish() {
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package="
|
||||
+ PACKAGE_ID)
|
||||
.then().statusCode(200).body("deletedPackage.package", equalTo(PACKAGE_ID));
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/index.json")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package=" + PACKAGE_ID)
|
||||
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
// BaGetter's own default (PackageDeletionBehavior: Unlist) would leave the old content in
|
||||
// place and reject this as a duplicate; Floci overrides it to HardDelete specifically so
|
||||
// a deleted package's coordinates are genuinely free again, matching every other
|
||||
// container-backed format's own DeletePackage semantics.
|
||||
byte[] nupkg = buildNupkg(PACKAGE_ID, VERSION, "A description.", null, null);
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(pushBody("boundary123", nupkg))
|
||||
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/**
|
||||
* The real NuGet push protocol's own documented shape: {@code multipart/form-data} whose
|
||||
* first item is the raw bytes of the {@code .nupkg}; the part name and filename are ignored
|
||||
* by both the real protocol and {@code CodeArtifactNuGetController}, so {@code "package"}/
|
||||
* {@code "p.nupkg"} here are arbitrary.
|
||||
*/
|
||||
private static byte[] pushBody(String boundary, byte[] nupkg) {
|
||||
String header = "--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"package\"; filename=\"p.nupkg\"\r\n"
|
||||
+ "Content-Type: application/octet-stream\r\n\r\n";
|
||||
String footer = "\r\n--" + boundary + "--\r\n";
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.writeBytes(header.getBytes(StandardCharsets.UTF_8));
|
||||
out.writeBytes(nupkg);
|
||||
out.writeBytes(footer.getBytes(StandardCharsets.UTF_8));
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* A real {@code .nupkg} is a plain ZIP with a {@code .nuspec} manifest at its root (built with
|
||||
* the JDK's own {@code java.util.zip}, matching {@code NuspecXml.extractFromNupkg}'s own
|
||||
* expectations); {@code readmePathOrNull}/{@code readmeTextOrNull} additionally pack a second
|
||||
* entry and reference it with a nuspec {@code <readme>} element, the real NuGet readme-file
|
||||
* feature.
|
||||
*/
|
||||
private static byte[] buildNupkg(String id, String version, String description, String readmePathOrNull,
|
||||
String readmeTextOrNull) {
|
||||
String readmeElement = readmePathOrNull == null ? "" : "<readme>" + readmePathOrNull + "</readme>";
|
||||
String nuspec = "<?xml version=\"1.0\"?>"
|
||||
+ "<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">"
|
||||
+ "<metadata><id>" + id + "</id><version>" + version + "</version><authors>floci</authors>"
|
||||
+ readmeElement + "<description>" + description + "</description></metadata></package>";
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
zip.putNextEntry(new ZipEntry(id + ".nuspec"));
|
||||
zip.write(nuspec.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
if (readmePathOrNull != null) {
|
||||
zip.putNextEntry(new ZipEntry(readmePathOrNull));
|
||||
zip.write(readmeTextOrNull.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+118
-6
@@ -58,6 +58,7 @@ class CodeArtifactServiceTest {
|
||||
private VerdaccioSidecarClient verdaccioClient;
|
||||
private ReposiliteSidecarClient reposiliteClient;
|
||||
private PypiserverSidecarClient pypiserverClient;
|
||||
private BagetterSidecarClient bagetterClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -82,9 +83,11 @@ class CodeArtifactServiceTest {
|
||||
when(reposiliteClient.format()).thenReturn("maven");
|
||||
pypiserverClient = mock(PypiserverSidecarClient.class);
|
||||
when(pypiserverClient.format()).thenReturn("pypi");
|
||||
bagetterClient = mock(BagetterSidecarClient.class);
|
||||
when(bagetterClient.format()).thenReturn("nuget");
|
||||
service = new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore,
|
||||
regionResolver, config, true, null, new CodeArtifactSidecarRegistry(
|
||||
List.of(verdaccioClient, reposiliteClient, pypiserverClient)));
|
||||
List.of(verdaccioClient, reposiliteClient, pypiserverClient, bagetterClient)));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- domains
|
||||
@@ -549,6 +552,26 @@ class CodeArtifactServiceTest {
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS's own NuGet normalization doc: package names are lowercased only, no further collapsing
|
||||
* the way pypi's PEP 503 normalization does, so an upload spelled with mixed case and a {@code
|
||||
* DeletePackage} spelled already-lowercase still address the one byte count BaGetter itself would
|
||||
* treat as a single package.
|
||||
*/
|
||||
@Test
|
||||
void nugetAccountingNormalizesThePackageNameToLowercase() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
recordBytes("dom", "repo", "nuget", null, "My.Package", 42L);
|
||||
assertEquals(42L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
when(bagetterClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my.package")))
|
||||
.thenReturn(true);
|
||||
|
||||
service.deletePackage(REGION, "dom", null, "repo", "nuget", null, "my.package");
|
||||
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentCreateDomainWithSameNameOnlyOneWins() throws InterruptedException {
|
||||
int attempts = 8;
|
||||
@@ -650,7 +673,7 @@ class CodeArtifactServiceTest {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
assertEquals(Set.of("maven", "npm", "pypi"), created.getSidecarContainerIds().keySet());
|
||||
assertEquals(Set.of("maven", "npm", "pypi", "nuget"), created.getSidecarContainerIds().keySet());
|
||||
created.getSidecarContainerIds().values()
|
||||
.forEach(id -> assertTrue(id != null && !id.isBlank()));
|
||||
}
|
||||
@@ -1480,6 +1503,31 @@ class CodeArtifactServiceTest {
|
||||
verify(pypiserverClient, never()).packageVersionExists(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describePackageVersionBridgesToTheNugetSidecar() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(bagetterClient.packageVersionExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
|
||||
eq("1.0.0"))).thenReturn(true);
|
||||
|
||||
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "nuget", null,
|
||||
"my-pkg", "1.0.0");
|
||||
|
||||
assertEquals("Published", pv.getStatus());
|
||||
assertEquals("my-pkg", pv.getPackageName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describePackageVersionRejectsANamespaceForNuget() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom", null,
|
||||
"repo", "nuget", "ns", "my-pkg", "1.0.0"));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
verify(bagetterClient, never()).packageVersionExists(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describePackageReportsTheDirectPublishDefaultsAndMatchesExactly() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
@@ -1674,6 +1722,11 @@ class CodeArtifactServiceTest {
|
||||
"ALLOW", "BLOCK"));
|
||||
assertEquals("ValidationException", namespaceForPypi.getErrorCode());
|
||||
|
||||
AwsException namespaceForNuget = assertThrows(AwsException.class, () -> service
|
||||
.putPackageOriginConfiguration(REGION, "dom", null, "repo", "nuget", "bogus-namespace", "my-pkg",
|
||||
"ALLOW", "BLOCK"));
|
||||
assertEquals("ValidationException", namespaceForNuget.getErrorCode());
|
||||
|
||||
// None of the rejections above may have created the package or changed anything about it:
|
||||
// every one of them must still 404 just like before any of these calls were attempted.
|
||||
AwsException stillAbsent = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom",
|
||||
@@ -2294,20 +2347,79 @@ class CodeArtifactServiceTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* nuget is a documented valid format for this action, but nothing in Floci implements the
|
||||
* real NuGet wire protocol, so no nuget package version can ever actually exist here; this
|
||||
* must 404 honestly rather than throwing some other error for a format it otherwise accepts.
|
||||
* Unlike npm and pypi, nuget is answered live against its sidecar (see {@code
|
||||
* BagetterSidecarClient#fetchPackageVersionReadme}'s own javadoc for why BaGetter can support this
|
||||
* where Verdaccio and pypiserver can't), so this never goes through {@code
|
||||
* recordPublishedPackageVersionReadme}/{@code packageVersionReadmes} the way npm/pypi do.
|
||||
*/
|
||||
@Test
|
||||
void getPackageVersionReadme404sForNugetSinceNothingCanEverPublishOne() {
|
||||
void getPackageVersionReadmeReturnsWhatTheNugetSidecarAnswersLive() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(bagetterClient.fetchPackageVersionReadme(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
|
||||
eq("1.0.0"))).thenReturn(Optional.of("# My Package"));
|
||||
|
||||
CodeArtifactService.PackageVersionReadmeResult result = service.getPackageVersionReadme(REGION, "dom", null,
|
||||
"repo", "nuget", null, "my-pkg", "1.0.0");
|
||||
|
||||
assertEquals("# My Package", result.readme());
|
||||
assertEquals("my-pkg", result.packageName());
|
||||
assertEquals("1.0.0", result.version());
|
||||
}
|
||||
|
||||
/** A published nuget version with no embedded readme or description answers "", not 404. */
|
||||
@Test
|
||||
void getPackageVersionReadmeReturnsEmptyStringForANugetVersionWithNoReadmeOrDescription() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(bagetterClient.fetchPackageVersionReadme(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
|
||||
eq("1.0.0"))).thenReturn(Optional.of(""));
|
||||
|
||||
CodeArtifactService.PackageVersionReadmeResult result = service.getPackageVersionReadme(REGION, "dom", null,
|
||||
"repo", "nuget", null, "my-pkg", "1.0.0");
|
||||
|
||||
assertEquals("", result.readme());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPackageVersionReadme404sForNugetWhenTheSidecarHasNeverPublishedIt() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(bagetterClient.fetchPackageVersionReadme(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
|
||||
eq("1.0.0"))).thenReturn(Optional.empty());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom", null,
|
||||
"repo", "nuget", null, "my-pkg", "1.0.0"));
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Qodo review: a caller-supplied namespace for pypi or nuget, neither of which has
|
||||
* one, used to pass this method's own validation (it only checked namespace's token syntax)
|
||||
* and reach the sidecar lookup, which ignores the namespace entirely and would echo it back
|
||||
* in the response as though it belonged to the package.
|
||||
*/
|
||||
@Test
|
||||
void getPackageVersionReadmeRejectsANamespaceForNuget() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom", null,
|
||||
"repo", "nuget", "ns", "my-pkg", "1.0.0"));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
verify(bagetterClient, never()).fetchPackageVersionReadme(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPackageVersionReadmeRejectsANamespaceForPypi() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom", null,
|
||||
"repo", "pypi", "ns", "my-pkg", "1.0.0"));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordPublishedPackageVersionReadmeSkipsAPackageNameContainingTheEscapeCharacterWithoutCorruptingOthers() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** Each case is one of the three transformations AWS's own NuGet normalization doc documents. */
|
||||
class NuGetVersionsTest {
|
||||
|
||||
/**
|
||||
* AWS's own worked example text is "1.00 is treated as 1.0", a 2-segment result; this
|
||||
* intentionally returns {@code 1.0.0} instead, matching what the real {@code
|
||||
* NuGetVersion.ToNormalizedString()} BaGetter itself calls actually produces (always at least
|
||||
* Major.Minor.Patch) rather than AWS's own apparently-simplified doc example. This class
|
||||
* exists only to match what BaGetter's own version list already contains well enough to find
|
||||
* a caller's version in it, so matching the real sidecar's output is what matters here, not
|
||||
* reproducing AWS's doc text byte-for-byte.
|
||||
*/
|
||||
@Test
|
||||
void stripsLeadingZeroesFromEachSegment() {
|
||||
assertEquals("1.0.0", NuGetVersions.normalize("1.00"));
|
||||
assertEquals("1.1.1", NuGetVersions.normalize("1.01.1"));
|
||||
assertEquals("1.0.0.1", NuGetVersions.normalize("1.00.0.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsAZeroFourthSegment() {
|
||||
assertEquals("1.0.0", NuGetVersions.normalize("1.0.0.0"));
|
||||
assertEquals("1.0.1", NuGetVersions.normalize("1.0.01.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removesSemVerBuildMetadata() {
|
||||
assertEquals("1.0.7", NuGetVersions.normalize("1.0.7+r3456"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void padsAShortReleaseUpToThreeSegments() {
|
||||
assertEquals("1.0.0", NuGetVersions.normalize("1.0"));
|
||||
assertEquals("1.0.0", NuGetVersions.normalize("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsAPrereleaseLabelAndLowercasesIt() {
|
||||
assertEquals("1.0.0-beta.1", NuGetVersions.normalize("1.0.0-Beta.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesAnythingItDoesNotConfidentlyUnderstandUnchanged() {
|
||||
assertEquals("not-a-version", NuGetVersions.normalize("not-a-version"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Qodo review: a plain {@code split} silently drops a trailing empty string, so
|
||||
* {@code "1.0.0."} would otherwise normalize identically to the real version {@code "1.0.0"}
|
||||
* and let a malformed caller-supplied version resolve a published one.
|
||||
*/
|
||||
@Test
|
||||
void leavesATrailingDotUnchangedRatherThanNormalizingItAwayAsAnEmptySegment() {
|
||||
assertEquals("1.0.0.", NuGetVersions.normalize("1.0.0."));
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Qodo review: an oversized numeric segment used to throw {@code
|
||||
* NumberFormatException} out of {@code normalize} instead of falling back like any other
|
||||
* segment it isn't confident it understood.
|
||||
*/
|
||||
@Test
|
||||
void leavesASegmentTooLargeForALongUnchangedRatherThanThrowing() {
|
||||
String tooLarge = "99999999999999999999.0.0";
|
||||
assertEquals(tooLarge, NuGetVersions.normalize(tooLarge));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class NuspecXmlTest {
|
||||
|
||||
private static final String NUSPEC = "<?xml version=\"1.0\"?>"
|
||||
+ "<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">"
|
||||
+ "<metadata><id>Demo.Package</id><version>1.0.0</version><authors>me</authors>"
|
||||
+ "<description>A description.</description></metadata></package>";
|
||||
|
||||
@Test
|
||||
void parseReadsIdVersionAndDescriptionThroughTheDefaultNamespace() {
|
||||
NuspecXml.Metadata metadata = NuspecXml.parse(NUSPEC.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertEquals("Demo.Package", metadata.id());
|
||||
assertEquals("1.0.0", metadata.version());
|
||||
assertEquals(Optional.of("A description."), metadata.description());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRejectsAMissingRequiredElement() {
|
||||
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>Demo</id></metadata></package>";
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> NuspecXml.parse(nuspec.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A DOCTYPE declaration is rejected outright rather than silently resolved: this is the one
|
||||
* observable way to confirm external entity expansion is actually disabled, since a
|
||||
* successful parse of a benign payload alone wouldn't distinguish "XXE is disabled" from
|
||||
* "this particular payload didn't need an external entity anyway."
|
||||
*/
|
||||
@Test
|
||||
void parseRejectsADoctypeDeclarationRatherThanResolvingIt() {
|
||||
String maliciousNuspec = "<?xml version=\"1.0\"?><!DOCTYPE package [<!ENTITY xxe SYSTEM \"file:///etc/"
|
||||
+ "hostname\">]><package><metadata><id>&xxe;</id><version>1.0.0</version></metadata></package>";
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> NuspecXml.parse(maliciousNuspec.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractFromNupkgFindsTheRootNuspecEntryInsideTheZip() throws Exception {
|
||||
byte[] nupkg = buildNupkg(NUSPEC);
|
||||
|
||||
NuspecXml.Metadata metadata = NuspecXml.extractFromNupkg(nupkg);
|
||||
|
||||
assertEquals("Demo.Package", metadata.id());
|
||||
}
|
||||
|
||||
/** The manifest must sit at the archive root; a same-suffix entry nested in a subdirectory doesn't count. */
|
||||
@Test
|
||||
void extractFromNupkgIgnoresANestedNuspecSuffixedEntry() {
|
||||
byte[] nupkg = buildNupkg(null);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> NuspecXml.extractFromNupkg(nupkg));
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Qodo review: a highly-compressible entry can expand to far more than the overall
|
||||
* upload's own, already-checked, compressed byte count, so the bound has to apply to the
|
||||
* decompressed stream, not just the request body. The repeated character below compresses to
|
||||
* a tiny fraction of its real size, matching exactly that shape.
|
||||
*/
|
||||
@Test
|
||||
void extractFromNupkgRejectsANuspecEntryThatDecompressesPastTheSizeLimit() {
|
||||
String oversizedDescription = "A".repeat(2 * 1024 * 1024);
|
||||
String nuspec = "<?xml version=\"1.0\"?><package><metadata><id>Demo</id><version>1.0.0</version>"
|
||||
+ "<description>" + oversizedDescription + "</description></metadata></package>";
|
||||
byte[] nupkg = buildNupkg(nuspec);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> NuspecXml.extractFromNupkg(nupkg));
|
||||
}
|
||||
|
||||
private static byte[] buildNupkg(String rootNuspecOrNull) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
if (rootNuspecOrNull != null) {
|
||||
zip.putNextEntry(new ZipEntry("Demo.Package.nuspec"));
|
||||
zip.write(rootNuspecOrNull.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
} else {
|
||||
zip.putNextEntry(new ZipEntry("package/services/metadata/core-properties/fake.nuspec"));
|
||||
zip.write("not a real manifest".getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user