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 1eb326c495..716cc71a03 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 @@ -178,8 +178,9 @@ public class CodeArtifactMavenController { return 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)) { + if ((artifact.isEmpty() || isBareMavenMetadataFile(gav)) + && 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()); @@ -197,13 +198,29 @@ public class CodeArtifactMavenController { // 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)) { + if ((!exists || isBareMavenMetadataFile(gav)) + && 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(); } + /** + * {@code true} only for the exact, bare {@code maven-metadata.xml} path, never a checksum + * sibling: unlike a fixed version's own assets, which never change once retained, a package's + * available-version list can keep growing on the real public repository after this + * repository's own first merge of it, so a request for this exact file always gets a fresh + * import attempt even when a local copy already exists, not just on the first ever miss. + * Raised by Greptile's review: without this, {@link #fetch}/{@link #head} only ever imported + * metadata once, the first time this exact GAV was requested, and every later request for the + * same package's version list silently kept serving that same first snapshot forever, no + * matter how many releases the public repository published afterward. + */ + private static boolean isBareMavenMetadataFile(String gav) { + return gav.endsWith("/maven-metadata.xml"); + } + /** * {@code true} unless {@code gav} names an exact version this service knows is {@code * Archived}: {@link #parseNamespaceAndPackageName}'s own version element is {@code null} for a 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 index fd2d5cb2aa..930efddc42 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporter.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.codeartifact; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -7,6 +8,7 @@ import org.jboss.logging.Logger; import java.util.List; import java.util.Optional; +import java.util.function.Predicate; /** * Retains a Maven package version from the real public repository a repository's {@code @@ -50,6 +52,12 @@ import java.util.Optional; * 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. + *
  • Resolving version ranges and dynamic versions. A bare group/artifact-level + * {@code maven-metadata.xml} request is resolved by merging in whichever release versions the + * public repository's own metadata names, not by importing a single fixed version; see + * {@link #tryImportMetadata}'s own javadoc. Without this, a Maven version range or a Gradle + * dynamic version could never resolve against a connected repository that has not already + * retained some other fixed version of this exact package some other way.
  • * * *

    Deliberately not modeled here, because it cannot apply without an actual upstream @@ -84,16 +92,30 @@ public class CodeArtifactMavenExternalConnectionImporter { * 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). + * + *

    A bare group/artifact-level {@code maven-metadata.xml} (no version segment in {@code + * gav}) is resolved differently: see {@link #tryImportMetadata}. This only ever merges in + * which releases the public repository has; the real bytes of whichever version a resolver + * settles on afterward still come through this same method's ordinary per-asset path, on + * the request that follows, the same two-step resolution a real {@code mvn}/Gradle client + * already does against a connected upstream. */ 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")) { + if (coordinate.isEmpty()) { return false; } String namespace = coordinate.get()[0]; String packageName = coordinate.get()[1]; String version = coordinate.get()[2]; + if (version == null) { + return gav.endsWith("/maven-metadata.xml") && tryImportMetadata(region, domain, owner, repository, + repoId, namespace, packageName); + } + if (version.endsWith("-SNAPSHOT")) { + return false; + } String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository); if (externalConnectionName == null) { @@ -251,6 +273,69 @@ public class CodeArtifactMavenExternalConnectionImporter { return externalConnectionClient.exists(externalConnectionName, pomGav); } + /** + * Resolves {@code namespace}/{@code packageName}'s own group/artifact-level {@code + * maven-metadata.xml} through {@code repository}'s maven external connection: without this, a + * Maven version range or a Gradle dynamic version could never resolve against a connected + * repository that has not already retained a fixed version of this exact package some other + * way, since nothing else here ever asks the real public repository what versions it + * actually has. Every candidate version this repository already knows is {@code Archived}/ + * {@code Disposed} is kept out of the merge, the same existence check a per-version download + * itself already enforces through {@link + * CodeArtifactService#requireContainerBackedVersionDownloadable}, so a disposed version's + * metadata entry can never come back from the public repository's own still-unaware listing. + * Returns {@code true} only when the public repository's own metadata named at least one + * allowed release version this repository did not already have listed; see {@link + * ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s own javadoc for exactly + * how a merge with any locally-published versions is handled. + * + *

    Raised by Greptile's review: the real fetch from the public repository below can take + * long enough for a concurrent {@code DeletePackage} to finish while it is still in flight. + * Without a fence, the merge that follows would write {@code maven-metadata.xml} straight + * back once that fetch completes, resurrecting the version list {@code DeletePackage} had + * already told its caller was gone. {@code packageFenceSnapshot} is taken here, before that + * fetch, for {@link CodeArtifactService#mergeMavenMetadataUnderPackageFence} to check right + * before the write, inside the same lock {@code DeletePackage} itself holds for its own entire + * operation; see that method's own javadoc for the full race this closes. + */ + private boolean tryImportMetadata(String region, String domain, String owner, String repository, String repoId, + String namespace, String packageName) { + String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository); + if (externalConnectionName == null) { + return false; + } + if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace, + packageName)) { + return false; + } + long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, + "maven", namespace, packageName); + String metadataGav = namespace.replace('.', '/') + "/" + packageName + "/maven-metadata.xml"; + Optional fetched; + try { + fetched = externalConnectionClient.fetchAsset(externalConnectionName, metadataGav); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not fetch {0}/{1}''s maven-metadata.xml from {2} while resolving its versions " + + "through an external connection; leaving it unresolved.", namespace, packageName, + externalConnectionName); + return false; + } + if (fetched.isEmpty()) { + return false; + } + Predicate versionAllowed = version -> { + try { + service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "maven", + namespace, packageName, version, repoId); + return true; + } catch (AwsException e) { + return false; + } + }; + return service.mergeMavenMetadataUnderPackageFence(region, domain, owner, repository, namespace, + packageName, packageFenceSnapshot, reposilite, repoId, fetched.get().content(), versionAllowed); + } + 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())) 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 325ba4746f..baf0a7dcf8 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 @@ -53,6 +53,7 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; +import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -3126,6 +3127,54 @@ public class CodeArtifactService implements Resettable { return new MavenDeployAttemptResult(true, outcome); } + /** + * {@link ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s own counterpart to + * {@link #deployMavenAssetUnderVersionFence}, at package granularity rather than one version's: + * a metadata merge has no single version or claim episode of its own to check against, since + * it only ever advertises versions, never retains real bytes for any of them. Checked and + * acted on inside this very same {@code synchronized} call {@link #deletePackage} already + * holds for its own entire operation (and bumps {@code containerBackedPackageDeletionFence} + * behind), so the two can never interleave. + * + *

    Raised by Greptile's review: {@code CodeArtifactMavenExternalConnectionImporter} used to + * fetch the real public repository's metadata and write the merge straight back with no fence + * check at all. A {@code DeletePackage} that finished while that real, slow fetch was still in + * flight would have its removal silently undone the moment the fetch finally completed and + * this write landed, resurrecting a {@code maven-metadata.xml} (and its checksums) for a + * package {@code DeletePackage} had already told its caller was gone, even if the external + * connection itself was also removed somewhere in that same gap. + * + *

    {@code packageFenceSnapshot} is whatever {@link #currentContainerBackedPackageFence} + * returned when the importer called it, right before issuing the real fetch that produced + * {@code externalMetadataXml}; {@code reposilite}, {@code repoId}, and the rest of the merge's + * own inputs come from the caller for the same reason {@link #deployMavenAssetUnderVersionFence} + * takes them as parameters rather than fields: the slow part already happened before this lock + * was ever taken. + * + *

    Raised by Greptile's review: the package fence alone says nothing about {@link + * #deleteRepository} (also {@code synchronized} on this same lock) having removed the whole + * repository, not just this one package, while that same fetch was in flight. Without also + * checking that here, {@link ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s + * own {@code ensureRepository} call would transparently recreate the Reposilite repository + * {@code deleteRepository} had just torn down, leaving real metadata and checksum files behind + * with no CodeArtifact repository left through which anything could ever delete them again. + */ + public synchronized boolean mergeMavenMetadataUnderPackageFence(String region, String domain, + String domainOwner, String repository, String namespace, String packageName, long packageFenceSnapshot, + ReposiliteSidecarClient reposilite, String repoId, byte[] externalMetadataXml, + Predicate versionAllowed) { + if (currentContainerBackedPackageFence(region, domain, domainOwner, repository, "maven", namespace, + packageName) != packageFenceSnapshot) { + return false; + } + String owner = effectiveOwner(domainOwner); + if (repositories.getForAccount(owner, repositoryKey(region, domain, repository)).isEmpty()) { + return false; + } + return reposilite.mergeExternalConnectionReleaseVersions(repoId, namespace, packageName, externalMetadataXml, + versionAllowed); + } + /** * 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 @@ -3194,11 +3243,16 @@ public class CodeArtifactService implements Resettable { if (CONTAINER_BACKED_FORMATS.contains(format)) { hadRealContent = deleteContainerBackedPackageIfPresent(region, domain, owner, repository, format, namespace, packageName); - if (hadRealContent) { - // Bumped only on an actual deletion, never a no-op (nothing there to begin with): - // see currentContainerBackedPackageFence's own javadoc for what this protects - // against, and why it can replace a sidecar round trip entirely rather than just - // relocate one. + if (hadRealContent || originConfig.isPresent()) { + // Bumped on any deletion this call actually goes through with, not just one that + // removed real content: see currentContainerBackedPackageFence's own javadoc for + // what this protects against, and why it can replace a sidecar round trip entirely + // rather than just relocate one. Raised by Greptile's review: an origin-config-only + // package (no real content, just a stored PutPackageOriginConfiguration) used to + // leave this fence untouched, so a Maven metadata merge already in flight for that + // exact package, racing this exact delete, could still write maven-metadata.xml + // back afterward with a snapshot that still matched, resurrecting a package this + // call had already told its caller was gone. containerBackedPackageDeletionFence.put(ownerScopedKey(owner, accountingKey), containerBackedPackageDeletionCounter.incrementAndGet()); } @@ -3306,13 +3360,21 @@ public class CodeArtifactService implements Resettable { * origin-config-only or not; that cost already existed for every real package before this * method's origin-config awareness, this just stops it from being skipped by accident instead * of by choice. + * + *

    Checked through {@link RepositorySidecarManager#hasAnyContentToDelete}, not {@link + * RepositorySidecarManager#packageExists}: a Maven package that only ever had its {@code + * maven-metadata.xml} merged in from an external connection, with no version ever actually + * retained, correctly answers {@code packageExists} {@code false} (see that method's own + * javadoc), but still has that merged metadata file sitting on the sidecar for this call to + * actually remove, rather than skipping the delete and reporting success while leaving it + * fetchable. */ private boolean deleteContainerBackedPackageIfPresent(String region, String domain, String owner, String repository, String format, String namespace, String packageName) { String repoId = ensureFormatContainerId(format, region, domain, owner, repository); RepositorySidecarManager manager = sidecarRegistry.forFormat(format) .orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, "package")); - if (!manager.packageExists(repoId, domain, repository, namespace, packageName)) { + if (!manager.hasAnyContentToDelete(repoId, domain, repository, namespace, packageName)) { return false; } try { @@ -4530,8 +4592,10 @@ public class CodeArtifactService implements Resettable { * delayed callback (its own Vert.x response arriving well after this snapshot was taken, long * after Maven's or pypi's near-immediate inline accounting would have run) must not have the * first publish's bytes misattributed to the second. {@code deletePackage}'s container-backed - * branch bumps the counter behind this snapshot on an actual deletion; so does - * {@link #forgetContainerBackedPackage}, for the one other way a container-backed package's + * branch bumps the counter behind this snapshot on any deletion it actually goes through with, + * real content or an origin-config-only package alike, never a no-op where neither existed to + * begin with (that case 404s outright instead); so does {@link #forgetContainerBackedPackage}, + * for the one other way a container-backed package's * real content can disappear: a real npm client's native {@code npm unpublish}, which the * pinned Verdaccio image (configured with {@code unpublish: $all}) honors on its own wire * protocol without ever calling {@code deletePackage} (confirmed: {@code diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java index a26ba6ec9b..93fcb56d89 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.function.Predicate; /** * HTTP client for the shared Reposilite sidecar. A CodeArtifact repository maps to a named @@ -149,15 +150,55 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { } /** - * Only a confirmed 404 means absent; confirmed live (a {@code GET} on a missing directory, or a - * never-provisioned repository, both answer a clean 404). Anything else, an auth failure or a - * server error, throws instead of collapsing to "not found": a Reposilite outage must not read - * as every Maven package having been deleted. + * {@code true} only when at least one real version subdirectory sits beneath the group/ + * artifact directory, not merely whenever that directory answers at all: {@link + * #mergeExternalConnectionReleaseVersions} writes a {@code maven-metadata.xml} straight into + * that same directory purely to advertise resolvable versions, with no version ever actually + * retained there, so treating that file's presence alone as "exists" would make {@code + * CodeArtifactService#isUpstreamRetentionBlocked} see a brand-new package as already + * directly-published and permanently refuse every later retention attempt for it, since no + * claim could ever get recorded to prove otherwise. A confirmed 404 means absent (a missing + * directory, or a never-provisioned repository, both answer a clean 404). Anything else, an + * auth failure or a server error, throws instead of collapsing to "not found": a Reposilite + * outage must not read as every Maven package having been deleted. */ @Override public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace, String packageName) { String baseUrl = manager.ensureReady(); + String path = "/api/maven/details" + packageDirectoryPath(repositoryContainerId, namespace, packageName); + HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path)) + .timeout(Duration.ofSeconds(30)) + .header("Authorization", manager.basicAuthHeader()) + .GET() + .build(); + HttpResponse response = send(request, BodyHandlers.ofString()); + if (response.statusCode() == 404) { + return false; + } + if (response.statusCode() != 200) { + throw new IllegalStateException("Could not look up " + packageName + " on the Reposilite sidecar: " + + "upstream returned " + response.statusCode()); + } + for (JsonNode entry : readTree(response.body()).path("files")) { + if ("DIRECTORY".equals(entry.path("type").asText())) { + return true; + } + } + return false; + } + + /** + * Unlike {@link #packageExists}, a bare GET on the group/artifact directory, with no + * requirement that anything beneath it be a real version: a metadata-only merge (just a + * {@code maven-metadata.xml} file, no version subdirectory) still answers {@code 200} here, + * so {@code DeletePackage} actually removes it instead of skipping the delete and reporting + * success while leaving it fetchable. + */ + @Override + public boolean hasAnyContentToDelete(String repositoryContainerId, String domain, String repository, + String namespace, String packageName) { + String baseUrl = manager.ensureReady(); HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), packageDirectoryPath(repositoryContainerId, namespace, packageName))) .timeout(Duration.ofSeconds(30)) @@ -624,6 +665,138 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager { deployArtifact(repositoryContainerId, gav, metadata.build().getBytes(StandardCharsets.UTF_8)); } + /** + * Merges {@code externalMetadataXml}, a real public Maven repository's own group/artifact- + * level {@code maven-metadata.xml} fetched through an external connection, into {@code + * repositoryContainerId}'s own copy, so a client resolving a Maven version range or a Gradle + * dynamic version can discover a release this repository has never actually retained a byte + * of yet. The real asset bytes for whichever version the resolver settles on are still + * fetched on demand the normal way, through a separate, per-version import attempt; this + * only ever advertises versions, the same separation a real {@code maven-metadata.xml} + * request and the version-specific GAV requests that follow it already have. + * + *

    Only {@code -SNAPSHOT}-free versions this repository's own {@code versionAllowed} does + * not reject are merged in: the snapshot restriction matches an external connection's own + * per-asset import ("AWS CodeArtifact only supports importing Maven release versions"), and + * {@code versionAllowed} exists so a caller can also keep out any version this repository has + * recorded as {@code Archived}/{@code Disposed}. Without that second check, disposing this + * package's only locally-listed version deletes its metadata file outright (see {@link + * #recordVersionDisposed}), and the next merge would otherwise re-import that exact disposed + * version straight back from the public repository's own still-unaware listing: a resolver + * could then pick a version whose real bytes this repository will never serve again. A + * version already listed locally is never added twice. Returns {@code false} without writing + * anything when the public repository's own metadata names no allowed release version this + * repository doesn't already have listed. + * + *

    Reads the existing local copy through {@link #fetchArtifactConfirmingMissing}, not + * {@link #fetchArtifact}: that method's {@code empty()} also means "any non-200," 500/503 + * included, which this merge must never read as "no local metadata yet," since that would let + * a transient sidecar read failure silently replace a real, locally-published package's + * {@code latest}/{@code release} with the external source's own guess at them. + * + *

    Never lets the external source override an already-existing local {@code latest}/ + * {@code release}: this bridge has no reliable way to tell whether a locally-published + * version a direct {@code mvn deploy} already recorded is newer or older than whatever the + * public repository last published, since Maven version strings do not sort by any universal + * rule this emulator could apply safely. A package with no local metadata at all has nothing + * to protect, so its merged {@code latest}/{@code release} are taken from the external + * source's own declared values, falling back to the last release version in document order + * when the source's own {@code }/{@code } elements are themselves missing. + * + *

    Writes the matching {@code .sha1}/{@code .md5} checksum siblings alongside every write, + * the same upkeep {@link #recordVersionDisposed} already owes this exact file: left out, a + * Maven client that verifies checksums could never trust even the first metadata response + * this merge ever produces. Raised by Greptile's review: the no-op return below, taken once + * every external version is already listed locally, repairs those same two checksums against + * the existing metadata first, the same way {@link #recordVersionDisposed}'s own early + * returns already do. Without that, a prior attempt whose metadata write succeeded but whose + * checksum write then failed would leave a stale checksum in place forever: every later + * request for this exact package would keep finding nothing new to add and keep taking this + * same no-op path, never repairing it, so a client verifying checksums could keep failing + * indefinitely even once the sidecar itself has long since recovered. + */ + public boolean mergeExternalConnectionReleaseVersions(String repositoryContainerId, String namespace, + String packageName, byte[] externalMetadataXml, Predicate versionAllowed) { + ensureRepository(repositoryContainerId); + String externalXml = new String(externalMetadataXml, StandardCharsets.UTF_8); + List externalReleaseVersions = XmlParser.extractAll(externalXml, "version").stream() + .filter(v -> !v.endsWith("-SNAPSHOT")) + .filter(versionAllowed) + .toList(); + if (externalReleaseVersions.isEmpty()) { + return false; + } + String gav = artifactMetadataGav(namespace, packageName); + Optional existing = fetchArtifactConfirmingMissing(repositoryContainerId, gav); + List versions = new ArrayList<>(); + String groupId = namespace; + String artifactId = packageName; + String latest = null; + String release = null; + boolean hadLocalMetadata = existing.isPresent(); + if (hadLocalMetadata) { + String xml = new String(existing.get().content(), StandardCharsets.UTF_8); + versions.addAll(XmlParser.extractAll(xml, "version")); + groupId = XmlParser.extractFirst(xml, "groupId", namespace); + artifactId = XmlParser.extractFirst(xml, "artifactId", packageName); + latest = XmlParser.extractFirst(xml, "latest", null); + release = XmlParser.extractFirst(xml, "release", null); + } + boolean addedAny = false; + for (String version : externalReleaseVersions) { + if (!versions.contains(version)) { + versions.add(version); + addedAny = true; + } + } + if (!addedAny) { + if (hadLocalMetadata) { + writeMetadataChecksum(repositoryContainerId, gav + ".sha1", + Digests.sha1Hex(existing.get().content())); + writeMetadataChecksum(repositoryContainerId, gav + ".md5", + Digests.md5Hex(existing.get().content())); + } + return false; + } + if (!hadLocalMetadata) { + groupId = XmlParser.extractFirst(externalXml, "groupId", namespace); + artifactId = XmlParser.extractFirst(externalXml, "artifactId", packageName); + // The external source's own declared / are trusted only when they + // actually name one of this merge's own release versions: a public repository could + // declare a SNAPSHOT (or any other value already filtered out above) as its latest, + // which must never end up named here without also being listed in . + String lastReleaseVersion = externalReleaseVersions.get(externalReleaseVersions.size() - 1); + String declaredLatest = XmlParser.extractFirst(externalXml, "latest", null); + latest = externalReleaseVersions.contains(declaredLatest) ? declaredLatest : lastReleaseVersion; + String declaredRelease = XmlParser.extractFirst(externalXml, "release", null); + release = externalReleaseVersions.contains(declaredRelease) ? declaredRelease : lastReleaseVersion; + } + XmlBuilder metadata = new XmlBuilder().start("metadata") + .elem("groupId", groupId) + .elem("artifactId", artifactId) + .start("versioning") + .elem("latest", latest) + .elem("release", release) + .start("versions"); + for (String v : versions) { + metadata.elem("version", v); + } + metadata.end("versions") + .elem("lastUpdated", METADATA_TIMESTAMP.format(Instant.now())) + .end("versioning") + .end("metadata"); + byte[] metadataBytes = metadata.build().getBytes(StandardCharsets.UTF_8); + DeployOutcome outcome = deployArtifact(repositoryContainerId, gav, metadataBytes); + if (!outcome.wroteNewContent()) { + throw new IllegalStateException("Could not merge external connection release versions into " + + packageName + "'s maven-metadata.xml on the Reposilite sidecar: upstream returned " + + outcome.status()); + } + writeMetadataChecksum(repositoryContainerId, gav + ".sha1", Digests.sha1Hex(metadataBytes)); + writeMetadataChecksum(repositoryContainerId, gav + ".md5", Digests.md5Hex(metadataBytes)); + return true; + } + /** * {@link #recordVersionAvailable}'s dispose-time counterpart (found missing by Qodo review on * the PR that added {@code DisposePackageVersions}): without this, a disposed Maven version's diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java index 6c2f0ba2d5..f13b03deab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/RepositorySidecarManager.java @@ -67,6 +67,23 @@ public interface RepositorySidecarManager { boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace, String packageName); + /** + * {@code true} when this sidecar has written anything at all under this package, even content + * that would not count as "holding a version" for {@link #packageExists}: a Maven + * group/artifact directory that only ever got a {@code maven-metadata.xml} merged into it to + * advertise a public repository's release list, with no version ever actually retained, is + * real content a {@code DeletePackage} still has to clear, even though {@link #packageExists} + * correctly answers {@code false} for it. Defaults to exactly {@link #packageExists}, since no + * other format currently has an equivalent metadata-but-no-version state; {@code + * ReposiliteSidecarClient} is the only implementation that overrides this, so a package left + * in that state is still actually deleted rather than {@code DeletePackage} reporting success + * while leaving it fetchable. + */ + default boolean hasAnyContentToDelete(String repositoryContainerId, String domain, String repository, + String namespace, String packageName) { + return packageExists(repositoryContainerId, domain, repository, namespace, packageName); + } + /** * {@code true} when this sidecar holds exactly the named version of the named package, for * bridging {@code DescribePackageVersion} when there is no generic-format record to describe: diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenControllerTest.java new file mode 100644 index 0000000000..15654c57d4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenControllerTest.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; +import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +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 CodeArtifactMavenController#fetch}'s own decision of when to ask {@link + * CodeArtifactMavenExternalConnectionImporter} to attempt an external-connection import at all, + * not the importer's or {@link ReposiliteSidecarClient}'s own logic, which each have their own + * tests. Both collaborators are mocked, so no real sidecar or network call ever happens here. + */ +class CodeArtifactMavenControllerTest { + + private static final String REGION = "us-east-1"; + private static final String OWNER = "123456789012"; + private static final String DOMAIN = "dom"; + private static final String REPOSITORY = "repo"; + private static final String REPO_ID = "repo-id"; + private static final String METADATA_GAV = "com/example/widget/maven-metadata.xml"; + + private CodeArtifactService service; + private ReposiliteSidecarClient reposilite; + private CodeArtifactMavenExternalConnectionImporter externalConnectionImporter; + private CodeArtifactMavenController controller; + private HttpHeaders headers; + + @BeforeEach + void setUp() { + service = mock(CodeArtifactService.class); + reposilite = mock(ReposiliteSidecarClient.class); + externalConnectionImporter = mock(CodeArtifactMavenExternalConnectionImporter.class); + controller = new CodeArtifactMavenController(service, reposilite, externalConnectionImporter); + headers = mock(HttpHeaders.class); + when(headers.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer some-token"); + when(service.resolveAuthorizationToken("some-token", DOMAIN)) + .thenReturn(Optional.of(new AuthorizationTokenScope(OWNER, REGION))); + when(service.ensureFormatContainerId("maven", REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(REPO_ID); + } + + /** + * Raised by Greptile's review: once a bare group/artifact-level {@code maven-metadata.xml} + * import ever succeeds, a local copy exists from then on, so the old miss-only gate + * ({@code artifact.isEmpty()}) would never let a later request try the importer again, and a + * public release published after that first import would stay invisible to every version + * range or dynamic version indefinitely. This exact path is now always retried, so a second + * request still picks up whatever the importer merges in afterward. + */ + @Test + void aSecondRequestForBareMetadataStillAttemptsAFreshImportEvenWhenALocalCopyAlreadyExists() { + FetchedArtifact stale = new FetchedArtifact("".getBytes(StandardCharsets.UTF_8), + "application/xml"); + FetchedArtifact refreshed = new FetchedArtifact("" + .getBytes(StandardCharsets.UTF_8), "application/xml"); + when(reposilite.fetchArtifact(REPO_ID, METADATA_GAV)).thenReturn(Optional.of(stale)) + .thenReturn(Optional.of(refreshed)); + when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, METADATA_GAV)) + .thenReturn(true); + + Response response = controller.fetch(headers, DOMAIN, REPOSITORY, METADATA_GAV); + + assertEquals(200, response.getStatus()); + assertEquals("", + new String((byte[]) response.getEntity(), StandardCharsets.UTF_8)); + verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, METADATA_GAV); + } + + /** + * The counterpart that keeps the always-retry behavior scoped to bare metadata: a fixed + * version's own asset never changes once retained, so re-asking the importer for it on every + * request a local copy already answers would just be wasted external-connection traffic. + */ + @Test + void aFixedVersionAssetIsNotReimportedOnceALocalCopyAlreadyExists() { + String versionGav = "com/example/widget/1.0/widget-1.0.jar"; + FetchedArtifact existing = new FetchedArtifact("real-bytes".getBytes(StandardCharsets.UTF_8), + "application/java-archive"); + when(reposilite.fetchArtifact(REPO_ID, versionGav)).thenReturn(Optional.of(existing)); + + Response response = controller.fetch(headers, DOMAIN, REPOSITORY, versionGav); + + assertEquals(200, response.getStatus()); + verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any()); + } +} 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 index 0c6f28adb3..afd8525009 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionDockerIntegrationTest.java @@ -14,6 +14,7 @@ import java.nio.charset.StandardCharsets; import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -25,7 +26,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * 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. + * does not re-exercise, and {@code ReposiliteSidecarClientTest} for the same of the + * {@code maven-metadata.xml} merge a Maven version range or Gradle dynamic version actually relies + * on to resolve at all. */ @QuarkusTest @TestProfile(SidecarContainersProfile.class) @@ -36,8 +39,10 @@ class CodeArtifactMavenExternalConnectionDockerIntegrationTest { 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 DYNAMIC_REPO = "maven-external-connection-dynamic-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 final String JUNIT_METADATA = "junit/junit/maven-metadata.xml"; private static String bearerToken; @@ -59,6 +64,9 @@ class CodeArtifactMavenExternalConnectionDockerIntegrationTest { 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?domain=" + DOMAIN + "&repository=" + DYNAMIC_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") @@ -67,6 +75,10 @@ class CodeArtifactMavenExternalConnectionDockerIntegrationTest { .post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_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=" + DYNAMIC_REPO + + "&external-connection=public:maven-central") + .then().statusCode(200); bearerToken = given().header("Authorization", AUTH) .post("/v1/authorization-token?domain=" + DOMAIN) @@ -151,4 +163,34 @@ class CodeArtifactMavenExternalConnectionDockerIntegrationTest { + "/com/example/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar") .then().statusCode(404); } + + /** + * The sequence a real Maven version range or Gradle dynamic version actually produces: a bare + * {@code maven-metadata.xml} request first, merging in the real release versions {@code + * public:maven-central} names for junit, then a request for whichever exact version got picked + * (4.13.2, the real latest). Runs against its own repository, never touched by an earlier + * {@code @Order}, so the metadata request here is genuinely this package's first contact with + * the sidecar: merging metadata before any version is ever retained once made {@code + * packageExists} see the group/artifact directory as already present and permanently refuse to + * ever retain a real version for it, since no claim could get recorded to prove the package's + * origin was external rather than directly published. This is the regression test for that. + */ + @Test + @Order(6) + void aVersionRangeResolvesThroughAMetadataRequestThenRetainsTheChosenVersion() { + byte[] metadata = given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + DYNAMIC_REPO + "/" + JUNIT_METADATA) + .then().statusCode(200) + .extract().asByteArray(); + String metadataXml = new String(metadata, StandardCharsets.UTF_8); + assertThat(metadataXml, containsString("4.13.2")); + + byte[] jar = given().header("Authorization", "Bearer " + bearerToken) + .get("/codeartifact/maven/" + DOMAIN + "/" + DYNAMIC_REPO + "/" + JUNIT_JAR) + .then().statusCode(200) + .extract().asByteArray(); + assertEquals('P', (char) jar[0]); + assertEquals('K', (char) jar[1]); + assertThat(jar.length, greaterThan(1000)); + } } 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 index 147095bad6..cdc90aa83e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenExternalConnectionImporterTest.java @@ -1,13 +1,16 @@ package io.github.hectorvent.floci.services.codeartifact; +import io.github.hectorvent.floci.core.common.AwsException; 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.ArgumentCaptor; import org.mockito.InOrder; import java.util.List; import java.util.Optional; +import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -15,6 +18,7 @@ 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.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -99,7 +103,117 @@ class CodeArtifactMavenExternalConnectionImporterTest { } @Test - void doesNothingForABareMavenMetadataPath() { + void resolvesMetadataThroughTheExternalConnectionWhenNotFoundLocally() { + byte[] metadataBytes = "".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + .thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/maven-metadata.xml"); + + assertTrue(imported); + } + + /** + * Raised by Greptile's review: the real fetch from the public repository can take long enough + * for a concurrent {@code DeletePackage} to finish while it is still in flight, so the fence + * snapshot passed to {@link CodeArtifactService#mergeMavenMetadataUnderPackageFence} must be + * taken before that fetch, not after, or a delete landing in between would never be caught by + * the check that runs inside that same call. + */ + @Test + void takesThePackageFenceSnapshotBeforeFetchingFromThePublicRepository() { + byte[] metadataBytes = "".getBytes(); + when(service.currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "maven", "com.example", + "widget")).thenReturn(42L); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + .thenReturn(true); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/maven-metadata.xml"); + + assertTrue(imported); + verify(service).mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq("com.example"), eq("widget"), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any()); + } + + /** + * {@link CodeArtifactMavenExternalConnectionImporter#tryImportMetadata} builds its own + * {@code versionAllowed} predicate from {@link + * CodeArtifactService#requireContainerBackedVersionDownloadable}, the exact same existence + * check a per-version download itself already enforces: a version this repository knows is + * {@code Archived}/{@code Disposed} throws from that check and must come back {@code false}, + * while a version with no override at all (the common case: nothing here has ever recorded + * one) must come back {@code true}. + */ + @Test + @SuppressWarnings("unchecked") + void versionAllowedPredicateRejectsOnlyVersionsTheServiceReportsNotDownloadable() { + byte[] metadataBytes = "".getBytes(); + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) + .thenReturn(Optional.of(new MavenExternalConnectionClient.FetchedAsset(metadataBytes))); + when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any())) + .thenReturn(true); + doThrow(new AwsException("ResourceNotFoundException", "gone", 404)) + .when(service).requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, REPOSITORY, "maven", + "com.example", "widget", "1.0-disposed", REPO_ID); + + importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "com/example/widget/maven-metadata.xml"); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Predicate.class); + verify(service).mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), + eq("com.example"), eq("widget"), anyLong(), eq(reposilite), eq(REPO_ID), eq(metadataBytes), + captor.capture()); + Predicate versionAllowed = captor.getValue(); + assertFalse(versionAllowed.test("1.0-disposed")); + assertTrue(versionAllowed.test("1.0")); + } + + @Test + void doesNothingForABareMavenMetadataPathWhenTheExternalSourceHasNone() { + when(externalConnectionClient.fetchAsset("public:maven-central", "com/example/widget/maven-metadata.xml")) + .thenReturn(Optional.empty()); + + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/maven-metadata.xml"); + + assertFalse(imported); + verify(service, never()).mergeMavenMetadataUnderPackageFence(any(), any(), any(), any(), any(), any(), + anyLong(), any(), any(), any(), any()); + } + + @Test + void doesNothingForAMavenMetadataChecksumSiblingPath() { + boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, + "com/example/widget/maven-metadata.xml.sha1"); + + assertFalse(imported); + verify(externalConnectionClient, never()).fetchAsset(anyString(), anyString()); + } + + @Test + void doesNothingForMavenMetadataWhenTheRepositoryHasNoMavenExternalConnection() { + when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(new CodeArtifactRepository()); + + 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 doesNothingForMavenMetadataWhenUpstreamRetentionIsBlocked() { + 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/maven-metadata.xml"); 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 75ddc73871..67e1b9cfd7 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 @@ -398,6 +398,8 @@ class CodeArtifactServiceTest { service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("removed"))) .thenReturn(true); + when(reposiliteClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), eq("com.example"), + eq("removed"))).thenReturn(true); recordBytes("dom", "repo", "maven", "com.example", "kept", 40L); recordBytes("dom", "repo", "maven", "com.example", "removed", 60L); assertEquals(100L, service.describeDomain(REGION, "dom", null).assetSizeBytes()); @@ -495,6 +497,8 @@ class CodeArtifactServiceTest { "late"); when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("late"))) .thenReturn(true); + when(reposiliteClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), eq("com.example"), + eq("late"))).thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "late"); service.recordContainerBackedAssetBytes(REGION, "dom", null, "repo", "maven", "com.example", "late", 999L, @@ -517,6 +521,8 @@ class CodeArtifactServiceTest { "late"); when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("late"))) .thenReturn(true); + when(reposiliteClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), eq("com.example"), + eq("late"))).thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "late"); // The republish: a different publish, same coordinates, after the first one's snapshot. recordBytes("dom", "repo", "maven", "com.example", "late", 10L); @@ -562,6 +568,8 @@ class CodeArtifactServiceTest { assertEquals(42L, service.describeDomain(REGION, "dom", null).assetSizeBytes()); when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my_package"))) .thenReturn(true); + when(pypiserverClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("my_package"))) + .thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my_package"); @@ -582,6 +590,8 @@ class CodeArtifactServiceTest { assertEquals(42L, service.describeDomain(REGION, "dom", null).assetSizeBytes()); when(bagetterClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my.package"))) .thenReturn(true); + when(bagetterClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("my.package"))) + .thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "nuget", null, "my.package"); @@ -2107,6 +2117,8 @@ class CodeArtifactServiceTest { // 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); + when(reposiliteClient.hasAnyContentToDelete(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. @@ -2290,38 +2302,38 @@ class CodeArtifactServiceTest { } /** - * 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. + * A failed attempt (nothing imported) releases its own claim through {@link + * CodeArtifactService#finishMavenRetainedVersionOriginAttempt} without touching either fence + * at all, so a fresh claim made afterward under a different connection leaves both fences + * exactly as they were. A very late, straggling write from the attempt that already reported + * itself finished (its own real network write's retry or duplicate, arriving well after its + * finish call already ran) would otherwise still see both fences match and write real bytes + * under whatever connection claimed the version next, mixing assets from two different public + * sources into one version; only the episode check catches this, since neither fence ever + * moved. {@link #deployMavenAssetUnderVersionFenceRefusesAStaleEpisodeAfterAnEmptyPackageDeleteAndFreshClaim}'s + * delete-based scenario now also gets caught by the package fence itself, since {@link + * CodeArtifactService#deletePackage} bumps it on an origin-config-only delete too; this + * scenario has no delete in it at all, so it keeps the episode check genuinely necessary. */ @Test - void deployMavenAssetUnderVersionFenceRefusesAStaleEpisodeAfterAnEmptyPackageDeleteAndFreshClaim() { + void deployMavenAssetUnderVersionFenceRefusesAStaleEpisodeAfterAFailedAttemptReleasesItAndAFreshClaimFollows() { 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). + // until after it finishes empty-handed and a fresh claim follows below (simulating a + // fetch still in flight for a real network write that arrives only after that). long staleEpisodeId = service.claimMavenRetainedVersionOrigin(REGION, "dom", null, "repo", "com.example", "widget", "1.0", "public:maven-central", packageFence).episodeId(); - // 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"); + // Finds nothing from the public repository: releases its own claim, touching neither fence. + service.finishMavenRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "com.example", "widget", "1.0", + staleEpisodeId, false); assertEquals(packageFence, service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example", "widget")); @@ -2329,9 +2341,9 @@ class CodeArtifactServiceTest { 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. + // The stalled attempt's own late write finally arrives and tries to write under its own + // stale episode: both fences still match (neither was ever bumped), so only the episode + // 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, @@ -2341,6 +2353,118 @@ class CodeArtifactServiceTest { verify(reposiliteClient, never()).deployArtifact(anyString(), anyString(), any()); } + /** + * {@link CodeArtifactService#mergeMavenMetadataUnderPackageFence}'s own version of the same + * race {@link #deployMavenAssetUnderVersionFenceWritesNothingWhenTheVersionFenceHasMoved} + * covers for a per-version write: a {@code DeletePackage} that finishes while the real, + * public-repository metadata fetch is still in flight must bump the package fence behind the + * snapshot the importer took before that fetch, so the merge that follows never lands. + */ + @Test + void mergeMavenMetadataUnderPackageFenceWritesNothingWhenThePackageFenceHasMoved() { + 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 packageFenceSnapshot = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + // The DeletePackage that lands while the importer's own real fetch is still in flight, + // simulated here the same way as every other fence test in this class. + when(reposiliteClient.hasAnyContentToDelete(repoId, "dom", "repo", "com.example", "widget")) + .thenReturn(true); + service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget"); + + boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", + "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( + StandardCharsets.UTF_8), v -> true); + + assertFalse(merged); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any()); + } + + @Test + void mergeMavenMetadataUnderPackageFenceDelegatesToReposiliteWhenTheFenceStillMatches() { + 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 packageFenceSnapshot = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + byte[] metadataBytes = "".getBytes(StandardCharsets.UTF_8); + when(reposiliteClient.mergeExternalConnectionReleaseVersions(eq(repoId), eq("com.example"), eq("widget"), + eq(metadataBytes), any())).thenReturn(true); + + boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", + "widget", packageFenceSnapshot, reposiliteClient, repoId, metadataBytes, v -> true); + + assertTrue(merged); + verify(reposiliteClient).mergeExternalConnectionReleaseVersions(eq(repoId), eq("com.example"), eq("widget"), + eq(metadataBytes), any()); + } + + /** + * Raised by Greptile's review: an origin-config-only package (a {@code + * PutPackageOriginConfiguration} with no version ever actually published or retained) used to + * leave the package fence untouched on delete, since {@link + * CodeArtifactMavenExternalConnectionImporterTest} and {@link + * #mergeMavenMetadataUnderPackageFenceWritesNothingWhenThePackageFenceHasMoved} only ever cover + * a delete that found real content. A {@code DeletePackage} racing a metadata fetch still in + * flight for exactly that kind of package would otherwise leave the fence matching, letting the + * merge land afterward and resurrect a package {@code DeletePackage} had already told its + * caller was gone. See {@link CodeArtifactService#deletePackage}'s own javadoc for the fix. + */ + @Test + void mergeMavenMetadataUnderPackageFenceWritesNothingAfterAnOriginConfigOnlyPackageIsDeleted() { + 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"); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget", + "ALLOW", "ALLOW"); + long packageFenceSnapshot = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + // No real content exists for this package, only the origin configuration above, the same + // way the importer's own metadata fetch found nothing to retain yet either. + when(reposiliteClient.hasAnyContentToDelete(repoId, "dom", "repo", "com.example", "widget")) + .thenReturn(false); + + service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "widget"); + + boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", + "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( + StandardCharsets.UTF_8), v -> true); + + assertFalse(merged); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), any()); + } + + /** + * Raised by Greptile's review: the package fence alone says nothing about {@link + * CodeArtifactService#deleteRepository} removing the whole repository, not just one package, + * while the same metadata fetch is in flight; {@code deleteRepository} never touches any + * individual package's fence, so the snapshot still matches even though the repository itself + * is gone. Without a separate check, the sidecar merge's own {@code ensureRepository} would + * transparently recreate the repository {@code deleteRepository} had just torn down. + */ + @Test + void mergeMavenMetadataUnderPackageFenceWritesNothingAfterTheRepositoryItselfIsDeleted() { + 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 packageFenceSnapshot = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", + "com.example", "widget"); + + service.deleteRepository(REGION, "dom", null, "repo"); + + boolean merged = service.mergeMavenMetadataUnderPackageFence(REGION, "dom", null, "repo", "com.example", + "widget", packageFenceSnapshot, reposiliteClient, repoId, "".getBytes( + StandardCharsets.UTF_8), v -> true); + + assertFalse(merged); + verify(reposiliteClient, never()).mergeExternalConnectionReleaseVersions(any(), any(), any(), any(), 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 @@ -2564,6 +2688,8 @@ class CodeArtifactServiceTest { String repoId = created.getSidecarContainerIds().get("maven"); when(reposiliteClient.packageExists(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), eq("my-artifact"))).thenReturn(true); + when(reposiliteClient.hasAnyContentToDelete(eq(repoId), eq("dom"), eq("repo"), eq("com.example"), + eq("my-artifact"))).thenReturn(true); CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "my-artifact"); @@ -2599,6 +2725,8 @@ class CodeArtifactServiceTest { service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"))) .thenReturn(true); + when(pypiserverClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"))) + .thenReturn(true); doThrow(new UnsupportedOperationException("pypi packages cannot be deleted through this sidecar")) .when(pypiserverClient).deletePackage(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg")); @@ -6243,6 +6371,8 @@ class CodeArtifactServiceTest { recordReadme("dom", "repo", "pypi", null, "my-pkg", "1.0.0", "old text"); when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"))) .thenReturn(true); + when(pypiserverClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-pkg"))) + .thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my-pkg"); @@ -6307,6 +6437,8 @@ class CodeArtifactServiceTest { long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", null, "late"); when(verdaccioClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("late"))) .thenReturn(true); + when(verdaccioClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("late"))) + .thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "npm", null, "late"); service.recordPublishedPackageVersionReadme(REGION, "dom", null, "repo", "npm", null, "late", "1.0.0", @@ -6345,6 +6477,8 @@ class CodeArtifactServiceTest { recordReadme("dom", "repo", "pypi", null, "My.Package", "1.0.0", "the readme"); when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-package"))) .thenReturn(true); + when(pypiserverClient.hasAnyContentToDelete(anyString(), eq("dom"), eq("repo"), isNull(), eq("my-package"))) + .thenReturn(true); service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my-package"); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java index 5c2874e9af..f8f8bfb6f1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java @@ -574,17 +574,30 @@ class ReposiliteSidecarClientTest { } @Test - void packageExistsReflectsAGetResponseOnTheGroupArtifactDirectory() { - server.createContext("/dom--repo/com/example/present/", exchange -> respond(exchange, 200, "")); - server.createContext("/dom--repo/com/example/absent/", exchange -> respond(exchange, 404, "")); + void packageExistsReflectsWhetherTheGroupArtifactDirectoryHasAVersionSubdirectory() { + server.createContext("/api/maven/details/dom--repo/com/example/present/", + exchange -> respond(exchange, 200, "{\"files\":[" + + "{\"name\":\"1.0\",\"type\":\"DIRECTORY\"}]}")); + server.createContext("/api/maven/details/dom--repo/com/example/absent/", exchange -> respond(exchange, 404, + "{\"status\":404,\"message\":\"File not found\"}")); assertTrue(client.packageExists("dom--repo", "dom", "repo", "com.example", "present")); assertFalse(client.packageExists("dom--repo", "dom", "repo", "com.example", "absent")); } + @Test + void packageExistsIsFalseForAGroupArtifactDirectoryThatHasOnlyAMergedMetadataFileAndNoRealVersion() { + server.createContext("/api/maven/details/dom--repo/com/example/metadata-only/", + exchange -> respond(exchange, 200, "{\"files\":[" + + "{\"name\":\"maven-metadata.xml\",\"type\":\"FILE\"}]}")); + + assertFalse(client.packageExists("dom--repo", "dom", "repo", "com.example", "metadata-only")); + } + @Test void packageExistsThrowsRatherThanReportingAbsentOnASidecarServerError() { - server.createContext("/dom--repo/com/example/broken/", exchange -> respond(exchange, 500, "")); + server.createContext("/api/maven/details/dom--repo/com/example/broken/", exchange -> respond(exchange, 500, + "{\"status\":500,\"message\":\"internal error\"}")); assertThrows(IllegalStateException.class, () -> client.packageExists("dom--repo", "dom", "repo", "com.example", "broken")); @@ -788,6 +801,273 @@ class ReposiliteSidecarClientTest { assertEquals("1.0", XmlParser.extractFirst(xml, "release", null)); } + @Test + void mergeExternalConnectionReleaseVersionsCreatesMetadataFromTheExternalSourceWhenNoneExistsLocally() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 404, ""); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.21.21.0" + + "1.11.2"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertTrue(merged); + String xml = new String(putBody.get(), StandardCharsets.UTF_8); + assertEquals("com.example", XmlParser.extractFirst(xml, "groupId", null)); + assertEquals("a", XmlParser.extractFirst(xml, "artifactId", null)); + assertEquals("1.2", XmlParser.extractFirst(xml, "latest", null)); + assertEquals("1.2", XmlParser.extractFirst(xml, "release", null)); + assertEquals(List.of("1.0", "1.1", "1.2"), XmlParser.extractAll(xml, "version")); + } + + @Test + void mergeExternalConnectionReleaseVersionsWritesMatchingSha1AndMd5Checksums() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + AtomicReference sha1Body = new AtomicReference<>(); + AtomicReference md5Body = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 404, ""); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + server.createContext(metadataPath + ".sha1", exchange -> { + sha1Body.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + }); + server.createContext(metadataPath + ".md5", exchange -> { + md5Body.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + }); + String externalXml = "com.examplea" + + "1.01.01.0" + + ""; + + client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertEquals(Digests.sha1Hex(putBody.get()), new String(sha1Body.get(), StandardCharsets.UTF_8)); + assertEquals(Digests.md5Hex(putBody.get()), new String(md5Body.get(), StandardCharsets.UTF_8)); + } + + @Test + void mergeExternalConnectionReleaseVersionsExcludesAVersionTheVersionAllowedPredicateRejects() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 404, ""); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.11.11.0" + + "1.1"; + + // Simulates a version this repository already knows is Disposed: a public repository's + // own metadata has no idea that happened, so a merge must never let a rejected version + // back in just because the public source still lists it. + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> !v.equals("1.1")); + + assertTrue(merged); + String xml = new String(putBody.get(), StandardCharsets.UTF_8); + assertEquals(List.of("1.0"), XmlParser.extractAll(xml, "version")); + assertEquals("1.0", XmlParser.extractFirst(xml, "latest", null)); + assertEquals("1.0", XmlParser.extractFirst(xml, "release", null)); + } + + /** + * {@link io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient#fetchArtifact} + * returns {@code empty()} for a transient server error too, not just a confirmed 404: a merge + * that read the existing local metadata through that method could mistake the error for "no + * local metadata yet" and silently replace a real, locally-published package's {@code latest}/ + * {@code release} with the external source's own guess at them. The merge must surface the + * failure instead. + */ + @Test + void mergeExternalConnectionReleaseVersionsThrowsOnATransientReadErrorInsteadOfTreatingItAsMissing() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + server.createContext("/dom--repo/com/example/a/maven-metadata.xml", exchange -> respond(exchange, 500, "")); + String externalXml = "com.examplea" + + "1.01.01.0" + + ""; + + assertThrows(IllegalStateException.class, () -> client.mergeExternalConnectionReleaseVersions("dom--repo", + "com.example", "a", externalXml.getBytes(StandardCharsets.UTF_8), v -> true)); + } + + /** + * A locally-published version has no reliable way to be compared against whatever the public + * repository's own metadata declares as its latest/release (Maven version strings don't sort + * by any universal rule), so a merge must only ever add the versions the local copy doesn't + * already have, never move {@code latest}/{@code release} away from what a real local publish + * already recorded. + */ + @Test + void mergeExternalConnectionReleaseVersionsAppendsMissingVersionsWithoutOverridingAnExistingLocalLatest() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String existing = "com.examplea" + + "2.02.02.0" + + "20260101000000"; + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 200, existing); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.11.11.0" + + "1.1"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertTrue(merged); + String xml = new String(putBody.get(), StandardCharsets.UTF_8); + assertEquals(List.of("2.0", "1.0", "1.1"), XmlParser.extractAll(xml, "version")); + assertEquals("2.0", XmlParser.extractFirst(xml, "latest", null)); + assertEquals("2.0", XmlParser.extractFirst(xml, "release", null)); + } + + @Test + void mergeExternalConnectionReleaseVersionsFiltersOutSnapshotVersionsFromTheExternalSource() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 404, ""); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.1-SNAPSHOT1.0" + + "1.1-SNAPSHOT"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertTrue(merged); + String xml = new String(putBody.get(), StandardCharsets.UTF_8); + assertEquals(List.of("1.0"), XmlParser.extractAll(xml, "version")); + assertEquals("1.0", XmlParser.extractFirst(xml, "latest", null)); + } + + @Test + void mergeExternalConnectionReleaseVersionsIsANoOpWhenEveryExternalVersionIsAlreadyListedLocally() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String existing = "com.examplea" + + "1.01.01.0" + + "20260101000000"; + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference putBody = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 200, existing); + } else if (metadataPath.equals(exchange.getRequestURI().getPath())) { + putBody.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + } else { + respond(exchange, 200, ""); + } + }); + String externalXml = "com.examplea" + + "1.01.01.0"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertFalse(merged); + assertNull(putBody.get()); + } + + /** + * Raised by Greptile's review: a prior attempt whose metadata write succeeded but whose + * checksum write then failed would otherwise leave a stale checksum in place forever, since + * every later request for this exact package also finds nothing new to add and takes this + * same no-op path. The repair must happen every time this path is taken, not just once. + */ + @Test + void mergeExternalConnectionReleaseVersionsRepairsChecksumsEvenWhenItIsANoOp() { + settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}"); + server.createContext("/api/settings/domain/maven", exchange -> respond(exchange, 200, settingsBody.get())); + String existing = "com.examplea" + + "1.01.01.0" + + "20260101000000"; + String metadataPath = "/dom--repo/com/example/a/maven-metadata.xml"; + AtomicReference sha1Body = new AtomicReference<>(); + AtomicReference md5Body = new AtomicReference<>(); + server.createContext(metadataPath, exchange -> { + if ("GET".equals(exchange.getRequestMethod())) { + respond(exchange, 200, existing); + } else { + respond(exchange, 200, ""); + } + }); + server.createContext(metadataPath + ".sha1", exchange -> { + sha1Body.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + }); + server.createContext(metadataPath + ".md5", exchange -> { + md5Body.set(exchange.getRequestBody().readAllBytes()); + respond(exchange, 200, ""); + }); + String externalXml = "com.examplea" + + "1.01.01.0"; + + boolean merged = client.mergeExternalConnectionReleaseVersions("dom--repo", "com.example", "a", + externalXml.getBytes(StandardCharsets.UTF_8), v -> true); + + assertFalse(merged); + assertEquals(Digests.sha1Hex(existing.getBytes(StandardCharsets.UTF_8)), + new String(sha1Body.get(), StandardCharsets.UTF_8)); + assertEquals(Digests.md5Hex(existing.getBytes(StandardCharsets.UTF_8)), + new String(md5Body.get(), StandardCharsets.UTF_8)); + } + /** * {@link io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient#recordVersionDisposed}'s * dispose-time counterpart to {@link #recordVersionAvailableAppendsToExistingVersionsAndAdvancesReleaseForANonSnapshot}: