mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(codeartifact): support the cargo (crates.io) registry format (#8370)
CodeArtifact's Rust/Cargo repositories had no native support at all: no sidecar, no wire protocol, no external connection. Adds it following the same shape as the existing Maven/npm/pypi/NuGet container-backed formats. KellnrSidecarManager/KellnrSidecarClient run a real Kellnr container per cargo-enabled repository and speak its native HTTP API for publish, download, and the sparse index. CodeArtifactCargoController implements the real `cargo` sparse-registry wire protocol (publish, download, sparse index lookup, config.json) and forwards Kellnr's own publish rejections (e.g. republishing an existing version, which the Cargo Book documents as permanently disallowed) verbatim rather than swallowing them into an opaque error. Adds the `public:crates-io` external connection via CargoExternalConnectionClient (real index.crates.io/static.crates.io wire calls) and CodeArtifactCargoExternalConnectionImporter, reusing the existing claim/fence/retention-origin machinery the same way NuGet's own importer does. Cargo's sparse index covers every version of a crate name in one file and a real cargo client always consults it first, so unlike the other formats' importers this one also merges real upstream-only version lines into the local index response (mergeExternalVersions), a read-only proxy step with no retention write of its own, so an upstream-only crate is actually visible to a client's dependency resolution before anything is retained. Fixes against the live Kellnr/crates.io protocols found while addressing review: KellnrSidecarClient now implements listPackages (its absence made every ListPackages call 500 once cargo joined the container-backed formats); sparse-index bucket paths are lowercased per the Cargo Book's own spec (crates.io's own index is case-sensitive about this even though a crate's real name isn't); the admin account behind Kellnr's internal publish token is given a fresh random password per container rather than Kellnr's own shared default; a stale cached publish token (e.g. after a silent container restart) is retried once rather than 401ing forever; both publish-body parsing and the external sparse-index fetch are now bounded against an oversized allocation; a renamed dependency's alias and real name are mapped correctly between the index and publish shapes, and features2/links/rust_version now survive a retained crate's synthesized metadata; the Kellnr image is pinned to the exact version this was built and tested against rather than a floating major tag. Known gaps, called out in docs/services/codeartifact.md: no repository-to-repository upstream importer yet for cargo (every other native format already has one), and no yank/owner/search routes.
This commit is contained in:
1 parent
1b14d10b1f
commit
15a632e446
19 files changed
+4286
-79
No files matched your search
+183
@@ -0,0 +1,183 @@
|
||||
package io.floci.aws.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.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.HexFormat;
|
||||
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 the real public {@code crates.io} registry, exercised against a
|
||||
* local {@code HttpServer} fake standing in for it, named {@code fake} in these tests rather than
|
||||
* the real {@code public:crates-io} connection name, mirroring {@link
|
||||
* NuGetExternalConnectionClientTest}'s own shape.
|
||||
*/
|
||||
class CargoExternalConnectionClientTest {
|
||||
|
||||
private HttpServer server;
|
||||
private CargoExternalConnectionClient client;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.start();
|
||||
String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
client = new CargoExternalConnectionClient(
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(),
|
||||
Map.of("fake", baseUrl), Map.of("fake", baseUrl));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsTheRealBytesOnA200() throws IOException {
|
||||
byte[] content = "{\"name\":\"widget\",\"vers\":\"1.0.0\"}\n".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/wi/dg/widget", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client.fetchSparseIndex("fake", "widget");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get());
|
||||
}
|
||||
|
||||
/** Confirms the real RFC 2789 bucketing rule for each name-length case, not just the 4+
|
||||
* character case the one example above covers. */
|
||||
@Test
|
||||
void fetchSparseIndexUsesTheRealBucketingPathForEveryNameLength() throws IOException {
|
||||
server.createContext("/1/a", exchange -> respond(exchange, 200, "one"));
|
||||
server.createContext("/2/ab", exchange -> respond(exchange, 200, "two"));
|
||||
server.createContext("/3/a/abc", exchange -> respond(exchange, 200, "three"));
|
||||
server.createContext("/wi/dg/widget", exchange -> respond(exchange, 200, "four-plus"));
|
||||
|
||||
assertEquals("one", new String(client.fetchSparseIndex("fake", "a").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("two", new String(client.fetchSparseIndex("fake", "ab").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("three",
|
||||
new String(client.fetchSparseIndex("fake", "abc").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("four-plus",
|
||||
new String(client.fetchSparseIndex("fake", "widget").orElseThrow(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsEmptyOnA404() throws IOException {
|
||||
server.createContext("/wi/dg/widget", exchange -> respondEmpty(exchange, 404));
|
||||
|
||||
assertFalse(client.fetchSparseIndex("fake", "widget").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsEmptyForAnUnknownConnectionName() {
|
||||
assertFalse(client.fetchSparseIndex("public:crates-io", "widget").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateWritesTheRealBytesAndReportsTheirRealSizeAndSha256() throws IOException, NoSuchAlgorithmException {
|
||||
byte[] content = "crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/download", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> result =
|
||||
client.fetchCrate("fake", "widget", "1.0.0", destination);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(content.length, result.get().size());
|
||||
assertArrayEquals(content, Files.readAllBytes(destination));
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
String expectedSha256 = HexFormat.of().formatHex(digest.digest(content));
|
||||
assertEquals(expectedSha256, result.get().sha256());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateReturnsEmptyOnA404() throws IOException {
|
||||
server.createContext("/widget/1.0.0/download", exchange -> respondEmpty(exchange, 404));
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
assertFalse(client.fetchCrate("fake", "widget", "1.0.0", destination).isPresent());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateReturnsEmptyForAnUnknownConnectionName() throws IOException {
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
assertFalse(client.fetchCrate("public:crates-io", "widget", "1.0.0", destination).isPresent());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
|
||||
byte[] content = "redirected-crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/download", exchange -> {
|
||||
exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.0.crate");
|
||||
exchange.sendResponseHeaders(301, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/moved/widget-1.0.0.crate", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> result =
|
||||
client.fetchCrate("fake", "widget", "1.0.0", destination);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, Files.readAllBytes(destination));
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
|
||||
exchange.sendResponseHeaders(status, -1);
|
||||
exchange.close();
|
||||
}
|
||||
}
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.StreamingOutput;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Lease and dispatch correctness for {@link CodeArtifactCargoController}, mirroring {@link
|
||||
* CodeArtifactNuGetControllerLeaseTest}'s own shape. {@link KellnrSidecarClient} is mocked, so no
|
||||
* real Kellnr call ever happens here; its own wire contract has its own tests.
|
||||
*/
|
||||
class CodeArtifactCargoControllerLeaseTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OWNER = "123456789012";
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String REPO_ID = "cargo-repo-id";
|
||||
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private CodeArtifactCargoController controller;
|
||||
private HttpHeaders headers;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionImporter = mock(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
controller = new CodeArtifactCargoController(service, kellnr, externalConnectionImporter, new ObjectMapper());
|
||||
// Default: no external connection configured, so the merge is a pure pass-through of
|
||||
// whatever Kellnr's own local lookup returned, exactly what the real importer itself does
|
||||
// when cargoExternalConnectionName resolves to null. Individual tests override this to
|
||||
// exercise the merge itself.
|
||||
when(externalConnectionImporter.mergeExternalVersions(any(), any(), any(), any(), any(), any()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(5));
|
||||
headers = mock(HttpHeaders.class);
|
||||
// A bare token, no scheme prefix: the real shape a cargo client sends (confirmed from the
|
||||
// Cargo Book's own registry-authentication page).
|
||||
when(headers.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("token");
|
||||
when(service.resolveAuthorizationToken("token", DOMAIN))
|
||||
.thenReturn(Optional.of(new AuthorizationTokenScope(OWNER, REGION)));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, REPOSITORY, kellnr))
|
||||
.thenReturn(REPO_ID);
|
||||
when(service.getRepositoryEndpoint(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null))
|
||||
.thenReturn("http://localhost:4566/codeartifact/cargo/dom/repo/");
|
||||
when(service.stageAssetBody(any())).thenAnswer(invocation -> {
|
||||
InputStream in = invocation.getArgument(0);
|
||||
Path staged = Files.createTempFile("cargo-controller-test-", ".bin");
|
||||
Files.copy(in, staged, StandardCopyOption.REPLACE_EXISTING);
|
||||
return staged;
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
Files.deleteIfExists(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(service).deleteStagedAssetBody(any());
|
||||
when(kellnr.lockFor(any())).thenReturn(new Object());
|
||||
when(kellnr.publishRawWireBody(any(), any(), anyLong()))
|
||||
.thenReturn(new KellnrSidecarClient.KellnrPublishResult(200, "{\"warnings\":null}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configJsonReleasesItsLeaseWithoutEverStartingTheSidecar() {
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "config.json");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("\"dl\": "
|
||||
+ "\"http://localhost:4566/codeartifact/cargo/dom/repo/api/v1/crates\""));
|
||||
verify(service).resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, REPOSITORY, kellnr);
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
// config.json is authored directly from GetRepositoryEndpoint, never from the sidecar
|
||||
// itself, so there is no reason to ever start a container just to answer it.
|
||||
verify(kellnr, never()).ensureReady(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupReleasesItsLeaseOnAMiss() {
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate")).thenReturn(Optional.empty());
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupProxiesTheRealBytesVerbatim() {
|
||||
byte[] indexBytes = "{\"name\":\"democrate\",\"vers\":\"1.0.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate"))
|
||||
.thenReturn(Optional.of(indexBytes));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(new String(indexBytes, StandardCharsets.UTF_8),
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupServesTheMergedResultFromTheExternalConnectionImporter() {
|
||||
Optional<byte[]> local = Optional.empty();
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate")).thenReturn(local);
|
||||
byte[] merged = "{\"name\":\"democrate\",\"vers\":\"2.0.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionImporter.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, "democrate", local))
|
||||
.thenReturn(Optional.of(merged));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(new String(merged, StandardCharsets.UTF_8),
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadReleasesItsLeaseOnAnEarlyNotFound() {
|
||||
doThrow(mock(AwsException.class)).when(service).requireContainerBackedVersionDownloadable(
|
||||
OWNER, REGION, DOMAIN, REPOSITORY, "cargo", null, "democrate", "1.0.0", REPO_ID);
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadAttemptsAnExternalConnectionImportOnlyOnALocalMiss() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(true);
|
||||
|
||||
controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadAttemptsAnExternalConnectionImportOnALocalMissThenStreamsWhatItImported() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(false);
|
||||
byte[] crateBytes = "imported-crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchPackageVersionAssetStreamed(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate")).thenReturn(Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(crateBytes), crateBytes.length)));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "democrate",
|
||||
"1.0.0");
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* The one real asset download in this controller: proves it streams the sidecar's response
|
||||
* straight through rather than buffering it first, and still releases its lease afterward.
|
||||
*/
|
||||
@Test
|
||||
void downloadStreamsTheCrateAndReleasesItsLease() throws Exception {
|
||||
byte[] crateBytes = "crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchPackageVersionAssetStreamed(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate")).thenReturn(Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(crateBytes), crateBytes.length)));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
// The lease must still be held once the method itself has returned: a concurrent
|
||||
// DeleteRepository must not be able to tear down the Kellnr container before the entity
|
||||
// stream below is actually drained.
|
||||
verify(kellnr, never()).endUse(REPO_ID);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("crate-bytes", new String(readEntity(response), StandardCharsets.UTF_8));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
private static byte[] readEntity(Response response) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try {
|
||||
((StreamingOutput) response.getEntity()).write(out);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishParsesTheMetadataPrefixAndForwardsTheWholeBodyVerbatim() throws Exception {
|
||||
byte[] body = publishBody("democrate", "1.0.0", "crate-bytes");
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(body));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).requireContainerBackedPackagePublishAllowed(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
"democrate");
|
||||
verify(service).requireContainerBackedVersionNotArchivedOrDisposed(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
"cargo", null, "democrate", "1.0.0");
|
||||
verify(kellnr).publishRawWireBody(eq(REPO_ID), any(Path.class), eq((long) body.length));
|
||||
verify(service).completeContainerBackedPublishIfCurrentRepository(eq(REGION), eq(DOMAIN), eq(OWNER),
|
||||
eq(REPOSITORY), eq(REPO_ID), eq("cargo"), eq("democrate"), eq("1.0.0"),
|
||||
eq((long) "crate-bytes".getBytes(StandardCharsets.UTF_8).length), any(Long.class), isNull(),
|
||||
isNull(), eq(0L));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishRefusesAPublishBlockedByOriginConfiguration() throws Exception {
|
||||
doThrow(new AwsException("ConflictException", "blocked", 409)).when(service)
|
||||
.requireContainerBackedPackagePublishAllowed(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
"democrate");
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(publishBody("democrate", "1.0.0", "crate-bytes")));
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
verify(kellnr, never()).publishRawWireBody(any(), any(), anyLong());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishForwardsKellnrsOwnRejectionVerbatimWithoutCompletingTheBookkeeping() throws Exception {
|
||||
when(kellnr.publishRawWireBody(eq(REPO_ID), any(Path.class), anyLong()))
|
||||
.thenReturn(new KellnrSidecarClient.KellnrPublishResult(400,
|
||||
"{\"errors\":[{\"detail\":\"ERROR: Crate with version already exists: democrate-1.0.0\"}]}"));
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(publishBody("democrate", "1.0.0", "crate-bytes")));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("{\"errors\":[{\"detail\":\"ERROR: Crate with version already exists: democrate-1.0.0\"}]}",
|
||||
response.getEntity());
|
||||
verify(service, never()).completeContainerBackedPublishIfCurrentRepository(any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), anyLong(), anyLong(), any(), any(), anyLong());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishReleasesItsLeaseOnATruncatedMetadataPrefix() {
|
||||
byte[] truncated = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(100).array();
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(truncated));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishDeletesItsStagedFileEvenOnFailure() {
|
||||
byte[] truncated = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(100).array();
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(truncated));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
// The shared setUp() stub for deleteStagedAssetBody actually deletes the real temp file
|
||||
// it's handed, so a real leaked file (not just a missed call) would survive to fail a
|
||||
// later assertion that reads it; verifying the call happened is the meaningful check here.
|
||||
verify(service).deleteStagedAssetBody(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSidecarStartupReleasesTheLease() {
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate"))
|
||||
.thenThrow(new IllegalStateException("Docker unavailable"));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate"));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLeaseCompletionIsNotHidden() {
|
||||
IllegalStateException invalidLease = new IllegalStateException("No active Kellnr sidecar use");
|
||||
doThrow(invalidLease).when(kellnr).endUse(REPO_ID);
|
||||
|
||||
assertSame(invalidLease,
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> controller.get(headers, DOMAIN, REPOSITORY, "config.json")));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
private static byte[] publishBody(String name, String version, String crateContent) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
byte[] metadata = mapper.writeValueAsBytes(Map.of("name", name, "vers", version));
|
||||
byte[] crate = crateContent.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crate.length).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crate.length);
|
||||
buffer.put(crate);
|
||||
return buffer.array();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
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.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Runs a real Cargo publish/install round trip against a live, per-repository Kellnr container,
|
||||
* started by {@link KellnrSidecarManager} exactly as in production. The published {@code .crate}
|
||||
* files are hand-built with the JDK's own {@code java.util.zip} plus the already-present {@code
|
||||
* commons-compress} (a real {@code Cargo.toml} inside a real gzipped tarball), 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, the same reasoning {@link
|
||||
* CodeArtifactNuGetDockerIntegrationTest}'s own class-level documentation gives for NuGet.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactCargoDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "cargo-sidecar-domain";
|
||||
private static final String REPO = "cargo-sidecar-repo";
|
||||
private static final String CRATE_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
|
||||
private static String bearerToken;
|
||||
private static byte[] originalPublishBody;
|
||||
private static byte[] originalCrateBytes;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.cargo-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");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code config.json} must be rooted at the exact endpoint {@code GetRepositoryEndpoint}
|
||||
* itself returns, the same requirement {@link CodeArtifactNuGetDockerIntegrationTest}'s own
|
||||
* service-index test proves for NuGet: a real {@code cargo} client's own sparse-registry
|
||||
* resolver only trusts an absolute {@code dl}/{@code api} rooted at the address it already
|
||||
* reached this response through.
|
||||
*/
|
||||
@Test
|
||||
@Order(1)
|
||||
void configJsonIsRootedAtTheRealRepositoryEndpoint() {
|
||||
String repositoryEndpoint = given().header("Authorization", AUTH)
|
||||
.get("/v1/repository/endpoint?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("repositoryEndpoint");
|
||||
String endpointNoTrailingSlash = repositoryEndpoint.substring(0, repositoryEndpoint.length() - 1);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(200)
|
||||
.body("dl", equalTo(endpointNoTrailingSlash + "/api/v1/crates"))
|
||||
.body("api", equalTo(endpointNoTrailingSlash))
|
||||
.body("auth-required", equalTo(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* The full round trip: publish with a real, non-empty dependency list, then confirm the
|
||||
* sparse index and the download both genuinely reflect what was published, dependency list
|
||||
* included, not a reconstructed or truncated version of it.
|
||||
*/
|
||||
@Test
|
||||
@Order(2)
|
||||
void publishThenInstallRoundTripsTheExactBytesAndRealDependencies() throws IOException {
|
||||
originalCrateBytes = buildCrate(CRATE_NAME, VERSION);
|
||||
originalPublishBody = publishBody(CRATE_NAME, VERSION, originalCrateBytes);
|
||||
long assetSizeBytesBeforePublish = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(originalPublishBody)
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200)
|
||||
.body("warnings", equalTo(null));
|
||||
|
||||
assertEquals(assetSizeBytesBeforePublish + originalCrateBytes.length, describeDomainAssetSizeBytes());
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/de/mo/" + CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + CRATE_NAME + "\""))
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""))
|
||||
.body(containsString("\"name\":\"real-dependency\""));
|
||||
|
||||
byte[] fetchedCrate = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalCrateBytes, fetchedCrate);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package=" + CRATE_NAME)
|
||||
.then().statusCode(200).body("package.name", equalTo(CRATE_NAME))
|
||||
.body("package.originConfiguration.restrictions.publish", equalTo("ALLOW"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void getPackageVersionAssetBridgesToTheRealKellnrSidecar() throws IOException {
|
||||
String assetName = CRATE_NAME + "-" + VERSION + ".crate";
|
||||
byte[] fetched = given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo"
|
||||
+ "&package=" + CRATE_NAME + "&version=" + VERSION + "&asset=" + assetName)
|
||||
.then().statusCode(200)
|
||||
.header("X-AssetName", equalTo(assetName))
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalCrateBytes, fetched);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void describePackageVersionBridgesToTheRealKellnrSidecar() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME + "&version=" + VERSION)
|
||||
.then().statusCode(200)
|
||||
.body("packageVersion.version", equalTo(VERSION))
|
||||
.body("packageVersion.status", equalTo("Published"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A republish of an already-existing name/version is rejected, matching the Cargo Book's own
|
||||
* documented rule that "a publish is generally permanent" and a version "can never be
|
||||
* overwritten", confirmed live against Kellnr: it answers 400 with a body already shaped
|
||||
* exactly like the Cargo Book's own documented error response, which this test confirms is
|
||||
* forwarded to the client verbatim rather than swallowed into an opaque 500.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void repeatingTheExactSamePublishIsRejectedAsAnAlreadyExistingVersion() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(originalPublishBody)
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(400)
|
||||
.body("errors[0].detail", containsString("already exists"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void repositoriesAreIsolatedFromEachOther() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-cargo-repo")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/other-cargo-repo/de/mo/" + CRATE_NAME)
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void missingOrWrongDomainTokensAreUnauthorized() {
|
||||
given().get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
|
||||
given().header("Authorization", "not-a-real-token")
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/domain?domain=other-cargo-token-domain")
|
||||
.then().statusCode(200);
|
||||
String otherDomainToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=other-cargo-token-domain")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
given().header("Authorization", otherDomainToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes 10-NATIVE-STATUS for cargo: a plain {@code cargo add}/{@code cargo build} download of
|
||||
* an Archived version's real {@code .crate} must 404 against the live Kellnr sidecar, even
|
||||
* though the file itself is still sitting there untouched. Its own crate, not {@link
|
||||
* #CRATE_NAME}, so archiving it can't disturb any other ordered test in this class.
|
||||
*/
|
||||
@Test
|
||||
@Order(8)
|
||||
void archivingAVersionBlocksItsRealKellnrContentDownloadWhileLeavingTheBytesInPlace() throws IOException {
|
||||
String crateName = "archivecrate";
|
||||
byte[] crateBytes = buildCrate(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, crateBytes))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"versions\":[\"" + VERSION + "\"],\"targetStatus\":\"Archived\"}")
|
||||
.post("/v1/package/versions/update_status?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&format=cargo&package=" + crateName)
|
||||
.then().statusCode(200)
|
||||
.body("successfulVersions['" + VERSION + "'].status", equalTo("Archived"));
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + crateName + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(404);
|
||||
|
||||
// Proves the block above is this check's own override, not Kellnr having genuinely lost
|
||||
// the file: un-archiving must make the exact same bytes fetchable again, with nothing
|
||||
// re-published in between.
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"versions\":[\"" + VERSION + "\"],\"targetStatus\":\"Published\"}")
|
||||
.post("/v1/package/versions/update_status?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&format=cargo&package=" + crateName)
|
||||
.then().statusCode(200)
|
||||
.body("successfulVersions['" + VERSION + "'].status", equalTo("Published"));
|
||||
byte[] fetchedAfterUnarchive = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + crateName + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(crateBytes, fetchedAfterUnarchive);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code publish:BLOCK} set through the real {@code PutPackageOriginConfiguration} route must
|
||||
* refuse a real {@code cargo publish}, the same real-world gap this already closed for every
|
||||
* other native format. Its own crate, so no other ordered test is disturbed.
|
||||
*/
|
||||
@Test
|
||||
@Order(9)
|
||||
void publishBlockedByOriginConfigurationRefusesARealPublishUntilItIsLifted() throws IOException {
|
||||
String crateName = "originblockedcrate";
|
||||
byte[] published = buildCrate(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, published))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, REPO, "cargo", null, crateName, "BLOCK", "BLOCK");
|
||||
|
||||
byte[] nextVersionCrate = buildCrate(crateName, "2.0.0");
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(409);
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/" + sparseIndexPath(crateName))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""));
|
||||
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, REPO, "cargo", null, crateName, "ALLOW", "BLOCK");
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ListPackages} against a repository that has actually published through cargo, against
|
||||
* the real Kellnr container this whole class already shares: {@code KellnrSidecarClient} had
|
||||
* no {@code listPackages} override at all until this was added, so adding {@code cargo} to
|
||||
* {@code CONTAINER_BACKED_FORMATS} alone made every unfiltered or cargo-filtered {@code
|
||||
* ListPackages} request on any repository 500 before this fix, confirmed only by calling the
|
||||
* real action here rather than the sidecar client directly.
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
void listPackagesListsEveryRealCrateThisRepositoryHasPublished() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/packages?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo")
|
||||
.then().statusCode(200)
|
||||
.body("packages.package", hasItem(CRATE_NAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases this class's own Kellnr container (via a real ordered {@code @Test}, not {@code
|
||||
* @AfterAll}: Quarkus's own test extension can already be tearing down the HTTP listener by
|
||||
* the time a {@code @AfterAll} static method runs if this happens to be the last class in the
|
||||
* fork, so the request itself would fail with a connection reset) rather than leaving it for a
|
||||
* later, unrelated {@code /state/reset} call to stop as part of {@code ContainerTeardowns
|
||||
* #stopAll}'s own sequential sweep over every registered {@code ContainerTeardown}, cargo's
|
||||
* included: that sweep blocks whichever single HTTP request happens to trigger it on every
|
||||
* one of them, so a container left running here only extends some later, unrelated test's own
|
||||
* reset call rather than this class's own.
|
||||
*/
|
||||
@Test
|
||||
@Order(11)
|
||||
void releasesItsOwnKellnrContainerSoALaterUnrelatedResetDoesNotHaveToStopIt() {
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/** The real crates.io sparse-index bucketing rule for a name 9 characters long (4+ case). */
|
||||
private static String sparseIndexPath(String crateName) {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real binary wire body confirmed directly from the Cargo Book's own spec text, and live
|
||||
* against a real Kellnr container in part 1: a 4-byte little-endian metadata length, the JSON
|
||||
* metadata itself (here with one real, non-empty dependency, to prove a native publish's own
|
||||
* dependency list survives the round trip untouched, unlike {@code CopyPackageVersions}'s own
|
||||
* always-empty-deps path), then a 4-byte little-endian crate length and the crate itself.
|
||||
*/
|
||||
private static byte[] publishBody(String name, String version, byte[] crateBytes) {
|
||||
String metadataJson = "{\"name\":\"" + name + "\",\"vers\":\"" + version + "\",\"deps\":["
|
||||
+ "{\"name\":\"real-dependency\",\"version_req\":\"^1.0\",\"features\":[],\"optional\":false,"
|
||||
+ "\"default_features\":true,\"target\":null,\"kind\":\"normal\",\"registry\":null}],"
|
||||
+ "\"features\":{},\"authors\":[],\"description\":\"a test crate\",\"documentation\":null,"
|
||||
+ "\"homepage\":null,\"readme\":null,\"readme_file\":null,\"keywords\":[],\"categories\":[],"
|
||||
+ "\"license\":\"MIT\",\"license_file\":null,\"repository\":null,\"badges\":{},\"links\":null}";
|
||||
byte[] metadata = metadataJson.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
/** A real, minimal, valid {@code .crate}: a gzipped tarball with one real {@code Cargo.toml}. */
|
||||
private static byte[] buildCrate(String name, String version) throws IOException {
|
||||
String cargoToml = "[package]\nname = \"" + name + "\"\nversion = \"" + version + "\"\nedition = \"2021\"\n";
|
||||
byte[] cargoTomlBytes = cargoToml.getBytes(StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out);
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name + "-" + version + "/Cargo.toml");
|
||||
entry.setSize(cargoTomlBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(cargoTomlBytes);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.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.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Retains a real crate version from the real, live {@code public:crates-io} repository (not a
|
||||
* local fake), through the native per-format route, the way a real {@code cargo build}/{@code
|
||||
* cargo add} would. {@code libc} 0.2.169 is picked because it is small, stable, and confirmed
|
||||
* live against the real {@code index.crates.io}/{@code static.crates.io} production endpoints
|
||||
* (the index's own {@code cksum} for this exact version was confirmed to match the real
|
||||
* downloaded bytes' own SHA-256 before writing this test, not assumed). A genuine network
|
||||
* dependency, unlike every other sidecar-backed test here, which only ever talks to a container
|
||||
* Floci itself started; see {@code CodeArtifactCargoExternalConnectionImporterTest} for the
|
||||
* mocked, deterministic coverage of the claim/fence/mixed-origin/checksum logic this test does
|
||||
* not re-exercise, mirroring {@code CodeArtifactNuGetExternalConnectionDockerIntegrationTest}'s
|
||||
* own shape and reasoning.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactCargoExternalConnectionDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "cargo-external-connection-domain";
|
||||
private static final String REPO = "cargo-external-connection-repo";
|
||||
private static final String BLOCKED_REPO = "cargo-external-connection-blocked-repo";
|
||||
private static final String CRATE_NAME = "libc";
|
||||
private static final String VERSION = "0.2.169";
|
||||
|
||||
private static String bearerToken;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.cargo-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:crates-io")
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
|
||||
+ "&external-connection=public:crates-io")
|
||||
.then().statusCode(200);
|
||||
|
||||
bearerToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves {@link CodeArtifactCargoExternalConnectionImporter#mergeExternalVersions}'s own
|
||||
* reason for existing: the real upstream version line is visible here even though nothing
|
||||
* has ever been downloaded (so nothing is retained yet), which a real {@code cargo} client's
|
||||
* dependency resolver needs in order to ever choose this version at all. Run before the
|
||||
* download test below, so this genuinely proves the merge, not a locally-cached line.
|
||||
*/
|
||||
@Test
|
||||
@Order(1)
|
||||
void fetchingTheSparseIndexMergesInTheRealUpstreamVersionBeforeAnythingIsRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + CRATE_NAME + "\""))
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void fetchingAMissingCrateRetainsItFromTheRealCratesIoConnectionAndCountsItsBytes() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
assertEquals(0L, assetSizeBytesBefore);
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
|
||||
// A real .crate is a real gzip file: 0x1f 0x8b magic bytes, not asserting exact content
|
||||
// since the real artifact is out of this test's control.
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(1000));
|
||||
|
||||
assertEquals(assetSizeBytesBefore + fetched.length, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void refetchingTheSameVersionServesItWithoutRetainingItAgain() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
|
||||
assertEquals(assetSizeBytesBefore, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code BLOCK}ed package shows no upstream-only version either, matching every other
|
||||
* retention path's own "behave exactly as if the external content did not exist" rule, not
|
||||
* just refusing the download: a real {@code cargo} client's own resolver must not even see a
|
||||
* version this repository is configured never to retain.
|
||||
*/
|
||||
@Test
|
||||
@Order(4)
|
||||
void upstreamBlockPreventsBothRetentionAndTheIndexMerge() {
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, BLOCKED_REPO, "cargo", null, CRATE_NAME, "ALLOW", "BLOCK");
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/api/v1/crates/" + CRATE_NAME + "/"
|
||||
+ VERSION + "/download")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void aVersionTheRealRepositoryDoesNotHaveIsNeverRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME
|
||||
+ "/999.999.999/download")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms the fix every other format's own importer already needed (a successfully retained
|
||||
* version reporting an external, not internal, origin) holds for cargo too, against the real
|
||||
* sidecar's own retained version from {@link
|
||||
* #fetchingAMissingCrateRetainsItFromTheRealCratesIoConnectionAndCountsItsBytes}, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void aRetainedVersionReportsAnExternalOriginNotInternal() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("versions[0].version", equalTo(VERSION))
|
||||
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
|
||||
.body("versions[0].origin.domainEntryPoint.externalConnectionName", equalTo("public:crates-io"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A mixed-case real crate name, confirmed live against production before writing this test
|
||||
* (its real {@code cksum} matches its real downloaded bytes' own SHA-256): the Cargo Book
|
||||
* requires the sparse-index bucket path and filename to be lowercased, confirmed live too
|
||||
* (the real {@code index.crates.io} 404s at {@code In/fl/Inflector} and only resolves at
|
||||
* {@code in/fl/inflector}), while the download route needs the crate's own original case.
|
||||
* Its own repository, separate from {@link #REPO}, so this doesn't interleave with the
|
||||
* ordered sequence above.
|
||||
*/
|
||||
@Test
|
||||
@Order(7)
|
||||
void aMixedCaseCrateNameResolvesAndRetainsCorrectly() {
|
||||
String domain = "cargo-external-connection-mixed-case-domain";
|
||||
String repo = "cargo-external-connection-mixed-case-repo";
|
||||
String crateName = "Inflector";
|
||||
String version = "0.11.4";
|
||||
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/external-connection?domain=" + domain + "&repository=" + repo
|
||||
+ "&external-connection=public:crates-io")
|
||||
.then().statusCode(200);
|
||||
String token = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + domain)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
given().header("Authorization", token)
|
||||
.get("/codeartifact/cargo/" + domain + "/" + repo + "/" + sparseIndexPath(crateName))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + crateName + "\""))
|
||||
.body(containsString("\"vers\":\"" + version + "\""));
|
||||
|
||||
byte[] fetched = given().header("Authorization", token)
|
||||
.get("/codeartifact/cargo/" + domain + "/" + repo + "/api/v1/crates/" + crateName + "/" + version
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(100));
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every Kellnr container this class started (see {@code
|
||||
* CodeArtifactCargoDockerIntegrationTest#releasesItsOwnKellnrContainerSoALaterUnrelatedResetDoesNotHaveToStopIt}'s
|
||||
* own javadoc for why this is a real ordered {@code @Test} and not {@code @AfterAll}),
|
||||
* including the mixed-case test's own separate repository.
|
||||
*/
|
||||
@Test
|
||||
@Order(8)
|
||||
void releasesEveryKellnrContainerThisClassStarted() {
|
||||
given().header("Authorization", AUTH).delete("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=cargo-external-connection-mixed-case-domain&repository="
|
||||
+ "cargo-external-connection-mixed-case-repo")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/** The real crates.io sparse-index bucketing rule for {@link #CRATE_NAME} (a 4+-character
|
||||
* name): first two, then next two, characters. */
|
||||
private static String sparseIndexPath(String crateName) {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
|
||||
import io.floci.aws.services.codeartifact.model.ExternalConnection;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
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.assertThrows;
|
||||
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 CodeArtifactCargoExternalConnectionImporter}'s own decision logic: when it attempts a
|
||||
* real external-connection fetch at all, and what it writes back, mirroring {@link
|
||||
* CodeArtifactNuGetExternalConnectionImporterTest}'s own shape for {@code tryImport}, plus
|
||||
* dedicated cases for {@code mergeExternalVersions}, the one genuinely new piece this format
|
||||
* needs (see this importer's own javadoc for why). {@link KellnrSidecarClient} and {@link
|
||||
* CargoExternalConnectionClient} are both mocked, so no real network or Kellnr call ever happens
|
||||
* here; their own wire contracts have their own tests.
|
||||
*/
|
||||
class CodeArtifactCargoExternalConnectionImporterTest {
|
||||
|
||||
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_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
private static final byte[] CRATE_CONTENT = "crate-content".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final long EPISODE_ID = 7L;
|
||||
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CargoExternalConnectionClient externalConnectionClient;
|
||||
private CodeArtifactCargoExternalConnectionImporter importer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionClient = mock(CargoExternalConnectionClient.class);
|
||||
importer = new CodeArtifactCargoExternalConnectionImporter(service, kellnr, externalConnectionClient,
|
||||
new ObjectMapper());
|
||||
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(
|
||||
List.of(new ExternalConnection("public:crates-io", "cargo", "AVAILABLE")));
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), eq("EXTERNAL_UPSTREAM"))).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);
|
||||
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsFromExternalConnectionWhenNotFoundLocally() {
|
||||
stubRealIndexAndCrate(VERSION, CRATE_CONTENT);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("cargo"),
|
||||
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
|
||||
eq(PACKAGE_NAME + "-" + VERSION + ".crate"), eq((long) CRATE_CONTENT.length), any());
|
||||
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
"cargo", null, PACKAGE_NAME, 42L, REPO_ID);
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenNoCargoExternalConnectionIsConfigured() {
|
||||
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_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION),
|
||||
anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"EXTERNAL_UPSTREAM")).thenReturn(true);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION),
|
||||
anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
|
||||
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, "public:crates-io", RetentionOriginKind.EXTERNAL_CONNECTION, 42L))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(kellnr, 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(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(Optional.of("public:crates-io"));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
verify(externalConnectionClient, never()).fetchCrate(anyString(), anyString(), anyString(), any());
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotMislabelAVersionADirectPushWroteDuringTheRaceAsExternallyRetained() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndFinishesWhenTheRealIndexIsUnreachable() {
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenTheRealIndexNamesNoMatchingVersion() {
|
||||
byte[] index = indexLine("2.0.0", sha256Hex(CRATE_CONTENT)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(externalConnectionClient, never()).fetchCrate(anyString(), anyString(), anyString(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFetchThatThrowsPropagatesRatherThanBeingTreatedLikeAMissingCrate() {
|
||||
byte[] index = indexLine(VERSION, sha256Hex(CRATE_CONTENT)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
when(externalConnectionClient.fetchCrate(eq("public:crates-io"), eq(PACKAGE_NAME), eq(VERSION),
|
||||
any(Path.class))).thenThrow(new IllegalStateException("public registry unreachable"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, VERSION));
|
||||
|
||||
// Still runs its own bookkeeping on the way out, via the outer finally, rather than ever
|
||||
// leaving a claimed-but-never-finished retention attempt behind.
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsAnImportWhoseRealBytesDoNotMatchTheIndexsOwnCksum() {
|
||||
byte[] index = indexLine(VERSION, "0".repeat(64)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
stubFetchCrate(VERSION, CRATE_CONTENT);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
|
||||
stubRealIndexAndCrate(VERSION, CRATE_CONTENT);
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsLocalBytesUnchangedWhenNoConnectionConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
Optional<byte[]> local = Optional.of("local-bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
local);
|
||||
|
||||
assertEquals(local, merged);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsLocalBytesUnchangedWhenUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"EXTERNAL_UPSTREAM")).thenReturn(true);
|
||||
Optional<byte[]> local = Optional.of("local-bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
local);
|
||||
|
||||
assertEquals(local, merged);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsAddsUpstreamOnlyVersionLinesNotAlreadyLocal() {
|
||||
String localLine = indexLine("1.0.0", "a".repeat(64));
|
||||
String upstreamOnlyLine = indexLine("2.0.0", "b".repeat(64));
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of((localLine + "\n" + upstreamOnlyLine).getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.of((localLine + "\n").getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertTrue(merged.isPresent());
|
||||
String mergedText = new String(merged.get(), StandardCharsets.UTF_8);
|
||||
assertTrue(mergedText.contains("\"1.0.0\""));
|
||||
assertTrue(mergedText.contains("\"2.0.0\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsKeepsTheLocalLineForAVersionPresentInBoth() {
|
||||
String localLine = indexLine("1.0.0", "a".repeat(64));
|
||||
String upstreamLineSameVersion = indexLine("1.0.0", "different-cksum-should-never-win".repeat(2));
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamLineSameVersion.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.of(localLine.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertTrue(merged.isPresent());
|
||||
assertEquals(localLine, new String(merged.get(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsEmptyWhenBothLocalAndUpstreamAreEmpty() {
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(new byte[0]));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), merged);
|
||||
}
|
||||
|
||||
private static String indexLine(String version, String cksum) {
|
||||
return "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + version + "\",\"deps\":[],\"cksum\":\"" + cksum
|
||||
+ "\",\"features\":{},\"yanked\":false}";
|
||||
}
|
||||
|
||||
private void stubRealIndexAndCrate(String version, byte[] content) {
|
||||
byte[] index = indexLine(version, sha256Hex(content)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
stubFetchCrate(version, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code fetchCrate}'s real, streamed signature takes the destination {@link Path} to write
|
||||
* to, generated fresh by the importer itself for every real call, so a test fixture can't
|
||||
* name it in advance the way it could a plain {@code byte[]}-returning method: this answers
|
||||
* whatever path the importer actually passes by writing {@code content} straight to it, the
|
||||
* same real effect the real method has.
|
||||
*/
|
||||
private void stubFetchCrate(String version, byte[] content) {
|
||||
when(externalConnectionClient.fetchCrate(eq("public:crates-io"), eq(PACKAGE_NAME), eq(version),
|
||||
any(Path.class))).thenAnswer(invocation -> {
|
||||
Path destination = invocation.getArgument(3);
|
||||
Files.write(destination, content);
|
||||
return Optional.of(new CargoExternalConnectionClient.FetchedFile(content.length,
|
||||
sha256Hex(content)));
|
||||
});
|
||||
}
|
||||
|
||||
private static String sha256Hex(byte[] content) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(content));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1065,7 +1065,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", "nuget"), created.getSidecarContainerIds().keySet());
|
||||
assertEquals(Set.of("maven", "npm", "pypi", "nuget", "cargo"), created.getSidecarContainerIds().keySet());
|
||||
created.getSidecarContainerIds().values()
|
||||
.forEach(id -> assertTrue(id != null && !id.isBlank()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,508 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Wire-contract tests for {@link KellnrSidecarClient} against a JDK {@code HttpServer} standing
|
||||
* in for a running Kellnr container, shaped exactly like the real responses captured live against
|
||||
* a real Kellnr container earlier in this project. The container is registered in the manager's
|
||||
* pool directly, so readiness resolves to the fake server without any Docker daemon.
|
||||
*/
|
||||
class KellnrSidecarClientTest {
|
||||
|
||||
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("/api/v1/crates/config.json", exchange -> {
|
||||
byte[] body = "{\"dl\":\"/api/v1/crates/dl\",\"api\":\"\",\"auth-required\":false}"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
backend.start();
|
||||
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDownBackend() {
|
||||
backend.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsTrueForAPublishedVersion() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
assertTrue(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsFalseForAVersionThatWasNeverPublished() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
assertFalse(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "democrate", "9.9.9"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageExistsFalseWhenTheSparseIndexHasNeverBeenPublished() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
backend.createContext("/api/v1/crates/de/mo/democrate", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertFalse(client(manager).packageExists("cargo-repo-1", "dom", "repo", null, "democrate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackagesIsEmptyWhenTheRepositoryHasNoRunningContainerYet() {
|
||||
KellnrSidecarManager manager = manager();
|
||||
|
||||
assertTrue(client(manager).listPackages("cargo-repo-1", "dom", "repo").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackagesNamesEveryCrateAcrossAPaginatedReadOfTheRealListingRoute() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
List<String> requestedQueries = new CopyOnWriteArrayList<>();
|
||||
backend.createContext("/api/v1/ui/crates", exchange -> {
|
||||
requestedQueries.add(exchange.getRequestURI().getQuery());
|
||||
byte[] body;
|
||||
if (exchange.getRequestURI().getQuery().contains("page=0")) {
|
||||
body = ("{\"crates\":[{\"name\":\"democrate\",\"version\":\"1.0.0\"},"
|
||||
+ "{\"name\":\"othercrate\",\"version\":\"2.0.0\"}],\"page_size\":100,\"page\":0}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
} else {
|
||||
body = "{\"crates\":[],\"page_size\":100,\"page\":1}".getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
List<RepositorySidecarManager.PackageIdentifier> packages = client(manager).listPackages("cargo-repo-1",
|
||||
"dom", "repo");
|
||||
|
||||
assertEquals(List.of(new RepositorySidecarManager.PackageIdentifier(null, "democrate"),
|
||||
new RepositorySidecarManager.PackageIdentifier(null, "othercrate")), packages);
|
||||
assertEquals(2, requestedQueries.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetGetsTheRealDownloadPath() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
backend.createContext("/api/v1/crates/dl/democrate/1.0.0/download", exchange -> {
|
||||
byte[] body = "crate bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0", "democrate-1.0.0.crate");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("crate bytes", new String(result.get(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetEmptyWhenTheAssetNameIsNotTheDeterministicForm() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0", "wrong-name.crate");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #fetchPackageVersionAssetGetsTheRealDownloadPath}'s own streamed sibling: same wire
|
||||
* behavior, but the caller gets an open {@link InputStream} plus the real {@code
|
||||
* Content-Length} instead of an already-resident {@code byte[]}.
|
||||
*/
|
||||
@Test
|
||||
void fetchPackageVersionAssetStreamedGetsTheRealDownloadPath() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
backend.createContext("/api/v1/crates/dl/democrate/1.0.0/download", exchange -> {
|
||||
byte[] body = "crate bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<RepositorySidecarManager.StreamedAsset> result = client(manager).fetchPackageVersionAssetStreamed(
|
||||
"cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0", "democrate-1.0.0.crate");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
try (InputStream in = result.get().content()) {
|
||||
assertEquals("crate bytes", new String(in.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
assertEquals(11, result.get().contentLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackageVersionAssetNamesNamesTheOneDeterministicAsset() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
List<String> result = client(manager).listPackageVersionAssetNames("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0");
|
||||
|
||||
assertEquals(List.of("democrate-1.0.0.crate"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackageVersionsReadsEachEntrysPubtime() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndexLines("democrate",
|
||||
sparseIndexLine("democrate", "1.0.0", "2026-01-15T10:00:00Z"),
|
||||
sparseIndexLine("democrate", "2.0.0", "2026-02-20T10:00:00Z"));
|
||||
|
||||
List<RepositorySidecarManager.PackageVersionTimestamp> result = client(manager)
|
||||
.listPackageVersions("cargo-repo-1", "dom", "repo", null, "democrate");
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals("1.0.0", result.get(0).version());
|
||||
assertEquals(Instant.parse("2026-01-15T10:00:00Z"), result.get(0).publishedTime());
|
||||
assertEquals("2.0.0", result.get(1).version());
|
||||
assertEquals(Instant.parse("2026-02-20T10:00:00Z"), result.get(1).publishedTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* The real crates.io sparse-index bucketing rule for a 4+ character name: first two
|
||||
* characters, then next two, then the name itself, confirmed live against a real Kellnr
|
||||
* container earlier in this project.
|
||||
*/
|
||||
@Test
|
||||
void sparseIndexPathBucketsAFourCharacterOrLongerNameByItsFirstFourCharacters() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
backend.createContext("/api/v1/crates/se/rd/serde", exchange -> {
|
||||
byte[] body = sparseIndexLine("serde", "1.0.0", "2026-01-15T10:00:00Z").getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertTrue(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "serde", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePackageVersionAssetPublishesTheRealBinaryWireBody() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
AtomicReference<String> receivedCookie = new AtomicReference<>();
|
||||
AtomicReference<byte[]> receivedBody = new AtomicReference<>();
|
||||
AtomicReference<String> receivedAuthorization = new AtomicReference<>();
|
||||
respondToLogin();
|
||||
respondToAddToken(cookie -> receivedCookie.set(cookie));
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
receivedAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
|
||||
receivedBody.set(exchange.getRequestBody().readAllBytes());
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", "crate bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// The token-mint call used the admin session cookie, and the real publish call used the
|
||||
// minted token (no "Bearer" prefix, confirmed live against a real Kellnr container) rather
|
||||
// than the cookie itself.
|
||||
assertEquals("kellnr_session_id=test-session", receivedCookie.get());
|
||||
assertEquals("tok-1", receivedAuthorization.get());
|
||||
byte[] body = receivedBody.get();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(body).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int metadataLength = buffer.getInt();
|
||||
byte[] metadata = new byte[metadataLength];
|
||||
buffer.get(metadata);
|
||||
assertTrue(new String(metadata, StandardCharsets.UTF_8).contains("\"name\":\"democrate\""));
|
||||
assertTrue(new String(metadata, StandardCharsets.UTF_8).contains("\"vers\":\"1.0.0\""));
|
||||
int crateLength = buffer.getInt();
|
||||
byte[] crate = new byte[crateLength];
|
||||
buffer.get(crate);
|
||||
assertEquals("crate bytes", new String(crate, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link KellnrSidecarClient#storePackageVersionAsset(String, String, String, String, String,
|
||||
* String, String, byte[])}'s own streamed sibling: the staged file's real content ends up in
|
||||
* the same binary wire body.
|
||||
*/
|
||||
@Test
|
||||
void storePackageVersionAssetStreamedSendsTheStagedFilesRealContent() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
Path staged = Files.createTempFile("kellnr-client-test-", ".tmp");
|
||||
Files.writeString(staged, "staged crate bytes");
|
||||
respondToLogin();
|
||||
respondToAddToken(cookie -> { });
|
||||
AtomicReference<byte[]> receivedBody = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
receivedBody.set(exchange.getRequestBody().readAllBytes());
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", staged, Files.size(staged));
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.wrap(receivedBody.get()).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int metadataLength = buffer.getInt();
|
||||
buffer.position(buffer.position() + metadataLength);
|
||||
int crateLength = buffer.getInt();
|
||||
byte[] crate = new byte[crateLength];
|
||||
buffer.get(crate);
|
||||
assertEquals("staged crate bytes", new String(crate, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePackageVersionAssetMintsOnlyOneTokenAcrossSeveralPublishes() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
List<String> mintedTokenNames = new CopyOnWriteArrayList<>();
|
||||
backend.createContext("/api/v1/user/add_token", exchange -> {
|
||||
mintedTokenNames.add("minted");
|
||||
byte[] body = "{\"name\":\"floci\",\"token\":\"tok-1\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
KellnrSidecarClient client = client(manager);
|
||||
|
||||
client.storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", "a".getBytes(StandardCharsets.UTF_8));
|
||||
client.storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "2.0.0",
|
||||
"democrate-2.0.0.crate", "b".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertEquals(1, mintedTokenNames.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageDeletesViaTheAdminRouteWithTheSessionCookie() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
AtomicReference<String> receivedQuery = new AtomicReference<>();
|
||||
AtomicReference<String> receivedCookie = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/ui/delete_crate", exchange -> {
|
||||
receivedQuery.set(exchange.getRequestURI().getQuery());
|
||||
receivedCookie.set(exchange.getRequestHeaders().getFirst("Cookie"));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).deletePackage("cargo-repo-1", "dom", "repo", null, "democrate");
|
||||
|
||||
assertEquals("name=democrate", receivedQuery.get());
|
||||
assertEquals("kellnr_session_id=test-session", receivedCookie.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageVersionAssetDeletesViaTheAdminRouteWithBothNameAndVersion() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
AtomicReference<String> receivedQuery = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/ui/delete_version", exchange -> {
|
||||
receivedQuery.set(exchange.getRequestURI().getQuery());
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).deletePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate");
|
||||
|
||||
assertEquals("name=democrate&version=1.0.0", receivedQuery.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageToleratesAnAlreadyGoneCoordinate() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
backend.createContext("/api/v1/ui/delete_crate", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertFalse(catches(() -> client(manager).deletePackage("cargo-repo-1", "dom", "repo", null, "democrate")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A future {@code CodeArtifactCargoController}'s own push handler is expected to synchronize
|
||||
* on this exact object for a repository, the same one {@link KellnrSidecarClient
|
||||
* #storePackageVersionAsset} and {@link KellnrSidecarClient#deletePackage} themselves take, 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() {
|
||||
KellnrSidecarClient client = client(manager());
|
||||
|
||||
Object repo1Again = client.lockFor("cargo-repo-1");
|
||||
|
||||
assertSame(client.lockFor("cargo-repo-1"), repo1Again);
|
||||
assertNotSame(client.lockFor("cargo-repo-1"), client.lockFor("cargo-repo-2"));
|
||||
}
|
||||
|
||||
private static boolean catches(ThrowingRunnable runnable) {
|
||||
try {
|
||||
runnable.run();
|
||||
return false;
|
||||
} catch (RuntimeException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ThrowingRunnable {
|
||||
void run();
|
||||
}
|
||||
|
||||
private void respondToLogin() {
|
||||
backend.createContext("/api/v1/user/login", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "kellnr_session_id=test-session; Path=/");
|
||||
byte[] body = "{\"user\":\"admin\",\"is_admin\":true,\"is_logged_in\":true}"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private void respondToAddToken(Consumer<String> receivedCookie) {
|
||||
backend.createContext("/api/v1/user/add_token", exchange -> {
|
||||
receivedCookie.accept(exchange.getRequestHeaders().getFirst("Cookie"));
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] body = "{\"name\":\"floci\",\"token\":\"tok-1\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private void respondWithSparseIndex(String packageName, String version) {
|
||||
respondWithSparseIndexLines(packageName, sparseIndexLine(packageName, version, "2026-01-15T10:00:00Z"));
|
||||
}
|
||||
|
||||
private void respondWithSparseIndexLines(String packageName, String... lines) {
|
||||
String body = String.join("\n", lines);
|
||||
backend.createContext(sparseIndexContextPath(packageName), exchange -> {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private static String sparseIndexContextPath(String packageName) {
|
||||
String first2 = packageName.substring(0, 2);
|
||||
String next2 = packageName.substring(2, 4);
|
||||
return "/api/v1/crates/" + first2 + "/" + next2 + "/" + packageName;
|
||||
}
|
||||
|
||||
private static String sparseIndexLine(String packageName, String version, String pubtime) {
|
||||
return "{\"name\":\"" + packageName + "\",\"vers\":\"" + version + "\",\"deps\":[],\"cksum\":\"abc\","
|
||||
+ "\"features\":{},\"yanked\":false,\"pubtime\":\"" + pubtime + "\",\"v\":1}";
|
||||
}
|
||||
|
||||
private KellnrSidecarClient client(KellnrSidecarManager manager) {
|
||||
return new KellnrSidecarClient(manager, new ObjectMapper(), HttpClient.newHttpClient());
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(KellnrSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = KellnrSidecarManager.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));
|
||||
// The real startContainer() always mints and stores a password together with starting the
|
||||
// container; this fake seeding stands in for both at once via the manager's own
|
||||
// package-private test seam, not reflection, since that one is new to this class.
|
||||
manager.seedAdminPasswordForTest(key, "test-admin-password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.http.HttpClient;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* Checks teardown wiring and use leases without a Docker daemon. Containers are seeded directly
|
||||
* into the pool; the manager must defer deletion while a request is active and retain failed
|
||||
* removal for a later teardown retry. Mirrors {@link BagetterSidecarManagerTest} exactly: same
|
||||
* per-repository container lease shape, different sidecar.
|
||||
*/
|
||||
class KellnrSidecarManagerTest {
|
||||
|
||||
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 {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
seedPooledContainer(manager, "cargo-repo-2", "tracked-kellnr-2", "http://127.0.0.1:1");
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-2", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
|
||||
KellnrSidecarManager manager = manager();
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseWaitsForTheLastCargoRequestBeforeStoppingItsContainer() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
RepositorySidecarManager client = new KellnrSidecarClient(manager, new ObjectMapper(),
|
||||
HttpClient.newHttpClient());
|
||||
client.registerRepository("cargo-repo-1");
|
||||
client.beginUse("cargo-repo-1");
|
||||
|
||||
client.release("cargo-repo-1");
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
assertThrows(IllegalStateException.class, () -> client.beginUse("cargo-repo-1"));
|
||||
|
||||
client.endUse("cargo-repo-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRemovalRemainsRetryableAfterTheLastUse() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
manager.registerRepository("cargo-repo-1");
|
||||
manager.beginUse("cargo-repo-1");
|
||||
manager.release("cargo-repo-1");
|
||||
doThrow(new IllegalStateException("Docker unavailable")).doNothing().when(lifecycleManager)
|
||||
.stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
|
||||
assertDoesNotThrow(() -> manager.endUse("cargo-repo-1"));
|
||||
assertTrue(manager.isRunning("cargo-repo-1"));
|
||||
assertThrows(IllegalStateException.class, () -> manager.beginUse("cargo-repo-1"));
|
||||
assertThrows(IllegalStateException.class, () -> manager.endUse("cargo-repo-1"));
|
||||
|
||||
manager.stopManagedContainers();
|
||||
assertFalse(manager.isRunning("cargo-repo-1"));
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void teardownKeepsAnActiveUseUntilTheRequestFinishes() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
manager.registerRepository("cargo-repo-1");
|
||||
manager.beginUse("cargo-repo-1");
|
||||
|
||||
manager.stopManagedContainers();
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
assertThrows(IllegalStateException.class, () -> manager.beginUse("cargo-repo-1"));
|
||||
|
||||
manager.endUse("cargo-repo-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(KellnrSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = KellnrSidecarManager.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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user