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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 18:04:57 -05:00
1 parent 743bede481
commit a03e88b451
11 files changed
+2471 -46

No files matched your search

@@ -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;
}
@@ -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<String[]> parseNamespaceAndPackageName(String gav) {
static Optional<String[]> 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<FetchedArtifact> 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();
}
/**
@@ -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:
*
* <ul>
* <li><b>Release versions only.</b> "AWS CodeArtifact only supports importing Maven release
* versions" through an external connection; a {@code -SNAPSHOT} version is never attempted.</li>
* <li><b>Standard assets, imported together.</b> When the requested filename matches one of the
* 4 names CodeArtifact's own docs enumerate ({@code <artifactId>-<version>.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).</li>
* <li><b>Non-standard assets, imported on demand only.</b> 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.</li>
* <li><b>Checking asset origins.</b> 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.</li>
* <li><b>Coordinated with this emulator's own deletion and disposal.</b> 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.</li>
* </ul>
*
* <p>Deliberately not modeled here, because it cannot apply without an actual upstream
* <em>repository</em> 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<String[]> 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<String> standardNames = standardAssetFilenames(packageName, version);
List<String> candidates = standardNames.contains(filename) ? standardNames : List.of(filename);
boolean importedRequestedAsset = false;
boolean importedAny = false;
try {
for (String candidateFilename : candidates) {
String candidateGav = directory + candidateFilename;
Optional<MavenExternalConnectionClient.FetchedAsset> 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 <em>version</em> 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<String[]> 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<String> standardAssetFilenames(String artifactId, String version) {
String base = artifactId + "-" + version;
return List.of(base + ".pom", base + ".jar", base + "-javadoc.jar", base + "-sources.jar");
}
}
@@ -160,7 +160,8 @@ public class CodeArtifactService implements Resettable {
public record AssetSummary(String name, long size, Map<String, String> hashes) {}
public record PackageVersionAssetsListResult(String format, String namespace, String packageName,
String version, String versionRevision, List<AssetSummary> 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<PackageVersionSummary> 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<String, Set<String>> 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<String, MavenRetainedVersionOriginClaim> 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 <em>and</em> {@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 {
*
* <p>{@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.
*
* <p>{@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<PackageVersionEntry> 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<PackageVersionEntry> 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<PackageVersionEntry> matchingOrigin = originType != null && !"INTERNAL".equals(originType)
? List.of()
List<PackageVersionEntry> matchingOrigin = originType != null
? entries.stream().filter(e -> originType.equals(e.originType())).toList()
: entries;
List<PackageVersionEntry> 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<PackageVersionSummary> 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 <em>and</em> 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.
*
* <p>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 <em>any</em>
* 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<PackageOriginConfig> 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.
*
* <p>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<String> 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).
*
* <p>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.
*
* <p>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.
*
* <p>{@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 <em>and</em> 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.
*
* <p>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.
*
* <p>{@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.
*
* <p>The fence comparison alone only proves nothing changed <em>since the caller's own
* snapshot was taken</em>; it says nothing about whether this version was already Disposed or
* Archived <em>before</em> 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.
*
* <p>{@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<String> 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.
*
* <p>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.
*
* <p>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<String> 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) {
@@ -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):
*
* <ul>
* <li>{@code public:maven-central}: {@code https://repo.maven.apache.org/maven2}, the Super
* POM's and Gradle's own {@code MAVEN_CENTRAL_URL} default.</li>
* <li>{@code public:maven-clojars}: {@code https://repo.clojars.org}.</li>
* <li>{@code public:maven-commonsware}: {@code https://s3.amazonaws.com/repo.commonsware.com},
* confirmed against a real CWAC library's own published README.</li>
* <li>{@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).</li>
* <li>{@code public:maven-gradleplugins}: {@code https://plugins.gradle.org/m2}, what {@code
* gradlePluginPortal()} resolves to.</li>
* </ul>
*
* <p>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<String, String> 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<String, String> 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<String, String> 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 <groupPath>/<artifactId>/<version>/<filename>} shape
* Reposilite itself uses, since both are standard Maven2 repository layouts) from the real
* public repository {@code externalConnectionName} names.
*/
public Optional<FetchedAsset> 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<HttpResponse<byte[]>> 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<byte[]> 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);
}
}
}
@@ -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<String, PackageAsset> 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<String, PackageAsset> getAssets() {
return Collections.unmodifiableMap(assets);
}