fix(codeartifact): stream asset uploads instead of buffering them as byte[] (#8170)

PublishPackageVersion and the Maven, pypi, and NuGet wire-protocol endpoints all
received the request body as a single byte[] before any size check ran, so the
real, documented 5 GB asset quota never actually applied: an array is capped at
~2.147 GB (Integer.MAX_VALUE), so a legitimately-sized multi-GB asset either
failed with an OOM or never got far enough to hit the quota check at all.

Reworks the write path for all four formats to stream through a staged file
instead of a resident array:

- AssetDigestingInputStream computes MD5/SHA-1/SHA-256/SHA-512 and enforces the
  5 GB cap in one pass while the body is read, rather than after it's fully
  buffered.
- CodeArtifactService.stageAssetBody/deleteStagedAssetBody give every upload
  path a single, consistent staged-file lifecycle; existing byte[]-based
  entry points (CopyPackageVersions, small in-process metadata writes) are
  left as additive overloads, not replaced, so ~120 existing direct-call test
  fixtures keep working unchanged.
- MultipartFormParser.extractFilePart streams a pypi/NuGet multipart body from
  disk in fixed-size chunks with a carried-over overlap window, so a boundary
  marker that straddles two reads is still found correctly, without ever
  holding the whole envelope (or the file part inside it) in one array. Text
  fields are bounded both individually and in aggregate, so a real long
  pypi description doesn't get rejected but many small fields together still
  can't accumulate the whole envelope on the heap.
- Every sidecar write (Reposilite, pypiserver, BaGetter) now has a
  Path/InputStream-based overload alongside its existing byte[] one, using
  HttpRequest.BodyPublishers.ofFile/concat instead of a resident buffer.
  Verdaccio's own write streams the base64-encoded tarball through a piped
  JDK Base64 encoder instead of building one large encoded string, and a
  writer-side read failure now fails the publish outright instead of risking
  a truncated tarball published under hashes computed from the whole file.
- Every large-transfer HTTP call site's timeout now scales with the content
  length (SidecarUriUtils.transferTimeout) instead of a flat 30 seconds, which
  a multi-GB transfer can legitimately exceed.

Manually verified against a packaged jar running under a 1 GB heap cap: a 3 GiB
Maven deploy, a 3 GiB pypi twine-shaped upload, and a 3.2 GB NuGet push each
completed with no OOM and round-tripped byte-identical. Documents two related,
pre-existing ceilings that this change does not and cannot remove on its own:
the emulator's own global HTTP body-size cap (FLOCI_PROTOCOLS_MAX_REQUEST_SIZE,
2048 MB by default) still caps any single request below the real 5 GB quota
until raised, and the generic format's in-memory storage mode still holds an
asset as one byte[].
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-12 23:30:30 -04:00
1 parent c1c1c2475f
commit a3eea94899
54 files changed
+4614 -838

No files matched your search

@@ -1,20 +1,30 @@
package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.Random;
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;
class MultipartFormParserTest {
private static final String BOUNDARY = "boundary123";
@TempDir
Path tempDir;
@Test
void extractBoundaryReadsTheParameterRegardlessOfQuoting() {
assertEquals(Optional.of("abc"), MultipartFormParser.extractBoundary("multipart/form-data; boundary=abc"));
@@ -74,6 +84,160 @@ class MultipartFormParserTest {
assertTrue(form.file().isEmpty());
}
@Test
void extractFilePartSeparatesTextFieldsFromTheFilePart() throws IOException {
byte[] body = multipart(
field("name", "requests"),
field("version", "2.34.2"),
file("content", "requests-2.34.2-py3-none-any.whl", "application/octet-stream",
"fake wheel bytes"));
Path staged = stage(body);
Path destination = tempDir.resolve("extracted");
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY, destination);
assertEquals("requests", form.fields().get("name"));
assertEquals("2.34.2", form.fields().get("version"));
assertFalse(form.fields().containsKey("content"));
assertTrue(form.file().isPresent());
MultipartFormParser.ExtractedFile file = form.file().get();
assertEquals("content", file.fieldName());
assertEquals("requests-2.34.2-py3-none-any.whl", file.filename());
assertEquals("application/octet-stream", file.contentType());
assertEquals("fake wheel bytes", Files.readString(destination, StandardCharsets.UTF_8));
}
@Test
void extractFilePartReturnsAnEmptyFileWhenNoPartCarriesAFilename() throws IOException {
byte[] body = multipart(field("key", "value"));
Path staged = stage(body);
Path destination = tempDir.resolve("extracted");
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY, destination);
assertEquals("value", form.fields().get("key"));
assertTrue(form.file().isEmpty());
assertFalse(Files.exists(destination));
}
@Test
void extractFilePartPreservesBinaryContentThatContainsCrlfBytes() throws IOException {
byte[] binary = {0x50, 0x4B, 0x03, 0x04, '\r', '\n', 0x00, (byte) 0xFF};
byte[] body = multipart(filePart("content", "binary.bin", "application/octet-stream", binary));
Path staged = stage(body);
Path destination = tempDir.resolve("extracted");
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY, destination);
assertTrue(form.file().isPresent());
assertArrayEquals(binary, Files.readAllBytes(destination));
}
@Test
void extractFilePartOnAnEmptyOrMalformedBodyReturnsNoFieldsAndNoFile() throws IOException {
Path staged = stage(new byte[0]);
Path destination = tempDir.resolve("extracted");
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY, destination);
assertTrue(form.fields().isEmpty());
assertTrue(form.file().isEmpty());
}
@Test
void extractFilePartRejectsABodyThatNeverClosesAPart() throws IOException {
byte[] malformed = ("--" + BOUNDARY + "\r\nContent-Disposition: form-data; name=\"x\"; filename=\"f\"\r\n\r\n"
+ "unterminated content, no closing boundary at all").getBytes(StandardCharsets.UTF_8);
Path staged = stage(malformed);
Path destination = tempDir.resolve("extracted");
assertThrows(IOException.class, () -> MultipartFormParser.extractFilePart(staged, BOUNDARY, destination));
}
/**
* {@code extractFilePart}'s own boundary search must still find a boundary marker correctly
* even when it straddles two separate chunk reads of the staged file, not just when it lands
* cleanly inside one. Rather than hand-computing the exact byte offset its internal chunk size
* uses, this sweeps the file-part content length across a window around the one power-of-two
* size (64 KiB) any reasonable streaming implementation would pick, so at least one case in
* the sweep is guaranteed to straddle whatever chunk size the implementation actually uses,
* and checks every case against {@code parse}'s own byte[]-based result as the oracle.
*/
@Test
void extractFilePartFindsABoundaryThatStraddlesAChunkReadBoundary() throws IOException {
Random random = new Random(42);
int chunkSize = 64 * 1024;
for (int offset = -16; offset <= 16; offset++) {
int contentLength = chunkSize + offset;
byte[] content = new byte[contentLength];
random.nextBytes(content);
byte[] body = multipart(
field("name", "pkg"),
filePart("content", "asset.bin", "application/octet-stream", content));
MultipartFormParser.ParsedForm oracle = MultipartFormParser.parse(body, BOUNDARY);
Path staged = stage(body);
Path destination = tempDir.resolve("extracted-" + offset);
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY,
destination);
assertEquals(oracle.fields().get("name"), form.fields().get("name"), "offset " + offset);
assertArrayEquals(oracle.file().orElseThrow().content(), Files.readAllBytes(destination),
"offset " + offset);
}
}
/**
* The sweep above only proves the delimiter itself is still <em>found</em> correctly when it
* straddles a chunk read; it uses random content, so the delimiter's own match position inside
* the reconstructed buffer always lands comfortably past the first couple of bytes. This
* covers a narrower, previously-missed case: a chunk read that happens to end with EXACTLY the
* delimiter's own leading bytes already in hand, so the match completes at index 0 or 1 of the
* very next read. The CRLF immediately before the delimiter must still be trimmed in that case
* too, even though those two bytes were read in the PRIOR chunk, not the one the match itself
* was found in — a real streaming implementation has no second chance to go back and un-write
* bytes it already flushed to the sink.
*
* <p>The exact content length that lands the match at index 0/1 is not simply
* {@code chunkSize - delimiter.length} from this test's own vantage point: the body's leading
* {@code name} field is parsed first, and whatever few bytes {@code copyUntilDelimiter}'s own
* pushback scanner is left holding once that field's own delimiter is found get served back out
* on this part's very first read before the underlying file is touched again, shifting every
* later chunk boundary by that same, otherwise-unpredictable amount. Rather than hand-deriving
* that shift, this sweeps a window comfortably wider than one delimiter's own length around the
* one power-of-two chunk size (64 KiB) any reasonable implementation would pick, so the sweep
* is guaranteed to cross the real critical offset wherever the actual shift places it; confirmed
* empirically to land at content lengths 65328/65329 bytes for this exact body shape, well
* inside the swept window.
*/
@Test
void extractFilePartTrimsTheTrailingCrlfWhenTheDelimiterLandsAtTheVeryStartOfAChunkRead() throws IOException {
int chunkSize = 64 * 1024;
for (int offset = -300; offset <= 50; offset += 1) {
int contentLength = chunkSize + offset;
byte[] content = new byte[contentLength];
Arrays.fill(content, (byte) 'F');
byte[] body = multipart(
field("name", "pkg"),
filePart("content", "asset.bin", "application/octet-stream", content));
Path staged = stage(body);
Path destination = tempDir.resolve("extracted-offset-" + offset);
MultipartFormParser.ExtractedForm form = MultipartFormParser.extractFilePart(staged, BOUNDARY,
destination);
assertEquals("pkg", form.fields().get("name"), "offset " + offset);
assertArrayEquals(content, Files.readAllBytes(destination), "offset " + offset);
}
}
private Path stage(byte[] content) throws IOException {
Path staged = Files.createTempFile(tempDir, "staged", ".bin");
Files.write(staged, content);
return staged;
}
private static void assertArrayEqualsExactly(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
@@ -0,0 +1,30 @@
package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StreamingResponsesTest {
@Test
void responseThatFailsToBuildClosesTheBodyStream() {
AtomicBoolean closed = new AtomicBoolean();
InputStream body = new ByteArrayInputStream(new byte[16]) {
@Override
public void close() {
closed.set(true);
}
};
assertThrows(NullPointerException.class, () -> StreamingResponses.streamingResponse(body, stream -> {
throw new NullPointerException("Last-Modified is missing");
}));
assertTrue(closed.get(), "the body stream was left open");
}
}
@@ -0,0 +1,99 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
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.Random;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AssetDigestingInputStreamTest {
@Test
void computesEveryAssetHashAlgorithmInOnePass() throws IOException, NoSuchAlgorithmException {
byte[] content = new byte[1024 * 1024 + 37];
new Random(7).nextBytes(content);
AssetDigestingInputStream digesting = new AssetDigestingInputStream(
new ByteArrayInputStream(content), content.length);
byte[] buffer = new byte[4096];
int read;
while ((read = digesting.read(buffer)) >= 0) {
assertEquals(read >= 0, true);
}
assertEquals((long) content.length, digesting.size());
for (String algorithm : new String[] {"MD5", "SHA-1", "SHA-256", "SHA-512"}) {
String expected = HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(content));
assertEquals(expected, digesting.hashesHex().get(algorithm), algorithm);
}
}
@Test
void throwsOnceTheCapIsExceededMidStream() {
byte[] content = new byte[10_000];
AssetDigestingInputStream digesting = new AssetDigestingInputStream(new ByteArrayInputStream(content), 100);
assertThrows(AssetDigestingInputStream.AssetTooLargeException.class, () -> {
byte[] buffer = new byte[256];
int read;
while ((read = digesting.read(buffer)) >= 0) {
// keep reading until the cap trips
}
});
}
@Test
void readOneByteAtATimeStillUpdatesTheDigest() throws IOException, NoSuchAlgorithmException {
byte[] content = "hello world".getBytes();
AssetDigestingInputStream digesting = new AssetDigestingInputStream(
new ByteArrayInputStream(content), content.length);
int next;
while ((next = digesting.read()) >= 0) {
assertEquals(true, next >= 0 && next <= 255);
}
String expected = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));
assertEquals(expected, digesting.hashesHex().get("SHA-256"));
assertEquals((long) content.length, digesting.size());
}
/** Every external-connection client's own streamed fetch shares this one copy helper. */
@Test
void copyCappedWritesTheRealBytesAndReportsTheirSize() throws IOException {
byte[] content = "tarball-content".getBytes();
Path destination = Files.createTempFile("asset-digesting-input-stream-test-", ".bin");
try {
long size = AssetDigestingInputStream.copyCapped(new ByteArrayInputStream(content), destination,
content.length);
assertEquals((long) content.length, size);
assertArrayEquals(content, Files.readAllBytes(destination));
} finally {
Files.deleteIfExists(destination);
}
}
@Test
void copyCappedThrowsOnceTheCapIsExceededMidCopy() throws IOException {
byte[] content = new byte[10_000];
Path destination = Files.createTempFile("asset-digesting-input-stream-test-", ".bin");
try {
assertThrows(AssetDigestingInputStream.AssetTooLargeException.class,
() -> AssetDigestingInputStream.copyCapped(new ByteArrayInputStream(content), destination, 100));
} finally {
Files.deleteIfExists(destination);
}
}
}
@@ -10,10 +10,13 @@ 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.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
@@ -79,6 +82,63 @@ class BagetterSidecarClientTest {
assertEquals("nupkg bytes", new String(result.get(), StandardCharsets.UTF_8));
}
/**
* {@link #fetchPackageVersionAssetGetsTheFlatContainerNupkgPath}'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 fetchPackageVersionAssetStreamedGetsTheFlatContainerNupkgPath() throws Exception {
BagetterSidecarManager manager = manager();
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
respondWithVersions("demo-pkg", "1.0.0");
backend.createContext("/v3/package/demo-pkg/1.0.0/demo-pkg.1.0.0.nupkg", exchange -> {
byte[] body = "nupkg bytes".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
Optional<RepositorySidecarManager.StreamedAsset> result = client(manager).fetchPackageVersionAssetStreamed(
"nuget-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0", "demo-pkg.1.0.0.nupkg");
assertTrue(result.isPresent());
try (InputStream in = result.get().content()) {
assertEquals("nupkg bytes", new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
assertEquals(11, result.get().contentLength());
}
/**
* {@link BagetterSidecarClient#storePackageVersionAsset(String, String, String, String,
* String, String, String, Path, long)}'s own wire contract: the staged file's real content
* ends up in the multipart push's {@code package} part, built via {@code BodyPublishers
* .concat} rather than one combined array the way the {@code byte[]} overload still needs.
*/
@Test
void storePackageVersionAssetStreamedSendsTheStagedFilesRealContent() throws Exception {
BagetterSidecarManager manager = manager();
seedPooledContainer(manager, "nuget-repo-1", "tracked-bagetter-1", backendUrl);
Path staged = Files.createTempFile("bagetter-client-test-", ".tmp");
Files.writeString(staged, "staged nupkg bytes");
AtomicReference<byte[]> received = new AtomicReference<>();
backend.createContext("/api/v2/package", exchange -> {
received.set(exchange.getRequestBody().readAllBytes());
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
try {
client(manager).storePackageVersionAsset("nuget-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0",
"demo-pkg.1.0.0.nupkg", staged, Files.size(staged));
} finally {
Files.deleteIfExists(staged);
}
String body = new String(received.get(), StandardCharsets.UTF_8);
assertTrue(body.contains("staged nupkg bytes"));
}
/**
* AWS normalizes NuGet versions (leading zeroes removed): a caller asking for {@code 1.00.0}
* must still find the version BaGetter itself lists as {@code 1.0.0}.
@@ -3,13 +3,22 @@ package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.floci.aws.services.codeartifact.ReposiliteSidecarClient.DeployOutcome;
import io.floci.aws.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact;
import io.floci.aws.services.codeartifact.ReposiliteSidecarClient.StreamedArtifact;
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.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
@@ -18,6 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -58,6 +68,20 @@ class CodeArtifactMavenControllerTest {
when(service.resolveAuthorizationToken("some-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope(OWNER, REGION)));
when(service.ensureFormatContainerId("maven", REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(REPO_ID);
// service is a mock, so its own real stageAssetBody (which the controller now calls to
// stream a deploy's body to disk) never runs; stubbed here to actually stage to a real
// temp file, the same real behavior the controller depends on, so content-length/byte
// accounting downstream of it reflects what was actually uploaded rather than a null Path.
when(service.stageAssetBody(any())).thenAnswer(invocation -> {
InputStream in = invocation.getArgument(0);
Path staged = Files.createTempFile("maven-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());
}
/**
@@ -70,11 +94,12 @@ class CodeArtifactMavenControllerTest {
*/
@Test
void aSecondRequestForBareMetadataStillAttemptsAFreshImportEvenWhenALocalCopyAlreadyExists() {
FetchedArtifact stale = new FetchedArtifact("<metadata/>".getBytes(StandardCharsets.UTF_8),
"application/xml");
FetchedArtifact refreshed = new FetchedArtifact("<metadata><refreshed/></metadata>"
.getBytes(StandardCharsets.UTF_8), "application/xml");
when(reposilite.fetchArtifact(REPO_ID, METADATA_GAV)).thenReturn(Optional.of(stale))
StreamedArtifact stale = new StreamedArtifact(
new ByteArrayInputStream("<metadata/>".getBytes(StandardCharsets.UTF_8)), 11, "application/xml");
byte[] refreshedBytes = "<metadata><refreshed/></metadata>".getBytes(StandardCharsets.UTF_8);
StreamedArtifact refreshed = new StreamedArtifact(new ByteArrayInputStream(refreshedBytes),
refreshedBytes.length, "application/xml");
when(reposilite.fetchArtifactStreamed(REPO_ID, METADATA_GAV)).thenReturn(Optional.of(stale))
.thenReturn(Optional.of(refreshed));
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, METADATA_GAV))
.thenReturn(true);
@@ -83,7 +108,7 @@ class CodeArtifactMavenControllerTest {
assertEquals(200, response.getStatus());
assertEquals("<metadata><refreshed/></metadata>",
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
new String(readEntity(response), StandardCharsets.UTF_8));
verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, METADATA_GAV);
}
@@ -95,9 +120,10 @@ class CodeArtifactMavenControllerTest {
@Test
void aFixedVersionAssetIsNotReimportedOnceALocalCopyAlreadyExists() {
String versionGav = "com/example/widget/1.0/widget-1.0.jar";
FetchedArtifact existing = new FetchedArtifact("real-bytes".getBytes(StandardCharsets.UTF_8),
byte[] realBytes = "real-bytes".getBytes(StandardCharsets.UTF_8);
StreamedArtifact existing = new StreamedArtifact(new ByteArrayInputStream(realBytes), realBytes.length,
"application/java-archive");
when(reposilite.fetchArtifact(REPO_ID, versionGav)).thenReturn(Optional.of(existing));
when(reposilite.fetchArtifactStreamed(REPO_ID, versionGav)).thenReturn(Optional.of(existing));
Response response = controller.fetch(headers, DOMAIN, REPOSITORY, versionGav);
@@ -105,6 +131,16 @@ class CodeArtifactMavenControllerTest {
verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any());
}
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();
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK must refuse a real mvn
* deploy the way PublishPackageVersion already refuses it for the generic format, before
@@ -115,10 +151,10 @@ class CodeArtifactMavenControllerTest {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, "com/example/widget/1.0/widget-1.0.jar",
"jar-bytes".getBytes(StandardCharsets.UTF_8));
new ByteArrayInputStream("jar-bytes".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(reposilite, never()).deployArtifact(any(), any(), any(Path.class));
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
@@ -133,10 +169,10 @@ class CodeArtifactMavenControllerTest {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, METADATA_GAV,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
new ByteArrayInputStream("<metadata/>".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(reposilite, never()).deployArtifact(any(), any(), any(Path.class));
}
/**
@@ -152,11 +188,11 @@ class CodeArtifactMavenControllerTest {
for (String gav : List.of("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml",
"com/example/widget/1.0-SNAPSHOT/maven-metadata.xml.sha1")) {
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, gav,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
new ByteArrayInputStream("<metadata/>".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.getStatus(), gav);
}
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(reposilite, never()).deployArtifact(any(), any(), any(Path.class));
}
@Test
@@ -180,10 +216,11 @@ class CodeArtifactMavenControllerTest {
blockPublish("com.example", "widget-SNAPSHOT");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY,
"com/example/widget-SNAPSHOT/maven-metadata.xml", "<metadata/>".getBytes(StandardCharsets.UTF_8));
"com/example/widget-SNAPSHOT/maven-metadata.xml",
new ByteArrayInputStream("<metadata/>".getBytes(StandardCharsets.UTF_8)));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(reposilite, never()).deployArtifact(any(), any(), any(Path.class));
}
@Test
@@ -204,7 +241,7 @@ class CodeArtifactMavenControllerTest {
private void blockPublish(String namespace, String packageName) {
// What Reposilite would answer if the deploy got through, so a missing refusal fails on
// the status assertion rather than on a null outcome.
when(reposilite.deployArtifact(any(), any(), any()))
when(reposilite.deployArtifact(any(), any(), any(Path.class)))
.thenReturn(new DeployOutcome(201, true));
doThrow(new AwsException("ConflictException", "Package '" + packageName + "' cannot be published because "
+ "its origin configuration blocks direct publish.", 409))
@@ -8,6 +8,8 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
@@ -81,25 +83,45 @@ class CodeArtifactMavenExternalConnectionImporterTest {
// this per call via stubDeploy.
when(service.deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
anyString(), any())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(true,
anyString(), any(), anyLong())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(true,
new ReposiliteSidecarClient.DeployOutcome(201, true)));
}
/**
* Stubs the single candidate named by {@code gav}/{@code content}; every other candidate
* keeps the default stub from {@link #setUp}.
* keeps the default stub from {@link #setUp}. {@code content}'s own bytes are matched by
* length alone, not identity: the real staged {@link Path} the importer passes is a fresh
* temp file created fresh for every real call, so a test fixture can't name it in advance the
* way it could the old {@code byte[]}-returning method; {@code gav} alone already picks out
* the one candidate this stub is for.
*/
private void stubDeploy(String gav, byte[] content, CodeArtifactService.MavenDeployAttemptResult result) {
when(service.deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq(gav), eq(content))).thenReturn(result);
eq(gav), any(Path.class), eq((long) content.length))).thenReturn(result);
}
/** Verifies the call for {@code gav}/{@code content} also passed the package fence through. */
private void verifyDeployPassedPackageFence(String gav, byte[] content, long packageFenceSnapshot) {
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), eq(packageFenceSnapshot), anyLong(), eq(reposilite),
eq(REPO_ID), eq(gav), eq(content));
eq(REPO_ID), eq(gav), any(Path.class), eq((long) content.length));
}
/**
* {@code fetchAsset}'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 the old {@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 stubFetchAsset(String gav, byte[] content) {
when(externalConnectionClient.fetchAsset(eq("public:maven-central"), eq(gav), any(Path.class))).thenAnswer(
invocation -> {
Path destination = invocation.getArgument(2);
Files.write(destination, content);
return Optional.of(new MavenExternalConnectionClient.FetchedFile(content.length));
});
}
@Test
@@ -227,7 +249,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
"com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString(), any());
}
@Test
@@ -238,7 +260,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString(), any());
}
@Test
@@ -250,7 +272,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString(), any());
}
@Test
@@ -265,21 +287,19 @@ class CodeArtifactMavenExternalConnectionImporterTest {
"com/example/widget/1.0/widget-1.0.jar");
assertFalse(imported);
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString());
verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString(), any());
}
@Test
void aStandardAssetNameImportsAllFourStandardAssetsBestEffort() {
byte[] pomBytes = "pom-content".getBytes();
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
stubFetchAsset("com/example/widget/1.0/widget-1.0.pom", pomBytes);
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", jarBytes);
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any(Path.class))).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-sources.jar"), any(Path.class))).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
@@ -292,7 +312,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.jar", jarBytes, 42L);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any());
anyString(), eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any(), anyLong());
verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget",
"1.0", "public:maven-central", 42L);
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example",
@@ -312,8 +332,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
*/
@Test
void takesTheVersionFenceSnapshotBeforeClaimingNotAfter() {
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", "jar".getBytes());
importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/1.0/widget-1.0.jar");
@@ -327,8 +346,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
@Test
void anIdempotentMatchCountsAsImportedButIsNotDoubleCountedInByteAccounting() {
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", jarBytes);
// deployArtifact's own idempotent-match short-circuit: status 200, wroteNewContent false,
// because the exact same bytes were already there (e.g. a sibling asset imported it moments
// earlier in a race with another request for the same version).
@@ -353,8 +371,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
@Test
void aRealDeployConflictOnTheRequestedAssetCountsAsNotImported() {
byte[] jarBytes = "jar".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes)));
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", jarBytes);
stubDeploy("com/example/widget/1.0/widget-1.0.jar", jarBytes,
new CodeArtifactService.MavenDeployAttemptResult(true,
new ReposiliteSidecarClient.DeployOutcome(409, false)));
@@ -375,14 +392,12 @@ class CodeArtifactMavenExternalConnectionImporterTest {
@Test
void aLaterCandidateThatThrowsStillFinalizesWhatAnEarlierCandidateGenuinelyWrote() {
byte[] pomBytes = "pom-content".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
stubFetchAsset("com/example/widget/1.0/widget-1.0.pom", pomBytes);
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", "jar".getBytes());
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any(Path.class))).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-sources.jar"), any(Path.class))).thenReturn(Optional.empty());
// The POM deploy succeeds, but the JAR deploy (the requested asset) fails inside the
// sidecar call itself, e.g. it going unreachable mid-import: deployMavenAssetUnderVersionFence
// catches that on the real path and reports a matched fence with no outcome, exactly as
@@ -405,14 +420,14 @@ class CodeArtifactMavenExternalConnectionImporterTest {
@Test
void aCandidateFetchThatThrowsIsTreatedLikeAMissingCandidateRatherThanAbortingTheWholeAttempt() {
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0.pom"), any(Path.class)))
.thenThrow(new IllegalStateException("public repository unreachable"));
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes())));
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset("public:maven-central",
"com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty());
stubFetchAsset("com/example/widget/1.0/widget-1.0.jar", "jar".getBytes());
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any(Path.class))).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0-sources.jar"), any(Path.class))).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
@@ -420,17 +435,16 @@ class CodeArtifactMavenExternalConnectionImporterTest {
assertTrue(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0.pom"), any());
anyString(), eq("com/example/widget/1.0/widget-1.0.pom"), any(), anyLong());
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq("com/example/widget/1.0/widget-1.0.jar"), eq("jar".getBytes()));
eq("com/example/widget/1.0/widget-1.0.jar"), any(Path.class), eq(3L));
}
@Test
void aDisposalLandingWhileAFetchIsInFlightStopsEveryLaterWriteForThisAttempt() {
byte[] pomBytes = "pom-content".getBytes();
when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes)));
stubFetchAsset("com/example/widget/1.0/widget-1.0.pom", pomBytes);
// A DisposePackageVersions landed on this exact version while the first candidate's
// (the pom's) fetch was in flight: deployMavenAssetUnderVersionFence detects the fence
// mismatch itself (inside its own lock) and reports it rather than writing anything, so
@@ -444,7 +458,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), eq("com/example/widget/1.0/widget-1.0.jar"), any());
anyString(), eq("com/example/widget/1.0/widget-1.0.jar"), any(), anyLong());
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, false);
}
@@ -452,22 +466,21 @@ class CodeArtifactMavenExternalConnectionImporterTest {
@Test
void aNonStandardAssetNameOnlyImportsTheExactRequestedAsset() {
String nonStandardGav = "com/example/widget/1.0/widget-1.0-windows.jar";
when(externalConnectionClient.fetchAsset("public:maven-central", nonStandardGav))
.thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("windows-jar".getBytes())));
stubFetchAsset(nonStandardGav, "windows-jar".getBytes());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, nonStandardGav);
assertTrue(imported);
verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID),
eq(nonStandardGav), eq("windows-jar".getBytes()));
eq(nonStandardGav), any(Path.class), eq((long) "windows-jar".getBytes().length));
verify(externalConnectionClient, never()).fetchAsset(eq("public:maven-central"),
eq("com/example/widget/1.0/widget-1.0.pom"));
eq("com/example/widget/1.0/widget-1.0.pom"), any());
}
@Test
void returnsFalseWhenTheRequestedAssetItselfIsNotFoundEvenIfItWouldHaveBeenAStandardImport() {
when(externalConnectionClient.fetchAsset(anyString(), anyString())).thenReturn(Optional.empty());
when(externalConnectionClient.fetchAsset(anyString(), anyString(), any())).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
"com/example/widget/1.0/widget-1.0.jar");
@@ -475,7 +488,7 @@ class CodeArtifactMavenExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(),
anyString(), anyString(), any());
anyString(), anyString(), any(), anyLong());
verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example",
"widget", "1.0", EPISODE_ID, false);
}
@@ -9,6 +9,8 @@ import io.floci.aws.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
@@ -81,7 +83,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
when(verdaccio.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(), any(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
when(verdaccio.ensureReady(REPO_ID, BASE_URL)).thenReturn(BASE_URL);
when(verdaccio.publicUrl(DOMAIN, REPOSITORY)).thenReturn(BASE_URL);
@@ -89,8 +91,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
@Test
void tryImportAssetImportsFromExternalConnectionWhenNotFoundLocally() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
stubFetchTarball(TARBALL_CONTENT);
// The real registry is reachable and genuinely has no readme for this package (unlike
// Optional.empty(), which models the full fetch itself failing, see
// tryImportAssetReturnsFalseAndRetriesLaterWhenTheFullPackumentFetchFails below).
@@ -107,7 +108,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("npm"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq(ASSET_NAME), eq(TARBALL_CONTENT), any());
eq(ASSET_NAME), eq((long) TARBALL_CONTENT.length), any());
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, 42L);
verify(service).recordPublishedPackageVersionReadme(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
@@ -125,8 +126,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
*/
@Test
void tryImportAssetReturnsFalseAndRetriesLaterWhenTheFullPackumentFetchFails() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
stubFetchTarball(TARBALL_CONTENT);
when(externalConnectionClient.fetchFullPackument("public:npmjs", null, PACKAGE_NAME))
.thenReturn(Optional.empty());
@@ -136,7 +136,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
anyString(), anyLong(), any());
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service, never()).recordPublishedPackageVersionReadme(anyString(), anyString(), anyString(),
@@ -153,8 +153,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
*/
@Test
void tryImportAssetPreservesTheRealVersionDocumentAndReadme() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
stubFetchTarball(TARBALL_CONTENT);
ObjectMapper mapper = new ObjectMapper();
ObjectNode full = mapper.createObjectNode();
full.put("readme", "# Widget\nA real readme.");
@@ -233,10 +232,10 @@ class CodeArtifactNpmExternalConnectionImporterTest {
VERSION, ASSET_NAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString());
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString(), any());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
anyString(), anyLong(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
@@ -258,7 +257,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
VERSION, ASSET_NAME);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString());
verify(externalConnectionClient, never()).fetchTarball(anyString(), any(), anyString(), anyString(), any());
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyLong());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
@@ -267,8 +266,8 @@ class CodeArtifactNpmExternalConnectionImporterTest {
@Test
void tryImportAssetReturnsFalseAndFinishesWhenTheRealRegistryDoesNotHaveIt() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.empty());
when(externalConnectionClient.fetchTarball(eq("public:npmjs"), isNull(), eq(PACKAGE_NAME), eq(VERSION),
any(Path.class))).thenReturn(Optional.empty());
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
@@ -276,15 +275,15 @@ class CodeArtifactNpmExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
anyString(), anyLong(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
@Test
void tryImportAssetFetchThatThrowsIsTreatedLikeAMissingPackageRatherThanPropagating() {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenThrow(new IllegalStateException("public registry unreachable"));
when(externalConnectionClient.fetchTarball(eq("public:npmjs"), isNull(), eq(PACKAGE_NAME), eq(VERSION),
any(Path.class))).thenThrow(new IllegalStateException("public registry unreachable"));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
@@ -296,8 +295,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
@Test
void tryImportAssetReturnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() throws Exception {
when(externalConnectionClient.fetchTarball("public:npmjs", null, PACKAGE_NAME, VERSION))
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(TARBALL_CONTENT)));
stubFetchTarball(TARBALL_CONTENT);
ObjectMapper mapper = new ObjectMapper();
ObjectNode full = mapper.createObjectNode();
full.putObject("versions").putObject(VERSION);
@@ -305,7 +303,7 @@ class CodeArtifactNpmExternalConnectionImporterTest {
.thenReturn(Optional.of(new NpmExternalConnectionClient.FetchedAsset(mapper.writeValueAsBytes(
full))));
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
@@ -634,4 +632,20 @@ class CodeArtifactNpmExternalConnectionImporterTest {
assertTrue(merged.isEmpty());
}
/**
* {@code fetchTarball}'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 the old {@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 stubFetchTarball(byte[] content) {
when(externalConnectionClient.fetchTarball(eq("public:npmjs"), isNull(), eq(PACKAGE_NAME), eq(VERSION),
any(Path.class))).thenAnswer(invocation -> {
Path destination = invocation.getArgument(4);
Files.write(destination, content);
return Optional.of(new NpmExternalConnectionClient.FetchedFile(content.length));
});
}
}
@@ -4,20 +4,36 @@ 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.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
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;
@@ -82,16 +98,90 @@ class CodeArtifactNuGetControllerLeaseTest {
verify(bagetter).endUse(REPO_ID);
}
/**
* The {@code .nupkg} branch is the one real asset download in this controller (a readme or
* {@code .nuspec} stays small): this proves it streams the sidecar's response straight through
* rather than buffering it first, and still releases its lease afterward.
*/
@Test
void packageContentStreamsTheNupkgAndReleasesItsLease() throws Exception {
HttpClient http = mock(HttpClient.class);
controller = new CodeArtifactNuGetController(service, bagetter,
mock(CodeArtifactNuGetExternalConnectionImporter.class), http);
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "pkg", "1.0.0")).thenReturn(true);
byte[] nupkgBytes = "nupkg-bytes".getBytes(StandardCharsets.UTF_8);
@SuppressWarnings("unchecked")
HttpResponse<InputStream> reply = mock(HttpResponse.class);
when(reply.statusCode()).thenReturn(200);
when(reply.body()).thenReturn(new ByteArrayInputStream(nupkgBytes));
when(reply.headers()).thenReturn(java.net.http.HttpHeaders.of(
Map.of("Content-Type", List.of("application/octet-stream")), (name, value) -> true));
when(http.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(reply);
Response response = controller.packageContent(headers, DOMAIN, REPOSITORY, "pkg", "1.0.0", "pkg.nupkg");
// The lease must still be held once packageContent itself has returned: a concurrent
// DeleteRepository must not be able to tear down the BaGetter container before the entity
// stream below is actually drained.
verify(bagetter, never()).endUse(REPO_ID);
assertEquals(200, response.getStatus());
assertEquals("nupkg-bytes", new String(readEntity(response), StandardCharsets.UTF_8));
verify(bagetter).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 pushReleasesItsLeaseOnInvalidMultipartInput() {
when(headers.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn("application/octet-stream");
Response response = controller.push(headers, DOMAIN, REPOSITORY, new byte[] {1});
Response response = controller.push(headers, DOMAIN, REPOSITORY, new ByteArrayInputStream(new byte[] {1}));
assertEquals(400, response.getStatus());
verify(bagetter).endUse(REPO_ID);
}
@Test
void pushDeletesTheExtractedStagedNupkgFileEvenWhenTheFilePartIsTruncatedBeforeItsClosingBoundary()
throws Exception {
when(headers.getHeaderString(HttpHeaders.CONTENT_TYPE))
.thenReturn("multipart/form-data; boundary=boundary123");
AtomicReference<Path> stagedWholeBody = new AtomicReference<>();
when(service.stageAssetBody(any())).thenAnswer(invocation -> {
InputStream in = invocation.getArgument(0);
Path staged = Files.createTempFile("nuget-controller-test-", ".bin");
Files.copy(in, staged, StandardCopyOption.REPLACE_EXISTING);
stagedWholeBody.set(staged);
return staged;
});
doAnswer(invocation -> {
Files.deleteIfExists(invocation.getArgument(0));
return null;
}).when(service).deleteStagedAssetBody(any());
// No closing "--boundary123--": extractFilePart has already created the destination file
// and started writing into it by the time copyUntilDelimiter runs off the end of the
// staged body and throws, so this exercises the 400 response's own cleanup path.
String truncated = "--boundary123\r\n"
+ "Content-Disposition: form-data; name=\"package\"; filename=\"my.pkg.1.0.0.nupkg\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n"
+ "partial, never-terminated file content";
Response response = controller.push(headers, DOMAIN, REPOSITORY,
new ByteArrayInputStream(truncated.getBytes(StandardCharsets.UTF_8)));
assertEquals(400, response.getStatus());
Path stagedNupkg = stagedWholeBody.get().resolveSibling(stagedWholeBody.get().getFileName() + ".nupkg");
assertFalse(Files.exists(stagedNupkg), "a staged nupkg file from a failed extraction must not leak: " + stagedNupkg);
}
@Test
void failedSidecarStartupReleasesTheLease() {
when(bagetter.ensureReady(REPO_ID, null)).thenThrow(new IllegalStateException("Docker unavailable"));
@@ -5,6 +5,8 @@ import io.floci.aws.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
@@ -78,21 +80,20 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
// CodeArtifactService method (see its own javadoc for why), so this mock is what every
// test configures instead.
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
}
@Test
void importsFromExternalConnectionWhenNotFoundLocally() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
stubFetchPackage(PACKAGE_ID, VERSION, NUPKG_CONTENT);
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("nuget"),
isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq("widget.1.0.0.nupkg"), eq(NUPKG_CONTENT), any());
eq("widget.1.0.0.nupkg"), eq((long) NUPKG_CONTENT.length), any());
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
"nuget", null, PACKAGE_ID, 42L, REPO_ID);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
@@ -149,10 +150,10 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString(), any());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
anyString(), anyLong(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, true);
}
@@ -173,7 +174,7 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString(), any());
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
@@ -182,23 +183,23 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
@Test
void returnsFalseAndFinishesWhenTheRealRepositoryDoesNotHaveIt() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.empty());
when(externalConnectionClient.fetchPackage(eq("public:nuget-org"), eq(PACKAGE_ID), eq(VERSION),
any(Path.class))).thenReturn(Optional.empty());
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
anyString(), any(), any());
anyString(), anyLong(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
@Test
void aFetchThatThrowsIsTreatedLikeAMissingPackageRatherThanPropagating() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenThrow(new IllegalStateException("public repository unreachable"));
when(externalConnectionClient.fetchPackage(eq("public:nuget-org"), eq(PACKAGE_ID), eq(VERSION),
any(Path.class))).thenThrow(new IllegalStateException("public repository unreachable"));
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
@@ -209,10 +210,9 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
@Test
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
stubFetchPackage(PACKAGE_ID, VERSION, NUPKG_CONTENT);
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
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_ID, VERSION);
@@ -223,4 +223,20 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, EPISODE_ID, false);
}
/**
* {@code fetchPackage}'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 the old {@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 stubFetchPackage(String packageId, String version, byte[] content) {
when(externalConnectionClient.fetchPackage(eq("public:nuget-org"), eq(packageId), eq(version),
any(Path.class))).thenAnswer(invocation -> {
Path destination = invocation.getArgument(3);
Files.write(destination, content);
return Optional.of(new NuGetExternalConnectionClient.FetchedFile(content.length));
});
}
}
@@ -8,14 +8,22 @@ import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
import org.junit.jupiter.api.AfterEach;
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.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.List;
import java.util.Map;
@@ -40,6 +48,7 @@ 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.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -68,6 +77,7 @@ class CodeArtifactPypiControllerTest {
private PypiserverSidecarClient pypiserver;
private CodeArtifactPypiExternalConnectionImporter externalConnectionImporter;
private CodeArtifactPypiController controller;
private final AtomicReference<Path> lastStagedWholeBody = new AtomicReference<>();
@BeforeEach
void setUp() throws Exception {
@@ -92,6 +102,22 @@ class CodeArtifactPypiControllerTest {
// method here, matching a repository with no pypi external connection configured at all;
// individual tests below override specific calls to exercise the merge/retention paths.
externalConnectionImporter = mock(CodeArtifactPypiExternalConnectionImporter.class);
// service is a mock, so its own real stageAssetBody (which the controller now calls to
// stage the whole raw multipart body before scanning it) never runs; stubbed here to
// actually stage to a real temp file, the same real behavior the controller depends on to
// parse/size/forward real content, rather than a null Path the controller's own file-path
// manipulation (MultipartFormParser.extractFilePart) would otherwise crash on.
when(service.stageAssetBody(any())).thenAnswer(invocation -> {
InputStream in = invocation.getArgument(0);
Path staged = Files.createTempFile("pypi-controller-test-", ".bin");
Files.copy(in, staged, StandardCopyOption.REPLACE_EXISTING);
lastStagedWholeBody.set(staged);
return staged;
});
doAnswer(invocation -> {
Files.deleteIfExists(invocation.getArgument(0));
return null;
}).when(service).deleteStagedAssetBody(any());
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
controller = new CodeArtifactPypiController(service, pypiserver, externalConnectionImporter, httpClient);
@@ -155,8 +181,12 @@ class CodeArtifactPypiControllerTest {
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY, "my-pkg-1.0.tar.gz");
// The lease must still be held once downloadFile itself has returned: a concurrent
// DeleteRepository must not be able to tear down the pypiserver container before the
// entity stream below is actually drained.
verify(pypiserver, never()).endUse("pypi-repo-id");
assertEquals(200, response.getStatus());
assertEquals("package bytes", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
assertEquals("package bytes", new String(readEntity(response), StandardCharsets.UTF_8));
verify(pypiserver).endUse("pypi-repo-id");
}
@@ -191,9 +221,14 @@ class CodeArtifactPypiControllerTest {
Response response = controller.downloadFile(headers("Bearer good"), DOMAIN, REPOSITORY,
"ext-pkg-1.0.0.tar.gz");
// The lease must survive the first 404, the external-connection import, and the retry: it
// is only released once the real 200's entity stream is actually drained below, not as
// soon as downloadFile itself returns.
verify(pypiserver, never()).endUse("pypi-repo-id");
assertEquals(200, response.getStatus());
assertEquals("real-upstream-bytes", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
assertEquals("real-upstream-bytes", new String(readEntity(response), StandardCharsets.UTF_8));
assertEquals(2, requestCount.get());
verify(pypiserver).endUse("pypi-repo-id");
}
@Test
@@ -457,17 +492,38 @@ class CodeArtifactPypiControllerTest {
@Test
void uploadRejectsABodyWithNoDeterminableBoundary() {
Response response = controller.upload(headers("Bearer good", "application/octet-stream"), DOMAIN, REPOSITORY,
"not multipart".getBytes(StandardCharsets.UTF_8));
new ByteArrayInputStream("not multipart".getBytes(StandardCharsets.UTF_8)));
assertEquals(400, response.getStatus());
}
@Test
void uploadDeletesTheExtractedStagedAssetFileEvenWhenTheFilePartIsTruncatedBeforeItsClosingBoundary() throws Exception {
// No closing "--boundary123--" at all: MultipartFormParser.extractFilePart has already
// created the destination file and started writing into it by the time this makes
// copyUntilDelimiter run off the end of the staged body and throw, so this exercises the
// 400 response's own cleanup path, not the success path's.
String truncated = "--boundary123\r\n"
+ "Content-Disposition: form-data; name=\"content\"; filename=\"my_pkg-1.0.tar.gz\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n"
+ "partial, never-terminated file content";
byte[] body = truncated.getBytes(StandardCharsets.UTF_8);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
new ByteArrayInputStream(body));
assertEquals(400, response.getStatus());
Path stagedAsset = lastStagedWholeBody.get().resolveSibling(lastStagedWholeBody.get().getFileName() + ".asset");
assertFalse(Files.exists(stagedAsset), "a staged asset file from a failed extraction must not leak: " + stagedAsset);
}
@Test
void uploadRejectsAMultipartBodyMissingNameOrContent() {
byte[] body = multipart("boundary123", "version", "1.0.0");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(400, response.getStatus());
}
@@ -486,7 +542,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -512,7 +568,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
assertEquals(true, uploadReceived.get());
@@ -537,7 +593,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my#pkg", "my_pkg-1.0.0.tar.gz", "content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
assertEquals("/simple/my%23pkg/", observedRawPath.get());
@@ -565,7 +621,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", filename, "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals("/packages/my_pkg-1.0.0%3Fsig.tar.gz", observedRawPath.get());
@@ -588,7 +644,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", sameContent);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -620,7 +676,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", sameContent);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -648,7 +704,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "other-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -673,7 +729,7 @@ class CodeArtifactPypiControllerTest {
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -694,7 +750,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "demo", "demo-1.0-1-py3-none-any.whl", "wheel bytes");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
}
@@ -712,7 +768,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
assertTrue(receivedBody.get().contains("new content"));
@@ -731,7 +787,7 @@ class CodeArtifactPypiControllerTest {
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(200, response.getStatus());
verify(service).completeContainerBackedPublishIfCurrentRepository(eq(REGION), eq(DOMAIN), eq(OWNER),
@@ -759,7 +815,7 @@ class CodeArtifactPypiControllerTest {
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(400, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -789,7 +845,7 @@ class CodeArtifactPypiControllerTest {
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -820,7 +876,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -851,7 +907,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "other-pkg", "my_pkg-1.0.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body));
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
@@ -865,7 +921,7 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "new content");
controller.upload(headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
body);
new ByteArrayInputStream(body));
verify(service).completeContainerBackedPublishIfCurrentRepository(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi-repo-id"), eq("pypi"), eq("my-pkg"), isNull(), eq(11L), anyLong(),
@@ -883,14 +939,14 @@ class CodeArtifactPypiControllerTest {
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content");
assertThrows(IllegalStateException.class, () -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body));
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, new ByteArrayInputStream(body)));
verify(pypiserver).endUse("pypi-repo-id");
}
@Test
void uploadReleasesTheLeaseOnInvalidMultipartInput() {
Response response = controller.upload(headers("Bearer good", "application/octet-stream"), DOMAIN,
REPOSITORY, new byte[] {1});
REPOSITORY, new ByteArrayInputStream(new byte[] {1}));
assertEquals(400, response.getStatus());
verify(pypiserver).endUse("pypi-repo-id");
@@ -931,12 +987,12 @@ class CodeArtifactPypiControllerTest {
try {
Future<Response> first = pool.submit(() -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-A")));
new ByteArrayInputStream(multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-A"))));
assertTrue(firstCheckEntered.await(5, TimeUnit.SECONDS), "first upload never started its check");
Future<Response> second = pool.submit(() -> controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY,
multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-B")));
new ByteArrayInputStream(multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", "content-B"))));
// The second upload must block on the same repository's lock, held by the first, and
// so cannot even reach the backend yet: without the lock this would race ahead and
@@ -952,6 +1008,16 @@ class CodeArtifactPypiControllerTest {
}
}
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();
}
private static HttpHeaders headers(String authorization) {
return headers(authorization, "text/plain");
}
@@ -10,6 +10,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.List;
@@ -97,15 +99,29 @@ class CodeArtifactPypiExternalConnectionImporterTest {
when(pypiserver.listPackageVersionAssetNames(anyString(), anyString(), anyString(), any(), anyString(),
anyString())).thenReturn(List.of());
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), any(),
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
when(externalConnectionClient.fetchSimpleIndex(eq("public:pypi"), eq(PACKAGE_NAME)))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(
simpleIndexJson(List.of(VERSION), SDIST_FILENAME, WHEEL_FILENAME))));
when(externalConnectionClient.fetchFile(eq("public:pypi"), eq(urlFor(SDIST_FILENAME))))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(SDIST_CONTENT)));
when(externalConnectionClient.fetchFile(eq("public:pypi"), eq(urlFor(WHEEL_FILENAME))))
.thenReturn(Optional.of(new PypiExternalConnectionClient.FetchedAsset(WHEEL_CONTENT)));
stubFetchFile(urlFor(SDIST_FILENAME), SDIST_CONTENT);
stubFetchFile(urlFor(WHEEL_FILENAME), WHEEL_CONTENT);
}
/**
* {@code fetchFile}'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 the old {@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 stubFetchFile(String url, byte[] content) {
when(externalConnectionClient.fetchFile(eq("public:pypi"), eq(url), any(Path.class))).thenAnswer(
invocation -> {
Path destination = invocation.getArgument(2);
Files.write(destination, content);
return Optional.of(new PypiExternalConnectionClient.FetchedFile(content.length));
});
}
@Test
@@ -121,7 +137,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
eq(SDIST_FILENAME), eq((long) SDIST_CONTENT.length), any());
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
"pypi", null, PACKAGE_NAME, 42L, REPO_ID);
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
@@ -137,13 +153,13 @@ class CodeArtifactPypiExternalConnectionImporterTest {
// moment tryImportAsset returns.
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(WHEEL_FILENAME), eq(WHEEL_CONTENT), any());
eq(WHEEL_FILENAME), eq((long) WHEEL_CONTENT.length), any());
// AWS: "CodeArtifact will import all the assets in that package version" -- the sdist is
// still imported, just handed off to run in the background (raised in review: hectorvent,
// #7741), so this waits for it rather than asserting it happened synchronously.
verify(service, timeout(2000)).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(),
eq(EPISODE_ID), eq(REPO_ID), eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
eq(EPISODE_ID), eq(REPO_ID), eq(SDIST_FILENAME), eq((long) SDIST_CONTENT.length), any());
}
@Test
@@ -154,10 +170,10 @@ class CodeArtifactPypiExternalConnectionImporterTest {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, WHEEL_FILENAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchFile(eq("public:pypi"), eq(urlFor(SDIST_FILENAME)));
verify(externalConnectionClient, never()).fetchFile(eq("public:pypi"), eq(urlFor(SDIST_FILENAME)), any());
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
eq(SDIST_FILENAME), anyLong(), any());
}
@Test
@@ -214,7 +230,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertFalse(imported);
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString());
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString(), any());
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
}
@@ -229,7 +245,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME);
assertTrue(imported);
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString());
verify(externalConnectionClient, never()).fetchFile(anyString(), anyString(), any());
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, EPISODE_ID, true);
}
@@ -252,10 +268,10 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertTrue(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
eq(SDIST_FILENAME), anyLong(), any());
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(WHEEL_FILENAME), eq(WHEEL_CONTENT), any());
eq(WHEEL_FILENAME), eq((long) WHEEL_CONTENT.length), any());
}
/**
@@ -276,7 +292,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertTrue(imported);
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
eq(SDIST_FILENAME), any(), any());
eq(SDIST_FILENAME), anyLong(), any());
}
/**
@@ -432,7 +448,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertFalse(imported);
verify(service, never()).retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(),
any(), anyLong(), anyLong(), anyLong(), any(), any(), any(), any());
any(), anyLong(), anyLong(), anyLong(), any(), any(), anyLong(), any());
}
/** A file whose real bytes genuinely match the index's own sha256 is still imported normally. */
@@ -454,7 +470,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertTrue(imported);
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"),
isNull(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), eq(EPISODE_ID), eq(REPO_ID),
eq(SDIST_FILENAME), eq(SDIST_CONTENT), any());
eq(SDIST_FILENAME), eq((long) SDIST_CONTENT.length), any());
}
/**
@@ -482,7 +498,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME,
VERSION)).thenReturn(Optional.of("public:pypi"));
when(service.retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(), any(), anyLong(),
anyLong(), anyLong(), any(), eq(SDIST_FILENAME), any(), any())).thenAnswer(invocation -> {
anyLong(), anyLong(), any(), eq(SDIST_FILENAME), anyLong(), any())).thenAnswer(invocation -> {
if (sdistWriteAttempts.getAndIncrement() == 0) {
firstWriteStarted.countDown();
assertTrue(releaseFirstWrite.await(5, TimeUnit.SECONDS), "test never released the first write");
@@ -491,7 +507,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
return new CodeArtifactService.AssetRetentionAttemptResult(true, true);
});
when(service.retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(), any(), anyLong(),
anyLong(), anyLong(), any(), eq(WHEEL_FILENAME), any(), any()))
anyLong(), anyLong(), any(), eq(WHEEL_FILENAME), anyLong(), any()))
.thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
ExecutorService pool = Executors.newFixedThreadPool(2);
@@ -513,7 +529,7 @@ class CodeArtifactPypiExternalConnectionImporterTest {
}
verify(service, times(1)).retainAssetUnderVersionFence(any(), any(), any(), any(), any(), any(), any(),
any(), anyLong(), anyLong(), anyLong(), any(), eq(SDIST_FILENAME), any(), any());
any(), anyLong(), anyLong(), anyLong(), any(), eq(SDIST_FILENAME), anyLong(), any());
}
private static String urlFor(String filename) {
@@ -24,14 +24,20 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
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.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -49,6 +55,7 @@ import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -59,12 +66,14 @@ 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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -351,6 +360,61 @@ class CodeArtifactServiceTest {
version, readme, fence);
}
/**
* Stands in for a real sidecar's {@code fetchPackageVersionAssetDigest} (the digest-only
* sibling {@code listPackageVersionAssets}/dispose byte-accounting now call instead of the
* full {@code fetchPackageVersionAsset}, so a mocked sidecar needs this stubbed too), computed
* over the exact algorithm set {@code CodeArtifactService} itself uses.
*/
private static RepositorySidecarManager.AssetDigest digestOf(byte[] content) {
try {
MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
Map<String, String> hashes = new HashMap<>();
hashes.put("MD5", Digests.md5Hex(content));
hashes.put("SHA-1", Digests.sha1Hex(content));
hashes.put("SHA-256", Digests.sha256Hex(content));
hashes.put("SHA-512", HexFormat.of().formatHex(sha512.digest(content)));
return new RepositorySidecarManager.AssetDigest(content.length, hashes);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/**
* {@code copyContainerBackedPackageVersions} now writes a copy through {@code
* copyPackageVersionAsset}'s {@code Path} overload, a file staged under the batch's own
* cleanup, deleted by the time the call returns, too late for a test to read it back
* afterward. Call this to set up the capture BEFORE invoking {@code copyPackageVersions},
* reading the file's bytes from inside the stubbed answer instead, while it still exists; the
* real write still happens underneath (the answer calls the real method), so this is additive
* instrumentation, not a replacement stub.
*/
private static AtomicReference<byte[]> captureCopiedAssetContent(ReposiliteSidecarClient client,
String sourceRepoId, String sourceRepo, String destRepoId, String destRepo, String namespace,
String packageName, String version, String assetName) {
AtomicReference<byte[]> captured = new AtomicReference<>();
doAnswer(invocation -> {
captured.set(Files.readAllBytes(invocation.getArgument(9)));
return null;
}).when(client).copyPackageVersionAsset(eq(sourceRepoId), eq("dom"), eq(sourceRepo), eq(destRepoId),
eq(destRepo), eq(namespace), eq(packageName), eq(version), eq(assetName), any(Path.class),
anyLong());
return captured;
}
/** {@link #captureCopiedAssetContent}'s own counterpart for a rollback's {@code storePackageVersionAsset}. */
private static AtomicReference<byte[]> captureStoredAssetContent(ReposiliteSidecarClient client,
String destRepoId, String destRepo, String namespace, String packageName, String version,
String assetName) {
AtomicReference<byte[]> captured = new AtomicReference<>();
doAnswer(invocation -> {
captured.set(Files.readAllBytes(invocation.getArgument(7)));
return null;
}).when(client).storePackageVersionAsset(eq(destRepoId), eq("dom"), eq(destRepo), eq(namespace),
eq(packageName), eq(version), eq(assetName), any(Path.class), anyLong());
return captured;
}
/**
* {@code recordContainerBackedAssetBytes} is what each of the three sidecar-backed proxies
* calls after a real (non-idempotent, non-rejected) write; this is the unit-level proof that
@@ -510,6 +574,13 @@ class CodeArtifactServiceTest {
HttpClient http = mock(HttpClient.class);
HttpResponse<byte[]> absent = mock(HttpResponse.class);
when(absent.statusCode()).thenReturn(404);
// A real HttpClient's body() is never null even for a 404 (Copilot's review of this PR:
// compareExistingNupkg now closes this body on the 404 branch), so this stub matches that
// instead of letting Mockito's default null stand in for a response shape that never
// actually occurs. doReturn, not when(...).thenReturn(...): this same mock also answers
// calls expecting an HttpResponse<byte[]>, and an InputStream is what the one caller that
// actually reads body() here (BodyHandlers.ofInputStream()) needs.
doReturn(new ByteArrayInputStream(new byte[0])).when(absent).body();
HttpResponse<Void> published = mock(HttpResponse.class);
when(published.statusCode()).thenReturn(201);
when(http.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenAnswer(call -> {
@@ -544,7 +615,7 @@ class CodeArtifactServiceTest {
body.writeBytes(packageBytes);
body.writeBytes("\r\n--boundary123--\r\n".getBytes(StandardCharsets.UTF_8));
Response response = controller.push(headers, "dom", "repo", body.toByteArray());
Response response = controller.push(headers, "dom", "repo", new ByteArrayInputStream(body.toByteArray()));
assertEquals(201, response.getStatus());
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
@@ -675,7 +746,7 @@ class CodeArtifactServiceTest {
AtomicBoolean wroteOldAsset = new AtomicBoolean();
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(REGION,
"dom", null, "repo", "nuget", null, "demo", "1.0.0", versionFence, packageFence,
oldClaim.episodeId(), oldId, "demo.1.0.0.nupkg", new byte[] {1},
oldClaim.episodeId(), oldId, "demo.1.0.0.nupkg", 1,
() -> wroteOldAsset.set(true));
assertFalse(result.fenceMatched());
@@ -703,7 +774,7 @@ class CodeArtifactServiceTest {
AtomicBoolean wroteOldAsset = new AtomicBoolean();
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(REGION,
"dom", null, "repo", "nuget", null, "demo", "1.0.0", versionFence, packageFence,
newClaim.episodeId(), oldId, "demo.1.0.0.nupkg", new byte[] {1},
newClaim.episodeId(), oldId, "demo.1.0.0.nupkg", 1,
() -> wroteOldAsset.set(true));
assertFalse(result.fenceMatched());
@@ -1802,6 +1873,33 @@ class CodeArtifactServiceTest {
order.verify(verdaccioClient).endUse(repoId);
}
/**
* {@code getPackageVersionAssetStreamed}'s real HTTP caller (CodeArtifactController) only
* drains and closes the returned stream later, when JAX-RS writes the deferred response body:
* the lease must stay held until that real close happens, not just until this method itself
* returns, or a concurrent DeleteRepository could stop this npm sidecar mid-download.
*/
@Test
void getPackageVersionAssetStreamedKeepsTheLeaseHeldUntilTheReturnedStreamIsClosed() throws Exception {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String repoId = created.getSidecarContainerIds().get("npm");
when(verdaccioClient.packageVersionExists(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"))).thenReturn(true);
byte[] tarball = "tarball bytes".getBytes(StandardCharsets.UTF_8);
when(verdaccioClient.fetchPackageVersionAssetStreamed(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz")))
.thenReturn(Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(tarball), tarball.length)));
CodeArtifactService.PackageVersionAssetStreamResult result = service.getPackageVersionAssetStreamed(REGION,
"dom", null, "repo", "npm", null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", null);
verify(verdaccioClient, never()).endUse(repoId);
result.content().close();
verify(verdaccioClient).endUse(repoId);
}
@Test
void describePackageBracketsVerdaccioExistenceCheckWithUse() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -2352,7 +2450,7 @@ class CodeArtifactServiceTest {
CodeArtifactService.AssetRetentionAttemptResult retained = service.retainAssetUnderVersionFence(REGION,
"dom", null, "repo", "nuget", null, "widget", "1.0.0", versionFence, packageFence,
claim.episodeId(), oldId, "widget.1.0.0.nupkg", new byte[] {1},
claim.episodeId(), oldId, "widget.1.0.0.nupkg", 1,
() -> wroteOldAsset.set(true));
assertTrue(retained.fenceMatched());
assertTrue(retained.wroteNewContent());
@@ -2627,7 +2725,7 @@ class CodeArtifactServiceTest {
reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any(byte[].class));
}
/**
@@ -2669,7 +2767,7 @@ class CodeArtifactServiceTest {
episodeId, reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any(byte[].class));
}
/**
@@ -2707,6 +2805,8 @@ class CodeArtifactServiceTest {
.thenReturn(List.of("widget-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(repoId, "dom", "repo", "com.example", "widget", "1.0",
"widget-1.0.jar")).thenReturn(Optional.of(content));
when(reposiliteClient.fetchPackageVersionAssetDigest(repoId, "dom", "repo", "com.example", "widget", "1.0",
"widget-1.0.jar")).thenReturn(Optional.of(digestOf(content)));
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "widget",
List.of("1.0"), null, null);
@@ -2765,7 +2865,7 @@ class CodeArtifactServiceTest {
reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8));
assertFalse(result.fenceMatched());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any());
verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any(byte[].class));
}
/**
@@ -3311,6 +3411,10 @@ class CodeArtifactServiceTest {
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
when(verdaccioClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenReturn(Optional.of(tarball));
when(verdaccioClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(tarball), tarball.length)));
recordReadme("dom", "src", "npm", null, "my-pkg", "1.0.0", "# Real Readme");
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "npm", null, "my-pkg", List.of("1.0.0"),
@@ -3338,6 +3442,10 @@ class CodeArtifactServiceTest {
eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my_pkg-1.0.0.tar.gz"));
when(pypiserverClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my_pkg-1.0.0.tar.gz"))).thenReturn(Optional.of(sdist));
when(pypiserverClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my_pkg-1.0.0.tar.gz"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(sdist), sdist.length)));
recordReadme("dom", "src", "pypi", null, "my-pkg", "1.0.0", "A pypi description");
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "pypi", null, "my-pkg", List.of("1.0.0"),
@@ -3367,6 +3475,18 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(pomBytes), pomBytes.length)));
AtomicReference<byte[]> copiedJar = captureCopiedAssetContent(reposiliteClient, srcRepoId, "src", dstRepoId,
"dst", "com.example", "a", "1.0", "a-1.0.jar");
AtomicReference<byte[]> copiedPom = captureCopiedAssetContent(reposiliteClient, srcRepoId, "src", dstRepoId,
"dst", "com.example", "a", "1.0", "a-1.0.pom");
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
@@ -3374,10 +3494,8 @@ class CodeArtifactServiceTest {
assertTrue(result.failedVersions().isEmpty());
assertEquals("Published", result.successfulVersions().get("1.0").status());
assertFalse(result.successfulVersions().get("1.0").revision().isBlank());
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(jarBytes));
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"), eq(pomBytes));
assertArrayEquals(jarBytes, copiedJar.get());
assertArrayEquals(pomBytes, copiedPom.get());
verify(reposiliteClient, never()).deletePackageVersionAsset(any(), any(), any(), any(), any(), any(),
any());
}
@@ -3404,6 +3522,10 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
@@ -3451,11 +3573,19 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
byte[] oldJarBytes = "old-jar-bytes".getBytes(StandardCharsets.UTF_8);
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar")))
.thenReturn(Optional.of("old-jar-bytes".getBytes(StandardCharsets.UTF_8)));
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newJarBytes), newJarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(oldJarBytes), oldJarBytes.length)));
long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
@@ -3498,11 +3628,19 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
byte[] oldJarBytes = "old-jar-bytes".getBytes(StandardCharsets.UTF_8);
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar")))
.thenReturn(Optional.of("old-jar-bytes".getBytes(StandardCharsets.UTF_8)));
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newJarBytes), newJarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(oldJarBytes), oldJarBytes.length)));
long dstPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "dst", "maven",
"com.example", "a");
CodeArtifactService.MavenClaimOutcome dstClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null,
@@ -3612,6 +3750,14 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes.clone()));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes.clone()), jarBytes.length)));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
@@ -3637,12 +3783,20 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
byte[] sourceBytes = "source-bytes".getBytes(StandardCharsets.UTF_8);
byte[] differentBytes = "different-bytes".getBytes(StandardCharsets.UTF_8);
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar")))
.thenReturn(Optional.of("source-bytes".getBytes(StandardCharsets.UTF_8)));
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(sourceBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar")))
.thenReturn(Optional.of("different-bytes".getBytes(StandardCharsets.UTF_8)));
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(differentBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(sourceBytes), sourceBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(differentBytes), differentBytes.length)));
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false);
@@ -3666,11 +3820,21 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar", "stale-readme.txt"));
byte[] oldJarBytes = "old-jar-bytes".getBytes(StandardCharsets.UTF_8);
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar")))
.thenReturn(Optional.of("old-jar-bytes".getBytes(StandardCharsets.UTF_8)));
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newJarBytes), newJarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(oldJarBytes), oldJarBytes.length)));
AtomicReference<byte[]> copiedJar = captureCopiedAssetContent(reposiliteClient, srcRepoId, "src", dstRepoId,
"dst", "com.example", "a", "1.0", "a-1.0.jar");
CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false);
@@ -3685,7 +3849,9 @@ class CodeArtifactServiceTest {
order.verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
order.verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(newJarBytes));
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), any(Path.class),
eq((long) newJarBytes.length));
assertArrayEquals(newJarBytes, copiedJar.get());
verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("stale-readme.txt"));
}
@@ -3717,15 +3883,24 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(pomBytes), pomBytes.length)));
doThrow(new IllegalStateException("sidecar unreachable")).when(reposiliteClient).copyPackageVersionAsset(
eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId), eq("dst"), eq("com.example"), eq("a"), eq("1.0"),
eq("a-1.0.pom"), eq(pomBytes));
eq("a-1.0.pom"), any(Path.class), eq((long) pomBytes.length));
AtomicReference<byte[]> copiedJar = captureCopiedAssetContent(reposiliteClient, srcRepoId, "src", dstRepoId,
"dst", "com.example", "a", "1.0", "a-1.0.jar");
assertThrows(IllegalStateException.class, () -> service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false));
verify(reposiliteClient).copyPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId),
eq("dst"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(jarBytes));
assertArrayEquals(jarBytes, copiedJar.get());
verify(reposiliteClient).deletePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"));
}
@@ -3759,15 +3934,28 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(newPomBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newJarBytes), newJarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newPomBytes), newPomBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(oldJarBytes), oldJarBytes.length)));
doThrow(new IllegalStateException("sidecar unreachable")).when(reposiliteClient).copyPackageVersionAsset(
eq(srcRepoId), eq("dom"), eq("src"), eq(dstRepoId), eq("dst"), eq("com.example"), eq("a"), eq("1.0"),
eq("a-1.0.pom"), eq(newPomBytes));
eq("a-1.0.pom"), any(Path.class), eq((long) newPomBytes.length));
AtomicReference<byte[]> restoredJar = captureStoredAssetContent(reposiliteClient, dstRepoId, "dst",
"com.example", "a", "1.0", "a-1.0.jar");
assertThrows(IllegalStateException.class, () -> service.copyPackageVersions(REGION, "dom", null,
"src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false));
verify(reposiliteClient).storePackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"), eq(oldJarBytes));
assertArrayEquals(oldJarBytes, restoredJar.get());
}
@Test
@@ -3786,6 +3974,10 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "maven", "com.example", "a",
List.of("1.0"), null, false, false);
@@ -3813,6 +4005,14 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(pomBytes), pomBytes.length)));
long before = service.describeDomain(REGION, "dom", null).assetSizeBytes();
service.copyPackageVersions(REGION, "dom", null, "src", "dst", "maven", "com.example", "a",
@@ -3875,6 +4075,10 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(jarBytes), jarBytes.length)));
String describedRevision = service.describePackageVersion(REGION, "dom", null, "src", "maven",
"com.example", "a", "1.0").getRevision();
@@ -4483,6 +4687,10 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(pomBytes));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(digestOf(jarBytes)));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(digestOf(pomBytes)));
CodeArtifactService.PackageVersionAssetsListResult result = service.listPackageVersionAssets(REGION, "dom",
null, "repo", "maven", "com.example", "a", "1.0", null, null);
@@ -4818,8 +5026,8 @@ class CodeArtifactServiceTest {
.thenReturn(true);
when(verdaccioClient.listPackageVersionAssetNames(repoId, "dom", "repo", null, "my-pkg", "1.0.0"))
.thenReturn(List.of("my-pkg-1.0.0.tgz"));
when(verdaccioClient.fetchPackageVersionAsset(repoId, "dom", "repo", null, "my-pkg", "1.0.0",
"my-pkg-1.0.0.tgz")).thenReturn(Optional.of(new byte[] {1, 2, 3}));
when(verdaccioClient.fetchPackageVersionAssetDigest(repoId, "dom", "repo", null, "my-pkg", "1.0.0",
"my-pkg-1.0.0.tgz")).thenReturn(Optional.of(digestOf(new byte[] {1, 2, 3})));
CodeArtifactService.PackageVersionAssetsListResult result = service.listPackageVersionAssets(REGION, "dom",
null, "repo", "npm", null, "my-pkg", "1.0.0", null, null);
@@ -4829,7 +5037,7 @@ class CodeArtifactServiceTest {
order.verify(verdaccioClient).beginUse(repoId);
order.verify(verdaccioClient).packageVersionExists(repoId, "dom", "repo", null, "my-pkg", "1.0.0");
order.verify(verdaccioClient).listPackageVersionAssetNames(repoId, "dom", "repo", null, "my-pkg", "1.0.0");
order.verify(verdaccioClient).fetchPackageVersionAsset(repoId, "dom", "repo", null, "my-pkg", "1.0.0",
order.verify(verdaccioClient).fetchPackageVersionAssetDigest(repoId, "dom", "repo", null, "my-pkg", "1.0.0",
"my-pkg-1.0.0.tgz");
order.verify(verdaccioClient).endUse(repoId);
}
@@ -5412,6 +5620,10 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(new byte[25]));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(digestOf(new byte[40])));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.pom"))).thenReturn(Optional.of(digestOf(new byte[25])));
doThrow(new IllegalStateException("sidecar unreachable"))
.when(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.pom"));
@@ -5633,6 +5845,8 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(digestOf(new byte[40])));
CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
null, "repo", "maven", "com.example", "a", List.of("1.0"), null);
@@ -5958,6 +6172,8 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
when(reposiliteClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(digestOf(new byte[40])));
service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"),
null, null);
@@ -5993,6 +6209,11 @@ class CodeArtifactServiceTest {
when(pypiserverClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0"), eq("my_pkg-1.0-py3-none-any.whl"))).thenAnswer(invocation ->
sdistDeleted.get() ? Optional.empty() : Optional.of(new byte[25]));
when(pypiserverClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0"), eq("my-pkg-1.0.tar.gz"))).thenReturn(Optional.of(digestOf(new byte[40])));
when(pypiserverClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0"), eq("my_pkg-1.0-py3-none-any.whl"))).thenAnswer(invocation ->
sdistDeleted.get() ? Optional.empty() : Optional.of(digestOf(new byte[25])));
doAnswer(invocation -> {
sdistDeleted.set(true);
return null;
@@ -6027,6 +6248,9 @@ class CodeArtifactServiceTest {
when(verdaccioClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenReturn(Optional.of("tgz-bytes".getBytes(
StandardCharsets.UTF_8)));
when(verdaccioClient.fetchPackageVersionAssetDigest(eq(repoId), eq("dom"), eq("repo"), isNull(),
eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"))).thenReturn(Optional.of(digestOf(
"tgz-bytes".getBytes(StandardCharsets.UTF_8))));
recordReadme("dom", "repo", "npm", null, "my-pkg", "1.0.0", "hello");
CodeArtifactService.PackageVersionStatusChangeResult changed = service.updatePackageVersionsStatus(REGION,
@@ -6070,6 +6294,14 @@ class CodeArtifactServiceTest {
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJar));
when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(oldJar));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(srcRepoId), eq("dom"), eq("src"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(newJar), newJar.length)));
when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(dstRepoId), eq("dom"), eq("dst"),
eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation ->
Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(oldJar), oldJar.length)));
when(reposiliteClient.listPackageVersions(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"),
eq("a"))).thenReturn(List.of(
new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
@@ -10,6 +10,8 @@ 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.time.Duration;
import java.util.Map;
import java.util.Optional;
@@ -61,6 +63,34 @@ class MavenExternalConnectionClientTest {
assertArrayEquals(content, result.get().content());
}
/**
* {@code fetchAsset(..., Path)} is the streamed sibling a large Maven release import actually
* uses: unlike the {@code byte[]} overload above, it writes straight to a file via an {@link
* AssetDigestingInputStream}-wrapped copy, so this confirms that wrapping still lands the real
* bytes on disk and reports their real size, not just that the plain {@code byte[]} path works.
*/
@Test
void fetchAssetToAPathWritesTheRealBytesAndReportsTheirSize() throws IOException {
byte[] content = "pom-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/com/example/widget/1.0/widget-1.0.pom", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Path destination = Files.createTempFile("maven-external-connection-test-", ".pom");
try {
Optional<MavenExternalConnectionClient.FetchedFile> result =
client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.pom", destination);
assertTrue(result.isPresent());
assertEquals(content.length, result.get().size());
assertArrayEquals(content, Files.readAllBytes(destination));
} finally {
Files.deleteIfExists(destination);
}
}
@Test
void fetchAssetReturnsEmptyOnA404() throws IOException {
server.createContext("/com/example/widget/1.0/widget-1.0.pom",
@@ -0,0 +1,45 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.io.UncheckedIOException;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MultipartFilePublisherTest {
@Test
void concatBuildsAPublisherAroundAnExistingFile() throws Exception {
Path content = Files.createTempFile("multipart-file-publisher-test-", ".bin");
try {
Files.writeString(content, "the asset's real bytes");
HttpRequest.BodyPublisher publisher = MultipartFilePublisher.concat(
"head\r\n".getBytes(StandardCharsets.UTF_8), content, "\r\ntail".getBytes(StandardCharsets.UTF_8));
assertNotNull(publisher);
} finally {
Files.deleteIfExists(content);
}
}
/**
* {@code BodyPublishers.ofFile} throws a checked {@code FileNotFoundException} synchronously,
* at construction time, for a {@code Path} that doesn't exist; {@link
* MultipartFilePublisher#concat} must turn that into the same unchecked shape every other
* I/O failure in this package already uses, not let a checked exception escape a caller that
* never declared one.
*/
@Test
void concatWrapsAMissingFileIntoAnUncheckedIOException() {
Path missing = Path.of(System.getProperty("java.io.tmpdir"), "multipart-file-publisher-test-missing.bin");
assertThrows(UncheckedIOException.class, () -> MultipartFilePublisher.concat(
"head".getBytes(StandardCharsets.UTF_8), missing, "tail".getBytes(StandardCharsets.UTF_8)));
}
}
@@ -10,6 +10,8 @@ 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.time.Duration;
import java.util.Map;
import java.util.Optional;
@@ -143,6 +145,35 @@ class NpmExternalConnectionClientTest {
assertArrayEquals(content, result.get().content());
}
/**
* {@code fetchTarball(..., Path)} is the streamed sibling that a large tarball import
* actually uses: unlike the {@code byte[]} overload above, it writes straight to a file via
* an {@link AssetDigestingInputStream}-wrapped copy, so this confirms that wrapping still
* lands the real bytes on disk and reports their real size, not just that the plain {@code
* byte[]} path works.
*/
@Test
void fetchTarballToAPathWritesTheRealBytesAndReportsTheirSize() throws IOException {
byte[] content = "tarball-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/-/widget-1.0.0.tgz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Path destination = Files.createTempFile("npm-external-connection-test-", ".tgz");
try {
Optional<NpmExternalConnectionClient.FetchedFile> result =
client.fetchTarball("fake", null, "widget", "1.0.0", destination);
assertTrue(result.isPresent());
assertEquals(content.length, result.get().size());
assertArrayEquals(content, Files.readAllBytes(destination));
} finally {
Files.deleteIfExists(destination);
}
}
@Test
void fetchTarballReturnsEmptyOnA404() throws IOException {
server.createContext("/widget/-/widget-1.0.0.tgz", exchange -> respondEmpty(exchange, 404));
@@ -10,11 +10,14 @@ 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.time.Duration;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -99,6 +102,35 @@ class NuGetExternalConnectionClientTest {
assertArrayEquals(content, result.get().content());
}
/**
* {@code fetchPackage(..., Path)} is the streamed sibling a large {@code .nupkg} import
* actually uses: unlike the {@code byte[]} overload above, it writes straight to a file via
* an {@link AssetDigestingInputStream}-wrapped copy, so this confirms that wrapping still
* lands the real bytes on disk and reports their real size, not just that the plain {@code
* byte[]} path works.
*/
@Test
void fetchPackageToAPathWritesTheRealBytesAndReportsTheirSize() throws IOException {
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Path destination = Files.createTempFile("nuget-external-connection-test-", ".nupkg");
try {
Optional<NuGetExternalConnectionClient.FetchedFile> result =
client.fetchPackage("fake", "widget", "1.0.0", destination);
assertTrue(result.isPresent());
assertEquals(content.length, result.get().size());
assertArrayEquals(content, Files.readAllBytes(destination));
} finally {
Files.deleteIfExists(destination);
}
}
@Test
void fetchPackageReturnsEmptyOnA404() throws IOException {
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 404));
@@ -3,7 +3,10 @@ package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -59,6 +62,28 @@ class NuspecXmlTest {
assertEquals("Demo.Package", metadata.id());
}
/**
* {@code extractFromNupkg(Path)} is the streamed sibling a large {@code .nupkg} push actually
* uses: confirms it reads the same real {@code .nuspec} entry straight off disk, not just that
* the {@code byte[]} overload parses it from a resident array.
*/
@Test
void extractFromNupkgFromAPathFindsTheRootNuspecEntryTheSameWayAsTheByteArrayOverload() throws IOException {
byte[] nupkg = buildNupkg(NUSPEC);
Path staged = Files.createTempFile("nuspec-xml-test-", ".nupkg");
try {
Files.write(staged, nupkg);
NuspecXml.Metadata metadata = NuspecXml.extractFromNupkg(staged);
assertEquals("Demo.Package", metadata.id());
assertEquals("1.0.0", metadata.version());
} finally {
Files.deleteIfExists(staged);
}
}
/** The manifest must sit at the archive root; a same-suffix entry nested in a subdirectory doesn't count. */
@Test
void extractFromNupkgIgnoresANestedNuspecSuffixedEntry() {
@@ -10,6 +10,8 @@ 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.time.Duration;
import java.util.Map;
import java.util.Optional;
@@ -116,6 +118,35 @@ class PypiExternalConnectionClientTest {
assertArrayEquals(content, result.get().content());
}
/**
* {@code fetchFile(..., Path)} is the streamed sibling a large sdist/wheel import actually
* uses: unlike the {@code byte[]} overload above, it writes straight to a file via an {@link
* AssetDigestingInputStream}-wrapped copy, so this confirms that wrapping still lands the
* real bytes on disk and reports their real size, not just that the plain {@code byte[]}
* path works.
*/
@Test
void fetchFileToAPathWritesTheRealBytesAndReportsTheirSize() throws IOException {
byte[] content = "sdist-content".getBytes(StandardCharsets.UTF_8);
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, content.length);
exchange.getResponseBody().write(content);
exchange.close();
});
Path destination = Files.createTempFile("pypi-external-connection-test-", ".tar.gz");
try {
Optional<PypiExternalConnectionClient.FetchedFile> result = client.fetchFile("fake",
serverBaseUrl + "/packages/aa/bb/widget-1.0.0.tar.gz", destination);
assertTrue(result.isPresent());
assertEquals(content.length, result.get().size());
assertArrayEquals(content, Files.readAllBytes(destination));
} finally {
Files.deleteIfExists(destination);
}
}
@Test
void fetchFileReturnsEmptyOnA404() {
server.createContext("/packages/aa/bb/widget-1.0.0.tar.gz", exchange -> respondEmpty(exchange, 404));
@@ -10,10 +10,13 @@ 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.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -75,6 +78,63 @@ class PypiserverSidecarClientTest {
assertEquals("sdist bytes", new String(result.get(), StandardCharsets.UTF_8));
}
/**
* {@link #fetchPackageVersionAssetGetsTheFlatPackagesPath}'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 fetchPackageVersionAssetStreamedGetsTheFlatPackagesPath() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
respondWithSimpleIndex("demo-pkg", "demo_pkg-1.0.0.tar.gz");
backend.createContext("/packages/demo_pkg-1.0.0.tar.gz", exchange -> {
byte[] body = "sdist bytes".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
Optional<RepositorySidecarManager.StreamedAsset> result = client(manager).fetchPackageVersionAssetStreamed(
"pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0", "demo_pkg-1.0.0.tar.gz");
assertTrue(result.isPresent());
try (InputStream in = result.get().content()) {
assertEquals("sdist bytes", new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
assertEquals(11, result.get().contentLength());
}
/**
* {@link PypiserverSidecarClient#storePackageVersionAsset(String, String, String, String,
* String, String, String, Path, long)}'s own wire contract: the staged file's real content
* ends up in the multipart body's {@code content} part, not just some bytes of the right
* length, built via {@code BodyPublishers.concat} rather than one combined array.
*/
@Test
void storePackageVersionAssetStreamedSendsTheStagedFilesRealContent() throws Exception {
PypiserverSidecarManager manager = manager();
seedPooledContainer(manager, "pypi-repo-1", "tracked-pypiserver-1", backendUrl);
Path staged = Files.createTempFile("pypiserver-client-test-", ".tmp");
Files.writeString(staged, "staged sdist bytes");
AtomicReference<byte[]> received = new AtomicReference<>();
backend.createContext("/", exchange -> {
received.set(exchange.getRequestBody().readAllBytes());
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
try {
client(manager).storePackageVersionAsset("pypi-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0",
"demo_pkg-1.0.0.tar.gz", staged, Files.size(staged));
} finally {
Files.deleteIfExists(staged);
}
String body = new String(received.get(), StandardCharsets.UTF_8);
assertTrue(body.contains("staged sdist bytes"));
}
/**
* The fix for a real finding: the filename alone was trusted as proof of version, so a caller
* could request a different (even nonexistent) version and still get back a real file that
@@ -11,11 +11,14 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -349,6 +352,64 @@ class ReposiliteSidecarClientTest {
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), putBody.get());
}
/**
* {@link #deployArtifactPutsTheBytesAndReturnsTheStatus}'s own streamed sibling: the file's
* real content ends up in the PUT body, sent via {@code BodyPublishers.ofFile} rather than a
* resident array.
*/
@Test
void deployArtifactFromAPathPutsTheBytesAndReturnsTheStatus() throws Exception {
AtomicReference<byte[]> received = new AtomicReference<>();
AtomicReference<String> authHeader = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
authHeader.set(exchange.getRequestHeaders().getFirst("Authorization"));
received.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
Path staged = Files.createTempFile("reposilite-client-test-", ".tmp");
try {
Files.writeString(staged, "hello");
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
"com/example/a/1.0/a-1.0.jar", staged);
assertThat(outcome.status(), is(200));
assertTrue(outcome.wroteNewContent());
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), received.get());
assertThat(authHeader.get(), equalTo("Basic dGVzdDp0ZXN0"));
} finally {
Files.deleteIfExists(staged);
}
}
/**
* {@link #deployArtifactShortCircuitsToTwoHundredWithoutPuttingWhenContentIsByteIdentical}'s
* own streamed sibling: the idempotent-match preflight compares the staged file against the
* existing artifact in a lockstep stream comparison rather than one resident array against
* another, and must short-circuit the same way once they match.
*/
@Test
void deployArtifactFromAPathShortCircuitsToTwoHundredWithoutPuttingWhenContentIsByteIdentical() throws Exception {
List<String> methodsSeen = new CopyOnWriteArrayList<>();
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
methodsSeen.add(exchange.getRequestMethod());
respond(exchange, 200, "hello");
});
Path staged = Files.createTempFile("reposilite-client-test-", ".tmp");
try {
Files.writeString(staged, "hello");
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
"com/example/a/1.0/a-1.0.jar", staged);
assertThat(outcome.status(), is(200));
assertFalse(outcome.wroteNewContent());
assertThat(methodsSeen, equalTo(List.of("GET")));
} finally {
Files.deleteIfExists(staged);
}
}
@Test
void fetchArtifactReturnsBytesAndContentTypeOnSuccess() {
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
@@ -373,6 +434,39 @@ class ReposiliteSidecarClientTest {
assertTrue(artifact.isEmpty());
}
/**
* {@link #fetchArtifactReturnsBytesAndContentTypeOnSuccess}'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 fetchArtifactStreamedReturnsTheStreamContentTypeAndLength() throws Exception {
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
exchange.getResponseHeaders().set("Content-Type", "application/java-archive");
respond(exchange, 200, "jar-bytes");
});
Optional<ReposiliteSidecarClient.StreamedArtifact> artifact =
client.fetchArtifactStreamed("dom--repo", "com/example/a/1.0/a-1.0.jar");
assertTrue(artifact.isPresent());
try (InputStream in = artifact.get().content()) {
assertArrayEquals("jar-bytes".getBytes(StandardCharsets.UTF_8), in.readAllBytes());
}
assertThat(artifact.get().contentType(), equalTo("application/java-archive"));
assertThat(artifact.get().contentLength(), is(9L));
}
@Test
void fetchArtifactStreamedIsEmptyOnNotFound() {
server.createContext("/dom--repo/missing.jar", exchange -> respond(exchange, 404, ""));
Optional<ReposiliteSidecarClient.StreamedArtifact> artifact =
client.fetchArtifactStreamed("dom--repo", "missing.jar");
assertTrue(artifact.isEmpty());
}
@Test
void fetchPackageVersionAssetBuildsTheGavPathFromTheGroupIdArtifactIdVersionAndFilename() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
@@ -386,6 +480,27 @@ class ReposiliteSidecarClientTest {
assertArrayEquals("jar-bytes".getBytes(StandardCharsets.UTF_8), result.get());
}
/**
* {@link #fetchPackageVersionAssetBuildsTheGavPathFromTheGroupIdArtifactIdVersionAndFilename}'s
* own streamed sibling.
*/
@Test
void fetchPackageVersionAssetStreamedBuildsTheGavPathFromTheGroupIdArtifactIdVersionAndFilename()
throws Exception {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get()));
server.createContext("/dom--repo/com/example/nested/a/1.0/a-1.0.jar", exchange -> respond(exchange, 200, "jar-bytes"));
Optional<RepositorySidecarManager.StreamedAsset> result = client.fetchPackageVersionAssetStreamed(
"dom--repo", "dom", "repo", "com.example.nested", "a", "1.0", "a-1.0.jar");
assertTrue(result.isPresent());
try (InputStream in = result.get().content()) {
assertArrayEquals("jar-bytes".getBytes(StandardCharsets.UTF_8), in.readAllBytes());
}
assertThat(result.get().contentLength(), is(9L));
}
/**
* The fix for a real finding: building the request URI with a plain string concatenation
* would let a {@code #} in a caller-supplied asset name get interpreted as a URI fragment and
@@ -3,6 +3,7 @@ package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -86,4 +87,34 @@ class SidecarUriUtilsTest {
assertThat(result.getRawAuthority(), equalTo("user%2Ftenant@example.com"));
}
@Test
void transferTimeoutIsJustTheFixedFloorForATinyUpload() {
assertThat(SidecarUriUtils.transferTimeout(0), equalTo(Duration.ofSeconds(30)));
}
@Test
void transferTimeoutScalesWithContentLengthPastTheFixedFloor() {
long twentyMebibytes = 20L * 1024 * 1024;
assertThat(SidecarUriUtils.transferTimeout(twentyMebibytes), equalTo(Duration.ofSeconds(32)));
}
/**
* {@link SidecarUriUtils#maxTransferTimeout()} is the worst-case sibling every real asset
* download (every sidecar client's own streamed read, every external-connection client's real
* registry fetch) uses instead of a flat, small timeout: confirms it is exactly {@link
* SidecarUriUtils#transferTimeout} evaluated at the real 5 GB asset quota, not some other,
* drifted value.
*/
@Test
void maxTransferTimeoutMatchesTransferTimeoutAtTheRealAssetQuota() {
assertThat(SidecarUriUtils.maxTransferTimeout(),
equalTo(SidecarUriUtils.transferTimeout(CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES)));
}
@Test
void maxTransferTimeoutIsGenerousEnoughForARealMultiGigabyteDownload() {
assertThat(SidecarUriUtils.maxTransferTimeout().compareTo(Duration.ofMinutes(5)) > 0, equalTo(true));
}
}
@@ -0,0 +1,54 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StreamEqualityTest {
@Test
void contentsMatchIsTrueForByteIdenticalStreams() throws IOException {
byte[] content = new byte[64 * 1024 + 37];
new Random(7).nextBytes(content);
boolean matches = StreamEquality.contentsMatch(new ByteArrayInputStream(content),
new ByteArrayInputStream(content.clone()));
assertTrue(matches);
}
@Test
void contentsMatchIsFalseWhenOneStreamIsShorter() throws IOException {
byte[] longer = new byte[1000];
byte[] shorter = new byte[900];
boolean matches = StreamEquality.contentsMatch(new ByteArrayInputStream(longer),
new ByteArrayInputStream(shorter));
assertFalse(matches);
}
@Test
void contentsMatchIsFalseOnASingleByteDifferenceFarPastTheFirstBuffer() throws IOException {
byte[] a = new byte[200_000];
byte[] b = a.clone();
b[150_000] = (byte) (b[150_000] + 1);
boolean matches = StreamEquality.contentsMatch(new ByteArrayInputStream(a), new ByteArrayInputStream(b));
assertFalse(matches);
}
@Test
void contentsMatchIsTrueForTwoEmptyStreams() throws IOException {
boolean matches = StreamEquality.contentsMatch(new ByteArrayInputStream(new byte[0]),
new ByteArrayInputStream(new byte[0]));
assertTrue(matches);
}
}
@@ -11,13 +11,19 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
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.util.Base64;
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 static org.junit.jupiter.api.Assertions.assertEquals;
@@ -74,6 +80,33 @@ class VerdaccioSidecarClientTest {
assertEquals("tarball bytes", new String(result.get(), StandardCharsets.UTF_8));
}
/**
* {@link #fetchPackageVersionAssetGetsTheUnscopedTarballPath}'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 fetchPackageVersionAssetStreamedGetsTheUnscopedTarballPath() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", backendUrl);
respondWithMetadata("/demo-pkg", "1.0.0", "/demo-pkg/-/demo-pkg-1.0.0.tgz");
backend.createContext("/demo-pkg/-/demo-pkg-1.0.0.tgz", exchange -> {
byte[] body = "tarball bytes".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
Optional<RepositorySidecarManager.StreamedAsset> result = client(manager).fetchPackageVersionAssetStreamed(
"npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0", "demo-pkg-1.0.0.tgz");
assertTrue(result.isPresent());
try (InputStream in = result.get().content()) {
assertEquals("tarball bytes", new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
assertEquals(13, result.get().contentLength());
}
/**
* Confirmed against a live Verdaccio container: a scoped package's tarball path keeps the
* {@code @scope/} segment in the URL even though the filename itself never includes it
@@ -227,6 +260,72 @@ class VerdaccioSidecarClientTest {
assertTrue(sentBody.path("dist-tags").isMissingNode(), "must not send its own dist-tags: " + observedBody.get());
}
/**
* {@code storePackageVersionAsset(..., Path, long)}'s own streamed body, built from explicit
* JSON prefix/suffix fragments around a piped base64 encoder, not {@code mapper
* .writeValueAsBytes} the way the {@code byte[]} overload's body still is, must still be
* byte-for-byte the same request body a real Verdaccio instance would otherwise see from the
* {@code byte[]} overload for the exact same content: this sends both for identical input and
* compares the two captured request bodies directly, rather than only checking the streamed
* one parses as valid JSON with the fields it expects.
*/
@Test
void storePackageVersionAssetFromAPathSendsTheExactSameBodyAsTheByteArrayOverload() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", backendUrl);
byte[] content = "tarball bytes, twice over".getBytes(StandardCharsets.UTF_8);
List<String> observedBodies = new CopyOnWriteArrayList<>();
backend.createContext("/demo-pkg", exchange -> {
observedBodies.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
client(manager).storePackageVersionAsset("npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0",
"demo-pkg-1.0.0.tgz", content);
Path staged = Files.createTempFile("verdaccio-test-", ".bin");
try {
Files.write(staged, content);
client(manager).storePackageVersionAsset("npm-repo-1", "dom", "repo", null, "demo-pkg", "1.0.0",
"demo-pkg-1.0.0.tgz", staged, content.length);
} finally {
Files.deleteIfExists(staged);
}
assertEquals(2, observedBodies.size());
assertEquals(observedBodies.get(0), observedBodies.get(1));
JsonNode sentBody = new ObjectMapper().readTree(observedBodies.get(1));
assertEquals("application/octet-stream", sentBody.path("_attachments")
.path("demo-pkg-1.0.0.tgz").path("content_type").asText());
assertEquals(content.length, sentBody.path("_attachments").path("demo-pkg-1.0.0.tgz")
.path("length").asLong());
assertEquals(Base64.getEncoder().encodeToString(content), sentBody.path("_attachments")
.path("demo-pkg-1.0.0.tgz").path("data").asText());
}
/**
* Raised by Qodo's review of this PR: {@code base64EncodingStream}'s writer thread used to
* simply close the pipe on its own read failure, which {@link PipedInputStream} cannot tell
* apart from the writer finishing normally — a real mid-publish failure (the staged file
* disappearing out from under it, say) would read as an ordinary clean EOF, silently sending
* a shorter payload than the {@code shasum}/{@code integrity}/{@code length} fields (computed
* from the file before this stream ever opened it) still claim. Targets {@code
* base64EncodingStream} directly (package-private for exactly this): a nonexistent path makes
* the writer's very first read fail, the simplest reproduction of "the writer failed before
* producing everything it was supposed to," which is the one property this fix actually
* changes, regardless of how far into the transfer the real failure happens to land.
*/
@Test
void base64EncodingStreamFailsRatherThanReadingAsACleanEofWhenTheFileIsGone() throws IOException {
Path missing = Files.createTempFile("verdaccio-test-", ".bin");
Files.delete(missing);
InputStream encoding = VerdaccioSidecarClient.base64EncodingStream(missing);
assertThrows(IOException.class, encoding::read);
}
/**
* Mirrors the real npm unpublish mechanism, confirmed against a live Verdaccio container: GET
* the packument for its {@code _rev}, then {@code DELETE} the package path with that revision
@@ -5,17 +5,14 @@ import io.floci.aws.core.storage.InMemoryStorage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@@ -67,21 +64,4 @@ class S3ObjectStreamTest {
assertArrayEquals(first, body.readAllBytes());
}
}
@Test
void responseThatFailsToBuildClosesTheObjectStream() {
AtomicBoolean closed = new AtomicBoolean();
InputStream body = new ByteArrayInputStream(new byte[16]) {
@Override
public void close() {
closed.set(true);
}
};
assertThrows(NullPointerException.class, () -> S3Controller.streamingResponse(body, stream -> {
throw new NullPointerException("Last-Modified is missing");
}));
assertTrue(closed.get(), "the object stream was left open");
}
}