diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index 80d0e05cf6..62eca7b5f6 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -40,6 +40,7 @@ the remaining formats (NuGet, etc.) have no real proxy behind them yet. | `PublishPackageVersion` | Uploads a generic-format asset, creating or extending a package version; requires `x-amz-content-sha256` and verifies it against the real hash of the bytes received. | | `DescribePackage` | Returns a package's format, namespace, name, and origin controls (`publish` and `upstream` restrictions). | | `DeletePackage` | Deletes a package and every one of its versions; `ResourceNotFoundException` for one that does not exist. | +| `PutPackageOriginConfiguration` | Sets a package's `publish`/`upstream` origin-control restrictions; can create the package (with no versions) if it doesn't exist 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. | | `TagResource` | Adds or updates tags on a domain or repository ARN. | @@ -279,11 +280,20 @@ state. named file, and none of these sidecars expose that shape cheaply (Reposilite has no per-GAV metadata beyond file listings; Verdaccio's own registry API could answer it for npm but Maven and pypi have nothing equivalent), so it remains unbridged and still 404s for these three formats. -- **`DescribePackage` origin controls are fixed.** Floci never ingests packages from an upstream - source and does not store origin controls, so every package reports `publish: ALLOW` and - `upstream: BLOCK`, the default for a package whose first version was published directly. For - Maven, npm, and pypi, `DescribePackage` asks the repository's sidecar whether the package exists, - which starts that sidecar if it is not already running. +- **`DescribePackage`'s origin controls default to `publish: ALLOW`/`upstream: BLOCK`** (the + default for a package whose first version was published directly, since Floci never ingests + packages from an upstream source) **until a caller sets them explicitly with + `PutPackageOriginConfiguration`.** For Maven, npm, and pypi, `DescribePackage` asks the + repository's sidecar whether the package exists, which starts that sidecar if it is not already + running; a package that exists only because `PutPackageOriginConfiguration` created it (no + versions yet) is found without touching any sidecar. +- **`PutPackageOriginConfiguration`'s `publish: BLOCK` is only enforced for the `generic` + format.** `PublishPackageVersion`, the one path it actually gates, accepts only `generic` to + begin with; Maven, npm, and pypi publishes go through their own native wire protocol (`mvn + deploy`, `npm publish`, `twine upload`) 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. See the [CodeArtifact API Reference](https://docs.aws.amazon.com/codeartifact/latest/APIReference/Welcome.html). diff --git a/docs/services/index.md b/docs/services/index.md index 8a409d704b..e63c4382e1 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -121,7 +121,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 | 28 | +| [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 | 29 | | [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 | 18 | 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 9ea8b5d5c5..155212318b 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 @@ -356,6 +356,27 @@ public class CodeArtifactController { return ok(single("deletedPackage", deletedPackageDescription(deleted))); } + @POST + @Path("/v1/package") + public Response putPackageOriginConfiguration(@Context HttpHeaders headers, @QueryParam("domain") String domain, + @QueryParam("domain-owner") String domainOwner, + @QueryParam("repository") String repository, + @QueryParam("format") String format, + @QueryParam("namespace") String namespace, + @QueryParam("package") String packageName, String body) { + JsonNode req = readTree(body); + JsonNode restrictions = req.get("restrictions"); + String region = regionResolver.resolveRegion(headers); + CodeArtifactService.PackageDescription described = service.putPackageOriginConfiguration(region, domain, + domainOwner, repository, format, namespace, packageName, text(restrictions, "publish"), + text(restrictions, "upstream")); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode restrictionsNode = response.putObject("originConfiguration").putObject("restrictions"); + restrictionsNode.put("publish", described.publishRestriction()); + restrictionsNode.put("upstream", described.upstreamRestriction()); + return ok(response); + } + @GET @Path("/v1/package/version") public Response describePackageVersion(@Context HttpHeaders headers, @QueryParam("domain") String domain, 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 2c8d9549fc..89bbadd986 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 @@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactPackag import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository; import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection; import io.github.hectorvent.floci.services.codeartifact.model.PackageAsset; +import io.github.hectorvent.floci.services.codeartifact.model.PackageOriginConfig; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -74,6 +75,7 @@ public class CodeArtifactService implements Resettable { * repositories created before that format's proxy existed. */ private static final List CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi"); + private static final Set ORIGIN_RESTRICTION_VALUES = Set.of("ALLOW", "BLOCK"); private static final Logger LOG = Logger.getLogger(CodeArtifactService.class); @@ -109,6 +111,7 @@ public class CodeArtifactService implements Resettable { private final AccountAwareStorageBackend domains; private final AccountAwareStorageBackend repositories; private final AccountAwareStorageBackend packageVersions; + private final AccountAwareStorageBackend packageOriginConfigs; private final RegionResolver regionResolver; private final EmulatorConfig config; private final CodeArtifactSidecarRegistry sidecarRegistry; @@ -132,6 +135,8 @@ public class CodeArtifactService implements Resettable { new TypeReference>() {}), storageFactory.create("codeartifact", "codeartifact-package-versions.json", new TypeReference>() {}), + storageFactory.create("codeartifact", "codeartifact-package-origin-configs.json", + new TypeReference>() {}), regionResolver, config, "memory".equals(serviceConfigAccess.storageMode("codeartifact")), Path.of(config.storage().persistentPath()).resolve(ASSET_STORAGE_DIR), @@ -142,11 +147,13 @@ public class CodeArtifactService implements Resettable { CodeArtifactService(AccountAwareStorageBackend domains, AccountAwareStorageBackend repositories, AccountAwareStorageBackend packageVersions, + AccountAwareStorageBackend packageOriginConfigs, RegionResolver regionResolver, EmulatorConfig config, boolean inMemory, Path assetRoot, CodeArtifactSidecarRegistry sidecarRegistry) { this.domains = domains; this.repositories = repositories; this.packageVersions = packageVersions; + this.packageOriginConfigs = packageOriginConfigs; this.regionResolver = regionResolver; this.config = config; this.sidecarRegistry = sidecarRegistry; @@ -322,6 +329,16 @@ public class CodeArtifactService implements Resettable { // must not leave the repository stuck: a retry would just 404, since the record above is // already gone. releaseSidecarStorage(r, domain, repository); + // packageOriginConfigs is keyed by name (region/domain/repository/format/namespace/package), + // unlike sidecarContainerIds, which createRepository deliberately assigns a fresh id for on + // every creation so a repository recreated under the same name never inherits the previous + // one's sidecar content. Without this, the same recreated-under-the-same-name repository + // would still inherit any package's stored publish/upstream restrictions, including a + // publish:BLOCK that would reject a publish with no way for the caller to know why. + String originPrefix = region + "::" + domain + "::" + repository + "::"; + packageOriginConfigs.keysForAccount(owner).stream() + .filter(k -> k.startsWith(originPrefix)) + .forEach(k -> packageOriginConfigs.deleteForAccount(owner, k)); return r; } @@ -563,6 +580,19 @@ public class CodeArtifactService implements Resettable { requireNonBlank(domain, "domain"); String owner = effectiveOwner(domainOwner); requireRepository(owner, repositoryKey(region, domain, repository), repository); + // A caller-configured publish:BLOCK (see PutPackageOriginConfiguration) gates the whole + // 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); + String publishRestriction = packageOriginConfigs.getForAccount(owner, originKey) + .map(PackageOriginConfig::getPublishRestriction) + .orElse("ALLOW"); + if ("BLOCK".equals(publishRestriction)) { + throw conflict("Package '" + packageName + "' cannot be published because its origin configuration " + + "blocks direct publish.", packageName, "package"); + } String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version); CodeArtifactPackageVersion pv = packageVersions.getForAccount(owner, key).orElse(null); @@ -665,41 +695,87 @@ public class CodeArtifactService implements Resettable { /** * Floci never ingests packages from an upstream source, so every package it holds was first * published directly. That is the one case where CodeArtifact's default origin controls are - * publish ALLOW and upstream BLOCK. + * publish ALLOW and upstream BLOCK; a package a caller has configured via + * {@link #putPackageOriginConfiguration} carries whatever restrictions were set there instead. */ public record PackageDescription(String format, String namespace, String packageName, String publishRestriction, String upstreamRestriction) {} public PackageDescription describePackage(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName) { - if (format == null || !PACKAGE_FORMATS.contains(format)) { - throw validation("format must be one of " + PACKAGE_FORMATS + "."); + validatePackageCoordinates(format, namespace, packageName, "describing"); + requireNonBlank(domain, "domain"); + requireNonBlank(repository, "repository"); + String owner = effectiveOwner(domainOwner); + requireRepository(owner, repositoryKey(region, domain, repository), repository); + String originKey = packageKey(region, domain, repository, format, namespace, packageName); + Optional 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 + // versions behind it, already proves the package exists, and the && below must short-circuit + // on originConfig.isEmpty() before packageExistsViaVersionsOrSidecar ever runs. For a + // container-backed format that call would otherwise start the real Maven/npm/pypi sidecar + // container (its own ensureReady lazily provisions one) just to answer a DescribePackage for + // a package nothing was ever actually published to. + if (originConfig.isEmpty() + && !packageExistsViaVersionsOrSidecar(region, domain, owner, repository, format, namespace, + packageName)) { + throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); } - validatePackageToken("package", packageName); - if (namespace != null) { - validatePackageToken("namespace", namespace); + String publishRestriction = originConfig.map(PackageOriginConfig::getPublishRestriction).orElse("ALLOW"); + String upstreamRestriction = originConfig.map(PackageOriginConfig::getUpstreamRestriction).orElse("BLOCK"); + return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction); + } + + /** + * Sets the publish/upstream origin-control restrictions for a package. Unlike every other + * package-level operation here, this one does not require the package to already exist: + * AWS documents that calling it on a package with no versions yet creates the package (with + * no versions) and applies the requested restrictions, specifically so a caller can lock down + * a package (block direct publish, block upstream ingestion, or both) before anything is ever + * published to it or connected to the repository. + * + *

{@code synchronized} for the same reason every other package-mutating method here is: + * {@link #publishPackageVersion} reads this same record to decide whether to allow a publish, + * and must never see a half-applied write. + */ + public synchronized PackageDescription putPackageOriginConfiguration(String region, String domain, + String domainOwner, String repository, String format, String namespace, String packageName, + String publishRestriction, String upstreamRestriction) { + validatePackageCoordinates(format, namespace, packageName, "setting the origin configuration of"); + // Both restrictions are required (the API reference: "You must include both the desired + // upstream and publish restrictions"), and package groups' extra ALLOW_SPECIFIC_REPOSITORIES + // / INHERIT values do not apply to a plain package's own restrictions. Set.of's own + // contains(null) throws rather than returning false, so a missing value needs its own + // null check first rather than falling into the membership test. + if (publishRestriction == null || !ORIGIN_RESTRICTION_VALUES.contains(publishRestriction)) { + throw validation("restrictions.publish must be one of " + ORIGIN_RESTRICTION_VALUES + "."); } - // The API reference's own namespace parameter doc for this action: "The namespace is - // required when requesting packages of the following formats: Maven, Swift, generic." - // pypi, nuget, ruby, and cargo packages have no namespace at all, so a supplied one can - // never be real; echoing it back in the response would misrepresent a package that way. - if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) { - throw validation("namespace is required when describing a " + format + " package."); - } - if ("pypi".equals(format) && namespace != null) { - throw validation("pypi packages do not have a namespace."); + if (upstreamRestriction == null || !ORIGIN_RESTRICTION_VALUES.contains(upstreamRestriction)) { + throw validation("restrictions.upstream must be one of " + ORIGIN_RESTRICTION_VALUES + "."); } requireNonBlank(domain, "domain"); requireNonBlank(repository, "repository"); String owner = effectiveOwner(domainOwner); requireRepository(owner, repositoryKey(region, domain, repository), repository); - boolean exists = CONTAINER_BACKED_FORMATS.contains(format) + String key = packageKey(region, domain, repository, format, namespace, packageName); + packageOriginConfigs.putForAccount(owner, key, new PackageOriginConfig(publishRestriction, + upstreamRestriction)); + return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction); + } + + /** + * Whether a package has any real version behind it: a stored {@code packageVersions} record + * for generic, or the repository's own sidecar for a container-backed format. Deliberately + * does not know about {@code packageOriginConfigs}; {@link #describePackage} checks that + * separately and short-circuits before ever calling this, so an origin-config-only package + * (no versions) never pays for a sidecar round trip just to be found. + */ + private boolean packageExistsViaVersionsOrSidecar(String region, String domain, String owner, String repository, + String format, String namespace, String packageName) { + return CONTAINER_BACKED_FORMATS.contains(format) ? containerBackedPackageExists(region, domain, owner, repository, format, namespace, packageName) : genericPackageExists(region, domain, owner, repository, format, namespace, packageName); - if (!exists) { - throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); - } - return new PackageDescription(format, namespace, packageName, "ALLOW", "BLOCK"); } private boolean containerBackedPackageExists(String region, String domain, String owner, String repository, @@ -739,35 +815,25 @@ public class CodeArtifactService implements Resettable { */ public synchronized PackageDescription deletePackage(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName) { - if (format == null || !PACKAGE_FORMATS.contains(format)) { - throw validation("format must be one of " + PACKAGE_FORMATS + "."); - } - validatePackageToken("package", packageName); - if (namespace != null) { - validatePackageToken("namespace", namespace); - } - // Same boundary as describePackage's own namespace rules (see its comment there for the - // API reference citation): a missing generic/maven namespace would delete under a - // null-namespace key nothing real ever publishes to, and a supplied pypi namespace would - // be silently ignored by the sidecar's existence check rather than rejected. - if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) { - throw validation("namespace is required when deleting a " + format + " package."); - } - if ("pypi".equals(format) && namespace != null) { - throw validation("pypi packages do not have a namespace."); - } + validatePackageCoordinates(format, namespace, packageName, "deleting"); requireNonBlank(domain, "domain"); requireNonBlank(repository, "repository"); String owner = effectiveOwner(domainOwner); requireRepository(owner, repositoryKey(region, domain, repository), repository); + // Looked up before any deletion below: an origin-config-only package (no version ever + // 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 originConfig = packageOriginConfigs.getForAccount(owner, originKey); + boolean hadRealContent; if (CONTAINER_BACKED_FORMATS.contains(format)) { - deleteContainerBackedPackage(region, domain, owner, repository, format, namespace, packageName); + hadRealContent = deleteContainerBackedPackageIfPresent(region, domain, owner, repository, format, + namespace, packageName); } else { List versions = genericPackageVersions(region, domain, owner, repository, format, namespace, packageName); - if (versions.isEmpty()) { - throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); - } + hadRealContent = !versions.isEmpty(); for (CodeArtifactPackageVersion pv : versions) { String versionKey = packageVersionKey(region, domain, repository, format, namespace, packageName, pv.getVersion()); @@ -787,7 +853,19 @@ public class CodeArtifactService implements Resettable { } } } - return new PackageDescription(format, namespace, packageName, "ALLOW", "BLOCK"); + if (!hadRealContent && originConfig.isEmpty()) { + throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); + } + // DeletePackage removes the package entity itself, origin configuration included (AWS's + // own doc: "Deletes a package and all associated package versions"), and the real + // DeletePackage response's deletedPackage.originConfiguration reports whatever restrictions + // 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); + String publishRestriction = originConfig.map(PackageOriginConfig::getPublishRestriction).orElse("ALLOW"); + String upstreamRestriction = originConfig.map(PackageOriginConfig::getUpstreamRestriction).orElse("BLOCK"); + return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction); } /** @@ -799,14 +877,29 @@ public class CodeArtifactService implements Resettable { * {@link UnsupportedOperationException} for a sidecar that genuinely cannot do this, rather than * silently leaving the package in place or claiming a success it cannot back up; that becomes a * real, if deliberately blunt, AWS error here instead of an unhandled 500. + * + *

Returns whether the sidecar actually had the package, rather than throwing when it does + * not: the caller still has to decide between success (an origin-config-only package with + * nothing real behind it yet) and a genuine 404, which needs the origin-config lookup this + * method deliberately knows nothing about. + * + *

Always asks the sidecar, even for a package deletePackage otherwise knows only through a + * stored origin configuration: unlike describePackage's short-circuit, a package set up this + * way is a real target for a later native-protocol publish (PublishPackageVersion only ever + * accepts generic, but {@code mvn deploy}/{@code npm publish}/{@code twine upload} go straight + * to the sidecar and leave no record here), so skipping this call could silently leave real + * content behind. The cost is a lazily-started container on every container-backed delete, + * origin-config-only or not; that cost already existed for every real package before this + * method's origin-config awareness, this just stops it from being skipped by accident instead + * of by choice. */ - private void deleteContainerBackedPackage(String region, String domain, String owner, String repository, - String format, String namespace, String packageName) { + private boolean deleteContainerBackedPackageIfPresent(String region, String domain, String owner, + String repository, String format, String namespace, String packageName) { String repoId = ensureFormatContainerId(format, region, domain, owner, repository); RepositorySidecarManager manager = sidecarRegistry.forFormat(format) .orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, "package")); if (!manager.packageExists(repoId, domain, repository, namespace, packageName)) { - throw notFound("Package '" + packageName + "' was not found.", packageName, "package"); + return false; } try { manager.deletePackage(repoId, domain, repository, namespace, packageName); @@ -814,6 +907,7 @@ public class CodeArtifactService implements Resettable { throw new AwsException("InternalServerException", "Deleting a " + format + " package is not yet supported by this emulator.", 500); } + return true; } private void deleteAssetContent(String owner, String packageVersionKey, String assetName) { @@ -1025,6 +1119,7 @@ public class CodeArtifactService implements Resettable { domains.clear(); repositories.clear(); packageVersions.clear(); + packageOriginConfigs.clear(); authorizationTokens.clear(); if (inMemory) { memoryAssetStore.clear(); @@ -1192,6 +1287,33 @@ public class CodeArtifactService implements Resettable { } } + /** + * The format/package/namespace coordinate validation shared by every package-level operation + * that takes them. {@code action} is a present-participle phrase ("describing", "setting the + * origin configuration of") substituted into the one message that otherwise differs per caller. + * + *

The namespace rule is the API reference's own namespace parameter doc for these actions: + * "The namespace is required when requesting packages of the following formats: Maven, Swift, + * generic." pypi, nuget, ruby, and cargo packages have no namespace at all, so a supplied one + * can never be real; echoing it back in a response would misrepresent a package that way. + */ + private static void validatePackageCoordinates(String format, String namespace, String packageName, + String action) { + if (format == null || !PACKAGE_FORMATS.contains(format)) { + throw validation("format must be one of " + PACKAGE_FORMATS + "."); + } + validatePackageToken("package", packageName); + if (namespace != null) { + validatePackageToken("namespace", namespace); + } + if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) { + throw validation("namespace is required when " + action + " a " + format + " package."); + } + if ("pypi".equals(format) && namespace != null) { + throw validation("pypi packages do not have a namespace."); + } + } + private static void validateAssetName(String assetName) { if (assetName == null || assetName.isEmpty() || assetName.length() > 255 || !ASSET_NAME.matcher(assetName).matches()) { @@ -1390,6 +1512,12 @@ public class CodeArtifactService implements Resettable { + (namespace == null ? "" : namespace) + "::" + packageName + "::" + version; } + private static String packageKey(String region, String domain, String repository, String format, + String namespace, String packageName) { + return region + "::" + domain + "::" + repository + "::" + format + "::" + + (namespace == null ? "" : namespace) + "::" + packageName; + } + private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); } diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/PackageOriginConfig.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/PackageOriginConfig.java new file mode 100644 index 0000000000..f41ee1a37c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/PackageOriginConfig.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.services.codeartifact.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The origin-control restrictions a caller explicitly set on a package via + * {@code PutPackageOriginConfiguration}. A package with no record here still has an origin + * configuration, it is just CodeArtifact's documented default (publish ALLOW, upstream BLOCK); + * see {@code CodeArtifactService.PackageDescription}'s own Javadoc for why that default holds + * for every package Floci serves until a caller overrides it. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class PackageOriginConfig { + private String publishRestriction; + private String upstreamRestriction; + + public PackageOriginConfig() { + } + + public PackageOriginConfig(String publishRestriction, String upstreamRestriction) { + this.publishRestriction = publishRestriction; + this.upstreamRestriction = upstreamRestriction; + } + + public String getPublishRestriction() { + return publishRestriction; + } + + public void setPublishRestriction(String publishRestriction) { + this.publishRestriction = publishRestriction; + } + + public String getUpstreamRestriction() { + return upstreamRestriction; + } + + public void setUpstreamRestriction(String upstreamRestriction) { + this.upstreamRestriction = upstreamRestriction; + } +} 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 d2d473b060..6ea17b011f 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 @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.Publ import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactDomain; import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactPackageVersion; import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository; +import io.github.hectorvent.floci.services.codeartifact.model.PackageOriginConfig; import io.github.hectorvent.floci.testutil.LogCapture; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; @@ -85,6 +86,28 @@ class CodeArtifactAssetPersistenceTest { assertEquals(published.packageVersion().getRevision(), result.packageVersionRevision()); } + /** + * {@code packageOriginConfigs} is wired through {@code StorageFactory} the same way + * {@code domains}/{@code repositories}/{@code packageVersions} are, but that similarity had + * never actually been exercised: this confirms a stored origin configuration, including one + * set on a package with no versions at all, actually round-trips through disk rather than only + * ever having been read back from the same in-memory instance that wrote it. + */ + @Test + void packageOriginConfigurationSurvivesRestart(@TempDir Path dir) { + CodeArtifactService first = newService(dir); + first.createDomain(REGION, "dom", null, Map.of()); + first.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + first.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "never-published", "BLOCK", + "ALLOW"); + + CodeArtifactService restarted = newService(dir); + CodeArtifactService.PackageDescription described = restarted.describePackage(REGION, "dom", null, "repo", + "generic", "ns", "never-published"); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("ALLOW", described.upstreamRestriction()); + } + /** * The in-memory {@code PackageAsset.content} field is {@code @JsonIgnore}, so a package * version reloaded from disk (a fresh {@code CodeArtifactService} instance here, standing in @@ -443,6 +466,8 @@ class CodeArtifactAssetPersistenceTest { "codeartifact-repositories.json", new TypeReference>() {}); AccountAwareStorageBackend packageVersionStore = accountAware(dir, "codeartifact-package-versions.json", new TypeReference>() {}); + AccountAwareStorageBackend packageOriginConfigStore = accountAware(dir, + "codeartifact-package-origin-configs.json", new TypeReference>() {}); RegionResolver regionResolver = mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID); @@ -453,8 +478,9 @@ class CodeArtifactAssetPersistenceTest { EmulatorConfig config = mock(EmulatorConfig.class); when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); - return new CodeArtifactService(domainStore, repoStore, packageVersionStore, regionResolver, config, - false, dir.resolve("codeartifact-assets"), new CodeArtifactSidecarRegistry(List.of())); + return new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore, + regionResolver, config, false, dir.resolve("codeartifact-assets"), + new CodeArtifactSidecarRegistry(List.of())); } private AccountAwareStorageBackend accountAware(Path dir, String fileName, TypeReference> type) { 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 d6e72f1867..1a55af7001 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 @@ -250,6 +250,49 @@ class CodeArtifactIntegrationTest { .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")); } + @Test + void putPackageOriginConfigurationCreatesAPackageAndItsRestrictionsSurviveDescribeAndDelete() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{}").post("/v1/domain?domain=origin-config-domain").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{}").post("/v1/repository?domain=origin-config-domain&repository=repo") + .then().statusCode(200); + + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"restrictions\":{\"publish\":\"BLOCK\",\"upstream\":\"ALLOW\"}}") + .post("/v1/package?domain=origin-config-domain&repository=repo&format=generic&namespace=ns" + + "&package=never-published") + .then().statusCode(200) + .body("originConfiguration.restrictions.publish", equalTo("BLOCK")) + .body("originConfiguration.restrictions.upstream", equalTo("ALLOW")); + + given().header("Authorization", AUTH) + .get("/v1/package?domain=origin-config-domain&repository=repo&format=generic&namespace=ns" + + "&package=never-published") + .then().statusCode(200) + .body("package.originConfiguration.restrictions.publish", equalTo("BLOCK")) + .body("package.originConfiguration.restrictions.upstream", equalTo("ALLOW")); + + byte[] content = "blocked".getBytes(StandardCharsets.UTF_8); + given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content)) + .contentType("application/octet-stream").body(content) + .post("/v1/package/version/publish?domain=origin-config-domain&repository=repo&format=generic" + + "&namespace=ns&package=never-published&version=1.0.0&asset=a.txt") + .then().statusCode(409).body("__type", equalTo("ConflictException")); + + given().header("Authorization", AUTH) + .delete("/v1/package?domain=origin-config-domain&repository=repo&format=generic&namespace=ns" + + "&package=never-published") + .then().statusCode(200) + .body("deletedPackage.originConfiguration.restrictions.publish", equalTo("BLOCK")) + .body("deletedPackage.originConfiguration.restrictions.upstream", equalTo("ALLOW")); + + given().header("Authorization", AUTH) + .get("/v1/package?domain=origin-config-domain&repository=repo&format=generic&namespace=ns" + + "&package=never-published") + .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")); + } + @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 5ddc798bcb..a821c8a9c0 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 @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.Reso import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactDomain; import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactPackageVersion; import io.github.hectorvent.floci.services.codeartifact.model.CodeArtifactRepository; +import io.github.hectorvent.floci.services.codeartifact.model.PackageOriginConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -63,6 +64,8 @@ class CodeArtifactServiceTest { repoStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); AccountAwareStorageBackend packageVersionStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + AccountAwareStorageBackend packageOriginConfigStore = + AccountAwareStorageBackend.inMemory(ACCOUNT_ID); regionResolver = mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID); @@ -79,8 +82,8 @@ class CodeArtifactServiceTest { when(reposiliteClient.format()).thenReturn("maven"); pypiserverClient = mock(PypiserverSidecarClient.class); when(pypiserverClient.format()).thenReturn("pypi"); - service = new CodeArtifactService(domainStore, repoStore, packageVersionStore, regionResolver, config, - true, null, new CodeArtifactSidecarRegistry( + service = new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore, + regionResolver, config, true, null, new CodeArtifactSidecarRegistry( List.of(verdaccioClient, reposiliteClient, pypiserverClient))); } @@ -421,6 +424,34 @@ class CodeArtifactServiceTest { assertEquals("ResourceNotFoundException", e.getErrorCode()); } + /** + * createRepository already guarantees this for container-backed sidecar content, by design + * (a fresh sidecarContainerIds id on every creation, never derived from the repository's + * name). packageOriginConfigs is keyed by name instead, so deleteRepository has to clean it + * up explicitly, or a repository recreated under the same name would inherit a prior + * package's restrictions, including a publish:BLOCK the new repository's owner never set and + * has no way to discover. + */ + @Test + void deleteRepositoryRemovesOriginConfigsSoARecreatedRepositoryDoesNotInheritThem() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK", + "BLOCK"); + + service.deleteRepository(REGION, "dom", null, "repo"); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException gone = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg")); + assertEquals("ResourceNotFoundException", gone.getErrorCode()); + + byte[] content = "x".getBytes(StandardCharsets.UTF_8); + PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", + "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content); + assertEquals("Published", published.packageVersion().getStatus()); + } + @Test void createRepositoryAcceptsExistingUpstream() { service.createDomain(REGION, "dom", null, Map.of()); @@ -660,11 +691,22 @@ class CodeArtifactServiceTest { void clearRemovesAllPersistedState() { service.createDomain(REGION, "dom", null, Map.of()); service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + // An origin-config-only package (no versions, see putPackageOriginConfiguration) is its + // own persisted record distinct from a domain, repository, or package version; clear() + // missing it would leave describePackage still finding a package that should be gone. + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "never-published", + "BLOCK", "BLOCK"); service.clear(); assertTrue(service.listDomains(REGION, null, null).items().isEmpty()); AwsException e = assertThrows(AwsException.class, () -> service.describeRepository(REGION, "dom", null, "repo")); assertEquals("ResourceNotFoundException", e.getErrorCode()); + + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + AwsException packageGone = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", + null, "repo", "generic", "ns", "never-published")); + assertEquals("ResourceNotFoundException", packageGone.getErrorCode()); } // ---------------------------------------------------- authorization tokens @@ -1104,6 +1146,156 @@ class CodeArtifactServiceTest { assertEquals("ValidationException", e.getErrorCode()); } + /** + * The one package-level operation that works before the package exists at all: AWS documents + * that calling it creates the package with no versions and applies the requested restrictions, + * so a caller can lock a package down before anything is ever published to it. + */ + @Test + void putPackageOriginConfigurationCreatesAPackageWithNoVersionsAndDescribePackageReflectsIt() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException notYetFound = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", + null, "repo", "generic", "ns", "never-published")); + assertEquals("ResourceNotFoundException", notYetFound.getErrorCode()); + + CodeArtifactService.PackageDescription configured = service.putPackageOriginConfiguration(REGION, "dom", + null, "repo", "generic", "ns", "never-published", "BLOCK", "BLOCK"); + assertEquals("BLOCK", configured.publishRestriction()); + assertEquals("BLOCK", configured.upstreamRestriction()); + + CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo", + "generic", "ns", "never-published"); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("BLOCK", described.upstreamRestriction()); + } + + /** + * The same no-versions-needed existence proof applies uniformly to a container-backed format, + * not just generic: the pypi sidecar never heard of this package (its mock answers false by + * default, standing in for a real sidecar that was never asked to provision anything for it), + * yet the stored origin configuration alone must still be enough for describePackage to find + * the package rather than 404ing because the sidecar-exists check came back empty. + */ + @Test + void putPackageOriginConfigurationCreatesAContainerBackedPackageWithNoVersionsToo() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", null, "never-published", "BLOCK", + "ALLOW"); + + CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo", + "pypi", null, "never-published"); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("ALLOW", described.upstreamRestriction()); + verify(pypiserverClient, never()).packageExists(any(), any(), any(), any(), any()); + } + + @Test + void putPackageOriginConfigurationOverridesTheDirectPublishDefaultsOfAnExistingPackage() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + byte[] content = "x".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", + sha256Hex(content), "false", content); + + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK", + "ALLOW"); + + CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo", + "generic", "ns", "my-pkg"); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("ALLOW", described.upstreamRestriction()); + } + + @Test + void putPackageOriginConfigurationValidatesRestrictionsAndNamespaceShape() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + + AwsException missingRestrictions = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", null, null)); + assertEquals("ValidationException", missingRestrictions.getErrorCode()); + + AwsException missingUpstreamOnly = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW", + null)); + assertEquals("ValidationException", missingUpstreamOnly.getErrorCode()); + + AwsException badRestrictionValue = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", + "ALLOW_SPECIFIC_REPOSITORIES", "BLOCK")); + assertEquals("ValidationException", badRestrictionValue.getErrorCode()); + + AwsException badUpstreamValue = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW", + "ALLOW_SPECIFIC_REPOSITORIES")); + assertEquals("ValidationException", badUpstreamValue.getErrorCode()); + + AwsException missingNamespaceForGeneric = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", null, "my-pkg", "ALLOW", + "BLOCK")); + assertEquals("ValidationException", missingNamespaceForGeneric.getErrorCode()); + + AwsException namespaceForPypi = assertThrows(AwsException.class, () -> service + .putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", "bogus-namespace", "my-pkg", + "ALLOW", "BLOCK")); + assertEquals("ValidationException", namespaceForPypi.getErrorCode()); + + // None of the rejections above may have created the package or changed anything about it: + // every one of them must still 404 just like before any of these calls were attempted. + AwsException stillAbsent = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg")); + assertEquals("ResourceNotFoundException", stillAbsent.getErrorCode()); + } + + /** + * Same rejections as above, but against a package that already carries a stored + * configuration: a rejected update must leave that prior configuration exactly as it was, + * not half-apply the new, invalid restrictions. + */ + @Test + void putPackageOriginConfigurationLeavesAnExistingConfigurationUnchangedOnRejection() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW", + "BLOCK"); + + assertThrows(AwsException.class, () -> service.putPackageOriginConfiguration(REGION, "dom", null, "repo", + "generic", "ns", "my-pkg", "ALLOW", "ALLOW_SPECIFIC_REPOSITORIES")); + + CodeArtifactService.PackageDescription unchanged = service.describePackage(REGION, "dom", null, "repo", + "generic", "ns", "my-pkg"); + assertEquals("ALLOW", unchanged.publishRestriction()); + assertEquals("BLOCK", unchanged.upstreamRestriction()); + } + + /** + * Mirrors the AWS user guide's own worked example: once a package's origin configuration sets + * Publish to Block, a direct PublishPackageVersion for that package must be rejected, even for + * an otherwise brand-new version, and restoring Publish to Allow lifts the rejection again. + */ + @Test + void publishPackageVersionIsRejectedOnceOriginConfigurationBlocksPublish() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK", + "ALLOW"); + + byte[] content = "x".getBytes(StandardCharsets.UTF_8); + AwsException blocked = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", + null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content)); + assertEquals("ConflictException", blocked.getErrorCode()); + + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW", + "ALLOW"); + PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", + "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content); + assertEquals("Published", published.packageVersion().getStatus()); + } + @Test void deletePackageRemovesEveryVersionAndAssetButLeavesOtherPackagesAlone() { service.createDomain(REGION, "dom", null, Map.of()); @@ -1145,6 +1337,93 @@ class CodeArtifactServiceTest { assertEquals("ResourceNotFoundException", unknown.getErrorCode()); } + /** + * The real DeletePackage response's deletedPackage.originConfiguration reports whatever + * restrictions were actually in effect, not CodeArtifact's bare ALLOW/BLOCK defaults. + */ + @Test + void deletePackageReportsTheOriginConfigurationThatWasActuallyInEffect() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + byte[] content = "x".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", + sha256Hex(content), "false", content); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW", + "ALLOW"); + + CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo", + "generic", "ns", "my-pkg"); + assertEquals("ALLOW", deleted.publishRestriction()); + assertEquals("ALLOW", deleted.upstreamRestriction()); + } + + /** + * DeletePackage removes the package entity, origin configuration included (AWS's own doc: + * "Deletes a package and all associated package versions"). A leftover origin-config record + * must not resurrect the deleted package as a zero-version one on the next DescribePackage. + */ + @Test + void deletePackageClearsTheOriginConfigurationSoDescribePackageStays404Afterward() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + byte[] content = "x".getBytes(StandardCharsets.UTF_8); + service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", + sha256Hex(content), "false", content); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK", + "BLOCK"); + + service.deletePackage(REGION, "dom", null, "repo", "generic", "ns", "my-pkg"); + + AwsException gone = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, + "repo", "generic", "ns", "my-pkg")); + assertEquals("ResourceNotFoundException", gone.getErrorCode()); + } + + /** + * An origin-config-only package (no version ever published) is still a package + * describePackage finds; deletePackage must agree rather than 404ing on the same coordinates + * describePackage just reported as existing. + */ + @Test + void deletePackageRemovesAnOriginConfigOnlyPackageThatWasNeverPublishedTo() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "never-published", + "BLOCK", "BLOCK"); + + CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo", + "generic", "ns", "never-published"); + assertEquals("BLOCK", deleted.publishRestriction()); + assertEquals("BLOCK", deleted.upstreamRestriction()); + + AwsException gone = assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, + "repo", "generic", "ns", "never-published")); + assertEquals("ResourceNotFoundException", gone.getErrorCode()); + } + + /** + * Same case for a container-backed format: the sidecar still gets asked (unlike + * describePackage's short-circuit, deletePackage cannot skip this: a package set up through + * PutPackageOriginConfiguration could also have real content published to it directly through + * the native protocol later, which deletePackage still has to find and remove), but it reports + * nothing there, and the stored origin configuration alone must still let deletePackage + * succeed rather than 404 on a package describePackage itself finds. + */ + @Test + void deletePackageRemovesAnOriginConfigOnlyContainerBackedPackageThatTheSidecarNeverHeardOf() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", null, "never-published", "ALLOW", + "BLOCK"); + when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("never-published"))) + .thenReturn(false); + + CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo", "pypi", + null, "never-published"); + assertEquals("ALLOW", deleted.publishRestriction()); + verify(pypiserverClient, never()).deletePackage(any(), any(), any(), any(), any()); + } + @Test void deletePackageBridgesToReposiliteForMavenAfterConfirmingItExists() { service.createDomain(REGION, "dom", null, Map.of());