diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index 5a032ccef9..dcbbc243a8 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -45,6 +45,7 @@ behind them yet. | `DescribePackageVersion` | Returns a package version's status, revision, and origin. | | `GetPackageVersionAsset` | Downloads one asset from a package version by name, optionally pinned to a specific revision. | | `GetPackageVersionReadme` | Returns the readme text for a package version; `npm`, `pypi`, and `nuget` only, matching AWS's own restriction for this action. | +| `CopyPackageVersions` | Copies one or more versions of a package from one repository to another in the same domain; `generic` only. | | `TagResource` | Adds or updates tags on a domain or repository ARN. | | `UntagResource` | Removes tags by key from a domain or repository ARN. | | `ListTagsForResource` | Lists the tags on a domain or repository ARN. | @@ -256,6 +257,15 @@ state. `DisposePackageVersions`, and `UpdatePackageVersionsStatus` don't exist yet; the only way to move a version from `Unfinished` to `Published` today is a follow-up `PublishPackageVersion` call that omits the `unfinished` flag. +- **`CopyPackageVersions` only supports the `generic` format, unlike real AWS.** The API + reference does not restrict this action's `format` parameter the way it restricts + `PublishPackageVersion`'s to `generic` alone; real CodeArtifact copies Maven, npm, pypi, and + nuget versions too. This is a Floci implementation gap, not an AWS restriction being mirrored: + Maven, npm, pypi, and nuget publish straight to their own sidecar and keep no `packageVersions` + record this could read from or write to, so bridging them needs the same per-sidecar + fetch-then-republish shape `GetPackageVersionAsset`'s own bridge already uses, not yet built. + `includeFromUpstream` is accepted but has no effect, since Floci has no upstream-ingestion path + for any format to begin with (see the upstream-resolution limitation below). - **The 5 GB asset size quota is nominal.** `PublishPackageVersion` and the Maven, pypi, and nuget repository endpoints all receive the request body as a single byte array before Floci ever checks its length, so a request already large enough to exhaust available heap fails before the @@ -340,9 +350,11 @@ state. format.** `PublishPackageVersion`, the one path it actually gates, accepts only `generic` to begin with; Maven, npm, pypi, and nuget publishes go through their own native wire protocol (`mvn deploy`, `npm publish`, `twine upload`, `nuget push`) directly against the repository endpoint, - which does not yet check this setting. `upstream` is stored and reported faithfully for every format but is - never enforced for any of them, since Floci has no upstream ingestion path to block in the first - place. + which does not yet check this setting. `upstream` is stored and reported faithfully for every + format but is never enforced for any of them, since Floci has no upstream ingestion path to + block in the first place. `CopyPackageVersions` deliberately does not check `publish: BLOCK` + either, for any format: the User Guide's own definition of that control scopes it to direct + publish "using package managers or similar tools," a mechanism Copy is not. - **`DescribeDomain`'s `assetSizeBytes` only counts what was published after this field started being computed.** Generic-format bytes are summed live from the still-existing `PublishPackageVersion` records, so they're always current. Maven, npm, pypi, and nuget have no diff --git a/docs/services/index.md b/docs/services/index.md index 54343587f5..9f2ba7453e 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -122,7 +122,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 | | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 | -| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 30 | +| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 31 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 27 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 19 | diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java index b5e53cc72b..8a4e3d27c0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java @@ -429,6 +429,37 @@ public class CodeArtifactController { return ok(packageVersionReadme(result)); } + @POST + @Path("/v1/package/versions/copy") + public Response copyPackageVersions(@Context HttpHeaders headers, @QueryParam("domain") String domain, + @QueryParam("domain-owner") String domainOwner, + @QueryParam("source-repository") String sourceRepository, + @QueryParam("destination-repository") String destinationRepository, + @QueryParam("format") String format, + @QueryParam("namespace") String namespace, + @QueryParam("package") String packageName, String body) { + JsonNode req = readTree(body); + String region = regionResolver.resolveRegion(headers); + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(region, domain, + domainOwner, sourceRepository, destinationRepository, format, namespace, packageName, + readStringArray(req.get("versions"), "versions"), readStringMap(req.get("versionRevisions")), + readBoolean(req, "allowOverwrite"), readBoolean(req, "includeFromUpstream")); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode successfulVersions = response.putObject("successfulVersions"); + result.successfulVersions().forEach((version, outcome) -> { + ObjectNode node = successfulVersions.putObject(version); + node.put("revision", outcome.revision()); + node.put("status", outcome.status()); + }); + ObjectNode failedVersions = response.putObject("failedVersions"); + result.failedVersions().forEach((version, failure) -> { + ObjectNode node = failedVersions.putObject(version); + node.put("errorCode", failure.errorCode()); + node.put("errorMessage", failure.errorMessage()); + }); + return ok(response); + } + // -------------------------------------------------------------------- tags @POST @@ -665,6 +696,53 @@ public class CodeArtifactController { return upstreams; } + private List readStringArray(JsonNode arrayNode, String field) { + List values = new ArrayList<>(); + if (arrayNode == null || arrayNode.isNull()) { + return values; + } + if (!arrayNode.isArray()) { + throw new AwsException("ValidationException", field + " must be an array of strings.", 400); + } + arrayNode.forEach(n -> { + if (!n.isTextual()) { + throw new AwsException("ValidationException", field + " must be an array of strings.", 400); + } + values.add(n.textValue()); + }); + return values; + } + + private Map readStringMap(JsonNode objectNode) { + Map values = new LinkedHashMap<>(); + if (objectNode == null || objectNode.isNull()) { + return values; + } + if (!objectNode.isObject()) { + throw new AwsException("ValidationException", + "versionRevisions must be an object of string to string.", 400); + } + objectNode.fields().forEachRemaining(e -> { + if (!e.getValue().isTextual()) { + throw new AwsException("ValidationException", + "versionRevisions['" + e.getKey() + "'] must be a string.", 400); + } + values.put(e.getKey(), e.getValue().textValue()); + }); + return values; + } + + private static boolean readBoolean(JsonNode req, String field) { + JsonNode value = req == null ? null : req.get(field); + if (value == null || value.isNull()) { + return false; + } + if (!value.isBoolean()) { + throw new AwsException("ValidationException", field + " must be a boolean.", 400); + } + return value.asBoolean(); + } + private static String text(JsonNode node, String field) { JsonNode value = node == null ? null : node.get(field); return value != null && value.isTextual() ? value.textValue() : null; diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java index 37516b4001..8995026696 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java @@ -40,6 +40,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -99,11 +100,21 @@ public class CodeArtifactService implements Resettable { // control/format/unassigned/surrogate/private-use characters. Without this, an asset name // containing '\r'/'\n' would be echoed back verbatim in the X-AssetName response header. private static final Pattern ASSET_NAME = Pattern.compile("\\P{C}+"); + // CopyPackageVersionsRequest.versionRevisions' map value pattern: "\S+", no whitespace + // anywhere in the string (not merely non-blank; a value containing an interior space is + // just as malformed as an all-whitespace one). + private static final Pattern VERSION_REVISION_VALUE = Pattern.compile("\\S+"); private static final List ASSET_HASH_ALGORITHMS = List.of("MD5", "SHA-1", "SHA-256", "SHA-512"); // Package-private: reused by CodeArtifactMavenController so the Maven proxy enforces the same // documented 5 GB AWS quota rather than duplicating the constant. static final long MAX_ASSET_FILE_SIZE_BYTES = 5L * 1024 * 1024 * 1024; private static final int MAX_ASSETS_PER_PACKAGE_VERSION = 350; + // AWS's own wire model: CopyPackageVersionsRequest.versions has "Array Members: Maximum + // number of 100 items." Applied the same way to versionRevisions, the alternate way of + // naming the same set of versions to copy. + private static final int MAX_COPY_VERSIONS_PER_CALL = 100; + // CopyPackageVersionsRequest.versionRevisions' map value: "Maximum length of 50." + private static final int MAX_REVISION_LENGTH = 50; private static final int MAX_DOMAINS_PER_ACCOUNT = 10; private static final int MAX_REPOSITORIES_PER_DOMAIN = 1000; private static final String ASSET_STORAGE_DIR = "codeartifact-assets"; @@ -118,6 +129,10 @@ public class CodeArtifactService implements Resettable { public record PackageVersionAssetResult(PackageAsset asset, String packageVersionRevision) {} public record PackageVersionReadmeResult(String format, String namespace, String packageName, String version, String versionRevision, String readme) {} + public record PackageVersionCopyOutcome(String revision, String status) {} + public record PackageVersionCopyFailure(String errorCode, String errorMessage) {} + public record CopyPackageVersionsResult(Map successfulVersions, + Map failedVersions) {} public record AuthorizationToken(String token, long expirationEpochSeconds) {} public record AuthorizationTokenScope(String owner, String region) {} private record AuthorizationTokenRecord(String owner, String region, String domain, Instant expiration) {} @@ -1194,6 +1209,309 @@ public class CodeArtifactService implements Resettable { return Digests.sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8)); } + /** + * Copies one or more versions of a package from one repository to another in the same + * domain. Only {@code generic} is supported today — unlike real AWS, which does not + * restrict this action's {@code format} the way it restricts {@link #publishPackageVersion}'s + * to {@code generic} alone (confirmed against the wire model: {@code + * CopyPackageVersionsRequest.format}'s own doc carries no such restriction). This is a Floci + * implementation gap, not an AWS restriction being mirrored: Maven, npm, pypi, and nuget + * publish straight to their own sidecar and keep no {@code packageVersions} record this could + * read from or write to, so bridging them needs the same per-sidecar fetch-then-republish + * shape {@code GetPackageVersionAsset}'s own bridge already uses, not yet built here. + * + *

Confirmed against the CodeArtifact User Guide's own worked examples ("Copy package + * versions"), not assumed from the shared {@code PackageVersionError} error-code enum alone, + * since that enum is reused across several batch actions and not every code it lists applies + * to this one: + *

    + *
  • Exactly one of {@code versions}/{@code versionRevisions} must be given. + *
  • A requested version absent from the source repository fails {@code NOT_FOUND}. + *
  • A {@code versionRevisions} entry whose expected revision doesn't match the source's + * actual one fails {@code MISMATCHED_REVISION}. + *
  • A version already present in the destination, byte- and metadata-identical to the + * source, is treated as an already-successful no-op: not copied, and not listed in either + * response map at all. + *
  • A version already present in the destination with different content fails {@code + * ALREADY_EXISTS} unless {@code allowOverwrite} is set, in which case the destination's + * asset set is replaced outright with the source's. + *
  • The whole call is all-or-nothing: one requested version failing any of the above + * aborts every other version that would otherwise have copied cleanly, each reported {@code + * SKIPPED} rather than performing a partial copy. + *
+ * {@code NOT_ALLOWED}, {@code MISMATCHED_STATUS}, and the top-level {@code ConflictException} + * are all part of this action's documented error surface but have no documented trigger + * specific to {@code CopyPackageVersions} (unlike, say, {@code UpdatePackageVersionsStatus}'s + * own {@code expectedStatus} parameter, which {@code CopyPackageVersionsRequest} has no + * equivalent of, or {@code PublishPackageVersion}'s origin-configuration check, which the User + * Guide's own definition of the "Publish" origin control scopes to direct publish "using + * package managers or similar tools" — a mechanism {@code CopyPackageVersions} is not) — this + * never produces any of the three, rather than guessing at a condition AWS never actually + * documents for this action. + * + *

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

A freshly copied version gets a new revision of its own ({@link #newRevision()}, never + * the source's): the User Guide's own definition of "package version revision" is explicit + * that "each time a package version is updated, a new package version revision is created," + * and landing a version in a repository it previously had no record in is such an update at + * the destination — the same reason {@link #publishPackageVersion} always mints its own rather + * than ever accepting a caller-supplied one. An identical-content no-op (see above) is + * correctly the opposite case: nothing was updated at the destination, so its existing + * revision, whatever it already was, is left untouched. + * + *

{@code synchronized} for the same reason every other package-mutating method here is: a + * concurrent publish or delete on either repository must never interleave with this method's + * own read-then-write of the destination's {@code packageVersions} record. + */ + public synchronized CopyPackageVersionsResult copyPackageVersions(String region, String domain, + String domainOwner, String sourceRepository, String destinationRepository, String format, + String namespace, String packageName, List versions, Map versionRevisions, + boolean allowOverwrite, boolean includeFromUpstream) { + if (!"generic".equals(format)) { + throw validation("format must be 'generic'; CopyPackageVersions only supports the generic package " + + "format."); + } + boolean hasVersions = versions != null && !versions.isEmpty(); + boolean hasRevisions = versionRevisions != null && !versionRevisions.isEmpty(); + if (hasVersions == hasRevisions) { + throw validation("Exactly one of versions or versionRevisions must be specified."); + } + // AWS's own wire model caps the versions array itself (and, by the same limit applied to + // the alternate way of naming the same set, versionRevisions) at 100 members; checked + // against the raw caller-supplied count, before any deduplication below, so a request + // that only looks small after collapsing repeats still gets rejected. + int rawRequestedCount = hasVersions ? versions.size() : versionRevisions.size(); + if (rawRequestedCount > MAX_COPY_VERSIONS_PER_CALL) { + throw validation("A single CopyPackageVersions call can copy at most " + MAX_COPY_VERSIONS_PER_CALL + + " versions."); + } + // A duplicate requested version (whether from a caller-supplied repeat in versions, or + // simply because a Set was never guaranteed here) must not be processed twice: besides + // the wasted work, double-copying would also waste the per-call quota check below. + List requestedVersions = List.copyOf( + new LinkedHashSet<>(hasVersions ? versions : versionRevisions.keySet())); + validatePackageCoordinates(format, namespace, packageName, "copying"); + for (String requestedVersion : requestedVersions) { + validatePackageToken("packageVersion", requestedVersion); + // AWS's own wire model: versionRevisions' map value has "Length Constraints: Minimum + // length of 1. Maximum length of 50" and "Value Pattern: \S+". A value outside that + // shape is a malformed request, not a per-version MISMATCHED_REVISION outcome the + // batch should otherwise report. + if (hasRevisions) { + String expectedRevision = versionRevisions.get(requestedVersion); + if (expectedRevision == null || expectedRevision.length() > MAX_REVISION_LENGTH + || !VERSION_REVISION_VALUE.matcher(expectedRevision).matches()) { + throw validation("versionRevisions['" + requestedVersion + "'] must be 1-" + MAX_REVISION_LENGTH + + " characters with no whitespace."); + } + } + } + requireNonBlank(domain, "domain"); + String owner = effectiveOwner(domainOwner); + requireRepository(owner, repositoryKey(region, domain, sourceRepository), sourceRepository); + requireRepository(owner, repositoryKey(region, domain, destinationRepository), destinationRepository); + // Deliberately does NOT check the destination package's origin configuration (see + // putPackageOriginConfiguration): the User Guide's own definition of the "Publish" origin + // control scopes it exactly to "publish directly to the repository using package managers + // or similar tools," and "Upstream" to ingestion from an external connection or a + // configured upstream repository. CopyPackageVersions is a distinct, explicit API action + // reached through neither mechanism, and nothing in the User Guide's "Editing package + // origin controls" chapter or the API reference ties the two together. ConflictException + // is part of this action's documented error list (so it's a real possible response), but + // this codebase has no confirmed trigger for it on this action and does not guess one. + + Map failures = new LinkedHashMap<>(); + List pendingCopies = new ArrayList<>(); + Map sourceByVersion = new LinkedHashMap<>(); + for (String version : requestedVersions) { + String sourceKey = packageVersionKey(region, domain, sourceRepository, format, namespace, packageName, + version); + CodeArtifactPackageVersion sourcePv = packageVersions.getForAccount(owner, sourceKey).orElse(null); + if (sourcePv == null) { + failures.put(version, new PackageVersionCopyFailure("NOT_FOUND", "Could not find version " + + version)); + continue; + } + if (hasRevisions) { + String expectedRevision = versionRevisions.get(version); + if (!sourcePv.getRevision().equals(expectedRevision)) { + failures.put(version, new PackageVersionCopyFailure("MISMATCHED_REVISION", + "current revision: " + sourcePv.getRevision() + ", expected revision: " + + expectedRevision)); + continue; + } + } + String destKey = packageVersionKey(region, domain, destinationRepository, format, namespace, + packageName, version); + CodeArtifactPackageVersion destPv = packageVersions.getForAccount(owner, destKey).orElse(null); + if (destPv != null) { + if (packageVersionContentMatches(sourcePv, destPv)) { + // Identical in both repositories already: AWS's own documented behavior is to + // treat this as an already-successful no-op, not copied and not listed in + // either response map at all, so this requested version is simply dropped + // here rather than added to either failures or pendingCopies. + continue; + } + if (!allowOverwrite) { + failures.put(version, new PackageVersionCopyFailure("ALREADY_EXISTS", + "Version " + version + " already exists")); + continue; + } + } + sourceByVersion.put(version, sourcePv); + pendingCopies.add(version); + } + + if (!failures.isEmpty()) { + for (String version : pendingCopies) { + failures.put(version, new PackageVersionCopyFailure("SKIPPED", "Version " + version + + " was skipped")); + } + return new CopyPackageVersionsResult(Map.of(), failures); + } + + // Every pending version's source assets are read and verified against their persisted + // hashes before any version in this same batch has anything written to the destination + // or committed: a missing or corrupted source asset for version 3 of 5 must never leave + // versions 1 and 2 committed while the batch as a whole fails, and must never be + // discovered only after this method already started mutating the destination. + Map> verifiedContentByVersion = new LinkedHashMap<>(); + for (String version : pendingCopies) { + verifiedContentByVersion.put(version, verifyAndReadSourceAssets(owner, sourceByVersion.get(version))); + } + + Map successes = new LinkedHashMap<>(); + for (String version : pendingCopies) { + CodeArtifactPackageVersion copied = copyGenericPackageVersionAssets(owner, region, domain, + destinationRepository, format, namespace, packageName, version, sourceByVersion.get(version), + verifiedContentByVersion.get(version)); + successes.put(version, new PackageVersionCopyOutcome(copied.getRevision(), copied.getStatus())); + } + return new CopyPackageVersionsResult(successes, Map.of()); + } + + /** + * Reads every one of {@code source}'s assets and confirms each one's actual bytes still hash + * to what its own persisted metadata claims, returning the verified bytes keyed by asset name. + * Guards against two distinct ways {@link #readAssetContent} can otherwise hand back the + * wrong bytes silently: a missing in-memory entry, which it answers with an empty array + * rather than an error, and disk corruption independent of Floci, which it never checks at + * all. Thrown as {@code InternalServerException} rather than folded into a per-version + * {@code CopyPackageVersionsResult} failure: this is this emulator's own storage integrity + * failing, not a caller-facing outcome any AWS-documented error code for this action + * describes. + */ + private Map verifyAndReadSourceAssets(String owner, CodeArtifactPackageVersion source) { + String sourceKey = packageVersionKey(source.getRegion(), source.getDomainName(), source.getRepositoryName(), + source.getFormat(), source.getNamespace(), source.getPackageName(), source.getVersion()); + Map verified = new LinkedHashMap<>(); + for (PackageAsset sourceAsset : source.getAssets().values()) { + byte[] content = readAssetContent(owner, sourceKey, sourceAsset.getName()); + String actualSha256 = computeHashes(content).get("SHA-256"); + String expectedSha256 = sourceAsset.getHashes().get("SHA-256"); + if (expectedSha256 == null || !expectedSha256.equalsIgnoreCase(actualSha256)) { + throw new AwsException("InternalServerException", "Could not copy version '" + source.getVersion() + + "' of package '" + source.getPackageName() + "': its asset '" + sourceAsset.getName() + + "' is missing from the source repository's storage or no longer matches its recorded " + + "hash.", 500); + } + verified.put(sourceAsset.getName(), content); + } + return verified; + } + + /** + * {@code true} only when {@code source} and {@code dest} would look identical to a client + * describing either one: same status, and the exact same set of asset names each hashing to + * the same SHA-256. Compared against the assets' own persisted hashes, the same way {@link + * #contentMatchesExisting} does for a single asset, rather than re-reading every asset's + * bytes from both repositories' asset stores. + */ + private static boolean packageVersionContentMatches(CodeArtifactPackageVersion source, + CodeArtifactPackageVersion dest) { + if (!source.getStatus().equals(dest.getStatus())) { + return false; + } + Map sourceAssets = source.getAssets(); + Map destAssets = dest.getAssets(); + if (!sourceAssets.keySet().equals(destAssets.keySet())) { + return false; + } + for (Map.Entry entry : sourceAssets.entrySet()) { + String sourceSha256 = entry.getValue().getHashes().get("SHA-256"); + String destSha256 = destAssets.get(entry.getKey()).getHashes().get("SHA-256"); + if (sourceSha256 == null || !sourceSha256.equalsIgnoreCase(destSha256)) { + return false; + } + } + return true; + } + + /** + * Actually performs one version's copy: every asset's bytes are read from the source + * repository's asset store and written into the destination's under the destination's own + * key, and the destination gets a package-version record of its own with a freshly minted + * revision (see {@link #copyPackageVersions}'s own javadoc for why it is never the source's). + * + *

{@code verifiedContent} is every one of {@code source}'s assets, already confirmed by + * {@link #verifyAndReadSourceAssets} to hash correctly, before this method or any other + * version in the same batch call had anything written to a destination; this method only + * ever writes bytes it did not itself have to read or validate. + * + *

The only way this is reached with an existing destination record already there is the + * {@code allowOverwrite} path, and the destination ends up with exactly the source's asset + * set afterward: any asset the old destination version had that the source version does not + * is deleted, not left behind as an orphan the new record no longer references. That cleanup + * runs last, after the new assets are written and the new record is committed, not first: a + * failure partway through writing the new assets must leave the old record and the old assets + * it still points to both intact and consistent, not a surviving old record pointing at bytes + * this method already deleted out from under it. + */ + private CodeArtifactPackageVersion copyGenericPackageVersionAssets(String owner, String region, String domain, + String destinationRepository, String format, String namespace, String packageName, String version, + CodeArtifactPackageVersion source, Map verifiedContent) { + String destKey = packageVersionKey(region, domain, destinationRepository, format, namespace, packageName, + version); + CodeArtifactPackageVersion existingDest = packageVersions.getForAccount(owner, destKey).orElse(null); + Map copiedAssets = new LinkedHashMap<>(); + for (PackageAsset sourceAsset : source.getAssets().values()) { + writeAssetContent(owner, destKey, sourceAsset.getName(), verifiedContent.get(sourceAsset.getName())); + PackageAsset copy = new PackageAsset(); + copy.setName(sourceAsset.getName()); + copy.setSize(sourceAsset.getSize()); + copy.setHashes(sourceAsset.getHashes()); + copiedAssets.put(sourceAsset.getName(), copy); + } + CodeArtifactPackageVersion dest = new CodeArtifactPackageVersion(); + dest.setDomainName(domain); + dest.setDomainOwner(owner); + dest.setRegion(region); + dest.setRepositoryName(destinationRepository); + dest.setFormat(format); + dest.setNamespace(namespace); + dest.setPackageName(packageName); + dest.setVersion(version); + dest.setStatus(source.getStatus()); + // publishedTime reflects when this version entered THIS repository, not the source + // repository's own publish time; an Unfinished version carries no publishedTime yet, + // matching publishPackageVersion's own rule for a version that hasn't been finalized. + dest.setPublishedTime("Unfinished".equals(source.getStatus()) ? null : Instant.now().getEpochSecond()); + dest.setRevision(newRevision()); + dest.setAssets(copiedAssets); + packageVersions.putForAccount(owner, destKey, dest); + if (existingDest != null) { + for (String staleAssetName : existingDest.getAssets().keySet()) { + if (!source.getAssets().containsKey(staleAssetName)) { + deleteAssetContent(owner, destKey, staleAssetName); + } + } + } + return dest; + } + /** * Gets the readme text for one package version. AWS documents this action for npm, pypi, and * nuget only (see {@link #README_FORMATS}), unlike every other package-version action here, diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java index a71fed2ad7..cff34bcd49 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java @@ -463,6 +463,48 @@ class CodeArtifactAssetPersistenceTest { } } + /** + * Found by Qodo review: {@code copyPackageVersions} used to read and write each version's + * assets inline inside its own commit loop, so a later version's corrupted source bytes + * would be discovered only after an earlier, otherwise-valid version in the same batch was + * already committed to the destination — the per-call all-or-nothing contract AWS documents + * for the caller-visible failure codes, silently broken for this emulator-internal one. + * Every pending version's source assets are now verified against their persisted hashes + * before any version in the batch has anything written to the destination at all. + */ + @Test + void copyPackageVersionsVerifiesEveryPendingVersionBeforeCommittingAnyOfThem(@TempDir Path dir) + throws IOException { + CodeArtifactService service = newService(dir); + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + byte[] contentGood = "version one, intact".getBytes(StandardCharsets.UTF_8); + byte[] contentBad = "version two, about to be corrupted".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "src", "generic", "ns", "my-pkg", "1.0.0", "a.txt", + Digests.sha256Hex(contentGood), "false", contentGood); + service.publishPackageVersion(REGION, "dom", null, "src", "generic", "ns", "my-pkg", "2.0.0", "a.txt", + Digests.sha256Hex(contentBad), "false", contentBad); + + Path corruptedFile; + try (Stream paths = Files.walk(dir.resolve("codeartifact-assets"))) { + corruptedFile = paths.filter(Files::isRegularFile) + .filter(p -> matchesContent(p, contentBad)) + .findFirst().orElseThrow(); + } + Files.write(corruptedFile, "corrupted on disk".getBytes(StandardCharsets.UTF_8)); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0", "2.0.0"), null, false, false)); + assertEquals("InternalServerException", e.getErrorCode()); + + AwsException notCopied = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, + "dom", null, "dst", "generic", "ns", "my-pkg", "1.0.0")); + assertEquals("ResourceNotFoundException", notCopied.getErrorCode(), + "version 1.0.0 was valid on its own, but must not have been committed ahead of the batch " + + "discovering version 2.0.0's corrupted bytes"); + } + @Test void distinctAssetNamesNeverCollideOnDisk(@TempDir Path dir) { CodeArtifactService service = newService(dir); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java index 5f1582135b..c61cac4dd0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; +import java.util.Map; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.emptyIterable; @@ -293,6 +294,70 @@ class CodeArtifactIntegrationTest { .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")); } + @Test + void copyPackageVersionsCopiesOneVersionAndSkipsASiblingWhenAnotherVersionIsNotFound() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{}").post("/v1/domain?domain=copy-domain").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{}").post("/v1/repository?domain=copy-domain&repository=src-repo").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{}").post("/v1/repository?domain=copy-domain&repository=dst-repo").then().statusCode(200); + + byte[] content = "copy-me".getBytes(StandardCharsets.UTF_8); + given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content)) + .contentType("application/octet-stream").body(content) + .post("/v1/package/version/publish?domain=copy-domain&repository=src-repo&format=generic" + + "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt") + .then().statusCode(200); + + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"versions\":[\"1.0.0\"]}") + .post("/v1/package/versions/copy?domain=copy-domain&source-repository=src-repo" + + "&destination-repository=dst-repo&format=generic&namespace=ns&package=my-pkg") + .then().statusCode(200) + .body("successfulVersions.'1.0.0'.status", equalTo("Published")) + .body("successfulVersions.'1.0.0'.revision", notNullValue()) + .body("failedVersions", equalTo(Map.of())); + + byte[] copied = given().header("Authorization", AUTH) + .get("/v1/package/version/asset?domain=copy-domain&repository=dst-repo&format=generic&namespace=ns" + + "&package=my-pkg&version=1.0.0&asset=a.txt") + .then().statusCode(200) + .extract().asByteArray(); + assertArrayEquals(content, copied); + + given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content)) + .contentType("application/octet-stream").body(content) + .post("/v1/package/version/publish?domain=copy-domain&repository=src-repo&format=generic" + + "&namespace=ns&package=my-pkg&version=2.0.0&asset=a.txt") + .then().statusCode(200); + + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"versions\":[\"2.0.0\",\"9.9.9\"]}") + .post("/v1/package/versions/copy?domain=copy-domain&source-repository=src-repo" + + "&destination-repository=dst-repo&format=generic&namespace=ns&package=my-pkg") + .then().statusCode(200) + .body("successfulVersions", equalTo(Map.of())) + .body("failedVersions.'9.9.9'.errorCode", equalTo("NOT_FOUND")) + .body("failedVersions.'2.0.0'.errorCode", equalTo("SKIPPED")); + } + + /** + * Found by Qodo review: a non-string element in the versions array (e.g. a bare number) used + * to become a null list entry that reached List.copyOf before any validation ran, throwing an + * unhandled NullPointerException instead of a clean ValidationException. This shape error is + * caught while parsing the request body, before any domain or repository lookup, so (unlike + * every other test in this class) it needs no domain/repository of its own to demonstrate. + */ + @Test + void copyPackageVersionsRejectsANonStringVersionsElementAsAValidationErrorNotAServerError() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"versions\":[\"1.0.0\",123]}") + .post("/v1/package/versions/copy?domain=no-such-domain&source-repository=no-such-repo" + + "&destination-repository=no-such-repo&format=generic&namespace=ns&package=my-pkg") + .then().statusCode(400).body("__type", equalTo("ValidationException")); + } + @Test void unfinishedPublishKeepsVersionOpenForMoreAssets() { given().contentType("application/json").header("Authorization", AUTH) diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java index d5259e0229..721af75d19 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java @@ -2115,6 +2115,386 @@ class CodeArtifactServiceTest { verify(pypiserverClient, never()).deletePackage(any(), any(), any(), any(), any()); } + // ----------------------------------------------------- copyPackageVersions + + private void publishGeneric(String repository, String packageName, String version, byte[] content) { + service.publishPackageVersion(REGION, "dom", null, repository, "generic", "ns", packageName, version, + "a.txt", Digests.sha256Hex(content), "false", content); + } + + @Test + void copyPackageVersionsCopiesEveryRequestedVersionAndTheyDescribeIdenticallyAtTheDestination() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + byte[] contentA = "version-a".getBytes(StandardCharsets.UTF_8); + byte[] contentB = "version-b".getBytes(StandardCharsets.UTF_8); + publishGeneric("src", "my-pkg", "1.0.0", contentA); + publishGeneric("src", "my-pkg", "2.0.0", contentB); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0", "2.0.0"), null, false, false); + + assertEquals(2, result.successfulVersions().size()); + assertTrue(result.failedVersions().isEmpty()); + assertEquals("Published", result.successfulVersions().get("1.0.0").status()); + assertTrue(result.successfulVersions().get("1.0.0").revision() != null + && !result.successfulVersions().get("1.0.0").revision().isBlank()); + + PackageVersionAssetResult copied = service.getPackageVersionAsset(REGION, "dom", null, "dst", "generic", + "ns", "my-pkg", "1.0.0", "a.txt", null); + assertEquals("version-a", new String(copied.asset().getContent(), StandardCharsets.UTF_8)); + // The destination's revision is its own, never the source's: see copyPackageVersions's + // own javadoc for why. + CodeArtifactPackageVersion sourcePv = service.describePackageVersion(REGION, "dom", null, "src", "generic", + "ns", "my-pkg", "1.0.0"); + assertTrue(!sourcePv.getRevision().equals(result.successfulVersions().get("1.0.0").revision())); + } + + @Test + void copyPackageVersionsRejectsBothVersionsAndVersionRevisionsTogether() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), Map.of("1.0.0", "rev"), false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRejectsNeitherVersionsNorVersionRevisions() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of(), Map.of(), false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRejectsANonGenericFormat() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "npm", null, "my-pkg", List.of("1.0.0"), null, false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsFailsNotFoundForAVersionMissingFromTheSourceRepository() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("9.9.9"), null, false, false); + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("NOT_FOUND", result.failedVersions().get("9.9.9").errorCode()); + } + + /** + * AWS's own documented example (array-unique 0.2.0/5.6.7): one requested version missing from + * the source repository fails the whole call, and every other requested version that would + * otherwise have copied cleanly is reported SKIPPED instead of actually being copied. + */ + @Test + void copyPackageVersionsSkipsAVersionThatWouldHaveSucceededWhenASiblingVersionIsNotFound() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0", "9.9.9"), null, false, false); + + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("NOT_FOUND", result.failedVersions().get("9.9.9").errorCode()); + assertEquals("SKIPPED", result.failedVersions().get("1.0.0").errorCode()); + AwsException notCopied = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, + "dom", null, "dst", "generic", "ns", "my-pkg", "1.0.0")); + assertEquals("ResourceNotFoundException", notCopied.getErrorCode()); + } + + /** + * AWS's own documented example (array-unique 0.2.1 already identical in both repositories): + * a version that is already byte- and metadata-identical at the destination is a successful + * no-op, not copied again and not listed in either response map. + */ + @Test + void copyPackageVersionsTreatsAByteIdenticalAlreadyPresentVersionAsANoOpNotListedEitherWay() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + byte[] content = "same-bytes".getBytes(StandardCharsets.UTF_8); + publishGeneric("src", "my-pkg", "1.0.0", content); + publishGeneric("dst", "my-pkg", "1.0.0", content); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false); + + assertTrue(result.successfulVersions().isEmpty()); + assertTrue(result.failedVersions().isEmpty()); + } + + /** + * AWS's own documented example (array-unique 0.3.2 present in both but different content): + * fails ALREADY_EXISTS without allowOverwrite. + */ + @Test + void copyPackageVersionsFailsAlreadyExistsForADifferentVersionAlreadyAtTheDestinationWithoutAllowOverwrite() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "source-bytes".getBytes(StandardCharsets.UTF_8)); + publishGeneric("dst", "my-pkg", "1.0.0", "different-bytes".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false); + + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("ALREADY_EXISTS", result.failedVersions().get("1.0.0").errorCode()); + } + + @Test + void copyPackageVersionsOverwritesADifferentExistingVersionWhenAllowOverwriteIsTrue() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "source-bytes".getBytes(StandardCharsets.UTF_8)); + publishGeneric("dst", "my-pkg", "1.0.0", "different-bytes".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, true, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals("Published", result.successfulVersions().get("1.0.0").status()); + PackageVersionAssetResult overwritten = service.getPackageVersionAsset(REGION, "dom", null, "dst", "generic", + "ns", "my-pkg", "1.0.0", "a.txt", null); + assertEquals("source-bytes", new String(overwritten.asset().getContent(), StandardCharsets.UTF_8)); + } + + /** + * An allowOverwrite copy makes the destination's asset set exactly the source's: an asset the + * old destination version had that the source version does not is removed, not left behind + * unreferenced. + */ + @Test + void copyPackageVersionsOverwriteRemovesAnAssetTheDestinationHadThatTheSourceDoesNot() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + byte[] sourceContent = "source-bytes".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "src", "generic", "ns", "my-pkg", "1.0.0", "a.txt", + Digests.sha256Hex(sourceContent), "false", sourceContent); + byte[] destContent = "dest-only".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", "1.0.0", "b.txt", + Digests.sha256Hex(destContent), "false", destContent); + + service.copyPackageVersions(REGION, "dom", null, "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), + null, true, false); + + AwsException goneAsset = assertThrows(AwsException.class, () -> service.getPackageVersionAsset(REGION, + "dom", null, "dst", "generic", "ns", "my-pkg", "1.0.0", "b.txt", null)); + assertEquals("ResourceNotFoundException", goneAsset.getErrorCode()); + PackageVersionAssetResult kept = service.getPackageVersionAsset(REGION, "dom", null, "dst", "generic", "ns", + "my-pkg", "1.0.0", "a.txt", null); + assertEquals("source-bytes", new String(kept.asset().getContent(), StandardCharsets.UTF_8)); + } + + @Test + void copyPackageVersionsFailsMismatchedRevisionWhenTheVersionRevisionsEntryDoesNotMatchTheSource() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", null, Map.of("1.0.0", "not-the-real-revision"), false, + false); + + assertTrue(result.successfulVersions().isEmpty()); + assertEquals("MISMATCHED_REVISION", result.failedVersions().get("1.0.0").errorCode()); + } + + @Test + void copyPackageVersionsSucceedsWhenTheVersionRevisionsEntryMatchesTheSource() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "src", "generic", + "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex("x".getBytes(StandardCharsets.UTF_8)), "false", + "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", null, + Map.of("1.0.0", published.packageVersion().getRevision()), false, false); + + assertTrue(result.failedVersions().isEmpty()); + assertEquals("Published", result.successfulVersions().get("1.0.0").status()); + } + + @Test + void copyPackageVersionsRequiresNamespaceForGeneric() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", null, "my-pkg", List.of("1.0.0"), null, false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRequiresTheSourceRepositoryToExist() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "no-such-repo", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRequiresTheDestinationRepositoryToExist() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "no-such-repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRejectsMoreThanOneHundredRequestedVersions() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + List tooMany = new ArrayList<>(); + for (int i = 0; i < 101; i++) { + tooMany.add("1.0." + i); + } + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", tooMany, null, false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + /** + * The 100-member cap AWS documents is on the request's own array, not on how many distinct + * versions remain after collapsing repeats: 101 entries that happen to repeat the same two + * versions must still be rejected, not quietly accepted because deduplication made the count + * look small. + */ + @Test + void copyPackageVersionsRejectsMoreThanOneHundredRequestedVersionsEvenWhenMostAreDuplicates() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + List tooManyWithDuplicates = new ArrayList<>(); + for (int i = 0; i < 101; i++) { + tooManyWithDuplicates.add(i % 2 == 0 ? "1.0.0" : "2.0.0"); + } + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", tooManyWithDuplicates, null, false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRejectsAVersionRevisionsValueContainingWhitespace() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", null, Map.of("1.0.0", "rev with space"), false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void copyPackageVersionsRejectsAVersionRevisionsValueOverFiftyCharacters() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", null, Map.of("1.0.0", "r".repeat(51)), false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + /** + * A caller-configured publish:BLOCK on the destination package does NOT gate + * CopyPackageVersions: the User Guide's own definition of the "Publish" origin control scopes + * it to direct publish "using package managers or similar tools," a mechanism Copy is not, + * and nothing in the API reference or the "Editing package origin controls" chapter ties the + * two together. A regression guard against re-adding that check without real evidence for it. + */ + @Test + void copyPackageVersionsIgnoresADestinationBlockOnDirectPublishSinceCopyIsNotDirectPublish() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.putPackageOriginConfiguration(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", "BLOCK", + "ALLOW"); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false); + assertTrue(result.failedVersions().isEmpty()); + assertEquals("Published", result.successfulVersions().get("1.0.0").status()); + } + + @Test + void copyPackageVersionsAllowsTheCallWhenTheDestinationPackageHasNoBlockingOriginConfiguration() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + service.putPackageOriginConfiguration(REGION, "dom", null, "dst", "generic", "ns", "my-pkg", "ALLOW", + "ALLOW"); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0"), null, false, false); + assertTrue(result.failedVersions().isEmpty()); + assertEquals("Published", result.successfulVersions().get("1.0.0").status()); + } + + @Test + void copyPackageVersionsRejectsABlankVersionRevisionsValueAsAValidationErrorRatherThanAMismatch() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + AwsException e = assertThrows(AwsException.class, () -> service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", null, Map.of("1.0.0", " "), false, false)); + assertEquals("ValidationException", e.getErrorCode()); + } + + /** + * A caller-supplied duplicate requested version must be copied (and counted) exactly once, + * not reported or processed as though two separate versions were requested. + */ + @Test + void copyPackageVersionsDeduplicatesARepeatedRequestedVersion() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "src", null, null, Map.of()); + service.createRepository(REGION, "dom", null, "dst", null, null, Map.of()); + publishGeneric("src", "my-pkg", "1.0.0", "x".getBytes(StandardCharsets.UTF_8)); + + CodeArtifactService.CopyPackageVersionsResult result = service.copyPackageVersions(REGION, "dom", null, + "src", "dst", "generic", "ns", "my-pkg", List.of("1.0.0", "1.0.0"), null, false, false); + + assertEquals(1, result.successfulVersions().size()); + assertTrue(result.failedVersions().isEmpty()); + } + @Test void getPackageVersionAssetReturnsExactBytesAndValidatesRevision() { service.createDomain(REGION, "dom", null, Map.of());