diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index d1ef73e096..abc149ed21 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -302,9 +302,9 @@ state. own write touched if a later step in that same version fails, preserving the original error, but a sidecar outage mid-cleanup can still leave a version in an inconsistent state, the same residual risk the generic path's own write-level failure handling already accepts. A single call - also holds every fetched asset in memory until the whole batch's destination writes complete, so - a batch of many large assets is bounded by available heap, not disk; the same nominal-quota - tradeoff the 5 GB limitation below already accepts elsewhere. A copied `npm` or `pypi` version's + stages every fetched asset to disk, not memory, for the whole batch's duration (cleaned up when + the call returns, success or failure), so a batch of many large assets is bounded by available + disk, not heap. A copied `npm` or `pypi` version's readme is propagated to the destination too, from this service's own record captured at publish time, since neither sidecar can answer for one after the fact (`GetPackageVersionReadme`'s own constraint, described earlier in this document); `nuget` needs no equivalent step, since @@ -313,12 +313,44 @@ state. own upstream-repository chain specifically, which this emulator does not resolve for any format yet (see the upstream-resolution limitation below). Maven's own external-connection retention is a different mechanism and does not change this. -- **The 5 GB asset size quota is nominal.** `PublishPackageVersion` and the Maven, pypi, and - nuget repository endpoints all receive the request body as a single byte array before Floci ever - checks its length, so a request already large enough to exhaust available heap fails before the - quota check runs. The rejection (`ServiceQuotaExceededException` from `PublishPackageVersion`, - HTTP 413 from the Maven, pypi, and nuget endpoints) is correct for anything that does fit in - memory; it is not itself a streaming size limit. +- **`CopyPackageVersions` holds this service's one write lock for the whole call, including the + disk staging and sidecar streaming a large batch now needs.** Every package-mutating method + here (`CreateDomain`, `PublishPackageVersion`, `DeletePackageVersions`, ...) shares one lock, so + only one such call runs at a time across every domain and repository, not just the one being + touched; that has always been true and is fine as long as what runs under the lock is fast. + `PublishPackageVersion` was specifically restructured to stage and digest a large upload + *before* taking this lock, so a multi-GB publish doesn't serialize every other call for as long + as it takes to read; `CopyPackageVersions` was not given the same treatment, since its own + validation (`NOT_FOUND`/`Disposed`/`MISMATCHED_REVISION`/content-match/`ALREADY_EXISTS`, all-or- + nothing across up to 100 requested versions) would need to be re-derived against a staged-then- + committed shape to split safely, a real design task rather than a mechanical move. A single + call copying many large versions can therefore hold up every other CodeArtifact request for as + long as that whole batch takes, not just slow down the one call itself. +- **The 5 GB asset size quota is a real streaming limit for `generic`, Maven, pypi, and nuget, + with two exceptions.** Every upload and download path (direct publish, the native Maven/pypi/ + nuget proxies, `GetPackageVersionAsset`, and `CopyPackageVersions`) stages an asset to disk and + streams it rather than holding it as one JVM array, so none of them are bound by the ~2 GiB + `byte[]` limit that would otherwise sit well under AWS's own 5 GB quota. Two things still cap a + real upload below that: + - **Every request body is still capped by `FLOCI_PROTOCOLS_MAX_REQUEST_SIZE`, 2048 MB by + default** (the same global limit [S3](s3.md) documents): raise it past 5120 to accept a 5 GiB + asset, the same adjustment a 5 GiB S3 `PutObject` needs. + - **In `floci.storage.mode: memory` (the shipped default), a `generic` asset's bytes are a + single in-memory `byte[]`**, so one can hold at most about 2 GiB there, the same ~2 GiB + ceiling S3 documents for its own `memory` mode (see [S3](s3.md#storage)); past that, the + publish fails with an uncaught `OutOfMemoryError` rather than a clean rejection. Unlike S3, + CodeArtifact has no per-service storage-mode override (`FLOCI_STORAGE_SERVICES_S3_MODE`'s own + equivalent does not exist here): set the global `FLOCI_STORAGE_MODE=persistent` (or `hybrid`/ + `wal`) to lift this. Maven, npm, pypi, and nuget assets are unaffected either way, since their + real bytes always live in their own sidecar container, never in this map. + - **npm has its own, separate, much lower ceiling that no Floci-side configuration changes:** + real npm's publish protocol embeds the whole tarball as one base64 string inside a JSON + document, and Verdaccio (the sidecar behind this proxy) converts the whole received body to a + single JavaScript string before parsing it. Past roughly a 500 MB asset (confirmed between + 200 MB, which succeeds, and 500 MB, which does not), that conversion hits V8's own hard maximum + string length and crashes the Verdaccio process outright with an uncaught `RangeError: Invalid + string length`, not a clean rejection either. This is a limitation of real npm's own wire + protocol as Verdaccio implements it, not something this emulator's own code can stream around. - **Maven artifacts, npm packages, pypi packages, and NuGet packages do not survive a Floci restart, even under persistent storage.** The Reposilite instance and every per-repository Verdaccio, pypiserver, and BaGetter container have no volume attached and are removed on shutdown diff --git a/src/main/java/io/floci/aws/core/common/Digests.java b/src/main/java/io/floci/aws/core/common/Digests.java index 91abf3ea56..974299495e 100644 --- a/src/main/java/io/floci/aws/core/common/Digests.java +++ b/src/main/java/io/floci/aws/core/common/Digests.java @@ -9,16 +9,32 @@ import java.util.HexFormat; public final class Digests { private static final MessageDigest MD5 = newDigest("MD5"); + private static final MessageDigest SHA1 = newDigest("SHA-1"); + private static final MessageDigest SHA512 = newDigest("SHA-512"); private Digests() { } /** A fresh MD5 digest. Cloning the prototype costs far less than MessageDigest.getInstance. */ public static MessageDigest md5Digest() { + return cloneOrFresh(MD5, "MD5"); + } + + /** A fresh SHA-1 digest. Cloning the prototype costs far less than MessageDigest.getInstance. */ + public static MessageDigest sha1Digest() { + return cloneOrFresh(SHA1, "SHA-1"); + } + + /** A fresh SHA-512 digest. Cloning the prototype costs far less than MessageDigest.getInstance. */ + public static MessageDigest sha512Digest() { + return cloneOrFresh(SHA512, "SHA-512"); + } + + private static MessageDigest cloneOrFresh(MessageDigest prototype, String algorithm) { try { - return (MessageDigest) MD5.clone(); + return (MessageDigest) prototype.clone(); } catch (CloneNotSupportedException e) { - return newDigest("MD5"); + return newDigest(algorithm); } } @@ -40,11 +56,7 @@ public final class Digests { } public static byte[] sha1(byte[] data) { - try { - return MessageDigest.getInstance("SHA-1").digest(data); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-1 is not available", e); - } + return sha1Digest().digest(data); } /** The SHA-1 digest of {@code data} as lowercase hex. */ diff --git a/src/main/java/io/floci/aws/core/common/MultipartFormParser.java b/src/main/java/io/floci/aws/core/common/MultipartFormParser.java index 2ede1c29d3..d1ebaa2937 100644 --- a/src/main/java/io/floci/aws/core/common/MultipartFormParser.java +++ b/src/main/java/io/floci/aws/core/common/MultipartFormParser.java @@ -1,6 +1,13 @@ package io.floci.aws.core.common; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; @@ -170,6 +177,263 @@ public final class MultipartFormParser { return headers.substring(valueStart, lineEnd).trim(); } + /** Small text fields plus, when present, the one file part's name/filename/content-type. */ + public record ExtractedFile(String fieldName, String filename, String contentType) {} + + /** {@link ParsedForm}'s streamed sibling; see {@link #file()} for why this isn't a record component. */ + public record ExtractedForm(Map fields, ExtractedFile fileOrNull) { + public Optional file() { + return Optional.ofNullable(fileOrNull); + } + } + + private static final int MAX_HEADER_BYTES = 64 * 1024; + /** + * Raised from an earlier 64 KiB (Copilot's review of this PR): a real {@code twine upload} + * sends a project's long description/README as an ordinary text field, not the file part, and + * a real README can comfortably exceed 64 KiB, so that cap rejected legitimate uploads this + * parser's own predecessor ({@link #parse}) never capped at all. + */ + private static final int MAX_FIELD_VALUE_BYTES = 8 * 1024 * 1024; + /** + * Bounds the combined size of every text field together, independent of {@link + * #MAX_FIELD_VALUE_BYTES}'s own per-field cap (Copilot's review of this PR): without this, a + * multipart body carrying many distinct, uniquely-named fields each just under the per-field + * cap could still accumulate nearly the whole multi-GB envelope in {@code fields} on the heap, + * defeating the reason this streamed sibling of {@link #parse} exists at all. + */ + private static final int MAX_TOTAL_FIELD_BYTES = 16 * 1024 * 1024; + + /** + * {@link #parse}'s streamed sibling, for a {@code multipart/form-data} body too large to hold + * in one {@code byte[]}: {@code stagedWholeBody} is the whole raw request body already written + * to disk by the caller, and only the one part whose {@code Content-Disposition} carries a + * {@code filename} parameter is ever copied anywhere further, out of {@code stagedWholeBody} + * and into {@code destinationFile}, so neither the whole multipart envelope nor that one + * part's own content is ever held in a single JVM array, however large either is. Small text + * fields (name/version and the like) are still buffered directly, since those are always a + * handful of bytes in practice; a boundary marker is still found correctly even when it + * straddles two separate chunk reads of the staged file, via an explicit carried-over overlap + * window (see {@link #copyUntilDelimiter}). If more than one part carries a {@code filename} + * parameter, the last one wins and is the one left in {@code destinationFile}, matching {@link + * #parse}'s own last-file-wins behavior. Inherits {@link #parse}'s own boundary-matching + * limitation as-is: a boundary string that happens to occur literally inside binary file + * content is not escaped against, the same as today. + */ + public static ExtractedForm extractFilePart(Path stagedWholeBody, String boundary, Path destinationFile) + throws IOException { + byte[] boundaryBytes = ("--" + boundary).getBytes(StandardCharsets.UTF_8); + Map fields = new LinkedHashMap<>(); + ExtractedFile file = null; + long totalFieldBytes = 0; + if (destinationFile.getParent() != null) { + Files.createDirectories(destinationFile.getParent()); + } + try (InputStream raw = Files.newInputStream(stagedWholeBody)) { + PushbackScanner scanner = new PushbackScanner(raw); + // The body's own preamble (anything before the first boundary) is discarded, matching + // parse's own indexOf-from-zero: a leading boundary need not be preceded by content. + if (!skipToNextOccurrence(scanner, boundaryBytes)) { + return new ExtractedForm(fields, null); + } + while (!isClosingBoundary(scanner)) { + consumeOptionalCrlf(scanner); + ByteArrayOutputStream headerBytes = new ByteArrayOutputStream(); + copyUntilDelimiter(scanner, CRLFCRLF, headerBytes, MAX_HEADER_BYTES, false); + String headers = headerBytes.toString(StandardCharsets.UTF_8); + String disposition = extractHeaderValue(headers, "Content-Disposition"); + String fieldName = disposition == null ? null : extractDispositionParam(disposition, "name"); + String filename = disposition == null ? null : extractDispositionParam(disposition, "filename"); + if (fieldName != null && filename != null) { + String partContentType = extractHeaderValue(headers, "Content-Type"); + try (OutputStream out = Files.newOutputStream(destinationFile, StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { + copyUntilDelimiter(scanner, boundaryBytes, out, Long.MAX_VALUE, true); + } + file = new ExtractedFile(fieldName, filename, partContentType == null ? null + : partContentType.trim()); + } else if (fieldName != null) { + ByteArrayOutputStream value = new ByteArrayOutputStream(); + copyUntilDelimiter(scanner, boundaryBytes, value, MAX_FIELD_VALUE_BYTES, true); + totalFieldBytes += value.size(); + if (totalFieldBytes > MAX_TOTAL_FIELD_BYTES) { + throw new IOException("Multipart body's text fields together exceeded the maximum " + + "allowed combined size."); + } + fields.put(fieldName, value.toString(StandardCharsets.UTF_8)); + } else { + // A part with no Content-Disposition name at all is skipped, matching parse's + // own "no fieldName -> continue" behavior. + copyUntilDelimiter(scanner, boundaryBytes, OutputStream.nullOutputStream(), Long.MAX_VALUE, + true); + } + } + } + return new ExtractedForm(fields, file); + } + + private static final byte[] CRLFCRLF = "\r\n\r\n".getBytes(StandardCharsets.UTF_8); + + /** True once a closing {@code --boundary--} is seen; otherwise consumes nothing further. */ + private static boolean isClosingBoundary(PushbackScanner scanner) throws IOException { + byte[] two = scanner.readExactly(2); + if (two != null && two[0] == '-' && two[1] == '-') { + return true; + } + if (two != null) { + scanner.unread(two, 0); + } + return false; + } + + private static void consumeOptionalCrlf(PushbackScanner scanner) throws IOException { + byte[] two = scanner.readExactly(2); + if (two == null) { + return; + } + if (two[0] != '\r' || two[1] != '\n') { + scanner.unread(two, 0); + } + } + + /** Discards everything up to and including the first occurrence of {@code delimiter}. */ + private static boolean skipToNextOccurrence(PushbackScanner scanner, byte[] delimiter) throws IOException { + try { + copyUntilDelimiter(scanner, delimiter, OutputStream.nullOutputStream(), Long.MAX_VALUE, false); + return true; + } catch (IOException e) { + return false; + } + } + + /** + * Copies everything read from {@code scanner} into {@code sink} up to (never including) the + * next occurrence of {@code delimiter}, leaving the scanner positioned exactly after the + * matched delimiter bytes. Never holds more than one chunk plus {@code delimiter.length - 1} + * carried-over bytes in memory at once, however far apart two reads of the underlying stream + * place a delimiter that straddles them. When {@code trimTrailingCrlf} is set (every real + * field/file part's content, never a header block), a {@code \r\n} immediately before the + * delimiter is dropped rather than written, matching the real content that preceded it: a + * carried-over window is always at least {@code delimiter.length - 1} bytes, several times + * larger than 2, so those two bytes are never written out before the delimiter they precede is + * confirmed to be the real match. + */ + private static void copyUntilDelimiter(PushbackScanner scanner, byte[] delimiter, OutputStream sink, + long maxBytes, boolean trimTrailingCrlf) throws IOException { + byte[] chunk = new byte[64 * 1024]; + byte[] carry = new byte[0]; + long written = 0; + while (true) { + int read = scanner.read(chunk); + if (read < 0) { + throw new IOException("Multipart body ended before its own delimiter was found."); + } + byte[] combined = new byte[carry.length + read]; + System.arraycopy(carry, 0, combined, 0, carry.length); + System.arraycopy(chunk, 0, combined, carry.length, read); + int idx = indexOf(combined, delimiter, 0); + if (idx >= 0) { + int end = idx; + if (trimTrailingCrlf && end >= 2 && combined[end - 2] == '\r' && combined[end - 1] == '\n') { + end -= 2; + } + written += end; + if (written > maxBytes) { + throw new IOException("Multipart part exceeded the maximum allowed size before its own " + + "delimiter was found."); + } + sink.write(combined, 0, end); + scanner.unread(combined, idx + delimiter.length); + return; + } + // When trimTrailingCrlf is set, the carried-over window must hold 2 bytes more than the + // minimum needed to find a split delimiter: a match can land as early as index 0 of the + // NEXT combined buffer (when a chunk read happens to end exactly delimiter.length - 1 + // bytes before the delimiter's own start), and the trim check below only ever looks at + // bytes still inside combined. Without this extra margin, the CRLF immediately before + // such a match would already have been flushed to sink by a prior iteration as if it + // were real content, before this method ever gets a chance to inspect, let alone trim, + // it. + int reserve = delimiter.length - 1 + (trimTrailingCrlf ? 2 : 0); + int keep = Math.min(combined.length, reserve); + int flush = combined.length - keep; + written += flush; + if (written > maxBytes) { + throw new IOException("Multipart part exceeded the maximum allowed size before its own " + + "delimiter was found."); + } + sink.write(combined, 0, flush); + carry = Arrays.copyOfRange(combined, flush, combined.length); + } + } + + /** + * A thin pushback wrapper so {@link #copyUntilDelimiter} can hand back the bytes it read past + * a delimiter match for the next caller to consume, without the two needing to share any other + * state: {@link java.io.PushbackInputStream} only supports pushing back as many bytes as its + * own fixed buffer size, declared up front, which does not fit this method's variable-length + * unread. + */ + private static final class PushbackScanner { + private final InputStream in; + private byte[] pending = new byte[0]; + private int pendingPos; + + PushbackScanner(InputStream in) { + this.in = in; + } + + int read(byte[] buffer) throws IOException { + if (pendingPos < pending.length) { + int n = Math.min(buffer.length, pending.length - pendingPos); + System.arraycopy(pending, pendingPos, buffer, 0, n); + pendingPos += n; + return n; + } + return in.read(buffer); + } + + /** + * Puts {@code data[from:]} back so the next {@link #read} serves it first, ahead of + * whatever this scanner was still holding unconsumed in {@code pending} at the time this + * is called (a single caller-facing read, like {@link #readExactly}'s own 2-byte peeks, + * only ever drains part of a larger {@code pending}, so the rest must be preserved, not + * replaced). + */ + void unread(byte[] data, int from) { + byte[] unreadPart = Arrays.copyOfRange(data, from, data.length); + byte[] remaining = Arrays.copyOfRange(pending, pendingPos, pending.length); + byte[] combined = new byte[unreadPart.length + remaining.length]; + System.arraycopy(unreadPart, 0, combined, 0, unreadPart.length); + System.arraycopy(remaining, 0, combined, unreadPart.length, remaining.length); + pending = combined; + pendingPos = 0; + } + + /** Reads exactly {@code count} bytes, or returns {@code null} on reaching end of stream first. */ + byte[] readExactly(int count) throws IOException { + byte[] result = new byte[count]; + int total = 0; + while (total < count) { + int read = read(result, total, count - total); + if (read < 0) { + return null; + } + total += read; + } + return result; + } + + private int read(byte[] buffer, int offset, int length) throws IOException { + byte[] tmp = new byte[length]; + int n = read(tmp); + if (n > 0) { + System.arraycopy(tmp, 0, buffer, offset, n); + } + return n; + } + } + private static String extractDispositionParam(String disposition, String paramName) { String search = paramName + "="; int idx = disposition.indexOf(search); diff --git a/src/main/java/io/floci/aws/core/common/StreamingResponses.java b/src/main/java/io/floci/aws/core/common/StreamingResponses.java new file mode 100644 index 0000000000..fd4a1d6fff --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/StreamingResponses.java @@ -0,0 +1,87 @@ +package io.floci.aws.core.common; + +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.function.Function; + +/** + * Builds a JAX-RS {@link Response} whose entity streams an already-open {@link InputStream} + * straight through to the client, never buffering it into a {@code byte[]} first. + */ +public final class StreamingResponses { + + private StreamingResponses() { + } + + /** + * Builds a response whose entity streams {@code body} and then closes it. If building the + * response fails, the entity is never written, so {@code body} is closed here instead. + */ + public static Response streamingResponse(InputStream body, Function build) { + StreamingOutput stream = output -> { + try (InputStream in = body) { + in.transferTo(output); + } + }; + try { + return build.apply(stream); + } catch (RuntimeException e) { + closeQuietly(body); + throw e; + } + } + + /** + * Closes {@code in}, discarding any {@link IOException}: every caller uses this on a stream + * it is abandoning (a failed response build, a redirect hop's unread body, a short-circuited + * fetch), where nothing downstream depends on the close completing cleanly and the only + * alternative to swallowing it is a log line nobody acts on. {@code in} being {@code null} is + * itself treated as nothing to close, not an error: a caller that only conditionally opened a + * stream before reaching its own cleanup (one branch of a {@code try}/{@code finally} that + * never got that far) shouldn't have to null-check before calling this, and an uncaught + * {@code NullPointerException} here, inside a {@code finally}, would silently skip whatever + * cleanup was meant to run after it. + */ + public static void closeQuietly(InputStream in) { + if (in == null) { + return; + } + try { + in.close(); + } catch (IOException ignored) { + } + } + + /** + * Wraps {@code in} so that closing it also runs {@code afterClose} exactly once, right after + * the underlying stream's own close completes. For a caller that hands this stream off to be + * drained later by someone else (a deferred {@link StreamingOutput}, built from this class's + * own {@link #streamingResponse}), the wrapped stream's eventual close is the only reliable + * signal that the real read is actually finished: a resource tied to {@code in} staying open + * for as long as the read takes (e.g. a sidecar-container use lease) must not be released any + * earlier than that, even though the method that obtained {@code in} returns long before the + * drain happens. + */ + public static InputStream closingWith(InputStream in, Runnable afterClose) { + return new FilterInputStream(in) { + private boolean closed; + + @Override + public void close() throws IOException { + if (closed) { + return; + } + closed = true; + try { + super.close(); + } finally { + afterClose.run(); + } + } + }; + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/AssetDigestingInputStream.java b/src/main/java/io/floci/aws/services/codeartifact/AssetDigestingInputStream.java new file mode 100644 index 0000000000..d7ed9e0ae8 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/AssetDigestingInputStream.java @@ -0,0 +1,137 @@ +package io.floci.aws.services.codeartifact; + +import io.floci.aws.core.common.auth.SigV4RequestValidator; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Passes an asset upload through while computing every {@code CodeArtifactService + * .ASSET_HASH_ALGORITHMS} digest and its size, so a large asset can be staged to disk without ever + * being held whole in a JVM array. Once more than {@code maxSize} bytes have been read, throws + * {@link AssetTooLargeException} rather than the digest/size this stream would otherwise report; + * each caller maps that to whatever response shape it already uses for an over-quota asset. + */ +final class AssetDigestingInputStream extends FilterInputStream { + + private static final List ALGORITHMS = List.of("MD5", "SHA-1", "SHA-256", "SHA-512"); + + /** Thrown once a read would push the running size past the cap this stream was given. */ + static final class AssetTooLargeException extends RuntimeException { + AssetTooLargeException(long maxSize) { + super("Asset exceeded the maximum allowed size of " + maxSize + " bytes."); + } + } + + private final Map digests = new LinkedHashMap<>(); + private final long maxSize; + private long size; + private Map hashesHex; + + AssetDigestingInputStream(InputStream in, long maxSize) { + super(in); + this.maxSize = maxSize; + for (String algorithm : ALGORITHMS) { + digests.put(algorithm, newDigest(algorithm)); + } + } + + private static MessageDigest newDigest(String algorithm) { + try { + return MessageDigest.getInstance(algorithm); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("JVM does not support " + algorithm, e); + } + } + + @Override + public int read() throws IOException { + int next = super.read(); + if (next >= 0) { + byte[] single = {(byte) next}; + update(single, 0, 1); + } + return next; + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + int read = super.read(buffer, offset, length); + if (read > 0) { + update(buffer, offset, read); + } + return read; + } + + @Override + public long skip(long n) throws IOException { + // Skipped bytes would be missing from the digests, so they are read instead. + byte[] buffer = new byte[8192]; + long skipped = 0; + while (skipped < n) { + int read = read(buffer, 0, (int) Math.min(buffer.length, n - skipped)); + if (read < 0) { + break; + } + skipped += read; + } + return skipped; + } + + @Override + public boolean markSupported() { + return false; + } + + long size() { + return size; + } + + /** + * Every external-connection client's own streamed fetch shares this: copy {@code in} to + * {@code destination}, capped at {@code maxSize} during the copy itself rather than checked + * only afterward, since the real public registry's own file size is otherwise unbounded. + * Returns the real byte count copied. + */ + static long copyCapped(InputStream in, Path destination, long maxSize) throws IOException { + AssetDigestingInputStream digesting = new AssetDigestingInputStream(in, maxSize); + Files.copy(digesting, destination, StandardCopyOption.REPLACE_EXISTING); + return digesting.size(); + } + + /** + * Every {@code ASSET_HASH_ALGORITHMS} digest of everything read so far, as lowercase hex. + * Finalizes each {@link MessageDigest}, so reading on afterward is not supported; the result + * is cached once asked for, since asking twice would otherwise re-finalize an already-reset + * digest and return the wrong value. + */ + Map hashesHex() { + if (hashesHex == null) { + Map hashes = new LinkedHashMap<>(); + for (Map.Entry entry : digests.entrySet()) { + hashes.put(entry.getKey(), SigV4RequestValidator.hexEncode(entry.getValue().digest())); + } + hashesHex = hashes; + } + return hashesHex; + } + + private void update(byte[] buffer, int offset, int length) { + size += length; + if (size > maxSize) { + throw new AssetTooLargeException(maxSize); + } + for (MessageDigest digest : digests.values()) { + digest.update(buffer, offset, length); + } + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarClient.java index e1fa391df1..c9ee3151bd 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarClient.java @@ -2,9 +2,11 @@ package io.floci.aws.services.codeartifact; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -12,6 +14,7 @@ import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; @@ -119,6 +122,24 @@ public class BagetterSidecarClient implements RepositorySidecarManager { + SidecarUriUtils.encodeSegment(expectedAssetName)); } + /** {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} for why. */ + @Override + public Optional fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain, + String repository, String namespace, String packageName, String version, String assetName) { + String lowerId = packageName.toLowerCase(Locale.ROOT); + Optional normalizedVersion = matchVersion(repositoryContainerId, lowerId, version); + if (normalizedVersion.isEmpty()) { + return Optional.empty(); + } + String expectedAssetName = lowerId + "." + normalizedVersion.get() + ".nupkg"; + if (!expectedAssetName.equals(assetName)) { + return Optional.empty(); + } + return getBytesStreamed(repositoryContainerId, "/v3/package/" + SidecarUriUtils.encodeSegment(lowerId) + "/" + + SidecarUriUtils.encodeSegment(normalizedVersion.get()) + "/" + + SidecarUriUtils.encodeSegment(expectedAssetName)); + } + @Override public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace, String packageName) { @@ -369,33 +390,66 @@ public class BagetterSidecarClient implements RepositorySidecarManager { public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, String namespace, String packageName, String version, String assetName, byte[] content) { synchronized (lockFor(repositoryContainerId)) { - String baseUrl = ensureReady(repositoryContainerId, null); String boundary = "flociNuGetCopyBoundary" + System.nanoTime(); - byte[] head = ("--" + boundary + "\r\n" - + "Content-Disposition: form-data; name=\"package\"; filename=\"" + assetName + "\"\r\n" - + "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8); - byte[] tail = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); + byte[] head = multipartHead(boundary, assetName); + byte[] tail = multipartTail(boundary); byte[] body = new byte[head.length + content.length + tail.length]; System.arraycopy(head, 0, body, 0, head.length); System.arraycopy(content, 0, body, head.length, content.length); System.arraycopy(tail, 0, body, head.length + content.length, tail.length); + sendMultipartPush(repositoryContainerId, boundary, BodyPublishers.ofByteArray(body), assetName, + body.length); + } + } - HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), - "/api/v2/package")) - .timeout(Duration.ofSeconds(30)) - .header("Content-Type", "multipart/form-data; boundary=" + boundary) - .PUT(BodyPublishers.ofByteArray(body)) - .build(); - HttpResponse response; - try { - response = httpClient.send(request, BodyHandlers.ofString()); - } catch (Exception e) { - throw new IllegalStateException("Could not reach the BaGetter sidecar to push " + assetName, e); - } - if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202) { - throw new IllegalStateException("Could not push " + assetName + " to the BaGetter sidecar: " - + "upstream returned " + response.statusCode()); - } + /** + * {@link #storePackageVersionAsset(String, String, String, String, String, String, String, + * byte[])}'s own streamed sibling: the same multipart shape, but the file part streams + * straight from disk via {@code BodyPublishers.concat}, so the asset's own content is never + * copied into one combined array the way the {@code byte[]} overload above still does for + * content that is already resident. + */ + @Override + public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength) { + synchronized (lockFor(repositoryContainerId)) { + String boundary = "flociNuGetCopyBoundary" + System.nanoTime(); + byte[] head = multipartHead(boundary, assetName); + byte[] tail = multipartTail(boundary); + HttpRequest.BodyPublisher publisher = MultipartFilePublisher.concat(head, content, tail); + sendMultipartPush(repositoryContainerId, boundary, publisher, assetName, contentLength); + } + } + + private static byte[] multipartHead(String boundary, String assetName) { + return ("--" + boundary + "\r\n" + + "Content-Disposition: form-data; name=\"package\"; filename=\"" + assetName + "\"\r\n" + + "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8); + } + + private static byte[] multipartTail(String boundary) { + return ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); + } + + private void sendMultipartPush(String repositoryContainerId, String boundary, HttpRequest.BodyPublisher publisher, + String assetName, long contentLength) { + String baseUrl = ensureReady(repositoryContainerId, null); + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), + "/api/v2/package")) + .timeout(SidecarUriUtils.transferTimeout(contentLength)) + .header("Content-Type", "multipart/form-data; boundary=" + boundary) + .PUT(publisher) + .build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofString()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the BaGetter sidecar to push " + assetName, e); + } + if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202) { + throw new IllegalStateException("Could not push " + assetName + " to the BaGetter sidecar: " + + "upstream returned " + response.statusCode()); } } @@ -550,4 +604,34 @@ public class BagetterSidecarClient implements RepositorySidecarManager { } return Optional.of(response.body()); } + + /** + * {@link #getBytes}'s streamed sibling, for the one asset download that can be large: a flat + * 10-second timeout, fine for {@link #getBytes}'s own small-metadata callers, would cancel a + * legitimately large, still-in-progress download here, the same gap the write side once had + * on its own forwarding call. The real size isn't known until the response itself arrives, so + * this uses the worst-case download timeout rather than one sized off an actual byte count. + */ + private Optional getBytesStreamed(String repositoryContainerId, String encodedPath) { + String baseUrl = ensureReady(repositoryContainerId, null); + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath)) + .timeout(SidecarUriUtils.maxTransferTimeout()).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the BaGetter sidecar at " + encodedPath, e); + } + if (response.statusCode() == 404) { + StreamingResponses.closeQuietly(response.body()); + return Optional.empty(); + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + throw new IllegalStateException("Could not fetch " + encodedPath + " from the BaGetter sidecar: upstream " + + "returned " + response.statusCode()); + } + long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1); + return Optional.of(new StreamedAsset(response.body(), contentLength)); + } } diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java index 7f7a5e8354..454cb5a088 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java @@ -12,9 +12,10 @@ import io.floci.aws.core.common.JsonErrorResponseUtils; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationToken; import io.floci.aws.services.codeartifact.CodeArtifactService.DomainView; -import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionAssetResult; +import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionAssetStreamResult; import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionReadmeResult; import io.floci.aws.services.codeartifact.CodeArtifactService.PublishPackageVersionResult; import io.floci.aws.services.codeartifact.CodeArtifactService.ResourcePolicy; @@ -38,6 +39,7 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -322,7 +324,7 @@ public class CodeArtifactController { @QueryParam("asset") String assetName, @QueryParam("unfinished") String unfinished, @HeaderParam("x-amz-content-sha256") String assetSha256, - byte[] body) { + InputStream body) { String region = regionResolver.resolveRegion(headers); PublishPackageVersionResult result = service.publishPackageVersion(region, domain, domainOwner, repository, format, namespace, packageName, version, assetName, assetSha256, unfinished, body); @@ -405,13 +407,16 @@ public class CodeArtifactController { @QueryParam("asset") String assetName, @QueryParam("revision") String revision) { String region = regionResolver.resolveRegion(headers); - PackageVersionAssetResult result = service.getPackageVersionAsset(region, domain, domainOwner, repository, - format, namespace, packageName, version, assetName, revision); - return Response.ok(result.asset().getContent(), MediaType.APPLICATION_OCTET_STREAM) - .header("X-AssetName", result.asset().getName()) + PackageVersionAssetStreamResult result = service.getPackageVersionAssetStreamed(region, domain, domainOwner, + repository, format, namespace, packageName, version, assetName, revision); + Response.ResponseBuilder builder = Response.ok().type(MediaType.APPLICATION_OCTET_STREAM) + .header("X-AssetName", result.assetName()) .header("X-PackageVersion", version) - .header("X-PackageVersionRevision", result.packageVersionRevision()) - .build(); + .header("X-PackageVersionRevision", result.packageVersionRevision()); + if (result.contentLength() >= 0) { + builder.header("Content-Length", result.contentLength()); + } + return StreamingResponses.streamingResponse(result.content(), stream -> builder.entity(stream).build()); } @POST diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java index 3ba506d096..b22ab69f2b 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java @@ -1,8 +1,9 @@ package io.floci.aws.services.codeartifact; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; -import io.floci.aws.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact; +import io.floci.aws.services.codeartifact.ReposiliteSidecarClient.StreamedArtifact; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; @@ -18,6 +19,7 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -60,14 +62,7 @@ public class CodeArtifactMavenController { @Consumes(MediaType.WILDCARD) public Response deploy(@Context HttpHeaders headers, @PathParam("domain") String domain, @PathParam("repository") String repository, @PathParam("gav") String gav, - byte[] body) { - byte[] content = body != null ? body : new byte[0]; - // Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy - // Reactive has already buffered the full body into this byte[] before the method runs, so - // this rejects anything that made it this far rather than bounding memory use upfront. - if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { - return Response.status(413).build(); - } + InputStream body) { MavenRequestScope scope = requireScope(headers, domain, repository); Optional coordinate = parseNamespaceAndPackageName(gav); // A package whose origin configuration sets publish:BLOCK refuses every mvn deploy, the @@ -118,25 +113,43 @@ public class CodeArtifactMavenController { // matters. Optional fenceSnapshot = coordinate.map(c -> service.currentContainerBackedPackageFence( scope.region(), domain, scope.owner(), repository, "maven", c[0], c[1])); - ReposiliteSidecarClient.DeployOutcome outcome = reposilite.deployArtifact(scope.repoId(), gav, content); - if (outcome.wroteNewContent()) { - coordinate.ifPresent(c -> service.recordContainerBackedAssetBytes(scope.region(), domain, scope.owner(), - repository, "maven", c[0], c[1], content.length, fenceSnapshot.get())); - // Found by Qodo review: a real mvn deploy to a coordinate updatePackageVersionsStatus/ - // disposePackageVersions previously archived or disposed would still have its fresh - // content blocked by that stale override, since nothing before this cleared it for a - // native publish the way copyPackageVersions now does for its own overwrite path. The - // version element is null for a bare maven-metadata.xml PUT (see this coordinate's own - // javadoc), which never represents a specific version to clear an override for anyway. - // By this point the guard above has already refused an Archived/Disposed coordinate, - // so the only override left to clear here is Unlisted (or none), and only if it is - // still exactly what the guard above saw. - String beforeRevisionFinal = beforeRevision; - coordinate.filter(c -> c[2] != null).ifPresent(c -> service.forgetContainerBackedStatusOverrideIfUnchanged( - scope.region(), domain, scope.owner(), repository, "maven", c[0], c[1], c[2], - beforeRevisionFinal)); + + java.nio.file.Path staged; + long contentLength; + try { + AssetDigestingInputStream digesting = new AssetDigestingInputStream(body, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + staged = service.stageAssetBody(digesting); + contentLength = digesting.size(); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + // Same 5 GB AWS quota PublishPackageVersion enforces: raised while the upload is still + // being staged to disk, not after it has already been buffered whole, so this now + // bounds real memory/disk use rather than only rejecting a body already paid for. + return Response.status(413).build(); + } + try { + ReposiliteSidecarClient.DeployOutcome outcome = reposilite.deployArtifact(scope.repoId(), gav, staged); + if (outcome.wroteNewContent()) { + coordinate.ifPresent(c -> service.recordContainerBackedAssetBytes(scope.region(), domain, + scope.owner(), repository, "maven", c[0], c[1], contentLength, fenceSnapshot.get())); + // Found by Qodo review: a real mvn deploy to a coordinate updatePackageVersionsStatus/ + // disposePackageVersions previously archived or disposed would still have its fresh + // content blocked by that stale override, since nothing before this cleared it for a + // native publish the way copyPackageVersions now does for its own overwrite path. The + // version element is null for a bare maven-metadata.xml PUT (see this coordinate's own + // javadoc), which never represents a specific version to clear an override for anyway. + // By this point the guard above has already refused an Archived/Disposed coordinate, + // so the only override left to clear here is Unlisted (or none), and only if it is + // still exactly what the guard above saw. + String beforeRevisionFinal = beforeRevision; + coordinate.filter(c -> c[2] != null).ifPresent( + c -> service.forgetContainerBackedStatusOverrideIfUnchanged(scope.region(), domain, + scope.owner(), repository, "maven", c[0], c[1], c[2], beforeRevisionFinal)); + } + return Response.status(outcome.status()).build(); + } finally { + service.deleteStagedAssetBody(staged); } - return Response.status(outcome.status()).build(); } /** @@ -218,11 +231,12 @@ public class CodeArtifactMavenController { if (!isDownloadable(scope, domain, repository, gav)) { return Response.status(Response.Status.NOT_FOUND).build(); } - Optional artifact = reposilite.fetchArtifact(scope.repoId(), gav); + Optional artifact = reposilite.fetchArtifactStreamed(scope.repoId(), gav); if ((artifact.isEmpty() || isBareMavenMetadataFile(gav)) && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository, scope.repoId(), gav)) { - artifact = reposilite.fetchArtifact(scope.repoId(), gav); + artifact.ifPresent(a -> StreamingResponses.closeQuietly(a.content())); + artifact = reposilite.fetchArtifactStreamed(scope.repoId(), gav); } return artifact.map(this::toResponse).orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); } @@ -281,8 +295,12 @@ public class CodeArtifactMavenController { }).orElse(true); } - private Response toResponse(FetchedArtifact artifact) { - return Response.ok(artifact.content(), artifact.contentType()).build(); + private Response toResponse(StreamedArtifact artifact) { + Response.ResponseBuilder builder = Response.ok().type(artifact.contentType()); + if (artifact.contentLength() >= 0) { + builder.header("Content-Length", artifact.contentLength()); + } + return StreamingResponses.streamingResponse(artifact.content(), stream -> builder.entity(stream).build()); } private record MavenRequestScope(String repoId, String region, String owner) {} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java index 46227fd353..9dc7bd4b3e 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java @@ -6,6 +6,10 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.function.Predicate; @@ -164,55 +168,85 @@ public class CodeArtifactMavenExternalConnectionImporter { try { for (String candidateFilename : candidates) { String candidateGav = directory + candidateFilename; - Optional fetched; + Path staged; try { - fetched = externalConnectionClient.fetchAsset(externalConnectionName, candidateGav); - } catch (RuntimeException e) { - LOG.warnv(e, "Could not fetch {0} from {1} while retaining a Maven release through an " - + "external connection; skipping this candidate.", candidateGav, externalConnectionName); - continue; + staged = Files.createTempFile("codeartifact-maven-import-", ".bin"); + } catch (IOException e) { + throw new UncheckedIOException("Failed to create a staging file for a Maven " + + "external-connection import", e); } - if (fetched.isEmpty()) { - continue; - } - byte[] content = fetched.get().content(); - // The fence check and the real write happen inside the very same synchronized - // call DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions - // already hold across their own entire operation, so a write here and one of - // those four operations can never interleave: whichever gets there first finishes - // completely before the other even starts. See deployMavenAssetUnderVersionFence's - // own javadoc for why this has to be a method on the service itself rather than a - // block synchronized on the injected reference here: only a lock actually taken - // inside that class's own synchronized method is guaranteed to be the exact same - // lock its other synchronized methods already hold. - // packageFenceSnapshot is passed through so byte accounting (when this write - // genuinely adds new content) runs inside this exact same locked call too, - // rather than in a separate call after this one already released the lock, which - // would let a delete or disposal subtract this asset's bytes as part of its own - // normal cleanup before that separate call added them, permanently over-counting - // DescribeDomain's total for an asset already gone. - CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence( - region, domain, owner, repository, namespace, packageName, version, versionFenceSnapshot, - fenceSnapshot, claim.episodeId(), reposilite, repoId, candidateGav, content); - if (!result.fenceMatched()) { - // The version itself is gone: every later candidate in this same attempt - // would fail the exact same way, so none of them are even attempted. - break; - } - ReposiliteSidecarClient.DeployOutcome outcome = result.outcome(); - if (outcome == null) { - continue; - } - // The asset is genuinely present either way a 200/201 status is reached: a fresh - // write (201, or 200 with wroteNewContent()) or an idempotent match against bytes - // already there (200, wroteNewContent() false). Only a real conflict or sidecar - // error leaves nothing to record. - if (outcome.status() != 200 && outcome.status() != 201) { - continue; - } - importedAny = true; - if (candidateFilename.equals(filename)) { - importedRequestedAsset = true; + try { + Optional fetched; + try { + fetched = externalConnectionClient.fetchAsset(externalConnectionName, candidateGav, staged); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + // The same 5 GB AWS quota CodeArtifactMavenController#deploy already + // enforces on a direct publish, now checked by fetchAsset(Path) itself + // during the download rather than in a second pass over the staged file + // afterward: a release this large is rejected before it is ever fully + // pulled across the network and written to local disk. This candidate + // alone is skipped, not the whole attempt: an oversized javadoc/sources + // jar should not stop the pom/jar themselves from still being imported. + LOG.warnv("Skipping {0}: the real registry''s own file is larger than this emulator''s " + + "{1}-byte asset quota.", candidateGav, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + continue; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} from {1} while retaining a Maven release through an " + + "external connection; skipping this candidate.", candidateGav, + externalConnectionName); + continue; + } + if (fetched.isEmpty()) { + continue; + } + long contentLength = fetched.get().size(); + // The fence check and the real write happen inside the very same synchronized + // call DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions + // already hold across their own entire operation, so a write here and one of + // those four operations can never interleave: whichever gets there first finishes + // completely before the other even starts. See deployMavenAssetUnderVersionFence's + // own javadoc for why this has to be a method on the service itself rather than a + // block synchronized on the injected reference here: only a lock actually taken + // inside that class's own synchronized method is guaranteed to be the exact same + // lock its other synchronized methods already hold. + // packageFenceSnapshot is passed through so byte accounting (when this write + // genuinely adds new content) runs inside this exact same locked call too, + // rather than in a separate call after this one already released the lock, which + // would let a delete or disposal subtract this asset's bytes as part of its own + // normal cleanup before that separate call added them, permanently over-counting + // DescribeDomain's total for an asset already gone. + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence( + region, domain, owner, repository, namespace, packageName, version, versionFenceSnapshot, + fenceSnapshot, claim.episodeId(), reposilite, repoId, candidateGav, staged, + contentLength); + if (!result.fenceMatched()) { + // The version itself is gone: every later candidate in this same attempt + // would fail the exact same way, so none of them are even attempted. + break; + } + ReposiliteSidecarClient.DeployOutcome outcome = result.outcome(); + if (outcome == null) { + continue; + } + // The asset is genuinely present either way a 200/201 status is reached: a fresh + // write (201, or 200 with wroteNewContent()) or an idempotent match against bytes + // already there (200, wroteNewContent() false). Only a real conflict or sidecar + // error leaves nothing to record. + if (outcome.status() != 200 && outcome.status() != 201) { + continue; + } + importedAny = true; + if (candidateFilename.equals(filename)) { + importedRequestedAsset = true; + } + } finally { + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete a staged Maven external-connection import file at {0}", + staged); + } } } } finally { diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java index 272c5bd799..38fd65d624 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java @@ -10,6 +10,9 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Optional; @@ -284,53 +287,79 @@ public class CodeArtifactNpmExternalConnectionImporter { namespace, packageName, version).filter(externalConnectionName::equals).isPresent(); return imported; } - Optional fetched; + Path staged; try { - fetched = externalConnectionClient.fetchTarball(externalConnectionName, namespace, packageName, - version); - } catch (RuntimeException e) { - LOG.warnv(e, "Could not fetch {0} {1} {2} from {3} while retaining an npm package through an " - + "external connection.", namespace, packageName, version, externalConnectionName); - return false; + staged = Files.createTempFile("codeartifact-npm-import-", ".bin"); + } catch (IOException e) { + throw new UncheckedIOException("Failed to create a staging file for an npm external-connection " + + "import", e); } - if (fetched.isEmpty()) { - return false; - } - byte[] content = fetched.get().content(); - // Fetched again here, full rather than abbreviated, rather than reusing whatever - // mergedPackument already saw: that call is per-request and never keeps anything - // around between one request and the next, and this is the one real network call - // this whole import attempt pays for retrieving a version's dependencies/engines/ - // scripts and the package's own readme (see ExternalPackumentDetails' own javadoc), - // paid at most once per version ever actually retained. - ExternalPackumentDetails details = fetchExternalPackumentDetails(externalConnectionName, namespace, - packageName, version); - if (details.versionDoc() == null) { - // Raised by hectorvent's review: storing now with no full-form document would - // retain this version with the minimal one storeRetainedVersionAsset falls back - // to (no dependencies/engines/scripts), and permanently so, since the merge above - // skips any version once versions.has(version) is true. Returning false instead - // abandons this attempt without writing anything, so a later download retries the - // full fetch rather than settling for a degraded document forever. - LOG.warnv("Not retaining {0}/{1}@{2} from {3} without its full-form version " - + "document; a later download will retry.", namespace, packageName, version, - externalConnectionName); - return false; - } - CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, - domain, owner, repository, "npm", namespace, packageName, version, versionFenceSnapshot, - packageFenceSnapshot, claim.episodeId(), repoId, assetName, content, - () -> verdaccio.storeRetainedVersionAsset(repoId, domain, repository, namespace, packageName, - version, assetName, content, details.versionDoc())); - imported = result.fenceMatched() && result.wroteNewContent(); - if (imported) { - // Raised by Greptile's review: without this, GetPackageVersionReadme 404s on an - // otherwise fully retained version, since npm (unlike nuget's BaGetter) answers - // that call from a capture taken at write time, never live from the sidecar; see - // CodeArtifactService#recordPublishedPackageVersionReadme's own javadoc for why - // versionFenceSnapshot, taken before this same write, is what it checks against. - service.recordPublishedPackageVersionReadme(region, domain, owner, repository, "npm", namespace, - packageName, version, details.readme(), versionFenceSnapshot); + try { + Optional fetched; + try { + fetched = externalConnectionClient.fetchTarball(externalConnectionName, namespace, packageName, + version, staged); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + // The same 5 GB AWS quota CodeArtifactNpmDataPlane's own real npm publish proxy + // already enforces, now checked by fetchTarball(Path) itself during the + // download rather than in a second pass over the staged file afterward: a + // tarball this large is rejected before it is ever fully pulled across the + // network and written to local disk. + LOG.warnv("Skipping {0}/{1}@{2}: the real registry''s own file is larger than this " + + "emulator''s {3}-byte asset quota.", namespace, packageName, version, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + return false; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} {1} {2} from {3} while retaining an npm package through an " + + "external connection.", namespace, packageName, version, externalConnectionName); + return false; + } + if (fetched.isEmpty()) { + return false; + } + long contentLength = fetched.get().size(); + // Fetched again here, full rather than abbreviated, rather than reusing whatever + // mergedPackument already saw: that call is per-request and never keeps anything + // around between one request and the next, and this is the one real network call + // this whole import attempt pays for retrieving a version's dependencies/engines/ + // scripts and the package's own readme (see ExternalPackumentDetails' own javadoc), + // paid at most once per version ever actually retained. + ExternalPackumentDetails details = fetchExternalPackumentDetails(externalConnectionName, namespace, + packageName, version); + if (details.versionDoc() == null) { + // Raised by hectorvent's review: storing now with no full-form document would + // retain this version with the minimal one storeRetainedVersionAsset falls back + // to (no dependencies/engines/scripts), and permanently so, since the merge above + // skips any version once versions.has(version) is true. Returning false instead + // abandons this attempt without writing anything, so a later download retries the + // full fetch rather than settling for a degraded document forever. + LOG.warnv("Not retaining {0}/{1}@{2} from {3} without its full-form version " + + "document; a later download will retry.", namespace, packageName, version, + externalConnectionName); + return false; + } + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "npm", namespace, packageName, version, versionFenceSnapshot, + packageFenceSnapshot, claim.episodeId(), repoId, assetName, contentLength, + () -> verdaccio.storeRetainedVersionAsset(repoId, domain, repository, namespace, packageName, + version, assetName, staged, contentLength, details.versionDoc())); + imported = result.fenceMatched() && result.wroteNewContent(); + if (imported) { + // Raised by Greptile's review: without this, GetPackageVersionReadme 404s on + // an otherwise fully retained version, since npm (unlike nuget's BaGetter) + // answers that call from a capture taken at write time, never live from the + // sidecar; see CodeArtifactService#recordPublishedPackageVersionReadme's own + // javadoc for why versionFenceSnapshot, taken before this same write, is what + // it checks against. + service.recordPublishedPackageVersionReadme(region, domain, owner, repository, "npm", namespace, + packageName, version, details.readme(), versionFenceSnapshot); + } + } finally { + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete a staged npm external-connection import file at {0}", staged); + } } return imported; } finally { diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java index 211ffb2a59..91d1fda956 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java @@ -2,6 +2,7 @@ package io.floci.aws.services.codeartifact; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.MultipartFormParser; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -17,16 +18,21 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.file.Files; import java.time.Duration; -import java.util.Arrays; import java.util.Locale; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; /** * Serves the real NuGet V3 wire protocol behind the URL {@code GetRepositoryEndpoint} returns for @@ -148,15 +154,23 @@ public class CodeArtifactNuGetController { @PathParam("repository") String repository, @PathParam("id") String id, @PathParam("version") String version, @PathParam("filename") String filename) { RepositoryHandle handle = requireRepository(headers, domain, repository); + // The .nupkg branch below hands back a Response whose body is only drained later, when + // JAX-RS writes the deferred StreamingOutput: this flag lets that branch defer releasing + // the lease until that real drain happens (via StreamingResponses.closingWith), instead of + // this method's own return letting a concurrent DeleteRepository stop the BaGetter + // container mid-download. + AtomicBoolean leaseTransferred = new AtomicBoolean(); try { - return packageContentWithLease(handle, domain, repository, id, version, filename); + return packageContentWithLease(handle, domain, repository, id, version, filename, leaseTransferred); } finally { - endUse(handle.repoId()); + if (!leaseTransferred.get()) { + endUse(handle.repoId()); + } } } private Response packageContentWithLease(RepositoryHandle handle, String domain, String repository, String id, - String version, String filename) { + String version, String filename, AtomicBoolean leaseTransferred) { try { service.requireContainerBackedVersionDownloadable(handle.owner(), handle.region(), domain, repository, "nuget", null, id, version, handle.repoId()); @@ -185,9 +199,9 @@ public class CodeArtifactNuGetController { externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository, handle.repoId(), id, version); } - return proxyGet(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/" + return proxyGetStreamed(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/" + lowerId + "." + SidecarUriUtils.encodeSegment(version.toLowerCase(Locale.ROOT)) + ".nupkg", - MediaType.APPLICATION_OCTET_STREAM); + MediaType.APPLICATION_OCTET_STREAM, leaseTransferred, () -> endUse(handle.repoId())); } return Response.status(404).build(); } @@ -208,40 +222,91 @@ public class CodeArtifactNuGetController { @Path("api/v2/package") @Consumes(MediaType.WILDCARD) public Response push(@Context HttpHeaders headers, @PathParam("domain") String domain, - @PathParam("repository") String repository, byte[] body) { - byte[] content = body != null ? body : new byte[0]; - // Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy - // Reactive has already buffered the full body into this byte[] before this method runs, - // so this rejects anything that made it this far rather than bounding memory use upfront. - if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { - return Response.status(413).build(); - } + @PathParam("repository") String repository, InputStream body) { RepositoryHandle handle = requireRepository(headers, domain, repository); try { - return pushWithLease(headers, domain, repository, content, handle); + return pushWithLease(headers, domain, repository, body, handle); } finally { endUse(handle.repoId()); } } - private Response pushWithLease(HttpHeaders headers, String domain, String repository, byte[] content, + /** + * Stages the whole raw multipart body to disk before anything else touches it, the same + * reason {@code CodeArtifactPypiController#uploadWithLease} does: {@link #forwardPush} can + * then send this exact file straight to BaGetter with no multipart rebuild at all, since it + * already re-sends the entire inbound body verbatim, not a reconstructed one. Capped at + * {@code CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES} during the staging copy itself: the + * envelope has no exact size semantics of its own against the 5 GB asset quota yet, but + * leaving this particular copy fully uncapped would let a client force an arbitrarily large + * file onto disk before the real per-asset check downstream ever runs. + */ + private Response pushWithLease(HttpHeaders headers, String domain, String repository, InputStream body, RepositoryHandle handle) { String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE); String boundary = MultipartFormParser.extractBoundary(contentType).orElse(null); if (boundary == null) { return Response.status(400).entity("Could not determine multipart boundary from Content-Type.").build(); } - MultipartFormParser.ParsedForm form = MultipartFormParser.parse(content, boundary); - Optional file = form.file(); + java.nio.file.Path stagedWholeBody; + try { + stagedWholeBody = service.stageAssetBody( + new AssetDigestingInputStream(body, CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES)); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + return Response.status(413).build(); + } + try { + return pushStagedBody(domain, repository, contentType, boundary, stagedWholeBody, handle); + } finally { + service.deleteStagedAssetBody(stagedWholeBody); + } + } + + /** + * {@code stagedWholeBody}'s own file part is extracted into a second, clean staged file + * (never the whole multipart envelope nor that one part held in a single array), the same + * shape {@code CodeArtifactPypiController} uses. + */ + private Response pushStagedBody(String domain, String repository, String contentType, String boundary, + java.nio.file.Path stagedWholeBody, RepositoryHandle handle) { + java.nio.file.Path stagedNupkg = stagedWholeBody.resolveSibling(stagedWholeBody.getFileName() + ".nupkg"); + try { + MultipartFormParser.ExtractedForm form; + try { + form = MultipartFormParser.extractFilePart(stagedWholeBody, boundary, stagedNupkg); + } catch (IOException e) { + return Response.status(400).entity("Could not parse the uploaded multipart body.").build(); + } + return pushExtractedForm(domain, repository, contentType, form, stagedWholeBody, stagedNupkg, handle); + } finally { + service.deleteStagedAssetBody(stagedNupkg); + } + } + + private Response pushExtractedForm(String domain, String repository, String contentType, + MultipartFormParser.ExtractedForm form, java.nio.file.Path stagedWholeBody, + java.nio.file.Path stagedNupkg, RepositoryHandle handle) { + Optional file = form.file(); if (file.isEmpty()) { return Response.status(400).entity("Upload must include the package file.").build(); } - byte[] nupkgBytes = file.get().content(); + long nupkgSize; + try { + nupkgSize = Files.size(stagedNupkg); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + // Same 5 GB AWS quota PublishPackageVersion enforces: checked against the real asset + // bytes alone (never the surrounding multipart envelope), once they are known, rather + // than before anything was read at all the way a non-multipart format's own cap can be. + if (nupkgSize > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { + return Response.status(413).build(); + } NuspecXml.Metadata nuspec; try { - nuspec = NuspecXml.extractFromNupkg(nupkgBytes); + nuspec = NuspecXml.extractFromNupkg(stagedNupkg); } catch (RuntimeException e) { return Response.status(400).entity("Could not read the uploaded package: " + e.getMessage()).build(); } @@ -298,66 +363,106 @@ public class CodeArtifactNuGetController { // its versions before this push lands and miss it, the one case a private lock here // could never close no matter how it synchronized with itself. synchronized (bagetter.lockFor(handle.repoId())) { - Optional existing = existingNupkgContent(handle.baseUrl(), packageName, version); - if (existing.isPresent()) { - if (Arrays.equals(existing.get(), nupkgBytes)) { - return Response.status(200).build(); - } + ExistingNupkgComparison existing = compareExistingNupkg(handle.baseUrl(), packageName, version, + stagedNupkg); + if (existing == ExistingNupkgComparison.MATCHES) { + return Response.status(200).build(); + } + if (existing == ExistingNupkgComparison.DIFFERS) { return Response.status(409) .entity("A package with this id and version already exists.") .build(); } - response = forwardPush(handle.baseUrl(), contentType, content); + // The entire original raw multipart body is re-sent verbatim, boundary and all, + // exactly as the byte[]-based version of this call always has: BaGetter parses its + // own multipart form the same way dotnet nuget push built it, so there was never a + // need to rebuild one here, only to stream the one already staged instead of a + // resident array. + response = forwardPush(handle.baseUrl(), contentType, stagedWholeBody); pushSucceeded = response.getStatus() == 200 || response.getStatus() == 201 || response.getStatus() == 202; } if (pushSucceeded) { service.completeContainerBackedPublishIfCurrentRepository(handle.region(), domain, handle.owner(), - repository, handle.repoId(), "nuget", packageName, version, nupkgBytes.length, fenceSnapshot, + repository, handle.repoId(), "nuget", packageName, version, nupkgSize, fenceSnapshot, beforeRevision, null, 0L); } return response; } + private enum ExistingNupkgComparison { NOT_LISTED, MATCHES, DIFFERS } + /** - * {@code empty()} when {@code packageName}/{@code version} isn't published on BaGetter yet, its - * actual bytes otherwise. A connectivity failure here throws rather than returning {@code - * empty()}, the same fail-safe reasoning as {@code CodeArtifactPypiController - * #existingFileContent}: letting a push with different content through to BaGetter during - * exactly the moment this check is unavailable would be the opposite of fail-safe, and BaGetter's - * own {@code AllowPackageOverwrites: false} would reject it anyway, just with a response this - * proxy no longer controls. + * {@code existingNupkgContent}'s own streamed sibling: compares BaGetter's own stored package + * against {@code localNupkg} chunk by chunk from each side, rather than buffering the remote + * file into a {@code byte[]} first (capped at ~2 GiB) just to compare it against another + * array, the same technique {@code CodeArtifactPypiController#compareExistingFile} and {@code + * ReposiliteSidecarClient}'s own streamed idempotent-match check both use. A connectivity + * failure here throws rather than returning {@code NOT_LISTED}, the same fail-safe reasoning + * the original method documented: letting a push with different content through to BaGetter + * during exactly the moment this check is unavailable would be the opposite of fail-safe, and + * BaGetter's own {@code AllowPackageOverwrites: false} would reject it anyway, just with a + * response this proxy no longer controls. */ - private Optional existingNupkgContent(String baseUrl, String packageName, String version) { + private ExistingNupkgComparison compareExistingNupkg(String baseUrl, String packageName, String version, + java.nio.file.Path localNupkg) { URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/v3/package/" + SidecarUriUtils.encodeSegment(packageName) + "/" + SidecarUriUtils.encodeSegment(version) + "/" + SidecarUriUtils.encodeSegment(packageName) + "." + SidecarUriUtils.encodeSegment(version) + ".nupkg"); HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build(); - HttpResponse response; + HttpResponse response; try { - response = httpClient.send(request, BodyHandlers.ofByteArray()); + response = httpClient.send(request, BodyHandlers.ofInputStream()); } catch (Exception e) { throw new IllegalStateException( "Could not check nuget package " + packageName + " " + version + " for an existing push", e); } if (response.statusCode() == 404) { - return Optional.empty(); + // Raised by Copilot's review of this PR: a brand-new package (the common case for a + // first-time push) answers 404 here every time, so leaving its body unclosed leaked + // the underlying response/connection on every such push, not just an edge case. + StreamingResponses.closeQuietly(response.body()); + return ExistingNupkgComparison.NOT_LISTED; } if (response.statusCode() != 200) { + try { + response.body().close(); + } catch (IOException ignored) { + // Closing an unread stream best-effort only; the exception thrown right below is + // the one that actually matters here. + } throw new IllegalStateException( "Could not check nuget package " + packageName + " " + version + ": upstream returned " + response.statusCode()); } - return Optional.of(response.body()); + try (InputStream remote = response.body(); InputStream local = Files.newInputStream(localNupkg)) { + return StreamEquality.contentsMatch(remote, local) ? ExistingNupkgComparison.MATCHES + : ExistingNupkgComparison.DIFFERS; + } catch (IOException e) { + throw new UncheckedIOException( + "Could not compare the existing nuget package " + packageName + " " + version + + " against the uploaded content", e); + } } - private Response forwardPush(String baseUrl, String contentType, byte[] content) { - HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/api/v2/package")) - .timeout(Duration.ofSeconds(30)) - .header("Content-Type", contentType) - .PUT(BodyPublishers.ofByteArray(content)) - .build(); + private Response forwardPush(String baseUrl, String contentType, java.nio.file.Path stagedWholeBody) { + long stagedSize; + try { + stagedSize = Files.size(stagedWholeBody); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), + "/api/v2/package")) + .timeout(SidecarUriUtils.transferTimeout(stagedSize)) + .header("Content-Type", contentType); + try { + requestBuilder.PUT(BodyPublishers.ofFile(stagedWholeBody)); + } catch (FileNotFoundException e) { + throw new UncheckedIOException(e); + } + HttpRequest request = requestBuilder.build(); HttpResponse response; try { response = httpClient.send(request, BodyHandlers.discarding()); @@ -387,6 +492,44 @@ public class CodeArtifactNuGetController { return Response.status(response.statusCode()).entity(response.body()).type(contentType).build(); } + /** + * {@link #proxyGet}'s streamed sibling, for the {@code .nupkg} branch of {@link + * #packageContentWithLease}: that method's own {@code byte[]} is fine for a readme or + * {@code .nuspec}, but a downloaded package itself can be gigabytes. + * + *

{@code afterClose} is the caller's lease release: on an immediate failure (the sidecar + * unreachable, or a 404) it runs right here, synchronously, since nothing is left streaming. + * On a real 200, it runs only once the entity stream this method returns is actually closed + * (via {@code leaseTransferred} and {@link StreamingResponses#closingWith}), so the sidecar + * container this is downloading from stays leased for as long as the real transfer takes, + * not just until this method itself returns. + * + *

Uses the worst-case download timeout, not {@link #proxyGet}'s flat 10 seconds: the real + * {@code .nupkg} this fetches can be gigabytes, and its real size isn't known until the + * response itself arrives. + */ + private Response proxyGetStreamed(String baseUrl, String encodedPath, String fallbackContentType, + AtomicBoolean leaseTransferred, Runnable afterClose) { + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath)) + .timeout(SidecarUriUtils.maxTransferTimeout()).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the BaGetter sidecar at " + encodedPath, e); + } + if (response.statusCode() == 404) { + StreamingResponses.closeQuietly(response.body()); + return Response.status(404).build(); + } + String contentType = response.headers().firstValue("Content-Type").orElse(fallbackContentType); + Response.ResponseBuilder builder = Response.status(response.statusCode()).type(contentType); + response.headers().firstValueAsLong("Content-Length").ifPresent(len -> builder.header("Content-Length", len)); + leaseTransferred.set(true); + InputStream body = StreamingResponses.closingWith(response.body(), afterClose); + return StreamingResponses.streamingResponse(body, stream -> builder.entity(stream).build()); + } + private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) { String token = CodeArtifactTokenExtractor.extractToken(headers); AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain) diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java index 212744756d..2a67fee991 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java @@ -5,6 +5,10 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Locale; import java.util.Optional; @@ -115,35 +119,61 @@ public class CodeArtifactNuGetExternalConnectionImporter { packageId, version).filter(externalConnectionName::equals).isPresent(); return imported; } - Optional fetched; + Path staged; try { - fetched = externalConnectionClient.fetchPackage(externalConnectionName, packageId, version); - } catch (RuntimeException e) { - LOG.warnv(e, "Could not fetch {0} {1} from {2} while retaining a NuGet package through an " - + "external connection.", packageId, version, externalConnectionName); - return false; + staged = Files.createTempFile("codeartifact-nuget-import-", ".bin"); + } catch (IOException e) { + throw new UncheckedIOException("Failed to create a staging file for a NuGet external-connection " + + "import", e); } - if (fetched.isEmpty()) { - return false; + try { + Optional fetched; + try { + fetched = externalConnectionClient.fetchPackage(externalConnectionName, packageId, version, + staged); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + // The same 5 GB AWS quota CodeArtifactNuGetController#push already enforces on + // a direct publish, now checked by fetchPackage(Path) itself during the + // download rather than in a second pass over the staged file afterward: a + // .nupkg this large is rejected before it is ever fully pulled across the + // network and written to local disk. + LOG.warnv("Skipping {0} {1}: the real registry''s own file is larger than this emulator''s " + + "{2}-byte asset quota.", packageId, version, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + return false; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} {1} from {2} while retaining a NuGet package through an " + + "external connection.", packageId, version, externalConnectionName); + return false; + } + if (fetched.isEmpty()) { + return false; + } + long contentLength = fetched.get().size(); + String assetName = packageId.toLowerCase(Locale.ROOT) + "." + version.toLowerCase(Locale.ROOT) + + ".nupkg"; + // The fence check and the real write happen inside the very same synchronized call + // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions already + // hold across their own entire operation, so a write here and one of those four + // operations can never interleave. See retainAssetUnderVersionFence's own javadoc for + // why this has to be a method on the service itself rather than a block synchronized on + // an injected reference here: only a lock actually taken inside that class's own + // synchronized method is guaranteed to be the exact same lock its other synchronized + // methods already hold. + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot, + packageFenceSnapshot, claim.episodeId(), repoId, assetName, contentLength, + () -> bagetter.storePackageVersionAsset(repoId, domain, repository, null, packageId, version, + assetName, staged, contentLength)); + imported = result.fenceMatched() && result.wroteNewContent(); + return imported; + } finally { + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete a staged NuGet external-connection import file at {0}", staged); + } } - byte[] content = fetched.get().content(); - String assetName = packageId.toLowerCase(Locale.ROOT) + "." + version.toLowerCase(Locale.ROOT) - + ".nupkg"; - // The fence check and the real write happen inside the very same synchronized call - // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions already - // hold across their own entire operation, so a write here and one of those four - // operations can never interleave. See retainAssetUnderVersionFence's own javadoc for - // why this has to be a method on the service itself rather than a block synchronized on - // an injected reference here: only a lock actually taken inside that class's own - // synchronized method is guaranteed to be the exact same lock its other synchronized - // methods already hold. - CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, - domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot, - packageFenceSnapshot, claim.episodeId(), repoId, assetName, content, - () -> bagetter.storePackageVersionAsset(repoId, domain, repository, null, packageId, version, - assetName, content)); - imported = result.fenceMatched() && result.wroteNewContent(); - return imported; } finally { // Finalized here, not just after a clean return, so an unexpected exception still lets // this bookkeeping run instead of leaving the claim held (or released) without ever diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java index 7bba70fe97..d3f311adf2 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java @@ -2,6 +2,7 @@ package io.floci.aws.services.codeartifact; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.MultipartFormParser; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -17,6 +18,10 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -24,8 +29,8 @@ import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.time.Duration; -import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -33,6 +38,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.MatchResult; import java.util.regex.Pattern; @@ -236,6 +242,15 @@ public class CodeArtifactPypiController { @PathParam("repository") String repository, @PathParam("filename") String filename) { RepositoryHandle handle = requireRepository(headers, domain, repository); + // A real (200) proxyGetStreamed response's body is only drained later, when JAX-RS writes + // the deferred StreamingOutput: this flag lets that case defer releasing the lease (via + // StreamingResponses.closingWith) until that real drain happens, instead of this method's + // own return letting a concurrent DeleteRepository stop the pypiserver container + // mid-download. A 404 from either attempt below leaves this flag unset, so the outer + // finally releases the lease immediately once this method actually returns: nothing is + // left streaming, and the lease must stay held across the external-connection import and + // retry that can follow a first-attempt 404 anyway. + AtomicBoolean leaseTransferred = new AtomicBoolean(); try { ArchivedOrDisposedMatch match = archivedOrDisposedVersionFromFilename(handle, domain, repository, filename); if (match != null) { @@ -246,15 +261,20 @@ public class CodeArtifactPypiController { return Response.status(404).build(); } } - Response response = proxyGet(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename)); + Response response = proxyGetStreamed(handle.baseUrl(), + "/packages/" + SidecarUriUtils.encodeSegment(filename), leaseTransferred, + () -> pypiserver.endUse(handle.repoId())); if (match == null && response.getStatus() == 404 && externalConnectionImporter.tryImportAsset(handle.region(), domain, handle.owner(), repository, handle.repoId(), filename)) { - return proxyGet(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename)); + return proxyGetStreamed(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename), + leaseTransferred, () -> pypiserver.endUse(handle.repoId())); } return response; } finally { - pypiserver.endUse(handle.repoId()); + if (!leaseTransferred.get()) { + pypiserver.endUse(handle.repoId()); + } } } @@ -276,36 +296,91 @@ public class CodeArtifactPypiController { @POST @Consumes(MediaType.WILDCARD) public Response upload(@Context HttpHeaders headers, @PathParam("domain") String domain, - @PathParam("repository") String repository, byte[] body) { - byte[] content = body != null ? body : new byte[0]; - // Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy - // Reactive has already buffered the full body into this byte[] before this method runs, - // so this rejects anything that made it this far rather than bounding memory use upfront. - if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { - return Response.status(413).build(); - } + @PathParam("repository") String repository, InputStream body) { RepositoryHandle handle = requireRepository(headers, domain, repository); try { - return uploadWithLease(headers, domain, repository, content, handle); + return uploadWithLease(headers, domain, repository, body, handle); } finally { pypiserver.endUse(handle.repoId()); } } - private Response uploadWithLease(HttpHeaders headers, String domain, String repository, byte[] content, + /** + * Stages the whole raw multipart body to disk before anything else touches it (its own + * envelope has no exact size semantics of its own, so nothing is checked against the 5 GB + * asset quota yet): {@link #forwardUpload} can then send this exact file straight to + * pypiserver with no multipart rebuild at all, since it already re-sends the entire inbound + * body verbatim, not a reconstructed one. The staging copy itself is still capped, at {@code + * CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES}, well above the real quota to leave room + * for the envelope's own overhead: leaving this particular copy fully uncapped would let a + * client force an arbitrarily large file onto disk before the real per-asset check downstream + * ever runs. + */ + private Response uploadWithLease(HttpHeaders headers, String domain, String repository, InputStream body, RepositoryHandle handle) { String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE); String boundary = MultipartFormParser.extractBoundary(contentType).orElse(null); if (boundary == null) { return Response.status(400).entity("Could not determine multipart boundary from Content-Type.").build(); } - MultipartFormParser.ParsedForm form = MultipartFormParser.parse(content, boundary); + java.nio.file.Path stagedWholeBody; + try { + stagedWholeBody = service.stageAssetBody( + new AssetDigestingInputStream(body, CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES)); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + return Response.status(413).build(); + } + try { + return uploadStagedBody(domain, repository, contentType, boundary, stagedWholeBody, handle); + } finally { + service.deleteStagedAssetBody(stagedWholeBody); + } + } + + /** + * {@code stagedWholeBody}'s own file part is extracted into a second, clean staged file (never + * the whole multipart envelope nor that one part held in a single array), so everything below + * this point (the 5 GB size cap, the existing-content comparison, the byte count recorded on + * a successful publish) runs against real content alone, the same as every other format's + * own asset. + */ + private Response uploadStagedBody(String domain, String repository, String contentType, String boundary, + java.nio.file.Path stagedWholeBody, RepositoryHandle handle) { + java.nio.file.Path stagedAsset = stagedWholeBody.resolveSibling(stagedWholeBody.getFileName() + ".asset"); + try { + MultipartFormParser.ExtractedForm form; + try { + form = MultipartFormParser.extractFilePart(stagedWholeBody, boundary, stagedAsset); + } catch (IOException e) { + return Response.status(400).entity("Could not parse the uploaded multipart body.").build(); + } + return uploadExtractedForm(domain, repository, contentType, form, stagedWholeBody, stagedAsset, handle); + } finally { + service.deleteStagedAssetBody(stagedAsset); + } + } + + private Response uploadExtractedForm(String domain, String repository, String contentType, + MultipartFormParser.ExtractedForm form, java.nio.file.Path stagedWholeBody, + java.nio.file.Path stagedAsset, RepositoryHandle handle) { String packageName = form.fields().get("name"); String version = form.fields().get("version"); - Optional file = form.file(); + Optional file = form.file(); if (packageName == null || packageName.isBlank() || file.isEmpty()) { return Response.status(400).entity("Upload must include name and content fields.").build(); } + long assetSize; + try { + assetSize = Files.size(stagedAsset); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + // Same 5 GB AWS quota PublishPackageVersion enforces: checked against the real asset + // bytes alone (never the surrounding multipart envelope), once they are known, rather + // than before anything was read at all the way a non-multipart format's own cap can be. + if (assetSize > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { + return Response.status(413).build(); + } // Raised by Greptile's review: pypiserver files an upload under the identity its own // filename embeds, not under whatever this form's name/version fields happen to say // (PypiserverSidecarClient#filenameEmbedsVersion's own javadoc explains why that @@ -374,11 +449,12 @@ public class CodeArtifactPypiController { } } - Optional existing = existingFileContent(handle.baseUrl(), packageName, file.get().filename()); - if (existing.isPresent()) { - if (Arrays.equals(existing.get(), file.get().content())) { - return Response.status(200).build(); - } + ExistingFileComparison existing = compareExistingFile(handle.baseUrl(), packageName, + file.get().filename(), stagedAsset); + if (existing == ExistingFileComparison.MATCHES) { + return Response.status(200).build(); + } + if (existing == ExistingFileComparison.DIFFERS) { return Response.status(409) .entity("File already exists. See " + "https://docs.aws.amazon.com/codeartifact/latest/ug/PyPI-format.html") @@ -397,11 +473,15 @@ public class CodeArtifactPypiController { long readmeFenceSnapshot = version == null || version.isBlank() ? 0L : service.currentContainerBackedVersionFence(handle.region(), domain, handle.owner(), repository, "pypi", null, packageName, version); - Response response = forwardUpload(handle.baseUrl(), contentType, content); + // The entire original raw multipart body is re-sent verbatim, boundary and all, + // exactly as the byte[]-based version of this call always has: pypiserver parses its + // own multipart form the same way twine built it, so there was never a need to + // rebuild one here, only to stream the one already staged instead of a resident array. + Response response = forwardUpload(handle.baseUrl(), contentType, stagedWholeBody); boolean uploadSucceeded = response.getStatus() == 200 || response.getStatus() == 201; if (uploadSucceeded) { service.completeContainerBackedPublishIfCurrentRepository(handle.region(), domain, handle.owner(), - repository, handle.repoId(), "pypi", packageName, version, file.get().content().length, + repository, handle.repoId(), "pypi", packageName, version, assetSize, fenceSnapshot, beforeRevision, form.fields().get("description"), readmeFenceSnapshot); } return response; @@ -426,7 +506,19 @@ public class CodeArtifactPypiController { * {@code ?} would be reinterpreted by {@link URI#create} as a fragment or query string, * silently fetching a different path than the one actually requested. */ - private Optional existingFileContent(String baseUrl, String packageName, String filename) { + private enum ExistingFileComparison { NOT_LISTED, MATCHES, DIFFERS } + + /** + * {@code existingFileContent}'s own streamed sibling: compares pypiserver's own stored file + * against {@code localAsset} chunk by chunk from each side, rather than buffering the remote + * file into a {@code byte[]} first (capped at ~2 GiB) just to compare it against another + * array. Uses {@code readNBytes} so a short individual {@code read()} on either side (always + * possible, never guaranteed to fill the buffer) can't be mistaken for the two disagreeing, + * the same technique {@code ReposiliteSidecarClient}'s own streamed idempotent-match check + * uses. + */ + private ExistingFileComparison compareExistingFile(String baseUrl, String packageName, String filename, + java.nio.file.Path localAsset) { String normalized = PypiserverSidecarClient.normalizePackageName(packageName); URI indexUri = SidecarUriUtils.combine(URI.create(baseUrl), SIMPLE_PATH + SidecarUriUtils.encodeSegment(normalized) + "/"); @@ -440,7 +532,7 @@ public class CodeArtifactPypiController { + " before publishing", e); } if (indexResponse.statusCode() == 404) { - return Optional.empty(); + return ExistingFileComparison.NOT_LISTED; } if (indexResponse.statusCode() != 200) { throw new IllegalStateException( @@ -448,25 +540,37 @@ public class CodeArtifactPypiController { + ": upstream returned " + indexResponse.statusCode()); } if (!indexListsFilename(indexResponse.body(), filename)) { - return Optional.empty(); + return ExistingFileComparison.NOT_LISTED; } URI fileUri = SidecarUriUtils.combine(URI.create(baseUrl), "/packages/" + SidecarUriUtils.encodeSegment(filename)); HttpRequest fileRequest = HttpRequest.newBuilder(fileUri).timeout(Duration.ofSeconds(10)).GET().build(); - HttpResponse fileResponse; + HttpResponse fileResponse; try { - fileResponse = httpClient.send(fileRequest, BodyHandlers.ofByteArray()); + fileResponse = httpClient.send(fileRequest, BodyHandlers.ofInputStream()); } catch (Exception e) { throw new IllegalStateException( "Could not fetch the existing pypi file " + filename + " to check for a content match", e); } if (fileResponse.statusCode() != 200) { + try { + fileResponse.body().close(); + } catch (IOException ignored) { + // Closing an unread stream best-effort only; the exception thrown right below is + // the one that actually matters here. + } throw new IllegalStateException( "Could not fetch the existing pypi file " + filename + " to check for a content match: " + "upstream returned " + fileResponse.statusCode()); } - return Optional.of(fileResponse.body()); + try (InputStream remote = fileResponse.body(); InputStream local = Files.newInputStream(localAsset)) { + return StreamEquality.contentsMatch(remote, local) ? ExistingFileComparison.MATCHES + : ExistingFileComparison.DIFFERS; + } catch (IOException e) { + throw new UncheckedIOException( + "Could not compare the existing pypi file " + filename + " against the uploaded content", e); + } } private record ArchivedOrDisposedMatch(String packageName, String version) { @@ -529,12 +633,22 @@ public class CodeArtifactPypiController { return filenames; } - private Response forwardUpload(String baseUrl, String contentType, byte[] content) { - HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/")) - .timeout(Duration.ofSeconds(30)) - .header("Content-Type", contentType) - .POST(BodyPublishers.ofByteArray(content)) - .build(); + private Response forwardUpload(String baseUrl, String contentType, java.nio.file.Path stagedWholeBody) { + long stagedSize; + try { + stagedSize = Files.size(stagedWholeBody); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(URI.create(baseUrl + "/")) + .timeout(SidecarUriUtils.transferTimeout(stagedSize)) + .header("Content-Type", contentType); + try { + requestBuilder.POST(BodyPublishers.ofFile(stagedWholeBody)); + } catch (FileNotFoundException e) { + throw new UncheckedIOException(e); + } + HttpRequest request = requestBuilder.build(); HttpResponse response; try { response = httpClient.send(request, BodyHandlers.discarding()); @@ -566,6 +680,43 @@ public class CodeArtifactPypiController { return Response.status(response.statusCode()).entity(response.body()).type(contentType).build(); } + /** + * {@link #proxyGet}'s streamed sibling, for {@link #downloadFile}'s real asset downloads: that + * method's own {@code byte[]} is fine for {@link #packageIndex}'s small HTML listing, but a + * downloaded package file can be gigabytes. + * + *

On a real 200, {@code leaseTransferred} is set so the caller's lease release ({@code + * afterClose}) runs only once the entity stream this method returns is actually closed (via + * {@link StreamingResponses#closingWith}), keeping the sidecar container leased for as long + * as the real transfer takes rather than just until this method returns. A 404 leaves it + * unset: nothing is left streaming, so the caller releases it synchronously instead. + * + *

Uses the worst-case download timeout, not {@link #proxyGet}'s flat 10 seconds: the real + * asset file this fetches can be gigabytes, and its real size isn't known until the response + * itself arrives. + */ + private Response proxyGetStreamed(String baseUrl, String encodedPath, AtomicBoolean leaseTransferred, + Runnable afterClose) { + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath)) + .timeout(SidecarUriUtils.maxTransferTimeout()).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the pypi sidecar at " + encodedPath, e); + } + if (response.statusCode() == 404) { + StreamingResponses.closeQuietly(response.body()); + return Response.status(404).build(); + } + String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream"); + Response.ResponseBuilder builder = Response.status(response.statusCode()).type(contentType); + response.headers().firstValueAsLong("Content-Length").ifPresent(len -> builder.header("Content-Length", len)); + leaseTransferred.set(true); + InputStream body = StreamingResponses.closingWith(response.body(), afterClose); + return StreamingResponses.streamingResponse(body, stream -> builder.entity(stream).build()); + } + private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) { String token = CodeArtifactTokenExtractor.extractToken(headers); AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain) diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java index 7fa3b9c814..93e58f4dda 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java @@ -10,10 +10,12 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; -import java.util.HexFormat; import java.util.List; import java.util.Optional; import java.util.Set; @@ -429,72 +431,105 @@ public class CodeArtifactPypiExternalConnectionImporter { long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, String importLockKey, JsonNode file, String candidateFilename) { String url = file.path("url").asText(null); - Optional fetched; + Path staged; try { - fetched = externalConnectionClient.fetchFile(externalConnectionName, url); - } catch (RuntimeException e) { - LOG.warnv(e, "Could not fetch {0} from {1} while retaining a pypi package through an " - + "external connection; skipping this file.", url, externalConnectionName); - return FileImportStatus.SKIPPED; + staged = Files.createTempFile("codeartifact-pypi-import-", ".bin"); + } catch (IOException e) { + throw new UncheckedIOException("Failed to create a staging file for a pypi external-connection " + + "import", e); } - if (fetched.isEmpty()) { - return FileImportStatus.SKIPPED; - } - byte[] content = fetched.get().content(); - // The same 5 GB AWS quota CodeArtifactPypiController#upload already enforces on a direct - // publish: without this, a single huge real file would be buffered whole (fetchFile has no - // streaming size cap of its own) and then written and counted as if any size were - // acceptable here just because it came from an external connection rather than a direct - // upload (raised in review). - if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { - LOG.warnv("Skipping {0}: the real registry''s own file is larger than this emulator''s " - + "{1}-byte asset quota.", candidateFilename, CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); - return FileImportStatus.SKIPPED; - } - // PEP 691/700's own hashes.sha256, verified against the real fetched bytes before they are - // ever written: fetchFile already restricts which host a file's bytes can come from, but a - // host passing that check is not the same as the bytes genuinely matching what the trusted - // index response itself said this exact file is (a truncated transfer, or a compromised/ - // misbehaving file host, would otherwise be retained and served as if it were correct). - // Verified only when the index actually names a hash (PEP 691 makes the field optional, - // though pypi.org's own real responses always include it): its absence is not itself proof - // of tampering, so this does not refuse a file over a missing hash alone, only a mismatched - // one. - String expectedSha256 = file.path("hashes").path("sha256").asText(null); - if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(sha256Hex(content))) { - LOG.warnv("Skipping {0}: its real bytes do not match the sha256 the registry''s own index " - + "names for it.", candidateFilename); - return FileImportStatus.SKIPPED; - } - // The lock below, the recheck inside it, and the write together close a gap the bare - // in-memory alreadyPresent snapshot taken once before this whole import started cannot on - // its own: a second call into this exact version -- a different pip request racing this - // one, or the background sibling batch racing the synchronous requested-file path -- could - // reach the very same candidate. retainAssetUnderVersionFence's own write has no way to - // tell a fresh write from a re-write of identical content (see AssetRetentionAttemptResult's - // own javadoc), so without serializing the recheck and the write together on a lock keyed - // to this exact version, two such calls could both see candidateFilename missing and both - // write it, double-counting its bytes in DescribeDomain's assetSizeBytes. - synchronized (siblingWriteLocks.computeIfAbsent(importLockKey, key -> new Object())) { - if (pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, packageName, version) - .contains(candidateFilename)) { - return FileImportStatus.ALREADY_PRESENT; + try { + Optional fetched; + try { + fetched = externalConnectionClient.fetchFile(externalConnectionName, url, staged); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { + // The same 5 GB AWS quota CodeArtifactPypiController#upload already enforces on a + // direct publish, now checked by fetchFile(Path) itself during the download + // (via AssetDigestingInputStream.copyCapped) rather than in a second pass over + // the staged file afterward: a file this large is rejected before it is ever + // fully pulled across the network and written to local disk. + LOG.warnv("Skipping {0}: the real registry''s own file is larger than this emulator''s " + + "{1}-byte asset quota.", candidateFilename, CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + return FileImportStatus.SKIPPED; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} from {1} while retaining a pypi package through an " + + "external connection; skipping this file.", url, externalConnectionName); + return FileImportStatus.SKIPPED; } - // The fence check and the real write happen inside the very same synchronized call - // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions already - // hold across their own entire operation, so a write here and one of those four - // operations can never interleave. - CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, - domain, owner, repository, "pypi", null, packageName, version, versionFenceSnapshot, - packageFenceSnapshot, episodeId, repoId, candidateFilename, content, - () -> pypiserver.storePackageVersionAsset(repoId, domain, repository, null, packageName, version, - candidateFilename, content)); - if (!result.fenceMatched()) { - // The version itself is gone: every later candidate in this same attempt would - // fail the exact same way. - return FileImportStatus.FENCE_GONE; + if (fetched.isEmpty()) { + return FileImportStatus.SKIPPED; + } + long contentLength; + String actualSha256; + // A second streaming pass over the now-staged, already-size-checked file, purely to + // compute the PEP 691/700 sha256 check below: fetchFile(Path) only reports the real + // byte count back, not its own digests, so this reuses AssetDigestingInputStream for + // that hash alone. The cap passed here can never actually trip (the file is already + // guaranteed no larger than it by the pass above); it is just the same bounded + // reader, not a second enforcement point. + try (InputStream in = Files.newInputStream(staged)) { + AssetDigestingInputStream digesting = new AssetDigestingInputStream(in, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + digesting.transferTo(OutputStream.nullOutputStream()); + contentLength = digesting.size(); + actualSha256 = digesting.hashesHex().get("SHA-256"); + } catch (IOException e) { + LOG.warnv(e, "Could not read the staged copy of {0} while retaining a pypi package through an " + + "external connection; skipping this file.", candidateFilename); + return FileImportStatus.SKIPPED; + } + // PEP 691/700's own hashes.sha256, verified against the real fetched bytes before they + // are ever written: fetchFile already restricts which host a file's bytes can come + // from, but a host passing that check is not the same as the bytes genuinely matching + // what the trusted index response itself said this exact file is (a truncated + // transfer, or a compromised/misbehaving file host, would otherwise be retained and + // served as if it were correct). Verified only when the index actually names a hash + // (PEP 691 makes the field optional, though pypi.org's own real responses always + // include it): its absence is not itself proof of tampering, so this does not refuse a + // file over a missing hash alone, only a mismatched one. + String expectedSha256 = file.path("hashes").path("sha256").asText(null); + if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(actualSha256)) { + LOG.warnv("Skipping {0}: its real bytes do not match the sha256 the registry''s own index " + + "names for it.", candidateFilename); + return FileImportStatus.SKIPPED; + } + // The lock below, the recheck inside it, and the write together close a gap the bare + // in-memory alreadyPresent snapshot taken once before this whole import started cannot + // on its own: a second call into this exact version -- a different pip request racing + // this one, or the background sibling batch racing the synchronous requested-file path + // -- could reach the very same candidate. retainAssetUnderVersionFence's own write has + // no way to tell a fresh write from a re-write of identical content (see + // AssetRetentionAttemptResult's own javadoc), so without serializing the recheck and + // the write together on a lock keyed to this exact version, two such calls could both + // see candidateFilename missing and both write it, double-counting its bytes in + // DescribeDomain's assetSizeBytes. + synchronized (siblingWriteLocks.computeIfAbsent(importLockKey, key -> new Object())) { + if (pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, packageName, version) + .contains(candidateFilename)) { + return FileImportStatus.ALREADY_PRESENT; + } + // The fence check and the real write happen inside the very same synchronized call + // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions + // already hold across their own entire operation, so a write here and one of those + // four operations can never interleave. + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "pypi", null, packageName, version, versionFenceSnapshot, + packageFenceSnapshot, episodeId, repoId, candidateFilename, contentLength, + () -> pypiserver.storePackageVersionAsset(repoId, domain, repository, null, packageName, + version, candidateFilename, staged, contentLength)); + if (!result.fenceMatched()) { + // The version itself is gone: every later candidate in this same attempt would + // fail the exact same way. + return FileImportStatus.FENCE_GONE; + } + return result.wroteNewContent() ? FileImportStatus.WROTE : FileImportStatus.SKIPPED; + } + } finally { + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete a staged pypi external-connection import file at {0}", staged); } - return result.wroteNewContent() ? FileImportStatus.WROTE : FileImportStatus.SKIPPED; } } @@ -544,14 +579,6 @@ public class CodeArtifactPypiExternalConnectionImporter { .findFirst(); } - private static String sha256Hex(byte[] content) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content)); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-256 is not available in this JVM", e); - } - } - private String pypiExternalConnectionName(String region, String domain, String owner, String repository) { return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream() .filter(ec -> "pypi".equals(ec.getPackageFormat())) diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java index 7ed3a184c8..ef898bc483 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java @@ -12,6 +12,7 @@ import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.Resettable; import io.floci.aws.core.common.ServiceConfigAccess; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.core.common.auth.SigV4RequestValidator; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -25,6 +26,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -39,7 +41,6 @@ import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; @@ -132,6 +133,14 @@ public class CodeArtifactService implements Resettable { // Package-private: reused by CodeArtifactMavenController so the Maven proxy enforces the same // documented 5 GB AWS quota rather than duplicating the constant. static final long MAX_ASSET_FILE_SIZE_BYTES = 5L * 1024 * 1024 * 1024; + // Package-private: the pypi/NuGet push controllers stage their whole raw multipart request + // body to disk before they have parsed far enough to know the real asset's own size (the + // envelope's boundaries, headers, and handful of small text fields have no size semantics of + // their own against the 5 GB asset quota). Without a cap on that staging step itself, a + // client could still force an arbitrarily large, wholly uncapped file onto disk before the + // real per-asset quota check downstream ever gets a chance to run. 64 MiB of slack is many + // times more than any real multipart envelope's own overhead ever needs. + static final long MAX_MULTIPART_ENVELOPE_BYTES = MAX_ASSET_FILE_SIZE_BYTES + 64L * 1024 * 1024; private static final int MAX_ASSETS_PER_PACKAGE_VERSION = 350; // AWS's own wire model: every batch package-version action's own PackageVersionList shape // (CopyPackageVersionsRequest.versions, UpdatePackageVersionsStatusRequest.versions, @@ -153,6 +162,13 @@ public class CodeArtifactService implements Resettable { public record ResourcePolicy(String resourceArn, String revision, String document) {} public record PublishPackageVersionResult(CodeArtifactPackageVersion packageVersion, PackageAsset asset) {} public record PackageVersionAssetResult(PackageAsset asset, String packageVersionRevision) {} + /** + * {@link PackageVersionAssetResult}'s streamed sibling, for {@code GetPackageVersionAsset}'s + * real HTTP entry point: the caller owns closing {@code content}. {@code contentLength} is -1 + * when it could not be determined up front. + */ + public record PackageVersionAssetStreamResult(InputStream content, long contentLength, String assetName, + String packageVersionRevision) {} public record PackageVersionReadmeResult(String format, String namespace, String packageName, String version, String versionRevision, String readme) {} public record SuccessfulPackageVersionInfo(String revision, String status) {} @@ -872,30 +888,76 @@ public class CodeArtifactService implements Resettable { // ------------------------------------------------------- package versions - public synchronized PublishPackageVersionResult publishPackageVersion(String region, String domain, + public PublishPackageVersionResult publishPackageVersion(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, String version, String assetName, String assetSha256, String unfinishedParam, byte[] content) { + byte[] assetContent = content != null ? content : new byte[0]; + return publishPackageVersion(region, domain, domainOwner, repository, format, namespace, packageName, + version, assetName, assetSha256, unfinishedParam, new ByteArrayInputStream(assetContent)); + } + + /** + * {@code byte[]}-taking sibling's own streamed real implementation: every production caller + * (the generic {@code PublishPackageVersion} controller route) goes through this one, for an + * asset too large to ever hold as a single {@code byte[]} (~2 GiB, the JVM array limit) the + * way the one above still does. Staging the body to disk and digesting it (the only genuinely + * slow part of a large publish) happens here, outside this method's own lock, so a multi-GB + * upload does not serialize every other CodeArtifact operation for as long as it takes to + * read; {@link #publishPackageVersionLocked} then does the fast, lock-protected decision and + * write against the already-staged file and already-computed hashes. + */ + public PublishPackageVersionResult publishPackageVersion(String region, String domain, + String domainOwner, String repository, String format, String namespace, String packageName, + String version, String assetName, String assetSha256, String unfinishedParam, InputStream body) { if (!"generic".equals(format)) { throw validation("format must be 'generic'; PublishPackageVersion only supports the generic " + "package format."); } - boolean unfinished = parseBoolean(unfinishedParam); - validatePackageToken("package", packageName); - validatePackageToken("packageVersion", version); - if (namespace != null) { - validatePackageToken("namespace", namespace); - } validateAssetName(assetName); if (assetSha256 == null || !SigV4RequestValidator.isSha256Hex(assetSha256)) { throw validation("assetSHA256 is required and must be a 64-character SHA-256 hex digest."); } - byte[] assetContent = content != null ? content : new byte[0]; - if (assetContent.length > MAX_ASSET_FILE_SIZE_BYTES) { + // Raised by Qodo's review of this PR: these are cheap, request-only checks with no + // dependency on the upload itself, so running them before staging+digesting (up to 5 GB, + // the only genuinely slow part of this method) rejects a malformed coordinate or a + // request aimed at a nonexistent repository immediately, instead of only after paying for + // the full staging cost first. publishPackageVersionLocked has exactly one caller (this + // method), so this is a move, not a duplicate: the repository/domain checks that still + // need the lock stay there. + validatePackageToken("package", packageName); + validatePackageToken("packageVersion", version); + if (namespace != null) { + validatePackageToken("namespace", namespace); + } + AssetUpload upload; + try { + AssetDigestingInputStream digesting = new AssetDigestingInputStream(body, MAX_ASSET_FILE_SIZE_BYTES); + Path staged = stageAssetBody(digesting); + upload = new AssetUpload(staged, digesting.size(), digesting.hashesHex()); + } catch (AssetDigestingInputStream.AssetTooLargeException e) { throw new AwsException("ServiceQuotaExceededException", "The maximum asset file size is 5 Gigabytes.", 402, resourceFields(assetName, "asset")); } - String actualSha256 = Digests.sha256Hex(assetContent); + try { + return publishPackageVersionLocked(region, domain, domainOwner, repository, format, namespace, + packageName, version, assetName, assetSha256, unfinishedParam, upload); + } finally { + // A no-op when the write below already moved this same file into place: deleting an + // already-moved path is simply not there to delete. + deleteStagedAssetBody(upload.content()); + } + } + + /** {@link #publishPackageVersion(String, String, String, String, String, String, String, String, String, + * String, String, InputStream)}'s own already-staged, already-digested upload. */ + private record AssetUpload(Path content, long size, Map hashes) {} + + private synchronized PublishPackageVersionResult publishPackageVersionLocked(String region, String domain, + String domainOwner, String repository, String format, String namespace, String packageName, + String version, String assetName, String assetSha256, String unfinishedParam, AssetUpload upload) { + boolean unfinished = parseBoolean(unfinishedParam); + String actualSha256 = upload.hashes().get("SHA-256"); if (!assetSha256.equalsIgnoreCase(actualSha256)) { throw validation("assetSHA256 does not match the SHA-256 hash of the uploaded content."); } @@ -954,7 +1016,7 @@ public class CodeArtifactService implements Resettable { // (missing file, or bytes corrupted independently of Floci) still self-heal here, since // existingFileMatches actually reads the file back rather than trusting it's fine. if (!existingFileMatches(owner, key, assetName, actualSha256)) { - writeAssetContent(owner, key, assetName, assetContent); + writeAssetContent(owner, key, assetName, upload.content()); } return new PublishPackageVersionResult(pv, existingAsset); } @@ -982,7 +1044,7 @@ public class CodeArtifactService implements Resettable { // Only rewrites when the actual disk bytes don't check out: see the identical // reasoning on the Published branch above. if (!existingFileMatches(owner, key, assetName, actualSha256)) { - writeAssetContent(owner, key, assetName, assetContent); + writeAssetContent(owner, key, assetName, upload.content()); } return new PublishPackageVersionResult(pv, existingAsset); } @@ -995,10 +1057,9 @@ public class CodeArtifactService implements Resettable { PackageAsset asset = new PackageAsset(); asset.setName(assetName); - asset.setSize(assetContent.length); - asset.setContent(assetContent); - asset.setHashes(computeHashes(assetContent)); - writeAssetContent(owner, key, assetName, assetContent); + asset.setSize(upload.size()); + asset.setHashes(new LinkedHashMap<>(upload.hashes())); + writeAssetContent(owner, key, assetName, upload.content()); assets.put(assetName, asset); pv.setAssets(assets); @@ -1096,12 +1157,12 @@ public class CodeArtifactService implements Resettable { nextToken, 100, 1000, "ValidationException"); List pageAssets = new ArrayList<>(); for (String assetName : namePage.items()) { - byte[] content = manager.fetchPackageVersionAsset(repoId, domain, repository, namespace, - packageName, version, assetName) + RepositorySidecarManager.AssetDigest digest = manager.fetchPackageVersionAssetDigest(repoId, + domain, repository, namespace, packageName, version, assetName) .orElseThrow(() -> new AwsException("InternalServerException", "Could not list version '" + version + "' of package '" + packageName + "': its asset '" + assetName + "' disappeared between listing and fetching it.", 500)); - pageAssets.add(new AssetSummary(assetName, content.length, computeHashes(content))); + pageAssets.add(new AssetSummary(assetName, digest.size(), digest.hashes())); } page = new PaginatedResult<>(pageAssets, namePage.nextToken()); revision = currentContainerBackedVersionStatus(owner, region, domain, repository, format, namespace, @@ -2054,8 +2115,9 @@ public class CodeArtifactService implements Resettable { String version, List assetNames) { Map sizeByAssetName = new LinkedHashMap<>(); for (String assetName : assetNames) { - sizeByAssetName.put(assetName, manager.fetchPackageVersionAsset(repoId, domain, repository, namespace, - packageName, version, assetName).map(bytes -> (long) bytes.length).orElse(0L)); + sizeByAssetName.put(assetName, manager.fetchPackageVersionAssetDigest(repoId, domain, repository, + namespace, packageName, version, assetName).map(RepositorySidecarManager.AssetDigest::size) + .orElse(0L)); } String key = ownerScopedKey(owner, packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName))); @@ -3340,6 +3402,38 @@ public class CodeArtifactService implements Resettable { return new MavenDeployAttemptResult(true, outcome); } + /** + * {@link #deployMavenAssetUnderVersionFence(String, String, String, String, String, String, + * String, long, long, long, ReposiliteSidecarClient, String, String, byte[])}'s own streamed + * sibling, for a release too large to ever hold as one {@code byte[]} (Maven's real-world + * assets are the least likely of any format here to actually need this, but the mechanism is + * shared infrastructure, not a per-format one): {@code contentLength} is the caller's own + * already-known size (from staging/digesting the upload), passed through rather than re-read + * from disk a second time. + */ + public synchronized MavenDeployAttemptResult deployMavenAssetUnderVersionFence(String region, String domain, + String domainOwner, String repository, String namespace, String packageName, String version, + long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, ReposiliteSidecarClient reposilite, + String repoId, String gav, Path content, long contentLength) { + if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, "maven", namespace, packageName, + version, repoId, versionFenceSnapshot, episodeId)) { + return new MavenDeployAttemptResult(false, null); + } + ReposiliteSidecarClient.DeployOutcome outcome; + try { + outcome = reposilite.deployArtifact(repoId, gav, content); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not deploy {0} while retaining a Maven release through an external connection.", + gav); + return new MavenDeployAttemptResult(true, null); + } + if ((outcome.status() == 200 || outcome.status() == 201) && outcome.wroteNewContent()) { + recordContainerBackedAssetBytes(region, domain, domainOwner, repository, "maven", namespace, + packageName, contentLength, packageFenceSnapshot); + } + return new MavenDeployAttemptResult(true, outcome); + } + /** * The shared fence/status/claim-episode gate {@link #deployMavenAssetUnderVersionFence} and * {@link #retainAssetUnderVersionFence} both check, inside the very same {@code synchronized} @@ -3407,7 +3501,7 @@ public class CodeArtifactService implements Resettable { public synchronized AssetRetentionAttemptResult retainAssetUnderVersionFence(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, String version, long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, - String repositoryContainerId, String assetName, byte[] content, Runnable write) { + String repositoryContainerId, String assetName, long contentLength, Runnable write) { if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, format, namespace, packageName, version, repositoryContainerId, versionFenceSnapshot, episodeId)) { return new AssetRetentionAttemptResult(false, false); @@ -3420,7 +3514,7 @@ public class CodeArtifactService implements Resettable { return new AssetRetentionAttemptResult(true, false); } recordContainerBackedAssetBytes(region, domain, domainOwner, repository, format, namespace, packageName, - content.length, packageFenceSnapshot); + contentLength, packageFenceSnapshot); return new AssetRetentionAttemptResult(true, true); } @@ -3707,20 +3801,8 @@ public class CodeArtifactService implements Resettable { public PackageVersionAssetResult getPackageVersionAsset(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, String version, String assetName, String packageVersionRevision) { - if (format == null || !PACKAGE_FORMATS.contains(format)) { - throw validation("format must be one of " + PACKAGE_FORMATS + "."); - } - requireNonBlank(domain, "domain"); - requireNonBlank(repository, "repository"); - requireNonBlank(packageName, "package"); - requireNonBlank(version, "packageVersion"); - requireNonBlank(assetName, "asset"); - validatePackageToken("package", packageName); - validatePackageToken("packageVersion", version); - if (namespace != null) { - validatePackageToken("namespace", namespace); - } - String owner = effectiveOwner(domainOwner); + String owner = validateAssetFetchArguments(format, domain, repository, packageName, version, assetName, + namespace, domainOwner); // Maven, npm, pypi, and nuget are metadata-free passthroughs straight to their own sidecar // (ReposiliteSidecarClient/VerdaccioSidecarClient/PypiserverSidecarClient/BagetterSidecarClient): publish for @@ -3754,6 +3836,60 @@ public class CodeArtifactService implements Resettable { return new PackageVersionAssetResult(asset, pv.getRevision()); } + /** + * {@link #getPackageVersionAsset}'s streamed sibling, for {@code GetPackageVersionAsset}'s real + * HTTP entry point, which has to hand back whatever was actually published, and that can be + * gigabytes: the {@code byte[]}-returning method above stays exactly as it was for its ~40 + * direct test call sites and anything else that only ever fetches a small fixture. The caller + * owns closing the returned stream. + */ + public PackageVersionAssetStreamResult getPackageVersionAssetStreamed(String region, String domain, + String domainOwner, String repository, String format, String namespace, String packageName, + String version, String assetName, String packageVersionRevision) { + String owner = validateAssetFetchArguments(format, domain, repository, packageName, version, assetName, + namespace, domainOwner); + + if (CONTAINER_BACKED_FORMATS.contains(format)) { + return getContainerBackedPackageVersionAssetStreamed(region, domain, owner, repository, format, + namespace, packageName, version, assetName, packageVersionRevision); + } + + String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version); + CodeArtifactPackageVersion pv = packageVersions.getForAccount(owner, key) + .orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName + + "' was not found.", version, "package-version")); + requireAssetDownloadable(pv.getStatus(), version); + if (packageVersionRevision != null && !packageVersionRevision.equals(pv.getRevision())) { + throw notFound("Package version '" + version + "' was not found at revision '" + + packageVersionRevision + "'.", version, "package-version"); + } + PackageAsset asset = pv.getAssets().get(assetName); + if (asset == null) { + throw notFound("Asset '" + assetName + "' was not found on package version '" + version + "'.", + assetName, "asset"); + } + return new PackageVersionAssetStreamResult(openAssetContent(owner, key, assetName), asset.getSize(), + assetName, pv.getRevision()); + } + + private String validateAssetFetchArguments(String format, String domain, String repository, String packageName, + String version, String assetName, String namespace, String domainOwner) { + if (format == null || !PACKAGE_FORMATS.contains(format)) { + throw validation("format must be one of " + PACKAGE_FORMATS + "."); + } + requireNonBlank(domain, "domain"); + requireNonBlank(repository, "repository"); + requireNonBlank(packageName, "package"); + requireNonBlank(version, "packageVersion"); + requireNonBlank(assetName, "asset"); + validatePackageToken("package", packageName); + validatePackageToken("packageVersion", version); + if (namespace != null) { + validatePackageToken("namespace", namespace); + } + return effectiveOwner(domainOwner); + } + private PackageVersionAssetResult getContainerBackedPackageVersionAsset(String region, String domain, String owner, String repository, String format, String namespace, String packageName, String version, String assetName, String packageVersionRevision) { @@ -3793,6 +3929,47 @@ public class CodeArtifactService implements Resettable { } } + /** {@link #getContainerBackedPackageVersionAsset}'s streamed sibling; see that method's own javadoc. */ + private PackageVersionAssetStreamResult getContainerBackedPackageVersionAssetStreamed(String region, + String domain, String owner, String repository, String format, String namespace, String packageName, + String version, String assetName, String packageVersionRevision) { + if ("maven".equals(format) && (namespace == null || namespace.isBlank())) { + throw validation("namespace is required when requesting an asset from a maven package version."); + } + RepositorySidecarManager manager = sidecarRegistry.forFormat(format) + .orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName + + "' was not found.", version, "package-version")); + String repoId = resolveContainerIdAndBeginUse(format, region, domain, owner, repository, manager); + boolean leaseTransferred = false; + try { + PackageVersionStatusOverride state = currentContainerBackedVersionStatus(owner, region, domain, repository, + format, namespace, packageName, version, repoId); + String revision = state.revision(); + if (packageVersionRevision != null && !packageVersionRevision.equals(revision)) { + throw notFound("Package version '" + version + "' was not found at revision '" + + packageVersionRevision + "'.", version, "package-version"); + } + requireAssetDownloadable(state.status(), version); + RepositorySidecarManager.StreamedAsset streamed = manager.fetchPackageVersionAssetStreamed(repoId, + domain, repository, namespace, packageName, version, assetName) + .orElseThrow(() -> notFound("Asset '" + assetName + "' was not found on package version '" + + version + "'.", assetName, "asset")); + // The caller (CodeArtifactController) only drains this stream later, when JAX-RS + // actually writes the deferred StreamingOutput response body: releasing the lease + // here, as soon as this method returns, would let a concurrent DeleteRepository stop + // this sidecar container mid-download. Tying the release to the stream's own close + // instead keeps the container alive for exactly as long as beginUse/endUse promise. + InputStream content = StreamingResponses.closingWith(streamed.content(), + () -> endSidecarUse(manager, repoId)); + leaseTransferred = true; + return new PackageVersionAssetStreamResult(content, streamed.contentLength(), assetName, revision); + } finally { + if (!leaseTransferred) { + endSidecarUse(manager, repoId); + } + } + } + /** * There's no stored revision for a sidecar-backed format to compare against, so one is * synthesized from the version coordinate itself (this repository's own sidecar container id, @@ -4049,20 +4226,33 @@ public class CodeArtifactService implements Resettable { // hashes before any version in this same batch has anything written to the destination // or committed: a missing or corrupted source asset for version 3 of 5 must never leave // versions 1 and 2 committed while the batch as a whole fails, and must never be - // discovered only after this method already started mutating the destination. - Map> verifiedContentByVersion = new LinkedHashMap<>(); - for (String version : pendingCopies) { - verifiedContentByVersion.put(version, verifyAndReadSourceAssets(owner, sourceByVersion.get(version))); - } + // discovered only after this method already started mutating the destination. Each + // asset is staged to its own temp file rather than held as a byte[] (a whole batch's + // worth of multi-GB assets could never fit as resident arrays at once); every staged + // file across the whole batch call is collected here and deleted exactly once in the + // finally below, regardless of how the batch finishes, the same convention + // copyContainerBackedPackageVersions already uses. + List stagedFiles = new ArrayList<>(); + try { + Map> verifiedContentByVersion = new LinkedHashMap<>(); + for (String version : pendingCopies) { + verifiedContentByVersion.put(version, verifyAndReadSourceAssets(owner, sourceByVersion.get(version), + stagedFiles)); + } - Map successes = new LinkedHashMap<>(); - for (String version : pendingCopies) { - CodeArtifactPackageVersion copied = copyGenericPackageVersionAssets(owner, region, domain, - destinationRepository, format, namespace, packageName, version, sourceByVersion.get(version), - verifiedContentByVersion.get(version)); - successes.put(version, new SuccessfulPackageVersionInfo(copied.getRevision(), copied.getStatus())); + Map successes = new LinkedHashMap<>(); + for (String version : pendingCopies) { + CodeArtifactPackageVersion copied = copyGenericPackageVersionAssets(owner, region, domain, + destinationRepository, format, namespace, packageName, version, + sourceByVersion.get(version), verifiedContentByVersion.get(version)); + successes.put(version, new SuccessfulPackageVersionInfo(copied.getRevision(), copied.getStatus())); + } + return new CopyPackageVersionsResult(successes, Map.of()); + } finally { + for (Path staged : stagedFiles) { + deleteStagedAssetBody(staged); + } } - return new CopyPackageVersionsResult(successes, Map.of()); } /** @@ -4195,97 +4385,136 @@ public class CodeArtifactService implements Resettable { // Same verify-before-write ordering as the generic path's own two-pass split: every // pending version's source assets are fetched and confirmed present before any version in - // this batch has anything written to the destination. - Map> verifiedContentByVersion = new LinkedHashMap<>(); - for (String version : pendingCopies) { - Map contentByAsset = new LinkedHashMap<>(); - for (String assetName : sourceAssetNamesByVersion.get(version)) { - byte[] content = manager.fetchPackageVersionAsset(sourceRepoId, domain, sourceRepository, namespace, - packageName, version, assetName) - .orElseThrow(() -> new AwsException("InternalServerException", "Could not copy version '" - + version + "' of package '" + packageName + "': its asset '" + assetName - + "' disappeared from the source repository between listing and fetching it.", - 500)); - contentByAsset.put(assetName, content); + // this batch has anything written to the destination. Each asset is staged to its own + // temp file rather than held as a byte[] (a whole batch's worth of multi-GB assets could + // never fit as resident arrays at once); every staged file across the whole batch call, + // source content and destination rollback snapshots alike, is collected here and deleted + // exactly once in the finally below, regardless of how the batch finishes. + List stagedFiles = new ArrayList<>(); + try { + Map> verifiedContentByVersion = new LinkedHashMap<>(); + for (String version : pendingCopies) { + Map contentByAsset = new LinkedHashMap<>(); + for (String assetName : sourceAssetNamesByVersion.get(version)) { + RepositorySidecarManager.StreamedAsset streamed = manager.fetchPackageVersionAssetStreamed( + sourceRepoId, domain, sourceRepository, namespace, packageName, version, + assetName) + .orElseThrow(() -> new AwsException("InternalServerException", "Could not copy " + + "version '" + version + "' of package '" + packageName + "': its asset '" + + assetName + "' disappeared from the source repository between listing and " + + "fetching it.", 500)); + Path staged = stageStreamedAsset(streamed); + stagedFiles.add(staged); + contentByAsset.put(assetName, staged); + } + verifiedContentByVersion.put(version, contentByAsset); } - verifiedContentByVersion.put(version, contentByAsset); - } - Map successes = new LinkedHashMap<>(); - for (String version : pendingCopies) { - List destAssetNames = destAssetNamesByVersion.getOrDefault(version, List.of()); - Map originalContent = new LinkedHashMap<>(); - for (String destAssetName : destAssetNames) { - manager.fetchPackageVersionAsset(destRepoId, domain, destinationRepository, namespace, packageName, - version, destAssetName) - .ifPresent(content -> originalContent.put(destAssetName, content)); - } - List touchedAssetNames = new ArrayList<>(); - // Snapshotted immediately before this version's own writes, the same way every other - // container-backed write path already takes its fence snapshot right before issuing - // the real write it will later report: recording this version's bytes must still - // reflect the latest live state even if an earlier version in this same batch call - // already changed it (there is no shared snapshot spanning the whole batch to go - // stale as later versions are processed). - long packageFenceSnapshot = currentContainerBackedPackageFence(region, domain, owner, - destinationRepository, format, namespace, packageName); - long bytesWritten = 0L; - try { - // Every asset this version already held at the destination is deleted first, in - // its own phase, before anything new is written: pypiserver's own delete call - // (confirmed live) removes every file sharing that exact package name and - // version, not just the one asset name passed to it, so deleting a same-named - // asset in the middle of a per-asset write loop would silently wipe a sibling - // asset (e.g. the wheel of a release also carrying an sdist) already rewritten - // earlier in that same loop. Clearing everything up front, before any of this - // version's new content exists to be collaterally wiped, is correct for every - // format: Reposilite/Verdaccio/BaGetter's own deletes are already scoped to - // exactly the asset (or, for npm/nuget, the single asset their formats ever hold - // per version) being removed, so doing them first changes nothing for them, and - // still satisfies Reposilite's own redeployment:false rejection of a plain PUT - // over differing existing content the same way the previous interleaved ordering - // did. + Map successes = new LinkedHashMap<>(); + for (String version : pendingCopies) { + List destAssetNames = destAssetNamesByVersion.getOrDefault(version, List.of()); + Map originalContent = new LinkedHashMap<>(); for (String destAssetName : destAssetNames) { - manager.deletePackageVersionAsset(destRepoId, domain, destinationRepository, namespace, - packageName, version, destAssetName); - touchedAssetNames.add(destAssetName); + manager.fetchPackageVersionAssetStreamed(destRepoId, domain, destinationRepository, namespace, + packageName, version, destAssetName) + .ifPresent(streamed -> { + Path staged = stageStreamedAsset(streamed); + stagedFiles.add(staged); + originalContent.put(destAssetName, staged); + }); } - for (Map.Entry entry : verifiedContentByVersion.get(version).entrySet()) { - String assetName = entry.getKey(); - manager.copyPackageVersionAsset(sourceRepoId, domain, sourceRepository, destRepoId, - destinationRepository, namespace, packageName, version, assetName, entry.getValue()); - if (!touchedAssetNames.contains(assetName)) { - touchedAssetNames.add(assetName); + List touchedAssetNames = new ArrayList<>(); + // Snapshotted immediately before this version's own writes, the same way every other + // container-backed write path already takes its fence snapshot right before issuing + // the real write it will later report: recording this version's bytes must still + // reflect the latest live state even if an earlier version in this same batch call + // already changed it (there is no shared snapshot spanning the whole batch to go + // stale as later versions are processed). + long packageFenceSnapshot = currentContainerBackedPackageFence(region, domain, owner, + destinationRepository, format, namespace, packageName); + long bytesWritten = 0L; + try { + // Every asset this version already held at the destination is deleted first, in + // its own phase, before anything new is written: pypiserver's own delete call + // (confirmed live) removes every file sharing that exact package name and + // version, not just the one asset name passed to it, so deleting a same-named + // asset in the middle of a per-asset write loop would silently wipe a sibling + // asset (e.g. the wheel of a release also carrying an sdist) already rewritten + // earlier in that same loop. Clearing everything up front, before any of this + // version's new content exists to be collaterally wiped, is correct for every + // format: Reposilite/Verdaccio/BaGetter's own deletes are already scoped to + // exactly the asset (or, for npm/nuget, the single asset their formats ever hold + // per version) being removed, so doing them first changes nothing for them, and + // still satisfies Reposilite's own redeployment:false rejection of a plain PUT + // over differing existing content the same way the previous interleaved ordering + // did. + for (String destAssetName : destAssetNames) { + manager.deletePackageVersionAsset(destRepoId, domain, destinationRepository, namespace, + packageName, version, destAssetName); + touchedAssetNames.add(destAssetName); } - bytesWritten += entry.getValue().length; + for (Map.Entry entry : verifiedContentByVersion.get(version).entrySet()) { + String assetName = entry.getKey(); + long contentLength = Files.size(entry.getValue()); + manager.copyPackageVersionAsset(sourceRepoId, domain, sourceRepository, destRepoId, + destinationRepository, namespace, packageName, version, assetName, entry.getValue(), + contentLength); + if (!touchedAssetNames.contains(assetName)) { + touchedAssetNames.add(assetName); + } + bytesWritten += contentLength; + } + manager.recordVersionAvailable(destRepoId, domain, destinationRepository, namespace, packageName, + version); + } catch (IOException e) { + rollbackContainerBackedVersionWrite(manager, destRepoId, domain, destinationRepository, + namespace, packageName, version, originalContent, touchedAssetNames); + throw new UncheckedIOException(e); + } catch (RuntimeException e) { + rollbackContainerBackedVersionWrite(manager, destRepoId, domain, destinationRepository, + namespace, packageName, version, originalContent, touchedAssetNames); + throw e; } - manager.recordVersionAvailable(destRepoId, domain, destinationRepository, namespace, packageName, + if (bytesWritten > 0) { + recordContainerBackedAssetBytes(region, domain, owner, destinationRepository, format, namespace, + packageName, bytesWritten, packageFenceSnapshot); + } + copyCapturedReadmeIfApplicable(region, domain, owner, sourceRepository, destinationRepository, + format, namespace, packageName, version); + copyMavenRetainedVersionOriginIfApplicable(region, domain, owner, sourceRepository, + destinationRepository, format, namespace, packageName, version); + // Drops any status override left over from whatever used to be at this destination + // coordinate (an Archived version this copy's allowOverwrite just replaced, most + // concretely): the response below reports Published, and a stale override would + // otherwise keep describing (and keep requireAssetDownloadable blocking downloads of) + // content that no longer matches what is now really there. A destination that + // never had an override is an inexpensive no-op (see that method's own javadoc). + clearContainerBackedStatusOverride(owner, region, domain, destinationRepository, format, namespace, + packageName, version); + String revision = synthesizeContainerBackedRevision(format, destRepoId, namespace, packageName, version); - } catch (RuntimeException e) { - rollbackContainerBackedVersionWrite(manager, destRepoId, domain, destinationRepository, namespace, - packageName, version, originalContent, touchedAssetNames); - throw e; + successes.put(version, new SuccessfulPackageVersionInfo(revision, "Published")); } - if (bytesWritten > 0) { - recordContainerBackedAssetBytes(region, domain, owner, destinationRepository, format, namespace, - packageName, bytesWritten, packageFenceSnapshot); + return new CopyPackageVersionsResult(successes, Map.of()); + } finally { + for (Path staged : stagedFiles) { + deleteStagedAssetBody(staged); } - copyCapturedReadmeIfApplicable(region, domain, owner, sourceRepository, destinationRepository, format, - namespace, packageName, version); - copyMavenRetainedVersionOriginIfApplicable(region, domain, owner, sourceRepository, - destinationRepository, format, namespace, packageName, version); - // Drops any status override left over from whatever used to be at this destination - // coordinate (an Archived version this copy's allowOverwrite just replaced, most - // concretely): the response below reports Published, and a stale override would - // otherwise keep describing (and keep requireAssetDownloadable blocking downloads of) - // content that no longer matches what is now really there. A destination that - // never had an override is an inexpensive no-op (see that method's own javadoc). - clearContainerBackedStatusOverride(owner, region, domain, destinationRepository, format, namespace, - packageName, version); - String revision = synthesizeContainerBackedRevision(format, destRepoId, namespace, packageName, version); - successes.put(version, new SuccessfulPackageVersionInfo(revision, "Published")); } - return new CopyPackageVersionsResult(successes, Map.of()); + } + + /** + * Stages an already-fetched streamed asset to a temp file via {@link #stageAssetBody}, closing + * the stream afterward regardless of outcome: {@link #stageAssetBody} itself never closes the + * body it is handed, since its other caller (a controller's own inbound request stream) owns + * that separately. + */ + private Path stageStreamedAsset(RepositorySidecarManager.StreamedAsset streamed) { + try { + return stageAssetBody(streamed.content()); + } finally { + StreamingResponses.closeQuietly(streamed.content()); + } } /** @@ -4393,18 +4622,18 @@ public class CodeArtifactService implements Resettable { */ private void rollbackContainerBackedVersionWrite(RepositorySidecarManager manager, String destRepoId, String domain, String destinationRepository, String namespace, String packageName, String version, - Map originalContent, List touchedAssetNames) { + Map originalContent, List touchedAssetNames) { for (String assetName : touchedAssetNames) { try { - byte[] original = originalContent.get(assetName); + Path original = originalContent.get(assetName); if (original != null) { manager.storePackageVersionAsset(destRepoId, domain, destinationRepository, namespace, - packageName, version, assetName, original); + packageName, version, assetName, original, Files.size(original)); } else { manager.deletePackageVersionAsset(destRepoId, domain, destinationRepository, namespace, packageName, version, assetName); } - } catch (RuntimeException rollbackFailure) { + } catch (IOException | RuntimeException rollbackFailure) { LOG.warnv(rollbackFailure, "Best-effort rollback could not restore {0}/{1} package ''{2}'' " + "version ''{3}'' asset ''{4}'' after a failed copy; the destination may still be " + "left in a partially-copied state for this version.", domain, destinationRepository, @@ -4417,7 +4646,9 @@ public class CodeArtifactService implements Resettable { * {@code true} only when {@code source} and {@code dest} hold the exact same asset names for * this version, each fetching to byte-identical content: the container-backed equivalent of * {@link #packageVersionContentMatches}, which compares persisted hashes instead since generic - * assets have one and these don't. + * assets have one and these don't. Streams both sides against each other rather than fetching + * either as a resident {@code byte[]}, the same reason {@code ReposiliteSidecarClient + * #existingArtifactMatches}'s own {@code Path} overload does. */ private static boolean containerBackedVersionContentMatches(RepositorySidecarManager manager, String sourceRepoId, String sourceRepository, String destRepoId, String destinationRepository, @@ -4427,35 +4658,69 @@ public class CodeArtifactService implements Resettable { return false; } for (String assetName : sourceAssetNames) { - byte[] sourceContent = manager.fetchPackageVersionAsset(sourceRepoId, domain, sourceRepository, - namespace, packageName, version, assetName).orElse(null); - byte[] destContent = manager.fetchPackageVersionAsset(destRepoId, domain, destinationRepository, - namespace, packageName, version, assetName).orElse(null); - if (!Arrays.equals(sourceContent, destContent)) { + Optional source = manager.fetchPackageVersionAssetStreamed( + sourceRepoId, domain, sourceRepository, namespace, packageName, version, assetName); + Optional dest = manager.fetchPackageVersionAssetStreamed( + destRepoId, domain, destinationRepository, namespace, packageName, version, assetName); + if (source.isEmpty() != dest.isEmpty()) { + source.ifPresent(s -> StreamingResponses.closeQuietly(s.content())); + dest.ifPresent(d -> StreamingResponses.closeQuietly(d.content())); + return false; + } + if (source.isPresent() && !streamsEqual(source.get().content(), dest.get().content())) { return false; } } return true; } + /** Reads both streams in lockstep without ever holding either one's content whole, then closes both. */ + private static boolean streamsEqual(InputStream a, InputStream b) { + try (InputStream closeA = a; InputStream closeB = b) { + return StreamEquality.contentsMatch(closeA, closeB); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + /** - * Reads every one of {@code source}'s assets and confirms each one's actual bytes still hash - * to what its own persisted metadata claims, returning the verified bytes keyed by asset name. - * Guards against two distinct ways {@link #readAssetContent} can otherwise hand back the - * wrong bytes silently: a missing in-memory entry, which it answers with an empty array - * rather than an error, and disk corruption independent of Floci, which it never checks at - * all. Thrown as {@code InternalServerException} rather than folded into a per-version - * {@code CopyPackageVersionsResult} failure: this is this emulator's own storage integrity - * failing, not a caller-facing outcome any AWS-documented error code for this action - * describes. + * Stages every one of {@code source}'s assets to its own temp file and confirms each one's + * actual bytes still hash to what its own persisted metadata claims, returning the verified + * content keyed by asset name. Guards against two distinct ways {@link #readAssetContent} + * could otherwise hand back the wrong bytes silently: a missing in-memory entry, which it + * answers with an empty array rather than an error, and disk corruption independent of Floci, + * which it never checks at all. Thrown as {@code InternalServerException} rather than folded + * into a per-version {@code CopyPackageVersionsResult} failure: this is this emulator's own + * storage integrity failing, not a caller-facing outcome any AWS-documented error code for + * this action describes. + * + *

Each asset is staged via {@link #openAssetContent} wrapped in an {@link + * AssetDigestingInputStream} rather than read whole with {@link #readAssetContent}: a source + * asset can be up to the real 5 GB CodeArtifact quota, far past what a {@code byte[]} can ever + * hold (~2 GiB), and this digests it in the same single streaming pass that stages it, rather + * than a separate full-array hash afterward. Every staged file, verified or not, is appended + * to {@code stagedFiles} so the caller's own batch-wide cleanup deletes it exactly once, + * including a file staged for an asset that then fails its own hash check. */ - private Map verifyAndReadSourceAssets(String owner, CodeArtifactPackageVersion source) { + private Map verifyAndReadSourceAssets(String owner, CodeArtifactPackageVersion source, + List stagedFiles) { String sourceKey = packageVersionKey(source.getRegion(), source.getDomainName(), source.getRepositoryName(), source.getFormat(), source.getNamespace(), source.getPackageName(), source.getVersion()); - Map verified = new LinkedHashMap<>(); + Map verified = new LinkedHashMap<>(); for (PackageAsset sourceAsset : source.getAssets().values()) { - byte[] content = readAssetContent(owner, sourceKey, sourceAsset.getName()); - String actualSha256 = computeHashes(content).get("SHA-256"); + AssetDigestingInputStream digesting = new AssetDigestingInputStream( + openAssetContent(owner, sourceKey, sourceAsset.getName()), MAX_ASSET_FILE_SIZE_BYTES); + Path staged; + try { + staged = stageAssetBody(digesting); + } finally { + // stageAssetBody itself never closes the body it is handed (see + // stageStreamedAsset's own javadoc); openAssetContent's disk-mode source is a real + // file handle, so without this it leaks one descriptor per asset copied. + StreamingResponses.closeQuietly(digesting); + } + stagedFiles.add(staged); + String actualSha256 = digesting.hashesHex().get("SHA-256"); String expectedSha256 = sourceAsset.getHashes().get("SHA-256"); if (expectedSha256 == null || !expectedSha256.equalsIgnoreCase(actualSha256)) { throw new AwsException("InternalServerException", "Could not copy version '" + source.getVersion() @@ -4463,7 +4728,7 @@ public class CodeArtifactService implements Resettable { + "' is missing from the source repository's storage or no longer matches its recorded " + "hash.", 500); } - verified.put(sourceAsset.getName(), content); + verified.put(sourceAsset.getName(), staged); } return verified; } @@ -4517,7 +4782,7 @@ public class CodeArtifactService implements Resettable { */ private CodeArtifactPackageVersion copyGenericPackageVersionAssets(String owner, String region, String domain, String destinationRepository, String format, String namespace, String packageName, String version, - CodeArtifactPackageVersion source, Map verifiedContent) { + CodeArtifactPackageVersion source, Map verifiedContent) { String destKey = packageVersionKey(region, domain, destinationRepository, format, namespace, packageName, version); CodeArtifactPackageVersion existingDest = packageVersions.getForAccount(owner, destKey).orElse(null); @@ -5407,11 +5672,7 @@ public class CodeArtifactService implements Resettable { Path tmp = filePath.resolveSibling(filePath.getFileName() + ".tmp-" + UUID.randomUUID()); try { Files.write(tmp, content); - try { - Files.move(tmp, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - } catch (AtomicMoveNotSupportedException e) { - Files.move(tmp, filePath, StandardCopyOption.REPLACE_EXISTING); - } + moveIntoPlace(tmp, filePath); } finally { Files.deleteIfExists(tmp); } @@ -5420,6 +5681,106 @@ public class CodeArtifactService implements Resettable { } } + /** + * {@link #writeAssetContent(String, String, String, byte[])}'s own streamed sibling: {@code + * stagedContent} already holds the asset's full bytes on disk (written by {@link + * #stageAssetBody}), so the disk-mode path is a plain atomic move into place rather than a + * second full write, the one real saving streaming a large upload is for, versus buffering + * it into a {@code byte[]} first and writing that out the way the method above still does for + * small, already-resident content. {@code inMemory} test mode has no file to move, so it reads + * the (necessarily small, test-fixture-sized) staged file back into a {@code byte[]} and + * reuses the exact same map-based store the byte[] overload does. + */ + private void writeAssetContent(String owner, String packageVersionKey, String assetName, Path stagedContent) { + if (inMemory) { + try { + writeAssetContent(owner, packageVersionKey, assetName, Files.readAllBytes(stagedContent)); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read staged CodeArtifact asset body: " + + stagedContent, e); + } + return; + } + Path filePath = resolveAssetPath(owner, packageVersionKey, assetName); + try { + Files.createDirectories(filePath.getParent()); + moveIntoPlace(stagedContent, filePath); + } catch (IOException e) { + throw new UncheckedIOException("Failed to write CodeArtifact asset file: " + filePath, e); + } + } + + private static void moveIntoPlace(Path source, Path destination) throws IOException { + try { + Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING); + } + } + + /** + * Writes a streamed asset upload to a new file under a staging directory and returns it, the + * CodeArtifact sibling of {@code S3Service#stageBody}: an upload larger than a {@code byte[]} + * can ever hold (~2 GiB) needs somewhere real to land before anything else: hashing, + * forwarding to a sidecar, an idempotency compare, can all happen against it. The caller owns + * deleting the returned file exactly once, on every exit path (written into place, discarded + * as an idempotent no-op, rejected for being too large, or failed outright); it is never + * deleted automatically just by virtue of being staged. + */ + Path stageAssetBody(InputStream body) { + Path staged; + try { + if (inMemory) { + // inMemory test mode constructs this service with no real asset directory on + // disk at all (nothing backs the asset store itself in that mode): the JVM's own + // default temp directory is the only place to stage a streamed body, and it is + // never moved into assetRoot in this mode anyway, just read back into a byte[] + // for the in-memory map (see writeAssetContent(..., Path)). + staged = Files.createTempFile("codeartifact-asset-", ".incoming"); + } else { + // Staged under assetRoot itself, not the JVM's default temp directory: the real + // write path below (writeAssetContent(..., Path) -> moveIntoPlace) needs source + // and destination on the same filesystem for its ATOMIC_MOVE to actually be + // atomic, rather than silently falling back to a copy+delete the moment assetRoot + // happens to sit on a different mount than the default temp directory, which + // would double the disk I/O for every large asset this streams. + Path incoming = assetRoot.resolve(".incoming"); + Files.createDirectories(incoming); + staged = Files.createTempFile(incoming, "codeartifact-asset-", ".incoming"); + } + } catch (IOException e) { + throw new UncheckedIOException("Failed to create a staging file for a CodeArtifact asset upload", e); + } + try { + Files.copy(body, staged, StandardCopyOption.REPLACE_EXISTING); + return staged; + } catch (IOException e) { + deleteQuietlyStaged(staged); + throw new UncheckedIOException("Failed to stage a CodeArtifact asset upload", e); + } catch (RuntimeException e) { + deleteQuietlyStaged(staged); + throw e; + } + } + + private void deleteQuietlyStaged(Path staged) { + deleteStagedAssetBody(staged); + } + + /** + * Every controller that calls {@link #stageAssetBody} owns deleting the file it gets back + * exactly once, on every exit path. This is the one place that deletion happens, so a + * controller's own {@code finally} block never needs to hand-roll the same + * log-and-swallow-{@code IOException} logic four times over. + */ + void deleteStagedAssetBody(Path staged) { + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete a staged CodeArtifact asset upload at {0}", staged); + } + } + private byte[] readAssetContent(String owner, String packageVersionKey, String assetName) { if (inMemory) { byte[] content = memoryAssetStore.get(assetStoreKey(owner, packageVersionKey, assetName)); @@ -5433,6 +5794,20 @@ public class CodeArtifactService implements Resettable { } } + /** {@link #readAssetContent}'s streamed sibling, for an asset too large to hold as one {@code byte[]}. */ + private InputStream openAssetContent(String owner, String packageVersionKey, String assetName) { + if (inMemory) { + byte[] content = memoryAssetStore.get(assetStoreKey(owner, packageVersionKey, assetName)); + return new ByteArrayInputStream(content != null ? content : new byte[0]); + } + Path filePath = resolveAssetPath(owner, packageVersionKey, assetName); + try { + return Files.newInputStream(filePath); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read CodeArtifact asset file: " + filePath, e); + } + } + private static String assetStoreKey(String owner, String packageVersionKey, String assetName) { return owner + "::" + packageVersionKey + "::" + assetName; } diff --git a/src/main/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClient.java b/src/main/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClient.java index 7ef640645d..77bca5a3b9 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClient.java @@ -1,16 +1,20 @@ package io.floci.aws.services.codeartifact; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.Optional; @@ -82,7 +86,75 @@ public class MavenExternalConnectionClient { * public repository {@code externalConnectionName} names. */ public Optional fetchAsset(String externalConnectionName, String gav) { - return send(externalConnectionName, gav, "GET").map(response -> new FetchedAsset(response.body())); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + boolean fetched = fetchAsset(externalConnectionName, gav, in -> in.transferTo(buffer)); + return fetched ? Optional.of(new FetchedAsset(buffer.toByteArray())) : Optional.empty(); + } + + /** One asset's real size, fetched straight to {@code destination} without ever being held whole in memory. */ + public record FetchedFile(long size) {} + + /** + * {@link #fetchAsset(String, String)}'s own streamed sibling, for a release asset too large to + * ever hold as one {@code byte[]} (~2 GiB, the JVM array limit): the confirmed-live response + * streamed straight to {@code destination} instead of into a resident array. Capped at {@code + * CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the copy itself, via {@link + * AssetDigestingInputStream}, rather than downloaded in full and checked only afterward: the + * real public repository's own file size is otherwise unbounded, so without this an oversized + * one would still be fully pulled across the network and written to local disk before ever + * being rejected. + */ + public Optional fetchAsset(String externalConnectionName, String gav, Path destination) { + long[] size = new long[1]; + boolean fetched = fetchAsset(externalConnectionName, gav, + in -> size[0] = AssetDigestingInputStream.copyCapped(in, destination, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES)); + return fetched ? Optional.of(new FetchedFile(size[0])) : Optional.empty(); + } + + private interface BodyConsumer { + void accept(InputStream body) throws IOException; + } + + /** The one real fetch both {@link #fetchAsset(String, String)} and {@link #fetchAsset(String, + * String, Path)} share, as well as the small {@code maven-metadata.xml} fetch. Uses the + * worst-case download timeout: a release asset fetched here can be up to 5 GB, and its real + * size isn't known until the response itself arrives, so a flat 20 seconds would cancel a + * legitimately large, still-in-progress download (harmless for the small metadata fetch, + * which never takes anywhere near this long anyway). + */ + private boolean fetchAsset(String externalConnectionName, String gav, BodyConsumer consumer) { + String baseUrl = baseUrls.get(externalConnectionName); + if (baseUrl == null) { + return false; + } + HttpResponse response; + try { + HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, gav)) + .timeout(SidecarUriUtils.maxTransferTimeout()) + .GET() + .build(); + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException e) { + LOG.warnv("Could not fetch {0} from external connection {1}: {2}", gav, externalConnectionName, + e.getMessage()); + return false; + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return false; + } + try (InputStream body = response.body()) { + consumer.accept(body); + return true; + } catch (IOException e) { + LOG.warnv("Could not read {0} from external connection {1}: {2}", gav, externalConnectionName, + e.getMessage()); + return false; + } } /** Whether {@code gav} exists in the real public repository, without downloading it. */ @@ -107,28 +179,6 @@ public class MavenExternalConnectionClient { } } - private Optional> send(String externalConnectionName, String gav, String method) { - String baseUrl = baseUrls.get(externalConnectionName); - if (baseUrl == null) { - return Optional.empty(); - } - try { - HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, gav)) - .timeout(Duration.ofSeconds(20)) - .method(method, HttpRequest.BodyPublishers.noBody()) - .build(); - HttpResponse response = httpClient.send(request, BodyHandlers.ofByteArray()); - return response.statusCode() == 200 ? Optional.of(response) : Optional.empty(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return Optional.empty(); - } catch (IOException e) { - LOG.warnv("Could not fetch {0} from external connection {1}: {2}", gav, externalConnectionName, - e.getMessage()); - return Optional.empty(); - } - } - /** * {@code gav} is an untrusted asset path (ultimately a caller-supplied wire-protocol segment), * and {@code baseUrl} can itself carry a path prefix (the CommonsWare connection's own host is diff --git a/src/main/java/io/floci/aws/services/codeartifact/MultipartFilePublisher.java b/src/main/java/io/floci/aws/services/codeartifact/MultipartFilePublisher.java new file mode 100644 index 0000000000..54aa661b6a --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/MultipartFilePublisher.java @@ -0,0 +1,29 @@ +package io.floci.aws.services.codeartifact; + +import java.io.FileNotFoundException; +import java.io.UncheckedIOException; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.nio.file.Path; + +/** + * The one request-body shape BaGetter's and pypiserver's own streamed {@code + * storePackageVersionAsset} overloads share: a multipart body whose file part streams straight + * from disk via {@code BodyPublishers.concat} rather than being copied into one combined array, + * sandwiched between caller-built {@code head}/{@code tail} byte fragments specific to each + * protocol's own field layout. + */ +final class MultipartFilePublisher { + + private MultipartFilePublisher() { + } + + static HttpRequest.BodyPublisher concat(byte[] head, Path content, byte[] tail) { + try { + return BodyPublishers.concat(BodyPublishers.ofByteArray(head), BodyPublishers.ofFile(content), + BodyPublishers.ofByteArray(tail)); + } catch (FileNotFoundException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClient.java b/src/main/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClient.java index 3493272d41..df9850a7c0 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClient.java @@ -1,15 +1,19 @@ package io.floci.aws.services.codeartifact; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.Optional; @@ -114,33 +118,96 @@ public class NpmExternalConnectionClient { /** Fetches {@code namespace}/{@code packageName}/{@code version}'s one real tarball. */ public Optional fetchTarball(String externalConnectionName, String namespace, String packageName, String version) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + boolean fetched = fetchTarball(externalConnectionName, namespace, packageName, version, + in -> in.transferTo(buffer)); + return fetched ? Optional.of(new FetchedAsset(buffer.toByteArray())) : Optional.empty(); + } + + /** One real tarball's size, fetched straight to {@code destination} without ever being held + * whole in memory. */ + public record FetchedFile(long size) {} + + /** + * {@link #fetchTarball(String, String, String, String)}'s own streamed sibling, for a + * tarball too large to ever hold as one {@code byte[]} (~2 GiB, the JVM array limit): the + * confirmed-live response streamed straight to {@code destination} instead of into a + * resident array. Capped at {@code CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the + * copy itself, via {@link AssetDigestingInputStream}, rather than downloaded in full and + * checked only afterward: the real registry's own tarball size is otherwise unbounded, so + * without this an oversized one would still be fully pulled across the network and written to + * local disk before ever being rejected. + */ + public Optional fetchTarball(String externalConnectionName, String namespace, String packageName, + String version, Path destination) { + long[] size = new long[1]; + boolean fetched = fetchTarball(externalConnectionName, namespace, packageName, version, + in -> size[0] = AssetDigestingInputStream.copyCapped(in, destination, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES)); + return fetched ? Optional.of(new FetchedFile(size[0])) : Optional.empty(); + } + + private interface BodyConsumer { + void accept(InputStream body) throws IOException; + } + + private boolean fetchTarball(String externalConnectionName, String namespace, String packageName, + String version, BodyConsumer consumer) { String baseUrl = baseUrls.get(externalConnectionName); if (baseUrl == null) { - return Optional.empty(); + return false; } URI uri = SidecarUriUtils.combine(URI.create(baseUrl), tarballPath(namespace, packageName, version)); - return send(uri, "*/*", namespace, packageName); + return sendToConsumer(uri, "*/*", namespace, packageName, consumer); } private Optional send(URI uri, String accept, String namespace, String packageName) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + boolean fetched = sendToConsumer(uri, accept, namespace, packageName, in -> in.transferTo(buffer)); + return fetched ? Optional.of(new FetchedAsset(buffer.toByteArray())) : Optional.empty(); + } + + /** The one real fetch every public method here shares: every redirect/host decision npm's + * fixed, single-base-URL registry needs none of, but the digest-once/stream-once discipline + * still matters for {@link #fetchTarball(String, String, String, String, Path)}. Also shares + * the worst-case download timeout with the small packument fetches that go through this same + * method: the real tarball this can fetch is up to 5 GB, and its real size isn't known until + * the response itself arrives, so a flat, small timeout sized for metadata alone would cancel + * a legitimately large, still-in-progress download. + */ + private boolean sendToConsumer(URI uri, String accept, String namespace, String packageName, + BodyConsumer consumer) { + HttpResponse response; try { HttpRequest request = HttpRequest.newBuilder(uri) - .timeout(Duration.ofSeconds(20)) + .timeout(SidecarUriUtils.maxTransferTimeout()) .header("Accept", accept) .GET() .build(); - HttpResponse response = httpClient.send(request, BodyHandlers.ofByteArray()); - return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty(); + response = httpClient.send(request, BodyHandlers.ofInputStream()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return Optional.empty(); + return false; } catch (IOException e) { LOG.warnv("Could not fetch {0} {1} from the public npm registry: {2}", namespace, packageName, e.getMessage()); - return Optional.empty(); + return false; + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return false; + } + try (InputStream body = response.body()) { + consumer.accept(body); + return true; + } catch (IOException e) { + LOG.warnv("Could not read {0} {1} from the public npm registry: {2}", namespace, packageName, + e.getMessage()); + return false; } } + /** * The real registry's single-package resource path: a bare, percent-encoded package name, or * for a scoped package, {@code @%2F} as one opaque segment with the diff --git a/src/main/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClient.java b/src/main/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClient.java index 16efcd7caa..b18af9ac8e 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClient.java @@ -1,16 +1,20 @@ package io.floci.aws.services.codeartifact; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.file.Path; import java.time.Duration; import java.util.Locale; import java.util.Map; @@ -64,9 +68,81 @@ public class NuGetExternalConnectionClient { * the real public repository {@code externalConnectionName} names. */ public Optional fetchPackage(String externalConnectionName, String packageId, String version) { - return send(externalConnectionName, packageId, version, "GET").map(r -> new FetchedAsset(r.body())); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + boolean fetched = fetchPackage(externalConnectionName, packageId, version, in -> in.transferTo(buffer)); + return fetched ? Optional.of(new FetchedAsset(buffer.toByteArray())) : Optional.empty(); } + /** One package version's real {@code .nupkg} size, fetched straight to {@code destination} + * without ever being held whole in memory. */ + public record FetchedFile(long size) {} + + /** + * {@link #fetchPackage(String, String, String)}'s own streamed sibling, for a package too + * large to ever hold as one {@code byte[]} (~2 GiB, the JVM array limit): the confirmed-live + * response streamed straight to {@code destination} instead of into a resident array. Capped + * at {@code CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the copy itself, via {@link + * AssetDigestingInputStream}, rather than downloaded in full and checked only afterward: the + * real registry's own {@code .nupkg} size is otherwise unbounded, so without this an + * oversized one would still be fully pulled across the network and written to local disk + * before ever being rejected. + */ + public Optional fetchPackage(String externalConnectionName, String packageId, String version, + Path destination) { + long[] size = new long[1]; + boolean fetched = fetchPackage(externalConnectionName, packageId, version, + in -> size[0] = AssetDigestingInputStream.copyCapped(in, destination, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES)); + return fetched ? Optional.of(new FetchedFile(size[0])) : Optional.empty(); + } + + private interface BodyConsumer { + void accept(InputStream body) throws IOException; + } + + /** + * The one real fetch both {@link #fetchPackage(String, String, String)} and {@link + * #fetchPackage(String, String, String, Path)} share. Uses the worst-case download timeout: + * the real {@code .nupkg} this fetches can be up to 5 GB, and its real size isn't known until + * the response itself arrives, so a flat 20 seconds would cancel a legitimately large, + * still-in-progress download. + */ + private boolean fetchPackage(String externalConnectionName, String packageId, String version, + BodyConsumer consumer) { + String baseUrl = baseUrls.get(externalConnectionName); + if (baseUrl == null) { + return false; + } + HttpResponse response; + try { + HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, packageId, version)) + .timeout(SidecarUriUtils.maxTransferTimeout()) + .GET() + .build(); + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException e) { + LOG.warnv("Could not fetch {0} {1} from external connection {2}: {3}", packageId, version, + externalConnectionName, e.getMessage()); + return false; + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return false; + } + try (InputStream body = response.body()) { + consumer.accept(body); + return true; + } catch (IOException e) { + LOG.warnv("Could not read {0} {1} from external connection {2}: {3}", packageId, version, + externalConnectionName, e.getMessage()); + return false; + } + } + + /** Whether {@code packageId}/{@code version} exists in the real public repository, without * downloading it. */ public boolean exists(String externalConnectionName, String packageId, String version) { @@ -90,29 +166,6 @@ public class NuGetExternalConnectionClient { } } - private Optional> send(String externalConnectionName, String packageId, String version, - String method) { - String baseUrl = baseUrls.get(externalConnectionName); - if (baseUrl == null) { - return Optional.empty(); - } - try { - HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, packageId, version)) - .timeout(Duration.ofSeconds(20)) - .method(method, HttpRequest.BodyPublishers.noBody()) - .build(); - HttpResponse response = httpClient.send(request, BodyHandlers.ofByteArray()); - return response.statusCode() == 200 ? Optional.of(response) : Optional.empty(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return Optional.empty(); - } catch (IOException e) { - LOG.warnv("Could not fetch {0} {1} from external connection {2}: {3}", packageId, version, - externalConnectionName, e.getMessage()); - return Optional.empty(); - } - } - /** * The real NuGet V3 flat-container path for one package version's {@code .nupkg}: {@code * //..nupkg}, confirmed against the same diff --git a/src/main/java/io/floci/aws/services/codeartifact/NuspecXml.java b/src/main/java/io/floci/aws/services/codeartifact/NuspecXml.java index 9cc92b00dd..207d746356 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/NuspecXml.java +++ b/src/main/java/io/floci/aws/services/codeartifact/NuspecXml.java @@ -8,8 +8,11 @@ import org.w3c.dom.NodeList; 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.util.Locale; import java.util.Optional; import java.util.zip.ZipEntry; @@ -77,7 +80,24 @@ final class NuspecXml { * crafted upload could otherwise plant inside a subdirectory. */ static Metadata extractFromNupkg(byte[] nupkgBytes) { - try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(nupkgBytes))) { + return extractFromNupkg(new ByteArrayInputStream(nupkgBytes)); + } + + /** + * {@code extractFromNupkg(byte[])}'s own streamed sibling, for an upload too large to ever + * hold as one array: {@link ZipInputStream} reads entries sequentially, the same way for a + * file as for a resident array, so this never needed random/seekable access to begin with. + */ + static Metadata extractFromNupkg(Path nupkgFile) { + try (InputStream in = Files.newInputStream(nupkgFile)) { + return extractFromNupkg(in); + } catch (IOException e) { + throw new UncheckedIOException("Could not read the uploaded package as a .nupkg archive.", e); + } + } + + private static Metadata extractFromNupkg(InputStream nupkgStream) { + try (ZipInputStream zip = new ZipInputStream(nupkgStream)) { ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { String name = entry.getName(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java b/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java index 598c7c078e..51c8d3a2ad 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClient.java @@ -1,15 +1,19 @@ package io.floci.aws.services.codeartifact; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.Optional; @@ -172,56 +176,116 @@ public class PypiExternalConnectionClient { * whatever host the response names before this method ever gets a chance to check it. */ public Optional fetchFile(String externalConnectionName, String fileUrl) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + boolean fetched = fetchFile(externalConnectionName, fileUrl, in -> in.transferTo(buffer)); + return fetched ? Optional.of(new FetchedAsset(buffer.toByteArray())) : Optional.empty(); + } + + /** One real file's size, fetched straight to {@code destination} without ever being held whole in memory. */ + public record FetchedFile(long size) {} + + /** + * {@link #fetchFile(String, String)}'s own streamed sibling, for a file too large to ever + * hold as one {@code byte[]} (~2 GiB, the JVM array limit): the exact same host/redirect + * validation, with the confirmed-live final response streamed straight to {@code destination} + * instead of into a resident array. Capped at {@code + * CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the copy itself, via {@link + * AssetDigestingInputStream}, rather than downloaded in full and checked only afterward: the + * real registry's own file size is otherwise unbounded, so without this an oversized one + * would still be fully pulled across the network and written to local disk before ever being + * rejected. + */ + public Optional fetchFile(String externalConnectionName, String fileUrl, Path destination) { + long[] size = new long[1]; + boolean fetched = fetchFile(externalConnectionName, fileUrl, + in -> size[0] = AssetDigestingInputStream.copyCapped(in, destination, + CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES)); + return fetched ? Optional.of(new FetchedFile(size[0])) : Optional.empty(); + } + + private interface BodyConsumer { + void accept(InputStream body) throws IOException; + } + + /** + * The one real fetch loop both {@link #fetchFile(String, String)} and {@link #fetchFile(String, + * String, Path)} share: every redirect/host-trust decision lives here exactly once, so neither + * public overload can drift from the other on the part that actually matters for safety. + * {@code consumer} only ever runs once, against the confirmed-live, already-host-checked + * final {@code 200} response's own body, streamed rather than pre-buffered by {@link + * HttpResponse.BodyHandlers#ofInputStream()}: unlike {@code BodyHandlers.ofFile}, this never + * risks a redirect hop's own (discarded) body colliding with a destination file a later hop + * might still need to create fresh. Every hop's own request uses the worst-case download + * timeout, not a flat 30 seconds: the real file this can fetch is up to 5 GB, and its real + * size isn't known until the final, non-redirect response itself arrives, so a flat, small + * timeout would cancel a legitimately large, still-in-progress download on that last hop + * (the redirect hops ahead of it have no body worth waiting on anyway, so the longer timeout + * costs them nothing). + */ + private boolean fetchFile(String externalConnectionName, String fileUrl, BodyConsumer consumer) { String baseUrl = baseUrls.get(externalConnectionName); if (baseUrl == null) { - return Optional.empty(); + return false; } URI uri; try { uri = URI.create(fileUrl); } catch (IllegalArgumentException e) { - return Optional.empty(); + return false; } for (int hop = 0; hop <= MAX_FILE_REDIRECTS; hop++) { if (!isTrustedFileHost(externalConnectionName, baseUrl, uri)) { LOG.warnv("Refusing to fetch {0} for external connection {1}: its host is not a trusted file " + "host for that connection.", uri, externalConnectionName); - return Optional.empty(); + return false; } - HttpResponse response; + HttpResponse response; try { HttpRequest request = HttpRequest.newBuilder(uri) - .timeout(Duration.ofSeconds(30)) + .timeout(SidecarUriUtils.maxTransferTimeout()) .GET() .build(); - response = fileHttpClient.send(request, BodyHandlers.ofByteArray()); + response = fileHttpClient.send(request, BodyHandlers.ofInputStream()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return Optional.empty(); + return false; } catch (IOException e) { LOG.warnv("Could not fetch {0} from external connection {1}: {2}", uri, externalConnectionName, e.getMessage()); - return Optional.empty(); + return false; } if (isRedirect(response.statusCode())) { + StreamingResponses.closeQuietly(response.body()); String location = response.headers().firstValue("Location").orElse(null); if (location == null) { - return Optional.empty(); + return false; } try { uri = uri.resolve(location); } catch (IllegalArgumentException e) { - return Optional.empty(); + return false; } continue; } - return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty(); + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return false; + } + try (InputStream body = response.body()) { + consumer.accept(body); + return true; + } catch (IOException e) { + LOG.warnv("Could not read {0} from external connection {1}: {2}", uri, externalConnectionName, + e.getMessage()); + return false; + } } LOG.warnv("Too many redirects fetching {0} from external connection {1}; giving up.", fileUrl, externalConnectionName); - return Optional.empty(); + return false; } + private static boolean isRedirect(int statusCode) { return statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307 || statusCode == 308; diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java index 416e75c49c..f31a8a7087 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarClient.java @@ -2,9 +2,11 @@ package io.floci.aws.services.codeartifact; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; @@ -13,6 +15,7 @@ import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; @@ -123,6 +126,43 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { return Optional.of(response.body()); } + /** + * {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} + * for why. Uses the worst-case download timeout, not the byte[] overload's flat 10 seconds: + * this one asset download can be gigabytes, and its real size isn't known until the response + * itself arrives. + */ + @Override + public Optional fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain, + String repository, String namespace, String packageName, String version, String assetName) { + if (!filenameEmbedsVersion(assetName, packageName, version)) { + return Optional.empty(); + } + String baseUrl = ensureReady(repositoryContainerId, null); + if (!packageIndexListsAsset(baseUrl, packageName, assetName)) { + return Optional.empty(); + } + URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/packages/" + SidecarUriUtils.encodeSegment(assetName)); + HttpRequest request = HttpRequest.newBuilder(uri).timeout(SidecarUriUtils.maxTransferTimeout()).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the pypiserver sidecar to fetch " + assetName, e); + } + if (response.statusCode() == 404) { + StreamingResponses.closeQuietly(response.body()); + return Optional.empty(); + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + throw new IllegalStateException("Could not fetch " + assetName + " from the pypiserver sidecar: " + + "upstream returned " + response.statusCode()); + } + long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1); + return Optional.of(new StreamedAsset(response.body(), contentLength)); + } + /** * PEP 503 normalization: lowercase, runs of {@code -_.} collapsed to one {@code -}. Not * {@code private}: {@code CodeArtifactPypiController}'s own pre-upload index check and the @@ -364,7 +404,36 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { String namespace, String packageName, String version, String assetName, byte[] content) { String baseUrl = ensureReady(repositoryContainerId, null); String boundary = "flociPypiCopyBoundary" + System.nanoTime(); - byte[] head = ("--" + boundary + "\r\n" + byte[] head = multipartHead(boundary, packageName, version, assetName); + byte[] tail = multipartTail(boundary); + byte[] body = new byte[head.length + content.length + tail.length]; + System.arraycopy(head, 0, body, 0, head.length); + System.arraycopy(content, 0, body, head.length, content.length); + System.arraycopy(tail, 0, body, head.length + content.length, tail.length); + sendMultipartUpload(baseUrl, boundary, BodyPublishers.ofByteArray(body), assetName, body.length); + } + + /** + * {@link #storePackageVersionAsset(String, String, String, String, String, String, String, + * byte[])}'s own streamed sibling: the same multipart shape, but the file part streams + * straight from disk via {@code BodyPublishers.concat}, so the asset's own content is never + * copied into one combined array the way the {@code byte[]} overload above still does for + * content that is already resident. + */ + @Override + public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength) { + String baseUrl = ensureReady(repositoryContainerId, null); + String boundary = "flociPypiCopyBoundary" + System.nanoTime(); + byte[] head = multipartHead(boundary, packageName, version, assetName); + byte[] tail = multipartTail(boundary); + HttpRequest.BodyPublisher publisher = MultipartFilePublisher.concat(head, content, tail); + sendMultipartUpload(baseUrl, boundary, publisher, assetName, contentLength); + } + + private static byte[] multipartHead(String boundary, String packageName, String version, String assetName) { + return ("--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\":action\"\r\n\r\nfile_upload\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"name\"\r\n\r\n" + packageName + "\r\n" @@ -373,16 +442,18 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"content\"; filename=\"" + assetName + "\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8); - byte[] tail = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); - byte[] body = new byte[head.length + content.length + tail.length]; - System.arraycopy(head, 0, body, 0, head.length); - System.arraycopy(content, 0, body, head.length, content.length); - System.arraycopy(tail, 0, body, head.length + content.length, tail.length); + } + private static byte[] multipartTail(String boundary) { + return ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); + } + + private void sendMultipartUpload(String baseUrl, String boundary, HttpRequest.BodyPublisher publisher, + String assetName, long contentLength) { HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/")) - .timeout(Duration.ofSeconds(30)) + .timeout(SidecarUriUtils.transferTimeout(contentLength)) .header("Content-Type", "multipart/form-data; boundary=" + boundary) - .POST(BodyPublishers.ofByteArray(body)) + .POST(publisher) .build(); HttpResponse response; try { diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java index 3b5f0eedd1..0df1a90069 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java @@ -121,6 +121,12 @@ public class PypiserverSidecarManager implements ContainerTeardown { "-P", ".", "--disable-fallback", "--health-endpoint", HEALTH_PATH, + // pypiserver's own default server selection ("auto") lands on a + // single-threaded synchronous fallback that cannot reliably receive a + // real multi-GB publish body, discovered by hand-testing one end to end + // (the connection was dropped mid-upload); gevent is already present in + // the pinned image and handles a large body correctly. + "--server", "gevent", PACKAGES_DIR)) .build(); String containerId = lifecycleManager.create(spec); diff --git a/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java index a61b017cdc..5415d02982 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.core.common.XmlParser; import jakarta.enterprise.context.ApplicationScoped; @@ -13,6 +14,7 @@ import org.jboss.logging.Logger; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; @@ -21,6 +23,8 @@ import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; @@ -128,6 +132,32 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { @Override public Optional fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository, String namespace, String packageName, String version, String assetName) { + HttpRequest request = packageVersionAssetRequest(repositoryContainerId, namespace, packageName, version, + assetName); + HttpResponse response = send(request, BodyHandlers.ofByteArray()); + if (response.statusCode() != 200) { + return Optional.empty(); + } + return Optional.of(response.body()); + } + + /** {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} for why. */ + @Override + public Optional fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain, + String repository, String namespace, String packageName, String version, String assetName) { + HttpRequest request = packageVersionAssetRequest(repositoryContainerId, namespace, packageName, version, + assetName); + HttpResponse response = send(request, BodyHandlers.ofInputStream()); + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return Optional.empty(); + } + long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1); + return Optional.of(new StreamedAsset(response.body(), contentLength)); + } + + private HttpRequest packageVersionAssetRequest(String repositoryContainerId, String namespace, + String packageName, String version, String assetName) { ensureRepository(repositoryContainerId); String baseUrl = manager.ensureReady(); StringBuilder path = new StringBuilder("/").append(SidecarUriUtils.encodeSegment(repositoryContainerId)); @@ -137,16 +167,15 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { path.append('/').append(SidecarUriUtils.encodeSegment(packageName)) .append('/').append(SidecarUriUtils.encodeSegment(version)) .append('/').append(SidecarUriUtils.encodeSegment(assetName)); - HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path.toString())) - .timeout(Duration.ofSeconds(30)) + // Shared by both fetchPackageVersionAsset (byte[]) and fetchPackageVersionAssetStreamed: + // the asset this fetches can be gigabytes through either one, so a flat, small timeout + // sized for metadata-only requests would cancel a legitimately large, still-in-progress + // download, the same gap the write side once had on its own forwarding call. + return HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path.toString())) + .timeout(SidecarUriUtils.maxTransferTimeout()) .header("Authorization", manager.basicAuthHeader()) .GET() .build(); - HttpResponse response = send(request, BodyHandlers.ofByteArray()); - if (response.statusCode() != 200) { - return Optional.empty(); - } - return Optional.of(response.body()); } /** @@ -570,6 +599,39 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { } } + /** + * {@link #storePackageVersionAsset(String, String, String, String, String, String, String, + * byte[])}'s own streamed sibling: without this override, {@code CopyPackageVersions}' + * destination write for Maven would silently fall back to {@link RepositorySidecarManager}'s + * own default, which reads the whole staged file into a {@code byte[]} before delegating to + * the overload above, reinstating the ~2 GiB ceiling this class's own {@link #deployArtifact} + * override already streams around for a direct publish. The real content is sent via {@code + * BodyPublishers.ofFile}, the same way {@link #deployArtifact(String, String, Path)} already + * does for its own PUT. + */ + @Override + public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength) { + ensureRepository(repositoryContainerId); + String baseUrl = manager.ensureReady(); + String gav = versionGav(namespace, packageName, version, assetName); + HttpRequest request; + try { + request = authenticated(baseUrl, repositoryContainerId, gav) + .timeout(SidecarUriUtils.transferTimeout(contentLength)) + .PUT(BodyPublishers.ofFile(content)) + .build(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + int status = send(request, BodyHandlers.discarding()).statusCode(); + if (status != 200 && status != 201) { + throw new IllegalStateException("Could not copy " + packageName + " " + version + "'s asset " + + assetName + " to the Reposilite sidecar: upstream returned " + status); + } + } + /** * Deletes one already-published asset outright, confirmed working for an arbitrarily deep path * the same way {@link #deletePackage}'s own group/artifact-directory {@code DELETE} is already @@ -1187,6 +1249,37 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { return new DeployOutcome(status, status == 200 || status == 201); } + /** + * {@code content}'s own streamed sibling, for an artifact too large to ever hold as one {@code + * byte[]} (Maven's own direct {@code deploy}/retention paths stage a large upload to disk + * rather than buffering it): streams the file straight to Reposilite via {@code + * BodyPublishers.ofFile} instead of reading it into memory first, and the idempotent-match + * preflight below compares two streams in lockstep instead of one stream against a resident + * array. + */ + public DeployOutcome deployArtifact(String repoId, String gav, Path content) { + String baseUrl = manager.ensureReady(); + if (existingArtifactMatches(baseUrl, repoId, gav, content)) { + return new DeployOutcome(200, false); + } + HttpRequest request; + try { + // authenticated(...)'s own flat 30-second timeout is sized for the small metadata + // requests every other call site here sends; overridden here (a builder's timeout(...) + // can be set more than once, the last call winning) with one that scales with this + // artifact's own size, discovered by hand-testing a multi-GB deploy end to end: the flat + // 30 seconds was nowhere near enough once the artifact itself, not just its metadata, is + // what's being forwarded. + request = authenticated(baseUrl, repoId, gav) + .timeout(SidecarUriUtils.transferTimeout(Files.size(content))) + .PUT(BodyPublishers.ofFile(content)).build(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + int status = send(request, BodyHandlers.discarding()).statusCode(); + return new DeployOutcome(status, status == 200 || status == 201); + } + /** * {@code true} when {@code repoId}'s {@code gav} path already holds content identical to * {@code content}. Streams the existing artifact in fixed-size chunks rather than buffering it @@ -1230,11 +1323,68 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { } } + /** + * {@link #existingArtifactMatches(String, String, String, byte[])}'s own streamed sibling: + * compares the remote artifact against {@code content} chunk by chunk from each side rather + * than against one resident array, using {@code readNBytes} so a short individual {@code + * read()} on either side (always possible, never guaranteed to fill the buffer) can't be + * mistaken for the two streams genuinely disagreeing. + */ + private boolean existingArtifactMatches(String baseUrl, String repoId, String gav, Path content) { + HttpRequest request = authenticated(baseUrl, repoId, gav).GET().build(); + try { + HttpResponse response = httpClient.send(request, BodyHandlers.ofInputStream()); + if (response.statusCode() != 200) { + response.body().close(); + return false; + } + try (InputStream remote = response.body(); InputStream local = Files.newInputStream(content)) { + return StreamEquality.contentsMatch(remote, local); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException e) { + LOG.warnv(e, "Could not check {0}/{1} for an existing match before deploying: {2}", repoId, gav, + e.getMessage()); + return false; + } + } + /** Fetches {@code repoId}'s {@code gav} path, or {@link Optional#empty()} on a non-200 response. */ public Optional fetchArtifact(String repoId, String gav) { return fetchArtifact(manager.ensureReady(), repoId, gav); } + /** + * {@link #fetchArtifact(String, String)}'s streamed sibling, for the real wire-protocol GET + * route: that method's own {@code byte[]} is fine for its other callers (a + * {@code maven-metadata.xml} listing, never a large asset), but the real download route has + * to hand back whatever a published jar actually is, which can be gigabytes. The caller owns + * closing the returned stream. + * + *

{@code authenticated(...)}'s own flat 30-second timeout is sized for the small metadata + * requests every other call site here sends; overridden here with the worst-case download + * timeout, the read-side counterpart of {@code deployArtifact(Path)}'s own override: a GET + * can't size its own timeout off a real {@code contentLength} the way that PUT can off its + * already-known upload size, since the real size here isn't known until the response itself + * arrives. + */ + public Optional fetchArtifactStreamed(String repoId, String gav) { + String baseUrl = manager.ensureReady(); + HttpRequest request = authenticated(baseUrl, repoId, gav) + .timeout(SidecarUriUtils.maxTransferTimeout()) + .GET().build(); + HttpResponse response = send(request, BodyHandlers.ofInputStream()); + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + return Optional.empty(); + } + String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream"); + long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1); + return Optional.of(new StreamedArtifact(response.body(), contentLength, contentType)); + } + /** * {@link #recordVersionDisposed}'s own counterpart to {@link #fetchArtifact}: that method's * {@code empty()} is not safe to read as "confirmed absent" everywhere, since it also means @@ -1269,6 +1419,10 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { public record FetchedArtifact(byte[] content, String contentType) {} + /** {@code contentLength} is -1 when the sidecar's response carried no {@code Content-Length} header. */ + public record StreamedArtifact(InputStream content, long contentLength, String contentType) {} + + /** {@code true} if {@code repoId}'s {@code gav} path exists. */ public boolean artifactExists(String repoId, String gav) { String baseUrl = manager.ensureReady(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/RepositorySidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/RepositorySidecarManager.java index 96cc20f045..fd7d5e9113 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/RepositorySidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/RepositorySidecarManager.java @@ -1,7 +1,15 @@ package io.floci.aws.services.codeartifact; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Optional; /** @@ -59,6 +67,48 @@ public interface RepositorySidecarManager { Optional fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository, String namespace, String packageName, String version, String assetName); + /** + * {@link #fetchPackageVersionAsset}'s streamed sibling, for a caller that hands the content + * straight to an HTTP response instead of holding it in memory ({@code GetPackageVersionAsset}, + * {@code CopyPackageVersions}): the caller owns closing the returned stream. + * {@code contentLength} is -1 when it could not be determined up front. The default falls back + * to {@link #fetchPackageVersionAsset} and wraps the resulting array, so every implementation + * keeps working correctly without its own override, just without the size headroom a real + * streamed override provides; every sidecar that matters for this overrides it directly. + */ + default Optional fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain, + String repository, String namespace, String packageName, String version, String assetName) { + return fetchPackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName, version, + assetName).map(content -> new StreamedAsset(new ByteArrayInputStream(content), content.length)); + } + + /** {@code contentLength} is -1 when the sidecar's own response carried no known length. */ + record StreamedAsset(InputStream content, long contentLength) {} + + /** + * {@link #fetchPackageVersionAsset}'s digest-only sibling, for a caller that only needs an + * asset's size and hashes, never its content ({@code ListPackageVersionAssets}, byte-accounting + * on a disposed version's delete): streams through {@link #fetchPackageVersionAssetStreamed} + * and digests it without ever holding the whole thing in memory, correct for any size asset + * regardless of which sidecar implements the streamed fetch it builds on. + */ + default Optional fetchPackageVersionAssetDigest(String repositoryContainerId, String domain, + String repository, String namespace, String packageName, String version, String assetName) { + return fetchPackageVersionAssetStreamed(repositoryContainerId, domain, repository, namespace, packageName, + version, assetName).map(streamed -> { + try (InputStream in = streamed.content()) { + AssetDigestingInputStream digesting = new AssetDigestingInputStream(in, Long.MAX_VALUE); + digesting.transferTo(OutputStream.nullOutputStream()); + return new AssetDigest(digesting.size(), digesting.hashesHex()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + + /** One asset's size and every {@code ASSET_HASH_ALGORITHMS} hash, with no content attached. */ + record AssetDigest(long size, Map hashes) {} + /** * {@code true} when this sidecar holds at least one version of the named package. {@code namespace} * follows the same convention as {@link #fetchPackageVersionAsset}: {@code null} for a format that @@ -161,6 +211,27 @@ public interface RepositorySidecarManager { + "sidecar"); } + /** + * {@link #storePackageVersionAsset(String, String, String, String, String, String, String, + * byte[])}'s own streamed sibling, for an asset too large to ever hold as one {@code byte[]} + * (~2 GiB, the JVM array limit): an implementer whose own write naturally streams from a file + * (every one that matters for this, as of this javadoc) overrides this directly; the default + * here falls back to reading the whole file into memory and delegating to the {@code byte[]} + * overload, so an implementer that has not been given its own streamed override yet still + * works correctly for anything that fits in memory, just without the size headroom the + * streamed override exists for. + */ + default void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength) { + try { + storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName, version, + assetName, Files.readAllBytes(content)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + /** * {@code CopyPackageVersions}' own destination write, as opposed to a bare {@link * #storePackageVersionAsset} call with no notion of a source: the default simply forwards to @@ -180,6 +251,19 @@ public interface RepositorySidecarManager { assetName, content); } + /** + * {@link #copyPackageVersionAsset(String, String, String, String, String, String, String, + * String, String, byte[])}'s own streamed sibling, mirroring {@link + * #storePackageVersionAsset(String, String, String, String, String, String, String, Path, + * long)}'s own reason for existing. + */ + default void copyPackageVersionAsset(String sourceRepositoryContainerId, String domain, String sourceRepository, + String repositoryContainerId, String repository, String namespace, String packageName, String version, + String assetName, Path content, long contentLength) { + storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName, version, + assetName, content, contentLength); + } + /** * Deletes one already-confirmed-present named asset from this sidecar's own backing storage * for the given package version, used by {@code CopyPackageVersions}'s overwrite path to drop diff --git a/src/main/java/io/floci/aws/services/codeartifact/SidecarUriUtils.java b/src/main/java/io/floci/aws/services/codeartifact/SidecarUriUtils.java index 189186f75f..cbbd498295 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/SidecarUriUtils.java +++ b/src/main/java/io/floci/aws/services/codeartifact/SidecarUriUtils.java @@ -3,14 +3,16 @@ package io.floci.aws.services.codeartifact; import io.floci.aws.core.common.auth.SigV4Canonicalization; import java.net.URI; +import java.time.Duration; /** - * Shared URI-construction helpers for the Maven, npm, and pypi sidecar clients, each of which - * builds a request URI out of its own {@code baseUrl} plus one or more caller-supplied path - * segments (a repository id, package coordinates, an asset filename). Package-private: every + * Shared helpers for the Maven, npm, pypi, and NuGet sidecar clients: URI construction out of + * each one's own {@code baseUrl} plus one or more caller-supplied path segments (a repository + * id, package coordinates, an asset filename), and a request timeout sized for forwarding a + * large asset's real bytes rather than a small metadata-only request. Package-private: every * caller lives in this package, and {@link #combine} in particular requires its {@code * encodedPath} argument to already be fully percent-encoded, a precondition not worth exposing - * to unrelated callers outside the three clients that know to uphold it. + * to unrelated callers outside the four clients that know to uphold it. */ final class SidecarUriUtils { @@ -57,4 +59,38 @@ final class SidecarUriUtils { } return SigV4Canonicalization.uriEncode(segment); } + + /** A deliberately pessimistic floor: real transfers to a local sidecar container are far + * faster than this in practice, but the point of a floor is to be safe against a slow one, + * not to reflect a realistic average. */ + private static final long MIN_TRANSFER_BYTES_PER_SECOND = 10L * 1024 * 1024; + + /** + * A request timeout long enough to cover forwarding {@code contentLength} bytes to a sidecar + * container even at {@link #MIN_TRANSFER_BYTES_PER_SECOND}, plus a fixed 30-second grace + * period for the sidecar's own processing time, not just the wire transfer. Every sidecar + * client's own small, metadata-only request keeps its existing flat 30-second timeout + * unchanged; this is only for the one call per format that actually forwards an asset's real + * bytes, discovered by hand-testing a multi-GB upload end to end: a flat 30 seconds was never + * enough once an asset is sized in gigabytes rather than the kilobytes every existing test + * fixture uses, and every one of the four sidecar clients shared the exact same gap. + */ + static Duration transferTimeout(long contentLength) { + return Duration.ofSeconds(30 + contentLength / MIN_TRANSFER_BYTES_PER_SECOND); + } + + /** + * {@link #transferTimeout}'s own worst-case sibling, for a download whose real size isn't + * known until the response itself arrives: a GET can't size its own request timeout off a + * {@code contentLength} the way a PUT/POST already knows its own body's size upfront, so this + * uses {@code CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} itself as the worst case instead. + * Every real asset-fetching GET, both the four sidecar clients' own streamed reads and the + * four external-connection clients' real public-registry fetches, shares this same gap for the + * identical reason the write side once did: a flat, small timeout sized for a metadata-only + * request silently cancels a transfer still legitimately in progress once it is no longer a + * few kilobytes but up to 5 GB. + */ + static Duration maxTransferTimeout() { + return transferTimeout(CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES); + } } diff --git a/src/main/java/io/floci/aws/services/codeartifact/StreamEquality.java b/src/main/java/io/floci/aws/services/codeartifact/StreamEquality.java new file mode 100644 index 0000000000..037307012d --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/StreamEquality.java @@ -0,0 +1,38 @@ +package io.floci.aws.services.codeartifact; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +/** + * The lockstep, fixed-buffer byte comparison every content-match preflight across the four + * sidecar write paths shares (the generic copy path, NuGet's and pypi's own direct-publish + * preflights, and Maven's {@code ReposiliteSidecarClient}): read a chunk from each side with + * {@code readNBytes} so a short individual {@code read()} on either stream can never be mistaken + * for the two genuinely disagreeing, and stop as soon as either a length mismatch or a content + * mismatch is found. Neither stream is closed here: each caller already owns that in its own + * try-with-resources, since what counts as "done with" either stream differs by caller. + */ +final class StreamEquality { + + private StreamEquality() { + } + + static boolean contentsMatch(InputStream a, InputStream b) throws IOException { + byte[] bufferA = new byte[8192]; + byte[] bufferB = new byte[8192]; + while (true) { + int readA = a.readNBytes(bufferA, 0, bufferA.length); + int readB = b.readNBytes(bufferB, 0, bufferB.length); + if (readA != readB) { + return false; + } + if (readA == 0) { + return true; + } + if (!Arrays.equals(bufferA, 0, readA, bufferB, 0, readB)) { + return false; + } + } + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClient.java index 1c3d8edd92..3414cd2bfc 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClient.java @@ -3,29 +3,43 @@ package io.floci.aws.services.codeartifact; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.StreamingResponses; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.SequenceInputStream; +import java.io.UncheckedIOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Base64; +import java.util.HexFormat; import java.util.Iterator; import java.util.List; import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; /** * The HTTP wire protocol for a Verdaccio sidecar: package metadata, tarball fetches, and stored @@ -108,6 +122,18 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { return fetchTarball(baseUrl, namespace, packageName, assetName); } + /** {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} for why. */ + @Override + public Optional fetchPackageVersionAssetStreamed( + String repositoryContainerId, String domain, String repository, String namespace, String packageName, + String version, String assetName) { + String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository)); + if (!versionHasAsset(baseUrl, packagePath(namespace, packageName), version, assetName)) { + return Optional.empty(); + } + return fetchTarballStreamed(baseUrl, namespace, packageName, assetName); + } + /** * The package's metadata document as Verdaccio serves it, or empty when the package isn't there. * {@code baseUrl} is a backend already made ready by {@link #ensureReady}. @@ -287,6 +313,29 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { return Optional.of(response.body()); } + /** {@link #fetchTarball}'s streamed sibling. The caller owns closing the returned stream. */ + public Optional fetchTarballStreamed(String baseUrl, String namespace, + String packageName, String assetName) { + HttpRequest request = tarballRequest(baseUrl, namespace, packageName, assetName); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofInputStream()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the Verdaccio sidecar to fetch " + assetName, e); + } + if (response.statusCode() == 404) { + StreamingResponses.closeQuietly(response.body()); + return Optional.empty(); + } + if (response.statusCode() != 200) { + StreamingResponses.closeQuietly(response.body()); + throw new IllegalStateException("Could not fetch " + assetName + + " from the Verdaccio sidecar: upstream returned " + response.statusCode()); + } + long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1); + return Optional.of(new RepositorySidecarManager.StreamedAsset(response.body(), contentLength)); + } + /** * The SHA-512 integrity of a stored tarball, computed by streaming its bytes so the file never * sits in memory. Empty when the tarball is not there. @@ -308,7 +357,7 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { throw new IllegalStateException("Could not fetch " + assetName + " from the Verdaccio sidecar: upstream returned " + response.statusCode()); } - MessageDigest digest = sha512(); + MessageDigest digest = Digests.sha512Digest(); byte[] chunk = new byte[64 * 1024]; for (int read = body.read(chunk); read != -1; read = body.read(chunk)) { digest.update(chunk, 0, read); @@ -319,16 +368,24 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { } } + private static String packagePath(String namespace, String packageName) { return namespace == null ? SidecarUriUtils.encodeSegment(packageName) : "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName); } + /** + * Shared by {@link #fetchTarball}, {@link #fetchTarballStreamed}, and {@link + * #storedTarballIntegrity} — every one of the three reads the real tarball's own bytes in + * full (the last one to compute its digest, not just to hand them back), so a flat, small + * timeout sized for a metadata-only request would cancel a legitimately large, still-in- + * progress read through any of them. + */ private HttpRequest tarballRequest(String baseUrl, String namespace, String packageName, String assetName) { URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath(namespace, packageName) + "/-/" + SidecarUriUtils.encodeSegment(assetName)); - return HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build(); + return HttpRequest.newBuilder(uri).timeout(SidecarUriUtils.maxTransferTimeout()).GET().build(); } private Optional packageDocument(String baseUrl, String packagePath) { @@ -443,6 +500,20 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { null); } + /** + * {@link #storePackageVersionAsset(String, String, String, String, String, String, String, + * byte[])}'s own streamed sibling, for a tarball too large to ever hold as one {@code byte[]} + * (~2 GiB, the JVM array limit): see {@link #storeVersion(String, String, String, String, + * String, String, String, Path, long, JsonNode)} for how the write itself streams. + */ + @Override + public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength) { + storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content, + contentLength, null); + } + /** * Reuses {@code sourceRepositoryContainerId}'s own version entry verbatim (the exact document * its original publish wrote, including {@code dependencies}/{@code scripts}/{@code engines} @@ -467,6 +538,25 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { sourceVersionDoc); } + /** + * {@link #copyPackageVersionAsset(String, String, String, String, String, String, String, + * String, String, byte[])}'s own streamed sibling, mirroring {@link + * #storePackageVersionAsset(String, String, String, String, String, String, String, Path, + * long)}'s own reason for existing. + */ + @Override + public void copyPackageVersionAsset(String sourceRepositoryContainerId, String domain, String sourceRepository, + String repositoryContainerId, String repository, String namespace, String packageName, String version, + String assetName, Path content, long contentLength) { + String sourceBaseUrl = ensureReady(sourceRepositoryContainerId, publicUrl(domain, sourceRepository)); + JsonNode sourceVersionDoc = packageDocument(sourceBaseUrl, packagePath(namespace, packageName)) + .map(doc -> doc.path("versions").path(version)) + .filter(node -> !node.isMissingNode() && !node.isNull()) + .orElse(null); + storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content, + contentLength, sourceVersionDoc); + } + /** * {@code CodeArtifactNpmExternalConnectionImporter}'s own destination write for a version * retained through a {@code public:npmjs} external connection, the same reuse-the-source- @@ -489,6 +579,20 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { externalVersionDoc); } + /** + * {@link #storeRetainedVersionAsset(String, String, String, String, String, String, String, + * byte[], JsonNode)}'s own streamed sibling, mirroring {@link #storePackageVersionAsset(String, + * String, String, String, String, String, String, Path, long)}'s own reason for existing: the + * real public registry's own tarballs are exactly the ones most likely to actually exceed + * {@code byte[]}'s own ~2 GiB ceiling. + */ + public void storeRetainedVersionAsset(String repositoryContainerId, String domain, String repository, + String namespace, String packageName, String version, String assetName, Path content, + long contentLength, JsonNode externalVersionDoc) { + storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content, + contentLength, externalVersionDoc); + } + /** * The one real write every {@code storePackageVersionAsset}/{@code copyPackageVersionAsset}/ * {@code storeRetainedVersionAsset} call goes through. Sends no {@code dist-tags} of its own @@ -506,18 +610,8 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository)); String path = packagePath(namespace, packageName); String npmName = npmPackageName(namespace, packageName); - String tarballUrl = baseUrl + "/" + path + "/-/" + assetName; - - ObjectNode versionDoc = sourceVersionDoc != null ? sourceVersionDoc.deepCopy() : mapper.createObjectNode(); - versionDoc.put("name", npmName); - versionDoc.put("version", version); - if (!versionDoc.has("description")) { - versionDoc.put("description", ""); - } - ObjectNode dist = versionDoc.putObject("dist"); - dist.put("shasum", Digests.sha1Hex(content)); - dist.put("integrity", "sha512-" + Base64.getEncoder().encodeToString(sha512().digest(content))); - dist.put("tarball", tarballUrl); + ObjectNode versionDoc = versionDocument(sourceVersionDoc, npmName, version, baseUrl, path, assetName, + Digests.sha1Hex(content), Base64.getEncoder().encodeToString(Digests.sha512Digest().digest(content))); // No dist-tags sent: see this method's own javadoc for why. ObjectNode body = mapper.createObjectNode(); @@ -530,10 +624,236 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { attachment.put("data", Base64.getEncoder().encodeToString(content)); attachment.put("length", content.length); + byte[] bodyBytes = writeValue(body); + sendVersionDocument(baseUrl, path, npmName, version, BodyPublishers.ofByteArray(bodyBytes), bodyBytes.length); + } + + /** + * {@link #storeVersion(String, String, String, String, String, String, String, byte[], + * JsonNode)}'s own streamed sibling: unlike every other sidecar write in this package, a + * plain {@code BodyPublishers.concat} around the tarball's own bytes is not enough here, + * since the tarball is not a standalone part of a multipart body but one base64-encoded JSON + * string value embedded inside a larger document (Verdaccio's own publish protocol, confirmed + * live). {@link #dist} aside, {@code shasum}/{@code integrity} are computed from the file + * once, up front (a second full pass, since this class's own byte[]-based hashing has no + * reason to be reused across the unrelated digest set {@code AssetDigestingInputStream} + * already computed when this content was staged/fetched), and the JSON document itself is + * built as explicit prefix/suffix string fragments around a {@link #base64EncodingStream} + * instead of one fully-serialized string, so the base64 payload streams through rather than + * ever being held, encoded, whole in memory the way the {@code byte[]} overload's own {@code + * Base64.getEncoder().encodeToString(content)} call still is. + */ + private void storeVersion(String repositoryContainerId, String domain, String repository, String namespace, + String packageName, String version, String assetName, Path content, long contentLength, + JsonNode sourceVersionDoc) { + String sha1Hex; + String sha512Base64; + try (InputStream in = Files.newInputStream(content)) { + MessageDigest sha1 = Digests.sha1Digest(); + MessageDigest sha512 = Digests.sha512Digest(); + byte[] buffer = new byte[64 * 1024]; + int read; + while ((read = in.read(buffer)) != -1) { + sha1.update(buffer, 0, read); + sha512.update(buffer, 0, read); + } + sha1Hex = HexFormat.of().formatHex(sha1.digest()); + sha512Base64 = Base64.getEncoder().encodeToString(sha512.digest()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository)); + String path = packagePath(namespace, packageName); + String npmName = npmPackageName(namespace, packageName); + ObjectNode versionDoc = versionDocument(sourceVersionDoc, npmName, version, baseUrl, path, assetName, + sha1Hex, sha512Base64); + + // No dist-tags sent: see storeVersion's own byte[] overload's javadoc for why. + ObjectNode bodyWithoutAttachment = mapper.createObjectNode(); + bodyWithoutAttachment.put("_id", npmName); + bodyWithoutAttachment.put("name", npmName); + bodyWithoutAttachment.put("description", ""); + bodyWithoutAttachment.putObject("versions").set(version, versionDoc); + String prefix = jsonUpTo(bodyWithoutAttachment) + ",\"_attachments\":{" + + writeValueAsString(assetName) + ":{\"content_type\":\"application/octet-stream\",\"data\":\""; + String suffix = "\",\"length\":" + contentLength + "}}}"; + byte[] prefixBytes = prefix.getBytes(StandardCharsets.UTF_8); + byte[] suffixBytes = suffix.getBytes(StandardCharsets.UTF_8); + + // BodyPublishers.ofInputStream's supplier can be invoked more than once (the JDK may + // retry a request before any byte of the body is sent), each time needing a genuinely + // fresh stream, so base64EncodingStream(content) is called inside the lambda, not hoisted + // above it. Confirmed directly (a probe against a server that accepts a connection then + // drops it mid-body): the JDK HttpClient does NOT close a supplied InputStream when the + // send fails or is aborted, so without tracking every stream the supplier ever actually + // created and closing it in the finally below, base64EncodingStream's own virtual thread + // would stay blocked forever on a full pipe, leaking the thread and the open file handle + // it still holds, on every aborted/timed-out npm publish, not just a successful one. + List encodingStreams = new CopyOnWriteArrayList<>(); + HttpRequest.BodyPublisher publisher = BodyPublishers.ofInputStream(() -> { + InputStream encoding = base64EncodingStream(content); + encodingStreams.add(encoding); + return new SequenceInputStream(new SequenceInputStream(new ByteArrayInputStream(prefixBytes), encoding), + new ByteArrayInputStream(suffixBytes)); + }); + // Base64 expands the real asset bytes by 4/3 (rounded up to a multiple of 4): the timeout + // below is sized against what actually crosses the wire, not the smaller pre-encoding + // contentLength, the same distinction suffix's own "length" field above does not need to + // make (that one reports the real asset size, matching what AWS's own npm dist.tarball + // convention expects a consumer to see, regardless of how it was transported here). + long encodedContentLength = prefixBytes.length + ((contentLength + 2) / 3) * 4 + suffixBytes.length; + try { + sendVersionDocument(baseUrl, path, npmName, version, publisher, encodedContentLength); + } finally { + // A no-op for a stream the HTTP client already read to EOF and closed itself (closing + // an already-closed PipedInputStream is safe); the real purpose is unblocking the + // encoding thread of a stream the client gave up on early, the gap this fix exists for. + encodingStreams.forEach(StreamingResponses::closeQuietly); + } + } + + /** {@code versionDoc}'s own {@code dist} fields, shared by both {@code storeVersion} overloads. */ + private ObjectNode versionDocument(JsonNode sourceVersionDoc, String npmName, String version, String baseUrl, + String path, String assetName, String shasum, String integritySha512Base64) { + ObjectNode versionDoc = sourceVersionDoc != null ? sourceVersionDoc.deepCopy() : mapper.createObjectNode(); + versionDoc.put("name", npmName); + versionDoc.put("version", version); + if (!versionDoc.has("description")) { + versionDoc.put("description", ""); + } + ObjectNode dist = versionDoc.putObject("dist"); + dist.put("shasum", shasum); + dist.put("integrity", "sha512-" + integritySha512Base64); + dist.put("tarball", baseUrl + "/" + path + "/-/" + assetName); + return versionDoc; + } + + /** + * {@code body} serialized as JSON with its own closing {@code }} dropped, so the caller can + * append one more field (here, {@code _attachments}) before closing the object itself: {@code + * body} has no {@code _attachments} of its own yet, so this is always well-formed JSON up to + * that point, never a value cut off mid-way. + */ + private String jsonUpTo(ObjectNode body) { + String json = new String(writeValue(body), StandardCharsets.UTF_8); + return json.substring(0, json.length() - 1); + } + + private String writeValueAsString(String value) { + return new String(writeValue(new TextNode(value)), StandardCharsets.UTF_8); + } + + /** + * A dedicated virtual thread reads {@code content} and writes it through the JDK's own + * {@link Base64.Encoder#wrap(java.io.OutputStream)} into a pipe, so the caller gets back a + * plain {@link InputStream} of base64 characters without this class hand-rolling its own + * encoder: {@link Base64.Encoder#encodeToString} has no streaming counterpart of its own, and + * every byte this emits still has to cross an {@code OutputStream}-shaped boundary somewhere. + * + *

Raised by Qodo's review of this PR: a failure on the writing side (the staged file + * disappearing mid-read, for instance) does not surface as an {@code IOException} on + * the reading side merely by closing the pipe, the way an earlier version of this method's + * own javadoc claimed. Closing a {@link PipedOutputStream} is indistinguishable, from the + * read side, from the writer finishing normally: either way {@link PipedInputStream} just + * reports a clean EOF. Left as a bare close, a truncated read would send a well-formed but + * short base64 payload inside an otherwise valid publish document whose {@code shasum}/ + * {@code integrity}/{@code length} fields (computed from the whole file before this stream + * was ever opened) still describe the untruncated original — a silently corrupted publish + * that reports success. The writer now records its own failure in {@code writerFailure} + * before the {@code try}'s own resources close (a plain {@code finally}, not a + * second try-with-resources, so the ordering is guaranteed: {@link FailFastInputStream} + * would otherwise race a reader that observes the pipe's own EOF before the failure is + * recorded), and the returned stream checks it after every read, turning that clean EOF back + * into a real {@code IOException} instead. + * + *

Package-private, not {@code private}, so {@code VerdaccioSidecarClientTest} can exercise + * this exact failure path directly against a nonexistent {@code content} path, rather than + * only through the full {@code storePackageVersionAsset} call chain, whose own earlier + * whole-file digesting pass would otherwise already reject a missing file before this method + * is ever reached. + */ + static InputStream base64EncodingStream(Path content) { + PipedOutputStream pipedOut = new PipedOutputStream(); + PipedInputStream pipedIn; + try { + pipedIn = new PipedInputStream(pipedOut, 64 * 1024); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + AtomicReference writerFailure = new AtomicReference<>(); + Thread.ofVirtual().start(() -> { + InputStream fileIn = null; + OutputStream encodingOut = null; + try { + encodingOut = Base64.getEncoder().wrap(pipedOut); + fileIn = Files.newInputStream(content); + fileIn.transferTo(encodingOut); + } catch (IOException e) { + writerFailure.set(e); + } finally { + StreamingResponses.closeQuietly(fileIn); + closeQuietly(encodingOut); + } + }); + return new FailFastInputStream(pipedIn, writerFailure); + } + + /** {@link #base64EncodingStream}'s own close helper for the {@code OutputStream} side of its pipe. */ + private static void closeQuietly(OutputStream out) { + if (out == null) { + return; + } + try { + out.close(); + } catch (IOException ignored) { + // Best-effort: the encoding thread is tearing down regardless, and any failure here + // is already captured (or about to be) in writerFailure above. + } + } + + /** + * Wraps {@link #base64EncodingStream}'s pipe so a writer-side failure recorded in {@code + * writerFailure} (set before the pipe itself closes; see that method's own javadoc) is + * thrown on the next read instead of being masked by the pipe's own ordinary EOF. + */ + private static final class FailFastInputStream extends FilterInputStream { + private final AtomicReference writerFailure; + + FailFastInputStream(InputStream in, AtomicReference writerFailure) { + super(in); + this.writerFailure = writerFailure; + } + + @Override + public int read() throws IOException { + int result = super.read(); + throwIfFailed(); + return result; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int result = super.read(b, off, len); + throwIfFailed(); + return result; + } + + private void throwIfFailed() throws IOException { + IOException failure = writerFailure.get(); + if (failure != null) { + throw new IOException("Failed to read the staged asset while base64-encoding it for the " + + "Verdaccio sidecar", failure); + } + } + } + + private void sendVersionDocument(String baseUrl, String path, String npmName, String version, + HttpRequest.BodyPublisher publisher, long contentLength) { HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + path)) - .timeout(Duration.ofSeconds(30)) + .timeout(SidecarUriUtils.transferTimeout(contentLength)) .header("Content-Type", "application/json") - .PUT(BodyPublishers.ofByteArray(writeValue(body))) + .PUT(publisher) .build(); HttpResponse response; try { @@ -625,19 +945,11 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager { return namespace == null ? packageName : "@" + namespace + "/" + packageName; } - private byte[] writeValue(ObjectNode value) { + private byte[] writeValue(JsonNode value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { throw new IllegalStateException("Could not serialize a Verdaccio request body", e); } } - - private static MessageDigest sha512() { - try { - return MessageDigest.getInstance("SHA-512"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-512 is required by every Java runtime", e); - } - } } diff --git a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java index c8183c0de1..4f521d44ca 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java @@ -48,6 +48,17 @@ public class VerdaccioSidecarManager implements ContainerTeardown { publish: $all unpublish: $all listen: 0.0.0.0:4873 + # Verdaccio's own documented default (10mb) is for a small JSON document, not a real + # npm publish's packument-with-embedded-tarball body; discovered by hand-testing a + # multi-GB publish end to end, which Verdaccio rejected outright with its own "request + # entity too large" below this value. Raising it past CodeArtifactService + # .MAX_ASSET_FILE_SIZE_BYTES is still worthwhile even though it alone doesn't reach + # that real AWS quota: past roughly a 500 MB asset, Verdaccio's own Node/V8 runtime hits + # its hard maximum JavaScript string length converting the received body to one string + # before parsing it, and crashes outright: a real, documented, npm-protocol-specific + # ceiling no Verdaccio config can move (see docs/services/codeartifact.md's own Known + # limitations entry). + max_body_size: 5gb log: type: stdout format: pretty diff --git a/src/main/java/io/floci/aws/services/s3/S3Controller.java b/src/main/java/io/floci/aws/services/s3/S3Controller.java index 1b17dd853d..54037c0950 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Controller.java +++ b/src/main/java/io/floci/aws/services/s3/S3Controller.java @@ -17,6 +17,7 @@ import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.ResteasyRequests; +import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.core.common.XmlParser; import io.floci.aws.core.common.auth.SigV4Canonicalization; @@ -1194,28 +1195,10 @@ public class S3Controller { /** Streams {@code body}, opened together with {@code obj} by {@link S3Service#openObject}, and closes it. */ private Response fullObjectResponse(S3Object obj, InputStream body, ResponseHeaderOverrides overrides, boolean includeChecksum) { - return streamingResponse(body, + return StreamingResponses.streamingResponse(body, stream -> objectResponseHeaders(Response.ok(stream), obj, overrides, includeChecksum).build()); } - /** - * Builds a response whose entity streams {@code body} and then closes it. If building the - * response fails, the entity is never written, so {@code body} is closed here instead. - */ - static Response streamingResponse(InputStream body, Function build) { - StreamingOutput stream = output -> { - try (InputStream in = body) { - in.transferTo(output); - } - }; - try { - return build.apply(stream); - } catch (RuntimeException e) { - closeQuietly(body); - throw e; - } - } - /** Applies the standard GetObject response headers derived from {@code obj} to {@code resp}. */ private Response.ResponseBuilder objectResponseHeaders(Response.ResponseBuilder resp, S3Object obj, ResponseHeaderOverrides overrides, @@ -1303,7 +1286,7 @@ public class S3Controller { } return resp.build(); }; - return body == null ? build.apply(null) : streamingResponse(part.slice(body), build); + return body == null ? build.apply(null) : StreamingResponses.streamingResponse(part.slice(body), build); } /** diff --git a/src/test/java/io/floci/aws/core/common/MultipartFormParserTest.java b/src/test/java/io/floci/aws/core/common/MultipartFormParserTest.java index 8f2c75ea04..70dc361a8e 100644 --- a/src/test/java/io/floci/aws/core/common/MultipartFormParserTest.java +++ b/src/test/java/io/floci/aws/core/common/MultipartFormParserTest.java @@ -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 found 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. + * + *

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++) { diff --git a/src/test/java/io/floci/aws/core/common/StreamingResponsesTest.java b/src/test/java/io/floci/aws/core/common/StreamingResponsesTest.java new file mode 100644 index 0000000000..a9a23423b8 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/StreamingResponsesTest.java @@ -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"); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/AssetDigestingInputStreamTest.java b/src/test/java/io/floci/aws/services/codeartifact/AssetDigestingInputStreamTest.java new file mode 100644 index 0000000000..6528706223 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/AssetDigestingInputStreamTest.java @@ -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); + } + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/BagetterSidecarClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/BagetterSidecarClientTest.java index 0993a06cb8..a2b9f7ece2 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/BagetterSidecarClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/BagetterSidecarClientTest.java @@ -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 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 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}. diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java index d544b6c2cb..1f43ed32dc 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java @@ -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("".getBytes(StandardCharsets.UTF_8), - "application/xml"); - FetchedArtifact refreshed = new FetchedArtifact("" - .getBytes(StandardCharsets.UTF_8), "application/xml"); - when(reposilite.fetchArtifact(REPO_ID, METADATA_GAV)).thenReturn(Optional.of(stale)) + StreamedArtifact stale = new StreamedArtifact( + new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)), 11, "application/xml"); + byte[] refreshedBytes = "".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("", - 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, - "".getBytes(StandardCharsets.UTF_8)); + new ByteArrayInputStream("".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, - "".getBytes(StandardCharsets.UTF_8)); + new ByteArrayInputStream("".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", "".getBytes(StandardCharsets.UTF_8)); + "com/example/widget-SNAPSHOT/maven-metadata.xml", + new ByteArrayInputStream("".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)) diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java index 997c4e8b1d..2d59625637 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java @@ -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); } diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java index 55c2f72d4a..d5360487d3 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java @@ -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)); + }); + } } diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java index 6ac6dcf2d2..db3ad3d4e6 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java @@ -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 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 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")); diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java index 64c0a23335..6a6f8cd007 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java @@ -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)); + }); + } } diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java index a1e5ea529a..015ba5c97a 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java @@ -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 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 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 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"); } diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java index 37e7f2011d..fcfd5b6e38 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java index f586d9f156..bbb3f9b52b 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java @@ -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 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 captureCopiedAssetContent(ReposiliteSidecarClient client, + String sourceRepoId, String sourceRepo, String destRepoId, String destRepo, String namespace, + String packageName, String version, String assetName) { + AtomicReference 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 captureStoredAssetContent(ReposiliteSidecarClient client, + String destRepoId, String destRepo, String namespace, String packageName, String version, + String assetName) { + AtomicReference 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 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, 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 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 copiedJar = captureCopiedAssetContent(reposiliteClient, srcRepoId, "src", dstRepoId, + "dst", "com.example", "a", "1.0", "a-1.0.jar"); + AtomicReference 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 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 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 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)))); diff --git a/src/test/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClientTest.java index 5dc683a1a7..1bd8c08722 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/MavenExternalConnectionClientTest.java @@ -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 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", diff --git a/src/test/java/io/floci/aws/services/codeartifact/MultipartFilePublisherTest.java b/src/test/java/io/floci/aws/services/codeartifact/MultipartFilePublisherTest.java new file mode 100644 index 0000000000..647d4d41c2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/MultipartFilePublisherTest.java @@ -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))); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClientTest.java index 725d570cd1..95b9f42033 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/NpmExternalConnectionClientTest.java @@ -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 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)); diff --git a/src/test/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClientTest.java index 11cee7fe13..2cb8f1a437 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/NuGetExternalConnectionClientTest.java @@ -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 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)); diff --git a/src/test/java/io/floci/aws/services/codeartifact/NuspecXmlTest.java b/src/test/java/io/floci/aws/services/codeartifact/NuspecXmlTest.java index ff1bc31031..c0d0899b88 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/NuspecXmlTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/NuspecXmlTest.java @@ -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() { diff --git a/src/test/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClientTest.java index 58982099d6..5ebef8c4b5 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/PypiExternalConnectionClientTest.java @@ -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 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)); diff --git a/src/test/java/io/floci/aws/services/codeartifact/PypiserverSidecarClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/PypiserverSidecarClientTest.java index b9e409fcc0..be463d1d42 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/PypiserverSidecarClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/PypiserverSidecarClientTest.java @@ -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 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 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 diff --git a/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java index ea75e2b779..d6263a8730 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java @@ -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 received = new AtomicReference<>(); + AtomicReference 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 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 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 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 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 diff --git a/src/test/java/io/floci/aws/services/codeartifact/SidecarUriUtilsTest.java b/src/test/java/io/floci/aws/services/codeartifact/SidecarUriUtilsTest.java index 51be48f3d7..bcd1921fb2 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/SidecarUriUtilsTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/SidecarUriUtilsTest.java @@ -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)); + } } diff --git a/src/test/java/io/floci/aws/services/codeartifact/StreamEqualityTest.java b/src/test/java/io/floci/aws/services/codeartifact/StreamEqualityTest.java new file mode 100644 index 0000000000..bfcaabdba9 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/StreamEqualityTest.java @@ -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); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClientTest.java index 848277aa72..d5a3bb903f 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/VerdaccioSidecarClientTest.java @@ -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 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 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 diff --git a/src/test/java/io/floci/aws/services/s3/S3ObjectStreamTest.java b/src/test/java/io/floci/aws/services/s3/S3ObjectStreamTest.java index 24c72a07ce..944c8e9fe5 100644 --- a/src/test/java/io/floci/aws/services/s3/S3ObjectStreamTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3ObjectStreamTest.java @@ -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"); - } }