diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index fc19ada00a..35608f456b 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -91,13 +91,15 @@ connection), the standard `.pom`/`.jar`/`-javadoc.jar`/`-sources.jar` set import standard-named request, a non-standard asset name imported individually and only on demand, a retained version's own origin checked against any later asset request for the same version (rejecting one that would mix in a different connection's bytes), and a direct `mvn deploy` of a -version already present in the connection rejected with `ConflictException`. See the -upstream-resolution limitation further down for exactly what this does not yet cover (a -repository-to-repository `upstreams` chain, for any format including Maven). npm's own `public:npmjs` -external connection and NuGet's own `public:nuget-org` one resolve the same way, each against its -own format's one real public connection and documented rules; see their own repository endpoint -sections and the known-limitations entry below for exactly how. pypi's own external connection does -not yet. +version already present in the connection rejected with `ConflictException`. npm's own +`public:npmjs` external connection, NuGet's own `public:nuget-org` one, and pypi's own +`public:pypi` one all resolve the same way, each against its own format's one real public +connection and documented rules; see their own repository endpoint sections and the +known-limitations entry below for exactly how. A repository-to-repository `upstreams` chain +resolves the same way too, for every format including Maven, reusing the same mechanism against +another repository in the domain instead of a real public registry; see the known-limitations +entry below for the real behavioral differences (Archived/Disposed propagation, and a candidate +upstream's own real content only, not its own external connection). `PublishPackageVersion` creates a package version in the `Unfinished` state when the `unfinished` flag is set, and `Published` otherwise. While still `Unfinished`, publishing a new asset name is @@ -276,9 +278,6 @@ state. ## Known limitations -- **Upstream cycles are not rejected.** `CreateRepository`/`UpdateRepository` reject a repository - naming itself as its own upstream and require each named upstream to already exist, but a longer - cycle (repository A has B as an upstream, B has A) is not detected. - **`DeleteRepository` does not check whether other repositories still reference it as an upstream.** Deleting a repository leaves any repository that named it as an upstream pointing at one that no longer exists. @@ -319,10 +318,13 @@ state. time, since neither sidecar can answer for one after the fact (`GetPackageVersionReadme`'s own constraint, described earlier in this document); `nuget` needs no equivalent step, since `GetPackageVersionReadme` already answers it live from the `.nupkg` this action already copies - in full. `includeFromUpstream` is accepted but has no effect: it names a source repository's - own upstream-repository chain specifically, which this emulator does not resolve for any - format yet (see the upstream-resolution limitation below). Maven's own external-connection - retention is a different mechanism and does not change this. + in full. `includeFromUpstream` (default `false`) is real: on a miss against the literal source + repository, it searches that repository's own `upstreams` chain, transitively and in priority + order, for the first repository with a usable (not Archived, not Disposed) copy of the + version, and copies from there instead, for every format. A version resolved this way records + its real origin (the actual, possibly several-hops-deep source repository, not the one named in + the request) the same way the native-protocol upstream-repository retention below does; a + version found directly at the named source repository records no new claim. - **`CopyPackageVersions` holds this service's one write lock for the whole call, including the disk staging and sidecar streaming a large batch now needs.** Every package-mutating method here (`CreateDomain`, `PublishPackageVersion`, `DeletePackageVersions`, ...) shares one lock, so @@ -385,11 +387,12 @@ state. would mean isolating each sidecar on its own Docker network reachable only from Floci's own process, a change that would need to apply uniformly across all four sidecar-backed formats, not a one-off fix to any single proxy. -- **The Maven, NuGet, and npm endpoints' own external connections resolve; pypi's does not.** - 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. Floci's Maven endpoint - does this for a direct external connection to one of the 5 real public Maven repositories +- **Every native endpoint's own external connections and repository-to-repository upstreams both + resolve, for all four formats.** 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 + for a direct external connection to one of the 5 real public Maven repositories (`public:maven-central`, `public:maven-clojars`, `public:maven-commonsware`, `public:maven-googleandroid`, `public:maven-gradleplugins`): a GET/HEAD miss fetches and retains the package version from the real public repository, following AWS's own documented @@ -407,12 +410,28 @@ state. knows (never written back to Verdaccio itself, since its publish protocol has no way to record a version's metadata without that version's real tarball bytes in the same call), and a tarball download for a version not yet genuinely retained triggers the real fetch and retention, using - the same claim/fence/origin-tracking machinery. None of this applies to a repository-to- - repository upstream (`UpdateRepository`'s `upstreams`, for any format including Maven, NuGet, - and npm, which is a materially different mechanism, not yet built) or to pypi's own external - connection, which still 404s exactly as before: the pypi proxy's pypiserver container is started - with `--disable-fallback`, specifically so it never silently redirects a missing package to the - real, public PyPI. + the same claim/fence/origin-tracking machinery. pypi's own `public:pypi` external connection + works the same way again, importing every real asset of a resolved version together (AWS's own + documented "will import all the assets in that package version," unlike npm/NuGet's one-asset + rule), with the requested file imported synchronously and its siblings handed to a background + 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 (an upstream's own upstreams are + searched too, breadth-first, matching AWS's documented priority order) and not just its direct + list, for the first repository with a usable copy. Two real differences from the + external-connection case: an Archived or Disposed version *at the resolved upstream repository + itself* is skipped, the walk continuing to the next candidate, since a same-domain upstream has + a real CodeArtifact-shaped status to check that a public registry never does; and each candidate + is checked only for what it already has retained, not what it could itself still pull from its + own configured external connection (AWS documents a downstream request chaining through an + upstream's own external connection too, so a version a candidate upstream hasn't fetched yet + from its own `public:*` connection stays a miss here, even though AWS would resolve it). Since a + same-domain upstream read never leaves this process, pypi's own version 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 imported 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 @@ -465,11 +484,12 @@ state. begin with; Maven, npm, pypi, and nuget publishes go through their own native wire protocol (`mvn deploy`, `npm publish`, `twine upload`, `nuget push`) directly against the repository endpoint, which does not yet check this setting. `upstream` is stored and reported faithfully for every - format; it gates Maven's own external-connection retention (see the upstream-resolution - limitation above) but is not enforced anywhere else, since Floci has no other upstream - ingestion path to block yet. `CopyPackageVersions` deliberately does not check `publish: BLOCK` - either, for any format: the User Guide's own definition of that control scopes it to direct - publish "using package managers or similar tools," a mechanism Copy is not. + format, and gates every format's own external-connection retention and repository-to-repository + upstream retention (both resolve for 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 + them to direct publish/retention "using package managers or similar tools," a mechanism Copy is + not. - **`DescribeDomain`'s `assetSizeBytes` only counts what was published after this field started being computed.** Generic-format bytes are summed live from the still-existing `PublishPackageVersion` records, so they're always current. Maven, npm, pypi, and nuget have no @@ -500,17 +520,18 @@ state. too, which this correctly attributes to the real artifact; only the rarer, version-scoped snapshot form gets a package name this way. The bytes are still counted toward the domain total either way, just under an internal accounting bucket nothing else ever looks up by name. -- **Package groups enforce `PUBLISH` and `EXTERNAL_UPSTREAM`; `INTERNAL_UPSTREAM` is stored and - resolved but never gates anything.** `PUBLISH` is wired into the one package-level origin check - every direct-publish path already shares (`PublishPackageVersion`'s own `generic`-format path - and every native proxy controller's own publish guard — `mvn deploy`, `npm publish`, `twine - upload`, `nuget push` — alike), and every format's external-connection retention (Maven, npm, - pypi, NuGet) is wired to the resolved `EXTERNAL_UPSTREAM` mode, both following the "`BLOCK` - always wins over `ALLOW`" interaction between a package's own origin configuration and its - associated group's, and both blocking a weak pattern match outright regardless of the group's - configured mode. `INTERNAL_UPSTREAM` has nothing to gate yet: it governs a repository-to- - repository upstream chain (`UpdateRepository`'s `upstreams`), which this emulator does not - simulate for any format. +- **Package groups enforce `PUBLISH`, `EXTERNAL_UPSTREAM`, and `INTERNAL_UPSTREAM`.** `PUBLISH` is + wired into the one package-level origin check every direct-publish path already shares + (`PublishPackageVersion`'s own `generic`-format path and every native proxy controller's own + publish guard, `mvn deploy`/`npm publish`/`twine upload`/`nuget push` alike); every + format's external-connection retention (Maven, npm, pypi, NuGet) 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 + way. All three follow the "`BLOCK` always wins over `ALLOW`" interaction between a package's own + origin configuration and its associated group's, and all three block a weak pattern match + outright regardless of the group's configured mode (the User Guide's own pattern-matching page + states this generically, "pulled from upstreams or published," not scoped to one restriction + type by name). - **Package group weak-match normalization does not model Unicode confusable characters.** The User Guide's own "Additional variations" section mentions visually-similar characters from different alphabets only in passing, with no concrete testable rule; this emulator's weak match diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java index a22eadfac1..428a234e44 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactController.java @@ -502,6 +502,8 @@ public class CodeArtifactController { ObjectNode domainEntryPoint = origin.putObject("domainEntryPoint"); if (summary.externalConnectionName() != null) { domainEntryPoint.put("externalConnectionName", summary.externalConnectionName()); + } else if (summary.upstreamRepositoryName() != null) { + domainEntryPoint.put("repositoryName", summary.upstreamRepositoryName()); } else { domainEntryPoint.put("repositoryName", repository); } diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java index b22ab69f2b..bee2d89fec 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenController.java @@ -49,13 +49,16 @@ public class CodeArtifactMavenController { private final CodeArtifactService service; private final ReposiliteSidecarClient reposilite; private final CodeArtifactMavenExternalConnectionImporter externalConnectionImporter; + private final CodeArtifactMavenUpstreamRepositoryImporter upstreamRepositoryImporter; @Inject public CodeArtifactMavenController(CodeArtifactService service, ReposiliteSidecarClient reposilite, - CodeArtifactMavenExternalConnectionImporter externalConnectionImporter) { + CodeArtifactMavenExternalConnectionImporter externalConnectionImporter, + CodeArtifactMavenUpstreamRepositoryImporter upstreamRepositoryImporter) { this.service = service; this.reposilite = reposilite; this.externalConnectionImporter = externalConnectionImporter; + this.upstreamRepositoryImporter = upstreamRepositoryImporter; } @PUT @@ -232,9 +235,14 @@ public class CodeArtifactMavenController { return Response.status(Response.Status.NOT_FOUND).build(); } Optional artifact = reposilite.fetchArtifactStreamed(scope.repoId(), gav); + // 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 (see CodeArtifactMavenUpstreamRepositoryImporter's own javadoc). if ((artifact.isEmpty() || isBareMavenMetadataFile(gav)) - && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository, - scope.repoId(), gav)) { + && (externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository, + scope.repoId(), gav) + || upstreamRepositoryImporter.tryImport(scope.region(), domain, scope.owner(), repository, + scope.repoId(), gav))) { artifact.ifPresent(a -> StreamingResponses.closeQuietly(a.content())); artifact = reposilite.fetchArtifactStreamed(scope.repoId(), gav); } @@ -254,8 +262,10 @@ public class CodeArtifactMavenController { // ever gets the chance to retain it. boolean exists = reposilite.artifactExists(scope.repoId(), gav); if ((!exists || isBareMavenMetadataFile(gav)) - && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository, - scope.repoId(), gav)) { + && (externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository, + scope.repoId(), gav) + || upstreamRepositoryImporter.tryImport(scope.region(), domain, scope.owner(), repository, + scope.repoId(), gav))) { exists = reposilite.artifactExists(scope.repoId(), gav); } return exists ? Response.ok().build() : Response.status(Response.Status.NOT_FOUND).build(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java index 9dc7bd4b3e..ec5330d7e4 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java @@ -126,7 +126,7 @@ public class CodeArtifactMavenExternalConnectionImporter { return false; } if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, - packageName)) { + packageName, "EXTERNAL_UPSTREAM")) { return false; } @@ -152,7 +152,8 @@ public class CodeArtifactMavenExternalConnectionImporter { // check and both write real bytes before either recorded anything), and for why its own // episodeId, not just the connection name, is what finally identifies this exact claim. CodeArtifactService.MavenClaimOutcome claim = service.claimMavenRetainedVersionOrigin(region, domain, owner, - repository, namespace, packageName, version, externalConnectionName, fenceSnapshot); + repository, namespace, packageName, version, externalConnectionName, + RetentionOriginKind.EXTERNAL_CONNECTION, fenceSnapshot); if (!claim.claimed()) { return false; } @@ -339,7 +340,7 @@ public class CodeArtifactMavenExternalConnectionImporter { return false; } if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, - packageName)) { + packageName, "EXTERNAL_UPSTREAM")) { return false; } long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, @@ -367,7 +368,8 @@ public class CodeArtifactMavenExternalConnectionImporter { } }; return service.mergeMavenMetadataUnderPackageFence(region, domain, owner, repository, namespace, - packageName, packageFenceSnapshot, reposilite, repoId, fetched.get().content(), versionAllowed); + packageName, packageFenceSnapshot, reposilite, repoId, fetched.get().content(), versionAllowed, + false); } private String mavenExternalConnectionName(String region, String domain, String owner, String repository) { diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporter.java new file mode 100644 index 0000000000..3120027c99 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporter.java @@ -0,0 +1,328 @@ +package io.floci.aws.services.codeartifact; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.StreamingResponses; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +/** + * {@code 16f-UPSTREAM-REPO}: retains a Maven package version from another repository in the same + * domain, named in {@code repository}'s own {@code upstreams} list (distinct from, and mutually + * exclusive with, {@link CodeArtifactMavenExternalConnectionImporter}'s real public registries). + * Reuses the exact claim/fence mechanism {@link CodeArtifactService#claimMavenRetainedVersionOrigin} + * already provides (see its own javadoc for the full race this closes), with real differences from + * the external-connection case: + * + * + * + *

Standard-sibling-asset grouping (pom/jar/javadoc/sources imported together for a standard + * asset name) carries over verbatim from the external-connection importer: it is Maven-protocol + * behavior, not specific to where the bytes came from. + */ +@ApplicationScoped +public class CodeArtifactMavenUpstreamRepositoryImporter { + + private static final Logger LOG = Logger.getLogger(CodeArtifactMavenUpstreamRepositoryImporter.class); + + private final CodeArtifactService service; + private final ReposiliteSidecarClient reposilite; + + @Inject + public CodeArtifactMavenUpstreamRepositoryImporter(CodeArtifactService service, + ReposiliteSidecarClient reposilite) { + this.service = service; + this.reposilite = reposilite; + } + + /** + * Mirrors {@link CodeArtifactMavenExternalConnectionImporter#tryImport}'s own contract exactly, + * sourced from the first eligible repository in {@code repository}'s own upstream chain instead + * of a real public registry. A bare group/artifact-level {@code maven-metadata.xml} (no version + * segment in {@code gav}) is resolved by {@link #tryImportUpstreamMetadata} instead, the same + * split that importer's own javadoc documents. + */ + public boolean tryImport(String region, String domain, String owner, String repository, String repoId, + String gav) { + Optional coordinate = CodeArtifactMavenController.parseNamespaceAndPackageName(gav); + if (coordinate.isEmpty()) { + return false; + } + String namespace = coordinate.get()[0]; + String packageName = coordinate.get()[1]; + String version = coordinate.get()[2]; + if (version == null) { + return gav.endsWith("/maven-metadata.xml") && tryImportUpstreamMetadata(region, domain, owner, + repository, repoId, namespace, packageName); + } + + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, packageName, + "INTERNAL_UPSTREAM")) { + return false; + } + + String upstreamRepository = null; + String upstreamRepoId = null; + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("maven", region, domain, owner, candidate, + reposilite); + } 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; + } + // Held past this loop, for the winning candidate only, until the claim/fetch/write + // below are entirely done with it (see the try/finally right after this loop). + boolean eligible = false; + try { + if (!reposilite.artifactExists(candidateRepoId, gav)) { + continue; + } + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "maven", + namespace, packageName, version, candidateRepoId); + } catch (AwsException e) { + // Archived or Disposed at this candidate: treated 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) { + reposilite.endUse(candidateRepoId); + } + } + } + if (upstreamRepository == null) { + return false; + } + + try { + return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, gav, namespace, + packageName, version, upstreamRepository, upstreamRepoId); + } finally { + reposilite.endUse(upstreamRepoId); + } + } + + private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository, + String repoId, String gav, String namespace, String packageName, String version, + String upstreamRepository, String upstreamRepoId) { + // Snapshotted before the claim and the real writes below, not after, the same ordering + // CodeArtifactMavenExternalConnectionImporter#tryImport already relies on. + long fenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, "maven", + namespace, packageName); + long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository, + "maven", namespace, packageName, version); + CodeArtifactService.MavenClaimOutcome claim = service.claimMavenRetainedVersionOrigin(region, domain, owner, + repository, namespace, packageName, version, upstreamRepository, + RetentionOriginKind.UPSTREAM_REPOSITORY, fenceSnapshot); + if (!claim.claimed()) { + return false; + } + + int lastSlash = gav.lastIndexOf('/'); + String directory = gav.substring(0, lastSlash + 1); + String filename = gav.substring(lastSlash + 1); + List standardNames = standardAssetFilenames(packageName, version); + List candidateFilenames = standardNames.contains(filename) ? standardNames : List.of(filename); + + boolean importedRequestedAsset = false; + boolean importedAny = false; + try { + for (String candidateFilename : candidateFilenames) { + String candidateGav = directory + candidateFilename; + Optional fetched; + try { + fetched = reposilite.fetchArtifactStreamed(upstreamRepoId, candidateGav); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} from upstream repository {1} while retaining a Maven " + + "release through a same-domain upstream; skipping this candidate.", candidateGav, + upstreamRepository); + continue; + } + if (fetched.isEmpty()) { + continue; + } + // ReposiliteSidecarClient.StreamedArtifact, not RepositorySidecarManager + // .StreamedAsset: Maven never routes through that shared interface (it speaks + // directly to ReposiliteSidecarClient everywhere else too), so this stages and + // closes the stream itself instead of reusing CodeArtifactService's own + // stageStreamedAsset, which only accepts the other record type. + Path staged; + try { + staged = service.stageAssetBody(fetched.get().content()); + } finally { + StreamingResponses.closeQuietly(fetched.get().content()); + } + // Not fetched.get().contentLength(): that's -1 whenever the upstream sidecar's own + // response carried no Content-Length header (see that record's own javadoc), 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; + try { + contentLength = Files.size(staged); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + try { + // The fence check and the real write happen inside the very same synchronized + // call DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions + // already hold across their own entire operation, so a write here and one of + // those four operations can never interleave. + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence( + region, domain, owner, repository, namespace, packageName, version, + versionFenceSnapshot, fenceSnapshot, claim.episodeId(), reposilite, repoId, candidateGav, + staged, contentLength); + if (!result.fenceMatched()) { + // The version itself is gone: every later candidate filename in this same + // attempt would fail the exact same way, so none of them are attempted. + break; + } + ReposiliteSidecarClient.DeployOutcome outcome = result.outcome(); + if (outcome == null || (outcome.status() != 200 && outcome.status() != 201)) { + continue; + } + importedAny = true; + if (candidateFilename.equals(filename)) { + importedRequestedAsset = true; + } + } finally { + service.deleteStagedAssetBody(staged); + } + } + } finally { + if (importedAny) { + service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "maven", namespace, + packageName, fenceSnapshot); + } + service.finishMavenRetainedVersionOriginAttempt(region, domain, owner, repository, namespace, + packageName, version, claim.episodeId(), importedAny); + } + return importedRequestedAsset; + } + + /** + * Mirrors {@link CodeArtifactMavenExternalConnectionImporter#tryImportMetadata}'s own contract: + * merges in whichever release versions the first eligible upstream candidate's own {@code + * maven-metadata.xml} names, so a version range or a Gradle dynamic version can resolve against + * an upstream-configured repository too. The first candidate that responds with any metadata at + * all wins (parallel to the asset case's "first match wins"); every version it names is still + * individually checked for Archived/Disposed status, at both {@code repository} itself (the + * existing protection the external-connection importer's own javadoc explains) and the winning + * candidate (new: a real upstream repository has a real status to check, unlike a public + * registry). + */ + private boolean tryImportUpstreamMetadata(String region, String domain, String owner, String repository, + String repoId, String namespace, String packageName) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, packageName, + "INTERNAL_UPSTREAM")) { + return false; + } + long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, + "maven", namespace, packageName); + String metadataGav = namespace.replace('.', '/') + "/" + packageName + "/maven-metadata.xml"; + + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("maven", region, domain, owner, candidate, + reposilite); + } catch (RuntimeException e) { + // The candidate is being concurrently deleted/released: treated exactly like + // "nothing there" below. + continue; + } + // Nothing escapes this iteration (the merge below both reads and writes entirely + // within this same candidate's lease), so it is always released before moving on, + // whether this candidate won or not. + try { + Optional fetched; + try { + fetched = reposilite.fetchArtifactStreamed(candidateRepoId, metadataGav); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0}/{1}''s maven-metadata.xml from upstream repository {2} while " + + "resolving its versions; trying the next candidate.", namespace, packageName, + candidate); + continue; + } + if (fetched.isEmpty()) { + continue; + } + byte[] metadataXml; + try (InputStream in = fetched.get().content()) { + metadataXml = in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + Predicate versionAllowed = version -> { + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "maven", + namespace, packageName, version, repoId); + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "maven", + namespace, packageName, version, candidateRepoId); + return true; + } catch (AwsException e) { + return false; + } + }; + // If this candidate's own metadata names nothing eligible (every version Archived + // or Disposed at either side), it is exactly like the asset case's Archived/ + // Disposed candidate: move on to the next one instead of stopping the search here. + if (ReposiliteSidecarClient.eligibleReleaseVersions(metadataXml, versionAllowed, true).isEmpty()) { + continue; + } + return service.mergeMavenMetadataUnderPackageFence(region, domain, owner, repository, namespace, + packageName, packageFenceSnapshot, reposilite, repoId, metadataXml, versionAllowed, true); + } finally { + reposilite.endUse(candidateRepoId); + } + } + return false; + } + + private static List standardAssetFilenames(String artifactId, String version) { + String base = artifactId + "-" + version; + return List.of(base + ".pom", base + ".jar", base + "-javadoc.jar", base + "-sources.jar"); + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java index 8d80dddb54..fe2596fd90 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java @@ -74,6 +74,7 @@ public class CodeArtifactNpmDataPlane { private final CodeArtifactService service; private final VerdaccioSidecarClient verdaccioClient; private final CodeArtifactNpmExternalConnectionImporter externalConnectionImporter; + private final CodeArtifactNpmUpstreamRepositoryImporter upstreamRepositoryImporter; private final ServiceConfigAccess serviceConfigAccess; private final Vertx vertx; private final HttpClient proxyClient; @@ -84,10 +85,12 @@ public class CodeArtifactNpmDataPlane { @Inject public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient, CodeArtifactNpmExternalConnectionImporter externalConnectionImporter, + CodeArtifactNpmUpstreamRepositoryImporter upstreamRepositoryImporter, ServiceConfigAccess serviceConfigAccess, Vertx vertx, ObjectMapper mapper) { this.service = service; this.verdaccioClient = verdaccioClient; this.externalConnectionImporter = externalConnectionImporter; + this.upstreamRepositoryImporter = upstreamRepositoryImporter; this.serviceConfigAccess = serviceConfigAccess; this.vertx = vertx; this.proxyClient = vertx.createHttpClient(new HttpClientOptions() @@ -174,9 +177,8 @@ public class CodeArtifactNpmDataPlane { PackageIdentity identity = packumentTarget.get(); boolean fullMetadata = !acceptsCorgi(context.request().getHeader("Accept")); use.retain(); - vertx.executeBlocking(promise -> promise.complete(externalConnectionImporter.mergedPackument( - tokenScope.region(), npmRequest.domain(), tokenScope.owner(), npmRequest.repository(), repoId, - identity.namespace(), identity.packageName(), fullMetadata).orElse(null)), false).onComplete( + vertx.executeBlocking(promise -> promise.complete(mergedPackumentFromEitherSource(tokenScope, + npmRequest, repoId, identity, fullMetadata)), false).onComplete( mergeResult -> { if (mergeResult.succeeded() && mergeResult.result() != null) { context.request().resume(); @@ -191,6 +193,24 @@ public class CodeArtifactNpmDataPlane { proceedToProxy(context, npmRequest, repoId, tokenScope, use); } + /** + * Tries {@code externalConnectionImporter}'s own merge first, then {@code + * upstreamRepositoryImporter}'s: a repository has either an external connection or upstreams, + * never both, so at most one of these two ever finds anything, and the other's own no-op is a + * single cheap in-memory check (see {@code CodeArtifactNpmUpstreamRepositoryImporter}'s own + * javadoc). Runs on the blocking worker thread {@link #handle}'s own {@code executeBlocking} + * call already dispatched to; both calls only ever touch local sidecar state here, never a + * real external network call for the upstream one. + */ + private ObjectNode mergedPackumentFromEitherSource(AuthorizationTokenScope tokenScope, NpmRequest npmRequest, + String repoId, PackageIdentity identity, boolean fullMetadata) { + return externalConnectionImporter.mergedPackument(tokenScope.region(), npmRequest.domain(), + tokenScope.owner(), npmRequest.repository(), repoId, identity.namespace(), identity.packageName(), + fullMetadata).or(() -> upstreamRepositoryImporter.mergedPackument(tokenScope.region(), + npmRequest.domain(), tokenScope.owner(), npmRequest.repository(), repoId, + identity.namespace(), identity.packageName())).orElse(null); + } + /** * {@code packumentTarget}'s own fallback, and the only path for every request that isn't a * bare packument GET to begin with: proxies straight to Verdaccio, importing a missing @@ -307,8 +327,13 @@ public class CodeArtifactNpmDataPlane { target.identity().namespace(), bareName, version)) { return; } - externalConnectionImporter.tryImportAsset(tokenScope.region(), npmRequest.domain(), tokenScope.owner(), - npmRequest.repository(), repoId, target.identity().namespace(), bareName, version, filename); + // A repository has either an external connection or upstreams, never both: at most one + // of these two ever does real work (see mergedPackumentFromEitherSource's own javadoc). + if (!externalConnectionImporter.tryImportAsset(tokenScope.region(), npmRequest.domain(), tokenScope.owner(), + npmRequest.repository(), repoId, target.identity().namespace(), bareName, version, filename)) { + upstreamRepositoryImporter.tryImportAsset(tokenScope.region(), npmRequest.domain(), tokenScope.owner(), + npmRequest.repository(), repoId, target.identity().namespace(), bareName, version, filename); + } } /** diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java index 38fd65d624..972e5a38bc 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporter.java @@ -130,7 +130,8 @@ public class CodeArtifactNpmExternalConnectionImporter { if (externalConnectionName == null) { return Optional.empty(); } - if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) { + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName, + "EXTERNAL_UPSTREAM")) { return Optional.empty(); } Optional fetched; @@ -265,7 +266,8 @@ public class CodeArtifactNpmExternalConnectionImporter { if (externalConnectionName == null) { return false; } - if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) { + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName, + "EXTERNAL_UPSTREAM")) { return false; } @@ -275,7 +277,7 @@ public class CodeArtifactNpmExternalConnectionImporter { "npm", namespace, packageName, version); CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, domain, owner, repository, "npm", namespace, packageName, version, externalConnectionName, - packageFenceSnapshot); + RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot); if (!claim.claimed()) { return false; } diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporter.java new file mode 100644 index 0000000000..b908ca6b05 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporter.java @@ -0,0 +1,346 @@ +package io.floci.aws.services.codeartifact; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import 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.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * {@code 16f-UPSTREAM-REPO}: retains npm packages and package versions from another repository in + * the same domain, named in {@code repository}'s own {@code upstreams} list (distinct from, and + * mutually exclusive with, {@link CodeArtifactNpmExternalConnectionImporter}'s real public + * registry). Reuses the exact claim/fence mechanism {@link + * CodeArtifactService#claimRetainedVersionOrigin} already provides, with real differences from the + * external-connection case: + * + *

+ */ +@ApplicationScoped +public class CodeArtifactNpmUpstreamRepositoryImporter { + + private static final Logger LOG = Logger.getLogger(CodeArtifactNpmUpstreamRepositoryImporter.class); + + /** Mirrors {@code CodeArtifactNpmExternalConnectionImporter}'s own identical list. */ + private static final List PACKAGE_LEVEL_DESCRIPTIVE_FIELDS = List.of("description", "readme", + "readmeFilename", "homepage", "license", "keywords", "author", "repository", "bugs", "maintainers"); + + private final CodeArtifactService service; + private final VerdaccioSidecarClient verdaccio; + private final ObjectMapper mapper; + + @Inject + public CodeArtifactNpmUpstreamRepositoryImporter(CodeArtifactService service, VerdaccioSidecarClient verdaccio, + ObjectMapper mapper) { + this.service = service; + this.verdaccio = verdaccio; + this.mapper = mapper; + } + + /** + * Mirrors {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument}'s own contract, + * sourced from the first eligible upstream candidate's own stored packument instead of a real + * registry fetch. Always merges every package-level descriptive field the candidate's document + * has (there is no abbreviated-vs-full distinction for a same-domain read, see this class's own + * javadoc). + */ + public Optional mergedPackument(String region, String domain, String owner, String repository, + String repoId, String namespace, String packageName) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return Optional.empty(); + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName, + "INTERNAL_UPSTREAM")) { + return Optional.empty(); + } + + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("npm", region, domain, owner, candidate, + verdaccio); + } catch (RuntimeException e) { + // The candidate is being concurrently deleted/released: treated exactly like + // "nothing there" below. + continue; + } + try { + String candidateBaseUrl = verdaccio.ensureReady(candidateRepoId, + verdaccio.publicUrl(domain, candidate)); + JsonNode external = verdaccio.fetchPackageDocument(candidateBaseUrl, namespace, packageName) + .orElse(null); + if (external == null) { + continue; + } + Optional merged = mergeFromCandidate(region, domain, owner, repository, repoId, + namespace, packageName, candidate, candidateRepoId, external); + if (merged.isPresent()) { + return merged; + } + } finally { + // Nothing escapes this iteration (the returned node is a plain JSON merge result, + // not this candidate's own id), so the lease is always released before moving on, + // whether this candidate won or not. + verdaccio.endUse(candidateRepoId); + } + } + return Optional.empty(); + } + + private Optional mergeFromCandidate(String region, String domain, String owner, String repository, + String repoId, String namespace, String packageName, String candidate, String candidateRepoId, + JsonNode external) { + String publicBaseUrl = verdaccio.publicUrl(domain, repository); + String containerBaseUrl = verdaccio.ensureReady(repoId, publicBaseUrl); + JsonNode local = verdaccio.fetchPackageDocument(containerBaseUrl, namespace, packageName).orElse(null); + ObjectNode merged = local != null ? ((ObjectNode) local).deepCopy() : mapper.createObjectNode(); + String npmName = namespace == null ? packageName : "@" + namespace + "/" + packageName; + merged.put("name", npmName); + if (!merged.has("_id")) { + merged.put("_id", npmName); + } + boolean addedAnything = false; + for (String field : PACKAGE_LEVEL_DESCRIPTIVE_FIELDS) { + if (!merged.has(field) && external.has(field)) { + merged.set(field, external.get(field)); + addedAnything = true; + } + } + if (!merged.has("description")) { + merged.put("description", ""); + } + ObjectNode versions = merged.has("versions") && merged.get("versions").isObject() + ? (ObjectNode) merged.get("versions") : merged.putObject("versions"); + ObjectNode distTags = merged.has("dist-tags") && merged.get("dist-tags").isObject() + ? (ObjectNode) merged.get("dist-tags") : merged.putObject("dist-tags"); + + for (Map.Entry entry : external.path("versions").properties()) { + String version = entry.getKey(); + if (versions.has(version)) { + continue; + } + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "npm", + namespace, packageName, version, repoId); + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "npm", + namespace, packageName, version, candidateRepoId); + } catch (AwsException e) { + continue; + } + ObjectNode versionDoc = ((ObjectNode) entry.getValue()).deepCopy(); + versionDoc.put("name", npmName); + versionDoc.put("version", version); + ObjectNode dist = versionDoc.has("dist") && versionDoc.get("dist").isObject() + ? (ObjectNode) versionDoc.get("dist") : versionDoc.putObject("dist"); + dist.put("tarball", publicBaseUrl + packagePath(namespace, packageName) + "/-/" + + tarballFilename(packageName, version)); + versions.set(version, versionDoc); + addedAnything = true; + } + for (Map.Entry tag : external.path("dist-tags").properties()) { + String tagVersion = tag.getValue().asText(null); + if (tagVersion == null || !versions.has(tagVersion)) { + continue; + } + String currentLocalVersion = distTags.path(tag.getKey()).asText(null); + boolean currentlyUnset = currentLocalVersion == null; + boolean currentlyPointsAtARetainedVersion = currentLocalVersion != null + && (service.retainedVersionOriginConnection(region, domain, owner, repository, "npm", namespace, + packageName, currentLocalVersion).isPresent() + || service.retainedUpstreamRepositoryOrigin(region, domain, owner, repository, "npm", + namespace, packageName, currentLocalVersion).isPresent()); + if (currentlyUnset || currentlyPointsAtARetainedVersion) { + distTags.set(tag.getKey(), tag.getValue()); + addedAnything = true; + } + } + return addedAnything ? Optional.of(merged) : Optional.empty(); + } + + /** + * Mirrors {@link CodeArtifactNpmExternalConnectionImporter#tryImportAsset}'s own contract. + * {@code version} is already resolved by the caller (npm's download route names it directly, + * unlike pypi's), so no candidate-version resolution is needed here, only which candidate has + * it. + */ + public boolean tryImportAsset(String region, String domain, String owner, String repository, String repoId, + String namespace, String packageName, String version, String assetName) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName, + "INTERNAL_UPSTREAM")) { + return false; + } + + String upstreamRepository = null; + String upstreamRepoId = null; + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("npm", region, domain, owner, candidate, + verdaccio); + } 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; + } + // Held past this loop, for the winning candidate only, until the claim/fetch/write + // below are entirely done with it (see the try/finally right after this loop). + boolean eligible = false; + try { + if (!verdaccio.packageVersionExists(candidateRepoId, domain, candidate, namespace, packageName, + version)) { + continue; + } + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "npm", + namespace, packageName, version, candidateRepoId); + } catch (AwsException e) { + // Archived or Disposed at this candidate: treated 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) { + verdaccio.endUse(candidateRepoId); + } + } + } + if (upstreamRepository == null) { + return false; + } + + try { + return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, namespace, packageName, + version, assetName, upstreamRepository, upstreamRepoId); + } finally { + verdaccio.endUse(upstreamRepoId); + } + } + + private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository, + String repoId, String namespace, String packageName, String version, String assetName, + String upstreamRepository, String upstreamRepoId) { + long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, + "npm", namespace, packageName); + long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository, + "npm", namespace, packageName, version); + CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, + domain, owner, repository, "npm", namespace, packageName, version, upstreamRepository, + RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot); + if (!claim.claimed()) { + return false; + } + + boolean imported = false; + try { + if (verdaccio.packageVersionExists(repoId, domain, repository, namespace, packageName, version)) { + imported = service.retainedUpstreamRepositoryOrigin(region, domain, owner, repository, "npm", + namespace, packageName, version).filter(upstreamRepository::equals).isPresent(); + return imported; + } + String candidateBaseUrl = verdaccio.ensureReady(upstreamRepoId, + verdaccio.publicUrl(domain, upstreamRepository)); + JsonNode candidateDocument = verdaccio.fetchPackageDocument(candidateBaseUrl, namespace, packageName) + .orElse(null); + JsonNode versionDoc = candidateDocument == null ? null + : candidateDocument.path("versions").path(version); + if (versionDoc == null || versionDoc.isMissingNode() || versionDoc.isNull()) { + LOG.warnv("Not retaining {0}/{1}@{2} from upstream repository {3}: its own version document " + + "disappeared between resolution and write.", namespace, packageName, version, + upstreamRepository); + return false; + } + String readme = candidateDocument.path("readme").asText(""); + Optional fetched = verdaccio.fetchPackageVersionAssetStreamed( + upstreamRepoId, domain, upstreamRepository, namespace, packageName, version, assetName); + if (fetched.isEmpty()) { + return false; + } + Path staged = service.stageStreamedAsset(fetched.get()); + // Not fetched.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, the same way the existing + // copyContainerBackedPackageVersions write loop already sources it. + long contentLength; + try { + contentLength = Files.size(staged); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + try { + // The fence check and the real write happen inside the very same synchronized call + // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions + // already hold across their own entire operation, so a write here and one of + // those four operations can never interleave. + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "npm", namespace, packageName, version, versionFenceSnapshot, + packageFenceSnapshot, claim.episodeId(), repoId, assetName, contentLength, + () -> verdaccio.storeRetainedVersionAsset(repoId, domain, repository, namespace, packageName, + version, assetName, staged, contentLength, versionDoc)); + imported = result.fenceMatched() && result.wroteNewContent(); + if (imported) { + service.recordPublishedPackageVersionReadme(region, domain, owner, repository, "npm", namespace, + packageName, version, readme, versionFenceSnapshot); + } + return imported; + } finally { + service.deleteStagedAssetBody(staged); + } + } finally { + if (imported) { + service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "npm", namespace, + packageName, packageFenceSnapshot); + } + service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "npm", namespace, + packageName, version, claim.episodeId(), imported); + } + } + + private static String packagePath(String namespace, String packageName) { + return namespace == null + ? SidecarUriUtils.encodeSegment(packageName) + : "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName); + } + + private static String tarballFilename(String packageName, String version) { + return packageName + "-" + version + ".tgz"; + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java index 91d1fda956..51c1da3b08 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetController.java @@ -72,20 +72,24 @@ public class CodeArtifactNuGetController { private final CodeArtifactService service; private final BagetterSidecarClient bagetter; private final CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter; + private final CodeArtifactNuGetUpstreamRepositoryImporter upstreamRepositoryImporter; private final HttpClient httpClient; @Inject public CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter, - CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter) { - this(service, bagetter, externalConnectionImporter, + CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter, + CodeArtifactNuGetUpstreamRepositoryImporter upstreamRepositoryImporter) { + this(service, bagetter, externalConnectionImporter, upstreamRepositoryImporter, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); } CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter, - CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter, HttpClient httpClient) { + CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter, + CodeArtifactNuGetUpstreamRepositoryImporter upstreamRepositoryImporter, HttpClient httpClient) { this.service = service; this.bagetter = bagetter; this.externalConnectionImporter = externalConnectionImporter; + this.upstreamRepositoryImporter = upstreamRepositoryImporter; this.httpClient = httpClient; } @@ -196,8 +200,15 @@ public class CodeArtifactNuGetController { // request. Not attempted at all when BaGetter already has it: the only extra cost on // every other request is this one cheap local existence check. if (!bagetter.packageVersionExists(handle.repoId(), domain, repository, null, id, version)) { - externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository, - handle.repoId(), id, 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 (see CodeArtifactNuGetUpstreamRepositoryImporter's + // own javadoc). + if (!externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository, + handle.repoId(), id, version)) { + upstreamRepositoryImporter.tryImport(handle.region(), domain, handle.owner(), repository, + handle.repoId(), id, version); + } } return proxyGetStreamed(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/" + lowerId + "." + SidecarUriUtils.encodeSegment(version.toLowerCase(Locale.ROOT)) + ".nupkg", diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java index 2a67fee991..25df33fffd 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporter.java @@ -79,7 +79,8 @@ public class CodeArtifactNuGetExternalConnectionImporter { if (externalConnectionName == null) { return false; } - if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "nuget", null, packageId)) { + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "nuget", null, packageId, + "EXTERNAL_UPSTREAM")) { return false; } @@ -95,7 +96,7 @@ public class CodeArtifactNuGetExternalConnectionImporter { // claimRetainedVersionOrigin's own javadoc for the race this closes. CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, domain, owner, repository, "nuget", null, packageId, version, externalConnectionName, - packageFenceSnapshot); + RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot); if (!claim.claimed()) { return false; } diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporter.java new file mode 100644 index 0000000000..1688c7b837 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporter.java @@ -0,0 +1,198 @@ +package io.floci.aws.services.codeartifact; + +import io.floci.aws.core.common.AwsException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; + +/** + * {@code 16f-UPSTREAM-REPO}: retains a NuGet package version from another repository in the same + * domain, named in {@code repository}'s own {@code upstreams} list (distinct from, and mutually + * exclusive with, {@link CodeArtifactNuGetExternalConnectionImporter}'s real public registry). + * Reuses that importer's exact claim/fence mechanism (see its own javadoc for the full race this + * closes), with two differences real AWS documents for a same-domain upstream rather than an + * external connection: + * + *
    + *
  • Transitive search, in priority order. {@link + * CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct + * upstreams first, then theirs, breadth-first, matching AWS's own documented "Upstream + * repository priority order." The first candidate with the requested version wins; it may be + * several hops deep, not necessarily a direct upstream of {@code repository} itself.
  • + *
  • Archived/Disposed propagation. A candidate's own copy of the version must still be + * downloadable there (checked via {@link + * CodeArtifactService#requireContainerBackedVersionDownloadable}): an Archived or Disposed + * version at a candidate is skipped, the walk continuing to the next one in order, exactly as + * AWS documents a disposed/archived upstream copy being treated as not found by a downstream + * request. The real public-registry importer has no equivalent of this, since "the real public + * source has no CodeArtifact-shaped status to check" (see its own javadoc): a same-domain + * upstream repository very much does.
  • + *
+ */ +@ApplicationScoped +public class CodeArtifactNuGetUpstreamRepositoryImporter { + + private final CodeArtifactService service; + private final BagetterSidecarClient bagetter; + + @Inject + public CodeArtifactNuGetUpstreamRepositoryImporter(CodeArtifactService service, BagetterSidecarClient bagetter) { + this.service = service; + this.bagetter = bagetter; + } + + /** + * Attempts to retain {@code packageId}/{@code version}'s one real asset into {@code repoId} + * from the first eligible repository in {@code repository}'s own upstream chain. Returns + * {@code true} only when the asset is genuinely present under this claim by the time this + * returns; a caller that gets {@code false} back falls through to its own existing not-found + * response exactly as if this method had never been called, the same contract {@link + * CodeArtifactNuGetExternalConnectionImporter#tryImport} already has. + */ + public boolean tryImport(String region, String domain, String owner, String repository, String repoId, + String packageId, String version) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "nuget", null, packageId, + "INTERNAL_UPSTREAM")) { + return false; + } + + String upstreamRepository = null; + String upstreamRepoId = null; + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("nuget", region, domain, owner, candidate, + bagetter); + } 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; + } + // Registers this candidate's own use with the sidecar manager, under the service's + // lock, for the exact same reason resolveContainerIdAndBeginUse's own javadoc + // documents for a repository this call is actively reading from: a DeleteRepository + // of this candidate racing in between resolving its id and reading its sidecar must + // not be able to run that candidate's own cleanup until this call releases it below. + // Held past this loop, for the winning candidate only, until the claim/fetch/write + // below are entirely done with it (see the try/finally right after this loop). + boolean eligible = false; + try { + if (!bagetter.packageVersionExists(candidateRepoId, domain, candidate, null, packageId, version)) { + continue; + } + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "nuget", + null, packageId, 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) { + bagetter.endUse(candidateRepoId); + } + } + } + if (upstreamRepository == null) { + return false; + } + + try { + return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, packageId, version, + upstreamRepository, upstreamRepoId); + } finally { + bagetter.endUse(upstreamRepoId); + } + } + + private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository, + String repoId, String packageId, String version, String upstreamRepository, String upstreamRepoId) { + // Snapshotted before the claim and the real write below, not after, the same ordering + // CodeArtifactNuGetExternalConnectionImporter#tryImport already relies on. + long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, + "nuget", null, packageId); + long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository, + "nuget", null, packageId, version); + CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, + domain, owner, repository, "nuget", null, packageId, version, upstreamRepository, + RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot); + if (!claim.claimed()) { + return false; + } + + boolean imported = false; + 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 (bagetter.packageVersionExists(repoId, domain, repository, null, packageId, version)) { + imported = service.retainedUpstreamRepositoryOrigin(region, domain, owner, repository, "nuget", + null, packageId, version).filter(upstreamRepository::equals).isPresent(); + return imported; + } + List assetNames = bagetter.listPackageVersionAssetNames(upstreamRepoId, domain, + upstreamRepository, null, packageId, version); + if (assetNames.isEmpty()) { + return false; + } + // NuGet packages have exactly one asset per version (the same real AWS fact the + // external-connection importer's own javadoc cites), so the first (and only) listed + // name is the real one, not a guess at the deterministic id.version.nupkg convention. + String assetName = assetNames.get(0); + Optional streamed = bagetter.fetchPackageVersionAssetStreamed( + upstreamRepoId, domain, upstreamRepository, null, packageId, version, assetName); + if (streamed.isEmpty()) { + return false; + } + Path staged = 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, the same way the existing + // copyContainerBackedPackageVersions write loop already sources it. + long contentLength; + try { + contentLength = Files.size(staged); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + try { + // The fence check and the real write happen inside the very same synchronized call + // DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions already + // hold across their own entire operation, so a write here and one of those four + // operations can never interleave. + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot, + packageFenceSnapshot, claim.episodeId(), repoId, assetName, contentLength, + () -> bagetter.storePackageVersionAsset(repoId, domain, repository, null, packageId, version, + assetName, staged, contentLength)); + imported = result.fenceMatched() && result.wroteNewContent(); + return imported; + } finally { + service.deleteStagedAssetBody(staged); + } + } finally { + if (imported) { + service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository, + "nuget", null, packageId, packageFenceSnapshot, repoId); + } + service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "nuget", null, packageId, + version, claim.episodeId(), imported); + } + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java index d3f311adf2..48e5b22daa 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java @@ -82,21 +82,25 @@ public class CodeArtifactPypiController { private final CodeArtifactService service; private final PypiserverSidecarClient pypiserver; private final CodeArtifactPypiExternalConnectionImporter externalConnectionImporter; + private final CodeArtifactPypiUpstreamRepositoryImporter upstreamRepositoryImporter; private final HttpClient httpClient; private final ConcurrentHashMap uploadLocks = new ConcurrentHashMap<>(); @Inject public CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarClient pypiserver, - CodeArtifactPypiExternalConnectionImporter externalConnectionImporter) { - this(service, pypiserver, externalConnectionImporter, + CodeArtifactPypiExternalConnectionImporter externalConnectionImporter, + CodeArtifactPypiUpstreamRepositoryImporter upstreamRepositoryImporter) { + this(service, pypiserver, externalConnectionImporter, upstreamRepositoryImporter, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); } CodeArtifactPypiController(CodeArtifactService service, PypiserverSidecarClient pypiserver, - CodeArtifactPypiExternalConnectionImporter externalConnectionImporter, HttpClient httpClient) { + CodeArtifactPypiExternalConnectionImporter externalConnectionImporter, + CodeArtifactPypiUpstreamRepositoryImporter upstreamRepositoryImporter, HttpClient httpClient) { this.service = service; this.pypiserver = pypiserver; this.externalConnectionImporter = externalConnectionImporter; + this.upstreamRepositoryImporter = upstreamRepositoryImporter; this.httpClient = httpClient; } @@ -147,9 +151,16 @@ public class CodeArtifactPypiController { } else { return response; } + // A repository has either an external connection or upstreams, never both: at most + // one of these two calls ever finds anything, and the other's own no-op is cheap + // (see CodeArtifactPypiUpstreamRepositoryImporter's own javadoc). List additional = externalConnectionImporter.additionalExternalFilenames(handle.region(), domain, handle.owner(), repository, handle.repoId(), packageName, knownFilenames); + if (additional.isEmpty()) { + additional = upstreamRepositoryImporter.additionalInternalFilenames(handle.region(), domain, + handle.owner(), repository, handle.repoId(), packageName, knownFilenames); + } if (rewrittenOrNull == null && additional.isEmpty()) { return response; } @@ -265,8 +276,10 @@ public class CodeArtifactPypiController { "/packages/" + SidecarUriUtils.encodeSegment(filename), leaseTransferred, () -> pypiserver.endUse(handle.repoId())); if (match == null && response.getStatus() == 404 - && externalConnectionImporter.tryImportAsset(handle.region(), domain, handle.owner(), repository, - handle.repoId(), filename)) { + && (externalConnectionImporter.tryImportAsset(handle.region(), domain, handle.owner(), + repository, handle.repoId(), filename) + || upstreamRepositoryImporter.tryImportAsset(handle.region(), domain, handle.owner(), + repository, handle.repoId(), filename))) { return proxyGetStreamed(handle.baseUrl(), "/packages/" + SidecarUriUtils.encodeSegment(filename), leaseTransferred, () -> pypiserver.endUse(handle.repoId())); } diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java index 4f381c8931..3500b9b0ba 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporter.java @@ -152,7 +152,8 @@ public class CodeArtifactPypiExternalConnectionImporter { if (externalConnectionName == null) { return List.of(); } - if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName)) { + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName, + "EXTERNAL_UPSTREAM")) { return List.of(); } JsonNode index = fetchSimpleIndexJson(externalConnectionName, packageName).orElse(null); @@ -223,7 +224,8 @@ public class CodeArtifactPypiExternalConnectionImporter { if (packageName.isEmpty()) { return false; } - if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName.get())) { + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName.get(), + "EXTERNAL_UPSTREAM")) { return false; } @@ -257,7 +259,7 @@ public class CodeArtifactPypiExternalConnectionImporter { "pypi", null, packageName.get(), version.get()); CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, domain, owner, repository, "pypi", null, packageName.get(), version.get(), externalConnectionName, - packageFenceSnapshot); + RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot); if (!claim.claimed()) { return false; } @@ -351,7 +353,8 @@ public class CodeArtifactPypiExternalConnectionImporter { if (fenceStillMatched && !remainingSiblings.isEmpty()) { CodeArtifactService.RetainedVersionOriginClaimOutcome backgroundClaim = service .claimRetainedVersionOrigin(region, domain, owner, repository, "pypi", null, - packageName.get(), version.get(), externalConnectionName, packageFenceSnapshot); + packageName.get(), version.get(), externalConnectionName, + RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot); if (backgroundClaim.claimed()) { List siblingsToImport = remainingSiblings; String resolvedPackageName = packageName.get(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporter.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporter.java new file mode 100644 index 0000000000..f9e9555b91 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporter.java @@ -0,0 +1,361 @@ +package io.floci.aws.services.codeartifact; + +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.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * {@code 16f-UPSTREAM-REPO}: retains pypi package version assets from another repository in the + * same domain, named in {@code repository}'s own {@code upstreams} list (distinct from, and + * mutually exclusive with, {@link CodeArtifactPypiExternalConnectionImporter}'s real public + * registry). Reuses the exact claim/fence mechanism {@link + * CodeArtifactService#claimRetainedVersionOrigin} already provides, with real differences from the + * external-connection case: + * + *
    + *
  • No PEP 691 index, no sha256 re-verification, no background thread. The external- + * connection importer's own complexity (a real registry's JSON Simple API response, a second + * hash pass over fetched bytes, and splitting the requested file from its siblings across a + * background task) exists entirely to cope with a real, slow, untrusted network call to + * pypi.org. A same-domain upstream is another repository this emulator itself already backs: + * {@code pypiserver.listPackageVersions}/{@code listPackageVersionAssetNames} already answer + * "which versions/files does it have" directly and fast, with nothing to re-verify against a + * trusted index that does not exist here, so every file of the resolved version is imported + * synchronously, in one pass, the same shape {@code CopyPackageVersions} already uses for a + * multi-asset copy.
  • + *
  • Transitive search, in priority order. {@link + * CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct + * upstreams first, then theirs, breadth-first. The first candidate whose own version list names + * a version {@code filename} belongs to wins; it may be several hops deep.
  • + *
  • Archived/Disposed propagation. A candidate's own copy of the version must still be + * downloadable there (checked via {@link + * CodeArtifactService#requireContainerBackedVersionDownloadable}): the walk skips an Archived or + * Disposed candidate and continues to the next one, exactly as AWS documents a disposed/archived + * upstream copy being treated as not found by a downstream request.
  • + *
+ */ +@ApplicationScoped +public class CodeArtifactPypiUpstreamRepositoryImporter { + + private static final Logger LOG = Logger.getLogger(CodeArtifactPypiUpstreamRepositoryImporter.class); + + private final CodeArtifactService service; + private final PypiserverSidecarClient pypiserver; + + // Keyed by repoId+packageName+version: see tryImportAsset's own javadoc for the double-count + // race this closes, the same reason CodeArtifactPypiExternalConnectionImporter keeps its own + // (separate, importer-scoped) lock map. The two never contend on the same key in practice, + // since a repository has either an external connection or upstreams, never both. + private final ConcurrentHashMap assetWriteLocks = new ConcurrentHashMap<>(); + + @Inject + public CodeArtifactPypiUpstreamRepositoryImporter(CodeArtifactService service, + PypiserverSidecarClient pypiserver) { + this.service = service; + this.pypiserver = pypiserver; + } + + /** + * {@link CodeArtifactPypiExternalConnectionImporter#additionalExternalFilenames}'s own + * counterpart, sourced from the first eligible upstream candidate's own version listing instead + * of a real registry's Simple API response. Every entry reports {@code yanked=false} and + * {@code requiresPythonOrNull=null}: neither PEP 592/700 concept exists for a same-domain + * repository. + */ + public List additionalInternalFilenames( + String region, String domain, String owner, String repository, String repoId, String packageName, + Set alreadyKnownFilenames) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return List.of(); + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName, + "INTERNAL_UPSTREAM")) { + return List.of(); + } + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("pypi", region, domain, owner, candidate, + pypiserver); + } catch (RuntimeException e) { + // The candidate is being concurrently deleted/released: treated exactly like + // "nothing listed there" below. + continue; + } + try { + List versions = packageVersionsAt(candidateRepoId, domain, candidate, packageName); + if (versions.isEmpty()) { + continue; + } + List additional = new ArrayList<>(); + for (String version : versions) { + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "pypi", + null, packageName, version, repoId); + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "pypi", + null, packageName, version, candidateRepoId); + } catch (AwsException e) { + continue; + } + for (String filename : assetNamesAt(candidateRepoId, domain, candidate, packageName, version)) { + if (!alreadyKnownFilenames.contains(filename)) { + additional.add(new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(filename, + false, null)); + } + } + } + if (!additional.isEmpty()) { + return additional; + } + } finally { + // Nothing escapes this iteration (the returned list is plain filename strings, not + // this candidate's own id), so the lease is always released before moving on, + // whether this candidate won or not. + pypiserver.endUse(candidateRepoId); + } + } + return List.of(); + } + + /** + * Mirrors {@link CodeArtifactPypiExternalConnectionImporter#tryImportAsset}'s own contract: + * returns {@code true} only when {@code filename} itself is genuinely present under this + * claim by the time this returns. Every other real file of the resolved version is imported in + * the same call, synchronously (see this class's own javadoc for why no background split is + * needed here). + */ + public boolean tryImportAsset(String region, String domain, String owner, String repository, String repoId, + String filename) { + if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) { + return false; + } + Optional packageName = PypiserverSidecarClient.guessPackageName(filename); + if (packageName.isEmpty()) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "pypi", null, packageName.get(), + "INTERNAL_UPSTREAM")) { + return false; + } + + String upstreamRepository = null; + String upstreamRepoId = null; + String version = null; + for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) { + String candidateRepoId; + try { + candidateRepoId = service.resolveContainerIdAndBeginUse("pypi", region, domain, owner, candidate, + pypiserver); + } 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; + } + // Held past this loop, for the winning candidate only, until the claim/fetch/write + // below are entirely done with it (see the try/finally right after this loop). + boolean eligible = false; + try { + Optional matchedVersion = packageVersionsAt(candidateRepoId, domain, candidate, + packageName.get()).stream() + .filter(v -> PypiserverSidecarClient.filenameEmbedsVersion(filename, packageName.get(), v)) + .filter(v -> assetNamesAt(candidateRepoId, domain, candidate, packageName.get(), v) + .contains(filename)) + .findFirst(); + if (matchedVersion.isEmpty()) { + continue; + } + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "pypi", null, + packageName.get(), matchedVersion.get(), candidateRepoId); + } catch (AwsException e) { + // Archived or Disposed at this candidate: treated exactly like "not found" + // there, so the walk continues to the next candidate rather than stopping. + continue; + } + eligible = true; + upstreamRepository = candidate; + upstreamRepoId = candidateRepoId; + version = matchedVersion.get(); + break; + } finally { + if (!eligible) { + pypiserver.endUse(candidateRepoId); + } + } + } + if (upstreamRepository == null) { + return false; + } + + try { + return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, filename, + packageName.get(), version, upstreamRepository, upstreamRepoId); + } finally { + pypiserver.endUse(upstreamRepoId); + } + } + + private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository, + String repoId, String filename, String packageName, String version, String upstreamRepository, + String upstreamRepoId) { + long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, + "pypi", null, packageName); + long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository, + "pypi", null, packageName, version); + CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region, + domain, owner, repository, "pypi", null, packageName, version, upstreamRepository, + RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot); + if (!claim.claimed()) { + return false; + } + + boolean importedRequested = false; + boolean importedAny = false; + try { + Set alreadyPresent; + try { + alreadyPresent = Set.copyOf(pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, + packageName, version)); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not list {0} {1}''s existing assets on the pypiserver sidecar while attempting " + + "a same-domain upstream retention; treating it as not retained.", packageName, + version); + return false; + } + if (alreadyPresent.contains(filename)) { + // A concurrent attempt under this exact same claim episode may already have + // written this exact file by the time this attempt gets here. + importedAny = service.retainedUpstreamRepositoryOrigin(region, domain, owner, repository, "pypi", + null, packageName, version).filter(upstreamRepository::equals).isPresent(); + importedRequested = importedAny; + return importedRequested; + } + for (String candidateFilename : assetNamesAt(upstreamRepoId, domain, upstreamRepository, + packageName, version)) { + if (alreadyPresent.contains(candidateFilename)) { + continue; + } + FileImportStatus status = importOneAsset(region, domain, owner, repository, repoId, + packageName, version, upstreamRepository, upstreamRepoId, versionFenceSnapshot, + packageFenceSnapshot, claim.episodeId(), candidateFilename); + if (status == FileImportStatus.FENCE_GONE) { + // The version itself is gone: every later candidate in this same attempt + // would fail the exact same way, so none of them are even attempted. + break; + } + if (status == FileImportStatus.WROTE) { + importedAny = true; + if (candidateFilename.equals(filename)) { + importedRequested = true; + } + } + } + return importedRequested; + } finally { + if (importedAny) { + service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository, + "pypi", null, packageName, packageFenceSnapshot, repoId); + } + service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "pypi", null, + packageName, version, claim.episodeId(), importedAny); + } + } + + private enum FileImportStatus { + WROTE, SKIPPED, FENCE_GONE + } + + /** + * Fetches and writes one asset from the resolved upstream candidate's own sidecar storage, + * under a lock keyed to this exact destination version: closes the same double-count race + * {@link CodeArtifactPypiExternalConnectionImporter#importOneCandidateFile}'s own javadoc + * documents (two concurrent attempts for the same version could otherwise both see a + * candidate filename missing and both write it, double-counting its bytes in + * {@code DescribeDomain}'s {@code assetSizeBytes}). + */ + private FileImportStatus importOneAsset(String region, String domain, String owner, String repository, + String repoId, String packageName, String version, String upstreamRepository, String upstreamRepoId, + long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, String candidateFilename) { + Optional fetched; + try { + fetched = pypiserver.fetchPackageVersionAssetStreamed(upstreamRepoId, domain, upstreamRepository, null, + packageName, version, candidateFilename); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} from upstream repository {1} while retaining a pypi package through " + + "a same-domain upstream; skipping this file.", candidateFilename, upstreamRepository); + return FileImportStatus.SKIPPED; + } + if (fetched.isEmpty()) { + return FileImportStatus.SKIPPED; + } + Path staged = service.stageStreamedAsset(fetched.get()); + // Not fetched.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, the same way the existing copyContainerBackedPackageVersions + // write loop already sources it. + long contentLength; + try { + contentLength = Files.size(staged); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + try { + String lockKey = repoId + "|" + PypiserverSidecarClient.normalizePackageName(packageName) + "|" + + version; + synchronized (assetWriteLocks.computeIfAbsent(lockKey, key -> new Object())) { + if (pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, packageName, version) + .contains(candidateFilename)) { + return FileImportStatus.SKIPPED; + } + CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region, + domain, owner, repository, "pypi", null, packageName, version, versionFenceSnapshot, + packageFenceSnapshot, episodeId, repoId, candidateFilename, contentLength, + () -> pypiserver.storePackageVersionAsset(repoId, domain, repository, null, packageName, + version, candidateFilename, staged, contentLength)); + if (!result.fenceMatched()) { + return FileImportStatus.FENCE_GONE; + } + return result.wroteNewContent() ? FileImportStatus.WROTE : FileImportStatus.SKIPPED; + } + } finally { + service.deleteStagedAssetBody(staged); + } + } + + private List packageVersionsAt(String repoId, String domain, String repository, String packageName) { + try { + return pypiserver.listPackageVersions(repoId, domain, repository, null, packageName).stream() + .map(RepositorySidecarManager.PackageVersionTimestamp::version) + .toList(); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not list {0}''s versions on upstream repository {1}''s pypiserver sidecar while " + + "resolving a same-domain upstream retention; treating it as having none.", packageName, + repository); + return List.of(); + } + } + + private List assetNamesAt(String repoId, String domain, String repository, String packageName, + String version) { + try { + return pypiserver.listPackageVersionAssetNames(repoId, domain, repository, null, packageName, version); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not list {0} {1}''s assets on upstream repository {2}''s pypiserver sidecar while " + + "resolving a same-domain upstream retention; treating it as having none.", packageName, + version, repository); + return List.of(); + } + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java index ccf458c853..1a23e5bb36 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactService.java @@ -198,7 +198,7 @@ public class CodeArtifactService implements Resettable { public record PackageVersionAssetsListResult(String format, String namespace, String packageName, String version, String versionRevision, List assets, String nextToken) {} public record PackageVersionSummary(String version, String revision, String status, String originType, - String externalConnectionName) {} + String externalConnectionName, String upstreamRepositoryName) {} public record ListPackageVersionsResult(String format, String namespace, String packageName, String defaultDisplayVersion, List versions, String nextToken) {} public record PackageSummaryEntry(String format, String namespace, String packageName, @@ -221,7 +221,8 @@ public class CodeArtifactService implements Resettable { * #listPackageVersions} before status/origin filtering and pagination are applied. * {@code publishedEpochSeconds} is {@code null} when nothing is known to order by. */ private record PackageVersionEntry(String version, String revision, String status, - Long publishedEpochSeconds, String originType, String externalConnectionName) {} + Long publishedEpochSeconds, String originType, String externalConnectionName, + String upstreamRepositoryName) {} public record AuthorizationToken(String token, long expirationEpochSeconds) {} public record AuthorizationTokenScope(String owner, String region) {} private record AuthorizationTokenRecord(String owner, String region, String domain, Instant expiration) {} @@ -369,22 +370,23 @@ public class CodeArtifactService implements Resettable { private final AtomicLong retainedVersionOriginEpisodeCounter = new AtomicLong(); /** - * One version's current claim on {@code externalConnectionName}, tagged with {@code - * episodeId}: {@code inFlightAttempts} counts how many calls into {@link + * One version's current claim on {@code originName} (an external connection's name, or a + * same-domain upstream repository's name, told apart by {@code originKind}), tagged with + * {@code episodeId}: {@code inFlightAttempts} counts how many calls into {@link * #claimRetainedVersionOrigin} for this exact version and episode have not yet reached * their own matching {@link #finishRetainedVersionOriginAttempt} call, and {@code * confirmed} is {@code true} once any one of them actually wrote real content under this * claim. A claim is only ever removed by {@link #finishRetainedVersionOriginAttempt} * once {@code inFlightAttempts} reaches 0 and {@code confirmed} is still {@code - * false}: as long as either holds, the connection stays reserved, so a concurrent attempt - * under a different connection is refused outright rather than slipping in once a sibling + * false}: as long as either holds, the source stays reserved, so a concurrent attempt + * under a different source is refused outright rather than slipping in once a sibling * attempt's own cleanup happens to run first. {@code episodeId} is assigned fresh only when a * claim is created from nothing (never on an increment of an existing one), so a finish call - * for an episode already torn down and replaced by a new one under the same connection name + * for an episode already torn down and replaced by a new one under the same source name * can never be mistaken for a finish of that new episode (see the field's own javadoc above). */ - private record RetainedVersionOriginClaim(String externalConnectionName, int inFlightAttempts, - boolean confirmed, long episodeId) { + private record RetainedVersionOriginClaim(String originName, RetentionOriginKind originKind, + int inFlightAttempts, boolean confirmed, long episodeId) { } /** @@ -1346,12 +1348,13 @@ public class CodeArtifactService implements Resettable { packageName, v.version()); if (override != null) { return new PackageVersionEntry(v.version(), override.revision(), override.status(), - override.publishedEpochSeconds(), origin.originType(), origin.externalConnectionName()); + override.publishedEpochSeconds(), origin.originType(), origin.externalConnectionName(), + origin.upstreamRepositoryName()); } return new PackageVersionEntry(v.version(), synthesizeContainerBackedRevision(format, repoId, namespace, packageName, v.version()), "Published", v.publishedTime() == null ? null : v.publishedTime().getEpochSecond(), - origin.originType(), origin.externalConnectionName()); + origin.originType(), origin.externalConnectionName(), origin.upstreamRepositoryName()); }); Stream disposedOnly = overridesByVersion.entrySet().stream() .filter(e -> !coveredVersions.contains(e.getKey())) @@ -1360,7 +1363,7 @@ public class CodeArtifactService implements Resettable { packageName, e.getKey()); return new PackageVersionEntry(e.getKey(), e.getValue().revision(), e.getValue().status(), e.getValue().publishedEpochSeconds(), origin.originType(), - origin.externalConnectionName()); + origin.externalConnectionName(), origin.upstreamRepositoryName()); }); entries = Stream.concat(fromSidecar, disposedOnly).toList(); } else { @@ -1370,8 +1373,13 @@ public class CodeArtifactService implements Resettable { throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); } entries = versions.stream() - .map(pv -> new PackageVersionEntry(pv.getVersion(), pv.getRevision(), pv.getStatus(), - pv.getPublishedTime(), "INTERNAL", null)) + .map(pv -> { + VersionOrigin origin = versionOrigin(region, domain, owner, repository, format, namespace, + packageName, pv.getVersion()); + return new PackageVersionEntry(pv.getVersion(), pv.getRevision(), pv.getStatus(), + pv.getPublishedTime(), origin.originType(), origin.externalConnectionName(), + origin.upstreamRepositoryName()); + }) .toList(); } @@ -1379,15 +1387,20 @@ public class CodeArtifactService implements Resettable { // Raised by Greptile's review: npm's own Verdaccio sidecar always points its own // dist-tags.latest at whichever version a package's very first-ever stored version // happens to be, confirmed live, with no way for a caller's write to suppress that - // default. A version retained through an external connection (never a deliberate local - // publish) is excluded from being read as this preference for exactly that reason: - // downloading an old, specifically-pinned version must never change what an unpinned - // npm install resolves to, the same most-recently-published fallback this already uses - // when preferredDisplayVersion itself is unset. - boolean preferredVersionIsExternallyRetained = preferredVersion != null + // default. A version retained through a claim (an external connection, or, since + // 16f-UPSTREAM-REPO, a same-domain upstream repository, never a deliberate local publish) + // is excluded from being read as this preference for exactly that reason: downloading an + // old, specifically-pinned version must never change what an unpinned npm install resolves + // to, the same most-recently-published fallback this already uses when + // preferredDisplayVersion itself is unset. Checked via externalConnectionName/ + // upstreamRepositoryName rather than originType, since a retained version's originType is + // "INTERNAL" for an upstream-repository claim, not "EXTERNAL" (matching AWS's real + // PackageVersionOrigin.originType enum), so originType alone can't tell a retained version + // apart from a direct publish here. + boolean preferredVersionIsRetained = preferredVersion != null && entries.stream().anyMatch(e -> e.version().equals(preferredVersion) - && "EXTERNAL".equals(e.originType())); - String defaultDisplayVersion = preferredVersion != null && !preferredVersionIsExternallyRetained + && (e.externalConnectionName() != null || e.upstreamRepositoryName() != null)); + String defaultDisplayVersion = preferredVersion != null && !preferredVersionIsRetained && entries.stream().anyMatch(e -> e.version().equals(preferredVersion) && "Published".equals(e.status())) ? preferredVersion @@ -1407,7 +1420,7 @@ public class CodeArtifactService implements Resettable { "ValidationException"); List summaries = page.items().stream() .map(e -> new PackageVersionSummary(e.version(), e.revision(), e.status(), e.originType(), - e.externalConnectionName())) + e.externalConnectionName(), e.upstreamRepositoryName())) .toList(); return new ListPackageVersionsResult(format, namespace, packageName, defaultDisplayVersion, summaries, page.nextToken()); @@ -1661,6 +1674,10 @@ public class CodeArtifactService implements Resettable { asset.getName(), e.getMessage()); } } + // A generic version deleted and republished under the same coordinates must not + // inherit its previous CopyPackageVersions(includeFromUpstream) claim, the same + // container-backed cleanup already does just above for its own deleted versions. + retainedVersionOriginConnections.remove(ownerScopedKey(owner, key)); successes.put(version, new SuccessfulPackageVersionInfo(pv.getRevision(), "Deleted")); } return new PackageVersionStatusChangeResult(successes, Map.of()); @@ -2729,18 +2746,27 @@ public class CodeArtifactService implements Resettable { } /** - * {@code originType} plus, for an {@code EXTERNAL} version, the exact external connection it - * was retained from: AWS's own {@code DomainEntryPoint} reference describes an ingested - * package's entry point as the external connection it came from, {@code repositoryName} only - * for one published directly, so a caller surfacing a domain entry point needs the connection - * name itself, not just the originType flag. + * {@code originType} plus the domain entry point a caller needs to render it: for {@code + * EXTERNAL}, the exact external connection a version was retained from; for an {@code + * INTERNAL} version genuinely retained from a same-domain upstream repository (real AWS has + * no third {@code originType} value for this, confirmed against the live {@code + * PackageVersionOrigin} API reference, which lists only {@code INTERNAL}/{@code EXTERNAL}/ + * {@code UNKNOWN}), {@code upstreamRepositoryName}; for a true direct publish, neither is set. + * AWS's own {@code DomainEntryPoint} reference describes an ingested package's entry point as + * the source it came from, {@code repositoryName} only for one published directly, so a caller + * surfacing a domain entry point needs the real source's name itself, not just the originType + * flag. */ - private record VersionOrigin(String originType, String externalConnectionName) {} + private record VersionOrigin(String originType, String externalConnectionName, String upstreamRepositoryName) {} private VersionOrigin versionOrigin(String region, String domain, String owner, String repository, String format, String namespace, String packageName, String version) { - return retainedVersionOriginConnection(region, domain, owner, repository, format, namespace, packageName, - version).map(name -> new VersionOrigin("EXTERNAL", name)).orElse(new VersionOrigin("INTERNAL", null)); + return confirmedRetainedVersionOriginClaim(region, domain, owner, repository, format, namespace, packageName, + version) + .map(c -> c.originKind() == RetentionOriginKind.EXTERNAL_CONNECTION + ? new VersionOrigin("EXTERNAL", c.originName(), null) + : new VersionOrigin("INTERNAL", null, c.originName())) + .orElse(new VersionOrigin("INTERNAL", null, null)); } /** @@ -3123,18 +3149,19 @@ public class CodeArtifactService implements Resettable { * only have gotten real content from a direct publish, still gets. * *

Once the package's own setting resolves to allowed, this also defers to the package's - * associated package group's {@code EXTERNAL_UPSTREAM} mode, the same "{@code BLOCK} always - * wins over {@code ALLOW}" interaction {@link #publishPackageVersion}'s own group check - * applies for {@code PUBLISH} (see that method's own javadoc). A weak pattern match (see - * {@link PackageGroupPatterns}' own javadoc) is blocked outright here too: the User Guide's - * package group pattern-matching page states the weak-match block applies to a package - * being "pulled from upstreams" just as much as published, not to {@code PUBLISH} alone. - * {@code INTERNAL_UPSTREAM} is deliberately never resolved here: it gates retention from a - * same-domain upstream repository chain, which this emulator has no real mechanism for yet - * (tracked separately, 16f-UPSTREAM-REPO). + * associated package group's {@code groupRestrictionType} mode (the caller passes {@code + * EXTERNAL_UPSTREAM} for an external-connection retention attempt, {@code INTERNAL_UPSTREAM} + * for a same-domain upstream-repository one, see {@link RetentionOriginKind}), the same + * "{@code BLOCK} always wins over {@code ALLOW}" interaction {@link #publishPackageVersion}'s + * own group check applies for {@code PUBLISH} (see that method's own javadoc). A weak pattern + * match (see {@link PackageGroupPatterns}' own javadoc) is blocked outright here too, + * regardless of which restriction type applies: the User Guide's package group + * pattern-matching page states the weak-match block applies to a package "being pulled from + * upstreams or published," generically, not scoped to {@code PUBLISH} or to one upstream kind + * by name. */ public boolean isUpstreamRetentionBlocked(String region, String domain, String domainOwner, String repository, - String format, String namespace, String packageName) { + String format, String namespace, String packageName, String groupRestrictionType) { String owner = effectiveOwner(domainOwner); // accountingPackageName, not the raw packageName (found by Greptile's review): a nuget // client's own native route always lowercases the id, while an operator setting @@ -3166,7 +3193,7 @@ public class CodeArtifactService implements Resettable { if (associatedGroup.get().strength() == PackageGroupPatterns.MatchStrength.WEAK) { return true; } - return !groupAllowsRestriction(groupsInDomain, associatedGroup.get().group(), "EXTERNAL_UPSTREAM", + return !groupAllowsRestriction(groupsInDomain, associatedGroup.get().group(), groupRestrictionType, repository); } @@ -3278,16 +3305,41 @@ public class CodeArtifactService implements Resettable { * Generic sibling of {@link #mavenRetainedVersionOriginConnection}, for any container-backed * format (npm, pypi, nuget) whose own external-connection importer claims and confirms a * retention origin through {@link #claimRetainedVersionOrigin}/{@link - * #finishRetainedVersionOriginAttempt} the same way Maven's own does. + * #finishRetainedVersionOriginAttempt} the same way Maven's own does. Only ever reports a name + * for a confirmed {@link RetentionOriginKind#EXTERNAL_CONNECTION} claim, exactly as before this + * method had to tell that kind apart from {@link RetentionOriginKind#UPSTREAM_REPOSITORY} at + * all (see {@link #retainedUpstreamRepositoryOrigin} for that kind's own equivalent lookup). */ public Optional retainedVersionOriginConnection(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, String version) { String owner = effectiveOwner(domainOwner); + return confirmedRetainedVersionOriginClaim(region, domain, owner, repository, format, namespace, packageName, + version) + .filter(c -> c.originKind() == RetentionOriginKind.EXTERNAL_CONNECTION) + .map(RetainedVersionOriginClaim::originName); + } + + /** + * {@link RetentionOriginKind#UPSTREAM_REPOSITORY} counterpart of {@link + * #retainedVersionOriginConnection}: the name of the same-domain upstream repository a package + * version was genuinely retained from, or {@link Optional#empty()} for anything else (never + * retained at all, or retained from an external connection instead). + */ + public Optional retainedUpstreamRepositoryOrigin(String region, String domain, String domainOwner, + String repository, String format, String namespace, String packageName, String version) { + String owner = effectiveOwner(domainOwner); + return confirmedRetainedVersionOriginClaim(region, domain, owner, repository, format, namespace, packageName, + version) + .filter(c -> c.originKind() == RetentionOriginKind.UPSTREAM_REPOSITORY) + .map(RetainedVersionOriginClaim::originName); + } + + private Optional confirmedRetainedVersionOriginClaim(String region, String domain, + String owner, String repository, String format, String namespace, String packageName, String version) { String key = packageVersionKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version)); return Optional.ofNullable(retainedVersionOriginConnections.get(ownerScopedKey(owner, key))) - .filter(RetainedVersionOriginClaim::confirmed) - .map(RetainedVersionOriginClaim::externalConnectionName); + .filter(RetainedVersionOriginClaim::confirmed); } /** @@ -3337,9 +3389,9 @@ public class CodeArtifactService implements Resettable { */ public synchronized MavenClaimOutcome claimMavenRetainedVersionOrigin(String region, String domain, String domainOwner, String repository, String namespace, String packageName, String version, - String externalConnectionName, long packageFenceSnapshot) { + String originName, RetentionOriginKind originKind, long packageFenceSnapshot) { RetainedVersionOriginClaimOutcome outcome = claimRetainedVersionOrigin(region, domain, domainOwner, - repository, "maven", namespace, packageName, version, externalConnectionName, packageFenceSnapshot); + repository, "maven", namespace, packageName, version, originName, originKind, packageFenceSnapshot); return new MavenClaimOutcome(outcome.claimed(), outcome.episodeId()); } @@ -3362,7 +3414,7 @@ public class CodeArtifactService implements Resettable { */ public synchronized RetainedVersionOriginClaimOutcome claimRetainedVersionOrigin(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, - String version, String externalConnectionName, long packageFenceSnapshot) { + String version, String originName, RetentionOriginKind originKind, long packageFenceSnapshot) { String owner = effectiveOwner(domainOwner); String accountingName = accountingPackageName(format, packageName); String packageKeyStr = packageKey(region, domain, repository, format, namespace, accountingName); @@ -3377,13 +3429,13 @@ public class CodeArtifactService implements Resettable { if (existing == null) { long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet(); retainedVersionOriginConnections.put(key, - new RetainedVersionOriginClaim(externalConnectionName, 1, false, episodeId)); + new RetainedVersionOriginClaim(originName, originKind, 1, false, episodeId)); return new RetainedVersionOriginClaimOutcome(true, episodeId); } - if (!existing.externalConnectionName().equals(externalConnectionName)) { + if (!existing.originName().equals(originName) || existing.originKind() != originKind) { return new RetainedVersionOriginClaimOutcome(false, 0L); } - retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(externalConnectionName, + retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(originName, originKind, existing.inFlightAttempts() + 1, existing.confirmed(), existing.episodeId())); return new RetainedVersionOriginClaimOutcome(true, existing.episodeId()); } @@ -3431,7 +3483,7 @@ public class CodeArtifactService implements Resettable { retainedVersionOriginConnections.remove(key); } else { retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim( - existing.externalConnectionName(), remaining, confirmed, episodeId)); + existing.originName(), existing.originKind(), remaining, confirmed, episodeId)); } } @@ -3671,7 +3723,7 @@ public class CodeArtifactService implements Resettable { public synchronized boolean mergeMavenMetadataUnderPackageFence(String region, String domain, String domainOwner, String repository, String namespace, String packageName, long packageFenceSnapshot, ReposiliteSidecarClient reposilite, String repoId, byte[] externalMetadataXml, - Predicate versionAllowed) { + Predicate versionAllowed, boolean allowSnapshots) { if (currentContainerBackedPackageFence(region, domain, domainOwner, repository, "maven", namespace, packageName) != packageFenceSnapshot) { return false; @@ -3681,7 +3733,7 @@ public class CodeArtifactService implements Resettable { return false; } return reposilite.mergeExternalConnectionReleaseVersions(repoId, namespace, packageName, externalMetadataXml, - versionAllowed); + versionAllowed, allowSnapshots); } /** @@ -3829,6 +3881,10 @@ public class CodeArtifactService implements Resettable { asset.getName(), e.getMessage()); } } + // Same reasoning as the container-backed branch's own cleanup just above: a + // generic package deleted and republished under the same coordinates must not + // inherit a previous version's CopyPackageVersions(includeFromUpstream) claim. + retainedVersionOriginConnections.remove(ownerScopedKey(owner, versionKey)); } } if (!hadRealContent && originConfig.isEmpty()) { @@ -4181,9 +4237,18 @@ public class CodeArtifactService implements Resettable { * never produces any of the three, rather than guessing at a condition AWS never actually * documents for this action. * - *

{@code includeFromUpstream} is accepted for wire compatibility but has no effect: Floci - * has no upstream-ingestion path for any format (see {@code docs/services/codeartifact.md}'s - * Known limitations), so there is never a separate upstream repository to also search. + *

{@code includeFromUpstream} (real AWS flag, default {@code false}): on a miss against + * the literal {@code sourceRepository}, searches its {@code upstreams} chain (see {@link + * #resolveUpstreamSearchOrder}) for the first repository with a usable (not Archived, not + * Disposed) copy of the version and copies from there instead, for every format. Deliberately + * does not consult {@code isUpstreamRetentionBlocked}/{@code INTERNAL_UPSTREAM} at all, the + * same "distinct, explicit API action reached through neither mechanism" reasoning this + * method's own javadoc already gives for skipping origin-configuration entirely: that + * restriction is documented as gating retention "when requested by a package manager," which + * this explicit administrative action is not. A version found directly at {@code + * sourceRepository} records no new claim; one resolved from the upstream chain records the + * real (possibly several hops deep) source via the same widened claim mechanism the + * native-protocol importers use (see {@code RetentionOriginKind}). * *

For {@code generic}, a freshly copied version gets a new revision of its own ({@link * #newRevision()}, never the source's): the User Guide's own definition of "package version @@ -4263,16 +4328,42 @@ public class CodeArtifactService implements Resettable { if (CONTAINER_BACKED_FORMATS.contains(format)) { return copyContainerBackedPackageVersions(region, domain, owner, sourceRepository, destinationRepository, format, namespace, packageName, requestedVersions, versionRevisions, - hasRevisions, allowOverwrite); + hasRevisions, allowOverwrite, includeFromUpstream); } Map failures = new LinkedHashMap<>(); List pendingCopies = new ArrayList<>(); Map sourceByVersion = new LinkedHashMap<>(); + // Only ever populated for a version actually resolved from the upstream chain below (not + // the literal sourceRepository): a direct copy from sourceRepository itself records no + // claim at all, exactly as before this emulator had any upstream-repository mechanism. + Map resolvedUpstreamSourceByVersion = new LinkedHashMap<>(); for (String version : requestedVersions) { String sourceKey = packageVersionKey(region, domain, sourceRepository, format, namespace, packageName, version); CodeArtifactPackageVersion sourcePv = packageVersions.getForAccount(owner, sourceKey).orElse(null); + // includeFromUpstream (real AWS flag, confirmed cross-format, default false): only + // consulted on a miss against the literal sourceRepository, matching AWS's own + // documented CopyPackageVersions behavior ("by default, only copies package versions + // that are stored in the target repository"). Archived is excluded here too, stricter + // than the direct-source check just below (which only excludes Disposed): a version + // this emulator would never resolve against an upstream through any other mechanism + // should not be silently resurrected into a fresh destination copy just because this + // one explicit, administrative action went looking further than a direct copy would. + if (sourcePv == null && includeFromUpstream) { + for (String candidate : resolveUpstreamSearchOrder(region, domain, owner, sourceRepository)) { + String candidateKey = packageVersionKey(region, domain, candidate, format, namespace, + packageName, version); + CodeArtifactPackageVersion candidatePv = packageVersions.getForAccount(owner, candidateKey) + .orElse(null); + if (candidatePv != null && !"Disposed".equals(candidatePv.getStatus()) + && !"Archived".equals(candidatePv.getStatus())) { + sourcePv = candidatePv; + resolvedUpstreamSourceByVersion.put(version, candidate); + break; + } + } + } if (sourcePv == null) { failures.put(version, new PackageVersionError("NOT_FOUND", "Could not find version " + version)); @@ -4363,6 +4454,19 @@ public class CodeArtifactService implements Resettable { CodeArtifactPackageVersion copied = copyGenericPackageVersionAssets(owner, region, domain, destinationRepository, format, namespace, packageName, version, sourceByVersion.get(version), verifiedContentByVersion.get(version)); + String resolvedUpstreamSource = resolvedUpstreamSourceByVersion.get(version); + if (resolvedUpstreamSource != null) { + recordUpstreamRepositoryOriginForCopiedVersion(region, domain, owner, destinationRepository, + format, namespace, packageName, version, resolvedUpstreamSource); + } else { + // A direct copy (resolved straight from the literal sourceRepository, not the + // upstream chain) must not leave an earlier CopyPackageVersions( + // includeFromUpstream) overwrite's own stale claim behind at this exact + // destination coordinate, the same way copyMavenRetainedVersionOriginIfApplicable + // already clears its own container-backed equivalent for a plain copy. + retainedVersionOriginConnections.remove(ownerScopedKey(owner, packageVersionKey(region, domain, + destinationRepository, format, namespace, packageName, version))); + } successes.put(version, new SuccessfulPackageVersionInfo(copied.getRevision(), copied.getStatus())); } return new CopyPackageVersionsResult(successes, Map.of()); @@ -4408,7 +4512,7 @@ public class CodeArtifactService implements Resettable { private CopyPackageVersionsResult copyContainerBackedPackageVersions(String region, String domain, String owner, String sourceRepository, String destinationRepository, String format, String namespace, String packageName, List requestedVersions, Map versionRevisions, - boolean hasRevisions, boolean allowOverwrite) { + boolean hasRevisions, boolean allowOverwrite, boolean includeFromUpstream) { RepositorySidecarManager manager = sidecarRegistry.forFormat(format) .orElseThrow(() -> new AwsException("InternalServerException", "Copying a " + format + " package version is not yet supported by this emulator.", 500)); @@ -4419,10 +4523,42 @@ public class CodeArtifactService implements Resettable { List pendingCopies = new ArrayList<>(); Map> sourceAssetNamesByVersion = new LinkedHashMap<>(); Map> destAssetNamesByVersion = new LinkedHashMap<>(); + // Per-version, since includeFromUpstream lets different requested versions in the same + // batch resolve from different repositories: defaults to the literal sourceRepository/ + // sourceRepoId for every version, overridden below only for one actually resolved from the + // upstream chain. resolvedUpstreamSourceByVersion stays unpopulated for a direct hit, the + // same "no claim recorded for a direct copy" rule the generic branch above applies. + Map effectiveSourceRepositoryByVersion = new LinkedHashMap<>(); + Map effectiveSourceRepoIdByVersion = new LinkedHashMap<>(); + Map resolvedUpstreamSourceByVersion = new LinkedHashMap<>(); try { for (String version : requestedVersions) { + String effectiveSourceRepository = sourceRepository; + String effectiveSourceRepoId = sourceRepoId; if (!manager.packageVersionExists(sourceRepoId, domain, sourceRepository, namespace, packageName, - version)) { + version) && includeFromUpstream) { + for (String candidate : resolveUpstreamSearchOrder(region, domain, owner, sourceRepository)) { + String candidateRepoId = ensureFormatContainerId(format, region, domain, owner, candidate); + if (!manager.packageVersionExists(candidateRepoId, domain, candidate, namespace, packageName, + version)) { + continue; + } + // Stricter than the direct-source check just below (which only ever + // excludes Disposed): matches the generic branch's own reasoning for why + // an Archived candidate upstream must not be resolved either. + String candidateStatus = currentContainerBackedVersionStatus(owner, region, domain, + candidate, format, namespace, packageName, version, candidateRepoId).status(); + if ("Disposed".equals(candidateStatus) || "Archived".equals(candidateStatus)) { + continue; + } + effectiveSourceRepository = candidate; + effectiveSourceRepoId = candidateRepoId; + resolvedUpstreamSourceByVersion.put(version, candidate); + break; + } + } + if (!manager.packageVersionExists(effectiveSourceRepoId, domain, effectiveSourceRepository, + namespace, packageName, version)) { failures.put(version, new PackageVersionError("NOT_FOUND", "Could not find version " + version)); continue; @@ -4435,7 +4571,8 @@ public class CodeArtifactService implements Resettable { // override directly, the same way the generic path's own source-side guard // already does, before this version's real files are ever listed or copied. PackageVersionStatusOverride sourceOverride = currentContainerBackedVersionStatus(owner, region, - domain, sourceRepository, format, namespace, packageName, version, sourceRepoId); + domain, effectiveSourceRepository, format, namespace, packageName, version, + effectiveSourceRepoId); if ("Disposed".equals(sourceOverride.status())) { failures.put(version, new PackageVersionError("NOT_ALLOWED", "Package version " + version + " has already been disposed at the source and cannot be copied")); @@ -4463,16 +4600,16 @@ public class CodeArtifactService implements Resettable { + " has already been disposed at the destination and cannot be republished")); continue; } - List sourceAssetNames = manager.listPackageVersionAssetNames(sourceRepoId, domain, - sourceRepository, namespace, packageName, version); + List sourceAssetNames = manager.listPackageVersionAssetNames(effectiveSourceRepoId, domain, + effectiveSourceRepository, namespace, packageName, version); boolean destExists = manager.packageVersionExists(destRepoId, domain, destinationRepository, namespace, packageName, version); if (destExists) { List destAssetNames = manager.listPackageVersionAssetNames(destRepoId, domain, destinationRepository, namespace, packageName, version); - if (containerBackedVersionContentMatches(manager, sourceRepoId, sourceRepository, destRepoId, - destinationRepository, domain, namespace, packageName, version, sourceAssetNames, - destAssetNames)) { + if (containerBackedVersionContentMatches(manager, effectiveSourceRepoId, effectiveSourceRepository, + destRepoId, destinationRepository, domain, namespace, packageName, version, + sourceAssetNames, destAssetNames)) { // Identical in both repositories already: the same already-successful, // not-listed-anywhere no-op the generic path applies (see // #copyPackageVersions's own javadoc). @@ -4485,6 +4622,8 @@ public class CodeArtifactService implements Resettable { } destAssetNamesByVersion.put(version, destAssetNames); } + effectiveSourceRepositoryByVersion.put(version, effectiveSourceRepository); + effectiveSourceRepoIdByVersion.put(version, effectiveSourceRepoId); sourceAssetNamesByVersion.put(version, sourceAssetNames); pendingCopies.add(version); } @@ -4513,10 +4652,12 @@ public class CodeArtifactService implements Resettable { Map> verifiedContentByVersion = new LinkedHashMap<>(); for (String version : pendingCopies) { Map contentByAsset = new LinkedHashMap<>(); + String effectiveSourceRepository = effectiveSourceRepositoryByVersion.get(version); + String effectiveSourceRepoId = effectiveSourceRepoIdByVersion.get(version); for (String assetName : sourceAssetNamesByVersion.get(version)) { RepositorySidecarManager.StreamedAsset streamed = manager.fetchPackageVersionAssetStreamed( - sourceRepoId, domain, sourceRepository, namespace, packageName, version, - assetName) + effectiveSourceRepoId, domain, effectiveSourceRepository, namespace, packageName, + version, assetName) .orElseThrow(() -> new AwsException("InternalServerException", "Could not copy " + "version '" + version + "' of package '" + packageName + "': its asset '" + assetName + "' disappeared from the source repository between listing and " @@ -4530,6 +4671,8 @@ public class CodeArtifactService implements Resettable { Map successes = new LinkedHashMap<>(); for (String version : pendingCopies) { + String effectiveSourceRepository = effectiveSourceRepositoryByVersion.get(version); + String effectiveSourceRepoId = effectiveSourceRepoIdByVersion.get(version); List destAssetNames = destAssetNamesByVersion.getOrDefault(version, List.of()); Map originalContent = new LinkedHashMap<>(); for (String destAssetName : destAssetNames) { @@ -4574,9 +4717,9 @@ public class CodeArtifactService implements Resettable { for (Map.Entry entry : verifiedContentByVersion.get(version).entrySet()) { String assetName = entry.getKey(); long contentLength = Files.size(entry.getValue()); - manager.copyPackageVersionAsset(sourceRepoId, domain, sourceRepository, destRepoId, - destinationRepository, namespace, packageName, version, assetName, entry.getValue(), - contentLength); + manager.copyPackageVersionAsset(effectiveSourceRepoId, domain, effectiveSourceRepository, + destRepoId, destinationRepository, namespace, packageName, version, assetName, + entry.getValue(), contentLength); if (!touchedAssetNames.contains(assetName)) { touchedAssetNames.add(assetName); } @@ -4597,10 +4740,22 @@ public class CodeArtifactService implements Resettable { recordContainerBackedAssetBytes(region, domain, owner, destinationRepository, format, namespace, packageName, bytesWritten, packageFenceSnapshot); } - copyCapturedReadmeIfApplicable(region, domain, owner, sourceRepository, destinationRepository, - format, namespace, packageName, version); - copyMavenRetainedVersionOriginIfApplicable(region, domain, owner, sourceRepository, + copyCapturedReadmeIfApplicable(region, domain, owner, effectiveSourceRepository, destinationRepository, format, namespace, packageName, version); + String resolvedUpstreamSource = resolvedUpstreamSourceByVersion.get(version); + if (resolvedUpstreamSource != null) { + // Resolved from the upstream chain, not the literal sourceRepository named in + // the request: there is no claim at sourceRepository itself to carry forward + // (nothing was found there at all), so this records a fresh one pointing at + // the real, resolved source instead of calling + // copyMavenRetainedVersionOriginIfApplicable below, which reads sourceRepository's + // own claim and would otherwise just clear the destination's. + recordUpstreamRepositoryOriginForCopiedVersion(region, domain, owner, destinationRepository, + format, namespace, packageName, version, resolvedUpstreamSource); + } else { + copyMavenRetainedVersionOriginIfApplicable(region, domain, owner, effectiveSourceRepository, + destinationRepository, format, namespace, packageName, version); + } // Drops any status override left over from whatever used to be at this destination // coordinate (an Archived version this copy's allowOverwrite just replaced, most // concretely): the response below reports Published, and a stale override would @@ -4625,9 +4780,13 @@ public class CodeArtifactService implements Resettable { * Stages an already-fetched streamed asset to a temp file via {@link #stageAssetBody}, closing * the stream afterward regardless of outcome: {@link #stageAssetBody} itself never closes the * body it is handed, since its other caller (a controller's own inbound request stream) owns - * that separately. + * that separately. Package-private (not {@code private}): the upstream-repository importers + * (npm/pypi/nuget) reuse this directly to stage an asset read from another repository's own + * sidecar via {@link RepositorySidecarManager#fetchPackageVersionAssetStreamed}, the same + * primitive {@link #copyContainerBackedPackageVersions} already uses for a cross-repository + * read. */ - private Path stageStreamedAsset(RepositorySidecarManager.StreamedAsset streamed) { + Path stageStreamedAsset(RepositorySidecarManager.StreamedAsset streamed) { try { return stageAssetBody(streamed.content()); } finally { @@ -4715,15 +4874,36 @@ public class CodeArtifactService implements Resettable { String key = ownerScopedKey(owner, packageVersionKey(region, domain, destinationRepository, format, namespace, accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version))); - Optional sourceConnection = retainedVersionOriginConnection(region, domain, owner, sourceRepository, - format, namespace, packageName, version); - if (sourceConnection.isEmpty()) { + Optional sourceClaim = confirmedRetainedVersionOriginClaim(region, domain, owner, + sourceRepository, format, namespace, packageName, version); + if (sourceClaim.isEmpty()) { retainedVersionOriginConnections.remove(key); return; } long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet(); - retainedVersionOriginConnections.put(key, - new RetainedVersionOriginClaim(sourceConnection.get(), 0, true, episodeId)); + retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(sourceClaim.get().originName(), + sourceClaim.get().originKind(), 0, true, episodeId)); + } + + /** + * Records {@code destinationRepository}'s freshly-copied version as genuinely retained from + * {@code upstreamRepository} (a {@code CopyPackageVersions} call with {@code + * includeFromUpstream} resolved it from there rather than from the literal {@code + * sourceRepository} named in the request): written directly as an already-confirmed claim, + * the same shape {@link #copyMavenRetainedVersionOriginIfApplicable} already uses for a plain + * copy, since the real write this claim describes has already finished by the time this runs, + * there is no concurrent writer to arbitrate against the way {@link + * #claimRetainedVersionOrigin}'s own claim-or-reject gate exists for. + */ + private void recordUpstreamRepositoryOriginForCopiedVersion(String region, String domain, String owner, + String destinationRepository, String format, String namespace, String packageName, String version, + String upstreamRepository) { + String key = ownerScopedKey(owner, packageVersionKey(region, domain, destinationRepository, format, + namespace, accountingPackageName(format, packageName), + normalizedContainerBackedVersion(format, version))); + long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet(); + retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(upstreamRepository, + RetentionOriginKind.UPSTREAM_REPOSITORY, 0, true, episodeId)); } /** @@ -6026,6 +6206,23 @@ public class CodeArtifactService implements Resettable { return domains.scanForAccount(owner, k -> k.startsWith(region + "::")).size(); } + /** + * Rejects a transitive cycle, not just a direct self-reference: no AWS documentation was found + * confirming CreateRepository/UpdateRepository rejects a cycle specifically (unlike the direct + * self-reference check below, nothing here cites an AWS error for this), so this is implemented + * defensively, by analogy with that same check's own spirit, rather than a confirmed AWS + * behavior. Checked by walking each candidate upstream's own transitive closure, using the + * graph as currently stored (before this update commits): if {@code repository} itself is + * already reachable from a candidate, adding that candidate would close a cycle, whichever + * direction it was introduced from (this repository adding an upstream that already reaches + * back to it, or discovered symmetrically when that upstream later tries to add this repository + * in turn, since at that point this repository already transitively reaches it). Uses {@link + * UpstreamRepositoryResolver#isReachable}, not {@link UpstreamRepositoryResolver#resolveSearchOrder}, + * deliberately: the latter is capped at {@link UpstreamRepositoryResolver#MAX_RESOLUTION_REPOSITORIES} + * to match AWS's own documented per-resolution search quota, but a domain can hold up to 1,000 + * repositories, so a cycle whose closing edge sits beyond that cap would otherwise pass + * validation and persist undetected. + */ private void validateUpstreams(String owner, String region, String domain, String repository, List upstreams) { if (upstreams == null) { @@ -6044,9 +6241,31 @@ public class CodeArtifactService implements Resettable { throw notFound("Upstream repository '" + upstream + "' was not found in domain '" + domain + "'.", upstream, "repository"); } + if (UpstreamRepositoryResolver.isReachable(upstream, repository, + upstreamsOfFunction(owner, region, domain))) { + throw validation("Repository '" + upstream + "' already has '" + repository + "' in its own " + + "upstream chain; adding it as an upstream here would create a cycle."); + } } } + /** + * The priority-ordered, deduplicated, cycle-safe chain of repositories AWS searches when + * resolving a package-manager request against {@code repository}'s own {@code upstreams} + * (never including {@code repository} itself); see {@link UpstreamRepositoryResolver}'s own + * javadoc for why this is a breadth-first walk, not a depth-first one. + */ + List resolveUpstreamSearchOrder(String region, String domain, String domainOwner, String repository) { + String owner = effectiveOwner(domainOwner); + return UpstreamRepositoryResolver.resolveSearchOrder(repository, upstreamsOfFunction(owner, region, domain)); + } + + private Function> upstreamsOfFunction(String owner, String region, String domain) { + return repositoryName -> repositories.getForAccount(owner, repositoryKey(region, domain, repositoryName)) + .map(CodeArtifactRepository::getUpstreams) + .orElse(List.of()); + } + // Used by DeleteDomain too: AWS returns ResourceNotFoundException for a missing domain there, // although the API reference does not declare it on that operation. private CodeArtifactDomain requireDomain(String owner, String key, String domainName) { diff --git a/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java b/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java index 5415d02982..76a9d7c793 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java +++ b/src/main/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClient.java @@ -776,15 +776,40 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { * request for this exact package would keep finding nothing new to add and keep taking this * same no-op path, never repairing it, so a client verifying checksums could keep failing * indefinitely even once the sidecar itself has long since recovered. + * + *

{@code allowSnapshots}: {@code false} for an external connection (AWS's own "release + * versions only" restriction, cited above); {@code true} for a same-domain upstream repository + * (16f-UPSTREAM-REPO), which has no such restriction, since a SNAPSHOT already published into + * one is a perfectly real, already-retained artifact. */ - public boolean mergeExternalConnectionReleaseVersions(String repositoryContainerId, String namespace, - String packageName, byte[] externalMetadataXml, Predicate versionAllowed) { - ensureRepository(repositoryContainerId); - String externalXml = new String(externalMetadataXml, StandardCharsets.UTF_8); - List externalReleaseVersions = XmlParser.extractAll(externalXml, "version").stream() - .filter(v -> !v.endsWith("-SNAPSHOT")) + /** + * The read-only half of {@link #mergeExternalConnectionReleaseVersions}'s own eligibility + * filter (SNAPSHOT exclusion plus {@code versionAllowed}), exposed so a caller searching + * several candidates in priority order (16f-UPSTREAM-REPO's {@code + * CodeArtifactMavenUpstreamRepositoryImporter}) can tell "this candidate's metadata names + * nothing usable, try the next one" apart from "this candidate is the one, merge it," without + * provisioning this repository or writing anything for a candidate it is about to skip. + */ + static List eligibleReleaseVersions(byte[] metadataXml, Predicate versionAllowed, + boolean allowSnapshots) { + return eligibleReleaseVersions(new String(metadataXml, StandardCharsets.UTF_8), versionAllowed, + allowSnapshots); + } + + private static List eligibleReleaseVersions(String xml, Predicate versionAllowed, + boolean allowSnapshots) { + return XmlParser.extractAll(xml, "version").stream() + .filter(v -> allowSnapshots || !v.endsWith("-SNAPSHOT")) .filter(versionAllowed) .toList(); + } + + public boolean mergeExternalConnectionReleaseVersions(String repositoryContainerId, String namespace, + String packageName, byte[] externalMetadataXml, Predicate versionAllowed, + boolean allowSnapshots) { + ensureRepository(repositoryContainerId); + String externalXml = new String(externalMetadataXml, StandardCharsets.UTF_8); + List externalReleaseVersions = eligibleReleaseVersions(externalXml, versionAllowed, allowSnapshots); if (externalReleaseVersions.isEmpty()) { return false; } diff --git a/src/main/java/io/floci/aws/services/codeartifact/RetentionOriginKind.java b/src/main/java/io/floci/aws/services/codeartifact/RetentionOriginKind.java new file mode 100644 index 0000000000..2e86792d7f --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/RetentionOriginKind.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.codeartifact; + +/** + * Which of the two real sources a retained package version's claim (see {@code + * CodeArtifactService#claimRetainedVersionOrigin}) was taken under: a real public registry + * reached through a repository's {@code externalConnections} ({@code public:npmjs}, {@code + * public:maven-central}, and so on), or another repository in the same domain reached through a + * repository's own {@code upstreams} list. A version can only ever be retained under one of the + * two (a repository has either an external connection or upstreams, never both, enforced at {@code + * associateExternalConnection}), but the claim/fence machinery is shared between them, so a claim + * needs this tag to tell its own source kind apart once confirmed. + */ +enum RetentionOriginKind { + EXTERNAL_CONNECTION, + UPSTREAM_REPOSITORY +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolver.java b/src/main/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolver.java new file mode 100644 index 0000000000..00328b8950 --- /dev/null +++ b/src/main/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolver.java @@ -0,0 +1,107 @@ +package io.floci.aws.services.codeartifact; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; + +/** + * Flattens a repository's {@code upstreams} graph into the real order AWS searches it in when + * resolving a package-manager request: confirmed against the live "Upstream repository priority + * order" documentation, a repository's own direct upstreams are searched in the order they were + * configured, and that search is transitive (a direct upstream's own upstreams are searched too, + * region-wide quota page confirms as many as 25 repositories total in one resolution), not limited + * to the one repository's own direct list. + * + *

Breadth-first, not depth-first: AWS's own ordering guarantee is that a repository's direct + * upstreams are searched, in their configured order, before any of their own transitive upstreams. + * A depth-first walk would violate this the moment a closer sibling exists alongside a deeper + * match: given {@code A -> [B, C]} and {@code B -> [D]}, a depth-first walk would recurse into + * {@code B}'s own subtree before ever reaching {@code C} (a direct upstream of {@code A}), + * producing the search order {@code [B, D, C]} rather than the correct {@code [B, C, D]}: C, one + * hop away, searched after D, two hops away. Breadth-first expands one full level (a "frontier") + * at a time, so every direct upstream is always searched before any of their own upstreams, + * matching AWS's documented guarantee exactly. + * + *

Cycle-safe by construction: a repository is enqueued at most once (the {@code visited} set), + * so a cycle anywhere in the graph simply stops expanding rather than looping. {@code + * validateUpstreams} independently rejects a cycle at the point it would be introduced (see its + * own javadoc), but this walk does not rely on that validation having run, since an upstream list + * can only be validated against the graph as it existed at that moment, not against every later + * edit to a different repository's own upstreams. + */ +final class UpstreamRepositoryResolver { + + /** + * A defensive bound adapted from, not identical to, AWS's own documented region-wide quota of + * 25 repositories searched in a single resolution (the "Service quotas" page): that page + * states a region-wide ceiling, not a literal guarantee about any one resolution's own walk, + * but a resolution that would otherwise need to visit more repositories than AWS's own total + * region-wide limit allows is not a real scenario this emulator needs to search further on. + */ + static final int MAX_RESOLUTION_REPOSITORIES = 25; + + private UpstreamRepositoryResolver() { + } + + /** + * The priority-ordered, deduplicated, cycle-safe list of repositories reachable from {@code + * startingRepository}'s own {@code upstreams} graph (the starting repository itself is never + * included). {@code upstreamsOf} reads one repository's current, stored {@code upstreams} list + * (an empty list for a repository with none, or one this emulator has never heard of). + */ + static List resolveSearchOrder(String startingRepository, Function> upstreamsOf) { + List order = new ArrayList<>(); + Set visited = new HashSet<>(); + visited.add(startingRepository); + Deque frontier = new ArrayDeque<>(); + frontier.add(startingRepository); + while (!frontier.isEmpty() && order.size() < MAX_RESOLUTION_REPOSITORIES) { + String current = frontier.removeFirst(); + for (String upstream : upstreamsOf.apply(current)) { + if (!visited.add(upstream)) { + continue; + } + order.add(upstream); + if (order.size() >= MAX_RESOLUTION_REPOSITORIES) { + break; + } + frontier.addLast(upstream); + } + } + return order; + } + + /** + * Whether {@code target} is reachable from {@code startingRepository}'s own {@code upstreams} + * graph, with no cap: unlike {@link #resolveSearchOrder}, which exists to answer "where does a + * package-manager request actually search" and is capped to match AWS's own documented + * region-wide resolution quota, {@code validateUpstreams}'s own cycle check needs a correct + * answer for the whole graph as stored, however large a domain's own repository count grows + * (up to 1,000, AWS's own documented per-domain quota, far more than {@link + * #MAX_RESOLUTION_REPOSITORIES}). Sharing that cap here would let a cycle whose closing edge + * sits beyond it pass validation and persist. Still cycle-safe and guaranteed to terminate via + * the same {@code visited} set, since a domain has a bounded, finite number of repositories. + */ + static boolean isReachable(String startingRepository, String target, Function> upstreamsOf) { + Set visited = new HashSet<>(); + visited.add(startingRepository); + Deque frontier = new ArrayDeque<>(); + frontier.add(startingRepository); + while (!frontier.isEmpty()) { + String current = frontier.removeFirst(); + for (String upstream : upstreamsOf.apply(current)) { + if (upstream.equals(target)) { + return true; + } + if (visited.add(upstream)) { + frontier.addLast(upstream); + } + } + } + return false; + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactAssetPersistenceTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactAssetPersistenceTest.java index b1644f5759..74122455ea 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactAssetPersistenceTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactAssetPersistenceTest.java @@ -651,7 +651,8 @@ class CodeArtifactAssetPersistenceTest { format, null, null, null, null, "BLOCK", "BLOCK"); assertEquals(List.of(normalized), listed.packages().stream() .map(CodeArtifactService.PackageSummaryEntry::packageName).toList()); - assertTrue(upgraded.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + assertTrue(upgraded.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized, + "EXTERNAL_UPSTREAM")); AccountAwareStorageBackend migrated = accountAware(dir, file, new TypeReference>() {}); assertTrue(migrated.getForAccount(ACCOUNT_ID, prefix + original).isEmpty()); diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java index 1f43ed32dc..8fc7c198d2 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenControllerTest.java @@ -54,6 +54,7 @@ class CodeArtifactMavenControllerTest { private CodeArtifactService service; private ReposiliteSidecarClient reposilite; private CodeArtifactMavenExternalConnectionImporter externalConnectionImporter; + private CodeArtifactMavenUpstreamRepositoryImporter upstreamRepositoryImporter; private CodeArtifactMavenController controller; private HttpHeaders headers; @@ -62,7 +63,9 @@ class CodeArtifactMavenControllerTest { service = mock(CodeArtifactService.class); reposilite = mock(ReposiliteSidecarClient.class); externalConnectionImporter = mock(CodeArtifactMavenExternalConnectionImporter.class); - controller = new CodeArtifactMavenController(service, reposilite, externalConnectionImporter); + upstreamRepositoryImporter = mock(CodeArtifactMavenUpstreamRepositoryImporter.class); + controller = new CodeArtifactMavenController(service, reposilite, externalConnectionImporter, + upstreamRepositoryImporter); headers = mock(HttpHeaders.class); when(headers.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer some-token"); when(service.resolveAuthorizationToken("some-token", DOMAIN)) diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java index 2d59625637..9eb5b9a933 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java @@ -17,6 +17,7 @@ import java.util.function.Predicate; 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; @@ -68,7 +69,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { // Unstubbed by default: the claim succeeds, matching the common case of a first or // same-connection retry. Tests for a conflicting claim override this per call. when(service.claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), any(), - anyString(), anyString(), anyString(), anyLong())) + anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong())) .thenReturn(new CodeArtifactService.MavenClaimOutcome(true, EPISODE_ID)); // Unstubbed by default: a constant snapshot, so a version-fence mismatch only ever // happens where a test deliberately stubs deployMavenAssetUnderVersionFence to report @@ -130,7 +131,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), - eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), eq(false))) .thenReturn(true); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, @@ -154,7 +155,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), - eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), eq(false))) .thenReturn(true); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, @@ -162,7 +163,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { assertTrue(imported); verify(service).mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), - eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any()); + eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), eq(false)); } /** @@ -181,7 +182,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), - eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), eq(false))) .thenReturn(true); doThrow(new AwsException("ResourceNotFoundException", "gone", 404)) .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, REPOSITORY, "maven", @@ -192,7 +193,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { ArgumentCaptor> captor = ArgumentCaptor.forClass(Predicate.class); verify(service).mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), - captor.capture()); + captor.capture(), eq(false)); Predicate versionAllowed = captor.getValue(); assertFalse(versionAllowed.test("1.0-disposed")); assertTrue(versionAllowed.test("1.0")); @@ -208,7 +209,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).mergeMavenMetadataUnderPackageFence(any(), any(), any(), any(), any(), any(), - anyLong(), any(), any(), any(), any()); + anyLong(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -234,7 +235,8 @@ class CodeArtifactMavenExternalConnectionImporterTest { @Test void doesNothingForMavenMetadataWhenUpstreamRetentionIsBlocked() { when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", - "widget")).thenReturn(true); + "widget", + "EXTERNAL_UPSTREAM")).thenReturn(true); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/maven-metadata.xml"); @@ -266,7 +268,8 @@ class CodeArtifactMavenExternalConnectionImporterTest { @Test void doesNothingWhenUpstreamRetentionIsBlocked() { when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", - "widget")).thenReturn(true); + "widget", + "EXTERNAL_UPSTREAM")).thenReturn(true); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/1.0/widget-1.0.jar"); @@ -280,7 +283,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { // The real service refuses the claim outright when a different connection already holds // it (see claimMavenRetainedVersionOrigin's own javadoc); the mock stands in for that here. when(service.claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", - "1.0", "public:maven-central", 42L)) + "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, 42L)) .thenReturn(new CodeArtifactService.MavenClaimOutcome(false, 0L)); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, @@ -314,7 +317,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any(), anyLong()); verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", - "1.0", "public:maven-central", 42L); + "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, 42L); verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", "widget", 42L); verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", @@ -340,7 +343,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", "widget", "1.0"); order.verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", - "widget", "1.0", "public:maven-central", 42L); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, 42L); } @Test @@ -359,7 +362,7 @@ class CodeArtifactMavenExternalConnectionImporterTest { assertTrue(imported); verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", - "1.0", "public:maven-central", 42L); + "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, 42L); // Something was genuinely retained (the idempotent match is still a real asset present // either way), so the claim is finished as confirmed, not released. Whether the // idempotent match itself double-counts bytes is deployMavenAssetUnderVersionFence's own diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporterTest.java new file mode 100644 index 0000000000..53f1226496 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactMavenUpstreamRepositoryImporterTest.java @@ -0,0 +1,409 @@ +package io.floci.aws.services.codeartifact; + +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 java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +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.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@link CodeArtifactMavenUpstreamRepositoryImporter}'s own decision logic: which candidate it + * resolves an asset or a metadata merge from, and what it writes back. {@link + * ReposiliteSidecarClient} is mocked, so no real Reposilite call ever happens here; its own wire + * contract has its own tests. + */ +class CodeArtifactMavenUpstreamRepositoryImporterTest { + + 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 NAMESPACE = "com.example"; + private static final String PACKAGE_NAME = "widget"; + private static final String VERSION = "1.0"; + private static final String GAV = "com/example/widget/1.0/widget-1.0.jar"; + + /** The episode id the default claim stub below hands out; every finish verify reuses it. */ + private static final long EPISODE_ID = 7L; + + private CodeArtifactService service; + private ReposiliteSidecarClient reposilite; + private CodeArtifactMavenUpstreamRepositoryImporter importer; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + reposilite = mock(ReposiliteSidecarClient.class); + importer = new CodeArtifactMavenUpstreamRepositoryImporter(service, reposilite); + + 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("maven", REGION, DOMAIN, OWNER, UPSTREAM, reposilite)) + .thenReturn(UPSTREAM_REPO_ID); + when(reposilite.artifactExists(UPSTREAM_REPO_ID, GAV)).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.claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString(), eq(RetentionOriginKind.UPSTREAM_REPOSITORY), anyLong())) + .thenReturn(new CodeArtifactService.MavenClaimOutcome(true, EPISODE_ID)); + when(service.stageAssetBody(any(InputStream.class))).thenAnswer(invocation -> { + Path staged = Files.createTempFile("test-maven-upstream-", ".bin"); + InputStream in = invocation.getArgument(0); + Files.copy(in, staged, StandardCopyOption.REPLACE_EXISTING); + return staged; + }); + when(service.deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), + anyString(), any(), anyLong())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(true, + new ReposiliteSidecarClient.DeployOutcome(201, true))); + } + + private void stubFetchArtifact(String repoId, String gav, byte[] content) { + when(reposilite.fetchArtifactStreamed(repoId, gav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(content), content.length, "application/octet-stream"))); + } + + @Test + void importsFromTheDirectUpstreamWhenNotFoundLocally() { + byte[] jarBytes = "jar-bytes".getBytes(); + stubFetchArtifact(UPSTREAM_REPO_ID, GAV, jarBytes); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertTrue(imported); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(reposilite), + eq(REPO_ID), eq(GAV), any(Path.class), eq((long) jarBytes.length)); + verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", NAMESPACE, + PACKAGE_NAME, 42L); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, + PACKAGE_NAME, VERSION, EPISODE_ID, true); + } + + /** + * A standard asset name (the {@code .jar} itself) imports its 3 standard siblings (pom, + * javadoc, sources) together, carried over verbatim from the external-connection importer's + * own shape; a missing sibling (javadoc, here) is normal, not a failure. + */ + @Test + void importsStandardSiblingsTogetherAndTheMissingOneIsNotAFailure() { + String pomGav = "com/example/widget/1.0/widget-1.0.pom"; + String jarGav = GAV; + String sourcesGav = "com/example/widget/1.0/widget-1.0-sources.jar"; + String javadocGav = "com/example/widget/1.0/widget-1.0-javadoc.jar"; + byte[] pomBytes = "pom-bytes".getBytes(); + byte[] jarBytes = "jar-bytes".getBytes(); + byte[] sourcesBytes = "sources-bytes".getBytes(); + stubFetchArtifact(UPSTREAM_REPO_ID, pomGav, pomBytes); + stubFetchArtifact(UPSTREAM_REPO_ID, jarGav, jarBytes); + stubFetchArtifact(UPSTREAM_REPO_ID, sourcesGav, sourcesBytes); + // javadocGav is left unstubbed: fetchArtifactStreamed defaults to Optional.empty(), the + // real "this real repository just doesn't have this standard sibling" shape. + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, jarGav); + + assertTrue(imported); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), anyLong(), eq(reposilite), + eq(REPO_ID), eq(pomGav), any(Path.class), eq((long) pomBytes.length)); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), anyLong(), eq(reposilite), + eq(REPO_ID), eq(jarGav), any(Path.class), eq((long) jarBytes.length)); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), anyLong(), eq(reposilite), + eq(REPO_ID), eq(sourcesGav), any(Path.class), eq((long) sourcesBytes.length)); + verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), + anyString(), eq(javadocGav), any(), anyLong()); + } + + /** + * {@code repo}'s own direct upstreams are {@code [near, far]}; only {@code far} (two hops via + * {@code near}'s own upstream chain) has the artifact. Confirms the walk is genuinely followed + * and the real, deep source is recorded, not an intermediate hop. + */ + @Test + void resolvesFromADeeperCandidateWhenCloserOnesDoNotHaveIt() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("near", "far")); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "near", reposilite)).thenReturn("near-id"); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "far", reposilite)).thenReturn("far-id"); + when(reposilite.artifactExists("near-id", GAV)).thenReturn(false); + when(reposilite.artifactExists("far-id", GAV)).thenReturn(true); + byte[] jarBytes = "jar-bytes".getBytes(); + stubFetchArtifact("far-id", GAV, jarBytes); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertTrue(imported); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, PACKAGE_NAME, + VERSION, "far", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + // The rejected candidate's lease is released as soon as it's rejected; the eventual + // winner's is held until the whole attempt finishes with it, but both are released + // exactly once by the time this call returns. + verify(reposilite).endUse("near-id"); + verify(reposilite).endUse("far-id"); + } + + /** + * A candidate being concurrently deleted/released can throw from {@code + * resolveContainerIdAndBeginUse} itself: treated exactly like "not found" there, same as an + * Archived/Disposed candidate, not propagated. + */ + @Test + void aCandidateBeingConcurrentlyDeletedIsSkippedRatherThanPropagatingTheFailure() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("vanishing", "healthy")); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "vanishing", reposilite)) + .thenThrow(new IllegalStateException("repository is being deleted")); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "healthy", reposilite)) + .thenReturn("healthy-id"); + when(reposilite.artifactExists("healthy-id", GAV)).thenReturn(true); + byte[] jarBytes = "jar-bytes".getBytes(); + stubFetchArtifact("healthy-id", GAV, jarBytes); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertTrue(imported); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + } + + /** + * An Archived candidate's own version must not be resolved; the walk continues to the next + * candidate in priority order instead of stopping there. + */ + @Test + void skipsAnArchivedCandidateAndContinuesToTheNextOne() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("archived", "healthy")); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "archived", reposilite)).thenReturn("archived-id"); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "healthy", reposilite)).thenReturn("healthy-id"); + when(reposilite.artifactExists("archived-id", GAV)).thenReturn(true); + doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, "archived", "maven", + NAMESPACE, PACKAGE_NAME, VERSION, "archived-id"); + when(reposilite.artifactExists("healthy-id", GAV)).thenReturn(true); + byte[] jarBytes = "jar-bytes".getBytes(); + stubFetchArtifact("healthy-id", GAV, jarBytes); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertTrue(imported); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(reposilite).endUse("archived-id"); + verify(reposilite).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, GAV); + + assertFalse(imported); + verify(service, never()).claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWhenInternalUpstreamRetentionIsBlocked() { + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "maven", NAMESPACE, PACKAGE_NAME, + "INTERNAL_UPSTREAM")).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertFalse(imported); + verify(service, never()).claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWhenNoCandidateHasTheAssetEither() { + when(reposilite.artifactExists(UPSTREAM_REPO_ID, GAV)).thenReturn(false); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertFalse(imported); + verify(service, never()).claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWithoutFinishingWhenTheClaimIsRefused() { + when(service.claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L)) + .thenReturn(new CodeArtifactService.MavenClaimOutcome(false, 0L)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertFalse(imported); + verify(reposilite, never()).fetchArtifactStreamed(anyString(), anyString()); + verify(service, never()).finishMavenRetainedVersionOriginAttempt(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyBoolean()); + } + + @Test + void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() { + stubFetchArtifact(UPSTREAM_REPO_ID, GAV, "jar-bytes".getBytes()); + when(service.deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), + anyString(), any(), anyLong())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(false, + null)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV); + + assertFalse(imported); + verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong()); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE, + PACKAGE_NAME, VERSION, EPISODE_ID, false); + } + + /** Names at least one real version, so the eligibility pre-check lets this candidate through. */ + private static final byte[] METADATA_WITH_ONE_VERSION = ("" + + "1.0").getBytes(); + + @Test + void resolvesMetadataFromTheUpstreamWhenNotFoundLocally() { + byte[] metadataBytes = METADATA_WITH_ONE_VERSION; + String metadataGav = "com/example/widget/maven-metadata.xml"; + when(reposilite.fetchArtifactStreamed(UPSTREAM_REPO_ID, metadataGav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(metadataBytes), metadataBytes.length, "text/xml"))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), + eq(true))).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav); + + assertTrue(imported); + } + + /** + * A candidate whose own metadata names nothing eligible (every version Archived at that + * candidate) must not stop the search: the next candidate still gets a chance, exactly like + * the asset case's own Archived/Disposed skip-and-continue ({@link + * #skipsAnArchivedCandidateAndContinuesToTheNextOne}). + */ + @Test + void continuesPastACandidateWhoseMetadataNamesNoEligibleVersion() { + String metadataGav = "com/example/widget/maven-metadata.xml"; + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("archived", "healthy")); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "archived", reposilite)).thenReturn("archived-id"); + when(service.resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, "healthy", reposilite)).thenReturn("healthy-id"); + byte[] archivedMetadata = ("9.9" + + "").getBytes(); + when(reposilite.fetchArtifactStreamed("archived-id", metadataGav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(archivedMetadata), archivedMetadata.length, "text/xml"))); + doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, "archived", "maven", + NAMESPACE, PACKAGE_NAME, "9.9", "archived-id"); + byte[] healthyMetadata = METADATA_WITH_ONE_VERSION; + when(reposilite.fetchArtifactStreamed("healthy-id", metadataGav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(healthyMetadata), healthyMetadata.length, "text/xml"))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(healthyMetadata), any(), + eq(true))).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav); + + assertTrue(imported); + verify(service, never()).mergeMavenMetadataUnderPackageFence(any(), any(), any(), any(), any(), any(), + anyLong(), any(), any(), eq(archivedMetadata), any(), anyBoolean()); + verify(reposilite).endUse("archived-id"); + verify(reposilite).endUse("healthy-id"); + } + + /** Holds the one argument captured below, since a lambda cannot assign a captured local. */ + private static final class CapturedPredicate { + private Predicate value; + } + + @Test + void metadataVersionAllowedChecksBothTheLocalRepositoryAndTheUpstreamCandidate() { + byte[] metadataBytes = METADATA_WITH_ONE_VERSION; + String metadataGav = "com/example/widget/maven-metadata.xml"; + when(reposilite.fetchArtifactStreamed(UPSTREAM_REPO_ID, metadataGav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(metadataBytes), metadataBytes.length, "text/xml"))); + CapturedPredicate captured = new CapturedPredicate(); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), + eq(true))).thenAnswer(invocation -> { + captured.value = invocation.getArgument(10); + return true; + }); + + importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav); + + assertTrue(captured.value.test("2.0")); + doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "maven", + NAMESPACE, PACKAGE_NAME, "3.0", UPSTREAM_REPO_ID); + assertFalse(captured.value.test("3.0")); + } + + /** + * {@code allowSnapshots} is passed as {@code true} for the same-domain upstream case (unlike + * the external-connection importer's {@code false}): a SNAPSHOT already published into an + * upstream repository is a perfectly real, already-retained artifact. + */ + @Test + void metadataMergeAllowsSnapshotVersionsFromTheUpstream() { + byte[] metadataBytes = ("1.0-SNAPSHOT" + + "").getBytes(); + String metadataGav = "com/example/widget/maven-metadata.xml"; + when(reposilite.fetchArtifactStreamed(UPSTREAM_REPO_ID, metadataGav)).thenAnswer(invocation -> + Optional.of(new ReposiliteSidecarClient.StreamedArtifact( + new ByteArrayInputStream(metadataBytes), metadataBytes.length, "text/xml"))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(), + eq(true))).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav); + + assertTrue(imported); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java index 7fce686e3f..8a07bb75dd 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java @@ -1596,8 +1596,14 @@ class CodeArtifactNpmDataPlaneTest { ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class); when(serviceConfigAccess.isEnabled("codeartifact")).thenReturn(codeArtifactEnabled); Router router = Router.router(vertx); - new CodeArtifactNpmDataPlane(service, verdaccioClient, externalConnectionImporter, serviceConfigAccess, - vertx, new ObjectMapper()) + // A fresh, unstubbed mock, the same convention the overload above already documents for + // externalConnectionImporter: every test here that never configures it relies on + // Mockito's own default (Optional.empty()/false) to mean "no upstreams configured, + // proceed with the ordinary proxy" exactly as if this importer did not exist. + CodeArtifactNpmUpstreamRepositoryImporter upstreamRepositoryImporter = + mock(CodeArtifactNpmUpstreamRepositoryImporter.class); + new CodeArtifactNpmDataPlane(service, verdaccioClient, externalConnectionImporter, upstreamRepositoryImporter, + serviceConfigAccess, vertx, new ObjectMapper()) .register(router); dataPlane = vertx.createHttpServer().requestHandler(router) .listen(0, "127.0.0.1") diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java index d5360487d3..c220cd2b94 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmExternalConnectionImporterTest.java @@ -68,7 +68,8 @@ class CodeArtifactNpmExternalConnectionImporterTest { repository.setExternalConnections(List.of(new ExternalConnection("public:npmjs", "npm", "AVAILABLE"))); when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString())).thenReturn(false); + any(), anyString(), + eq("EXTERNAL_UPSTREAM"))).thenReturn(false); when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(), anyString(), any(), anyString())).thenReturn(42L); when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(), @@ -76,7 +77,7 @@ class CodeArtifactNpmExternalConnectionImporterTest { // Unstubbed by default: the claim succeeds, matching the common case of a first or // same-connection retry. Tests for a conflicting claim override this per call. when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString(), anyString(), anyString(), anyLong())) + any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong())) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID)); // Unstubbed by default: Verdaccio does not have the version yet, matching the data plane's // own pre-check always calling tryImportAsset only on a miss. @@ -189,12 +190,13 @@ class CodeArtifactNpmExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void tryImportAssetReturnsFalseWhenUpstreamRetentionIsBlocked() { - when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME)) + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + "EXTERNAL_UPSTREAM")) .thenReturn(true); boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, @@ -202,13 +204,13 @@ class CodeArtifactNpmExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void tryImportAssetReturnsFalseWithoutFinishingWhenTheClaimIsRefused() { when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, - VERSION, "public:npmjs", 42L)) + VERSION, "public:npmjs", RetentionOriginKind.EXTERNAL_CONNECTION, 42L)) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, @@ -331,7 +333,8 @@ class CodeArtifactNpmExternalConnectionImporterTest { @Test void mergedPackumentReturnsEmptyWhenUpstreamRetentionIsBlocked() { - when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME)) + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + "EXTERNAL_UPSTREAM")) .thenReturn(true); Optional merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporterTest.java new file mode 100644 index 0000000000..84130a143c --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmUpstreamRepositoryImporterTest.java @@ -0,0 +1,330 @@ +package io.floci.aws.services.codeartifact; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import 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 java.io.ByteArrayInputStream; +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.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@link CodeArtifactNpmUpstreamRepositoryImporter}'s own decision logic: which candidate it + * resolves a merge or an asset from, and what it writes back. {@link VerdaccioSidecarClient} is + * mocked, so no real Verdaccio call ever happens here; its own wire contract has its own tests. + */ +class CodeArtifactNpmUpstreamRepositoryImporterTest { + + 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 = "widget"; + private static final String VERSION = "1.0.0"; + private static final String ASSET_NAME = "widget-1.0.0.tgz"; + private static final String BASE_URL = "http://localhost:4566/codeartifact/npm/dom/repo/"; + private static final String UPSTREAM_BASE_URL = "http://localhost:4566/codeartifact/npm/dom/upstream/"; + + /** The episode id the default claim stub below hands out; every finish verify reuses it. */ + private static final long EPISODE_ID = 7L; + + private CodeArtifactService service; + private VerdaccioSidecarClient verdaccio; + private CodeArtifactNpmUpstreamRepositoryImporter importer; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + verdaccio = mock(VerdaccioSidecarClient.class); + importer = new CodeArtifactNpmUpstreamRepositoryImporter(service, verdaccio, new ObjectMapper()); + + 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("npm", REGION, DOMAIN, OWNER, UPSTREAM, verdaccio)).thenReturn(UPSTREAM_REPO_ID); + when(verdaccio.publicUrl(DOMAIN, REPOSITORY)).thenReturn(BASE_URL); + when(verdaccio.publicUrl(DOMAIN, UPSTREAM)).thenReturn(UPSTREAM_BASE_URL); + when(verdaccio.ensureReady(REPO_ID, BASE_URL)).thenReturn(BASE_URL); + when(verdaccio.ensureReady(UPSTREAM_REPO_ID, UPSTREAM_BASE_URL)).thenReturn(UPSTREAM_BASE_URL); + when(verdaccio.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION)) + .thenReturn(true); + when(verdaccio.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION)) + .thenReturn(false); + when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString())).thenReturn(42L); + when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString(), anyString())).thenReturn(99L); + when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.UPSTREAM_REPOSITORY), anyLong())) + .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID)); + when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(), + any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true)); + when(service.stageStreamedAsset(any())).thenAnswer(invocation -> { + RepositorySidecarManager.StreamedAsset streamed = invocation.getArgument(0); + Path staged = Files.createTempFile("test-npm-upstream-", ".bin"); + Files.write(staged, streamed.content().readAllBytes()); + return staged; + }); + } + + private JsonNode upstreamDocument(String readme) { + ObjectNode doc = new ObjectMapper().createObjectNode(); + doc.put("name", PACKAGE_NAME); + doc.put("readme", readme); + ObjectNode versions = doc.putObject("versions"); + ObjectNode versionDoc = versions.putObject(VERSION); + versionDoc.put("version", VERSION); + versionDoc.putObject("dist").put("tarball", UPSTREAM_BASE_URL + PACKAGE_NAME + "/-/" + ASSET_NAME); + ObjectNode distTags = doc.putObject("dist-tags"); + distTags.put("latest", VERSION); + return doc; + } + + @Test + void importsFromTheDirectUpstreamWhenNotFoundLocally() { + when(verdaccio.fetchPackageDocument(UPSTREAM_BASE_URL, null, PACKAGE_NAME)) + .thenReturn(Optional.of(upstreamDocument("read me please"))); + byte[] tarballBytes = "tarball-content".getBytes(); + when(verdaccio.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION, ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(tarballBytes), tarballBytes.length))); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("npm"), + any(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID), eq(ASSET_NAME), + eq((long) tarballBytes.length), any()); + verify(service).recordPublishedPackageVersionReadme(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, + PACKAGE_NAME, VERSION, "read me please", 99L); + verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, + PACKAGE_NAME, 42L); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, + PACKAGE_NAME, VERSION, EPISODE_ID, true); + } + + /** + * An Archived candidate's own version must not be resolved; the walk continues to the next + * candidate in priority order instead of stopping there. + */ + @Test + void skipsAnArchivedCandidateAndContinuesToTheNextOne() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("archived", "healthy")); + when(service.resolveContainerIdAndBeginUse("npm", REGION, DOMAIN, OWNER, "archived", verdaccio)).thenReturn("archived-id"); + when(service.resolveContainerIdAndBeginUse("npm", REGION, DOMAIN, OWNER, "healthy", verdaccio)).thenReturn("healthy-id"); + when(verdaccio.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", "npm", + null, PACKAGE_NAME, VERSION, "archived-id"); + when(verdaccio.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION)) + .thenReturn(true); + when(verdaccio.publicUrl(DOMAIN, "healthy")).thenReturn("http://healthy/"); + when(verdaccio.ensureReady("healthy-id", "http://healthy/")).thenReturn("http://healthy/"); + when(verdaccio.fetchPackageDocument("http://healthy/", null, PACKAGE_NAME)) + .thenReturn(Optional.of(upstreamDocument(""))); + byte[] tarballBytes = "tarball-content".getBytes(); + when(verdaccio.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, + VERSION, ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(tarballBytes), tarballBytes.length))); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + // The rejected candidate's lease is released as soon as it's rejected; the eventual + // winner's is held until the whole attempt finishes with it, but both are released + // exactly once by the time this call returns. + verify(verdaccio).endUse("archived-id"); + verify(verdaccio).endUse("healthy-id"); + } + + /** + * A candidate being concurrently deleted/released can throw from {@code + * resolveContainerIdAndBeginUse} itself: treated exactly like "not found" there, same as an + * Archived/Disposed candidate, not propagated. + */ + @Test + void aCandidateBeingConcurrentlyDeletedIsSkippedRatherThanPropagatingTheFailure() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("vanishing", "healthy")); + when(service.resolveContainerIdAndBeginUse("npm", REGION, DOMAIN, OWNER, "vanishing", verdaccio)) + .thenThrow(new IllegalStateException("repository is being deleted")); + when(service.resolveContainerIdAndBeginUse("npm", REGION, DOMAIN, OWNER, "healthy", verdaccio)) + .thenReturn("healthy-id"); + when(verdaccio.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION)) + .thenReturn(true); + when(verdaccio.publicUrl(DOMAIN, "healthy")).thenReturn("http://healthy/"); + when(verdaccio.ensureReady("healthy-id", "http://healthy/")).thenReturn("http://healthy/"); + when(verdaccio.fetchPackageDocument("http://healthy/", null, PACKAGE_NAME)) + .thenReturn(Optional.of(upstreamDocument(""))); + byte[] tarballBytes = "tarball-content".getBytes(); + when(verdaccio.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, + VERSION, ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(tarballBytes), tarballBytes.length))); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + } + + @Test + void returnsFalseWhenNoUpstreamsAreConfigured() { + CodeArtifactRepository repository = new CodeArtifactRepository(); + repository.setUpstreams(List.of()); + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + 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, "npm", null, PACKAGE_NAME, + "INTERNAL_UPSTREAM")).thenReturn(true); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertFalse(imported); + verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWhenNoCandidateHasTheVersionEither() { + when(verdaccio.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION)) + .thenReturn(false); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + 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, "npm", null, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L)) + .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertFalse(imported); + verify(verdaccio, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString()); + verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(), + anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean()); + } + + @Test + void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() { + when(verdaccio.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION)) + .thenReturn(true); + when(service.retainedUpstreamRepositoryOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, PACKAGE_NAME, + VERSION)).thenReturn(Optional.of(UPSTREAM)); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertTrue(imported); + verify(verdaccio, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, + PACKAGE_NAME, VERSION, EPISODE_ID, true); + } + + @Test + void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() { + when(verdaccio.fetchPackageDocument(UPSTREAM_BASE_URL, null, PACKAGE_NAME)) + .thenReturn(Optional.of(upstreamDocument(""))); + byte[] tarballBytes = "tarball-content".getBytes(); + when(verdaccio.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION, ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(tarballBytes), tarballBytes.length))); + 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.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME, + VERSION, ASSET_NAME); + + assertFalse(imported); + verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null, + PACKAGE_NAME, VERSION, EPISODE_ID, false); + } + + @Test + void mergedPackumentMergesTheUpstreamsVersionAndRewritesItsTarballUrl() { + when(verdaccio.fetchPackageDocument(UPSTREAM_BASE_URL, null, PACKAGE_NAME)) + .thenReturn(Optional.of(upstreamDocument(""))); + when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty()); + + Optional merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, + PACKAGE_NAME); + + assertTrue(merged.isPresent()); + JsonNode versionDoc = merged.get().path("versions").path(VERSION); + assertFalse(versionDoc.isMissingNode()); + assertEquals(BASE_URL + PACKAGE_NAME + "/-/" + ASSET_NAME, versionDoc.path("dist").path("tarball").asText()); + assertEquals(VERSION, merged.get().path("dist-tags").path("latest").asText()); + verify(verdaccio).endUse(UPSTREAM_REPO_ID); + } + + @Test + void mergedPackumentReturnsEmptyWhenNoUpstreamsAreConfigured() { + CodeArtifactRepository repository = new CodeArtifactRepository(); + repository.setUpstreams(List.of()); + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); + + Optional merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, + PACKAGE_NAME); + + assertFalse(merged.isPresent()); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java index db3ad3d4e6..04ea15aa74 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetControllerLeaseTest.java @@ -55,7 +55,8 @@ class CodeArtifactNuGetControllerLeaseTest { bagetter = mock(BagetterSidecarClient.class); HttpClient http = mock(HttpClient.class); controller = new CodeArtifactNuGetController(service, bagetter, - mock(CodeArtifactNuGetExternalConnectionImporter.class), http); + mock(CodeArtifactNuGetExternalConnectionImporter.class), + mock(CodeArtifactNuGetUpstreamRepositoryImporter.class), http); headers = mock(HttpHeaders.class); when(headers.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer token"); when(service.resolveAuthorizationToken("token", DOMAIN)) @@ -78,7 +79,8 @@ class CodeArtifactNuGetControllerLeaseTest { void packageVersionsReleasesItsLeaseAfterProxying() throws Exception { HttpClient http = mock(HttpClient.class); controller = new CodeArtifactNuGetController(service, bagetter, - mock(CodeArtifactNuGetExternalConnectionImporter.class), http); + mock(CodeArtifactNuGetExternalConnectionImporter.class), + mock(CodeArtifactNuGetUpstreamRepositoryImporter.class), http); @SuppressWarnings("unchecked") HttpResponse reply = mock(HttpResponse.class); when(reply.statusCode()).thenReturn(404); @@ -107,7 +109,8 @@ class CodeArtifactNuGetControllerLeaseTest { void packageContentStreamsTheNupkgAndReleasesItsLease() throws Exception { HttpClient http = mock(HttpClient.class); controller = new CodeArtifactNuGetController(service, bagetter, - mock(CodeArtifactNuGetExternalConnectionImporter.class), http); + mock(CodeArtifactNuGetExternalConnectionImporter.class), + mock(CodeArtifactNuGetUpstreamRepositoryImporter.class), http); when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "pkg", "1.0.0")).thenReturn(true); byte[] nupkgBytes = "nupkg-bytes".getBytes(StandardCharsets.UTF_8); @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java index 6a6f8cd007..bd8888e08a 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetExternalConnectionImporterTest.java @@ -60,7 +60,8 @@ class CodeArtifactNuGetExternalConnectionImporterTest { List.of(new ExternalConnection("public:nuget-org", "nuget", "AVAILABLE"))); when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString())).thenReturn(false); + any(), anyString(), + eq("EXTERNAL_UPSTREAM"))).thenReturn(false); when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(), anyString(), any(), anyString())).thenReturn(42L); when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(), @@ -68,7 +69,7 @@ class CodeArtifactNuGetExternalConnectionImporterTest { // Unstubbed by default: the claim succeeds, matching the common case of a first or // same-connection retry. Tests for a conflicting claim override this per call. when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString(), anyString(), anyString(), anyLong())) + any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong())) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID)); // Unstubbed by default: BaGetter does not have the version yet, matching the controller's // own pre-check always calling tryImport only on a miss. Tests for the already-retained @@ -110,25 +111,26 @@ class CodeArtifactNuGetExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void returnsFalseWhenUpstreamRetentionIsBlocked() { - when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID)) + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + "EXTERNAL_UPSTREAM")) .thenReturn(true); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void returnsFalseWithoutFinishingWhenTheClaimIsRefused() { when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, - VERSION, "public:nuget-org", 42L)) + VERSION, "public:nuget-org", RetentionOriginKind.EXTERNAL_CONNECTION, 42L)) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporterTest.java new file mode 100644 index 0000000000..67096f4dfd --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNuGetUpstreamRepositoryImporterTest.java @@ -0,0 +1,287 @@ +package io.floci.aws.services.codeartifact; + +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 java.io.ByteArrayInputStream; +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.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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@link CodeArtifactNuGetUpstreamRepositoryImporter}'s own decision logic: when it attempts a + * same-domain upstream-repository fetch at all, which candidate it resolves from, and what it + * writes back. {@link BagetterSidecarClient} is mocked, so no real BaGetter call ever happens + * here; its own wire contract has its own tests. + */ +class CodeArtifactNuGetUpstreamRepositoryImporterTest { + + 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_ID = "Widget"; + private static final String VERSION = "1.0.0"; + private static final String ASSET_NAME = "widget.1.0.0.nupkg"; + private static final byte[] NUPKG_CONTENT = "nupkg-content".getBytes(); + + /** The episode id the default claim stub below hands out; every finish verify reuses it. */ + private static final long EPISODE_ID = 7L; + + private CodeArtifactService service; + private BagetterSidecarClient bagetter; + private CodeArtifactNuGetUpstreamRepositoryImporter importer; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + bagetter = mock(BagetterSidecarClient.class); + importer = new CodeArtifactNuGetUpstreamRepositoryImporter(service, bagetter); + + 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("nuget", REGION, DOMAIN, OWNER, UPSTREAM, bagetter)).thenReturn(UPSTREAM_REPO_ID); + when(bagetter.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, 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(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION)) + .thenReturn(false); + when(bagetter.listPackageVersionAssetNames(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, VERSION)) + .thenReturn(List.of(ASSET_NAME)); + when(bagetter.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, VERSION, + ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(NUPKG_CONTENT), NUPKG_CONTENT.length))); + when(service.stageStreamedAsset(any())).thenAnswer(invocation -> { + RepositorySidecarManager.StreamedAsset streamed = invocation.getArgument(0); + Path staged = Files.createTempFile("test-nuget-upstream-", ".nupkg"); + Files.write(staged, streamed.content().readAllBytes()); + return staged; + }); + 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() { + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("nuget"), + isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID), + eq(ASSET_NAME), eq((long) NUPKG_CONTENT.length), any()); + verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY, + "nuget", null, PACKAGE_ID, 42L, REPO_ID); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, + PACKAGE_ID, VERSION, EPISODE_ID, true); + } + + /** + * {@code src}'s own direct upstreams are {@code [near, far]}; only {@code far} (two hops via + * {@code near}'s own upstream chain, per {@link CodeArtifactService#resolveUpstreamSearchOrder}) + * has the version. Confirms the walk is genuinely followed, not limited to the first miss. + */ + @Test + void resolvesFromADeeperCandidateWhenCloserOnesDoNotHaveIt() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("near", "far")); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "near", bagetter)).thenReturn("near-id"); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "far", bagetter)).thenReturn("far-id"); + when(bagetter.packageVersionExists("near-id", DOMAIN, "near", null, PACKAGE_ID, VERSION)).thenReturn(false); + when(bagetter.packageVersionExists("far-id", DOMAIN, "far", null, PACKAGE_ID, VERSION)).thenReturn(true); + when(bagetter.listPackageVersionAssetNames("far-id", DOMAIN, "far", null, PACKAGE_ID, VERSION)) + .thenReturn(List.of(ASSET_NAME)); + when(bagetter.fetchPackageVersionAssetStreamed("far-id", DOMAIN, "far", null, PACKAGE_ID, VERSION, + ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(NUPKG_CONTENT), NUPKG_CONTENT.length))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + VERSION, "far", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + // The rejected candidate's lease is released as soon as it's rejected; the eventual + // winner's is held until the whole attempt (claim/fetch/write) finishes with it, but both + // are released exactly once by the time this call returns. + verify(bagetter).endUse("near-id"); + verify(bagetter).endUse("far-id"); + } + + /** + * A candidate being concurrently deleted/released can throw from {@code + * resolveContainerIdAndBeginUse} itself (its own registerRepository/beginUse): treated exactly + * like "not found" there, same as an Archived/Disposed candidate, not propagated. + */ + @Test + void aCandidateBeingConcurrentlyDeletedIsSkippedRatherThanPropagatingTheFailure() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("vanishing", "healthy")); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "vanishing", bagetter)) + .thenThrow(new IllegalStateException("repository is being deleted")); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "healthy", bagetter)) + .thenReturn("healthy-id"); + when(bagetter.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION)) + .thenReturn(true); + when(bagetter.listPackageVersionAssetNames("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION)) + .thenReturn(List.of(ASSET_NAME)); + when(bagetter.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION, + ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(NUPKG_CONTENT), NUPKG_CONTENT.length))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + } + + /** + * An Archived candidate's own version must not be resolved; the walk continues to the next + * candidate in priority order instead of stopping there (real AWS's own documented Archived/ + * Disposed-at-the-source propagation). + */ + @Test + void skipsAnArchivedCandidateAndContinuesToTheNextOne() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("archived", "healthy")); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "archived", bagetter)).thenReturn("archived-id"); + when(service.resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, "healthy", bagetter)).thenReturn("healthy-id"); + when(bagetter.packageVersionExists("archived-id", DOMAIN, "archived", null, PACKAGE_ID, VERSION)) + .thenReturn(true); + doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, "archived", "nuget", + null, PACKAGE_ID, VERSION, "archived-id"); + when(bagetter.packageVersionExists("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION)) + .thenReturn(true); + when(bagetter.listPackageVersionAssetNames("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION)) + .thenReturn(List.of(ASSET_NAME)); + when(bagetter.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_ID, VERSION, + ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(NUPKG_CONTENT), NUPKG_CONTENT.length))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(bagetter).endUse("archived-id"); + verify(bagetter).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_ID, 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, "nuget", null, PACKAGE_ID, + "INTERNAL_UPSTREAM")).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertFalse(imported); + verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWhenNoCandidateHasTheVersionEither() { + when(bagetter.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, VERSION)) + .thenReturn(false); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, 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, "nuget", null, PACKAGE_ID, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L)) + .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertFalse(imported); + verify(bagetter, never()).packageVersionExists(eq(REPO_ID), anyString(), anyString(), any(), anyString(), + anyString()); + verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(), + anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean()); + } + + @Test + void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() { + when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION)) + .thenReturn(true); + when(service.retainedUpstreamRepositoryOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID, + VERSION)).thenReturn(Optional.of(UPSTREAM)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION); + + assertTrue(imported); + verify(bagetter, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, + PACKAGE_ID, 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_ID, VERSION); + + assertFalse(imported); + verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(), + anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, + PACKAGE_ID, VERSION, EPISODE_ID, false); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java index 015ba5c97a..1ff6477503 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiControllerTest.java @@ -76,6 +76,7 @@ class CodeArtifactPypiControllerTest { private CodeArtifactService service; private PypiserverSidecarClient pypiserver; private CodeArtifactPypiExternalConnectionImporter externalConnectionImporter; + private CodeArtifactPypiUpstreamRepositoryImporter upstreamRepositoryImporter; private CodeArtifactPypiController controller; private final AtomicReference lastStagedWholeBody = new AtomicReference<>(); @@ -102,6 +103,7 @@ class CodeArtifactPypiControllerTest { // method here, matching a repository with no pypi external connection configured at all; // individual tests below override specific calls to exercise the merge/retention paths. externalConnectionImporter = mock(CodeArtifactPypiExternalConnectionImporter.class); + upstreamRepositoryImporter = mock(CodeArtifactPypiUpstreamRepositoryImporter.class); // service is a mock, so its own real stageAssetBody (which the controller now calls to // stage the whole raw multipart body before scanning it) never runs; stubbed here to // actually stage to a real temp file, the same real behavior the controller depends on to @@ -120,7 +122,8 @@ class CodeArtifactPypiControllerTest { }).when(service).deleteStagedAssetBody(any()); HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); - controller = new CodeArtifactPypiController(service, pypiserver, externalConnectionImporter, httpClient); + controller = new CodeArtifactPypiController(service, pypiserver, externalConnectionImporter, + upstreamRepositoryImporter, httpClient); } @AfterEach diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java index 3f276e0941..bb670a97bd 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiExternalConnectionImporterTest.java @@ -90,13 +90,14 @@ class CodeArtifactPypiExternalConnectionImporterTest { repository.setExternalConnections(List.of(new ExternalConnection("public:pypi", "pypi", "AVAILABLE"))); when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString())).thenReturn(false); + any(), anyString(), + eq("EXTERNAL_UPSTREAM"))).thenReturn(false); when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(), anyString(), any(), anyString())).thenReturn(42L); when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(), any(), anyString(), anyString())).thenReturn(99L); when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(), - any(), anyString(), anyString(), anyString(), anyLong())) + any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong())) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID)); when(pypiserver.listPackageVersionAssetNames(anyString(), anyString(), anyString(), any(), anyString(), anyString())).thenReturn(List.of()); @@ -188,12 +189,13 @@ class CodeArtifactPypiExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void returnsFalseWhenUpstreamRetentionIsBlocked() { - when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME)) + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + "EXTERNAL_UPSTREAM")) .thenReturn(true); boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME); @@ -220,13 +222,13 @@ class CodeArtifactPypiExternalConnectionImporterTest { assertFalse(imported); verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), - anyString(), any(), anyString(), anyString(), anyString(), anyLong()); + anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()); } @Test void returnsFalseWithoutFinishingWhenTheClaimIsRefused() { when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, - VERSION, "public:pypi", 42L)) + VERSION, "public:pypi", RetentionOriginKind.EXTERNAL_CONNECTION, 42L)) .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, SDIST_FILENAME); @@ -383,7 +385,8 @@ class CodeArtifactPypiExternalConnectionImporterTest { @Test void additionalExternalFilenamesReturnsEmptyWhenUpstreamRetentionIsBlocked() { - when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME)) + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + "EXTERNAL_UPSTREAM")) .thenReturn(true); List additional = diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporterTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporterTest.java new file mode 100644 index 0000000000..de26bc4444 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactPypiUpstreamRepositoryImporterTest.java @@ -0,0 +1,360 @@ +package io.floci.aws.services.codeartifact; + +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 java.io.ByteArrayInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +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.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@link CodeArtifactPypiUpstreamRepositoryImporter}'s own decision logic: which candidate it + * resolves a version or a filename merge from, and what it writes back. {@link + * PypiserverSidecarClient} is mocked, so no real pypiserver call ever happens here; its own wire + * contract has its own tests. + */ +class CodeArtifactPypiUpstreamRepositoryImporterTest { + + 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 = "widget"; + private static final String VERSION = "1.0.0"; + private static final String FILENAME = "widget-1.0.0.tar.gz"; + + /** The episode id the default claim stub below hands out; every finish verify reuses it. */ + private static final long EPISODE_ID = 7L; + + private CodeArtifactService service; + private PypiserverSidecarClient pypiserver; + private CodeArtifactPypiUpstreamRepositoryImporter importer; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + pypiserver = mock(PypiserverSidecarClient.class); + importer = new CodeArtifactPypiUpstreamRepositoryImporter(service, pypiserver); + + 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("pypi", REGION, DOMAIN, OWNER, UPSTREAM, pypiserver)) + .thenReturn(UPSTREAM_REPO_ID); + when(pypiserver.listPackageVersions(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME)) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION, + Instant.ofEpochSecond(1000)))); + when(pypiserver.listPackageVersionAssetNames(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION)).thenReturn(List.of(FILENAME)); + 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(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION)) + .thenReturn(List.of()); + when(pypiserver.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION, FILENAME)).thenAnswer(invocation -> { + byte[] content = "tarball-content".getBytes(); + return Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(content), content.length)); + }); + when(service.stageStreamedAsset(any())).thenAnswer(invocation -> { + RepositorySidecarManager.StreamedAsset streamed = invocation.getArgument(0); + Path staged = Files.createTempFile("test-pypi-upstream-", ".bin"); + Files.write(staged, streamed.content().readAllBytes()); + return staged; + }); + 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() { + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"), + any(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID), eq(FILENAME), + eq(15L), any()); + verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY, + "pypi", null, PACKAGE_NAME, 42L, REPO_ID); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, + PACKAGE_NAME, VERSION, EPISODE_ID, true); + } + + /** + * pypi imports every real asset of the resolved version together, not just the one requested: + * both files are written in the same attempt, and the one actually requested is reported. + */ + @Test + void importsEveryAssetOfTheResolvedVersionNotJustTheRequestedOne() { + String sibling = "widget-1.0.0-py3-none-any.whl"; + when(pypiserver.listPackageVersionAssetNames(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION)).thenReturn(List.of(FILENAME, sibling)); + when(pypiserver.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, + VERSION, sibling)).thenAnswer(invocation -> { + byte[] content = "wheel-content".getBytes(); + return Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(content), content.length)); + }); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"), + any(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), anyLong(), eq(REPO_ID), eq(FILENAME), + anyLong(), any()); + verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("pypi"), + any(), eq(PACKAGE_NAME), eq(VERSION), anyLong(), anyLong(), anyLong(), eq(REPO_ID), eq(sibling), + anyLong(), any()); + } + + /** + * {@code repo}'s own direct upstreams are {@code [near, far]}; only {@code far} (two hops via + * {@code near}'s own upstream chain) has the version. Confirms the walk is genuinely followed + * and the real, deep source is recorded. + */ + @Test + void resolvesFromADeeperCandidateWhenCloserOnesDoNotHaveIt() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("near", "far")); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "near", pypiserver)).thenReturn("near-id"); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "far", pypiserver)).thenReturn("far-id"); + when(pypiserver.listPackageVersions("near-id", DOMAIN, "near", null, PACKAGE_NAME)).thenReturn(List.of()); + when(pypiserver.listPackageVersions("far-id", DOMAIN, "far", null, PACKAGE_NAME)) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION, + Instant.ofEpochSecond(1000)))); + when(pypiserver.listPackageVersionAssetNames("far-id", DOMAIN, "far", null, PACKAGE_NAME, VERSION)) + .thenReturn(List.of(FILENAME)); + when(pypiserver.fetchPackageVersionAssetStreamed("far-id", DOMAIN, "far", null, PACKAGE_NAME, VERSION, + FILENAME)).thenAnswer(invocation -> { + byte[] content = "tarball-content".getBytes(); + return Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(content), content.length)); + }); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + VERSION, "far", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + // The rejected candidate's lease is released as soon as it's rejected; the eventual + // winner's is held until the whole attempt finishes with it, but both are released + // exactly once by the time this call returns. + verify(pypiserver).endUse("near-id"); + verify(pypiserver).endUse("far-id"); + } + + /** + * A candidate being concurrently deleted/released can throw from {@code + * resolveContainerIdAndBeginUse} itself: treated exactly like "not found" there, same as an + * Archived/Disposed candidate, not propagated. + */ + @Test + void aCandidateBeingConcurrentlyDeletedIsSkippedRatherThanPropagatingTheFailure() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("vanishing", "healthy")); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "vanishing", pypiserver)) + .thenThrow(new IllegalStateException("repository is being deleted")); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "healthy", pypiserver)) + .thenReturn("healthy-id"); + when(pypiserver.listPackageVersions("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME)) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION, + Instant.ofEpochSecond(1000)))); + when(pypiserver.listPackageVersionAssetNames("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION)) + .thenReturn(List.of(FILENAME)); + when(pypiserver.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, + VERSION, FILENAME)).thenAnswer(invocation -> { + byte[] content = "tarball-content".getBytes(); + return Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(content), content.length)); + }); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + } + + /** + * An Archived candidate's own version must not be resolved; the walk continues to the next + * candidate in priority order instead of stopping there. + */ + @Test + void skipsAnArchivedCandidateAndContinuesToTheNextOne() { + when(service.resolveUpstreamSearchOrder(REGION, DOMAIN, OWNER, REPOSITORY)) + .thenReturn(List.of("archived", "healthy")); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "archived", pypiserver)).thenReturn("archived-id"); + when(service.resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, "healthy", pypiserver)).thenReturn("healthy-id"); + when(pypiserver.listPackageVersions("archived-id", DOMAIN, "archived", null, PACKAGE_NAME)) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION, + Instant.ofEpochSecond(1000)))); + doThrow(new AwsException("ResourceNotFoundException", "Package version was not found.", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, "archived", "pypi", + null, PACKAGE_NAME, VERSION, "archived-id"); + when(pypiserver.listPackageVersions("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME)) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION, + Instant.ofEpochSecond(1000)))); + when(pypiserver.listPackageVersionAssetNames("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, VERSION)) + .thenReturn(List.of(FILENAME)); + when(pypiserver.fetchPackageVersionAssetStreamed("healthy-id", DOMAIN, "healthy", null, PACKAGE_NAME, + VERSION, FILENAME)).thenAnswer(invocation -> { + byte[] content = "tarball-content".getBytes(); + return Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(content), content.length)); + }); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + VERSION, "healthy", RetentionOriginKind.UPSTREAM_REPOSITORY, 42L); + verify(pypiserver).endUse("archived-id"); + verify(pypiserver).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.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + 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, "pypi", null, PACKAGE_NAME, + "INTERNAL_UPSTREAM")).thenReturn(true); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertFalse(imported); + verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong()); + } + + @Test + void returnsFalseWhenNoCandidateHasTheVersionEither() { + when(pypiserver.listPackageVersions(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME)) + .thenReturn(List.of()); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + 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, "pypi", null, PACKAGE_NAME, + VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L)) + .thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L)); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertFalse(imported); + verify(pypiserver, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString()); + verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(), + anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean()); + } + + @Test + void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() { + when(pypiserver.listPackageVersionAssetNames(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION)) + .thenReturn(List.of(FILENAME)); + when(service.retainedUpstreamRepositoryOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, PACKAGE_NAME, + VERSION)).thenReturn(Optional.of(UPSTREAM)); + + boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertTrue(imported); + verify(pypiserver, never()).fetchPackageVersionAssetStreamed(anyString(), anyString(), anyString(), any(), + anyString(), anyString(), anyString()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", 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.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME); + + assertFalse(imported); + verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(), + anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString()); + verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null, + PACKAGE_NAME, VERSION, EPISODE_ID, false); + } + + @Test + void additionalInternalFilenamesListsTheUpstreamsOwnFilesNotAlreadyKnown() { + List additional = importer + .additionalInternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, Set.of()); + + assertTrue(additional.stream().anyMatch(f -> f.filename().equals(FILENAME))); + assertTrue(additional.stream().allMatch(f -> !f.yanked() && f.requiresPythonOrNull() == null)); + } + + @Test + void additionalInternalFilenamesOmitsAFilenameAlreadyKnownLocally() { + List additional = importer + .additionalInternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, + Set.of(FILENAME)); + + assertTrue(additional.isEmpty()); + } + + @Test + void additionalInternalFilenamesReturnsEmptyWhenNoUpstreamsAreConfigured() { + CodeArtifactRepository repository = new CodeArtifactRepository(); + repository.setUpstreams(List.of()); + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); + + List additional = importer + .additionalInternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, Set.of()); + + assertTrue(additional.isEmpty()); + } +} diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java index 9334c5afa9..eb23ae0bd3 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactServiceTest.java @@ -74,6 +74,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -604,7 +605,8 @@ class CodeArtifactServiceTest { return published; }); CodeArtifactNuGetController controller = new CodeArtifactNuGetController(service, bagetterClient, - mock(CodeArtifactNuGetExternalConnectionImporter.class), http); + mock(CodeArtifactNuGetExternalConnectionImporter.class), + mock(CodeArtifactNuGetUpstreamRepositoryImporter.class), http); byte[] packageBytes; try (ByteArrayOutputStream output = new ByteArrayOutputStream(); ZipOutputStream zip = @@ -741,14 +743,14 @@ class CodeArtifactServiceTest { long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "nuget", null, "demo", "1.0.0"); CodeArtifactService.RetainedVersionOriginClaimOutcome oldClaim = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", packageFence); + "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); assertTrue(oldClaim.claimed()); service.deleteRepository(REGION, "dom", null, "repo"); CodeArtifactRepository replacement = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); assertNotEquals(oldId, replacement.getSidecarContainerIds().get("nuget")); CodeArtifactService.RetainedVersionOriginClaimOutcome newClaim = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", packageFence); + "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); assertTrue(newClaim.claimed()); assertNotEquals(oldClaim.episodeId(), newClaim.episodeId()); @@ -777,7 +779,7 @@ class CodeArtifactServiceTest { long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "nuget", null, "demo", "1.0.0"); CodeArtifactService.RetainedVersionOriginClaimOutcome newClaim = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", packageFence); + "dom", null, "repo", "nuget", null, "demo", "1.0.0", "public:nuget.org", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); assertTrue(newClaim.claimed()); AtomicBoolean wroteOldAsset = new AtomicBoolean(); @@ -1020,6 +1022,41 @@ class CodeArtifactServiceTest { assertEquals("ValidationException", e.getErrorCode()); } + @Test + void updateRepositoryRejectsATwoRepositoryCycle() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-b", null, List.of("repo-a"), Map.of()); + + AwsException e = assertThrows(AwsException.class, + () -> service.updateRepository(REGION, "dom", null, "repo-a", null, List.of("repo-b"))); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void updateRepositoryRejectsALongerCycle() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-b", null, List.of("repo-a"), Map.of()); + service.createRepository(REGION, "dom", null, "repo-c", null, List.of("repo-b"), Map.of()); + + AwsException e = assertThrows(AwsException.class, + () -> service.updateRepository(REGION, "dom", null, "repo-a", null, List.of("repo-c"))); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void aNonCyclicUpstreamChainIsAccepted() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-b", null, List.of("repo-a"), Map.of()); + + CodeArtifactRepository repoC = service.createRepository(REGION, "dom", null, "repo-c", null, + List.of("repo-b"), Map.of()); + + assertEquals(List.of("repo-b"), repoC.getUpstreams()); + } + @Test void createRepositoryAssignsFreshContainerIdsForEveryContainerBackedFormat() { service.createDomain(REGION, "dom", null, Map.of()); @@ -2341,7 +2378,8 @@ class CodeArtifactServiceTest { service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", - "widget")); + "widget", + "EXTERNAL_UPSTREAM")); } @Test @@ -2352,7 +2390,8 @@ class CodeArtifactServiceTest { "BLOCK"); assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", - "widget")); + "widget", + "EXTERNAL_UPSTREAM")); } /** @@ -2377,10 +2416,11 @@ class CodeArtifactServiceTest { // Simulates tryImport's own claim for this version, still in flight (never finished): no // configuration is saved yet, but real content from this same in-progress import exists. service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0", - "public:maven-central", fence); + "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence); assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", - "widget")); + "widget", + "EXTERNAL_UPSTREAM")); } /** @@ -2398,7 +2438,8 @@ class CodeArtifactServiceTest { when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true); assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", - "widget")); + "widget", + "EXTERNAL_UPSTREAM")); } @Test @@ -2488,7 +2529,7 @@ class CodeArtifactServiceTest { long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "nuget", null, "widget", "1.0.0"); CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "nuget", null, "widget", "1.0.0", "public:nuget-org", packageFence); + "dom", null, "repo", "nuget", null, "widget", "1.0.0", "public:nuget-org", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); AtomicBoolean wroteOldAsset = new AtomicBoolean(); CodeArtifactService.AssetRetentionAttemptResult retained = service.retainAssetUnderVersionFence(REGION, @@ -2540,17 +2581,17 @@ class CodeArtifactServiceTest { "com.example", "widget", "1.0")); CodeArtifactService.MavenClaimOutcome first = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "repo", "com.example", "widget", "1.0", "public:maven-central", fence); + "repo", "com.example", "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence); assertTrue(first.claimed()); // Same connection claiming again (an idempotent retry, or a concurrent request for the // same version and source) succeeds too, and shares the same episode. CodeArtifactService.MavenClaimOutcome second = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "repo", "com.example", "widget", "1.0", "public:maven-central", fence); + "repo", "com.example", "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence); assertTrue(second.claimed()); assertEquals(first.episodeId(), second.episodeId()); // A different connection trying to claim the same version loses: the origin never moves. assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-clojars", fence).claimed()); + "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, fence).claimed()); // Not reported as retained yet: two attempts are still in flight and neither has finished. assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo", "com.example", "widget", "1.0")); @@ -2561,6 +2602,71 @@ class CodeArtifactServiceTest { null, "repo", "com.example", "widget", "1.0")); } + /** + * The widened claim store distinguishes a connection name from an upstream repository's name + * by kind, not just by the raw name string being different: a claim taken under {@code + * UPSTREAM_REPOSITORY} for a given name must reject a concurrent attempt under {@code + * EXTERNAL_CONNECTION} for that exact same name, the same way two different connection names + * already reject each other in {@link #claimMavenRetainedVersionOriginIsAtomicPerVersion}. + * {@code retainedUpstreamRepositoryOrigin}/{@code mavenRetainedVersionOriginConnection} only + * ever report a confirmed name under their own matching kind, never the other's. + */ + @Test + void claimedOriginKindIsPartOfTheClaimsIdentityNotJustTheNameString() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "upstream-repo", null, null, Map.of()); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + + CodeArtifactService.MavenClaimOutcome upstreamClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", + null, "repo", "com.example", "widget", "1.0", "upstream-repo", + RetentionOriginKind.UPSTREAM_REPOSITORY, fence); + assertTrue(upstreamClaim.claimed()); + // Same name, different kind: must not be treated as the same source. + assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", + "1.0", "upstream-repo", RetentionOriginKind.EXTERNAL_CONNECTION, fence).claimed()); + + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + upstreamClaim.episodeId(), true); + + assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo", + "com.example", "widget", "1.0")); + assertEquals(Optional.of("upstream-repo"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, + "repo", "maven", "com.example", "widget", "1.0")); + } + + /** + * {@code originType} stays {@code "INTERNAL"} for a same-domain upstream-repository retention + * (real AWS's own {@code PackageVersionOrigin.originType} has no third value for this), with + * {@code domainEntryPoint.repositoryName} set to the actual upstream, not the requesting + * repository: the risk flagged when this was built was wiring it to {@code "EXTERNAL"} by + * analogy with the connection case, which this test exists to catch. + */ + @Test + void listPackageVersionsReportsAnUpstreamRepositoryRetentionAsInternalWithTheUpstreamsName() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "upstream-repo", null, null, Map.of()); + when(verdaccioClient.listPackageVersions(anyString(), eq("dom"), eq("repo"), isNull(), eq("widget"))) + .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0", + Instant.ofEpochSecond(1000)))); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", null, "widget"); + CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(REGION, + "dom", null, "repo", "npm", null, "widget", "1.0", "upstream-repo", + RetentionOriginKind.UPSTREAM_REPOSITORY, fence); + service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "npm", null, "widget", "1.0", + claim.episodeId(), true); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "npm", null, "widget", null, null, null, null, null); + + CodeArtifactService.PackageVersionSummary summary = result.versions().get(0); + assertEquals("INTERNAL", summary.originType()); + assertEquals(null, summary.externalConnectionName()); + assertEquals("upstream-repo", summary.upstreamRepositoryName()); + } + @Test void claimMavenRetainedVersionOriginFailsWhenTheFenceHasMoved() { service.createDomain(REGION, "dom", null, Map.of()); @@ -2572,7 +2678,7 @@ class CodeArtifactServiceTest { long staleFence = currentFence + 1; assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-central", staleFence).claimed()); + "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, staleFence).claimed()); assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo", "com.example", "widget", "1.0")); } @@ -2585,9 +2691,9 @@ class CodeArtifactServiceTest { "widget"); // Two concurrent attempts under the same connection, both still in flight, same episode. long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", fence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence).episodeId(); service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0", - "public:maven-central", fence); + "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence); // The first attempt finishes having retained nothing; the second is still mid-fetch. // A plain claim-or-reject check would let this exact finish remove the shared claim @@ -2597,14 +2703,14 @@ class CodeArtifactServiceTest { service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", episodeId, false); assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-clojars", fence).claimed()); + "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, fence).claimed()); // The second attempt finishes, also empty: now nothing is left relying on the claim, and // nothing was ever confirmed, so it is finally free for a different connection. service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", episodeId, false); assertTrue(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-clojars", fence).claimed()); + "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, fence).claimed()); } @Test @@ -2614,7 +2720,7 @@ class CodeArtifactServiceTest { long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", fence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence).episodeId(); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", episodeId, true); @@ -2624,7 +2730,7 @@ class CodeArtifactServiceTest { // A real retention happened under this connection: a different connection can never claim // this exact version afterward, no matter how long ago every attempt finished. assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-clojars", fence).claimed()); + "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, fence).claimed()); } @Test @@ -2634,7 +2740,7 @@ class CodeArtifactServiceTest { long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long realEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", fence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence).episodeId(); // A finish call carrying an episodeId that never matched any claim (made up here to // stand in for one whose own episode was already torn down and replaced by this one) @@ -2666,7 +2772,7 @@ class CodeArtifactServiceTest { long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", fence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, fence).episodeId(); // The old episode is torn down entirely, not through a finish call: some real content // already exists for this package (however it got there), so DeletePackage finds @@ -2681,7 +2787,7 @@ class CodeArtifactServiceTest { long freshFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long freshEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", freshFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, freshFence).episodeId(); assertNotEquals(staleEpisodeId, freshEpisodeId); // The old attempt's finish call, arriving late and carrying its own stale episodeId, must @@ -2690,7 +2796,7 @@ class CodeArtifactServiceTest { staleEpisodeId, false); assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", - "1.0", "public:maven-clojars", freshFence).claimed()); + "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, freshFence).claimed()); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", freshEpisodeId, true); assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom", @@ -2712,7 +2818,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, episodeId, @@ -2740,7 +2846,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, episodeId, reposiliteClient, repoId, gav, content); @@ -2761,7 +2867,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0", staleVersionFence, packageFence, episodeId, @@ -2802,7 +2908,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); String gav = "com/example/widget/1.0/widget-1.0.jar"; CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, @@ -2837,7 +2943,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget"); long episodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, episodeId, reposiliteClient, repoId, gav, content); assertEquals(content.length, service.describeDomain(REGION, "dom", null).assetSizeBytes()); @@ -2887,7 +2993,7 @@ class CodeArtifactServiceTest { // until after it finishes empty-handed and a fresh claim follows below (simulating a // fetch still in flight for a real network write that arrives only after that). long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", - "widget", "1.0", "public:maven-central", packageFence).episodeId(); + "widget", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence).episodeId(); // Finds nothing from the public repository: releases its own claim, touching neither fence. service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", @@ -2897,7 +3003,7 @@ class CodeArtifactServiceTest { // A fresh claim, under a different connection, succeeds because the old claim is gone. service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0", - "public:maven-clojars", packageFence); + "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); // The stalled attempt's own late write finally arrives and tries to write under its own // stale episode: both fences still match (neither was ever bumped), so only the episode @@ -2934,10 +3040,10 @@ class CodeArtifactServiceTest { boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( - StandardCharsets.UTF_8), v -> true); + StandardCharsets.UTF_8), v -> true, false); assertFalse(merged); - verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any()); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any(), anyBoolean()); } @Test @@ -2950,14 +3056,14 @@ class CodeArtifactServiceTest { "com.example", "widget"); byte[] metadataBytes = "".getBytes(StandardCharsets.UTF_8); when(reposiliteClient.mergeExternalConnectionReleaseVersions(eq(repoId), eq("com.example"), eq("widget"), - eq(metadataBytes), any())).thenReturn(true); + eq(metadataBytes), any(), anyBoolean())).thenReturn(true); boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", - "widget", packageFenceSnapshot, reposiliteClient, repoId, metadataBytes, v -> true); + "widget", packageFenceSnapshot, reposiliteClient, repoId, metadataBytes, v -> true, false); assertTrue(merged); verify(reposiliteClient).mergeExternalConnectionReleaseVersions(eq(repoId), eq("com.example"), eq("widget"), - eq(metadataBytes), any()); + eq(metadataBytes), any(), anyBoolean()); } /** @@ -2990,10 +3096,10 @@ class CodeArtifactServiceTest { boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( - StandardCharsets.UTF_8), v -> true); + StandardCharsets.UTF_8), v -> true, false); assertFalse(merged); - verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any()); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any(), anyBoolean()); } /** @@ -3017,10 +3123,10 @@ class CodeArtifactServiceTest { boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( - StandardCharsets.UTF_8), v -> true); + StandardCharsets.UTF_8), v -> true, false); assertFalse(merged); - verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any()); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any(), anyBoolean()); } /** @@ -3572,7 +3678,7 @@ class CodeArtifactServiceTest { long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven", "com.example", "a"); CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "src", "com.example", "a", "1.0", "public:maven-central", srcPackageFence); + "src", "com.example", "a", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, srcPackageFence); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "src", "com.example", "a", "1.0", srcClaim.episodeId(), true); @@ -3632,13 +3738,13 @@ class CodeArtifactServiceTest { long srcPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "src", "maven", "com.example", "a"); CodeArtifactService.MavenClaimOutcome srcClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "src", "com.example", "a", "1.0", "public:maven-clojars", srcPackageFence); + "src", "com.example", "a", "1.0", "public:maven-clojars", RetentionOriginKind.EXTERNAL_CONNECTION, srcPackageFence); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "src", "com.example", "a", "1.0", srcClaim.episodeId(), true); long dstPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "dst", "maven", "com.example", "a"); CodeArtifactService.MavenClaimOutcome dstClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "dst", "com.example", "a", "1.0", "public:maven-central", dstPackageFence); + "dst", "com.example", "a", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, dstPackageFence); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0", dstClaim.episodeId(), true); @@ -3687,7 +3793,7 @@ class CodeArtifactServiceTest { long dstPackageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "dst", "maven", "com.example", "a"); CodeArtifactService.MavenClaimOutcome dstClaim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "dst", "com.example", "a", "1.0", "public:maven-central", dstPackageFence); + "dst", "com.example", "a", "1.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, dstPackageFence); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0", dstClaim.episodeId(), true); @@ -3752,6 +3858,102 @@ class CodeArtifactServiceTest { assertTrue(result.successfulVersions().isEmpty()); } + /** + * {@code includeFromUpstream} for a container-backed format: the same mechanism as the + * generic branch (see {@link #copyPackageVersionsWithIncludeFromUpstreamResolvesFromADirectUpstreamRepository}), + * exercised here against Maven's own {@code copyContainerBackedPackageVersions} bridge + * instead of the generic path's {@code packageVersions} store. + */ + @Test + void copyPackageVersionsWithIncludeFromUpstreamResolvesFromAnUpstreamRepositoryForMaven() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository parent = service.createRepository(REGION, "dom", null, "parent", null, null, + Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + String parentRepoId = parent.getSidecarContainerIds().get("maven"); + String dstRepoId = dst.getSidecarContainerIds().get("maven"); + byte[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.packageVersionExists(eq(parentRepoId), eq("dom"), eq("parent"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(true); + when(reposiliteClient.listPackageVersionAssetNames(eq(parentRepoId), eq("dom"), eq("parent"), + eq("com.example"), eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(parentRepoId), eq("dom"), eq("parent"), + eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer(invocation -> + Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(jarBytes), jarBytes.length))); + AtomicReference copiedJar = captureCopiedAssetContent(reposiliteClient, parentRepoId, "parent", + dstRepoId, "dst", "com.example", "a", "1.0", "a-1.0.jar"); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertArrayEquals(jarBytes, copiedJar.get()); + assertEquals(Optional.of("parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "maven", "com.example", "a", "1.0")); + } + + @Test + void copyPackageVersionsWithIncludeFromUpstreamStillFailsNotFoundForMavenWhenNoUpstreamHasItEither() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, true); + + assertEquals("NOT_FOUND", result.failedVersions().get("1.0").errorCode()); + assertTrue(result.successfulVersions().isEmpty()); + } + + /** + * Stricter than the direct-source check (which only ever excludes Disposed): an Archived + * version at the first candidate upstream must not be resolved, and the walk must continue to + * the next candidate in priority order, the same rule the generic branch's own equivalent + * test confirms. + */ + @Test + void copyPackageVersionsWithIncludeFromUpstreamSkipsAnArchivedMavenCandidateForTheNextOne() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository archivedParent = service.createRepository(REGION, "dom", null, "archived-parent", + null, null, Map.of()); + CodeArtifactRepository healthyParent = service.createRepository(REGION, "dom", null, "healthy-parent", null, + null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, + List.of("archived-parent", "healthy-parent"), Map.of()); + CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + String archivedParentRepoId = archivedParent.getSidecarContainerIds().get("maven"); + String healthyParentRepoId = healthyParent.getSidecarContainerIds().get("maven"); + String dstRepoId = dst.getSidecarContainerIds().get("maven"); + byte[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.packageVersionExists(eq(archivedParentRepoId), eq("dom"), eq("archived-parent"), + eq("com.example"), eq("a"), eq("1.0"))).thenReturn(true); + when(reposiliteClient.listPackageVersions(eq(archivedParentRepoId), eq("dom"), eq("archived-parent"), + eq("com.example"), eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)))); + service.updatePackageVersionsStatus(REGION, "dom", null, "archived-parent", "maven", "com.example", "a", + List.of("1.0"), null, null, "Archived"); + when(reposiliteClient.packageVersionExists(eq(healthyParentRepoId), eq("dom"), eq("healthy-parent"), + eq("com.example"), eq("a"), eq("1.0"))).thenReturn(true); + when(reposiliteClient.listPackageVersionAssetNames(eq(healthyParentRepoId), eq("dom"), eq("healthy-parent"), + eq("com.example"), eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAssetStreamed(eq(healthyParentRepoId), eq("dom"), + eq("healthy-parent"), eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenAnswer( + invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset( + new ByteArrayInputStream(jarBytes), jarBytes.length))); + captureCopiedAssetContent(reposiliteClient, healthyParentRepoId, "healthy-parent", dstRepoId, "dst", + "com.example", "a", "1.0", "a-1.0.jar"); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.of("healthy-parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, + "dst", "maven", "com.example", "a", "1.0")); + } + @Test void copyPackageVersionsSkipsAMavenVersionThatWouldHaveSucceededWhenASiblingIsNotFound() { service.createDomain(REGION, "dom", null, Map.of()); @@ -4146,6 +4348,202 @@ class CodeArtifactServiceTest { assertEquals("NOT_FOUND", result.failedVersions().get("9.9.9").errorCode()); } + /** + * {@code includeFromUpstream} (real AWS flag, default {@code false}): a miss against the + * literal source repository is NOT_FOUND unless this is set, even when a configured upstream + * genuinely has the version. Confirms today's default behavior is completely unchanged. + */ + @Test + void copyPackageVersionsWithoutIncludeFromUpstreamNeverSearchesTheUpstreamChain() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false); + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("NOT_FOUND", result.failedVersions().get("1.0.0").errorCode()); + } + + @Test + void copyPackageVersionsWithIncludeFromUpstreamResolvesFromADirectUpstreamRepository() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals("1.0.0", service.describePackageVersion(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", + "1.0.0").getVersion()); + assertEquals(Optional.of("parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + + /** + * {@code src -> parent -> grandparent}, the version only published at {@code grandparent}: + * confirms the resolution walk is genuinely transitive (see {@link UpstreamRepositoryResolver} + * and {@link #resolveUpstreamSearchOrder}), not limited to {@code src}'s own direct list, and + * that the claim records the real (deep) source, not an intermediate hop. + */ + @Test + void copyPackageVersionsWithIncludeFromUpstreamResolvesFromATransitiveUpstreamRepository() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "grandparent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, List.of("grandparent"), Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("grandparent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.of("grandparent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + + @Test + void copyPackageVersionsWithIncludeFromUpstreamStillFailsNotFoundWhenNoUpstreamHasItEither() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, true); + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("NOT_FOUND", result.failedVersions().get("1.0.0").errorCode()); + } + + /** + * Stricter than the direct-source check (which only ever excludes {@code Disposed}): an + * Archived version at the first candidate upstream must not be resolved, and the walk must + * continue on to the next candidate in priority order instead of stopping there. + */ + @Test + void copyPackageVersionsWithIncludeFromUpstreamSkipsAnArchivedCandidateForTheNextOne() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "archived-parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "healthy-parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("archived-parent", "healthy-parent"), + Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("archived-parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.updatePackageVersionsStatus(REGION, "dom", null, "archived-parent", "generic", "ns", "my-pkg", + List.of("1.0.0"), null, null, "Archived"); + publishGeneric("healthy-parent", "my-pkg", "1.0.0", "y".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.of("healthy-parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, + "dst", "generic", "ns", "my-pkg", "1.0.0")); + } + + /** + * A version found directly at the literal source repository records no claim at all, even + * with {@code includeFromUpstream} set: this emulator never carries a source's own existing + * claim (if it had one) forward on a plain copy, matching {@code copyPackageVersions}'s own + * design choice (see its own javadoc on {@code copyMavenRetainedVersionOriginIfApplicable}'s + * container-backed-only counterpart). + */ + @Test + void copyPackageVersionsFoundDirectlyAtTheSourceRecordsNoUpstreamClaimEvenWithIncludeFromUpstream() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, true); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.empty(), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + + /** + * A generic version retained via {@code includeFromUpstream} and then deleted and republished + * under the same coordinates must not keep reporting the old upstream repository: {@link + * #deletePackageVersions} must clear the claim, the same way it already does for every + * container-backed format. + */ + @Test + void deletingAnUpstreamRetainedGenericVersionClearsItsOriginClaim() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.copyPackageVersions(REGION, "dom", null, "src", "dst", "generic", "ns", "my-pkg", + List.of("1.0.0"), null, false, true); + assertEquals(Optional.of("parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + + service.deletePackageVersions(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null); + publishGeneric("dst", "my-pkg", "1.0.0", "y".getBytes(StandardCharsets.UTF_8)); + + assertEquals(Optional.empty(), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + + /** {@link #deletePackage}'s own generic branch must clear the same claim, not just its + * per-version sibling above. + */ + @Test + void deletingAnUpstreamRetainedGenericPackageClearsItsOriginClaim() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.copyPackageVersions(REGION, "dom", null, "src", "dst", "generic", "ns", "my-pkg", + List.of("1.0.0"), null, false, true); + assertEquals(Optional.of("parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + + service.deletePackage(REGION, "dom", null, "dst", "generic", "ns", "my-pkg"); + publishGeneric("dst", "my-pkg", "1.0.0", "y".getBytes(StandardCharsets.UTF_8)); + + assertEquals(Optional.empty(), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + + /** + * A direct {@code CopyPackageVersions} overwrite (resolved straight from the literal {@code + * sourceRepository}, not the upstream chain) must clear a stale claim an earlier {@code + * includeFromUpstream} overwrite left at this same destination coordinate, not just skip + * adding a new one. + */ + @Test + void overwritingAnUpstreamRetainedGenericVersionWithADirectCopyClearsItsOriginClaim() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "parent", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, List.of("parent"), Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("parent", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.copyPackageVersions(REGION, "dom", null, "src", "dst", "generic", "ns", "my-pkg", + List.of("1.0.0"), null, false, true); + assertEquals(Optional.of("parent"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + publishGeneric("src", "my-pkg", "1.0.0", "y".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, true, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.empty(), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "dst", + "generic", "ns", "my-pkg", "1.0.0")); + } + /** * AWS's own documented example (array-unique 0.2.0/5.6.7): one requested version missing from * the source repository fails the whole call, and every other requested version that would @@ -4926,7 +5324,7 @@ class CodeArtifactServiceTest { long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "a"); CodeArtifactService.MavenClaimOutcome claim = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, - "repo", "com.example", "a", "2.0", "public:maven-central", packageFence); + "repo", "com.example", "a", "2.0", "public:maven-central", RetentionOriginKind.EXTERNAL_CONNECTION, packageFence); service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "a", "2.0", claim.episodeId(), true); @@ -5228,7 +5626,7 @@ class CodeArtifactServiceTest { String repoId = created.getSidecarContainerIds().get("npm"); long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", null, "my-pkg"); CodeArtifactService.RetainedVersionOriginClaimOutcome outcome = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "npm", null, "my-pkg", "1.0.0", "public:npmjs", fence); + "dom", null, "repo", "npm", null, "my-pkg", "1.0.0", "public:npmjs", RetentionOriginKind.EXTERNAL_CONNECTION, fence); service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "npm", null, "my-pkg", "1.0.0", outcome.episodeId(), true); when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), @@ -6085,7 +6483,7 @@ class CodeArtifactServiceTest { long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "nuget", null, "my-pkg"); CodeArtifactService.RetainedVersionOriginClaimOutcome outcome = service.claimRetainedVersionOrigin(REGION, - "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", "public:nuget-org", fence); + "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", "public:nuget-org", RetentionOriginKind.EXTERNAL_CONNECTION, fence); service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", outcome.episodeId(), true); assertEquals("public:nuget-org", service.retainedVersionOriginConnection(REGION, "dom", null, "repo", @@ -7409,7 +7807,8 @@ class CodeArtifactServiceTest { String legacyKey = REGION + "::dom::repo::" + format + "::::" + original; packageOriginConfigStore.putForAccount(ACCOUNT_ID, legacyKey, new PackageOriginConfig("BLOCK", "BLOCK", format, null, original)); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized, + "EXTERNAL_UPSTREAM")); } @Test @@ -7426,7 +7825,8 @@ class CodeArtifactServiceTest { service.createDomain(REGION, "dom", null, Map.of()); service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); service.putPackageOriginConfiguration(REGION, "dom", null, "repo", format, null, original, "BLOCK", "BLOCK"); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized, + "EXTERNAL_UPSTREAM")); } @Test void readingLegacyOriginConfigMigratesItBeforeRemovingTheOldKey() { @@ -7453,7 +7853,8 @@ class CodeArtifactServiceTest { "ALLOW", "ALLOW"); assertEquals(List.of(REGION + "::dom::repo::pypi::::my-proj"), packageOriginConfigStore.keysForAccount(ACCOUNT_ID).stream().sorted().toList()); - assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ", + "EXTERNAL_UPSTREAM")); } @Test @@ -7464,7 +7865,8 @@ class CodeArtifactServiceTest { packageOriginConfigStore.putForAccount("999999999999", REGION + "::dom::repo::nuget::::Newtonsoft.Json", config); packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::other::nuget::::Newtonsoft.Json", config); packageOriginConfigStore.putForAccount(ACCOUNT_ID, OTHER_REGION + "::dom::repo::nuget::::Newtonsoft.Json", config); - assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "nuget", null, "newtonsoft.json")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "nuget", null, "newtonsoft.json", + "EXTERNAL_UPSTREAM")); assertTrue(packageOriginConfigStore.getForAccount(ACCOUNT_ID, REGION + "::dom::repo::nuget::::newtonsoft.json").isEmpty()); assertEquals(2, packageOriginConfigStore.keysForAccount(ACCOUNT_ID).size()); @@ -7494,7 +7896,8 @@ class CodeArtifactServiceTest { new PackageOriginConfig("ALLOW", "ALLOW", "pypi", null, "my-proj")); packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::My_Proj", new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); - assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ", + "EXTERNAL_UPSTREAM")); service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my-proj"); assertTrue(packageOriginConfigStore.keysForAccount(ACCOUNT_ID).isEmpty()); assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo", @@ -7517,13 +7920,15 @@ class CodeArtifactServiceTest { doThrow(new IllegalStateException("save failed")).when(store) .putForAccount(eq(ACCOUNT_ID), eq(canonicalKey), any(PackageOriginConfig.class)); assertThrows(IllegalStateException.class, () -> failingService.isUpstreamRetentionBlocked(REGION, - "dom", null, "repo", "nuget", null, "newtonsoft.json")); + "dom", null, "repo", "nuget", null, "newtonsoft.json", + "EXTERNAL_UPSTREAM")); assertTrue(store.getForAccount(ACCOUNT_ID, legacyKey).isPresent()); assertTrue(store.getForAccount(ACCOUNT_ID, canonicalKey).isEmpty()); doAnswer(invocation -> invocation.callRealMethod()).when(store) .putForAccount(eq(ACCOUNT_ID), eq(canonicalKey), any(PackageOriginConfig.class)); assertTrue(failingService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "nuget", null, - "newtonsoft.json")); + "newtonsoft.json", + "EXTERNAL_UPSTREAM")); assertTrue(store.getForAccount(ACCOUNT_ID, legacyKey).isEmpty()); assertTrue(store.getForAccount(ACCOUNT_ID, canonicalKey).isPresent()); } @@ -7539,7 +7944,8 @@ class CodeArtifactServiceTest { for (String name : List.of("first", "second")) { lookupService.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", format, null, name); - assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, name)); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, name, + "EXTERNAL_UPSTREAM")); assertThrows(AwsException.class, () -> lookupService.describePackage(REGION, "dom", null, "repo", format, null, name)); lookupService.listPackages(REGION, "dom", null, "repo", format, null, null, null, null, null, null); @@ -7561,11 +7967,13 @@ class CodeArtifactServiceTest { origins.putForAccount(ACCOUNT_ID, legacy, new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); doThrow(new IllegalStateException("controlled delete failure")).when(origins).deleteForAccount(ACCOUNT_ID, legacy); assertThrows(IllegalStateException.class, () -> lookupService.isUpstreamRetentionBlocked(REGION, - "dom", null, "repo", "pypi", null, "my-proj")); + "dom", null, "repo", "pypi", null, "my-proj", + "EXTERNAL_UPSTREAM")); assertTrue(origins.getForAccount(ACCOUNT_ID, canonical).isPresent()); assertTrue(origins.getForAccount(ACCOUNT_ID, legacy).isPresent()); doAnswer(invocation -> invocation.callRealMethod()).when(origins).deleteForAccount(ACCOUNT_ID, legacy); - assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj")); + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj", + "EXTERNAL_UPSTREAM")); assertTrue(origins.getForAccount(ACCOUNT_ID, legacy).isEmpty()); lookupService.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "pypi", null, "new"); verify(origins, times(2)).keysForAccount(ACCOUNT_ID); @@ -7575,13 +7983,15 @@ class CodeArtifactServiceTest { void clearingServiceResetsAccountMigration() { AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); CodeArtifactService lookupService = originLookupService(origins); - assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "absent")); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "absent", + "EXTERNAL_UPSTREAM")); lookupService.clear(); lookupService.createDomain(REGION, "dom", null, Map.of()); lookupService.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); origins.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::My_Proj", new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); - assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj")); + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj", + "EXTERNAL_UPSTREAM")); verify(origins, times(2)).keysForAccount(ACCOUNT_ID); } @@ -7598,7 +8008,8 @@ class CodeArtifactServiceTest { assertEquals("BLOCK", lookupService.describePackage(REGION, "dom", null, "repo", format, null, "first").publishRestriction()); - assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "second")); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "second", + "EXTERNAL_UPSTREAM")); verify(origins, never()).putForAccount(anyString(), anyString(), any(PackageOriginConfig.class)); verify(origins, never()).deleteForAccount(anyString(), anyString()); @@ -7616,7 +8027,8 @@ class CodeArtifactServiceTest { origins.putForAccount(ACCOUNT_ID, legacy, new PackageOriginConfig("BLOCK", "ALLOW", format, null, "EXAMPLE")); clearInvocations(origins); - assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "example")); + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "example", + "EXTERNAL_UPSTREAM")); PackageOriginConfig repaired = origins.getForAccount(ACCOUNT_ID, canonical).orElseThrow(); assertEquals(format, repaired.getFormat()); @@ -7998,7 +8410,8 @@ class CodeArtifactServiceTest { service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", Map.of("EXTERNAL_UPSTREAM", "BLOCK"), List.of(), List.of()); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "EXTERNAL_UPSTREAM")); } @Test @@ -8011,8 +8424,10 @@ class CodeArtifactServiceTest { Map.of("EXTERNAL_UPSTREAM", "ALLOW_SPECIFIC_REPOSITORIES"), List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "EXTERNAL_UPSTREAM")), List.of()); - assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-a", "npm", null, "my-pkg")); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-b", "npm", null, "other-pkg")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-a", "npm", null, "my-pkg", + "EXTERNAL_UPSTREAM")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-b", "npm", null, "other-pkg", + "EXTERNAL_UPSTREAM")); } @Test @@ -8021,7 +8436,8 @@ class CodeArtifactServiceTest { service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); service.createPackageGroup(REGION, "dom", null, "/npm//AsyncStorage$", null, null, Map.of()); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "asyncstorage")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "asyncstorage", + "EXTERNAL_UPSTREAM")); } @Test @@ -8029,7 +8445,8 @@ class CodeArtifactServiceTest { service.createDomain(REGION, "dom", null, Map.of()); service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); - assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "EXTERNAL_UPSTREAM")); } @Test @@ -8039,7 +8456,79 @@ class CodeArtifactServiceTest { service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()); service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "npm", null, "my-pkg", "ALLOW", "BLOCK"); - assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "EXTERNAL_UPSTREAM")); + } + + /** + * {@code INTERNAL_UPSTREAM}'s own equivalent of {@link + * #isUpstreamRetentionBlockedIsBlockedByAnAssociatedGroupsBlockMode}: the one line that + * actually differs between the two restriction types ({@code groupAllowsRestriction}'s own + * restriction-type argument) is exercised here instead of {@code EXTERNAL_UPSTREAM}. + */ + @Test + void isUpstreamRetentionBlockedIsBlockedByAnAssociatedGroupsBlockModeUnderInternalUpstreamToo() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()); + service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", + Map.of("INTERNAL_UPSTREAM", "BLOCK"), List.of(), List.of()); + + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "INTERNAL_UPSTREAM")); + } + + /** + * Confirms the two restriction types are genuinely independent, not just two names for the + * same stored mode: {@code EXTERNAL_UPSTREAM} allowed while {@code INTERNAL_UPSTREAM} is + * blocked on the exact same group/package, each restriction type's own call reflecting only + * its own mode. + */ + @Test + void externalUpstreamAndInternalUpstreamAreCheckedIndependently() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()); + service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", + Map.of("EXTERNAL_UPSTREAM", "ALLOW", "INTERNAL_UPSTREAM", "BLOCK"), List.of(), List.of()); + + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "EXTERNAL_UPSTREAM")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg", + "INTERNAL_UPSTREAM")); + } + + @Test + void isUpstreamRetentionBlockedAllowsOnlyTheRepositoryListedForAllowSpecificRepositoriesUnderInternalUpstream() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of()); + service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()); + service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", + Map.of("INTERNAL_UPSTREAM", "ALLOW_SPECIFIC_REPOSITORIES"), + List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "INTERNAL_UPSTREAM")), List.of()); + + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-a", "npm", null, "my-pkg", + "INTERNAL_UPSTREAM")); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-b", "npm", null, "other-pkg", + "INTERNAL_UPSTREAM")); + } + + /** + * The weak-match-forces-BLOCK rule is documented generically ("preventing any new versions of + * the package from being pulled from upstreams or published"), not scoped to {@code + * EXTERNAL_UPSTREAM} by name: confirms it applies to {@code INTERNAL_UPSTREAM} too, the same + * way {@link #isUpstreamRetentionBlockedIsBlockedByAWeakMatchRegardlessOfTheGroupsMode} + * already confirms it for {@code EXTERNAL_UPSTREAM}. + */ + @Test + void isUpstreamRetentionBlockedIsBlockedByAWeakMatchUnderInternalUpstreamToo() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.createPackageGroup(REGION, "dom", null, "/npm//AsyncStorage$", null, null, Map.of()); + + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "asyncstorage", + "INTERNAL_UPSTREAM")); } @Test diff --git a/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java b/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java index d6263a8730..26db4f075c 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/ReposiliteSidecarClientTest.java @@ -937,7 +937,7 @@ class ReposiliteSidecarClientTest { + "1.11.2"; boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertTrue(merged); String xml = new String(putBody.get(), StandardCharsets.UTF_8); @@ -979,7 +979,7 @@ class ReposiliteSidecarClientTest { + ""; client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertEquals(Digests.sha1Hex(putBody.get()), new String(sha1Body.get(), StandardCharsets.UTF_8)); assertEquals(Digests.md5Hex(putBody.get()), new String(md5Body.get(), StandardCharsets.UTF_8)); @@ -1009,7 +1009,7 @@ class ReposiliteSidecarClientTest { // own metadata has no idea that happened, so a merge must never let a rejected version // back in just because the public source still lists it. boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> !v.equals("1.1")); + externalXml.getBytes(StandardCharsets.UTF_8), v -> !v.equals("1.1"), false); assertTrue(merged); String xml = new String(putBody.get(), StandardCharsets.UTF_8); @@ -1036,7 +1036,7 @@ class ReposiliteSidecarClientTest { + ""; assertThrows(IllegalStateException.class, () -> client.mergeExternalConnectionReleaseVersions("dom--repo", - "com.example", "a", externalXml.getBytes(StandardCharsets.UTF_8), v -> true)); + "com.example", "a", externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false)); } /** @@ -1070,7 +1070,7 @@ class ReposiliteSidecarClientTest { + "1.1"; boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertTrue(merged); String xml = new String(putBody.get(), StandardCharsets.UTF_8); @@ -1100,7 +1100,7 @@ class ReposiliteSidecarClientTest { + "1.1-SNAPSHOT"; boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertTrue(merged); String xml = new String(putBody.get(), StandardCharsets.UTF_8); @@ -1108,6 +1108,39 @@ class ReposiliteSidecarClientTest { assertEquals("1.0", XmlParser.extractFirst(xml, "latest", null)); } + /** + * {@code allowSnapshots=true} (16f-UPSTREAM-REPO's same-domain upstream case) keeps a + * {@code -SNAPSHOT} version that {@code allowSnapshots=false} (the real-registry external + * connection case, covered just above) would have filtered out. + */ + @Test + void mergeExternalConnectionReleaseVersionsKeepsSnapshotVersionsWhenAllowed() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 404, ""); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.1-SNAPSHOT1.0" + + "1.1-SNAPSHOT"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, true); + + assertTrue(merged); + String xml = new String(putBody.get(), StandardCharsets.UTF_8); + assertEquals(List.of("1.0", "1.1-SNAPSHOT"), XmlParser.extractAll(xml, "version")); + } + @Test void mergeExternalConnectionReleaseVersionsIsANoOpWhenEveryExternalVersionIsAlreadyListedLocally() { settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); @@ -1132,7 +1165,7 @@ class ReposiliteSidecarClientTest { + "versioning>"; boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertFalse(merged); assertNull(putBody.get()); @@ -1174,7 +1207,7 @@ class ReposiliteSidecarClientTest { + "versioning>"; boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", - externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + externalXml.getBytes(StandardCharsets.UTF_8), v -> true, false); assertFalse(merged); assertEquals(Digests.sha1Hex(existing.getBytes(StandardCharsets.UTF_8)), diff --git a/src/test/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolverTest.java b/src/test/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolverTest.java new file mode 100644 index 0000000000..8d1121c78d --- /dev/null +++ b/src/test/java/io/floci/aws/services/codeartifact/UpstreamRepositoryResolverTest.java @@ -0,0 +1,163 @@ +package io.floci.aws.services.codeartifact; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@code resolveSearchOrder}'s own javadoc works through the exact A/B/C/D counterexample this + * test locks in: a depth-first walk would wrongly search a 2-hop match before a 1-hop sibling. + */ +class UpstreamRepositoryResolverTest { + + @Test + void directUpstreamsAreSearchedBeforeAnyOfTheirOwnTransitiveUpstreams() { + // A -> [B, C], B -> [D]. A depth-first walk reaches D (via B) before C, a direct upstream + // of A; the correct, breadth-first order is B, C (both direct), then D. + Map> upstreams = Map.of( + "A", List.of("B", "C"), + "B", List.of("D"), + "C", List.of(), + "D", List.of()); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get); + + assertEquals(List.of("B", "C", "D"), order); + } + + @Test + void aCycleTerminatesInsteadOfLoopingForever() { + Map> upstreams = Map.of( + "A", List.of("B"), + "B", List.of("A")); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get); + + assertEquals(List.of("B"), order); + } + + @Test + void aLongerCycleTerminatesWithoutRevisitingAnyRepository() { + Map> upstreams = Map.of( + "A", List.of("B"), + "B", List.of("C"), + "C", List.of("A")); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get); + + assertEquals(List.of("B", "C"), order); + } + + @Test + void aRepositoryReachableThroughTwoPathsAppearsExactlyOnce() { + // A -> [B, C], B -> [D], C -> [D]: D is reachable from both B and C, but must only be + // searched once, at the position its first discovery (through B) places it. + Map> upstreams = Map.of( + "A", List.of("B", "C"), + "B", List.of("D"), + "C", List.of("D"), + "D", List.of()); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get); + + assertEquals(List.of("B", "C", "D"), order); + } + + @Test + void theStartingRepositoryItselfIsNeverIncluded() { + Map> upstreams = Map.of("A", List.of("B"), "B", List.of()); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get); + + assertEquals(List.of("B"), order); + assertTrue(order.stream().noneMatch("A"::equals)); + } + + @Test + void aChainLongerThanTheCapStopsAtTheCapRatherThanSearchingForever() { + // A chain of 30 repositories, each the sole upstream of the previous one: R0 -> R1 -> ... + // -> R29. The walk must stop at MAX_RESOLUTION_REPOSITORIES (25) rather than continuing + // past AWS's own documented region-wide search ceiling. + Map> upstreams = new HashMap<>(); + for (int i = 0; i < 30; i++) { + String name = "R" + i; + String next = i + 1 < 30 ? "R" + (i + 1) : null; + upstreams.put(name, next == null ? List.of() : List.of(next)); + } + + List order = UpstreamRepositoryResolver.resolveSearchOrder("R0", upstreams::get); + + assertEquals(UpstreamRepositoryResolver.MAX_RESOLUTION_REPOSITORIES, order.size()); + assertEquals(List.of("R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", + "R12", "R13", "R14", "R15", "R16", "R17", "R18", "R19", "R20", "R21", "R22", "R23", + "R24", "R25"), order); + } + + @Test + void anUnknownRepositoryHasNoUpstreamsAndStopsTheWalkThere() { + Map> upstreams = Map.of("A", List.of("unknown")); + + List order = UpstreamRepositoryResolver.resolveSearchOrder("A", + name -> upstreams.getOrDefault(name, List.of())); + + assertEquals(List.of("unknown"), order); + } + + @Test + void isReachableFindsADirectUpstream() { + Map> upstreams = Map.of("A", List.of("B"), "B", List.of()); + + assertTrue(UpstreamRepositoryResolver.isReachable("A", "B", upstreams::get)); + } + + @Test + void isReachableFindsATransitiveUpstream() { + Map> upstreams = Map.of("A", List.of("B"), "B", List.of("C"), "C", List.of()); + + assertTrue(UpstreamRepositoryResolver.isReachable("A", "C", upstreams::get)); + } + + @Test + void isReachableIsFalseWhenTheTargetIsNotInTheGraphAtAll() { + Map> upstreams = Map.of("A", List.of("B"), "B", List.of()); + + assertFalse(UpstreamRepositoryResolver.isReachable("A", "Z", upstreams::get)); + } + + @Test + void isReachableTerminatesOnACycleThatNeverReachesTheTarget() { + Map> upstreams = Map.of("A", List.of("B"), "B", List.of("A")); + + assertFalse(UpstreamRepositoryResolver.isReachable("A", "Z", upstreams::get)); + } + + /** + * Locks in the fix for the exact gap {@code resolveSearchOrder}'s own cap would otherwise leave + * in {@code validateUpstreams}'s cycle check: a chain of more than {@code + * MAX_RESOLUTION_REPOSITORIES} (25) repositories whose closing edge sits beyond that cap must + * still be found reachable, since a domain can hold far more repositories (AWS's own documented + * 1,000-per-domain quota) than any one resolution ever searches. + */ + @Test + void isReachableFindsATargetBeyondTheResolutionSearchCap() { + Map> upstreams = new HashMap<>(); + int chainLength = UpstreamRepositoryResolver.MAX_RESOLUTION_REPOSITORIES + 5; + for (int i = 0; i < chainLength; i++) { + String name = "R" + i; + String next = i + 1 < chainLength ? "R" + (i + 1) : null; + upstreams.put(name, next == null ? List.of() : List.of(next)); + } + String target = "R" + (chainLength - 1); + + assertTrue(UpstreamRepositoryResolver.isReachable("R0", target, upstreams::get)); + // Confirms resolveSearchOrder genuinely would not have found it, so this test is actually + // exercising the gap isReachable closes, not a scenario the capped walk already covered. + assertFalse(UpstreamRepositoryResolver.resolveSearchOrder("R0", upstreams::get).contains(target)); + } +}