From a03e88b4510514587973ec268dc9600a1a304d94 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:04:57 -0400 Subject: [PATCH] feat(codeartifact): retain Maven packages from a public external connection (#6889) GetAuthorizationToken-authenticated Maven GET/HEAD requests now retain a missing release version from the repository's own public:maven-* external connection (Maven Central, Clojars, CommonsWare, Google Android, Gradle Plugins), the way real CodeArtifact does, instead of always 404ing. Follows AWS's own documented rules: release versions only (SNAPSHOT is never imported through an external connection); the standard pom/jar/-javadoc.jar/-sources.jar set imported together on a standard 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 it, rejecting one from a different connection; package-level upstream:BLOCK respected; and a direct mvn deploy of a version already present in the connection rejected (ConflictException), matching AWS's documented publish-side behavior. Retained bytes are counted toward DescribeDomain's assetSizeBytes the same way a direct deploy already is, gated on the real deploy outcome rather than merely having fetched the bytes, and never double-counted on an idempotent-match retry. Verified against the real, live Maven Central in a Docker-gated integration test (junit 4.13.2), and manually with a real mvn client through a wildcard mirror. --- docs/services/codeartifact.md | 73 +- .../codeartifact/CodeArtifactController.java | 11 +- .../CodeArtifactMavenController.java | 40 +- ...tifactMavenExternalConnectionImporter.java | 266 +++++++ .../codeartifact/CodeArtifactService.java | 538 ++++++++++++- .../MavenExternalConnectionClient.java | 151 ++++ .../model/CodeArtifactPackageVersion.java | 13 + ...ternalConnectionDockerIntegrationTest.java | 154 ++++ ...ctMavenExternalConnectionImporterTest.java | 396 ++++++++++ .../codeartifact/CodeArtifactServiceTest.java | 719 ++++++++++++++++++ .../MavenExternalConnectionClientTest.java | 156 ++++ 11 files changed, 2471 insertions(+), 46 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClient.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClientTest.java diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index eeb75438f8..6b6ce79ac7 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -71,6 +71,21 @@ enforces the one-external-connection-per-repository limit AWS enforces. A reposi upstream repositories or an external connection, but not both, matching AWS; `CreateRepository` and `UpdateRepository` also cap direct upstreams at 10, AWS's own repository limit. +For the Maven format specifically, an external connection is more than stored metadata: a real +`mvn`/Gradle GET or HEAD miss on a repository with one of the 5 Maven external connections +attached (`public:maven-central`, `public:maven-clojars`, `public:maven-commonsware`, +`public:maven-googleandroid`, `public:maven-gradleplugins`) is retried against the real public +repository and, if found, retained into the repository exactly as a real CodeArtifact repository +would, with the same AWS-documented rules a real one applies: release versions only (AWS never imports a Maven SNAPSHOT through an external +connection), the standard `.pom`/`.jar`/`-javadoc.jar`/`-sources.jar` set imported together on a +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/pypi/nuget's own +external connections). + `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 always accepted; once `Published`, a new asset name always conflicts, since real CodeArtifact never @@ -291,9 +306,10 @@ 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, since Floci has no - upstream-ingestion path for any format to begin with (see - the upstream-resolution limitation below). + 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. - **The 5 GB asset size quota is nominal.** `PublishPackageVersion` and the Maven, pypi, and nuget repository endpoints all receive the request body as a single byte array before Floci ever checks its length, so a request already large enough to exhaust available heap fails before the @@ -324,17 +340,33 @@ 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. -- **None of the Maven, npm, pypi, or nuget repository endpoints resolve through upstream - repositories or external connections.** On real CodeArtifact, a repository with another - repository configured as an upstream (`UpdateRepository`'s `upstreams`) or with an - `AssociateExternalConnection` to a public repository (`public:maven-central`, `public:npmjs`, - `public:pypi`, `public:nuget-org`, etc.) serves packages from those sources too, not just its - own. Floci's proxies only ever look up the repository's own backing storage: a package that - exists solely in an upstream, or only through an external connection, returns 404 through a - repository that has it configured as one; the pypi proxy's pypiserver container is started with - `--disable-fallback`, and the nuget proxy's BaGetter container with `Mirror__Enabled=false`, - specifically so neither ever silently redirects a missing package to the real, public PyPI or - nuget.org. +- **Only the Maven endpoint's own external connection actually resolves; nothing else does.** + 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 + now 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 + rules (release versions only; the standard 4 assets imported together, a non-standard asset + name imported only on demand; a retained version's origin checked against any later asset + fetched for it, rejecting one from a different connection; `upstream: BLOCK` respected). A real + `mvn deploy` of a version already present in the external connection is also rejected (409), + matching AWS's documented publish-side behavior. None of this applies to a repository-to- + repository upstream (`UpdateRepository`'s `upstreams`, for any format including Maven, which is + a materially different mechanism, not yet built) or to npm, pypi, or nuget's own external + connections, which still 404 exactly as before: the pypi proxy's pypiserver container is + started with `--disable-fallback`, and the nuget proxy's BaGetter container with + `Mirror__Enabled=false`, specifically so neither ever silently redirects a missing package to + the real, public PyPI or nuget.org. +- **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 + miss simply 404s, exactly as AWS documents ("the only workaround is to try again later"). + There is no caching of that failure, so a later retry against a recovered source works + immediately, but there is also no retry/backoff of its own beyond the client's own. + Package-group-level `EXTERNAL_UPSTREAM` (once package groups exist in this emulator) is not + consulted yet by this check, only the plain package-level `upstream` restriction. - **The npm repository endpoint does not enforce the 5 GB asset size quota.** Unlike `PublishPackageVersion` and the Maven endpoint, it streams the request straight through to the backing Verdaccio container rather than buffering it first, so there is nowhere in the request @@ -368,9 +400,11 @@ state. AWS's own documented restriction that only NuGet's V3 protocol works against CodeArtifact at all and that `nuget list` specifically isn't supported. - **`DescribePackage`'s origin controls default to `publish: ALLOW`/`upstream: BLOCK`** (the - default for a package whose first version was published directly, since Floci never ingests - packages from an upstream source) **until a caller sets them explicitly with - `PutPackageOriginConfiguration`.** For Maven, npm, pypi, and nuget, `DescribePackage` asks the + default for a package whose first version was published directly) **until a caller sets them + explicitly with `PutPackageOriginConfiguration`, or until the package's first version is + retained from a Maven external connection, which instead defaults it to `publish: BLOCK`/ + `upstream: ALLOW`**, matching AWS's own documented "ingested from a public source" default. For + Maven, npm, pypi, and nuget, `DescribePackage` asks the repository's sidecar whether the package exists, which starts that sidecar if it is not already running; a package that exists only because `PutPackageOriginConfiguration` created it (no versions yet) is found without touching any sidecar. @@ -379,8 +413,9 @@ 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 but is never enforced for any of them, since Floci has no upstream ingestion path to - block in the first place. `CopyPackageVersions` deliberately does not check `publish: BLOCK` + 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. - **`DescribeDomain`'s `assetSizeBytes` only counts what was published after this field started diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java index 3dd434d258..995f05e747 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java @@ -486,8 +486,13 @@ public class CodeArtifactController { node.put("revision", summary.revision()); node.put("status", summary.status()); ObjectNode origin = node.putObject("origin"); - origin.put("originType", "INTERNAL"); - origin.putObject("domainEntryPoint").put("repositoryName", repository); + origin.put("originType", summary.originType()); + ObjectNode domainEntryPoint = origin.putObject("domainEntryPoint"); + if (summary.externalConnectionName() != null) { + domainEntryPoint.put("externalConnectionName", summary.externalConnectionName()); + } else { + domainEntryPoint.put("repositoryName", repository); + } }); if (result.nextToken() != null) { response.put("nextToken", result.nextToken()); @@ -818,7 +823,7 @@ public class CodeArtifactController { node.put("publishedTime", pv.getPublishedTime()); } ObjectNode origin = node.putObject("origin"); - origin.put("originType", "INTERNAL"); + origin.put("originType", pv.getOriginType()); node.putArray("licenses"); return node; } diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java index 4853c2a085..1eb326c495 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java @@ -44,11 +44,14 @@ public class CodeArtifactMavenController { private final CodeArtifactService service; private final ReposiliteSidecarClient reposilite; + private final CodeArtifactMavenExternalConnectionImporter externalConnectionImporter; @Inject - public CodeArtifactMavenController(CodeArtifactService service, ReposiliteSidecarClient reposilite) { + public CodeArtifactMavenController(CodeArtifactService service, ReposiliteSidecarClient reposilite, + CodeArtifactMavenExternalConnectionImporter externalConnectionImporter) { this.service = service; this.reposilite = reposilite; + this.externalConnectionImporter = externalConnectionImporter; } @PUT @@ -84,6 +87,17 @@ public class CodeArtifactMavenController { } catch (AwsException e) { return Response.status(409).entity(e.getMessage()).build(); } + // AWS's own documented behavior: "CodeArtifact will not permit publishing a package + // version that is already present in the external repository." Checked only for a + // well-formed, versioned GAV, same scope as the Archived/Disposed guard above; a bare + // maven-metadata.xml PUT is never a specific version to check either way. + if (externalConnectionImporter.existsInExternalConnection(scope.region(), domain, scope.owner(), + repository, gav)) { + return Response.status(409) + .entity("A version of this package is already present in the repository's external " + + "connection and cannot be republished directly.") + .build(); + } } // Snapshotted before the real write, not after: see // CodeArtifactService#currentContainerBackedPackageFence's own javadoc for why the order @@ -138,7 +152,7 @@ public class CodeArtifactMavenController { * name. The version element has no such approximation to make: it is {@code null} exactly * when there genuinely is no version in the path. */ - private static Optional parseNamespaceAndPackageName(String gav) { + static Optional parseNamespaceAndPackageName(String gav) { String[] segments = gav.split("/"); boolean metadataFile = isMavenMetadataFile(segments[segments.length - 1]); int packageNameIndex = metadataFile ? segments.length - 2 : segments.length - 3; @@ -163,9 +177,12 @@ public class CodeArtifactMavenController { if (!isDownloadable(scope, domain, repository, gav)) { return Response.status(Response.Status.NOT_FOUND).build(); } - return reposilite.fetchArtifact(scope.repoId(), gav) - .map(this::toResponse) - .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); + Optional artifact = reposilite.fetchArtifact(scope.repoId(), gav); + if (artifact.isEmpty() && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), + repository, scope.repoId(), gav)) { + artifact = reposilite.fetchArtifact(scope.repoId(), gav); + } + return artifact.map(this::toResponse).orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); } @HEAD @@ -175,9 +192,16 @@ public class CodeArtifactMavenController { if (!isDownloadable(scope, domain, repository, gav)) { return Response.status(Response.Status.NOT_FOUND).build(); } - return reposilite.artifactExists(scope.repoId(), gav) - ? Response.ok().build() - : Response.status(Response.Status.NOT_FOUND).build(); + // A dependency resolver can probe with HEAD before ever issuing the GET that would + // otherwise trigger retention below, so a miss here must attempt the same import a GET + // miss would, or a HEAD-first client would see a false "not found" before the real GET + // ever gets the chance to retain it. + boolean exists = reposilite.artifactExists(scope.repoId(), gav); + if (!exists && externalConnectionImporter.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/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java new file mode 100644 index 0000000000..fd2d5cb2aa --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java @@ -0,0 +1,266 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Optional; + +/** + * Retains a Maven package version from the real public repository a repository's {@code + * public:maven-*} external connection names, the way real CodeArtifact does when a {@code mvn}/ + * Gradle client requests a GAV that is not present locally yet. Confirmed against the User + * Guide's own "Connect a CodeArtifact repository to a public repository" and "Requesting Maven + * packages from upstreams and external connections" sections, not inferred: + * + *
    + *
  • Release versions only. "AWS CodeArtifact only supports importing Maven release + * versions" through an external connection; a {@code -SNAPSHOT} version is never attempted.
  • + *
  • Standard assets, imported together. When the requested filename matches one of the + * 4 names CodeArtifact's own docs enumerate ({@code -.pom/.jar/ + * -javadoc.jar/-sources.jar}), every reachable one of the 4 is imported in the same attempt, + * best-effort (a missing javadoc/sources jar is normal, not a failure).
  • + *
  • Non-standard assets, imported on demand only. A filename that does not match the + * standard shape (the docs' own {@code aapt2-7.3.1-8691043-windows.jar} example) is checked and + * imported individually, exactly as requested, never guessing at siblings this emulator has no + * way to list from the real public repository.
  • + *
  • Checking asset origins. A package version's retention origin, once confirmed, never + * changes (see {@link CodeArtifactService#claimMavenRetainedVersionOrigin}'s own javadoc); an + * import attempt under a different connection than what is already claimed for that exact + * version is refused outright, "prevent[ing] creating a 'mixed' package version where + * different assets originate from different public repositories", refused before any asset is + * ever fetched or written, and the claim stays reserved for as long as any concurrent attempt + * under the original connection is still in flight, even one that ultimately writes nothing; + * the claim's own episode identity, not just the connection name, is what a finished attempt + * checks before touching it, so a stray finish from an old, long-torn-down episode can never + * be mistaken for one belonging to a brand new episode claimed later under the same name. The + * same episode identity is checked again, under the same lock, right before each asset is + * actually written, so a claim torn down and reclaimed under a different connection while this + * attempt was still fetching cannot have its stale write land under the new claim's name.
  • + *
  • Coordinated with this emulator's own deletion and disposal. A fetch from the + * public source can take long enough for a concurrent {@code DeletePackageVersions}/{@code + * DeletePackage}/{@code DeleteRepository}/{@code DisposePackageVersions} on this exact version + * to finish first; each candidate's own write, via {@link + * CodeArtifactService#deployMavenAssetUnderVersionFence}, happens inside the exact same lock + * those four operations already hold for their entire duration, so the two can never + * interleave: whichever gets there first finishes completely before the other even starts, + * closing the race outright rather than narrowing the window it can land in. That same call + * also checks the version's current status directly, not just its fence, so a request already + * admitted before a disposal that finished before this attempt's own snapshot was even taken + * can never write real bytes back for a version already marked unusable.
  • + *
+ * + *

Deliberately not modeled here, because it cannot apply without an actual upstream + * repository chain: AWS's documented rule that an Archived/Disposed status on an + * upstream repository's own copy of a version blocks retaining it further downstream. A direct + * external connection has no such upstream repository in the picture at all, and the real public + * source has no CodeArtifact-shaped status to check. + */ +@ApplicationScoped +public class CodeArtifactMavenExternalConnectionImporter { + + private static final Logger LOG = Logger.getLogger(CodeArtifactMavenExternalConnectionImporter.class); + + private final CodeArtifactService service; + private final ReposiliteSidecarClient reposilite; + private final MavenExternalConnectionClient externalConnectionClient; + + @Inject + public CodeArtifactMavenExternalConnectionImporter(CodeArtifactService service, + ReposiliteSidecarClient reposilite, MavenExternalConnectionClient externalConnectionClient) { + this.service = service; + this.reposilite = reposilite; + this.externalConnectionClient = externalConnectionClient; + } + + /** + * Attempts to retain {@code gav} (and, for a standard asset name, its 3 standard siblings) + * into {@code repoId} from {@code repository}'s own maven external connection. Returns + * {@code true} only when the originally-requested asset itself was imported: a caller that + * gets {@code false} back should fall through to its own existing not-found response exactly + * as if this method had never been called, the same way AWS's own "the only workaround is to + * try again later" applies when nothing here can help (no connection configured, the version + * is a SNAPSHOT, retention is blocked, a mixed-origin conflict, or the real public repository + * genuinely doesn't have it). + */ + public boolean tryImport(String region, String domain, String owner, String repository, String repoId, + String gav) { + Optional coordinate = CodeArtifactMavenController.parseNamespaceAndPackageName(gav); + if (coordinate.isEmpty() || coordinate.get()[2] == null || coordinate.get()[2].endsWith("-SNAPSHOT")) { + return false; + } + String namespace = coordinate.get()[0]; + String packageName = coordinate.get()[1]; + String version = coordinate.get()[2]; + + String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository); + if (externalConnectionName == null) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, + packageName)) { + return false; + } + + // Snapshotted before the claim and the real writes below, not after, the same ordering + // CodeArtifactMavenController#deploy already relies on: a DeletePackage landing mid-import + // must not have its removal silently undone by the claim, the byte accounting, or the + // default-config bookkeeping this retention attempt is about to record. + long fenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, "maven", + namespace, packageName); + // Snapshotted here, before the claim below, not after it: a DisposePackageVersions that + // completes in the gap between the claim succeeding and a later snapshot read would + // already have bumped the fence by the time that later read ran, so the read would + // capture the post-disposal value as though it were the normal starting point, never + // noticing anything was amiss. Taken first, any disposal landing anywhere after this + // line, including during the claim call itself, is guaranteed to bump the fence to a + // value strictly higher than what is captured here, which the later locked check inside + // deployMavenAssetUnderVersionFence can then actually detect. + long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository, + "maven", namespace, packageName, version); + // Claims the version's origin atomically, before any network fetch happens at all: see + // claimMavenRetainedVersionOrigin's own javadoc for the race this closes (two concurrent + // imports under two different connections could otherwise both pass a read-then-write + // 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); + 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 candidates = standardNames.contains(filename) ? standardNames : List.of(filename); + + boolean importedRequestedAsset = false; + boolean importedAny = false; + try { + for (String candidateFilename : candidates) { + String candidateGav = directory + candidateFilename; + Optional fetched; + try { + fetched = externalConnectionClient.fetchAsset(externalConnectionName, candidateGav); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0} from {1} while retaining a Maven release through an " + + "external connection; skipping this candidate.", candidateGav, externalConnectionName); + continue; + } + if (fetched.isEmpty()) { + continue; + } + byte[] content = fetched.get().content(); + // The fence check and the real write happen inside the very same synchronized + // call DeletePackageVersions/DeletePackage/DeleteRepository/DisposePackageVersions + // already hold across their own entire operation, so a write here and one of + // those four operations can never interleave: whichever gets there first finishes + // completely before the other even starts. See deployMavenAssetUnderVersionFence's + // own javadoc for why this has to be a method on the service itself rather than a + // block synchronized on the injected reference here: only a lock actually taken + // inside that class's own synchronized method is guaranteed to be the exact same + // lock its other synchronized methods already hold. + // packageFenceSnapshot is passed through so byte accounting (when this write + // genuinely adds new content) runs inside this exact same locked call too, + // rather than in a separate call after this one already released the lock, which + // would let a delete or disposal subtract this asset's bytes as part of its own + // normal cleanup before that separate call added them, permanently over-counting + // DescribeDomain's total for an asset already gone. + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence( + region, domain, owner, repository, namespace, packageName, version, versionFenceSnapshot, + fenceSnapshot, claim.episodeId(), reposilite, repoId, candidateGav, content); + if (!result.fenceMatched()) { + // The version itself is gone: every later candidate in this same attempt + // would fail the exact same way, so none of them are even attempted. + break; + } + ReposiliteSidecarClient.DeployOutcome outcome = result.outcome(); + if (outcome == null) { + continue; + } + // The asset is genuinely present either way a 200/201 status is reached: a fresh + // write (201, or 200 with wroteNewContent()) or an idempotent match against bytes + // already there (200, wroteNewContent() false). Only a real conflict or sidecar + // error leaves nothing to record. + if (outcome.status() != 200 && outcome.status() != 201) { + continue; + } + importedAny = true; + if (candidateFilename.equals(filename)) { + importedRequestedAsset = true; + } + } + } finally { + // Finalized here, not just after a clean fall-through of the loop above, so an + // unexpected exception from one candidate still lets this bookkeeping run instead of + // leaving the claim held (or released) without ever recording what the candidates + // before it had already genuinely written. + if (importedAny) { + service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "maven", namespace, + packageName, fenceSnapshot); + } + // Matches the claim taken above, exactly once, regardless of what this attempt + // actually wrote: see finishMavenRetainedVersionOriginAttempt's own javadoc for why + // this must run even when importedAny is true, not only to release an empty claim. + // Passes the claim's own episodeId back, not the connection name: see that same + // javadoc for why a stray finish keyed only on connection name could otherwise affect + // a same-named replacement claim this attempt was never actually part of. + service.finishMavenRetainedVersionOriginAttempt(region, domain, owner, repository, namespace, + packageName, version, claim.episodeId(), importedAny); + } + return importedRequestedAsset; + } + + /** + * Whether {@code gav}'s own package version is already present in {@code + * repository}'s own maven external connection (if any): used to enforce AWS's documented + * "CodeArtifact will not permit publishing a package version that is already present in the + * external repository." Checks the version itself, not the specific filename being + * published: checking only the literal requested filename would let a non-standard asset + * name (one the real public repository never serves, e.g. a custom + * classifier) dodge this check entirely for a version that, under its standard name, already + * exists there. A version already claimed locally under this exact connection is treated as + * present without a further network call; otherwise the version's own standard POM (every + * real published Maven version has one) is checked as the authoritative "does this version + * exist" signal. A SNAPSHOT is never checked: external connections only ever import release + * versions, so one can never genuinely collide with what the real public repository holds. + */ + public boolean existsInExternalConnection(String region, String domain, String owner, String repository, + String gav) { + Optional coordinate = CodeArtifactMavenController.parseNamespaceAndPackageName(gav); + if (coordinate.isEmpty() || coordinate.get()[2] == null || coordinate.get()[2].endsWith("-SNAPSHOT")) { + return false; + } + String namespace = coordinate.get()[0]; + String packageName = coordinate.get()[1]; + String version = coordinate.get()[2]; + String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository); + if (externalConnectionName == null) { + return false; + } + if (service.mavenRetainedVersionOriginConnection(region, domain, owner, repository, namespace, packageName, + version).filter(externalConnectionName::equals).isPresent()) { + return true; + } + int lastSlash = gav.lastIndexOf('/'); + String directory = gav.substring(0, lastSlash + 1); + String pomGav = directory + packageName + "-" + version + ".pom"; + return externalConnectionClient.exists(externalConnectionName, pomGav); + } + + private String mavenExternalConnectionName(String region, String domain, String owner, String repository) { + return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream() + .filter(ec -> "maven".equals(ec.getPackageFormat())) + .map(ExternalConnection::getExternalConnectionName) + .findFirst() + .orElse(null); + } + + 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/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java index 31bf4f6552..325ba4746f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java @@ -160,7 +160,8 @@ public class CodeArtifactService implements Resettable { public record AssetSummary(String name, long size, Map hashes) {} 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) {} + public record PackageVersionSummary(String version, String revision, String status, String originType, + String externalConnectionName) {} public record ListPackageVersionsResult(String format, String namespace, String packageName, String defaultDisplayVersion, List versions, String nextToken) {} public record PackageSummaryEntry(String format, String namespace, String packageName, @@ -183,7 +184,7 @@ 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) {} + Long publishedEpochSeconds, String originType, String externalConnectionName) {} 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) {} @@ -271,6 +272,58 @@ public class CodeArtifactService implements Resettable { // entry for no caller that would ever need it. private final ConcurrentHashMap> containerBackedOverriddenPackagesByRepository = new ConcurrentHashMap<>(); + // Which public:maven-* external connection a Maven package version was first retained from, + // keyed like packageVersionKey (format fixed to "maven"). Claimed atomically, once per + // version (see claimMavenRetainedVersionOrigin's own javadoc): AWS's own documented "checking + // asset origins" rule is that a retained version's origin never changes once set, even if the + // repository's external connection is later swapped for a different one, so later assets of + // the same version fetched under a different connection must be rejected rather than mixed in. + // Removed on DeletePackageVersions/DeletePackage/DeleteRepository, the same way every other + // per-version/per-package/per-repository bookkeeping map here already is, so a coordinate + // recreated under the same name never inherits a dead claim it would otherwise be stuck + // behind. In memory only, like every other container-backed bookkeeping map here: the real + // retained bytes live in the Reposilite container itself, which has no attached volume and + // does not survive a Floci restart either, so persisting this alone would leave it answering + // for a version that, after a restart, no longer exists anywhere real. + // + // A plain name-to-connection map would let one in-flight attempt's own cleanup (nothing it + // fetched panned out) remove a claim a second, still-in-flight attempt under the same + // connection is still relying on, opening a window for a third attempt to claim the version + // under a newly-swapped connection while the first is still mid-fetch. Each entry instead + // counts how many attempts currently hold it and whether any of them ever actually wrote real + // content (see MavenRetainedVersionOriginClaim's own javadoc): the claim is only ever removed + // once no attempt is left holding it and nothing was ever confirmed under it. + private final ConcurrentHashMap mavenRetainedVersionOriginConnections = + new ConcurrentHashMap<>(); + + // inFlightAttempts alone only protects one claim episode against its own sibling attempts. + // If that whole episode is torn down (every attempt finishes, or the package/version is + // deleted and the map entry removed outright) and a brand new episode is then claimed under + // the exact same connection name, a stray finish call from the old episode, arriving late, is + // indistinguishable from a legitimate finish for the new one: same key, same connection name. + // episodeId, assigned fresh only when a claim is created from nothing, gives every episode + // its own identity a same-named replacement can never share, so a finish call can only ever + // affect the exact episode it was issued for. + private final AtomicLong mavenClaimEpisodeCounter = new AtomicLong(); + + /** + * One version's current claim on {@code externalConnectionName}, tagged with {@code + * episodeId}: {@code inFlightAttempts} counts how many calls into {@link + * #claimMavenRetainedVersionOrigin} for this exact version and episode have not yet reached + * their own matching {@link #finishMavenRetainedVersionOriginAttempt} 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 #finishMavenRetainedVersionOriginAttempt} + * 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 + * 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 + * can never be mistaken for a finish of that new episode (see the field's own javadoc above). + */ + private record MavenRetainedVersionOriginClaim(String externalConnectionName, int inFlightAttempts, + boolean confirmed, long episodeId) { + } /** * {@code publishedEpochSeconds} is carried forward from whichever value was already true for @@ -576,6 +629,14 @@ public class CodeArtifactService implements Resettable { .filter(k -> k.startsWith(ownerScopedOriginPrefix)) .toList() .forEach(containerBackedOverriddenPackagesByRepository::remove); + // Same reasoning, same prefix: a Maven repository recreated under this same name must + // not inherit a previous retention's claimed origin for a version with the same + // coordinates, or a real, freshly configured external connection on the new repository + // would be wrongly refused for mixing with a connection that belonged to the deleted one. + mavenRetainedVersionOriginConnections.keySet().stream() + .filter(k -> k.startsWith(ownerScopedOriginPrefix)) + .toList() + .forEach(mavenRetainedVersionOriginConnections::remove); return r; } @@ -1086,9 +1147,12 @@ public class CodeArtifactService implements Resettable { * *

{@code sortBy=PUBLISHED_TIME}, the only value {@code PackageVersionSortType} has, is * always applied (most recently published first) regardless of whether the caller passes it: - * there is no other sort mode for an omitted value to mean instead. {@code originType} other - * than {@code INTERNAL} always answers empty: Floci has no external-connection ingestion for - * any format, so nothing it ever lists is {@code EXTERNAL} or {@code UNKNOWN}. + * there is no other sort mode for an omitted value to mean instead. {@code originType} + * filters against each version's own real origin ({@link #versionOriginType}): {@code + * EXTERNAL} for a Maven version this service's own records show was retained from a {@code + * public:maven-*} external connection, {@code INTERNAL} for every other version, and nothing + * ever answers {@code UNKNOWN} at all, since every version this service tracks resolves to + * one of the other two. * *

{@code defaultDisplayVersion} is computed over every {@code Published} version * regardless of the {@code status}/{@code originType} filters applied to the returned {@code @@ -1150,18 +1214,26 @@ public class CodeArtifactService implements Resettable { .collect(Collectors.toSet()); Stream fromSidecar = raw.stream().map(v -> { PackageVersionStatusOverride override = overridesByVersion.get(v.version()); + VersionOrigin origin = versionOrigin(region, domain, owner, repository, format, namespace, + packageName, v.version()); if (override != null) { return new PackageVersionEntry(v.version(), override.revision(), override.status(), - override.publishedEpochSeconds()); + override.publishedEpochSeconds(), origin.originType(), origin.externalConnectionName()); } return new PackageVersionEntry(v.version(), synthesizeContainerBackedRevision(format, repoId, namespace, packageName, v.version()), - "Published", v.publishedTime() == null ? null : v.publishedTime().getEpochSecond()); + "Published", v.publishedTime() == null ? null : v.publishedTime().getEpochSecond(), + origin.originType(), origin.externalConnectionName()); }); Stream disposedOnly = overridesByVersion.entrySet().stream() .filter(e -> !coveredVersions.contains(e.getKey())) - .map(e -> new PackageVersionEntry(e.getKey(), e.getValue().revision(), e.getValue().status(), - e.getValue().publishedEpochSeconds())); + .map(e -> { + VersionOrigin origin = versionOrigin(region, domain, owner, repository, format, namespace, + packageName, e.getKey()); + return new PackageVersionEntry(e.getKey(), e.getValue().revision(), e.getValue().status(), + e.getValue().publishedEpochSeconds(), origin.originType(), + origin.externalConnectionName()); + }); entries = Stream.concat(fromSidecar, disposedOnly).toList(); preferredDisplayVersion = manager.preferredDisplayVersion(repoId, domain, repository, namespace, packageName).orElse(null); @@ -1173,7 +1245,7 @@ public class CodeArtifactService implements Resettable { } entries = versions.stream() .map(pv -> new PackageVersionEntry(pv.getVersion(), pv.getRevision(), pv.getStatus(), - pv.getPublishedTime())) + pv.getPublishedTime(), "INTERNAL", null)) .toList(); } @@ -1184,8 +1256,8 @@ public class CodeArtifactService implements Resettable { ? preferredVersion : mostRecentlyPublishedVersion(entries); - List matchingOrigin = originType != null && !"INTERNAL".equals(originType) - ? List.of() + List matchingOrigin = originType != null + ? entries.stream().filter(e -> originType.equals(e.originType())).toList() : entries; List filtered = status != null ? matchingOrigin.stream().filter(e -> status.equals(e.status())).toList() @@ -1197,7 +1269,8 @@ public class CodeArtifactService implements Resettable { CodeArtifactService::packageVersionSortCursor, maxResults, nextToken, 50, 1000, "ValidationException"); List summaries = page.items().stream() - .map(e -> new PackageVersionSummary(e.version(), e.revision(), e.status())) + .map(e -> new PackageVersionSummary(e.version(), e.revision(), e.status(), e.originType(), + e.externalConnectionName())) .toList(); return new ListPackageVersionsResult(format, namespace, packageName, defaultDisplayVersion, summaries, page.nextToken()); @@ -1584,6 +1657,10 @@ public class CodeArtifactService implements Resettable { String readmeKey = packageVersionKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName), version); packageVersionReadmes.remove(ownerScopedKey(owner, readmeKey)); + // Harmless no-op for every format but Maven, the only one that ever populates this + // map: a Maven version deleted and republished under the same coordinates must not + // inherit its previous claimed retention origin. + mavenRetainedVersionOriginConnections.remove(ownerScopedKey(owner, readmeKey)); // Bumps this version's own fence (see currentContainerBackedVersionFence's own // javadoc): raised by Greptile's review, without this a publish's readme capture // already in flight for this exact version, delayed past this delete, would resurrect @@ -1885,6 +1962,15 @@ public class CodeArtifactService implements Resettable { if (disposing) { deleteContainerBackedVersionAssets(manager, repoId, owner, region, domain, repository, format, namespace, packageName, version, assetNames); + // Bumps this version's own fence (see currentContainerBackedVersionFence's own + // javadoc): without this, a Maven external-connection import already fetching an + // asset for this exact version, delayed past this dispose, would write it back + // into the sidecar after disposal already deleted every real asset, leaving a + // disposed version with real bytes again. + String versionFenceKey = ownerScopedKey(owner, packageVersionKey(region, domain, repository, format, + namespace, accountingPackageName(format, packageName), version)); + containerBackedVersionDeletionFence.put(versionFenceKey, + containerBackedPackageDeletionCounter.incrementAndGet()); } successes.put(version, new SuccessfulPackageVersionInfo(updated.revision(), updated.status())); } @@ -2400,9 +2486,44 @@ public class CodeArtifactService implements Resettable { pv.setVersion(version); pv.setStatus(state.status()); pv.setRevision(state.revision()); + pv.setOriginType(versionOriginType(region, domain, owner, repository, format, namespace, packageName, + version)); return pv; } + /** + * {@code EXTERNAL} for a Maven version this service's own records show was retained from a + * {@code public:maven-*} external connection, {@code INTERNAL} for everything else: every + * other format/path here still only ever creates a version by direct publish. Without this, + * a retained version's real origin never reaches {@code DescribePackageVersion}/{@code + * ListPackageVersions} at all, both of which would keep reporting {@code INTERNAL} + * unconditionally, so filtering either by {@code originType=EXTERNAL} would find nothing even + * for a version this service itself knows was retained. + */ + private String versionOriginType(String region, String domain, String owner, String repository, String format, + String namespace, String packageName, String version) { + return versionOrigin(region, domain, owner, repository, format, namespace, packageName, version) + .originType(); + } + + /** + * {@code originType} plus, for an {@code EXTERNAL} Maven 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. + */ + private record VersionOrigin(String originType, String externalConnectionName) {} + + private VersionOrigin versionOrigin(String region, String domain, String owner, String repository, String format, + String namespace, String packageName, String version) { + if (!"maven".equals(format)) { + return new VersionOrigin("INTERNAL", null); + } + return mavenRetainedVersionOriginConnection(region, domain, owner, repository, namespace, packageName, + version).map(name -> new VersionOrigin("EXTERNAL", name)).orElse(new VersionOrigin("INTERNAL", null)); + } + /** * Every package a repository holds, for {@code ListPackages}: every format unless * {@code requestedFormat} narrows it to one, in which case only that one format's own source @@ -2680,6 +2801,331 @@ public class CodeArtifactService implements Resettable { return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction); } + /** + * Whether retaining a package version from an upstream/external source must be refused for + * {@code packageName}: {@code true} when an explicit {@code upstream: BLOCK} is on record, + * exactly like {@link #publishPackageVersion}'s own {@code publish: BLOCK} check, but also + * when no configuration was ever saved and the package already has a real version: + * no saved configuration does not always mean a brand-new package. A direct Maven deploy + * never writes an explicit configuration at all (see {@link #publishPackageVersion}'s own + * {@code publishRestriction} lookup, which defaults the same way), yet its real, documented + * default is {@code upstream: BLOCK}, the same default {@link #describePackage} already + * reports for it. Treating "no configuration" as universally unblocked would let a later + * retention attempt import a public version into a package {@code DescribePackage} itself + * already reports as blocked, then overwrite its defaults to {@code publish: BLOCK}/{@code + * upstream: ALLOW} as though it had never been published directly at all. Only a package + * genuinely never seen before (no configuration, no existing version) defaults to unblocked. + * + *

A standard Maven import writes its first asset, making {@code + * packageExistsViaVersionsOrSidecar} true, well before its own {@code finally} block finishes + * and saves {@code upstream: ALLOW} as the package's default (see {@link + * #ensureRetainedPackageOriginDefault}'s own javadoc). A second, concurrent request for a + * different file or version of the very same in-progress import would otherwise read that + * in-between state as a directly-published package and get wrongly refused. For Maven + * specifically, an in-flight or confirmed retention claim already existing for any + * version of this exact package (see {@link #claimMavenRetainedVersionOrigin}) is checked + * first: it can only exist at all because some earlier attempt already got past this exact + * check while the package had no real content yet, so it is itself the proof this package's + * real origin is external, without weakening the default block a package that has never had + * such a claim, and so can only have gotten real content from a direct publish, still gets. + */ + public boolean isUpstreamRetentionBlocked(String region, String domain, String domainOwner, String repository, + String format, String namespace, String packageName) { + String owner = effectiveOwner(domainOwner); + String key = packageKey(region, domain, repository, format, namespace, packageName); + Optional config = packageOriginConfigs.getForAccount(owner, key); + if (config.isPresent()) { + return "BLOCK".equals(config.get().getUpstreamRestriction()); + } + if ("maven".equals(format) && hasMavenRetainedVersionOriginClaimForAnyVersion(region, domain, owner, + repository, namespace, packageName)) { + return false; + } + return packageExistsViaVersionsOrSidecar(region, domain, owner, repository, format, namespace, packageName); + } + + /** + * Whether any version of {@code packageName}, under any connection, currently has or has ever + * had an entry in {@link #mavenRetainedVersionOriginConnections}: {@code true} for an + * in-flight claim just as much as a confirmed one, since {@link #isUpstreamRetentionBlocked}'s + * own caller (see its javadoc) needs to know an external import is under way before it ever + * writes anything a confirmed-only check could see. + */ + private boolean hasMavenRetainedVersionOriginClaimForAnyVersion(String region, String domain, String owner, + String repository, String namespace, String packageName) { + String prefix = ownerScopedKey(owner, packageKey(region, domain, repository, "maven", namespace, + packageName)) + "::"; + return mavenRetainedVersionOriginConnections.keySet().stream().anyMatch(k -> k.startsWith(prefix)); + } + + /** + * Writes {@code publish: BLOCK, upstream: ALLOW} as {@code packageName}'s origin + * configuration the first time any of its versions is retained from an upstream/external + * source, matching the User Guide's own documented default ("Default package origin control + * settings": "If the first package version is ingested from a public source, the settings + * will be Publish: BLOCK and Upstream: ALLOW"). A no-op once any configuration already + * exists, explicit or written by an earlier retention, so a caller's own {@code + * PutPackageOriginConfiguration} call, or an earlier retained version's own default, is never + * silently overwritten. Without this, {@link #describePackage}/{@link #listPackages} would + * report the direct-publish default ({@code publish: ALLOW, upstream: BLOCK}) for a package + * that in fact arrived the other way, and a second retention attempt for the same package + * would read as blocked the moment this service started honoring {@code upstream: BLOCK} at + * all. + * + *

Checks that the repository itself still exists, the same way {@link + * #recordContainerBackedAssetBytes} already does: {@code DeleteRepository} removes a + * repository's {@code packageOriginConfigs} entries directly rather than through this fence, + * so the package-level fence check below cannot by itself catch an import finishing after + * the repository was deleted. Without this, a repository recreated under the same name would + * see a stale default written back for a package it never had any version of. + */ + public synchronized void ensureRetainedPackageOriginDefault(String region, String domain, String domainOwner, + String repository, String format, String namespace, String packageName, long packageFenceSnapshot) { + String owner = effectiveOwner(domainOwner); + if (repositories.getForAccount(owner, repositoryKey(region, domain, repository)).isEmpty()) { + return; + } + String key = packageKey(region, domain, repository, format, namespace, packageName); + // Without this fence check, a DeletePackage that completed after the importer's own fence + // snapshot but before this call runs would have its removal of the package silently + // undone, recreating settings for a package whose real content is already gone, the same + // way every other write into this state already guards against (recordContainerBackedAssetBytes's + // own check, right below the one case that still differs: a deleted package genuinely has + // no configuration left to find, so an empty read here does not by itself mean this call + // is safe to proceed). + long currentFence = containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner, key), 0L); + if (currentFence != packageFenceSnapshot) { + return; + } + if (packageOriginConfigs.getForAccount(owner, key).isPresent()) { + return; + } + packageOriginConfigs.putForAccount(owner, key, + new PackageOriginConfig("BLOCK", "ALLOW", format, namespace, packageName)); + } + + /** + * The {@code public:maven-*} external connection name a Maven package version was genuinely + * retained from, or {@link Optional#empty()} if it has never been retained at all (either + * published directly, never seen before, or only ever tried and never confirmed; see {@link + * MavenRetainedVersionOriginClaim#confirmed}). Deliberately does not report a claim still only + * held by an in-flight attempt: nothing has genuinely been retained under it yet, so {@code + * false} here is the correct answer for a caller asking "is this version already retained", + * not just a conservative one. + */ + public Optional mavenRetainedVersionOriginConnection(String region, String domain, String domainOwner, + String repository, String namespace, String packageName, String version) { + String owner = effectiveOwner(domainOwner); + String key = packageVersionKey(region, domain, repository, "maven", namespace, packageName, version); + return Optional.ofNullable(mavenRetainedVersionOriginConnections.get(ownerScopedKey(owner, key))) + .filter(MavenRetainedVersionOriginClaim::confirmed) + .map(MavenRetainedVersionOriginClaim::externalConnectionName); + } + + /** + * The outcome of {@link #claimMavenRetainedVersionOrigin}: {@code claimed} is {@code false} + * only when a different connection already holds the claim, or the fence no longer matched, + * in which case {@code episodeId} is meaningless and must not be used. A {@code true} result + * must be matched, exactly once, by a later call to {@link + * #finishMavenRetainedVersionOriginAttempt} passing this exact {@code episodeId} back. + */ + public record MavenClaimOutcome(boolean claimed, long episodeId) { + } + + /** + * Atomically claims {@code version}'s retention origin for {@code externalConnectionName}, + * checked under the same fence {@code packageFenceSnapshot} was taken against (see {@link + * #currentContainerBackedPackageFence}'s own javadoc). The caller may proceed to fetch and + * write assets under this connection when {@link MavenClaimOutcome#claimed} is {@code true}: + * either this is the first claim for the version (a fresh {@link + * MavenRetainedVersionOriginClaim#episodeId} is assigned), or it was already claimed under + * the exact same connection and the exact same still-live episode (an idempotent retry, or a + * concurrent request for the same version and source), in which case this attempt is added to + * that episode's own {@link MavenRetainedVersionOriginClaim#inFlightAttempts} count. {@code + * claimed} is {@code false} when a different connection already holds the claim, or the fence + * no longer matches (the repository or package was deleted since the snapshot was taken). + * + *

Claims the origin atomically, before any network fetch or write happens at all, so the + * loser of a race between two concurrent imports for the same version, under two different + * connections, never writes anything in the first place, rather than both passing a + * read-then-write check and both writing real bytes before either recorded anything, mixing + * assets from two different public sources into one version, exactly what AWS's own "checking + * asset origins" rule exists to prevent. + * + *

Counting in-flight attempts, rather than a plain claim-or-reject flag, keeps the claim + * reserved for its connection as long as any attempt, confirmed or not, is still holding it: + * one attempt's own cleanup (see {@link #finishMavenRetainedVersionOriginAttempt}) must not + * remove a claim a sibling attempt under the same connection is still relying on, which would + * otherwise reopen a window for a third attempt to claim the version under a newly-swapped + * connection while the first is still mid-fetch. + * + *

{@code episodeId}, returned here and required back by {@link + * #finishMavenRetainedVersionOriginAttempt}, gives every claim episode an identity a + * same-named replacement can never share: once an entire episode is torn down (every attempt + * finishes with nothing confirmed, or a delete removes the map entry outright) and a brand + * new episode is claimed under the exact same connection name, a stray finish call from the + * old episode arriving late would otherwise be indistinguishable, by connection name alone, + * from a legitimate finish of the new one. + */ + public synchronized MavenClaimOutcome claimMavenRetainedVersionOrigin(String region, String domain, + String domainOwner, String repository, String namespace, String packageName, String version, + String externalConnectionName, long packageFenceSnapshot) { + String owner = effectiveOwner(domainOwner); + String packageKeyStr = packageKey(region, domain, repository, "maven", namespace, packageName); + long currentFence = containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner, packageKeyStr), + 0L); + if (currentFence != packageFenceSnapshot) { + return new MavenClaimOutcome(false, 0L); + } + String key = ownerScopedKey(owner, packageVersionKey(region, domain, repository, "maven", namespace, + packageName, version)); + MavenRetainedVersionOriginClaim existing = mavenRetainedVersionOriginConnections.get(key); + if (existing == null) { + long episodeId = mavenClaimEpisodeCounter.incrementAndGet(); + mavenRetainedVersionOriginConnections.put(key, + new MavenRetainedVersionOriginClaim(externalConnectionName, 1, false, episodeId)); + return new MavenClaimOutcome(true, episodeId); + } + if (!existing.externalConnectionName().equals(externalConnectionName)) { + return new MavenClaimOutcome(false, 0L); + } + mavenRetainedVersionOriginConnections.put(key, new MavenRetainedVersionOriginClaim(externalConnectionName, + existing.inFlightAttempts() + 1, existing.confirmed(), existing.episodeId())); + return new MavenClaimOutcome(true, existing.episodeId()); + } + + /** + * The exactly-once counterpart to a {@code claimed}-true {@link #claimMavenRetainedVersionOrigin} + * call for the same version, passing back the exact {@code episodeId} that call returned: + * marks the claim confirmed if {@code importedAnything} is {@code true} (this attempt, or an + * earlier sibling in the same episode, genuinely wrote real content under it), then removes + * this attempt from the episode's own in-flight count. The claim itself is only ever removed + * once no attempt is left holding it and it was never confirmed by any of them; + * otherwise it stays, so a sibling attempt still mid-fetch in the same episode keeps seeing + * its own claim intact, and a version that genuinely has real content stays reserved for its + * one true origin forever. A claim already gone, or now on a different episode (the one this + * call was issued for already torn down and replaced, see this method's own javadoc on {@link + * #claimMavenRetainedVersionOrigin}), is left alone: this attempt's own claim must have + * already been rejected or otherwise accounted for, and a same-named replacement episode is + * never mistaken for it. + */ + public synchronized void finishMavenRetainedVersionOriginAttempt(String region, String domain, + String domainOwner, String repository, String namespace, String packageName, String version, + long episodeId, boolean importedAnything) { + String owner = effectiveOwner(domainOwner); + String key = ownerScopedKey(owner, packageVersionKey(region, domain, repository, "maven", namespace, + packageName, version)); + MavenRetainedVersionOriginClaim existing = mavenRetainedVersionOriginConnections.get(key); + if (existing == null || existing.episodeId() != episodeId) { + return; + } + boolean confirmed = existing.confirmed() || importedAnything; + int remaining = Math.max(existing.inFlightAttempts() - 1, 0); + if (remaining == 0 && !confirmed) { + mavenRetainedVersionOriginConnections.remove(key); + } else { + mavenRetainedVersionOriginConnections.put(key, new MavenRetainedVersionOriginClaim( + existing.externalConnectionName(), remaining, confirmed, episodeId)); + } + } + + /** + * The outcome of {@link #deployMavenAssetUnderVersionFence}: {@code fenceMatched} is {@code + * false} only when the version's fence had already moved before the write was even + * attempted, in which case {@code outcome} is always {@code null}; otherwise {@code outcome} + * is whatever {@link ReposiliteSidecarClient#deployArtifact} returned, or {@code null} if + * that call itself failed. + */ + public record MavenDeployAttemptResult(boolean fenceMatched, ReposiliteSidecarClient.DeployOutcome outcome) { + } + + /** + * Deploys one Maven asset to the Reposilite sidecar, but only if {@code versionFenceSnapshot} + * still matches this exact version's current fence, checked and acted on inside the very same + * {@code synchronized} call {@link #deletePackageVersions}, {@link #deletePackage}, {@link + * #deleteRepository}, and {@link #disposePackageVersions} already hold for their own entire + * operation, so the two can never interleave at all: whichever gets here first finishes its + * entire write (or delete) before the other even starts, so a delete or disposal either + * already bumped the fence before this check runs (caught right here, nothing written) or + * has not started yet (and will see this exact write as part of what it must clean up, once + * this call returns and releases the lock). A plain compare-the-fence-before-and-after-the-write + * check, without the shared lock, could only narrow that window, never close it, and a + * rollback compensating for whatever landed in the narrower window would still risk deleting + * a different, later attempt's own legitimate write if it matched by name alone. + * + *

Byte accounting runs inside this exact same locked call, right after a real write, + * rather than in a separate call made after this one already returned and released the lock: + * {@link #recordContainerBackedAssetBytes} (itself {@code synchronized}, safely reentrant + * from here on the same thread) could otherwise be straddled by a delete or disposal landing + * in the gap between this call releasing the lock and that separate call acquiring it, + * subtracting this asset's bytes as part of its own normal cleanup before the separate call + * added them, leaving {@code DescribeDomain.assetSizeBytes} permanently over-counted for an + * asset already gone. + * + *

{@code reposilite}, {@code repoId}, {@code gav}, and {@code content} come from the + * caller, not a field here, so this service never needs its own reference to a sidecar + * client: the real, slow fetch from the public source that produced {@code content} must + * already be finished before calling this, since it must never itself run while this lock is + * held, the same way every other synchronized method here only ever talks to a sidecar it + * already has everything it needs for. + * + *

The fence comparison alone only proves nothing changed since the caller's own + * snapshot was taken; it says nothing about whether this version was already Disposed or + * Archived before that snapshot, the one case a plain delete/recreate (a fresh, + * legitimate fence value with no override at all) can never produce. A request the + * controller's own {@code isDownloadable} check already let through before a disposal that + * landed before this attempt's own snapshot was even taken, delayed past it by the real fetch + * above, would otherwise still write real bytes back for a version whose status says it can + * no longer be used. The status is checked here directly, inside the same lock {@link + * #disposePackageVersions} itself holds while writing that exact status, so the two can no + * longer straddle each other either. + * + *

{@code episodeId} must be the exact one {@link #claimMavenRetainedVersionOrigin} returned + * for this write's own claim, checked here against whatever episode (if any) currently owns + * the version's origin. Neither fence catches a {@link #deletePackage} that found no real + * content yet to delete: it removes the origin claim outright but, having deleted nothing, + * never bumps the package fence either, so a sibling attempt still mid-fetch under the old, + * now-removed claim would otherwise see both fences still match and write its content back + * under whatever connection claimed the version next, mixing assets from two different public + * sources into one version. Checking the live claim's own episode identity, not just the + * fences, catches exactly that case: a torn-down-and-replaced claim can never share an episode + * with the attempt that held the old one, no matter how its connection name compares. + */ + public synchronized MavenDeployAttemptResult deployMavenAssetUnderVersionFence(String region, String domain, + String domainOwner, String repository, String namespace, String packageName, String version, + long versionFenceSnapshot, long packageFenceSnapshot, long episodeId, ReposiliteSidecarClient reposilite, + String repoId, String gav, byte[] content) { + if (currentContainerBackedVersionFence(region, domain, domainOwner, repository, "maven", namespace, + packageName, version) != versionFenceSnapshot) { + return new MavenDeployAttemptResult(false, null); + } + String owner = effectiveOwner(domainOwner); + String status = currentContainerBackedVersionStatus(owner, region, domain, repository, "maven", namespace, + packageName, version, repoId).status(); + if ("Disposed".equals(status) || "Archived".equals(status)) { + return new MavenDeployAttemptResult(false, null); + } + String claimKey = ownerScopedKey(owner, packageVersionKey(region, domain, repository, "maven", namespace, + packageName, version)); + MavenRetainedVersionOriginClaim currentClaim = mavenRetainedVersionOriginConnections.get(claimKey); + if (currentClaim == null || currentClaim.episodeId() != episodeId) { + return new MavenDeployAttemptResult(false, null); + } + ReposiliteSidecarClient.DeployOutcome outcome; + try { + outcome = reposilite.deployArtifact(repoId, gav, content); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not deploy {0} while retaining a Maven release through an external connection.", + gav); + return new MavenDeployAttemptResult(true, null); + } + if ((outcome.status() == 200 || outcome.status() == 201) && outcome.wroteNewContent()) { + recordContainerBackedAssetBytes(region, domain, domainOwner, repository, "maven", namespace, + packageName, content.length, packageFenceSnapshot); + } + return new MavenDeployAttemptResult(true, outcome); + } + /** * Whether a package has any real version behind it: a stored {@code packageVersions} record * for generic, or the repository's own sidecar for a container-backed format. Deliberately @@ -2776,6 +3222,14 @@ public class CodeArtifactService implements Resettable { .toList() .forEach(containerBackedPackageVersionStatusOverrides::remove); containerBackedOverriddenVersionsByPackage.remove(ownerScopedKey(owner, accountingKey)); + // Same prefix, same reasoning: a Maven package deleted and republished under the + // same coordinates must not inherit a previous version's claimed retention origin, + // which would otherwise keep refusing a genuine new retention attempt under + // whichever connection the repository has configured now. + mavenRetainedVersionOriginConnections.keySet().stream() + .filter(k -> k.startsWith(ownerScopedReadmePrefix)) + .toList() + .forEach(mavenRetainedVersionOriginConnections::remove); if (namespace == null) { Set packageNames = containerBackedOverriddenPackagesByRepository.get( ownerScopedKey(owner, repositoryFormatKey(region, domain, repository, format))); @@ -3447,6 +3901,8 @@ public class CodeArtifactService implements Resettable { } copyCapturedReadmeIfApplicable(region, domain, owner, sourceRepository, destinationRepository, format, namespace, packageName, version); + copyMavenRetainedVersionOriginIfApplicable(region, domain, owner, sourceRepository, + destinationRepository, format, namespace, packageName, version); // Drops any status override left over from whatever used to be at this destination // coordinate (an Archived version this copy's allowOverwrite just replaced, most // concretely): the response below reports Published, and a stale override would @@ -3509,6 +3965,51 @@ public class CodeArtifactService implements Resettable { } } + /** + * Carries the source version's Maven retention origin into the destination: {@link + * #versionOrigin} only ever answers from the destination coordinate's own claim, and {@link + * #copyContainerBackedPackageVersions} copies a version's real asset bytes without copying + * that claim, so a copied version would otherwise keep reporting whatever origin the + * destination held before this exact write, even though its real content (and, with {@code + * allowOverwrite}, its real bytes) just became whatever the source held instead. + * + *

Replaces the destination's claim outright rather than going through {@link + * #claimMavenRetainedVersionOrigin}'s own claim-or-reject gate: that gate exists to stop two + * concurrent writers from mixing sources into a version neither has written to yet, not to + * protect a claim this exact write, already finished by the time this call runs, has just + * superseded. Going through it here would silently leave a stale, mismatched claim in place + * on exactly the case that matters most: overwriting a destination version already retained + * under a different connection, where the real bytes changed but the losing claim-or-reject + * call would leave the old origin recorded, pointing at content no longer actually there. A + * stray finish from whatever attempt held the old claim can never affect this fresh one: + * {@link #deployMavenAssetUnderVersionFence}'s own episode check already treats a torn-down- + * and-replaced claim as a hard rejection regardless of its former connection name, the same + * protection a {@link #deletePackage} tearing down a claim already relies on. + * + *

A source with no claim at all (a direct publish, not retained from any connection) + * clears any claim the destination held before this write, rather than leaving a stale one + * behind: the destination's real content just became the source's own, directly-published + * bytes, which were never retained from anywhere. + */ + private void copyMavenRetainedVersionOriginIfApplicable(String region, String domain, String owner, + String sourceRepository, String destinationRepository, String format, String namespace, + String packageName, String version) { + if (!"maven".equals(format)) { + return; + } + String key = ownerScopedKey(owner, packageVersionKey(region, domain, destinationRepository, "maven", + namespace, packageName, version)); + Optional sourceConnection = mavenRetainedVersionOriginConnection(region, domain, owner, + sourceRepository, namespace, packageName, version); + if (sourceConnection.isEmpty()) { + mavenRetainedVersionOriginConnections.remove(key); + return; + } + long episodeId = mavenClaimEpisodeCounter.incrementAndGet(); + mavenRetainedVersionOriginConnections.put(key, + new MavenRetainedVersionOriginClaim(sourceConnection.get(), 0, true, episodeId)); + } + /** * Best-effort compensating cleanup for one version's partially-applied destination writes * after {@link #copyContainerBackedPackageVersions} hits a failure partway through them: @@ -3803,8 +4304,8 @@ public class CodeArtifactService implements Resettable { } String owner = effectiveOwner(domainOwner); if (repositories.getForAccount(owner, repositoryKey(region, domain, repository)).isEmpty()) { - LOG.warnv("Skipping readme capture for {0}/{1}: the repository was deleted while this publish was in " - + "flight.", domain, repository); + LOG.warnv("Skipping readme capture for {0}/{1}: the repository was deleted while this publish was " + + "in flight.", domain, repository); return; } String accountingName = accountingPackageName(format, packageName); @@ -3935,6 +4436,7 @@ public class CodeArtifactService implements Resettable { containerBackedPackageVersionStatusOverrides.clear(); containerBackedOverriddenVersionsByPackage.clear(); containerBackedOverriddenPackagesByRepository.clear(); + mavenRetainedVersionOriginConnections.clear(); authorizationTokens.clear(); if (inMemory) { memoryAssetStore.clear(); @@ -4064,7 +4566,11 @@ public class CodeArtifactService implements Resettable { * of the package-wide fence or this version's own is higher, so a snapshot taken here still * catches a whole-package removal ({@link #deletePackage}, or a native {@code npm unpublish} * via {@link #forgetContainerBackedPackage}) exactly the way {@link - * #currentContainerBackedPackageFence} already does on its own. + * #currentContainerBackedPackageFence} already does on its own. {@link #disposePackageVersions}'s + * container-backed branch also bumps this version's own fence once it actually deletes real + * assets, for the same reason: {@code CodeArtifactMavenExternalConnectionImporter} takes its + * own snapshot before fetching from a public source and re-checks it right before writing each + * asset back, so a disposal that lands while that fetch is in flight is never silently undone. */ public long currentContainerBackedVersionFence(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName, String version) { diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClient.java new file mode 100644 index 0000000000..a5169bafd9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClient.java @@ -0,0 +1,151 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; + +/** + * A real outbound client for the five public Maven repositories CodeArtifact's {@code + * public:maven-*} external connections name, confirmed live (not AWS's own hidden internal proxy + * target, which is undocumented, but the same well-known public host any real {@code mvn}/Gradle + * build already resolves these coordinates against): + * + *

    + *
  • {@code public:maven-central}: {@code https://repo.maven.apache.org/maven2}, the Super + * POM's and Gradle's own {@code MAVEN_CENTRAL_URL} default.
  • + *
  • {@code public:maven-clojars}: {@code https://repo.clojars.org}.
  • + *
  • {@code public:maven-commonsware}: {@code https://s3.amazonaws.com/repo.commonsware.com}, + * confirmed against a real CWAC library's own published README.
  • + *
  • {@code public:maven-googleandroid}: {@code https://dl.google.com/dl/android/maven2}, the + * explicit alternative Android's own docs give for {@code google()}'s older, pre-4.1-Gradle + * form ({@code https://maven.google.com} 301-redirects a GAV request here).
  • + *
  • {@code public:maven-gradleplugins}: {@code https://plugins.gradle.org/m2}, what {@code + * gradlePluginPortal()} resolves to.
  • + *
+ * + *

Every failure mode (an unknown connection name, a real non-200 response, a network error) + * resolves to {@link Optional#empty()} rather than throwing: a caller here is always deciding + * whether to retain a package version from an external source, and AWS's own documented behavior + * for an unreachable external repository is to behave exactly as if the asset were not found, + * with no special error surfaced to the client ("the only workaround is to try again later"). + */ +@ApplicationScoped +public class MavenExternalConnectionClient { + + private static final Logger LOG = Logger.getLogger(MavenExternalConnectionClient.class); + + private static final Map BASE_URLS = Map.of( + "public:maven-central", "https://repo.maven.apache.org/maven2", + "public:maven-clojars", "https://repo.clojars.org", + "public:maven-commonsware", "https://s3.amazonaws.com/repo.commonsware.com", // partition-literal: CommonsWare's real repo is a commercial-partition S3 bucket, same for every partition Floci emulates + "public:maven-googleandroid", "https://dl.google.com/dl/android/maven2", + "public:maven-gradleplugins", "https://plugins.gradle.org/m2"); + + private final HttpClient httpClient; + private final Map baseUrls; + + @Inject + public MavenExternalConnectionClient() { + // java.net.http.HttpClient's own default redirect policy is NEVER, so a real public + // repository that redirects an artifact request (a CDN, a moved bucket path) would + // otherwise come back as a plain non-200, read here as "the asset does not exist" rather + // than followed. NORMAL follows redirects except from HTTPS down to HTTP, matching what a + // real mvn/Gradle build's own HTTP client does. + this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)) + .followRedirects(HttpClient.Redirect.NORMAL).build(), BASE_URLS); + } + + /** For tests: a fake base-URL map, so the wire contract can be exercised against a local + * {@code HttpServer} fake instead of the real public repositories. */ + MavenExternalConnectionClient(HttpClient httpClient, Map baseUrls) { + this.httpClient = httpClient; + this.baseUrls = baseUrls; + } + + /** One asset's real bytes, fetched from a public Maven repository. */ + public record FetchedAsset(byte[] content) {} + + /** + * Fetches {@code gav} (the same {@code ///} shape + * Reposilite itself uses, since both are standard Maven2 repository layouts) from the real + * public repository {@code externalConnectionName} names. + */ + public Optional fetchAsset(String externalConnectionName, String gav) { + return send(externalConnectionName, gav, "GET").map(response -> new FetchedAsset(response.body())); + } + + /** Whether {@code gav} exists in the real public repository, without downloading it. */ + public boolean exists(String externalConnectionName, String gav) { + String baseUrl = baseUrls.get(externalConnectionName); + if (baseUrl == null) { + return false; + } + try { + HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, gav)) + .timeout(Duration.ofSeconds(20)) + .method("HEAD", HttpRequest.BodyPublishers.noBody()) + .build(); + return httpClient.send(request, BodyHandlers.discarding()).statusCode() == 200; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException e) { + LOG.warnv("Could not check {0} in external connection {1}: {2}", gav, externalConnectionName, + e.getMessage()); + return false; + } + } + + private Optional> send(String externalConnectionName, String gav, String method) { + String baseUrl = baseUrls.get(externalConnectionName); + if (baseUrl == null) { + return Optional.empty(); + } + try { + HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, gav)) + .timeout(Duration.ofSeconds(20)) + .method(method, HttpRequest.BodyPublishers.noBody()) + .build(); + HttpResponse response = httpClient.send(request, BodyHandlers.ofByteArray()); + return response.statusCode() == 200 ? Optional.of(response) : Optional.empty(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return Optional.empty(); + } catch (IOException e) { + LOG.warnv("Could not fetch {0} from external connection {1}: {2}", gav, externalConnectionName, + e.getMessage()); + return Optional.empty(); + } + } + + /** + * {@code gav} is an untrusted asset path (ultimately a caller-supplied wire-protocol segment), + * and {@code baseUrl} can itself carry a path prefix (the CommonsWare connection's own host is + * really a bucket path, {@code s3.amazonaws.com/repo.commonsware.com}). Built the same safe + * way {@code ReposiliteSidecarClient}'s own {@code requestUri} builds a request to the + * internal sidecar: the three-argument {@link URI} constructor percent-encodes a stray + * {@code #} or {@code ?} instead of letting it truncate the path at a fragment or reinterpret + * the rest as a query string, and {@link SidecarUriUtils#combine} then joins that already- + * encoded path onto {@code baseUrl}'s own scheme, authority, and path prefix without + * re-encoding (and so without corrupting) either side. + */ + private static URI requestUri(String baseUrl, String gav) { + try { + String encodedPath = new URI(null, null, "/" + gav, null, null).getRawPath(); + return SidecarUriUtils.combine(URI.create(baseUrl), encodedPath); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Could not build an external-connection request URI for " + gav, e); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactPackageVersion.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactPackageVersion.java index 5dd005df57..a5fa814212 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactPackageVersion.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactPackageVersion.java @@ -21,6 +21,11 @@ public class CodeArtifactPackageVersion { private String status; private String revision; private Long publishedTime; + // Every real version here was either published directly (generic's own publishPackageVersion + // never sets this, so the default here stays correct for it) or synthesized for a + // container-backed format whose own describe path sets it explicitly once it knows better + // (currently only Maven's real external-connection retention ever reports EXTERNAL). + private String originType = "INTERNAL"; private Map assets = new LinkedHashMap<>(); public String getDomainName() { @@ -111,6 +116,14 @@ public class CodeArtifactPackageVersion { this.publishedTime = publishedTime; } + public String getOriginType() { + return originType; + } + + public void setOriginType(String originType) { + this.originType = originType; + } + public Map getAssets() { return Collections.unmodifiableMap(assets); } diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java new file mode 100644 index 0000000000..0c6f28adb3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java @@ -0,0 +1,154 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SidecarContainersProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.nio.charset.StandardCharsets; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Retains a real Maven package version from the real, live {@code public:maven-central} + * repository (not a local fake), through the native per-format route, the way a real {@code mvn}/ + * Gradle build would. junit 4.13.2 is picked because AWS's own User Guide uses it as its worked + * example and it's small, stable, and unlikely to ever be pulled from Maven Central. A genuine + * network dependency, unlike every other sidecar-backed test here, which only ever talks to a + * container Floci itself started; see {@code CodeArtifactMavenExternalConnectionImporterTest} + * for the mocked, deterministic coverage of the asset-selection and mixed-origin logic this test + * does not re-exercise. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CodeArtifactMavenExternalConnectionDockerIntegrationTest { + + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request"; + private static final String DOMAIN = "maven-external-connection-domain"; + private static final String REPO = "maven-external-connection-repo"; + private static final String BLOCKED_REPO = "maven-external-connection-blocked-repo"; + private static final String JUNIT_JAR = "junit/junit/4.13.2/junit-4.13.2.jar"; + private static final String JUNIT_POM = "junit/junit/4.13.2/junit-4.13.2.pom"; + + private static String bearerToken; + + @BeforeAll + static void setUp() { + SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.maven-image"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(0) + void createDomainRepositoriesConnectionAndToken() { + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .post("/v1/domain?domain=" + DOMAIN) + .then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO) + .then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO) + .then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO + + "&external-connection=public:maven-central") + .then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + + "&external-connection=public:maven-central") + .then().statusCode(200); + + bearerToken = given().header("Authorization", AUTH) + .post("/v1/authorization-token?domain=" + DOMAIN) + .then().statusCode(200) + .extract().jsonPath().getString("authorizationToken"); + } + + @Test + @Order(1) + void fetchingAMissingJarRetainsItFromTheRealMavenCentralConnectionAndCountsItsBytes() { + long assetSizeBytesBefore = given().header("Authorization", AUTH) + .get("/v1/domain?domain=" + DOMAIN) + .then().statusCode(200) + .extract().jsonPath().getLong("domain.assetSizeBytes"); + assertEquals(0L, assetSizeBytesBefore); + + byte[] fetched = given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + JUNIT_JAR) + .then().statusCode(200) + .extract().asByteArray(); + + // A real jar is a real zip: "PK" magic bytes, not asserting exact content since the real + // artifact is out of this test's control. + assertEquals('P', (char) fetched[0]); + assertEquals('K', (char) fetched[1]); + assertThat(fetched.length, greaterThan(1000)); + + // Proves the retained bytes are actually counted toward DescribeDomain's assetSizeBytes, + // the same way a direct mvn deploy already is: at least the jar's own length, since the + // standard-asset import also retains the pom (and possibly javadoc/sources) alongside it. + long assetSizeBytesAfter = given().header("Authorization", AUTH) + .get("/v1/domain?domain=" + DOMAIN) + .then().statusCode(200) + .extract().jsonPath().getLong("domain.assetSizeBytes"); + assertThat(assetSizeBytesAfter, greaterThan((long) fetched.length)); + } + + @Test + @Order(2) + void theStandardPomSiblingWasRetainedInTheSameAttemptNotJustTheRequestedJar() { + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .delete("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO + + "&external-connection=public:maven-central") + .then().statusCode(200); + + // With the external connection now gone, a fresh retention attempt is impossible: this can + // only succeed because the standard-asset import on order(1)'s own jar request already + // retained the pom alongside it. + given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + JUNIT_POM) + .then().statusCode(200); + } + + @Test + @Order(3) + void republishingAVersionAlreadyPresentInTheExternalConnectionIsRejected() { + given().header("Authorization", "Bearer " + bearerToken) + .body("not-the-real-bytes".getBytes(StandardCharsets.UTF_8)) + .put("/codeartifact/maven/" + DOMAIN + "/" + BLOCKED_REPO + "/" + JUNIT_JAR) + .then().statusCode(409); + } + + @Test + @Order(4) + void upstreamBlockPreventsRetentionEvenThoughTheRealArtifactExists() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"restrictions\":{\"publish\":\"ALLOW\",\"upstream\":\"BLOCK\"}}") + .post("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=maven" + + "&namespace=junit&package=junit") + .then().statusCode(200); + + given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + BLOCKED_REPO + "/" + JUNIT_JAR) + .then().statusCode(404); + } + + @Test + @Order(5) + void aSnapshotVersionIsNeverRetainedFromAnExternalConnection() { + given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + REPO + + "/com/example/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar") + .then().statusCode(404); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java new file mode 100644 index 0000000000..147095bad6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java @@ -0,0 +1,396 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository; +import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +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.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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 CodeArtifactMavenExternalConnectionImporter}'s own decision logic: when it attempts a + * real external-connection fetch at all, which asset names it tries, and what it writes back. + * {@link ReposiliteSidecarClient} and {@link MavenExternalConnectionClient} are both mocked, so + * no real network or Reposilite call ever happens here; their own wire contracts have their own + * tests. + */ +class CodeArtifactMavenExternalConnectionImporterTest { + + 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 CodeArtifactService service; + private ReposiliteSidecarClient reposilite; + private MavenExternalConnectionClient externalConnectionClient; + private CodeArtifactMavenExternalConnectionImporter importer; + + /** The episode id the default claim stub below hands out; every finish verify reuses it. */ + private static final long EPISODE_ID = 7L; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + reposilite = mock(ReposiliteSidecarClient.class); + externalConnectionClient = mock(MavenExternalConnectionClient.class); + importer = new CodeArtifactMavenExternalConnectionImporter(service, reposilite, externalConnectionClient); + + CodeArtifactRepository repository = new CodeArtifactRepository(); + repository.setExternalConnections( + List.of(new ExternalConnection("public:maven-central", "maven", "AVAILABLE"))); + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository); + when(service.mavenRetainedVersionOriginConnection(anyString(), anyString(), anyString(), anyString(), + any(), anyString(), anyString())).thenReturn(Optional.empty()); + when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString())).thenReturn(42L); + // 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())) + .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 + // one. The dispose-race test below overrides this per call. + when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), anyString(), anyString())).thenReturn(99L); + // Unstubbed by default: the fence matched and the write landed (201), matching the + // common case. The real deploy/fence check this stands in for is inside + // deployMavenAssetUnderVersionFence itself, a synchronized CodeArtifactService method + // (see its own javadoc for why), so this mock is what every test configures instead. + // Tests for the idempotent-match, conflict, fence-mismatch, and error cases override + // this per call via stubDeploy. + when(service.deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), + anyString(), any())).thenReturn(new CodeArtifactService.MavenDeployAttemptResult(true, + new ReposiliteSidecarClient.DeployOutcome(201, true))); + } + + /** + * Stubs the single candidate named by {@code gav}/{@code content}; every other candidate + * keeps the default stub from {@link #setUp}. + */ + private void stubDeploy(String gav, byte[] content, CodeArtifactService.MavenDeployAttemptResult result) { + when(service.deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID), + eq(gav), eq(content))).thenReturn(result); + } + + /** Verifies the call for {@code gav}/{@code content} also passed the package fence through. */ + private void verifyDeployPassedPackageFence(String gav, byte[] content, long packageFenceSnapshot) { + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + anyString(), anyString(), anyString(), anyLong(), eq(packageFenceSnapshot), anyLong(), eq(reposilite), + eq(REPO_ID), eq(gav), eq(content)); + } + + @Test + void doesNothingForABareMavenMetadataPath() { + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/maven-metadata.xml"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void doesNothingForASnapshotVersion() { + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void doesNothingWhenTheRepositoryHasNoMavenExternalConnection() { + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(new CodeArtifactRepository()); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void doesNothingWhenUpstreamRetentionIsBlocked() { + when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", + "widget")).thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void doesNothingWhenTheVersionWasAlreadyRetainedFromADifferentConnection() { + // 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)) + .thenReturn(new CodeArtifactService.MavenClaimOutcome(false, 0L)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void aStandardAssetNameImportsAllFourStandardAssetsBestEffort() { + byte[] pomBytes = "pom-content".getBytes(); + byte[] jarBytes = "jar".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes))); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes))); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty()); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty()); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertTrue(imported); + // packageFenceSnapshot (42L) is passed through so deployMavenAssetUnderVersionFence can + // record bytes atomically with the write itself; see its own javadoc, and + // CodeArtifactServiceTest for the byte-accounting behavior this stands in for here. + verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.pom", pomBytes, 42L); + verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.jar", jarBytes, 42L); + verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), + anyString(), eq("com/example/widget/1.0/widget-1.0-javadoc.jar"), any()); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", + "1.0", "public:maven-central", 42L); + verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", + "widget", 42L); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, true); + } + + /** + * Taking the version-fence snapshot after the claim instead of before it would leave a gap + * where a DisposePackageVersions completing in between would already have bumped the fence by + * the time the snapshot read ran, so that read would capture the post-disposal value as + * though it were the normal starting point, and the later locked write would never notice + * anything was amiss. The snapshot must be taken first, so any disposal landing anywhere after + * it, including during the claim call itself, is guaranteed to bump the fence to a value the + * later check can actually detect as different. + */ + @Test + void takesTheVersionFenceSnapshotBeforeClaimingNotAfter() { + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes()))); + + importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/1.0/widget-1.0.jar"); + + InOrder order = inOrder(service); + 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); + } + + @Test + void anIdempotentMatchCountsAsImportedButIsNotDoubleCountedInByteAccounting() { + byte[] jarBytes = "jar".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes))); + // deployArtifact's own idempotent-match short-circuit: status 200, wroteNewContent false, + // because the exact same bytes were already there (e.g. a sibling asset imported it moments + // earlier in a race with another request for the same version). + stubDeploy("com/example/widget/1.0/widget-1.0.jar", jarBytes, + new CodeArtifactService.MavenDeployAttemptResult(true, + new ReposiliteSidecarClient.DeployOutcome(200, false))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertTrue(imported); + verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", + "1.0", "public:maven-central", 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 + // concern now, covered in CodeArtifactServiceTest. + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, true); + } + + @Test + void aRealDeployConflictOnTheRequestedAssetCountsAsNotImported() { + byte[] jarBytes = "jar".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(jarBytes))); + stubDeploy("com/example/widget/1.0/widget-1.0.jar", jarBytes, + new CodeArtifactService.MavenDeployAttemptResult(true, + new ReposiliteSidecarClient.DeployOutcome(409, false))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(), + anyString(), anyString(), any(), anyString(), anyLong()); + // Nothing was actually retained (the only candidate's deploy hit a real conflict), so the + // claim this attempt took is finished as unconfirmed, never left dangling to block a + // later attempt. + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, false); + } + + @Test + void aLaterCandidateThatThrowsStillFinalizesWhatAnEarlierCandidateGenuinelyWrote() { + byte[] pomBytes = "pom-content".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes))); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes()))); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty()); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty()); + // The POM deploy succeeds, but the JAR deploy (the requested asset) fails inside the + // sidecar call itself, e.g. it going unreachable mid-import: deployMavenAssetUnderVersionFence + // catches that on the real path and reports a matched fence with no outcome, exactly as + // stubbed here. + stubDeploy("com/example/widget/1.0/widget-1.0.jar", "jar".getBytes(), + new CodeArtifactService.MavenDeployAttemptResult(true, null)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + // The requested asset itself never landed, but what the POM candidate genuinely wrote + // before the JAR candidate threw is still finalized, not silently dropped. + assertFalse(imported); + verifyDeployPassedPackageFence("com/example/widget/1.0/widget-1.0.pom", pomBytes, 42L); + verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", + "widget", 42L); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, true); + } + + @Test + void aCandidateFetchThatThrowsIsTreatedLikeAMissingCandidateRatherThanAbortingTheWholeAttempt() { + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom")) + .thenThrow(new IllegalStateException("public repository unreachable")); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.jar")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("jar".getBytes()))); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-javadoc.jar")).thenReturn(Optional.empty()); + when(externalConnectionClient.fetchAsset("public:maven-central", + "com/example/widget/1.0/widget-1.0-sources.jar")).thenReturn(Optional.empty()); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertTrue(imported); + verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), + anyString(), eq("com/example/widget/1.0/widget-1.0.pom"), any()); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID), + eq("com/example/widget/1.0/widget-1.0.jar"), eq("jar".getBytes())); + } + + @Test + void aDisposalLandingWhileAFetchIsInFlightStopsEveryLaterWriteForThisAttempt() { + byte[] pomBytes = "pom-content".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(pomBytes))); + // A DisposePackageVersions landed on this exact version while the first candidate's + // (the pom's) fetch was in flight: deployMavenAssetUnderVersionFence detects the fence + // mismatch itself (inside its own lock) and reports it rather than writing anything, so + // every later candidate, including the requested jar, is never even fetched. + stubDeploy("com/example/widget/1.0/widget-1.0.pom", pomBytes, + new CodeArtifactService.MavenDeployAttemptResult(false, null)); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), + anyString(), eq("com/example/widget/1.0/widget-1.0.jar"), any()); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, false); + } + + @Test + void aNonStandardAssetNameOnlyImportsTheExactRequestedAsset() { + String nonStandardGav = "com/example/widget/1.0/widget-1.0-windows.jar"; + when(externalConnectionClient.fetchAsset("public:maven-central", nonStandardGav)) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset("windows-jar".getBytes()))); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, nonStandardGav); + + assertTrue(imported); + verify(service).deployMavenAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), eq(reposilite), eq(REPO_ID), + eq(nonStandardGav), eq("windows-jar".getBytes())); + verify(externalConnectionClient, never()).fetchAsset(eq("public:maven-central"), + eq("com/example/widget/1.0/widget-1.0.pom")); + } + + @Test + void returnsFalseWhenTheRequestedAssetItselfIsNotFoundEvenIfItWouldHaveBeenAStandardImport() { + when(externalConnectionClient.fetchAsset(anyString(), anyString())).thenReturn(Optional.empty()); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/1.0/widget-1.0.jar"); + + assertFalse(imported); + verify(service, never()).deployMavenAssetUnderVersionFence(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), + anyString(), anyString(), any()); + verify(service).finishMavenRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", + "widget", "1.0", EPISODE_ID, false); + } + + @Test + void existsInExternalConnectionChecksTheRealPublicRepositoryForAReleaseVersion() { + // Checks the version's own standard POM, not the literal requested filename: every real + // published Maven version has one, while a non-standard classifier asset may not. + when(externalConnectionClient.exists("public:maven-central", "com/example/widget/1.0/widget-1.0.pom")) + .thenReturn(true); + + assertTrue(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY, + "com/example/widget/1.0/widget-1.0.jar")); + } + + @Test + void existsInExternalConnectionIsTrueWhenTheVersionIsAlreadyClaimedUnderThisConnectionLocally() { + when(service.mavenRetainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "com.example", "widget", + "1.0")).thenReturn(Optional.of("public:maven-central")); + + assertTrue(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY, + "com/example/widget/1.0/widget-1.0-windows.jar")); + verify(externalConnectionClient, never()).exists(anyString(), anyString()); + } + + @Test + void existsInExternalConnectionNeverChecksASnapshotVersion() { + assertFalse(importer.existsInExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY, + "com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar")); + verify(externalConnectionClient, never()).exists(anyString(), anyString()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java index d6dd291094..75ddc73871 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java @@ -1820,6 +1820,527 @@ class CodeArtifactServiceTest { assertEquals("BLOCK", second.upstreamRestriction()); } + @Test + void isUpstreamRetentionBlockedIsFalseWithNoConfigurationAtAll() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", + "widget")); + } + + @Test + void isUpstreamRetentionBlockedReflectsAnExplicitUpstreamBlock() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", "ALLOW", + "BLOCK"); + + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", + "widget")); + } + + /** + * A standard import writes + * its first asset (making the package's real content exist) well before its own {@code + * finally} block saves {@code upstream: ALLOW} as the package's default, once every candidate + * is done. A concurrent request for a different file or version of that same in-progress + * import must not read that in-between state as a directly-published package and get wrongly + * refused, even though no configuration has been saved for it yet either. + */ + @Test + void isUpstreamRetentionBlockedIsFalseWhileASiblingVersionsImportIsStillInFlight() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + // The first candidate of this same in-progress import already wrote real content, the + // same way packageExistsViaVersionsOrSidecar would see it mid-import. + when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + // 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); + + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", + "widget")); + } + + /** + * The other side of the same fix: a package that really was directly published (real content, + * no claim ever taken for any version) must still default to blocked with no configuration + * saved, exactly as {@link #isUpstreamRetentionBlockedReflectsAnExplicitUpstreamBlock}'s own + * sibling test already covers for an explicit block. + */ + @Test + void isUpstreamRetentionBlockedIsStillTrueForADirectlyPublishedPackageWithNoClaimAtAll() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true); + + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "maven", "com.example", + "widget")); + } + + @Test + void ensureRetainedPackageOriginDefaultWritesTheIngestedFirstVersionDefault() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + + service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget", + fence); + + CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo", + "maven", "com.example", "widget"); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("ALLOW", described.upstreamRestriction()); + } + + @Test + void ensureRetainedPackageOriginDefaultNeverOverwritesAnExistingConfiguration() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", "ALLOW", + "BLOCK"); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + + service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget", + fence); + + CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo", + "maven", "com.example", "widget"); + assertEquals("ALLOW", described.publishRestriction()); + assertEquals("BLOCK", described.upstreamRestriction()); + } + + @Test + void ensureRetainedPackageOriginDefaultIsANoOpWhenTheFenceHasMoved() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long currentFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + // A fence snapshot that no longer matches "current" simulates a DeletePackage/ + // DeleteRepository that completed after the snapshot was taken, before this call runs. + long staleFence = currentFence + 1; + + service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget", + staleFence); + + AwsException e = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo", + "maven", "com.example", "widget")); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + /** + * {@code DeleteRepository} never bumps {@code containerBackedPackageDeletionFence}; it + * removes {@code packageOriginConfigs} entries directly instead, so the fence snapshot taken + * before an import started would still match after the repository was deleted. An import + * finishing in that gap must not write a dangling origin config that outlives the deleted + * repository and resurfaces the moment a repository is recreated under the same name: the + * repository-existence check this method also makes is what actually catches it. + */ + @Test + void ensureRetainedPackageOriginDefaultIsANoOpOnceTheRepositoryIsDeleted() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + + service.deleteRepository(REGION, "dom", null, "repo"); + service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "maven", "com.example", "widget", + fence); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo", + "maven", "com.example", "widget")); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void claimMavenRetainedVersionOriginIsAtomicPerVersion() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "widget"); + + assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo", + "com.example", "widget", "1.0")); + + CodeArtifactService.MavenClaimOutcome first = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, + "repo", "com.example", "widget", "1.0", "public:maven-central", 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); + 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()); + // 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")); + + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + first.episodeId(), true); + assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom", + null, "repo", "com.example", "widget", "1.0")); + } + + @Test + void claimMavenRetainedVersionOriginFailsWhenTheFenceHasMoved() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long currentFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + // A fence snapshot that no longer matches "current" simulates a DeletePackage/ + // DeleteRepository that completed after the snapshot was taken, before this call runs. + long staleFence = currentFence + 1; + + assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", + "1.0", "public:maven-central", staleFence).claimed()); + assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "repo", + "com.example", "widget", "1.0")); + } + + @Test + void finishMavenRetainedVersionOriginAttemptRemovesAnUnconfirmedClaimOnlyOnceEveryAttemptHasFinished() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", + "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(); + service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + "public:maven-central", 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 + // outright, opening a window for a third + // attempt to claim the version under a newly-swapped connection while the second attempt + // was still relying on the original one. + 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()); + + // 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()); + } + + @Test + void finishMavenRetainedVersionOriginAttemptKeepsAConfirmedClaimEvenOnceEveryAttemptHasFinished() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + 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(); + + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + episodeId, true); + + assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom", + null, "repo", "com.example", "widget", "1.0")); + // 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()); + } + + @Test + void finishMavenRetainedVersionOriginAttemptIgnoresAStaleEpisode() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + 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(); + + // 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) + // must not disturb the real claim. + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + realEpisodeId + 1000, false); + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + realEpisodeId, true); + + assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom", + null, "repo", "com.example", "widget", "1.0")); + } + + /** + * Attempt A claims under X and stalls; a sibling under X finishes empty, + * leaving A as the only one still holding the episode; the whole episode is then torn down + * from under A (simulating a DeletePackageVersions wiping the map entry outright, the one + * path that does not go through finishMavenRetainedVersionOriginAttempt's own bookkeeping at + * all); a brand new attempt claims fresh under the exact same connection name X. A's own, + * long-stale finish call, carrying its original episodeId, must never be able to touch that + * brand new episode just because the connection name happens to match. + */ + @Test + void aStaleFinishCanNeverReleaseAReplacementEpisodeClaimedUnderTheSameConnectionName() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + 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(); + + // 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 + // something real to delete and, as part of its own ordinary cleanup, wipes the origin map + // entry outright, the same way it already does today, regardless of any in-flight count. + when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(true); + service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget"); + + // A brand new episode is claimed fresh under the exact same connection name. + 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(); + assertNotEquals(staleEpisodeId, freshEpisodeId); + + // The old attempt's finish call, arriving late and carrying its own stale episodeId, must + // not release the fresh episode, even though both share the same connection name. + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + staleEpisodeId, false); + + assertFalse(service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", + "1.0", "public:maven-clojars", 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", + null, "repo", "com.example", "widget", "1.0")); + } + + @Test + void deployMavenAssetUnderVersionFenceRecordsBytesAtomicallyWithTheWriteItself() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8); + String gav = "com/example/widget/1.0/widget-1.0.jar"; + when(reposiliteClient.deployArtifact(repoId, gav, content)) + .thenReturn(new ReposiliteSidecarClient.DeployOutcome(201, true)); + long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget", "1.0"); + 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(); + + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, + "dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, episodeId, + reposiliteClient, repoId, gav, content); + + assertTrue(result.fenceMatched()); + assertEquals(201, result.outcome().status()); + // This must be true the instant this call returns, not after some separate later call, + // since byte accounting now happens inside this exact same locked call as the write itself. + assertEquals(content.length, service.describeDomain(REGION, "dom", null).assetSizeBytes()); + } + + @Test + void deployMavenAssetUnderVersionFenceDoesNotRecordBytesOnAnIdempotentMatch() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8); + String gav = "com/example/widget/1.0/widget-1.0.jar"; + when(reposiliteClient.deployArtifact(repoId, gav, content)) + .thenReturn(new ReposiliteSidecarClient.DeployOutcome(200, false)); + long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget", "1.0"); + 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(); + + service.deployMavenAssetUnderVersionFence(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + versionFence, packageFence, episodeId, reposiliteClient, repoId, gav, content); + + assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes()); + } + + @Test + void deployMavenAssetUnderVersionFenceWritesNothingWhenTheVersionFenceHasMoved() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + String gav = "com/example/widget/1.0/widget-1.0.jar"; + long currentVersionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget", "1.0"); + long staleVersionFence = currentVersionFence + 1; + 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(); + + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, + "dom", null, "repo", "com.example", "widget", "1.0", staleVersionFence, packageFence, episodeId, + reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8)); + + assertFalse(result.fenceMatched()); + verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any()); + } + + /** + * The fence comparison alone only proves nothing changed since the caller's own snapshot, not + * that the version was not already Disposed before that snapshot was ever taken, the one + * case a plain delete and reimport can never produce (a fresh fence value with no override + * at all). A request the controller's own isDownloadable check let through before this exact + * disposal landed, then delayed past it by the real public fetch, takes its own version-fence + * snapshot only after reaching this far, so the snapshot matches perfectly even though the + * version is already Disposed; the fence alone would wrongly let the write through. + */ + @Test + void deployMavenAssetUnderVersionFenceRefusesToWriteIntoAnAlreadyDisposedVersionEvenWhenTheFenceMatches() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("widget"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)))); + when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("widget"), eq("1.0"))).thenReturn(List.of()); + + service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "widget", + List.of("1.0"), null, null); + + // Taken only after the disposal above, the same way an admitted-but-delayed download's + // own snapshot would be if it reached this far only after disposal already finished. + long versionFenceAfterDisposal = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", + "maven", "com.example", "widget", "1.0"); + 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(); + String gav = "com/example/widget/1.0/widget-1.0.jar"; + + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, + "dom", null, "repo", "com.example", "widget", "1.0", versionFenceAfterDisposal, packageFence, + episodeId, reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8)); + + assertFalse(result.fenceMatched()); + verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any()); + } + + /** + * The end-to-end proof for the same fix: before it, a write's byte accounting ran in a + * separate call after the lock this method now holds was already released, so a dispose + * landing in that exact gap could subtract these same bytes (as part of its own ordinary + * accounting) before the separate call added them, leaving the total permanently + * over-counted for an asset that, by then, no longer existed. With the write and the + * accounting now one atomic call, a dispose that runs any time after this one returns always + * sees the bytes it is actually supposed to subtract, so the net total lands at exactly zero. + */ + @Test + void disposingAVersionJustDeployedThroughThisMethodNeverLeavesItsBytesOverCounted() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8); + String gav = "com/example/widget/1.0/widget-1.0.jar"; + when(reposiliteClient.deployArtifact(repoId, gav, content)) + .thenReturn(new ReposiliteSidecarClient.DeployOutcome(201, true)); + long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget", "1.0"); + 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(); + 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()); + + when(reposiliteClient.listPackageVersions(repoId, "dom", "repo", "com.example", "widget")).thenReturn( + List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)))); + when(reposiliteClient.listPackageVersionAssetNames(repoId, "dom", "repo", "com.example", "widget", "1.0")) + .thenReturn(List.of("widget-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAsset(repoId, "dom", "repo", "com.example", "widget", "1.0", + "widget-1.0.jar")).thenReturn(Optional.of(content)); + + service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "widget", + List.of("1.0"), null, null); + + verify(reposiliteClient).deletePackageVersionAsset(repoId, "dom", "repo", "com.example", "widget", "1.0", + "widget-1.0.jar"); + assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes()); + } + + /** + * DeletePackage on a package with no real content yet (nothing a stalled import has written + * back) removes the origin claim outright but, having deleted nothing, never bumps the package + * fence. A sibling attempt still mid-fetch under that now-removed claim takes its + * versionFenceSnapshot/packageFenceSnapshot before the delete, so neither fence alone would + * ever catch the delete happening in between; a fresh claim made afterward under a different + * connection must still be shielded from that sibling's own stale write. + */ + @Test + void deployMavenAssetUnderVersionFenceRefusesAStaleEpisodeAfterAnEmptyPackageDeleteAndFreshClaim() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, + Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + // An origin configuration (e.g. from an earlier PutPackageOriginConfiguration) is what + // lets deletePackage find this package at all despite no real content ever landing for + // it; without one, deletePackage would 404 outright rather than reaching the empty-content + // path this test is exercising. + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", + "ALLOW", "ALLOW"); + long packageFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + long versionFence = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget", "1.0"); + // The stalled attempt: claims under the first connection, then takes no further action + // until after the delete and fresh claim below (simulating a fetch still in flight). + long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", + "widget", "1.0", "public:maven-central", packageFence).episodeId(); + + // No real content exists for this package yet, so this delete finds nothing to remove and + // never bumps the package fence, even though it does wipe the origin claim above. + when(reposiliteClient.packageExists(repoId, "dom", "repo", "com.example", "widget")).thenReturn(false); + service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget"); + assertEquals(packageFence, service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget")); + + // 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); + + // The stalled attempt's fetch finally returns and tries to write under its own stale + // episode: both fences still match (neither was ever bumped), so only the episode check + // can refuse this write. + String gav = "com/example/widget/1.0/widget-1.0.jar"; + CodeArtifactService.MavenDeployAttemptResult result = service.deployMavenAssetUnderVersionFence(REGION, + "dom", null, "repo", "com.example", "widget", "1.0", versionFence, packageFence, staleEpisodeId, + reposiliteClient, repoId, gav, "jar-content".getBytes(StandardCharsets.UTF_8)); + + assertFalse(result.fenceMatched()); + verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any()); + } + /** * Same coordinate-boundary collision as above, but for published version content rather than * origin configuration: without escaping, the second publish's bytes would be stored under the @@ -2318,6 +2839,142 @@ class CodeArtifactServiceTest { any()); } + /** + * {@code copyContainerBackedPackageVersions} copies a version's real asset bytes without + * copying the source's own Maven retention claim, so without carrying it across separately, + * a copied EXTERNAL version would otherwise report INTERNAL at the destination even though + * its bytes genuinely came from a public connection. + */ + @Test + void copyPackageVersionsCarriesTheSourcesMavenRetentionOriginToTheDestination() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + String srcRepoId = src.getSidecarContainerIds().get("maven"); + String dstRepoId = dst.getSidecarContainerIds().get("maven"); + byte[] jarBytes = "jar-bytes".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(true); + when(reposiliteClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(false); + when(reposiliteClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(jarBytes)); + 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); + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "src", "com.example", "a", "1.0", + srcClaim.episodeId(), true); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, false, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.of("public:maven-central"), service.mavenRetainedVersionOriginConnection(REGION, "dom", + null, "dst", "com.example", "a", "1.0")); + when(reposiliteClient.listPackageVersions(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), + eq("a"))).thenReturn( + List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0", + Instant.ofEpochSecond(1000)))); + CodeArtifactService.ListPackageVersionsResult listed = service.listPackageVersions(REGION, "dom", null, + "dst", "maven", "com.example", "a", null, null, null, null, null); + CodeArtifactService.PackageVersionSummary copied = listed.versions().stream() + .filter(v -> "1.0".equals(v.version())).findFirst().orElseThrow(); + assertEquals("EXTERNAL", copied.originType()); + assertEquals("public:maven-central", copied.externalConnectionName()); + } + + /** + * Overwriting a destination version already retained under one connection with a source + * retained under a different one must not leave the old connection recorded: the real bytes + * just became the source's, so the destination's origin has to follow them, not stay pointing + * at content that is no longer actually there. + */ + @Test + void copyPackageVersionsOverwritingADifferentlyRetainedDestinationReplacesItsOriginRatherThanLeavingItStale() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + String srcRepoId = src.getSidecarContainerIds().get("maven"); + String dstRepoId = dst.getSidecarContainerIds().get("maven"); + byte[] newJarBytes = "new-jar-bytes".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(true); + when(reposiliteClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(true); + when(reposiliteClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJarBytes)); + when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), + eq("a"), eq("1.0"), eq("a-1.0.jar"))) + .thenReturn(Optional.of("old-jar-bytes".getBytes(StandardCharsets.UTF_8))); + 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); + 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); + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0", + dstClaim.episodeId(), true); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.of("public:maven-clojars"), service.mavenRetainedVersionOriginConnection(REGION, "dom", + null, "dst", "com.example", "a", "1.0")); + } + + /** + * Overwriting a destination version retained under a connection with a source that was never + * retained from anywhere (a plain direct publish) must clear the destination's stale claim, + * not leave it reporting a connection whose bytes were just replaced by a direct publish. + */ + @Test + void copyPackageVersionsOverwritingARetainedDestinationWithADirectlyPublishedSourceClearsItsOrigin() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository src = service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + CodeArtifactRepository dst = service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + String srcRepoId = src.getSidecarContainerIds().get("maven"); + String dstRepoId = dst.getSidecarContainerIds().get("maven"); + byte[] newJarBytes = "new-jar-bytes".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.packageVersionExists(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(true); + when(reposiliteClient.packageVersionExists(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), eq("a"), + eq("1.0"))).thenReturn(true); + when(reposiliteClient.listPackageVersionAssetNames(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.listPackageVersionAssetNames(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + when(reposiliteClient.fetchPackageVersionAsset(eq(srcRepoId), eq("dom"), eq("src"), eq("com.example"), + eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(newJarBytes)); + when(reposiliteClient.fetchPackageVersionAsset(eq(dstRepoId), eq("dom"), eq("dst"), eq("com.example"), + eq("a"), eq("1.0"), eq("a-1.0.jar"))) + .thenReturn(Optional.of("old-jar-bytes".getBytes(StandardCharsets.UTF_8))); + 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); + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "dst", "com.example", "a", "1.0", + dstClaim.episodeId(), true); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "maven", "com.example", "a", List.of("1.0"), null, true, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals(Optional.empty(), service.mavenRetainedVersionOriginConnection(REGION, "dom", null, "dst", + "com.example", "a", "1.0")); + } + /** * Raised by Greptile's review: a Maven dispose failing partway through its own asset-deletion * loop leaves the source override reading {@code Disposed} while real files genuinely still @@ -3451,6 +4108,42 @@ class CodeArtifactServiceTest { assertTrue(page2.nextToken() == null); } + /** + * AWS's own {@code DomainEntryPoint} reference: a package ingested from an external source + * reports {@code externalConnectionName}, never {@code repositoryName}, which is reserved for + * one published directly. {@code ListPackageVersions} must surface which of the two applies + * per version, not just the {@code originType} flag. + */ + @Test + void listPackageVersionsReportsTheExternalConnectionNameOnlyForARetainedVersion() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)), + new RepositorySidecarManager.PackageVersionTimestamp("2.0", Instant.ofEpochSecond(2000)))); + 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); + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "a", "2.0", + claim.episodeId(), true); + + CodeArtifactService.ListPackageVersionsResult result = service.listPackageVersions(REGION, "dom", null, + "repo", "maven", "com.example", "a", null, null, null, null, null); + + CodeArtifactService.PackageVersionSummary retained = result.versions().stream() + .filter(v -> "2.0".equals(v.version())).findFirst().orElseThrow(); + assertEquals("EXTERNAL", retained.originType()); + assertEquals("public:maven-central", retained.externalConnectionName()); + + CodeArtifactService.PackageVersionSummary direct = result.versions().stream() + .filter(v -> "1.0".equals(v.version())).findFirst().orElseThrow(); + assertEquals("INTERNAL", direct.originType()); + assertEquals(null, direct.externalConnectionName()); + } + /** * A sidecar that could not supply a timestamp for any version (every {@code * PackageVersionTimestamp.publishedTime} is {@code null}) must still report a deterministic @@ -4022,6 +4715,32 @@ class CodeArtifactServiceTest { assertEquals("Disposed", listed.versions().get(0).status()); } + /** + * Disposing a container-backed version must invalidate any write already snapshotted against + * it, the same way deleting + * one already does, so a Maven external-connection import whose fetch was in flight when + * this runs can detect it and refuse to write the disposed version's bytes back. + */ + @Test + void disposePackageVersionsBumpsThisVersionsOwnFenceOnceItActuallyDeletesRealAssets() { + service.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String repoId = created.getSidecarContainerIds().get("maven"); + when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"))).thenReturn(List.of( + new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000)))); + when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar")); + long fenceSnapshot = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "maven", + "com.example", "a", "1.0"); + + service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"), + null, null); + + assertNotEquals(fenceSnapshot, service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", + "maven", "com.example", "a", "1.0")); + } + /** * Raised by Greptile's review: {@code applyContainerBackedStatusChange} writes the override * {@code Disposed} before deleting any real assets, so a sidecar failure partway through that diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClientTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClientTest.java new file mode 100644 index 0000000000..a0a69b80d6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/MavenExternalConnectionClientTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The wire contract towards a public Maven repository, exercised against a local {@code + * HttpServer} fake standing in for one, named {@code fake} in these tests rather than any of the + * 5 real {@code public:maven-*} connection names. + */ +class MavenExternalConnectionClientTest { + + private HttpServer server; + private MavenExternalConnectionClient client; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.start(); + Map baseUrls = Map.of("fake", "http://127.0.0.1:" + server.getAddress().getPort()); + client = new MavenExternalConnectionClient( + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)) + .followRedirects(HttpClient.Redirect.NORMAL).build(), + baseUrls); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void fetchAssetReturnsTheRealBytesOnA200() throws IOException { + byte[] content = "pom-content".getBytes(StandardCharsets.UTF_8); + server.createContext("/com/example/widget/1.0/widget-1.0.pom", exchange -> { + exchange.sendResponseHeaders(200, content.length); + exchange.getResponseBody().write(content); + exchange.close(); + }); + + Optional result = + client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.pom"); + + assertTrue(result.isPresent()); + assertArrayEquals(content, result.get().content()); + } + + @Test + void fetchAssetReturnsEmptyOnA404() throws IOException { + server.createContext("/com/example/widget/1.0/widget-1.0.pom", + exchange -> respondEmpty(exchange, 404)); + + Optional result = + client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.pom"); + + assertFalse(result.isPresent()); + } + + @Test + void fetchAssetReturnsEmptyForAnUnknownConnectionName() { + Optional result = + client.fetchAsset("public:maven-central", "com/example/widget/1.0/widget-1.0.pom"); + + assertFalse(result.isPresent()); + } + + @Test + void existsReturnsTrueOnA200HeadResponse() throws IOException { + server.createContext("/com/example/widget/1.0/widget-1.0.jar", + exchange -> respondEmpty(exchange, 200)); + + assertTrue(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar")); + } + + @Test + void existsReturnsFalseOnA404HeadResponse() throws IOException { + server.createContext("/com/example/widget/1.0/widget-1.0.jar", + exchange -> respondEmpty(exchange, 404)); + + assertFalse(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar")); + } + + @Test + void fetchAssetEncodesAFragmentCharacterInTheFilenameInsteadOfTruncatingThePath() throws IOException { + byte[] content = "jar-content".getBytes(StandardCharsets.UTF_8); + server.createContext("/", exchange -> { + if (exchange.getRequestURI().getRawPath().contains("%23")) { + exchange.sendResponseHeaders(200, content.length); + exchange.getResponseBody().write(content); + } else { + exchange.sendResponseHeaders(404, -1); + } + exchange.close(); + }); + + Optional result = + client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0#build.jar"); + + assertTrue(result.isPresent()); + assertArrayEquals(content, result.get().content()); + } + + @Test + void fetchAssetFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException { + byte[] content = "redirected-content".getBytes(StandardCharsets.UTF_8); + server.createContext("/com/example/widget/1.0/widget-1.0.jar", exchange -> { + exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.jar"); + exchange.sendResponseHeaders(301, -1); + exchange.close(); + }); + server.createContext("/moved/widget-1.0.jar", exchange -> { + exchange.sendResponseHeaders(200, content.length); + exchange.getResponseBody().write(content); + exchange.close(); + }); + + Optional result = + client.fetchAsset("fake", "com/example/widget/1.0/widget-1.0.jar"); + + assertTrue(result.isPresent()); + assertArrayEquals(content, result.get().content()); + } + + @Test + void existsFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException { + server.createContext("/com/example/widget/1.0/widget-1.0.jar", exchange -> { + exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.jar"); + exchange.sendResponseHeaders(301, -1); + exchange.close(); + }); + server.createContext("/moved/widget-1.0.jar", exchange -> respondEmpty(exchange, 200)); + + assertTrue(client.exists("fake", "com/example/widget/1.0/widget-1.0.jar")); + } + + private static void respondEmpty(HttpExchange exchange, int status) throws IOException { + exchange.sendResponseHeaders(status, -1); + exchange.close(); + } +}