mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(codeartifact): retain Cargo crates from a same-domain upstream repository (#8423)
16f-UPSTREAM-REPO (#8261) gave every container-backed format its own repository-to-repository upstream importer except cargo, since cargo didn't exist yet when that PR merged. Adds cargo's own share of it. CodeArtifactCargoUpstreamRepositoryImporter mirrors CodeArtifactNuGetUpstreamRepositoryImporter's own claim/fence/walk shell (transitive search via resolveUpstreamSearchOrder, Archived/Disposed propagation, falling through to UpstreamExternalConnectionFetch for the last leg through a candidate's own external connection), reusing CodeArtifactCargoExternalConnectionImporter's own index-line/wire-body helpers directly rather than duplicating the index-shape to publish-shape mapping a second time. The one new piece: mergeUpstreamRepositoryVersions, a real multi-version sparse-index merge across the whole upstream chain, the same reason mergeExternalVersions exists for the external-connection side. Unlike pypi's own single-target additionalInternalFilenames, this walks every reachable upstream candidate in search order rather than stopping at the first one with anything to offer, since it is merging real version lines across however many hops the chain has; each candidate's own external connection, if it has one, is layered in too via a direct mergeExternalVersions call with that candidate as the repository argument. Wired into CodeArtifactCargoController's existing two call sites, matching every sibling controller's own "external connection or upstreams, never both" shape. A live Docker integration test proves the real synthesized wire body this importer builds from one Kellnr container's own sparse-index line is accepted by a second, genuinely different Kellnr container, not just internally consistent against mocks.
This commit is contained in:
1 parent
8ba3f00443
commit
85492a4147
9 files changed
+1344
-99
No files matched your search
@@ -460,20 +460,19 @@ state.
|
||||
(`KELLNR_SETUP__ADMIN_PWD`, confirmed live to override that default) and read fresh on every
|
||||
admin login rather than cached, so it also stays correct across a container silently restarted
|
||||
under the same repository id.
|
||||
- **Every native endpoint's own external connections resolve, for Maven, npm, pypi, nuget, and now
|
||||
cargo (`public:crates-io`, against the real `index.crates.io`/`static.crates.io`); the
|
||||
repository-to-repository upstream side does not yet resolve for cargo.** A real `cargo build`/
|
||||
`cargo add` needs more than a plain on-demand fetch to work at all: its own sparse index for one
|
||||
crate name is a single file covering every version, so a cache miss on the download route alone
|
||||
would leave an upstream-only version invisible to its resolver. The native cargo endpoint's own
|
||||
sparse-index route merges in the real upstream index's own version lines not already known
|
||||
locally (read-only, nothing retained until a real download actually happens), the one thing none
|
||||
of the other four formats' own external-connection importers need, since their own clients can
|
||||
always ask for one already-known version directly. `cargo` is otherwise still a container-backed
|
||||
format like the other four (`DescribePackageVersion`, `ListPackages`, `DeletePackage`,
|
||||
`CopyPackageVersions`, and byte accounting all already work for it the same way), but has no
|
||||
repository-to-repository upstream resolution against its own native endpoint yet; that's its own
|
||||
future work. On real CodeArtifact, a repository with another repository
|
||||
- **Every native endpoint's own external connections, and now its own repository-to-repository
|
||||
upstream chain too, resolve for Maven, npm, pypi, nuget, and cargo** (cargo's external
|
||||
connection is `public:crates-io`, against the real `index.crates.io`/`static.crates.io`). A real
|
||||
`cargo build`/`cargo add` needs more than a plain on-demand fetch to work at all: its own sparse
|
||||
index for one crate name is a single file covering every version, so a cache miss on the
|
||||
download route alone would leave an upstream-only version invisible to its resolver. The native
|
||||
cargo endpoint's own sparse-index route merges in real version lines not already known locally,
|
||||
from both its external connection and its own upstream repository chain (read-only, nothing
|
||||
retained until a real download actually happens), the one thing none of the other four formats'
|
||||
own importers need, since their own clients can always ask for one already-known version
|
||||
directly. `cargo` is otherwise still a container-backed format like the other four
|
||||
(`DescribePackageVersion`, `ListPackages`, `DeletePackage`, `CopyPackageVersions`, and byte
|
||||
accounting all already work for it the same way). On real CodeArtifact, a repository with another repository
|
||||
configured as an upstream (`UpdateRepository`'s `upstreams`) or with an
|
||||
`AssociateExternalConnection` to a public repository serves packages from those sources too, not
|
||||
just its own; a repository has one or the other, never both. Floci's Maven endpoint does this
|
||||
@@ -502,10 +501,10 @@ state.
|
||||
task so a popular package's first install doesn't risk outlasting a real `pip`/`twine` client's
|
||||
own default read timeout.
|
||||
|
||||
A repository-to-repository upstream chain resolves the same way, for all four formats, reusing
|
||||
the exact claim/fence/origin-tracking machinery above: a GET/HEAD/tarball-download/packument
|
||||
miss searches the repository's own `upstreams`, transitively, for the first repository with a
|
||||
usable copy. The order is AWS's documented priority order: depth-first, in each repository's
|
||||
A repository-to-repository upstream chain resolves the same way, for all five formats, reusing
|
||||
the exact claim/fence/origin-tracking machinery above: a GET/HEAD/tarball-download/packument/
|
||||
sparse-index miss searches the repository's own `upstreams`, transitively, for the first
|
||||
repository with a usable copy. The order is AWS's documented priority order: depth-first, in each repository's
|
||||
listed order, an upstream's own upstreams searched before the next one, so `my_repo` with
|
||||
upstreams `A` and `B`, `A` with `C` and `D` and `D` with `E` is searched `A, C, D, E, B`. An
|
||||
Archived or Disposed version *at the resolved upstream repository itself* is skipped, the walk
|
||||
@@ -514,14 +513,18 @@ state.
|
||||
through an upstream's own external connection, the first in that same order that has one, and
|
||||
retained both there and in the repository the request was made to, as AWS documents for a
|
||||
downstream request chaining through an upstream's `public:*` connection; a packument, Simple
|
||||
index or `maven-metadata.xml` read through such an upstream offers what its connection has too.
|
||||
index, `maven-metadata.xml`, or cargo sparse-index read through such an upstream offers what its
|
||||
connection has too (cargo's own sparse-index merge walks every reachable upstream in that same
|
||||
priority order rather than stopping at the first one with anything to offer, since it is merging
|
||||
real version lines across however many hops the chain has, not resolving a single target the way
|
||||
the other four formats' own one-shot reads do).
|
||||
A retained version's `origin.domainEntryPoint` names where it entered the domain: the external
|
||||
connection it was fetched through, `EXTERNAL`, or the repository it was published to, however
|
||||
many upstreams it was retained through. Since the copy from a same-domain upstream never leaves
|
||||
this process (a fetch through an upstream's connection is that connection's own import), pypi's
|
||||
own copy here needs none of the real external connection's PEP 691 sha256 re-verification or
|
||||
background-thread split: every asset of the resolved version is copied synchronously, in one
|
||||
pass.
|
||||
and cargo's own copy here need none of the real external connection's PEP 691/cargo-index-cksum
|
||||
re-verification or (pypi's own) background-thread split: every asset of the resolved version is
|
||||
copied synchronously, in one pass.
|
||||
- **Maven external-connection retention is the one place this emulator makes a real outbound
|
||||
call to the public internet**, rather than only ever talking to a container it started itself.
|
||||
An offline environment, or a real outage of the public repository being connected to, means a
|
||||
@@ -577,8 +580,8 @@ state.
|
||||
native wire protocol (`mvn deploy`, `npm publish`, `twine upload`, `nuget push`, `cargo publish`)
|
||||
directly against the repository endpoint. `upstream` is stored and reported faithfully for every
|
||||
format, and gates every format's own external-connection retention and repository-to-repository
|
||||
upstream retention (external-connection retention now resolves for cargo too, alongside Maven,
|
||||
npm, pypi, and nuget; cargo has no repository-to-repository upstream retention yet, see above).
|
||||
upstream retention, both of which now resolve for cargo too, alongside Maven, npm, pypi, and
|
||||
nuget (see above).
|
||||
`CopyPackageVersions`
|
||||
deliberately does not check `publish: BLOCK`/`upstream: BLOCK` either, for any format, including
|
||||
its own `includeFromUpstream` search: the User Guide's own definition of both controls scopes
|
||||
@@ -620,10 +623,9 @@ state.
|
||||
(`PublishPackageVersion`'s own `generic`-format path and every native proxy controller's own
|
||||
publish guard, `mvn deploy`/`npm publish`/`twine upload`/`nuget push`/`cargo publish` alike);
|
||||
`EXTERNAL_UPSTREAM` and `INTERNAL_UPSTREAM` only apply where a format has retention to gate in
|
||||
the first place; cargo's own external-connection retention is gated by `EXTERNAL_UPSTREAM` the
|
||||
same way the other four formats' already are (`isUpstreamRetentionBlocked`'s own check is fully
|
||||
format-agnostic), but `INTERNAL_UPSTREAM` still never reaches cargo, since it has no
|
||||
repository-to-repository upstream resolution yet (see above). For the formats that do: every
|
||||
the first place; cargo's own external-connection and repository-to-repository retention are both
|
||||
gated the same way the other four formats' already are (`isUpstreamRetentionBlocked`'s own check
|
||||
is fully format-agnostic). Every
|
||||
format's external-connection retention (Maven, npm, pypi, NuGet, and now cargo) is wired to the
|
||||
resolved `EXTERNAL_UPSTREAM` mode; and every format's repository-to-repository upstream retention
|
||||
(`UpdateRepository`'s `upstreams`) is wired to the resolved `INTERNAL_UPSTREAM` mode the same
|
||||
|
||||
@@ -75,14 +75,17 @@ public class CodeArtifactCargoController {
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private final CodeArtifactCargoUpstreamRepositoryImporter upstreamRepositoryImporter;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoController(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CodeArtifactCargoExternalConnectionImporter externalConnectionImporter, ObjectMapper mapper) {
|
||||
CodeArtifactCargoExternalConnectionImporter externalConnectionImporter,
|
||||
CodeArtifactCargoUpstreamRepositoryImporter upstreamRepositoryImporter, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
this.upstreamRepositoryImporter = upstreamRepositoryImporter;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@@ -150,8 +153,15 @@ public class CodeArtifactCargoController {
|
||||
// one cheap local existence check, the same pattern CodeArtifactNuGetController's own
|
||||
// .nupkg route already uses.
|
||||
if (!kellnr.packageVersionExists(handle.repoId(), domain, repository, null, packageName, version)) {
|
||||
externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), packageName, version);
|
||||
// A repository has either an external connection or upstreams, never both: at most
|
||||
// one of these two calls ever does real work, and the other's own no-op is a single
|
||||
// cheap in-memory check, the same pattern CodeArtifactNuGetController's own .nupkg
|
||||
// route already uses.
|
||||
if (!externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), packageName, version)) {
|
||||
upstreamRepositoryImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), packageName, version);
|
||||
}
|
||||
}
|
||||
Optional<RepositorySidecarManager.StreamedAsset> streamed = kellnr.fetchPackageVersionAssetStreamed(
|
||||
handle.repoId(), domain, repository, null, packageName, version,
|
||||
@@ -177,11 +187,12 @@ public class CodeArtifactCargoController {
|
||||
* javadoc for why that mapping is deliberately deferred rather than guessed at.
|
||||
*
|
||||
* <p>Merged with any real upstream-only version lines the repository's own {@code
|
||||
* public:crates-io} external connection can see (see {@link
|
||||
* CodeArtifactCargoExternalConnectionImporter}'s own javadoc for why this, unlike every other
|
||||
* format's own external-connection importer, needs a listing merge and not just an
|
||||
* on-demand download): a real {@code cargo} client's dependency resolver only ever sees a
|
||||
* version by first finding it here.
|
||||
* public:crates-io} external connection, and now its own same-domain upstream chain too, can
|
||||
* see (see {@link CodeArtifactCargoExternalConnectionImporter}'s own javadoc for why this,
|
||||
* unlike every other format's own external-connection importer, needs a listing merge and not
|
||||
* just an on-demand download, and {@link CodeArtifactCargoUpstreamRepositoryImporter}'s own
|
||||
* javadoc for the same reasoning extended across an upstream chain): a real {@code cargo}
|
||||
* client's dependency resolver only ever sees a version by first finding it here.
|
||||
*/
|
||||
private Response sparseIndexLookup(RepositoryHandle handle, String domain, String repository, String path) {
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
@@ -190,8 +201,10 @@ public class CodeArtifactCargoController {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
Optional<byte[]> local = kellnr.fetchSparseIndexRaw(handle.repoId(), domain, repository, packageName);
|
||||
Optional<byte[]> merged = externalConnectionImporter.mergeExternalVersions(handle.region(), domain,
|
||||
Optional<byte[]> mergedExternal = externalConnectionImporter.mergeExternalVersions(handle.region(), domain,
|
||||
handle.owner(), repository, packageName, local);
|
||||
Optional<byte[]> merged = upstreamRepositoryImporter.mergeUpstreamRepositoryVersions(handle.region(), domain,
|
||||
handle.owner(), repository, handle.repoId(), packageName, mergedExternal);
|
||||
return merged.map(bytes -> Response.status(200).entity(bytes).type(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.build())
|
||||
.orElseGet(() -> Response.status(404).build());
|
||||
|
||||
+19
-6
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.AwsException;
|
||||
import io.floci.aws.services.codeartifact.model.ExternalConnection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -221,7 +222,19 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
return Optional.of(String.join("\n", merged.values()).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private Optional<String> indexLineVersion(String line) {
|
||||
/**
|
||||
* Whether {@code repository} has a cargo external connection to fetch through. A repository
|
||||
* deleted since its name was read, as an upstream in a search order can be, has none.
|
||||
*/
|
||||
boolean hasExternalConnection(String region, String domain, String owner, String repository) {
|
||||
try {
|
||||
return cargoExternalConnectionName(region, domain, owner, repository) != null;
|
||||
} catch (AwsException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Optional<String> indexLineVersion(String line) {
|
||||
try {
|
||||
return Optional.ofNullable(mapper.readTree(line).path("vers").asText(null));
|
||||
} catch (IOException e) {
|
||||
@@ -229,7 +242,7 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> splitLines(byte[] indexBytes) {
|
||||
static List<String> splitLines(byte[] indexBytes) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (String line : new String(indexBytes, StandardCharsets.UTF_8).split("\n")) {
|
||||
if (!line.isBlank()) {
|
||||
@@ -239,7 +252,7 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
return lines;
|
||||
}
|
||||
|
||||
private Optional<JsonNode> findIndexLine(byte[] indexBytes, String version) {
|
||||
Optional<JsonNode> findIndexLine(byte[] indexBytes, String version) {
|
||||
for (String line : splitLines(indexBytes)) {
|
||||
JsonNode node;
|
||||
try {
|
||||
@@ -278,7 +291,7 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
* though crates.io itself re-derives it from the {@code .crate}'s own {@code Cargo.toml}
|
||||
* rather than trusting the index's copy.
|
||||
*/
|
||||
private byte[] metadataFromIndexLine(JsonNode indexLine) {
|
||||
byte[] metadataFromIndexLine(JsonNode indexLine) {
|
||||
ObjectNode metadata = mapper.createObjectNode();
|
||||
metadata.put("name", indexLine.path("name").asText());
|
||||
metadata.put("vers", indexLine.path("vers").asText());
|
||||
@@ -334,7 +347,7 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
* asset can, so the header is written first and {@code crateFile}'s own real bytes are then
|
||||
* streamed straight through rather than ever held alongside it in memory.
|
||||
*/
|
||||
private static Path buildStagedWireBody(byte[] metadataJson, Path crateFile) {
|
||||
static Path buildStagedWireBody(byte[] metadataJson, Path crateFile) {
|
||||
Path staged;
|
||||
try {
|
||||
staged = Files.createTempFile("codeartifact-cargo-import-wire-", ".bin");
|
||||
@@ -366,7 +379,7 @@ public class CodeArtifactCargoExternalConnectionImporter {
|
||||
}
|
||||
}
|
||||
|
||||
private static long fileSize(Path path) {
|
||||
static long fileSize(Path path) {
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException e) {
|
||||
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
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.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* {@code 17d-CARGO-UPSTREAM-REPO}: retains a Cargo crate version from another repository in the
|
||||
* same domain, named in {@code repository}'s own {@code upstreams} list (distinct from, and
|
||||
* mutually exclusive with, {@link CodeArtifactCargoExternalConnectionImporter}'s real public
|
||||
* registry). Reuses the exact claim/fence mechanism {@link
|
||||
* CodeArtifactService#claimRetainedVersionOrigin} already provides, mirroring {@link
|
||||
* CodeArtifactNuGetUpstreamRepositoryImporter}'s own shell for the single-asset-per-version walk
|
||||
* (transitive search in priority order via {@link CodeArtifactService#resolveUpstreamSearchOrder},
|
||||
* Archived/Disposed propagation via {@link
|
||||
* CodeArtifactService#requireContainerBackedVersionDownloadable}, falling through to {@link
|
||||
* UpstreamExternalConnectionFetch} for the last leg through an upstream's own external
|
||||
* connection), and reusing {@link CodeArtifactCargoExternalConnectionImporter}'s own now
|
||||
* package-visible index-line/wire-body helpers directly rather than duplicating the index-shape to
|
||||
* publish-shape mapping a second time. No {@code cksum} re-verification against the candidate's
|
||||
* own index line, the same reasoning {@link CodeArtifactPypiUpstreamRepositoryImporter}'s own
|
||||
* javadoc gives for skipping pypi's own PEP 691/sha256 re-check here: a same-domain upstream is
|
||||
* another repository this emulator itself already backs, with nothing untrusted or remote to
|
||||
* re-verify against, unlike the real public registry the external-connection importer fetches
|
||||
* from.
|
||||
*
|
||||
* <p><b>The same genuinely new piece {@link CodeArtifactCargoExternalConnectionImporter} needed,
|
||||
* needed again here</b>: a real {@code cargo} client always resolves the sparse index before a
|
||||
* download, and the index for one crate name is a single file covering every version, so this
|
||||
* importer also has {@link #mergeUpstreamRepositoryVersions}, a read-only listing merge over
|
||||
* {@code repository}'s own upstream chain, the same reason {@code mergeExternalVersions} exists.
|
||||
* Unlike {@link CodeArtifactPypiUpstreamRepositoryImporter#additionalInternalFilenames}'s own
|
||||
* per-request merge (which stops at the first candidate naming the one requested file, a single-
|
||||
* target resolution), this one is a real multi-version index merge, so it walks every reachable
|
||||
* candidate in search order rather than stopping at the first one with anything to offer, in two
|
||||
* complete passes rather than interleaved per candidate: every candidate's own real local lines
|
||||
* first (first-found-per-version wins, matching {@code mergeExternalVersions}'s own "local always
|
||||
* wins over upstream" compositional model extended across however many hops the chain has), then
|
||||
* every candidate's own external connection, if it has one, each layered in too by calling {@code
|
||||
* mergeExternalVersions} directly with that candidate as the repository argument, the same
|
||||
* chain-through {@code additionalInternalFilenames} already does for pypi's own sibling-files
|
||||
* case. The two full passes, not interleaved, matter: {@link #tryImport}'s own real resolution
|
||||
* order tries every candidate's own local copy, across the whole chain, before ever falling
|
||||
* through to any candidate's external connection, so a real download can retain a later
|
||||
* candidate's own local bytes for a version an earlier candidate's external connection also
|
||||
* offers with different bytes; advertising the earlier, external line here while a download would
|
||||
* retain the later, local one would hand a real {@code cargo} client a {@code cksum} that doesn't
|
||||
* match what it actually downloads. Each external-connection-contributed line also gets the same
|
||||
* two-sided Archived/Disposed check a locally-contributed line already does (checked only against
|
||||
* genuinely new versions that pass contributed, never against ones already known), since a real
|
||||
* download through a candidate's own external connection already refuses one Archived or Disposed
|
||||
* there.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactCargoUpstreamRepositoryImporter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactCargoUpstreamRepositoryImporter.class);
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoUpstreamRepositoryImporter(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CodeArtifactCargoExternalConnectionImporter externalConnectionImporter) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retain {@code packageName}/{@code version}'s one real crate asset into {@code
|
||||
* repoId} from the first eligible repository in {@code repository}'s own upstream chain.
|
||||
* Returns {@code true} only when the crate is genuinely present under this claim by the time
|
||||
* this returns, the same contract {@link CodeArtifactCargoExternalConnectionImporter
|
||||
* #tryImport}'s own javadoc documents.
|
||||
*/
|
||||
public boolean tryImport(String region, String domain, String owner, String repository, String repoId,
|
||||
String packageName, String version) {
|
||||
if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"INTERNAL_UPSTREAM")) {
|
||||
return false;
|
||||
}
|
||||
// Snapshotted before the walk, not once a candidate is found, the same ordering
|
||||
// CodeArtifactCargoExternalConnectionImporter#tryImport relies on: the walk's last leg can
|
||||
// fetch through an upstream's own external connection, and a deletion here during that
|
||||
// fetch must still move the fence away from the snapshot.
|
||||
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName);
|
||||
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName, version);
|
||||
|
||||
String upstreamRepository = null;
|
||||
String upstreamRepoId = null;
|
||||
for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) {
|
||||
String candidateRepoId;
|
||||
try {
|
||||
candidateRepoId = service.resolveContainerIdAndBeginUse("cargo", region, domain, owner, candidate,
|
||||
kellnr);
|
||||
} catch (RuntimeException e) {
|
||||
// The candidate is being concurrently deleted/released: treated exactly like "not
|
||||
// found" there, the same way an Archived/Disposed candidate below is.
|
||||
continue;
|
||||
}
|
||||
boolean eligible = false;
|
||||
try {
|
||||
if (!kellnr.packageVersionExists(candidateRepoId, domain, candidate, null, packageName, version)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "cargo",
|
||||
null, packageName, version, candidateRepoId);
|
||||
} catch (AwsException e) {
|
||||
// Archived or Disposed at this candidate: AWS treats this exactly like "not
|
||||
// found" there, so the walk continues to the next candidate rather than
|
||||
// stopping.
|
||||
continue;
|
||||
}
|
||||
eligible = true;
|
||||
upstreamRepository = candidate;
|
||||
upstreamRepoId = candidateRepoId;
|
||||
break;
|
||||
} finally {
|
||||
if (!eligible) {
|
||||
kellnr.endUse(candidateRepoId);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (upstreamRepository == null) {
|
||||
Optional<UpstreamExternalConnectionFetch.Fetched> fetched = UpstreamExternalConnectionFetch.firstFetched(
|
||||
service, kellnr, "cargo", region, domain, owner, repository, null, packageName,
|
||||
candidate -> externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate),
|
||||
(candidate, candidateRepoId) -> externalConnectionImporter.tryImport(region, domain, owner,
|
||||
candidate, candidateRepoId, packageName, version) ? Optional.of(version)
|
||||
: Optional.empty());
|
||||
if (fetched.isPresent()) {
|
||||
upstreamRepository = fetched.get().repository();
|
||||
upstreamRepoId = fetched.get().repoId();
|
||||
}
|
||||
}
|
||||
if (upstreamRepository == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, packageName, version,
|
||||
upstreamRepository, upstreamRepoId, packageFenceSnapshot, versionFenceSnapshot);
|
||||
} finally {
|
||||
kellnr.endUse(upstreamRepoId);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository,
|
||||
String repoId, String packageName, String version, String upstreamRepository, String upstreamRepoId,
|
||||
long packageFenceSnapshot, long versionFenceSnapshot) {
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
|
||||
domain, owner, repository, "cargo", null, packageName, version, upstreamRepository,
|
||||
RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot);
|
||||
if (!claim.claimed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean imported = false;
|
||||
Path crateFile = null;
|
||||
Path stagedWireBody = null;
|
||||
try {
|
||||
// Same race this closes for the external-connection importer: a concurrent attempt
|
||||
// under this exact claim episode, or a real client's own direct push, may have already
|
||||
// landed these bytes by the time this attempt gets here.
|
||||
if (kellnr.packageVersionExists(repoId, domain, repository, null, packageName, version)) {
|
||||
imported = service.retainedUpstreamRepositoryOrigin(region, domain, owner, repository, "cargo",
|
||||
null, packageName, version).filter(upstreamRepository::equals).isPresent();
|
||||
return imported;
|
||||
}
|
||||
Optional<byte[]> upstreamIndex = kellnr.fetchSparseIndexRaw(upstreamRepoId, domain, upstreamRepository,
|
||||
packageName);
|
||||
if (upstreamIndex.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Optional<JsonNode> indexLine = externalConnectionImporter.findIndexLine(upstreamIndex.get(), version);
|
||||
if (indexLine.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String assetName = packageName + "-" + version + ".crate";
|
||||
Optional<RepositorySidecarManager.StreamedAsset> streamed = kellnr.fetchPackageVersionAssetStreamed(
|
||||
upstreamRepoId, domain, upstreamRepository, null, packageName, version, assetName);
|
||||
if (streamed.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
crateFile = service.stageStreamedAsset(streamed.get());
|
||||
// Not streamed.get().contentLength(): that's -1 whenever the upstream sidecar's own
|
||||
// response carried no Content-Length header, and forwarding -1 into byte accounting
|
||||
// would shrink DescribeDomain's assetSizeBytes instead of growing it. The staged
|
||||
// file's own real size is always correct.
|
||||
long contentLength = fileSizeOf(crateFile);
|
||||
byte[] metadata = externalConnectionImporter.metadataFromIndexLine(indexLine.get());
|
||||
stagedWireBody = CodeArtifactCargoExternalConnectionImporter.buildStagedWireBody(metadata, crateFile);
|
||||
long wireBodyLength = CodeArtifactCargoExternalConnectionImporter.fileSize(stagedWireBody);
|
||||
Path finalStagedWireBody = stagedWireBody;
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
|
||||
domain, owner, repository, "cargo", null, packageName, version, versionFenceSnapshot,
|
||||
packageFenceSnapshot, claim.episodeId(), repoId, assetName, contentLength,
|
||||
() -> {
|
||||
KellnrSidecarClient.KellnrPublishResult publishResult = kellnr.publishRawWireBody(repoId,
|
||||
finalStagedWireBody, wireBodyLength);
|
||||
if (publishResult.statusCode() != 200) {
|
||||
throw new IllegalStateException("Kellnr refused this retained crate: upstream "
|
||||
+ "returned " + publishResult.statusCode());
|
||||
}
|
||||
});
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
return imported;
|
||||
} finally {
|
||||
if (crateFile != null) {
|
||||
service.deleteStagedAssetBody(crateFile);
|
||||
}
|
||||
if (stagedWireBody != null) {
|
||||
try {
|
||||
Files.deleteIfExists(stagedWireBody);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Cargo upstream-repository wire-body file at {0}",
|
||||
stagedWireBody);
|
||||
}
|
||||
}
|
||||
if (imported) {
|
||||
service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository,
|
||||
"cargo", null, packageName, packageFenceSnapshot, repoId);
|
||||
}
|
||||
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "cargo", null,
|
||||
packageName, version, claim.episodeId(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code alreadyMergedBytes}'s own real version lines (whatever the local sparse index and
|
||||
* {@link CodeArtifactCargoExternalConnectionImporter#mergeExternalVersions} already
|
||||
* contributed), plus every real version line any repository in {@code repository}'s own
|
||||
* upstream chain carries that isn't already known, walked in {@link
|
||||
* CodeArtifactService#resolveUpstreamSearchOrder}'s own priority order (an earlier candidate's
|
||||
* line for a version always wins over a later one's line for that same version). A version
|
||||
* Archived or Disposed, at this repository or at the candidate offering it, is excluded from
|
||||
* the merge the same way {@link CodeArtifactPypiUpstreamRepositoryImporter
|
||||
* #additionalInternalFilenames} already excludes one. Each candidate's own external connection,
|
||||
* if it has one, is layered in too via a direct {@code mergeExternalVersions} call with that
|
||||
* candidate as the repository argument, the same chain-through pypi's own sibling method
|
||||
* already does. No upstreams configured, or the package {@code BLOCK}ed, returns {@code
|
||||
* alreadyMergedBytes} unchanged.
|
||||
*/
|
||||
public Optional<byte[]> mergeUpstreamRepositoryVersions(String region, String domain, String owner,
|
||||
String repository, String repoId, String packageName, Optional<byte[]> alreadyMergedBytes) {
|
||||
if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) {
|
||||
return alreadyMergedBytes;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"INTERNAL_UPSTREAM")) {
|
||||
return alreadyMergedBytes;
|
||||
}
|
||||
Map<String, String> merged = new LinkedHashMap<>();
|
||||
for (String line : CodeArtifactCargoExternalConnectionImporter.splitLines(
|
||||
alreadyMergedBytes.orElse(new byte[0]))) {
|
||||
externalConnectionImporter.indexLineVersion(line).ifPresent(vers -> merged.put(vers, line));
|
||||
}
|
||||
List<String> candidates = service.resolveUpstreamSearchOrder(region, domain, owner, repository);
|
||||
Map<String, String> candidateRepoIds = new LinkedHashMap<>();
|
||||
for (String candidate : candidates) {
|
||||
try {
|
||||
candidateRepoIds.put(candidate, service.resolveContainerIdAndBeginUse("cargo", region, domain, owner,
|
||||
candidate, kellnr));
|
||||
} catch (RuntimeException e) {
|
||||
// The candidate is being concurrently deleted/released: nothing listed there.
|
||||
}
|
||||
}
|
||||
try {
|
||||
// Pass 1: every candidate's own real local lines, in priority order, before any
|
||||
// external connection is considered at all. This has to be its own complete pass, not
|
||||
// interleaved per candidate the way an earlier version of this method did: tryImport's
|
||||
// own real resolution order tries every candidate's own local copy, across the whole
|
||||
// chain, before ever falling through to any candidate's external connection, so a
|
||||
// download picks a later candidate's own local bytes over an earlier candidate's
|
||||
// external-connection bytes for the same version. Advertising the earlier, external
|
||||
// cksum here while a download would retain the later, local bytes would hand a real
|
||||
// cargo client a checksum that doesn't match what it actually downloads.
|
||||
for (String candidate : candidates) {
|
||||
String candidateRepoId = candidateRepoIds.get(candidate);
|
||||
if (candidateRepoId != null) {
|
||||
mergeOneCandidate(region, domain, owner, repository, repoId, candidate, candidateRepoId,
|
||||
packageName, merged);
|
||||
}
|
||||
}
|
||||
// Pass 2: each candidate's own external connection, same priority order, only for a
|
||||
// version no candidate's own local copy already contributed in pass 1 (mirroring
|
||||
// tryImport's own fallback-only-after-every-local-candidate-misses order), and only
|
||||
// once it passes the same two-sided Archived/Disposed check pass 1's own local lines
|
||||
// already go through: a real download through a candidate's own external connection
|
||||
// (UpstreamExternalConnectionFetch) already refuses an Archived/Disposed version at
|
||||
// the candidate, and a version disposed here, at the requesting repository, must stay
|
||||
// invisible the same way a locally-contributed line already does.
|
||||
for (String candidate : candidates) {
|
||||
String candidateRepoId = candidateRepoIds.get(candidate);
|
||||
if (candidateRepoId == null
|
||||
|| !externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate)) {
|
||||
continue;
|
||||
}
|
||||
Set<String> beforeThisConnection = new HashSet<>(merged.keySet());
|
||||
Optional<byte[]> withConnection = externalConnectionImporter.mergeExternalVersions(region, domain,
|
||||
owner, candidate, packageName, Optional.of(serializeMerged(merged)));
|
||||
for (String line : CodeArtifactCargoExternalConnectionImporter.splitLines(
|
||||
withConnection.orElse(new byte[0]))) {
|
||||
Optional<String> version = externalConnectionImporter.indexLineVersion(line);
|
||||
if (version.isEmpty() || beforeThisConnection.contains(version.get())) {
|
||||
continue;
|
||||
}
|
||||
if (!downloadable(owner, region, domain, repository, packageName, version.get(), repoId)
|
||||
|| !downloadable(owner, region, domain, candidate, packageName, version.get(),
|
||||
candidateRepoId)) {
|
||||
continue;
|
||||
}
|
||||
merged.put(version.get(), line);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
candidateRepoIds.values().forEach(kellnr::endUse);
|
||||
}
|
||||
if (merged.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(serializeMerged(merged));
|
||||
}
|
||||
|
||||
private void mergeOneCandidate(String region, String domain, String owner, String repository, String repoId,
|
||||
String candidate, String candidateRepoId, String packageName, Map<String, String> merged) {
|
||||
Optional<byte[]> candidateIndex = kellnr.fetchSparseIndexRaw(candidateRepoId, domain, candidate,
|
||||
packageName);
|
||||
if (candidateIndex.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (String line : CodeArtifactCargoExternalConnectionImporter.splitLines(candidateIndex.get())) {
|
||||
Optional<String> version = externalConnectionImporter.indexLineVersion(line);
|
||||
if (version.isEmpty() || merged.containsKey(version.get())) {
|
||||
continue;
|
||||
}
|
||||
if (!downloadable(owner, region, domain, repository, packageName, version.get(), repoId)
|
||||
|| !downloadable(owner, region, domain, candidate, packageName, version.get(), candidateRepoId)) {
|
||||
continue;
|
||||
}
|
||||
merged.put(version.get(), line);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean downloadable(String owner, String region, String domain, String repository, String packageName,
|
||||
String version, String repoId) {
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "cargo", null,
|
||||
packageName, version, repoId);
|
||||
return true;
|
||||
} catch (AwsException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] serializeMerged(Map<String, String> merged) {
|
||||
return String.join("\n", merged.values()).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static long fileSizeOf(Path path) {
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-1
@@ -53,6 +53,7 @@ class CodeArtifactCargoControllerLeaseTest {
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private CodeArtifactCargoUpstreamRepositoryImporter upstreamRepositoryImporter;
|
||||
private CodeArtifactCargoController controller;
|
||||
private HttpHeaders headers;
|
||||
|
||||
@@ -61,13 +62,19 @@ class CodeArtifactCargoControllerLeaseTest {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionImporter = mock(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
controller = new CodeArtifactCargoController(service, kellnr, externalConnectionImporter, new ObjectMapper());
|
||||
upstreamRepositoryImporter = mock(CodeArtifactCargoUpstreamRepositoryImporter.class);
|
||||
controller = new CodeArtifactCargoController(service, kellnr, externalConnectionImporter,
|
||||
upstreamRepositoryImporter, new ObjectMapper());
|
||||
// Default: no external connection configured, so the merge is a pure pass-through of
|
||||
// whatever Kellnr's own local lookup returned, exactly what the real importer itself does
|
||||
// when cargoExternalConnectionName resolves to null. Individual tests override this to
|
||||
// exercise the merge itself.
|
||||
when(externalConnectionImporter.mergeExternalVersions(any(), any(), any(), any(), any(), any()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(5));
|
||||
// Same default for the upstream-repository merge: no upstreams configured, pass whatever
|
||||
// the external-connection merge already produced straight through unchanged.
|
||||
when(upstreamRepositoryImporter.mergeUpstreamRepositoryVersions(any(), any(), any(), any(), any(), any(),
|
||||
any())).thenAnswer(invocation -> invocation.getArgument(6));
|
||||
headers = mock(HttpHeaders.class);
|
||||
// A bare token, no scheme prefix: the real shape a cargo client sends (confirmed from the
|
||||
// Cargo Book's own registry-authentication page).
|
||||
@@ -146,6 +153,31 @@ class CodeArtifactCargoControllerLeaseTest {
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* The upstream-repository merge chains off whatever the external-connection merge already
|
||||
* produced, not off Kellnr's own raw local bytes directly: this is what lets a version only
|
||||
* the upstream chain has show up even when an external-connection merge already added
|
||||
* something else first.
|
||||
*/
|
||||
@Test
|
||||
void sparseIndexLookupServesTheMergedResultFromTheUpstreamRepositoryImporter() {
|
||||
Optional<byte[]> local = Optional.empty();
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate")).thenReturn(local);
|
||||
byte[] afterExternal = "{\"name\":\"democrate\",\"vers\":\"2.0.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionImporter.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, "democrate", local))
|
||||
.thenReturn(Optional.of(afterExternal));
|
||||
byte[] afterUpstream = ("{\"name\":\"democrate\",\"vers\":\"2.0.0\"}\n"
|
||||
+ "{\"name\":\"democrate\",\"vers\":\"3.0.0\"}").getBytes(StandardCharsets.UTF_8);
|
||||
when(upstreamRepositoryImporter.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
|
||||
"democrate", Optional.of(afterExternal))).thenReturn(Optional.of(afterUpstream));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(new String(afterUpstream, StandardCharsets.UTF_8),
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadReleasesItsLeaseOnAnEarlyNotFound() {
|
||||
doThrow(mock(AwsException.class)).when(service).requireContainerBackedVersionDownloadable(
|
||||
@@ -183,6 +215,35 @@ class CodeArtifactCargoControllerLeaseTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadFallsThroughToUpstreamRepositoryImportWhenExternalConnectionFindsNothing() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(false);
|
||||
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "democrate", "1.0.0"))
|
||||
.thenReturn(false);
|
||||
|
||||
controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(upstreamRepositoryImporter).tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "democrate",
|
||||
"1.0.0");
|
||||
}
|
||||
|
||||
/**
|
||||
* A repository has either an external connection or upstreams, never both: a successful
|
||||
* external-connection import must never fall through to an upstream-repository attempt too.
|
||||
*/
|
||||
@Test
|
||||
void downloadNeverAttemptsUpstreamRepositoryImportWhenExternalConnectionAlreadyImported() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(false);
|
||||
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "democrate", "1.0.0"))
|
||||
.thenReturn(true);
|
||||
|
||||
controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(upstreamRepositoryImporter, never()).tryImport(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* The one real asset download in this controller: proves it streams the sidecar's response
|
||||
* straight through rather than buffering it first, and still releases its lease afterward.
|
||||
|
||||
+11
-55
@@ -4,21 +4,16 @@ import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.cargoCrateBytes;
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.cargoPublishBody;
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
@@ -105,8 +100,8 @@ class CodeArtifactCargoDockerIntegrationTest {
|
||||
@Test
|
||||
@Order(2)
|
||||
void publishThenInstallRoundTripsTheExactBytesAndRealDependencies() throws IOException {
|
||||
originalCrateBytes = buildCrate(CRATE_NAME, VERSION);
|
||||
originalPublishBody = publishBody(CRATE_NAME, VERSION, originalCrateBytes);
|
||||
originalCrateBytes = cargoCrateBytes(CRATE_NAME, VERSION);
|
||||
originalPublishBody = cargoPublishBody(CRATE_NAME, VERSION, originalCrateBytes);
|
||||
long assetSizeBytesBeforePublish = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
@@ -225,10 +220,10 @@ class CodeArtifactCargoDockerIntegrationTest {
|
||||
@Order(8)
|
||||
void archivingAVersionBlocksItsRealKellnrContentDownloadWhileLeavingTheBytesInPlace() throws IOException {
|
||||
String crateName = "archivecrate";
|
||||
byte[] crateBytes = buildCrate(crateName, VERSION);
|
||||
byte[] crateBytes = cargoCrateBytes(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, crateBytes))
|
||||
.body(cargoPublishBody(crateName, VERSION, crateBytes))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
@@ -270,19 +265,19 @@ class CodeArtifactCargoDockerIntegrationTest {
|
||||
@Order(9)
|
||||
void publishBlockedByOriginConfigurationRefusesARealPublishUntilItIsLifted() throws IOException {
|
||||
String crateName = "originblockedcrate";
|
||||
byte[] published = buildCrate(crateName, VERSION);
|
||||
byte[] published = cargoCrateBytes(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, published))
|
||||
.body(cargoPublishBody(crateName, VERSION, published))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, REPO, "cargo", null, crateName, "BLOCK", "BLOCK");
|
||||
|
||||
byte[] nextVersionCrate = buildCrate(crateName, "2.0.0");
|
||||
byte[] nextVersionCrate = cargoCrateBytes(crateName, "2.0.0");
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.body(cargoPublishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(409);
|
||||
given().header("Authorization", bearerToken)
|
||||
@@ -294,7 +289,7 @@ class CodeArtifactCargoDockerIntegrationTest {
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.body(cargoPublishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
@@ -347,43 +342,4 @@ class CodeArtifactCargoDockerIntegrationTest {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real binary wire body confirmed directly from the Cargo Book's own spec text, and live
|
||||
* against a real Kellnr container in part 1: a 4-byte little-endian metadata length, the JSON
|
||||
* metadata itself (here with one real, non-empty dependency, to prove a native publish's own
|
||||
* dependency list survives the round trip untouched, unlike {@code CopyPackageVersions}'s own
|
||||
* always-empty-deps path), then a 4-byte little-endian crate length and the crate itself.
|
||||
*/
|
||||
private static byte[] publishBody(String name, String version, byte[] crateBytes) {
|
||||
String metadataJson = "{\"name\":\"" + name + "\",\"vers\":\"" + version + "\",\"deps\":["
|
||||
+ "{\"name\":\"real-dependency\",\"version_req\":\"^1.0\",\"features\":[],\"optional\":false,"
|
||||
+ "\"default_features\":true,\"target\":null,\"kind\":\"normal\",\"registry\":null}],"
|
||||
+ "\"features\":{},\"authors\":[],\"description\":\"a test crate\",\"documentation\":null,"
|
||||
+ "\"homepage\":null,\"readme\":null,\"readme_file\":null,\"keywords\":[],\"categories\":[],"
|
||||
+ "\"license\":\"MIT\",\"license_file\":null,\"repository\":null,\"badges\":{},\"links\":null}";
|
||||
byte[] metadata = metadataJson.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
/** A real, minimal, valid {@code .crate}: a gzipped tarball with one real {@code Cargo.toml}. */
|
||||
private static byte[] buildCrate(String name, String version) throws IOException {
|
||||
String cargoToml = "[package]\nname = \"" + name + "\"\nversion = \"" + version + "\"\nedition = \"2021\"\n";
|
||||
byte[] cargoTomlBytes = cargoToml.getBytes(StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out);
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name + "-" + version + "/Cargo.toml");
|
||||
entry.setSize(cargoTomlBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(cargoTomlBytes);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.cargoCrateBytes;
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.cargoPublishBody;
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@code 17d-CARGO-UPSTREAM-REPO}: retains a real crate version from another, real-Kellnr-backed
|
||||
* repository in the same domain through the native per-format route, the way a real {@code cargo
|
||||
* build}/{@code cargo add} would, against two genuinely separate Kellnr containers (the source
|
||||
* repository's own, and the destination's), not a mock standing in for either. See {@link
|
||||
* CodeArtifactCargoUpstreamRepositoryImporterTest} for the mocked, deterministic coverage of the
|
||||
* claim/fence/walk/archived-propagation logic this test does not re-exercise, mirroring {@link
|
||||
* CodeArtifactCargoExternalConnectionDockerIntegrationTest}'s own shape and reasoning for why a
|
||||
* live test earns its place alongside a thorough mocked one: the one thing mocks cannot prove is
|
||||
* that the real synthesized wire body this importer builds from one Kellnr's own real sparse-index
|
||||
* line is actually accepted by a second, genuinely different Kellnr container.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactCargoUpstreamRepositoryDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "cargo-upstream-repo-domain";
|
||||
private static final String SOURCE_REPO = "cargo-upstream-repo-source";
|
||||
private static final String DEST_REPO = "cargo-upstream-repo-dest";
|
||||
private static final String BLOCKED_REPO = "cargo-upstream-repo-blocked-dest";
|
||||
private static final String CRATE_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
|
||||
private static String bearerToken;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.cargo-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(0)
|
||||
void createDomainRepositoriesUpstreamsAndTokens() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + SOURCE_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + DEST_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"upstreams\":[{\"repositoryName\":\"" + SOURCE_REPO + "\"}]}")
|
||||
.put("/v1/repository?domain=" + DOMAIN + "&repository=" + DEST_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"upstreams\":[{\"repositoryName\":\"" + SOURCE_REPO + "\"}]}")
|
||||
.put("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
|
||||
bearerToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
|
||||
byte[] crate = cargoCrateBytes(CRATE_NAME, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(cargoPublishBody(CRATE_NAME, VERSION, crate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + SOURCE_REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves {@link CodeArtifactCargoUpstreamRepositoryImporter#mergeUpstreamRepositoryVersions}'s
|
||||
* own reason for existing, the same reason the external-connection importer's own merge
|
||||
* exists: the source's own version line is visible here even though nothing has ever been
|
||||
* downloaded from it yet (so nothing is retained), which a real {@code cargo} client's
|
||||
* dependency resolver needs in order to ever choose this version at all. Run before the
|
||||
* download test below, so this genuinely proves the merge, not a locally-cached line.
|
||||
*/
|
||||
@Test
|
||||
@Order(1)
|
||||
void fetchingTheSparseIndexMergesInTheSourceRepositorysVersionBeforeAnythingIsRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + DEST_REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + CRATE_NAME + "\""))
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void fetchingAMissingCrateRetainsItFromTheSourceRepositoryAndCountsItsBytes() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + DEST_REPO + "/api/v1/crates/" + CRATE_NAME + "/"
|
||||
+ VERSION + "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
|
||||
// A real .crate is a real gzip file: 0x1f 0x8b magic bytes, not asserting exact content
|
||||
// since the wire-body-synthesizing path rebuilds the metadata, only the crate bytes
|
||||
// themselves survive untouched.
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(50));
|
||||
|
||||
assertEquals(assetSizeBytesBefore + fetched.length, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void refetchingTheSameVersionServesItWithoutRetainingItAgain() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + DEST_REPO + "/api/v1/crates/" + CRATE_NAME + "/"
|
||||
+ VERSION + "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
|
||||
assertEquals(assetSizeBytesBefore, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code BLOCK}ed package shows no upstream-only version either, matching every other
|
||||
* retention path's own "behave exactly as if the upstream repository did not have it" rule,
|
||||
* not just refusing the download: a real {@code cargo} client's own resolver must not even
|
||||
* see a version this repository is configured never to retain from its own upstream chain.
|
||||
*/
|
||||
@Test
|
||||
@Order(4)
|
||||
void internalUpstreamBlockPreventsBothRetentionAndTheIndexMerge() {
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, BLOCKED_REPO, "cargo", null, CRATE_NAME, "ALLOW", "BLOCK");
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/api/v1/crates/" + CRATE_NAME + "/"
|
||||
+ VERSION + "/download")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void aVersionTheSourceRepositoryDoesNotHaveIsNeverRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + DEST_REPO + "/api/v1/crates/" + CRATE_NAME
|
||||
+ "/999.999.999/download")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms the fix every other format's own importer already needed (a successfully retained
|
||||
* version reporting its real origin) holds for cargo too, against the real sidecar's own
|
||||
* retained version from {@link #fetchingAMissingCrateRetainsItFromTheSourceRepositoryAndCountsItsBytes},
|
||||
* not a mock: {@code INTERNAL}, not {@code EXTERNAL} (a same-domain upstream, confirmed from
|
||||
* {@code CodeArtifactService}'s own real {@code PackageVersionOrigin.originType} mapping), with
|
||||
* {@code domainEntryPoint.repositoryName} naming the real source repository.
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void aRetainedVersionReportsAnInternalOriginNamingTheSourceRepository() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + DEST_REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("versions[0].version", equalTo(VERSION))
|
||||
.body("versions[0].origin.originType", equalTo("INTERNAL"))
|
||||
.body("versions[0].origin.domainEntryPoint.repositoryName", equalTo(SOURCE_REPO));
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every Kellnr container this class started: see {@code
|
||||
* CodeArtifactCargoDockerIntegrationTest}'s own javadoc note on why this is a real ordered
|
||||
* {@code @Test} and not {@code @AfterAll}.
|
||||
*/
|
||||
@Test
|
||||
@Order(7)
|
||||
void releasesEveryKellnrContainerThisClassStarted() {
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + SOURCE_REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + DEST_REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/** The real crates.io sparse-index bucketing rule for {@link #CRATE_NAME} (a 4+-character
|
||||
* name): first two, then next two, characters. */
|
||||
private static String sparseIndexPath(String crateName) {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
}
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link CodeArtifactCargoUpstreamRepositoryImporter}'s own decision logic, mirroring {@link
|
||||
* CodeArtifactNuGetUpstreamRepositoryImporterTest}'s own shape for {@code tryImport} plus
|
||||
* dedicated cases for {@code mergeUpstreamRepositoryVersions}. {@link KellnrSidecarClient} is
|
||||
* mocked, so no real Kellnr call ever happens here; its own wire contract has its own tests.
|
||||
*/
|
||||
class CodeArtifactCargoUpstreamRepositoryImporterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String OWNER = "123456789012";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String REPO_ID = "repo-id";
|
||||
private static final String UPSTREAM = "upstream";
|
||||
private static final String UPSTREAM_REPO_ID = "upstream-repo-id";
|
||||
private static final String PACKAGE_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
private static final String ASSET_NAME = "democrate-1.0.0.crate";
|
||||
private static final byte[] CRATE_CONTENT = "crate-content".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
|
||||
private static final long EPISODE_ID = 7L;
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private CodeArtifactCargoUpstreamRepositoryImporter importer;
|
||||
|
||||
private JsonNode indexLine;
|
||||
private byte[] upstreamIndexBytes;
|
||||
private byte[] publishMetadata;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionImporter = mock(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
importer = new CodeArtifactCargoUpstreamRepositoryImporter(service, kellnr, externalConnectionImporter);
|
||||
|
||||
indexLine = mapper.readTree("{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + VERSION
|
||||
+ "\",\"deps\":[],\"cksum\":\"abc\",\"features\":{},\"yanked\":false}");
|
||||
upstreamIndexBytes = indexLine.toString().getBytes(StandardCharsets.UTF_8);
|
||||
publishMetadata = ("{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + VERSION + "\"}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setUpstreams(List.of(UPSTREAM));
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), eq("INTERNAL_UPSTREAM"))).thenReturn(false);
|
||||
when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(List.of(UPSTREAM));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, UPSTREAM, kellnr))
|
||||
.thenReturn(UPSTREAM_REPO_ID);
|
||||
when(kellnr.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
// Unstubbed by default: requireContainerBackedVersionDownloadable is a void method a mock
|
||||
// never throws from unless told to, matching "the candidate's version is downloadable."
|
||||
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString())).thenReturn(42L);
|
||||
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString())).thenReturn(99L);
|
||||
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.UPSTREAM_REPOSITORY), anyLong()))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
when(kellnr.fetchSparseIndexRaw(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamIndexBytes));
|
||||
when(externalConnectionImporter.findIndexLine(upstreamIndexBytes, VERSION)).thenReturn(Optional.of(indexLine));
|
||||
when(externalConnectionImporter.metadataFromIndexLine(indexLine)).thenReturn(publishMetadata);
|
||||
when(kellnr.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION,
|
||||
ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(CRATE_CONTENT), CRATE_CONTENT.length)));
|
||||
when(service.stageStreamedAsset(any())).thenAnswer(invocation -> {
|
||||
RepositorySidecarManager.StreamedAsset streamed = invocation.getArgument(0);
|
||||
Path staged = Files.createTempFile("test-cargo-upstream-", ".crate");
|
||||
Files.write(staged, streamed.content().readAllBytes());
|
||||
return staged;
|
||||
});
|
||||
when(kellnr.publishRawWireBody(any(), any(), anyLong()))
|
||||
.thenReturn(new KellnrSidecarClient.KellnrPublishResult(200, "{\"warnings\":null}"));
|
||||
// Plain thenReturn, not an answer that invokes the write Runnable: re-stubbing this exact
|
||||
// call with the same matchers in an individual test (as one test below does) would invoke
|
||||
// whatever is currently stubbed as part of registering the new stub, running this one's
|
||||
// own side effect with a matcher object standing in for the real Runnable and throwing.
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsFromTheDirectUpstreamWhenNotFoundLocally() {
|
||||
// This one test cares that the real write actually ran (kellnr.publishRawWireBody),
|
||||
// unlike the others below that only care what retainAssetUnderVersionFence itself
|
||||
// reported: re-stubbed locally, not in setUp, since re-stubbing an exact-matcher stub a
|
||||
// second time invokes whatever is currently stubbed as part of registering the new one.
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenAnswer(invocation -> {
|
||||
Runnable write = invocation.getArgument(14);
|
||||
write.run();
|
||||
return new CodeArtifactService.AssetRetentionAttemptResult(true, true);
|
||||
});
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
|
||||
verify(kellnr).publishRawWireBody(eq(REPO_ID), any(), anyLong());
|
||||
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
"cargo", null, PACKAGE_NAME, 42L, REPO_ID);
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVersionNoUpstreamHoldsIsFetchedThroughAnUpstreamsExternalConnection() {
|
||||
when(kellnr.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
|
||||
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(true);
|
||||
|
||||
assertTrue(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION));
|
||||
InOrder order = inOrder(service, externalConnectionImporter);
|
||||
order.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME);
|
||||
order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION);
|
||||
order.verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID,
|
||||
PACKAGE_NAME, VERSION);
|
||||
order.verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
|
||||
verify(service, times(2)).resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, UPSTREAM, kellnr);
|
||||
verify(kellnr, times(2)).endUse(UPSTREAM_REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVersionArchivedAtTheUpstreamIsNotCopiedThroughItsExternalConnection() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
|
||||
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, UPSTREAM_REPO_ID);
|
||||
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
|
||||
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(true);
|
||||
|
||||
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION));
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
|
||||
verify(kellnr, times(2)).endUse(UPSTREAM_REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpstreamWithoutAnExternalConnectionIsNotAskedToFetch() {
|
||||
when(kellnr.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
|
||||
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION));
|
||||
verify(externalConnectionImporter, never()).tryImport(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesFromADeeperCandidateWhenCloserOnesDoNotHaveIt() {
|
||||
when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY))
|
||||
.thenReturn(List.of("near", "far"));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "near", kellnr))
|
||||
.thenReturn("near-id");
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "far", kellnr))
|
||||
.thenReturn("far-id");
|
||||
when(kellnr.packageVersionExists("near-id", DOMAIN, "near", null, PACKAGE_NAME, VERSION)).thenReturn(false);
|
||||
when(kellnr.packageVersionExists("far-id", DOMAIN, "far", null, PACKAGE_NAME, VERSION)).thenReturn(true);
|
||||
when(kellnr.fetchSparseIndexRaw("far-id", DOMAIN, "far", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamIndexBytes));
|
||||
when(kellnr.fetchPackageVersionAssetStreamed("far-id", DOMAIN, "far", null, PACKAGE_NAME, VERSION,
|
||||
ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(CRATE_CONTENT), CRATE_CONTENT.length)));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, "far", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
|
||||
verify(kellnr).endUse("near-id");
|
||||
verify(kellnr).endUse("far-id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCandidateBeingConcurrentlyDeletedIsSkippedRatherThanPropagatingTheFailure() {
|
||||
when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY))
|
||||
.thenReturn(List.of("vanishing", "healthy"));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "vanishing", kellnr))
|
||||
.thenThrow(new IllegalStateException("repository is being deleted"));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "healthy", kellnr))
|
||||
.thenReturn("healthy-id");
|
||||
when(kellnr.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(kellnr.fetchSparseIndexRaw("healthy-id", DOMAIN, "healthy", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamIndexBytes));
|
||||
when(kellnr.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION,
|
||||
ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(CRATE_CONTENT), CRATE_CONTENT.length)));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsAnArchivedCandidateAndContinuesToTheNextOne() {
|
||||
when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY))
|
||||
.thenReturn(List.of("archived", "healthy"));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "archived", kellnr))
|
||||
.thenReturn("archived-id");
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "healthy", kellnr))
|
||||
.thenReturn("healthy-id");
|
||||
when(kellnr.packageVersionExists("archived-id", DOMAIN, "archived", null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404))
|
||||
.when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, "archived", "cargo",
|
||||
null, PACKAGE_NAME, VERSION, "archived-id");
|
||||
when(kellnr.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(kellnr.fetchSparseIndexRaw("healthy-id", DOMAIN, "healthy", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamIndexBytes));
|
||||
when(kellnr.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION,
|
||||
ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(CRATE_CONTENT), CRATE_CONTENT.length)));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
|
||||
verify(kellnr).endUse("archived-id");
|
||||
verify(kellnr).endUse("healthy-id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenNoUpstreamsAreConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setUpstreams(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenInternalUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"INTERNAL_UPSTREAM")).thenReturn(true);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenNoCandidateHasTheVersionEither() {
|
||||
when(kellnr.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
|
||||
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(kellnr, never()).fetchSparseIndexRaw(eq(UPSTREAM_REPO_ID), anyString(), anyString(), anyString());
|
||||
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedUpstreamRepositoryOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION)).thenReturn(Optional.of(UPSTREAM));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(kellnr, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(),
|
||||
anyString(), anyString(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeReturnsUnchangedWhenNoUpstreamsAreConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setUpstreams(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
Optional<byte[]> alreadyMerged = Optional.of("existing".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, alreadyMerged);
|
||||
|
||||
assertEquals(alreadyMerged, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeReturnsUnchangedWhenInternalUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"INTERNAL_UPSTREAM")).thenReturn(true);
|
||||
Optional<byte[]> alreadyMerged = Optional.of("existing".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, alreadyMerged);
|
||||
|
||||
assertEquals(alreadyMerged, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeAddsUpstreamOnlyVersionLinesNotAlreadyKnown() {
|
||||
String alreadyKnownLine = "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"0.9.0\"}";
|
||||
Optional<byte[]> alreadyMerged = Optional.of(alreadyKnownLine.getBytes(StandardCharsets.UTF_8));
|
||||
when(externalConnectionImporter.indexLineVersion(alreadyKnownLine)).thenReturn(Optional.of("0.9.0"));
|
||||
when(externalConnectionImporter.indexLineVersion(indexLine.toString())).thenReturn(Optional.of(VERSION));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, alreadyMerged);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
String merged = new String(result.get(), StandardCharsets.UTF_8);
|
||||
assertTrue(merged.contains("0.9.0"));
|
||||
assertTrue(merged.contains(VERSION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeSkipsAVersionAlreadyKnownRatherThanDuplicatingIt() {
|
||||
when(externalConnectionImporter.indexLineVersion(indexLine.toString())).thenReturn(Optional.of(VERSION));
|
||||
Optional<byte[]> alreadyMerged = Optional.of(indexLine.toString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, alreadyMerged);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
String merged = new String(result.get(), StandardCharsets.UTF_8);
|
||||
assertEquals(1, merged.split("\n").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExcludesAVersionArchivedAtTheCandidate() {
|
||||
when(externalConnectionImporter.indexLineVersion(indexLine.toString())).thenReturn(Optional.of(VERSION));
|
||||
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
|
||||
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, UPSTREAM_REPO_ID);
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, Optional.empty());
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeReturnsEmptyWhenNothingIsKnownAnywhere() {
|
||||
when(kellnr.fetchSparseIndexRaw(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, PACKAGE_NAME)).thenReturn(Optional.empty());
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, Optional.empty());
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeChainsThroughACandidatesOwnExternalConnection() {
|
||||
String connectionOnlyLine = "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"2.0.0\"}";
|
||||
when(externalConnectionImporter.indexLineVersion(indexLine.toString())).thenReturn(Optional.of(VERSION));
|
||||
when(externalConnectionImporter.indexLineVersion(connectionOnlyLine)).thenReturn(Optional.of("2.0.0"));
|
||||
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
|
||||
byte[] withConnection = (indexLine.toString() + "\n" + connectionOnlyLine)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionImporter.mergeExternalVersions(eq(REGION), eq(DOMAIN), eq(OWNER), eq(UPSTREAM),
|
||||
eq(PACKAGE_NAME), any())).thenReturn(Optional.of(withConnection));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, Optional.empty());
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
String merged = new String(result.get(), StandardCharsets.UTF_8);
|
||||
assertTrue(merged.contains(VERSION));
|
||||
assertTrue(merged.contains("2.0.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code near} (first in search order) has no local copy but an external connection
|
||||
* advertising the same version with a different {@code cksum}; {@code far} (second) has its
|
||||
* own real local copy, with yet another {@code cksum}. {@code tryImport}'s own real walk
|
||||
* tries every candidate's own local copy, across the whole chain, before ever falling through
|
||||
* to any candidate's external connection, so a real download retains {@code far}'s own local
|
||||
* bytes, not {@code near}'s own external ones: the merge must advertise the same line a
|
||||
* download would actually retain, not whichever one it reaches first per candidate.
|
||||
*/
|
||||
@Test
|
||||
void mergeKeepsALaterCandidatesOwnLocalLineOverAnEarlierCandidatesOwnExternalConnectionLine() {
|
||||
when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY))
|
||||
.thenReturn(List.of("near", "far"));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "near", kellnr))
|
||||
.thenReturn("near-id");
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, "far", kellnr))
|
||||
.thenReturn("far-id");
|
||||
when(kellnr.fetchSparseIndexRaw("near-id", DOMAIN, "near", PACKAGE_NAME)).thenReturn(Optional.empty());
|
||||
String farLocalLine = "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + VERSION + "\",\"cksum\":\"far\"}";
|
||||
when(kellnr.fetchSparseIndexRaw("far-id", DOMAIN, "far", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(farLocalLine.getBytes(StandardCharsets.UTF_8)));
|
||||
when(externalConnectionImporter.indexLineVersion(farLocalLine)).thenReturn(Optional.of(VERSION));
|
||||
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, "near")).thenReturn(true);
|
||||
String nearConnectionLine = "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + VERSION
|
||||
+ "\",\"cksum\":\"near\"}";
|
||||
when(externalConnectionImporter.indexLineVersion(nearConnectionLine)).thenReturn(Optional.of(VERSION));
|
||||
when(externalConnectionImporter.mergeExternalVersions(eq(REGION), eq(DOMAIN), eq(OWNER), eq("near"),
|
||||
eq(PACKAGE_NAME), any())).thenReturn(Optional.of(nearConnectionLine.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, Optional.empty());
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
String merged = new String(result.get(), StandardCharsets.UTF_8);
|
||||
assertTrue(merged.contains("\"cksum\":\"far\""));
|
||||
assertFalse(merged.contains("\"cksum\":\"near\""));
|
||||
}
|
||||
|
||||
/**
|
||||
* A version only a candidate's own external connection offers, Archived there, must stay out
|
||||
* of the merge the same way a locally-contributed line already does: a real download through
|
||||
* that connection ({@link UpstreamExternalConnectionFetch}) already refuses an Archived
|
||||
* version at the candidate, so advertising it in the index here would offer a client
|
||||
* something a download could never actually retain.
|
||||
*/
|
||||
@Test
|
||||
void mergeExcludesAVersionArchivedAtTheCandidateEvenWhenOnlyItsExternalConnectionOffersIt() {
|
||||
when(kellnr.fetchSparseIndexRaw(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, PACKAGE_NAME))
|
||||
.thenReturn(Optional.empty());
|
||||
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
|
||||
when(externalConnectionImporter.indexLineVersion(indexLine.toString())).thenReturn(Optional.of(VERSION));
|
||||
when(externalConnectionImporter.mergeExternalVersions(eq(REGION), eq(DOMAIN), eq(OWNER), eq(UPSTREAM),
|
||||
eq(PACKAGE_NAME), any())).thenReturn(Optional.of(upstreamIndexBytes));
|
||||
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
|
||||
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, UPSTREAM_REPO_ID);
|
||||
|
||||
Optional<byte[]> result = importer.mergeUpstreamRepositoryVersions(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, Optional.empty());
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,18 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
@@ -57,4 +67,50 @@ public final class CodeArtifactRequests {
|
||||
.body("originConfiguration.restrictions.publish", equalTo(publish))
|
||||
.body("originConfiguration.restrictions.upstream", equalTo(upstream));
|
||||
}
|
||||
|
||||
/**
|
||||
* A real, minimal, valid {@code .crate}: a gzipped tarball with one real {@code Cargo.toml},
|
||||
* shared by every Cargo Docker integration test that needs to publish something Kellnr
|
||||
* genuinely accepts rather than a mocked unit test's own arbitrary bytes.
|
||||
*/
|
||||
public static byte[] cargoCrateBytes(String name, String version) {
|
||||
String cargoToml = "[package]\nname = \"" + name + "\"\nversion = \"" + version + "\"\nedition = \"2021\"\n";
|
||||
byte[] cargoTomlBytes = cargoToml.getBytes(StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out);
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name + "-" + version + "/Cargo.toml");
|
||||
entry.setSize(cargoTomlBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(cargoTomlBytes);
|
||||
tar.closeArchiveEntry();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* The real Cargo publish wire body (confirmed from the Cargo Book's own spec text and live
|
||||
* against a real Kellnr container): a 4-byte little-endian metadata length, the JSON metadata
|
||||
* itself (one real, non-empty dependency, to prove a native publish's own dependency list
|
||||
* survives the round trip untouched), then a 4-byte little-endian crate length and the crate
|
||||
* itself.
|
||||
*/
|
||||
public static byte[] cargoPublishBody(String name, String version, byte[] crateBytes) {
|
||||
String metadataJson = "{\"name\":\"" + name + "\",\"vers\":\"" + version + "\",\"deps\":["
|
||||
+ "{\"name\":\"real-dependency\",\"version_req\":\"^1.0\",\"features\":[],\"optional\":false,"
|
||||
+ "\"default_features\":true,\"target\":null,\"kind\":\"normal\",\"registry\":null}],"
|
||||
+ "\"features\":{},\"authors\":[],\"description\":\"a test crate\",\"documentation\":null,"
|
||||
+ "\"homepage\":null,\"readme\":null,\"readme_file\":null,\"keywords\":[],\"categories\":[],"
|
||||
+ "\"license\":\"MIT\",\"license_file\":null,\"repository\":null,\"badges\":{},\"links\":null}";
|
||||
byte[] metadata = metadataJson.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user