mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(codeartifact): retain NuGet packages from a public external connection (#7104)
NuGet's native v3/package route can now retain a missing package version
from a repository's own public:nuget-org external connection and serve
it, instead of always 404ing, matching AWS's documented external-
connection behavior already shipped for Maven.
- A version's retention origin is claimed atomically before any fetch
happens, rejecting a later attempt under a different connection
outright ("checking asset origins").
- Package-level upstream: BLOCK is respected, including when the
restriction and the request spell the package name differently
(nuget/pypi names are case/punctuation normalized everywhere this
service tracks a package; PackageOriginConfig now keys by that same
normalization too, instead of the caller's raw spelling).
- A retained version reports originType: EXTERNAL and its source
connection through DescribePackageVersion/ListPackageVersions, for
any format that retains (not just Maven).
- A concurrent retention attempt racing a real client's own direct
push is never mislabeled as an external import: existence in the
real sidecar alone no longer implies success, only a confirmed claim
under the exact same connection does.
- Retained bytes are counted toward DescribeDomain's assetSizeBytes,
never double-counted on a concurrent retry.
- A real HTTP redirect from the public repository is followed instead
of being treated as a 404.
- Fixed-version retention only; resolving a floating/omitted version by
merging in nuget.org's own version listing is left for a follow-up,
the same baseline scope Maven's own external-connection work shipped
first.
New: NuGetExternalConnectionClient (the outbound client for
public:nuget-org) and CodeArtifactNuGetExternalConnectionImporter (the
retention decision logic), wired into CodeArtifactNuGetController.
The claim/fence/deploy machinery CodeArtifactService already used for
Maven's own external-connection retention is generalized into
format-parameterized methods so npm and pypi can reuse it too, with
Maven's own public methods kept as thin, behavior-identical delegates
over the generic ones.
This commit is contained in:
1 parent
2b6a8b4e66
commit
300e62a0ed
8 files changed
+1239
-132
No files matched your search
+17
-3
@@ -65,16 +65,21 @@ public class CodeArtifactNuGetController {
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final BagetterSidecarClient bagetter;
|
||||
private final CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter) {
|
||||
this(service, bagetter, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
public CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter,
|
||||
CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter) {
|
||||
this(service, bagetter, externalConnectionImporter,
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
}
|
||||
|
||||
CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter, HttpClient httpClient) {
|
||||
CodeArtifactNuGetController(CodeArtifactService service, BagetterSidecarClient bagetter,
|
||||
CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter, HttpClient httpClient) {
|
||||
this.service = service;
|
||||
this.bagetter = bagetter;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@@ -150,6 +155,15 @@ public class CodeArtifactNuGetController {
|
||||
+ lowerId + ".nuspec", "text/xml");
|
||||
}
|
||||
if (lowerFilename.endsWith(".nupkg")) {
|
||||
// A cache miss on this emulator's own BaGetter is exactly the trigger AWS's own docs
|
||||
// describe for an external connection: fetch the real asset from the public repository
|
||||
// and retain it, then let the proxy below find it there, the same as any other
|
||||
// request. Not attempted at all when BaGetter already has it: the only extra cost on
|
||||
// every other request is this one cheap local existence check.
|
||||
if (!bagetter.packageVersionExists(handle.repoId(), domain, repository, null, id, version)) {
|
||||
externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), id, version);
|
||||
}
|
||||
return proxyGet(baseUrl, "/v3/package/" + lowerId + "/" + encodedVersion + "/"
|
||||
+ lowerId + "." + SidecarUriUtils.encodeSegment(version.toLowerCase(Locale.ROOT)) + ".nupkg",
|
||||
MediaType.APPLICATION_OCTET_STREAM);
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
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.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Retains a NuGet package version from the real public repository a repository's {@code
|
||||
* public:nuget-org} external connection names, the way real CodeArtifact does when a {@code
|
||||
* nuget}/{@code dotnet} client requests a package version that is not present locally yet.
|
||||
* Confirmed against the User Guide's own "Connect a CodeArtifact repository to a public
|
||||
* repository" section, not inferred:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Exactly one public connection, one asset per version.</b> AWS names {@code
|
||||
* public:nuget-org} as NuGet's only public connection, and states NuGet packages "only have
|
||||
* one asset per package version", unlike Maven's standard-sibling-asset bundle: the real {@code
|
||||
* .nupkg} itself is the only thing this ever imports.</li>
|
||||
* <li><b>No release-only restriction.</b> Unlike Maven's own external connections, AWS's docs
|
||||
* name no equivalent carve-out for NuGet prerelease versions, so every version this emulator is
|
||||
* asked for is eligible, prerelease included.</li>
|
||||
* <li><b>Checking asset origins.</b> A package version's retention origin, once confirmed,
|
||||
* never changes (see {@link CodeArtifactService#claimRetainedVersionOrigin}'s own javadoc,
|
||||
* generalized from Maven's own first use of this mechanism); an import attempt under a
|
||||
* different connection than what is already claimed for that exact version is refused
|
||||
* outright, and the claim stays reserved for as long as any concurrent attempt under the
|
||||
* original connection is still in flight.</li>
|
||||
* <li><b>Coordinated with this emulator's own deletion and disposal.</b> The real write, via
|
||||
* {@link CodeArtifactService#retainAssetUnderVersionFence}, happens inside the exact same lock
|
||||
* {@code DeletePackageVersions}/{@code DeletePackage}/{@code DeleteRepository}/{@code
|
||||
* DisposePackageVersions} already hold for their entire duration, so the two can never
|
||||
* interleave.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Deliberately not modeled here, matching {@code CodeArtifactMavenExternalConnectionImporter}'s
|
||||
* own documented scope: resolving a floating/omitted version by merging in the public
|
||||
* repository's own version listing ({@code v3/package/{id}/index.json}). A client must request
|
||||
* this exact, fixed version for retention to trigger, the same baseline scope Maven's own first
|
||||
* external-connection work shipped before its own later metadata-merge follow-up.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactNuGetExternalConnectionImporter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactNuGetExternalConnectionImporter.class);
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final BagetterSidecarClient bagetter;
|
||||
private final NuGetExternalConnectionClient externalConnectionClient;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactNuGetExternalConnectionImporter(CodeArtifactService service, BagetterSidecarClient bagetter,
|
||||
NuGetExternalConnectionClient externalConnectionClient) {
|
||||
this.service = service;
|
||||
this.bagetter = bagetter;
|
||||
this.externalConnectionClient = externalConnectionClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retain {@code packageId}/{@code version}'s one real asset into {@code repoId}
|
||||
* from {@code repository}'s own nuget external connection. Returns {@code true} only when the
|
||||
* asset is genuinely present under this connection's claim by the time this returns, whether
|
||||
* because this attempt imported it or a concurrent one already had: 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, 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 packageId, String version) {
|
||||
String externalConnectionName = nugetExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "nuget", null, packageId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Snapshotted before the claim and the real write below, not after, the same ordering
|
||||
// CodeArtifactMavenExternalConnectionImporter#tryImport 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 packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"nuget", null, packageId);
|
||||
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
|
||||
"nuget", null, packageId, version);
|
||||
// Claims the version's origin atomically, before any network fetch happens at all: see
|
||||
// claimRetainedVersionOrigin's own javadoc for the race this closes.
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
|
||||
domain, owner, repository, "nuget", null, packageId, version, externalConnectionName,
|
||||
packageFenceSnapshot);
|
||||
if (!claim.claimed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean imported = false;
|
||||
try {
|
||||
// BaGetter may already have these exact bytes by the time this attempt gets here, via
|
||||
// a concurrent attempt under this exact same claim episode (see
|
||||
// claimRetainedVersionOrigin's own javadoc on inFlightAttempts), or via a real client's
|
||||
// own direct push landing in the gap between this attempt's own claim above and this
|
||||
// check. Only the former genuinely proves this version arrived through
|
||||
// externalConnectionName (found by Greptile's review): existence alone does not, and
|
||||
// treating a direct push as "a sibling import already retained it" would wrongly mark
|
||||
// it EXTERNAL and overwrite its origin defaults in the finally block below. If this
|
||||
// isn't confirmed under this exact connection, the real write attempt further down
|
||||
// safely absorbs BaGetter's own AllowPackageOverwrites: false rejection (unlike
|
||||
// Reposilite's idempotent PUT) rather than this method ever assuming success from
|
||||
// existence alone.
|
||||
if (bagetter.packageVersionExists(repoId, domain, repository, null, packageId, version)) {
|
||||
imported = service.retainedVersionOriginConnection(region, domain, owner, repository, "nuget", null,
|
||||
packageId, version).filter(externalConnectionName::equals).isPresent();
|
||||
return imported;
|
||||
}
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> fetched;
|
||||
try {
|
||||
fetched = externalConnectionClient.fetchPackage(externalConnectionName, packageId, version);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not fetch {0} {1} from {2} while retaining a NuGet package through an "
|
||||
+ "external connection.", packageId, version, externalConnectionName);
|
||||
return false;
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
byte[] content = fetched.get().content();
|
||||
String assetName = packageId.toLowerCase(Locale.ROOT) + "." + version.toLowerCase(Locale.ROOT)
|
||||
+ ".nupkg";
|
||||
// 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. See retainAssetUnderVersionFence's own javadoc for
|
||||
// why this has to be a method on the service itself rather than a block synchronized on
|
||||
// an 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.
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
|
||||
domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot,
|
||||
packageFenceSnapshot, claim.episodeId(), bagetter, repoId, assetName, content);
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
return imported;
|
||||
} finally {
|
||||
// Finalized here, not just after a clean return, so an unexpected exception still lets
|
||||
// this bookkeeping run instead of leaving the claim held (or released) without ever
|
||||
// recording what this attempt actually wrote.
|
||||
if (imported) {
|
||||
service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "nuget", null,
|
||||
packageId, packageFenceSnapshot);
|
||||
}
|
||||
// Matches the claim taken above, exactly once, regardless of what this attempt actually
|
||||
// wrote: see finishRetainedVersionOriginAttempt's own javadoc for why this must run even
|
||||
// when imported is true, not only to release an empty claim.
|
||||
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "nuget", null, packageId,
|
||||
version, claim.episodeId(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
private String nugetExternalConnectionName(String region, String domain, String owner, String repository) {
|
||||
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
|
||||
.filter(ec -> "nuget".equals(ec.getPackageFormat()))
|
||||
.map(ExternalConnection::getExternalConnectionName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
+274
-129
@@ -273,17 +273,18 @@ 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.
|
||||
// Which public:* external connection a container-backed package version was first retained
|
||||
// from, keyed like packageVersionKey (so Maven, npm, pypi, and nuget claims never collide:
|
||||
// format is already part of the key). Claimed atomically, once per version (see
|
||||
// #claimRetainedVersionOrigin'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
|
||||
// retained bytes live in the sidecar 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.
|
||||
//
|
||||
@@ -292,9 +293,9 @@ public class CodeArtifactService implements Resettable {
|
||||
// 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
|
||||
// content (see RetainedVersionOriginClaim'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 =
|
||||
private final ConcurrentHashMap<String, RetainedVersionOriginClaim> retainedVersionOriginConnections =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
// inFlightAttempts alone only protects one claim episode against its own sibling attempts.
|
||||
@@ -305,15 +306,15 @@ public class CodeArtifactService implements Resettable {
|
||||
// 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();
|
||||
private final AtomicLong retainedVersionOriginEpisodeCounter = new AtomicLong();
|
||||
|
||||
/**
|
||||
* One version's current claim on {@code externalConnectionName}, tagged with {@code
|
||||
* episodeId}: {@code inFlightAttempts} counts how many calls into {@link
|
||||
* #claimMavenRetainedVersionOrigin} for this exact version and episode have not yet reached
|
||||
* their own matching {@link #finishMavenRetainedVersionOriginAttempt} call, and {@code
|
||||
* #claimRetainedVersionOrigin} for this exact version and episode have not yet reached
|
||||
* their own matching {@link #finishRetainedVersionOriginAttempt} call, and {@code
|
||||
* confirmed} is {@code true} once any one of them actually wrote real content under this
|
||||
* claim. A claim is only ever removed by {@link #finishMavenRetainedVersionOriginAttempt}
|
||||
* claim. A claim is only ever removed by {@link #finishRetainedVersionOriginAttempt}
|
||||
* 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
|
||||
@@ -322,7 +323,7 @@ public class CodeArtifactService implements Resettable {
|
||||
* 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,
|
||||
private record RetainedVersionOriginClaim(String externalConnectionName, int inFlightAttempts,
|
||||
boolean confirmed, long episodeId) {
|
||||
}
|
||||
|
||||
@@ -630,14 +631,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()
|
||||
// Same reasoning, same prefix: a 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.
|
||||
retainedVersionOriginConnections.keySet().stream()
|
||||
.filter(k -> k.startsWith(ownerScopedOriginPrefix))
|
||||
.toList()
|
||||
.forEach(mavenRetainedVersionOriginConnections::remove);
|
||||
.forEach(retainedVersionOriginConnections::remove);
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -898,8 +899,12 @@ public class CodeArtifactService implements Resettable {
|
||||
// operation before any idempotency check below, the same way a real prerequisite failure
|
||||
// would: a retry of already-published bytes is still a PublishPackageVersion call, and
|
||||
// AWS's own documented behavior ("version 1.2 cannot be published" once Publish is set to
|
||||
// Block) draws no bytes-already-match exception to it.
|
||||
String originKey = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
// Block) draws no bytes-already-match exception to it. accountingPackageName, not the raw
|
||||
// packageName, so this sees the same config PutPackageOriginConfiguration/
|
||||
// isUpstreamRetentionBlocked now key by for a format (nuget, pypi) whose names are
|
||||
// case/punctuation normalized.
|
||||
String originKey = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName));
|
||||
String publishRestriction = packageOriginConfigs.getForAccount(owner, originKey)
|
||||
.map(PackageOriginConfig::getPublishRestriction)
|
||||
.orElse("ALLOW");
|
||||
@@ -1179,7 +1184,8 @@ public class CodeArtifactService implements Resettable {
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
requireRepository(owner, repositoryKey(region, domain, repository), repository);
|
||||
|
||||
String originKey = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
String originKey = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName));
|
||||
boolean hasOriginConfig = packageOriginConfigs.getForAccount(owner, originKey).isPresent();
|
||||
List<PackageVersionEntry> entries;
|
||||
String preferredDisplayVersion = null;
|
||||
@@ -1658,10 +1664,17 @@ 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));
|
||||
// Harmless no-op for a format that has never retained anything: a container-backed
|
||||
// version deleted and republished under the same coordinates must not inherit its
|
||||
// previous claimed retention origin. matchVersion, not readmeKey's own raw version
|
||||
// (found by Greptile's review): retainedVersionOriginConnection's own claim is keyed
|
||||
// by normalizedContainerBackedVersion, so deleting a nuget version spelled
|
||||
// differently than the one it was imported under (AWS's own worked example, 1.00
|
||||
// against 1.0.0) would otherwise remove the asset bytes but leave the claim behind,
|
||||
// and a later direct push of the same real version would still read back as EXTERNAL.
|
||||
String claimKey = packageVersionKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName), matchVersion);
|
||||
retainedVersionOriginConnections.remove(ownerScopedKey(owner, claimKey));
|
||||
// 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
|
||||
@@ -2493,13 +2506,14 @@ public class CodeArtifactService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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.
|
||||
* {@code EXTERNAL} for a version this service's own records show was genuinely retained from
|
||||
* an external connection (Maven, npm, pypi, or nuget alike, see {@link
|
||||
* #retainedVersionOriginConnection}), {@code INTERNAL} for one created 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) {
|
||||
@@ -2508,20 +2522,17 @@ public class CodeArtifactService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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.
|
||||
* {@code originType} plus, for an {@code EXTERNAL} version, the exact external connection it
|
||||
* was retained from: AWS's own {@code DomainEntryPoint} reference describes an ingested
|
||||
* package's entry point as the external connection it came from, {@code repositoryName} only
|
||||
* for one published directly, so a caller surfacing a domain entry point needs the connection
|
||||
* name itself, not just the originType flag.
|
||||
*/
|
||||
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,
|
||||
return retainedVersionOriginConnection(region, domain, owner, repository, format, namespace, packageName,
|
||||
version).map(name -> new VersionOrigin("EXTERNAL", name)).orElse(new VersionOrigin("INTERNAL", null));
|
||||
}
|
||||
|
||||
@@ -2746,7 +2757,8 @@ public class CodeArtifactService implements Resettable {
|
||||
requireNonBlank(repository, "repository");
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
requireRepository(owner, repositoryKey(region, domain, repository), repository);
|
||||
String originKey = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
String originKey = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName));
|
||||
Optional<PackageOriginConfig> originConfig = packageOriginConfigs.getForAccount(owner, originKey);
|
||||
// PutPackageOriginConfiguration can be called on a package with no versions yet, creating
|
||||
// it with no versions (its own documented behavior): a stored config, even with zero
|
||||
@@ -2796,7 +2808,13 @@ public class CodeArtifactService implements Resettable {
|
||||
requireNonBlank(repository, "repository");
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
requireRepository(owner, repositoryKey(region, domain, repository), repository);
|
||||
String key = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
// accountingPackageName, not the raw packageName: nuget/pypi names are case/punctuation
|
||||
// normalized everywhere else this service tracks a package (see that method's own
|
||||
// javadoc), and every other packageOriginConfigs reader (isUpstreamRetentionBlocked,
|
||||
// describePackage, deletePackage, publishPackageVersion's own BLOCK check) now keys by the
|
||||
// same normalized spelling, so a restriction set under one casing is found under any other.
|
||||
String key = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName));
|
||||
packageOriginConfigs.putForAccount(owner, key, new PackageOriginConfig(publishRestriction,
|
||||
upstreamRestriction, format, namespace, packageName));
|
||||
return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction);
|
||||
@@ -2817,29 +2835,35 @@ public class CodeArtifactService implements Resettable {
|
||||
* 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
|
||||
* <p>A standard container-backed 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.
|
||||
* in-between state as a directly-published package and get wrongly refused. An in-flight or
|
||||
* confirmed retention claim already existing for <em>any</em> version of this exact package
|
||||
* (see {@link #claimRetainedVersionOrigin}) 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);
|
||||
// accountingPackageName, not the raw packageName (found by Greptile's review): a nuget
|
||||
// client's own native route always lowercases the id, while an operator setting
|
||||
// PutPackageOriginConfiguration through the management API may well type it in its
|
||||
// original display casing; without this, upstream: BLOCK set one way would silently never
|
||||
// match a request spelled the other.
|
||||
String key = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, 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)) {
|
||||
if (hasRetainedVersionOriginClaimForAnyVersion(region, domain, owner, repository, format, namespace,
|
||||
packageName)) {
|
||||
return false;
|
||||
}
|
||||
return packageExistsViaVersionsOrSidecar(region, domain, owner, repository, format, namespace, packageName);
|
||||
@@ -2847,16 +2871,16 @@ public class CodeArtifactService implements Resettable {
|
||||
|
||||
/**
|
||||
* Whether any version of {@code packageName}, under any connection, currently has or has ever
|
||||
* had an entry in {@link #mavenRetainedVersionOriginConnections}: {@code true} for an
|
||||
* had an entry in {@link #retainedVersionOriginConnections}: {@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));
|
||||
private boolean hasRetainedVersionOriginClaimForAnyVersion(String region, String domain, String owner,
|
||||
String repository, String format, String namespace, String packageName) {
|
||||
String prefix = ownerScopedKey(owner, packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName))) + "::";
|
||||
return retainedVersionOriginConnections.keySet().stream().anyMatch(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2886,7 +2910,13 @@ public class CodeArtifactService implements Resettable {
|
||||
if (repositories.getForAccount(owner, repositoryKey(region, domain, repository)).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String key = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
// accountingPackageName, not the raw packageName: currentContainerBackedPackageFence
|
||||
// (which produced packageFenceSnapshot, see this method's own caller) and deletePackage's
|
||||
// own fence bump both key by the normalized spelling already; without this, this fence
|
||||
// check here could compare against the wrong entry entirely for a caller that ever passed
|
||||
// this a non-normalized nuget/pypi name, silently skipping the default write below.
|
||||
String key = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, 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
|
||||
@@ -2909,18 +2939,31 @@ public class CodeArtifactService implements Resettable {
|
||||
* 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
|
||||
* RetainedVersionOriginClaim#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) {
|
||||
return retainedVersionOriginConnection(region, domain, domainOwner, repository, "maven", namespace,
|
||||
packageName, version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic sibling of {@link #mavenRetainedVersionOriginConnection}, for any container-backed
|
||||
* format (npm, pypi, nuget) whose own external-connection importer claims and confirms a
|
||||
* retention origin through {@link #claimRetainedVersionOrigin}/{@link
|
||||
* #finishRetainedVersionOriginAttempt} the same way Maven's own does.
|
||||
*/
|
||||
public Optional<String> retainedVersionOriginConnection(String region, String domain, String domainOwner,
|
||||
String repository, String format, 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);
|
||||
String key = packageVersionKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version));
|
||||
return Optional.ofNullable(retainedVersionOriginConnections.get(ownerScopedKey(owner, key)))
|
||||
.filter(RetainedVersionOriginClaim::confirmed)
|
||||
.map(RetainedVersionOriginClaim::externalConnectionName);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2939,10 +2982,10 @@ public class CodeArtifactService implements Resettable {
|
||||
* #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
|
||||
* RetainedVersionOriginClaim#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
|
||||
* that episode's own {@link RetainedVersionOriginClaim#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).
|
||||
*
|
||||
@@ -2971,28 +3014,54 @@ public class CodeArtifactService implements Resettable {
|
||||
public synchronized MavenClaimOutcome claimMavenRetainedVersionOrigin(String region, String domain,
|
||||
String domainOwner, String repository, String namespace, String packageName, String version,
|
||||
String externalConnectionName, long packageFenceSnapshot) {
|
||||
RetainedVersionOriginClaimOutcome outcome = claimRetainedVersionOrigin(region, domain, domainOwner,
|
||||
repository, "maven", namespace, packageName, version, externalConnectionName, packageFenceSnapshot);
|
||||
return new MavenClaimOutcome(outcome.claimed(), outcome.episodeId());
|
||||
}
|
||||
|
||||
/**
|
||||
* The outcome of {@link #claimRetainedVersionOrigin}: {@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
|
||||
* #finishRetainedVersionOriginAttempt} passing this exact {@code episodeId} back.
|
||||
*/
|
||||
public record RetainedVersionOriginClaimOutcome(boolean claimed, long episodeId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic sibling of {@link #claimMavenRetainedVersionOrigin}, parameterized by {@code
|
||||
* format} so npm/pypi/nuget's own external-connection importers can claim a retention origin
|
||||
* the exact same way, atomically and before any real network fetch, closing the same
|
||||
* mixed-origin race for their own format that Maven's own method already closes for Maven
|
||||
* (see that method's own javadoc for the full race this prevents).
|
||||
*/
|
||||
public synchronized RetainedVersionOriginClaimOutcome claimRetainedVersionOrigin(String region, String domain,
|
||||
String domainOwner, String repository, String format, String namespace, String packageName,
|
||||
String version, String externalConnectionName, long packageFenceSnapshot) {
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
String packageKeyStr = packageKey(region, domain, repository, "maven", namespace, packageName);
|
||||
String accountingName = accountingPackageName(format, packageName);
|
||||
String packageKeyStr = packageKey(region, domain, repository, format, namespace, accountingName);
|
||||
long currentFence = containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner, packageKeyStr),
|
||||
0L);
|
||||
if (currentFence != packageFenceSnapshot) {
|
||||
return new MavenClaimOutcome(false, 0L);
|
||||
return new RetainedVersionOriginClaimOutcome(false, 0L);
|
||||
}
|
||||
String key = ownerScopedKey(owner, packageVersionKey(region, domain, repository, "maven", namespace,
|
||||
packageName, version));
|
||||
MavenRetainedVersionOriginClaim existing = mavenRetainedVersionOriginConnections.get(key);
|
||||
String key = ownerScopedKey(owner, packageVersionKey(region, domain, repository, format, namespace,
|
||||
accountingName, normalizedContainerBackedVersion(format, version)));
|
||||
RetainedVersionOriginClaim existing = retainedVersionOriginConnections.get(key);
|
||||
if (existing == null) {
|
||||
long episodeId = mavenClaimEpisodeCounter.incrementAndGet();
|
||||
mavenRetainedVersionOriginConnections.put(key,
|
||||
new MavenRetainedVersionOriginClaim(externalConnectionName, 1, false, episodeId));
|
||||
return new MavenClaimOutcome(true, episodeId);
|
||||
long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet();
|
||||
retainedVersionOriginConnections.put(key,
|
||||
new RetainedVersionOriginClaim(externalConnectionName, 1, false, episodeId));
|
||||
return new RetainedVersionOriginClaimOutcome(true, episodeId);
|
||||
}
|
||||
if (!existing.externalConnectionName().equals(externalConnectionName)) {
|
||||
return new MavenClaimOutcome(false, 0L);
|
||||
return new RetainedVersionOriginClaimOutcome(false, 0L);
|
||||
}
|
||||
mavenRetainedVersionOriginConnections.put(key, new MavenRetainedVersionOriginClaim(externalConnectionName,
|
||||
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(externalConnectionName,
|
||||
existing.inFlightAttempts() + 1, existing.confirmed(), existing.episodeId()));
|
||||
return new MavenClaimOutcome(true, existing.episodeId());
|
||||
return new RetainedVersionOriginClaimOutcome(true, existing.episodeId());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3013,19 +3082,31 @@ public class CodeArtifactService implements Resettable {
|
||||
public synchronized void finishMavenRetainedVersionOriginAttempt(String region, String domain,
|
||||
String domainOwner, String repository, String namespace, String packageName, String version,
|
||||
long episodeId, boolean importedAnything) {
|
||||
finishRetainedVersionOriginAttempt(region, domain, domainOwner, repository, "maven", namespace, packageName,
|
||||
version, episodeId, importedAnything);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic sibling of {@link #finishMavenRetainedVersionOriginAttempt}, parameterized by
|
||||
* {@code format}, for the exactly-once counterpart to a {@code claimed}-true {@link
|
||||
* #claimRetainedVersionOrigin} call under any container-backed format.
|
||||
*/
|
||||
public synchronized void finishRetainedVersionOriginAttempt(String region, String domain, String domainOwner,
|
||||
String repository, String format, 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);
|
||||
String key = ownerScopedKey(owner, packageVersionKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version)));
|
||||
RetainedVersionOriginClaim existing = retainedVersionOriginConnections.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);
|
||||
retainedVersionOriginConnections.remove(key);
|
||||
} else {
|
||||
mavenRetainedVersionOriginConnections.put(key, new MavenRetainedVersionOriginClaim(
|
||||
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(
|
||||
existing.externalConnectionName(), remaining, confirmed, episodeId));
|
||||
}
|
||||
}
|
||||
@@ -3096,20 +3177,8 @@ public class CodeArtifactService implements Resettable {
|
||||
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) {
|
||||
if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, "maven", namespace, packageName,
|
||||
version, repoId, versionFenceSnapshot, episodeId)) {
|
||||
return new MavenDeployAttemptResult(false, null);
|
||||
}
|
||||
ReposiliteSidecarClient.DeployOutcome outcome;
|
||||
@@ -3127,6 +3196,81 @@ public class CodeArtifactService implements Resettable {
|
||||
return new MavenDeployAttemptResult(true, outcome);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared fence/status/claim-episode gate {@link #deployMavenAssetUnderVersionFence} and
|
||||
* {@link #retainAssetUnderVersionFence} both check, inside the very same {@code synchronized}
|
||||
* call, right before their own format-specific sidecar write: see {@link
|
||||
* #deployMavenAssetUnderVersionFence}'s own javadoc for the full race this closes against
|
||||
* {@code deletePackageVersions}/{@code deletePackage}/{@code deleteRepository}/{@code
|
||||
* disposePackageVersions}, all still held under this exact same lock. Not {@code
|
||||
* synchronized} itself: only ever called from inside a caller that already is, on this same
|
||||
* instance, so re-entering the (reentrant) monitor here would add nothing.
|
||||
*/
|
||||
private boolean retentionWriteStillAllowed(String region, String domain, String domainOwner, String repository,
|
||||
String format, String namespace, String packageName, String version, String repoId,
|
||||
long versionFenceSnapshot, long episodeId) {
|
||||
if (currentContainerBackedVersionFence(region, domain, domainOwner, repository, format, namespace,
|
||||
packageName, version) != versionFenceSnapshot) {
|
||||
return false;
|
||||
}
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
String status = currentContainerBackedVersionStatus(owner, region, domain, repository, format, namespace,
|
||||
packageName, version, repoId).status();
|
||||
if ("Disposed".equals(status) || "Archived".equals(status)) {
|
||||
return false;
|
||||
}
|
||||
String claimKey = ownerScopedKey(owner, packageVersionKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version)));
|
||||
RetainedVersionOriginClaim currentClaim = retainedVersionOriginConnections.get(claimKey);
|
||||
return currentClaim != null && currentClaim.episodeId() == episodeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The outcome of {@link #retainAssetUnderVersionFence}: {@code fenceMatched} is {@code false}
|
||||
* only when the version's fence (or status, or claim episode) no longer allowed the write at
|
||||
* all, in which case {@code wroteNewContent} is always {@code false}; otherwise {@code
|
||||
* wroteNewContent} is {@code true} once the sidecar write itself genuinely succeeded.
|
||||
*/
|
||||
public record AssetRetentionAttemptResult(boolean fenceMatched, boolean wroteNewContent) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic sibling of {@link #deployMavenAssetUnderVersionFence}, for npm/pypi/nuget's own
|
||||
* external-connection importers to write a retained asset into their own sidecar
|
||||
* ({@code sidecar.storePackageVersionAsset}) under the same fence/status/claim-episode
|
||||
* protection Maven's own method already provides, inside the exact same lock {@code
|
||||
* deletePackageVersions}/{@code deletePackage}/{@code deleteRepository}/{@code
|
||||
* disposePackageVersions} hold for their own entire operation.
|
||||
*
|
||||
* <p>Unlike {@link ReposiliteSidecarClient#deployArtifact}, {@link
|
||||
* RepositorySidecarManager#storePackageVersionAsset} reports no status code or idempotent-match
|
||||
* distinction of its own: it either succeeds (void) or throws. A caller that wants to avoid
|
||||
* double-counting bytes on a retry should check {@link
|
||||
* RepositorySidecarManager#fetchPackageVersionAsset} first and skip this call entirely when
|
||||
* the asset is already there with matching content, the same way a direct upload's own
|
||||
* idempotency check already does for this format's controller.
|
||||
*/
|
||||
public synchronized AssetRetentionAttemptResult retainAssetUnderVersionFence(String region, String domain,
|
||||
String domainOwner, String repository, String format, String namespace, String packageName,
|
||||
String version, long versionFenceSnapshot, long packageFenceSnapshot, long episodeId,
|
||||
RepositorySidecarManager sidecar, String repositoryContainerId, String assetName, byte[] content) {
|
||||
if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, format, namespace, packageName,
|
||||
version, repositoryContainerId, versionFenceSnapshot, episodeId)) {
|
||||
return new AssetRetentionAttemptResult(false, false);
|
||||
}
|
||||
try {
|
||||
sidecar.storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName,
|
||||
version, assetName, content);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not write {0} {1} {2}''s asset {3} while retaining it through an external "
|
||||
+ "connection.", format, packageName, version, assetName);
|
||||
return new AssetRetentionAttemptResult(true, false);
|
||||
}
|
||||
recordContainerBackedAssetBytes(region, domain, domainOwner, repository, format, namespace, packageName,
|
||||
content.length, packageFenceSnapshot);
|
||||
return new AssetRetentionAttemptResult(true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s own counterpart to
|
||||
* {@link #deployMavenAssetUnderVersionFence}, at package granularity rather than one version's:
|
||||
@@ -3235,11 +3379,13 @@ public class CodeArtifactService implements Resettable {
|
||||
// published, see putPackageOriginConfiguration) is the one case where neither branch below
|
||||
// finds anything real to delete, yet the package still exists, the same way describePackage
|
||||
// already recognizes it. hadRealContent carries whether the branch actually found something.
|
||||
String originKey = packageKey(region, domain, repository, format, namespace, packageName);
|
||||
Optional<PackageOriginConfig> originConfig = packageOriginConfigs.getForAccount(owner, originKey);
|
||||
boolean hadRealContent;
|
||||
// accountingKey, not the raw packageName: every packageOriginConfigs reader/writer now
|
||||
// keys by the same normalized spelling (accountingPackageName's own javadoc), and this one
|
||||
// key already serves every other per-package map below too.
|
||||
String accountingKey = packageKey(region, domain, repository, format, namespace,
|
||||
accountingPackageName(format, packageName));
|
||||
Optional<PackageOriginConfig> originConfig = packageOriginConfigs.getForAccount(owner, accountingKey);
|
||||
boolean hadRealContent;
|
||||
if (CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
hadRealContent = deleteContainerBackedPackageIfPresent(region, domain, owner, repository, format,
|
||||
namespace, packageName);
|
||||
@@ -3259,10 +3405,10 @@ public class CodeArtifactService implements Resettable {
|
||||
// Harmless to do unconditionally: without this, a package republished under the same
|
||||
// namespace/packageName/version after being deleted would inherit the deleted
|
||||
// publish's readme text instead of whatever (or nothing) the new publish itself sent.
|
||||
// Built from accountingKey, not the raw originKey above: readme capture/lookup key off
|
||||
// accountingPackageName the same way the fence and byte accounting just above do (see
|
||||
// accountingPackageName's own javadoc), so a pypi package deleted under one case/
|
||||
// punctuation spelling still finds the readme captured under another.
|
||||
// Built from accountingKey: readme capture/lookup key off accountingPackageName the
|
||||
// same way the fence and byte accounting just above do (see accountingPackageName's
|
||||
// own javadoc), so a pypi package deleted under one case/punctuation spelling still
|
||||
// finds the readme captured under another.
|
||||
String ownerScopedReadmePrefix = ownerScopedKey(owner, accountingKey) + "::";
|
||||
packageVersionReadmes.keySet().stream()
|
||||
.filter(k -> k.startsWith(ownerScopedReadmePrefix))
|
||||
@@ -3276,14 +3422,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 prefix, same reasoning: a 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()
|
||||
retainedVersionOriginConnections.keySet().stream()
|
||||
.filter(k -> k.startsWith(ownerScopedReadmePrefix))
|
||||
.toList()
|
||||
.forEach(mavenRetainedVersionOriginConnections::remove);
|
||||
.forEach(retainedVersionOriginConnections::remove);
|
||||
if (namespace == null) {
|
||||
Set<String> packageNames = containerBackedOverriddenPackagesByRepository.get(
|
||||
ownerScopedKey(owner, repositoryFormatKey(region, domain, repository, format)));
|
||||
@@ -3323,12 +3469,11 @@ public class CodeArtifactService implements Resettable {
|
||||
// were actually in effect, not CodeArtifact's bare defaults. A later DescribePackage on the
|
||||
// same coordinates must 404 rather than finding a zero-version package the deleted config
|
||||
// left behind.
|
||||
packageOriginConfigs.deleteForAccount(owner, originKey);
|
||||
packageOriginConfigs.deleteForAccount(owner, accountingKey);
|
||||
// Harmless no-op for generic (nothing is ever recorded there under this key; its bytes
|
||||
// live in packageVersions instead, already gone via the version-deleting branch above).
|
||||
// Uses accountingKey, not originKey: for pypi the two can differ (see
|
||||
// accountingPackageName's own javadoc), and the byte count was written under whichever
|
||||
// one actually matches what pypiserver itself treats as this package's identity.
|
||||
// The byte count was written under whichever spelling actually matches what the real
|
||||
// sidecar itself treats as this package's identity (accountingPackageName's own javadoc).
|
||||
containerBackedAssetBytes.remove(ownerScopedKey(owner, accountingKey));
|
||||
String publishRestriction = originConfig.map(PackageOriginConfig::getPublishRestriction).orElse("ALLOW");
|
||||
String upstreamRestriction = originConfig.map(PackageOriginConfig::getUpstreamRestriction).orElse("BLOCK");
|
||||
@@ -4056,20 +4201,18 @@ public class CodeArtifactService implements Resettable {
|
||||
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);
|
||||
String key = ownerScopedKey(owner, packageVersionKey(region, domain, destinationRepository, format,
|
||||
namespace, accountingPackageName(format, packageName),
|
||||
normalizedContainerBackedVersion(format, version)));
|
||||
Optional<String> sourceConnection = retainedVersionOriginConnection(region, domain, owner, sourceRepository,
|
||||
format, namespace, packageName, version);
|
||||
if (sourceConnection.isEmpty()) {
|
||||
mavenRetainedVersionOriginConnections.remove(key);
|
||||
retainedVersionOriginConnections.remove(key);
|
||||
return;
|
||||
}
|
||||
long episodeId = mavenClaimEpisodeCounter.incrementAndGet();
|
||||
mavenRetainedVersionOriginConnections.put(key,
|
||||
new MavenRetainedVersionOriginClaim(sourceConnection.get(), 0, true, episodeId));
|
||||
long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet();
|
||||
retainedVersionOriginConnections.put(key,
|
||||
new RetainedVersionOriginClaim(sourceConnection.get(), 0, true, episodeId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4498,7 +4641,7 @@ public class CodeArtifactService implements Resettable {
|
||||
containerBackedPackageVersionStatusOverrides.clear();
|
||||
containerBackedOverriddenVersionsByPackage.clear();
|
||||
containerBackedOverriddenPackagesByRepository.clear();
|
||||
mavenRetainedVersionOriginConnections.clear();
|
||||
retainedVersionOriginConnections.clear();
|
||||
authorizationTokens.clear();
|
||||
if (inMemory) {
|
||||
memoryAssetStore.clear();
|
||||
@@ -4802,8 +4945,10 @@ public class CodeArtifactService implements Resettable {
|
||||
* treats case- and punctuation-equivalent spellings as the same package, so an upload spelled
|
||||
* one way and a later {@code DeletePackage} spelled another must still address the same byte
|
||||
* count and the same fence entry, the way they already address the same sidecar package.
|
||||
* {@code packageOriginConfigs} deliberately keeps using the caller's raw spelling unchanged;
|
||||
* that mismatch is pre-existing and unrelated to the byte accounting this method guards.
|
||||
* {@code packageOriginConfigs} uses this same normalized spelling too (found by Greptile's
|
||||
* review of the nuget external-connection work: a {@code PutPackageOriginConfiguration} call
|
||||
* and a later request for the same package must resolve to the same restriction regardless of
|
||||
* which casing/punctuation either one happened to use).
|
||||
*/
|
||||
private static String accountingPackageName(String format, String packageName) {
|
||||
if ("pypi".equals(format)) {
|
||||
|
||||
+151
@@ -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.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A real outbound client for the one public NuGet repository CodeArtifact's {@code
|
||||
* public:nuget-org} external connection names: {@code https://api.nuget.org/v3-flatcontainer},
|
||||
* the NuGet V3 {@code PackageBaseAddress/3.0.0} resource real tooling resolves against for a
|
||||
* fixed-version install, confirmed against {@code docs.microsoft.com}'s own NuGet V3 API
|
||||
* reference ("Package Content" resource, {@code @type PackageBaseAddress/3.0.0}) rather than
|
||||
* inferred. Unlike Maven, AWS's own docs state NuGet packages "only have one asset per package
|
||||
* version", the {@code .nupkg} itself, at the deterministic path {@code
|
||||
* <id-lower>/<version-lower>/<id-lower>.<version-lower>.nupkg} the same reference documents.
|
||||
*
|
||||
* <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.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class NuGetExternalConnectionClient {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(NuGetExternalConnectionClient.class);
|
||||
|
||||
private static final Map<String, String> BASE_URLS = Map.of(
|
||||
"public:nuget-org", "https://api.nuget.org/v3-flatcontainer");
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final Map<String, String> baseUrls;
|
||||
|
||||
@Inject
|
||||
public NuGetExternalConnectionClient() {
|
||||
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 repository. */
|
||||
NuGetExternalConnectionClient(HttpClient httpClient, Map<String, String> baseUrls) {
|
||||
this.httpClient = httpClient;
|
||||
this.baseUrls = baseUrls;
|
||||
}
|
||||
|
||||
/** One package version's real {@code .nupkg} bytes, fetched from the real public repository. */
|
||||
public record FetchedAsset(byte[] content) {}
|
||||
|
||||
/**
|
||||
* Fetches {@code packageId}/{@code version}'s one real asset, the {@code .nupkg} itself, from
|
||||
* the real public repository {@code externalConnectionName} names.
|
||||
*/
|
||||
public Optional<FetchedAsset> fetchPackage(String externalConnectionName, String packageId, String version) {
|
||||
return send(externalConnectionName, packageId, version, "GET").map(r -> new FetchedAsset(r.body()));
|
||||
}
|
||||
|
||||
/** Whether {@code packageId}/{@code version} exists in the real public repository, without
|
||||
* downloading it. */
|
||||
public boolean exists(String externalConnectionName, String packageId, String version) {
|
||||
String baseUrl = baseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, packageId, version))
|
||||
.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} {1} in external connection {2}: {3}", packageId, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<HttpResponse<byte[]>> send(String externalConnectionName, String packageId, String version,
|
||||
String method) {
|
||||
String baseUrl = baseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(requestUri(baseUrl, packageId, version))
|
||||
.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} {1} from external connection {2}: {3}", packageId, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The real NuGet V3 flat-container path for one package version's {@code .nupkg}: {@code
|
||||
* <id-lower>/<version-lower>/<id-lower>.<version-lower>.nupkg}, confirmed against the same
|
||||
* reference this class's own javadoc cites. {@code version} is {@link NuGetVersions#normalize}d
|
||||
* here, not just lowercased (found by Greptile's review): confirmed directly against the real
|
||||
* {@code api.nuget.org/v3-flatcontainer}, which 404s on an equivalent-but-not-canonical
|
||||
* spelling (AWS's own worked example, {@code 1.00} for {@code 1.0.0}) even though it accepts
|
||||
* mixed case, since the real storage only ever holds the one canonical path NuGet's own {@code
|
||||
* NuGetVersion.ToNormalizedString()} would produce; {@link #exists}/{@link #fetchPackage}'s own
|
||||
* caller only ever validated that spelling against BaGetter's own, already-normalized listing
|
||||
* (see {@code NuGetVersions}' own javadoc), never against what the real upstream path needs.
|
||||
* The extra {@code toLowerCase} around the normalized result is deliberate: {@code
|
||||
* NuGetVersions#normalize} returns a version it cannot confidently parse completely
|
||||
* unchanged, case included, so without this, a version that used to always reach here
|
||||
* lowercased (the old behavior this replaces) could regress to a mixed-case segment for
|
||||
* exactly the inputs normalize gives up on, a no-op for every version it actually normalizes
|
||||
* since that result is already lowercase. Built the same safe way {@code
|
||||
* MavenExternalConnectionClient}'s own request builder does: the
|
||||
* three-argument {@link URI} constructor percent-encodes a stray {@code #} or {@code ?} in an
|
||||
* untrusted segment 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} without re-encoding (and so without corrupting) either side.
|
||||
*/
|
||||
private static URI requestUri(String baseUrl, String packageId, String version) {
|
||||
String lowerId = packageId.toLowerCase(Locale.ROOT);
|
||||
String lowerVersion = NuGetVersions.normalize(version).toLowerCase(Locale.ROOT);
|
||||
String path = lowerId + "/" + lowerVersion + "/" + lowerId + "." + lowerVersion + ".nupkg";
|
||||
try {
|
||||
String encodedPath = new URI(null, null, "/" + path, 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 " + packageId
|
||||
+ " " + version, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Retains a real NuGet package version from the real, live {@code public:nuget-org} repository
|
||||
* (not a local fake), through the native per-format route, the way a real {@code dotnet restore}/
|
||||
* {@code nuget install} would. {@code Newtonsoft.Json} 13.0.3 is picked because it is small,
|
||||
* stable, and unlikely to ever be pulled from nuget.org. A genuine network dependency, unlike
|
||||
* every other sidecar-backed test here, which only ever talks to a container Floci itself
|
||||
* started; see {@code CodeArtifactNuGetExternalConnectionImporterTest} for the mocked,
|
||||
* deterministic coverage of the claim/fence/mixed-origin logic this test does not re-exercise.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactNuGetExternalConnectionDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "nuget-external-connection-domain";
|
||||
private static final String REPO = "nuget-external-connection-repo";
|
||||
private static final String BLOCKED_REPO = "nuget-external-connection-blocked-repo";
|
||||
private static final String PACKAGE_ID = "Newtonsoft.Json";
|
||||
private static final String LOWER_ID = "newtonsoft.json";
|
||||
private static final String VERSION = "13.0.3";
|
||||
|
||||
private static String bearerToken;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.nuget-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(0)
|
||||
void createDomainRepositoriesConnectionAndToken() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&external-connection=public:nuget-org")
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
|
||||
+ "&external-connection=public:nuget-org")
|
||||
.then().statusCode(200);
|
||||
|
||||
bearerToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void fetchingAMissingNupkgRetainsItFromTheRealNuGetOrgConnectionAndCountsItsBytes() {
|
||||
long assetSizeBytesBefore = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
assertEquals(0L, assetSizeBytesBefore);
|
||||
|
||||
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
|
||||
+ LOWER_ID + "." + VERSION + ".nupkg")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
|
||||
// A real .nupkg is a real zip: "PK" magic bytes, not asserting exact content since the
|
||||
// real artifact is out of this test's control.
|
||||
assertEquals('P', (char) fetched[0]);
|
||||
assertEquals('K', (char) fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(1000));
|
||||
|
||||
// Proves the retained bytes are actually counted toward DescribeDomain's assetSizeBytes,
|
||||
// the same way a direct nuget push already is.
|
||||
long assetSizeBytesAfter = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
assertEquals(assetSizeBytesBefore + fetched.length, assetSizeBytesAfter);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void refetchingTheSameVersionServesItWithoutRetainingItAgain() {
|
||||
long assetSizeBytesBefore = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
|
||||
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/" + VERSION + "/"
|
||||
+ LOWER_ID + "." + VERSION + ".nupkg")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals('P', (char) fetched[0]);
|
||||
assertEquals('K', (char) fetched[1]);
|
||||
|
||||
long assetSizeBytesAfter = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
assertEquals(assetSizeBytesBefore, assetSizeBytesAfter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Greptile's review: {@code PackageOriginConfig} used to be keyed by whatever raw
|
||||
* spelling a caller used, so a restriction set through one casing silently never matched a
|
||||
* request spelled another way. Deliberately mixed-case here ({@link #PACKAGE_ID}) against the
|
||||
* native route's own lowercase spelling, the exact mismatch the fix closes: an operator
|
||||
* blocking upstream retention through the management API is not required to already know (or
|
||||
* guess at) the normalized spelling nuget's own URL convention happens to use.
|
||||
*/
|
||||
@Test
|
||||
@Order(3)
|
||||
void upstreamBlockPreventsRetentionEvenThoughTheRealPackageExists() {
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"restrictions\":{\"publish\":\"ALLOW\",\"upstream\":\"BLOCK\"}}")
|
||||
.post("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=nuget"
|
||||
+ "&package=" + PACKAGE_ID)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + BLOCKED_REPO + "/v3/package/" + LOWER_ID + "/" + VERSION
|
||||
+ "/" + LOWER_ID + "." + VERSION + ".nupkg")
|
||||
.then().statusCode(404);
|
||||
|
||||
// The block itself is visible under either spelling too, not just enforced: proves the
|
||||
// fix is a real normalization, not a one-off match on this test's own two spellings.
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=nuget&package="
|
||||
+ LOWER_ID)
|
||||
.then().statusCode(200)
|
||||
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void aVersionTheRealRepositoryDoesNotHaveIsNeverRetained() {
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID
|
||||
+ "/999.999.999/" + LOWER_ID + ".999.999.999.nupkg")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Greptile's review: a successfully retained version used to still report {@code
|
||||
* originType: INTERNAL}, since {@code versionOrigin} special-cased Maven only. Confirms the
|
||||
* fix against the real sidecar's own retained version from {@link
|
||||
* #fetchingAMissingNupkgRetainsItFromTheRealNuGetOrgConnectionAndCountsItsBytes}, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void aRetainedVersionReportsAnExternalOriginNotInternal() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package="
|
||||
+ LOWER_ID)
|
||||
.then().statusCode(200)
|
||||
.body("versions[0].version", equalTo(VERSION))
|
||||
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
|
||||
.body("versions[0].origin.domainEntryPoint.externalConnectionName",
|
||||
equalTo("public:nuget-org"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Greptile's review: the outbound request to the real public repository only
|
||||
* lowercased the version instead of fully normalizing it, so a request spelled equivalently
|
||||
* but not canonically (AWS's own worked example, {@code 1.00} for {@code 1.0.0}) built a path
|
||||
* the real {@code api.nuget.org/v3-flatcontainer} storage has nothing under and 404s on,
|
||||
* confirmed directly against it, even though the exact same real package version exists under
|
||||
* its canonical spelling. A distinct, never-before-retained version ({@code 9.0.1}) proves the
|
||||
* fetch itself succeeds under the equivalent spelling, not just that local matching tolerates
|
||||
* it once something is already retained.
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void fetchingAnEquivalentlySpelledVersionStillRetainsItFromTheRealNuGetOrgConnection() {
|
||||
String equivalentVersion = "9.00.1";
|
||||
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/" + LOWER_ID + "/"
|
||||
+ equivalentVersion + "/" + LOWER_ID + "." + equivalentVersion + ".nupkg")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
|
||||
assertEquals('P', (char) fetched[0]);
|
||||
assertEquals('K', (char) fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(1000));
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository;
|
||||
import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link CodeArtifactNuGetExternalConnectionImporter}'s own decision logic: when it attempts a
|
||||
* real external-connection fetch at all, and what it writes back. {@link BagetterSidecarClient}
|
||||
* and {@link NuGetExternalConnectionClient} are both mocked, so no real network or BaGetter call
|
||||
* ever happens here; their own wire contracts have their own tests.
|
||||
*/
|
||||
class CodeArtifactNuGetExternalConnectionImporterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String OWNER = "123456789012";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String REPO_ID = "repo-id";
|
||||
private static final String PACKAGE_ID = "Widget";
|
||||
private static final String VERSION = "1.0.0";
|
||||
private static final byte[] NUPKG_CONTENT = "nupkg-content".getBytes();
|
||||
|
||||
/** The episode id the default claim stub below hands out; every finish verify reuses it. */
|
||||
private static final long EPISODE_ID = 7L;
|
||||
|
||||
private CodeArtifactService service;
|
||||
private BagetterSidecarClient bagetter;
|
||||
private NuGetExternalConnectionClient externalConnectionClient;
|
||||
private CodeArtifactNuGetExternalConnectionImporter importer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(CodeArtifactService.class);
|
||||
bagetter = mock(BagetterSidecarClient.class);
|
||||
externalConnectionClient = mock(NuGetExternalConnectionClient.class);
|
||||
importer = new CodeArtifactNuGetExternalConnectionImporter(service, bagetter, externalConnectionClient);
|
||||
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(
|
||||
List.of(new ExternalConnection("public:nuget-org", "nuget", "AVAILABLE")));
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString())).thenReturn(false);
|
||||
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString())).thenReturn(42L);
|
||||
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString())).thenReturn(99L);
|
||||
// Unstubbed by default: the claim succeeds, matching the common case of a first or
|
||||
// same-connection retry. Tests for a conflicting claim override this per call.
|
||||
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyString(), anyLong()))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
|
||||
// Unstubbed by default: BaGetter does not have the version yet, matching the controller's
|
||||
// own pre-check always calling tryImport only on a miss. Tests for the already-retained
|
||||
// race override this per call.
|
||||
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
|
||||
.thenReturn(false);
|
||||
// Unstubbed by default: the fence matched and the write landed. The real check this
|
||||
// stands in for is inside retainAssetUnderVersionFence itself, a synchronized
|
||||
// CodeArtifactService method (see its own javadoc for why), so this mock is what every
|
||||
// test configures instead.
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsFromExternalConnectionWhenNotFoundLocally() {
|
||||
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
|
||||
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("nuget"),
|
||||
isNull(), eq(PACKAGE_ID), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(bagetter), eq(REPO_ID),
|
||||
eq("widget.1.0.0.nupkg"), eq(NUPKG_CONTENT));
|
||||
verify(service).ensureRetainedPackageOriginDefault(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, 42L);
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenNoNuGetExternalConnectionIsConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID))
|
||||
.thenReturn(true);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
|
||||
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
|
||||
VERSION, "public:nuget-org", 42L))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(bagetter, never()).packageVersionExists(anyString(), anyString(), anyString(), any(), anyString(),
|
||||
anyString());
|
||||
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() {
|
||||
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
|
||||
VERSION)).thenReturn(Optional.of("public:nuget-org"));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
|
||||
anyString(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Found by Greptile's review: {@code bagetter.packageVersionExists} alone proves nothing about
|
||||
* who put the content there. A real client's own direct push can land between this attempt's
|
||||
* own claim and this existence check; treating that as "a sibling import already retained it"
|
||||
* would wrongly mark a privately-pushed version EXTERNAL and overwrite its origin defaults.
|
||||
*/
|
||||
@Test
|
||||
void doesNotMislabelAVersionADirectPushWroteDuringTheRaceAsExternallyRetained() {
|
||||
when(bagetter.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_ID, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null, PACKAGE_ID,
|
||||
VERSION)).thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(externalConnectionClient, never()).fetchPackage(anyString(), anyString(), anyString());
|
||||
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), any(), anyString(), anyLong());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndFinishesWhenTheRealRepositoryDoesNotHaveIt() {
|
||||
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(),
|
||||
anyString(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFetchThatThrowsIsTreatedLikeAMissingPackageRatherThanPropagating() {
|
||||
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
|
||||
.thenThrow(new IllegalStateException("public repository unreachable"));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
|
||||
when(externalConnectionClient.fetchPackage("public:nuget-org", PACKAGE_ID, VERSION))
|
||||
.thenReturn(Optional.of(new NuGetExternalConnectionClient.FetchedAsset(NUPKG_CONTENT)));
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), any(), anyString(), anyString(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).ensureRetainedPackageOriginDefault(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), any(), anyString(), anyLong());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
|
||||
PACKAGE_ID, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
}
|
||||
+34
@@ -5299,6 +5299,40 @@ class CodeArtifactServiceTest {
|
||||
eq("1.00"), eq("my-pkg.1.00.nupkg"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised by Greptile's review: this method's own claimed-origin cleanup removed the record
|
||||
* keyed by the caller's raw version, but {@link CodeArtifactService#retainedVersionOriginConnection}'s
|
||||
* own claim is keyed by its normalized spelling. Deleting a retained nuget version under an
|
||||
* equivalent-but-different spelling (AWS's own worked example, {@code 1.00} against {@code
|
||||
* 1.0.0}) removed the real asset but left the claim behind, so a later direct push of the
|
||||
* same real version would still read back as {@code EXTERNAL} under the stale connection.
|
||||
*/
|
||||
@Test
|
||||
void deletePackageVersionsClearsARetainedClaimEvenUnderAnEquivalentNuGetVersionSpelling() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
String repoId = created.getSidecarContainerIds().get("nuget");
|
||||
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "nuget", null,
|
||||
"my-pkg");
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome outcome = service.claimRetainedVersionOrigin(REGION,
|
||||
"dom", null, "repo", "nuget", null, "my-pkg", "1.0.0", "public:nuget-org", fence);
|
||||
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "nuget", null, "my-pkg", "1.0.0",
|
||||
outcome.episodeId(), true);
|
||||
assertEquals("public:nuget-org", service.retainedVersionOriginConnection(REGION, "dom", null, "repo",
|
||||
"nuget", null, "my-pkg", "1.0.0").orElseThrow());
|
||||
|
||||
when(bagetterClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
|
||||
.thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.00",
|
||||
Instant.ofEpochSecond(1000))));
|
||||
when(bagetterClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
|
||||
eq("my-pkg"), eq("1.00"))).thenReturn(List.of("my-pkg.1.00.nupkg"));
|
||||
|
||||
service.deletePackageVersions(REGION, "dom", null, "repo", "nuget", null, "my-pkg", List.of("1.00"), null);
|
||||
|
||||
assertTrue(service.retainedVersionOriginConnection(REGION, "dom", null, "repo", "nuget", null, "my-pkg",
|
||||
"1.0.0").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageVersionsFailsNotFoundForAContainerBackedVersionThatWasNeverPublished() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The wire contract towards the real public NuGet repository, exercised against a local {@code
|
||||
* HttpServer} fake standing in for it, named {@code fake} in these tests rather than the real
|
||||
* {@code public:nuget-org} connection name.
|
||||
*/
|
||||
class NuGetExternalConnectionClientTest {
|
||||
|
||||
private HttpServer server;
|
||||
private NuGetExternalConnectionClient client;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.start();
|
||||
Map<String, String> baseUrls = Map.of("fake", "http://127.0.0.1:" + server.getAddress().getPort());
|
||||
client = new NuGetExternalConnectionClient(
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(),
|
||||
baseUrls);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageReturnsTheRealBytesOnA200() throws IOException {
|
||||
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "Widget", "1.0.0");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get().content());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageLowercasesTheIdAndVersionInThePath() throws IOException {
|
||||
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0-beta/widget.1.0.0-beta.nupkg", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
|
||||
client.fetchPackage("fake", "WIDGET", "1.0.0-BETA");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get().content());
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised by Greptile's review: the real {@code api.nuget.org/v3-flatcontainer} only ever
|
||||
* stores one canonical path per version and 404s on an equivalent-but-not-canonical spelling
|
||||
* (confirmed directly against it: {@code 13.00.3} 404s where {@code 13.0.3} 200s), the same
|
||||
* normalization {@code NuGetVersions#normalize} already applies for matching BaGetter's own
|
||||
* listing. Requesting {@code 1.00.0} must still build the canonical {@code 1.0.0} path, not
|
||||
* the merely-lowercased {@code 1.00.0} the old code sent.
|
||||
*/
|
||||
@Test
|
||||
void fetchPackageNormalizesAnEquivalentVersionSpellingToTheCanonicalPath() throws IOException {
|
||||
byte[] content = "nupkg-content".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
|
||||
client.fetchPackage("fake", "widget", "1.00.0");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get().content());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageReturnsEmptyOnA404() throws IOException {
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 404));
|
||||
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "widget", "1.0.0");
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageReturnsEmptyForAnUnknownConnectionName() {
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result =
|
||||
client.fetchPackage("public:nuget-org", "widget", "1.0.0");
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsReturnsTrueOnA200HeadResponse() throws IOException {
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 200));
|
||||
|
||||
assertTrue(client.exists("fake", "widget", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsReturnsFalseOnA404HeadResponse() throws IOException {
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> respondEmpty(exchange, 404));
|
||||
|
||||
assertFalse(client.exists("fake", "widget", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
|
||||
byte[] content = "redirected-content".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/widget.1.0.0.nupkg", exchange -> {
|
||||
exchange.getResponseHeaders().add("Location", "/moved/widget.1.0.0.nupkg");
|
||||
exchange.sendResponseHeaders(301, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/moved/widget.1.0.0.nupkg", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<NuGetExternalConnectionClient.FetchedAsset> result = client.fetchPackage("fake", "widget", "1.0.0");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get().content());
|
||||
}
|
||||
|
||||
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
|
||||
exchange.sendResponseHeaders(status, -1);
|
||||
exchange.close();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user