feat(codeartifact): add Package Groups support (#8206)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-13 15:33:11 -04:00
1 parent b3f9401e9f
commit a852078fc9
10 files changed
+2260 -44

No files matched your search

+30 -5
View File
@@ -52,9 +52,19 @@ behind them yet.
| `UpdatePackageVersionsStatus` | Moves one or more versions of a package to `Published`, `Unlisted`, or `Archived`; all-or-nothing per call, with `versionRevisions`/`expectedStatus` as optional preconditions. |
| `DisposePackageVersions` | Permanently deletes a package version's assets and sets its status to `Disposed`; irreversible, and shares `UpdatePackageVersionsStatus`'s all-or-nothing batch semantics. |
| `DeletePackageVersions` | Permanently removes one or more versions of a package, real assets included; unlike `DisposePackageVersions`, leaves no trace, the freed coordinates can be freely republished, and it is the one action allowed on an already-`Disposed` version. |
| `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. |
| `CreatePackageGroup` | Creates a package group from a pattern (its own identifier); every restriction type starts at `INHERIT`. |
| `DeletePackageGroup` | Deletes a package group; its direct children reparent onto its own parent, recomputed from the remaining groups. |
| `DescribePackageGroup` | Returns a package group's pattern, origin configuration (stored and resolved effective mode per restriction type), and parent. |
| `UpdatePackageGroup` | Updates a package group's `contactInfo`/`description`; the pattern and restrictions are unchanged. |
| `UpdatePackageGroupOriginConfiguration` | Sets a package group's per-restriction-type mode and/or edits its `ALLOW_SPECIFIC_REPOSITORIES` allow-list. |
| `ListPackageGroups` | Lists package group summaries in a domain, optionally filtered by pattern prefix, paginated. |
| `ListSubPackageGroups` | Lists a package group's direct children only (not grandchildren), per the hierarchy computed from the domain's current groups. |
| `ListAllowedRepositoriesForGroup` | Lists the repositories a package group's `ALLOW_SPECIFIC_REPOSITORIES` allow-list names for one restriction type. |
| `ListAssociatedPackages` | Lists the packages (across every repository in the domain) for which this group is the most specific match; `preview` answers the same question for a pattern that doesn't exist yet. |
| `GetAssociatedPackageGroup` | Returns the most specific package group matching a package's coordinate, and whether the match is `STRONG` or `WEAK`; `ResourceNotFoundException` if no group's pattern reaches it at all. |
| `TagResource` | Adds or updates tags on a domain, repository, or package group ARN. |
| `UntagResource` | Removes tags by key from a domain, repository, or package group ARN. |
| `ListTagsForResource` | Lists the tags on a domain, repository, or package group ARN. |
<!-- floci:actions:end -->
Domains and repositories are account and Region scoped and persisted through `StorageFactory`.
@@ -409,8 +419,6 @@ state.
miss simply 404s, exactly as AWS documents ("the only workaround is to try again later").
There is no caching of that failure, so a later retry against a recovered source works
immediately, but there is also no retry/backoff of its own beyond the client's own.
Package-group-level `EXTERNAL_UPSTREAM` (once package groups exist in this emulator) is not
consulted yet by this check, only the plain package-level `upstream` restriction.
- **The npm repository endpoint does not enforce the 5 GB asset size quota.** Unlike
`PublishPackageVersion` and the Maven endpoint, it streams the request straight through to the
backing Verdaccio container rather than buffering it first, so there is nowhere in the request
@@ -492,6 +500,23 @@ state.
too, which this correctly attributes to the real artifact; only the rarer, version-scoped
snapshot form gets a package name this way. The bytes are still counted toward the domain total
either way, just under an internal accounting bucket nothing else ever looks up by name.
- **Package groups enforce `PUBLISH` and `EXTERNAL_UPSTREAM`; `INTERNAL_UPSTREAM` is stored and
resolved but never gates anything.** `PUBLISH` is wired into the one package-level origin check
every direct-publish path already shares (`PublishPackageVersion`'s own `generic`-format path
and every native proxy controller's own publish guard — `mvn deploy`, `npm publish`, `twine
upload`, `nuget push` — alike), and every format's external-connection retention (Maven, npm,
pypi, NuGet) is wired to the resolved `EXTERNAL_UPSTREAM` mode, both following the "`BLOCK`
always wins over `ALLOW`" interaction between a package's own origin configuration and its
associated group's, and both blocking a weak pattern match outright regardless of the group's
configured mode. `INTERNAL_UPSTREAM` has nothing to gate yet: it governs a repository-to-
repository upstream chain (`UpdateRepository`'s `upstreams`), which this emulator does not
simulate for any format.
- **Package group weak-match normalization does not model Unicode confusable characters.** The
User Guide's own "Additional variations" section mentions visually-similar characters from
different alphabets only in passing, with no concrete testable rule; this emulator's weak match
only casefolds and collapses runs of `-`/`.`/`_` into a single `.`, the part of that section with
an actual rule to implement. A package name that only a real Unicode confusables table would
catch is treated as a non-match rather than a weak one.
See the [CodeArtifact API Reference](https://docs.aws.amazon.com/codeartifact/latest/APIReference/Welcome.html).
+1 -1
View File
@@ -131,7 +131,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Backup](backup.md) | `/backup-vaults/*`, `/logically-air-gapped-backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 35 |
| [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 | 37 |
| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/package-group*`, `/v1/list-associated-packages`, `/v1/get-associated-package-group`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 47 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*`, `/key-value-stores/*` | REST XML, REST JSON | 61 |
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 |
| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 |
@@ -15,10 +15,17 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StreamingResponses;
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationToken;
import io.floci.aws.services.codeartifact.CodeArtifactService.DomainView;
import io.floci.aws.services.codeartifact.CodeArtifactService.GetAssociatedPackageGroupResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ListAllowedRepositoriesForGroupResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ListAssociatedPackagesResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupAllowedRepositoryEdit;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupDescriptionView;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupListResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionAssetStreamResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionReadmeResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PublishPackageVersionResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ResourcePolicy;
import io.floci.aws.services.codeartifact.CodeArtifactService.UpdatePackageGroupOriginConfigurationResult;
import io.floci.aws.services.codeartifact.model.CodeArtifactPackageVersion;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
@@ -662,6 +669,140 @@ public class CodeArtifactController {
return response;
}
// -------------------------------------------------------------- package groups
@POST
@Path("/v1/package-group")
public Response createPackageGroup(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner, String body) {
JsonNode req = readTree(body);
String region = regionResolver.resolveRegion(headers);
PackageGroupDescriptionView view = service.createPackageGroup(region, domain, domainOwner,
text(req, "packageGroup"), text(req, "contactInfo"), text(req, "description"),
readTagList(req.get("tags")));
return ok(single("packageGroup", packageGroupDescription(view)));
}
@DELETE
@Path("/v1/package-group")
public Response deletePackageGroup(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup) {
String region = regionResolver.resolveRegion(headers);
PackageGroupDescriptionView view = service.deletePackageGroup(region, domain, domainOwner, packageGroup);
return ok(single("packageGroup", packageGroupDescription(view)));
}
@GET
@Path("/v1/package-group")
public Response describePackageGroup(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup) {
String region = regionResolver.resolveRegion(headers);
PackageGroupDescriptionView view = service.describePackageGroup(region, domain, domainOwner, packageGroup);
return ok(single("packageGroup", packageGroupDescription(view)));
}
@PUT
@Path("/v1/package-group")
public Response updatePackageGroup(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner, String body) {
JsonNode req = readTree(body);
String region = regionResolver.resolveRegion(headers);
PackageGroupDescriptionView view = service.updatePackageGroup(region, domain, domainOwner,
text(req, "packageGroup"), text(req, "contactInfo"), text(req, "description"));
return ok(single("packageGroup", packageGroupDescription(view)));
}
@PUT
@Path("/v1/package-group-origin-configuration")
public Response updatePackageGroupOriginConfiguration(@Context HttpHeaders headers,
@QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup,
String body) {
JsonNode req = readTree(body);
String region = regionResolver.resolveRegion(headers);
UpdatePackageGroupOriginConfigurationResult result = service.updatePackageGroupOriginConfiguration(region,
domain, domainOwner, packageGroup, readPackageGroupRestrictions(req.get("restrictions")),
readAllowedRepositoryEdits(req.get("addAllowedRepositories"), "addAllowedRepositories"),
readAllowedRepositoryEdits(req.get("removeAllowedRepositories"), "removeAllowedRepositories"));
ObjectNode response = objectMapper.createObjectNode();
response.set("packageGroup", packageGroupDescription(result.packageGroup()));
response.set("allowedRepositoryUpdates", allowedRepositoryUpdates(result.allowedRepositoryUpdates()));
return ok(response);
}
@POST
@Path("/v1/package-groups")
public Response listPackageGroups(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("prefix") String prefix,
@QueryParam("max-results") String maxResults,
@QueryParam("next-token") String nextToken) {
String region = regionResolver.resolveRegion(headers);
PackageGroupListResult result = service.listPackageGroups(region, domain, domainOwner, prefix,
Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken);
return ok(packageGroupListResponse(result));
}
@POST
@Path("/v1/package-groups/sub-groups")
public Response listSubPackageGroups(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup,
@QueryParam("max-results") String maxResults,
@QueryParam("next-token") String nextToken) {
String region = regionResolver.resolveRegion(headers);
PackageGroupListResult result = service.listSubPackageGroups(region, domain, domainOwner, packageGroup,
Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken);
return ok(packageGroupListResponse(result));
}
@GET
@Path("/v1/package-group-allowed-repositories")
public Response listAllowedRepositoriesForGroup(@Context HttpHeaders headers,
@QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup,
@QueryParam("originRestrictionType") String originRestrictionType,
@QueryParam("max-results") String maxResults,
@QueryParam("next-token") String nextToken) {
String region = regionResolver.resolveRegion(headers);
ListAllowedRepositoriesForGroupResult result = service.listAllowedRepositoriesForGroup(region, domain,
domainOwner, packageGroup, originRestrictionType,
Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken);
return ok(listAllowedRepositoriesForGroupResponse(result));
}
@GET
@Path("/v1/list-associated-packages")
public Response listAssociatedPackages(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("package-group") String packageGroup,
@QueryParam("max-results") String maxResults,
@QueryParam("next-token") String nextToken,
@QueryParam("preview") String preview) {
String region = regionResolver.resolveRegion(headers);
ListAssociatedPackagesResult result = service.listAssociatedPackages(region, domain, domainOwner,
packageGroup, Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken,
Boolean.parseBoolean(preview));
return ok(listAssociatedPackagesResponse(result));
}
@GET
@Path("/v1/get-associated-package-group")
public Response getAssociatedPackageGroup(@Context HttpHeaders headers, @QueryParam("domain") String domain,
@QueryParam("domain-owner") String domainOwner,
@QueryParam("format") String format,
@QueryParam("namespace") String namespace,
@QueryParam("package") String packageName) {
String region = regionResolver.resolveRegion(headers);
GetAssociatedPackageGroupResult result = service.getAssociatedPackageGroup(region, domain, domainOwner,
format, namespace, packageName);
return ok(getAssociatedPackageGroupResponse(result));
}
// -------------------------------------------------------------------- tags
@POST
@@ -863,6 +1004,137 @@ public class CodeArtifactController {
return node;
}
private ObjectNode packageGroupDescription(PackageGroupDescriptionView view) {
ObjectNode node = objectMapper.createObjectNode();
node.put("arn", view.arn());
node.put("pattern", view.pattern());
node.put("domainName", view.domainName());
node.put("domainOwner", view.domainOwner());
node.put("createdTime", view.createdTime());
if (view.contactInfo() != null) {
node.put("contactInfo", view.contactInfo());
}
if (view.description() != null) {
node.put("description", view.description());
}
node.set("originConfiguration", packageGroupOriginConfiguration(view.restrictions()));
if (view.parentPattern() != null) {
ObjectNode parent = node.putObject("parent");
parent.put("arn", view.parentArn());
parent.put("pattern", view.parentPattern());
}
return node;
}
private ObjectNode packageGroupOriginConfiguration(
Map<String, CodeArtifactService.PackageGroupOriginRestrictionView> restrictions) {
ObjectNode configuration = objectMapper.createObjectNode();
ObjectNode restrictionsNode = configuration.putObject("restrictions");
restrictions.forEach((type, view) -> {
ObjectNode r = restrictionsNode.putObject(type);
r.put("mode", view.mode());
r.put("effectiveMode", view.effectiveMode());
if (view.inheritedFromArn() != null) {
ObjectNode inheritedFrom = r.putObject("inheritedFrom");
inheritedFrom.put("arn", view.inheritedFromArn());
inheritedFrom.put("pattern", view.inheritedFromPattern());
}
r.put("repositoriesCount", view.repositoriesCount());
});
return configuration;
}
private ObjectNode packageGroupListResponse(PackageGroupListResult result) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("packageGroups");
result.packageGroups().forEach(g -> items.add(packageGroupDescription(g)));
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return response;
}
private ObjectNode allowedRepositoryUpdates(Map<String, Map<String, List<String>>> updates) {
ObjectNode node = objectMapper.createObjectNode();
updates.forEach((type, byUpdateType) -> {
ObjectNode typeNode = node.putObject(type);
byUpdateType.forEach((updateType, names) -> {
ArrayNode items = typeNode.putArray(updateType);
names.forEach(items::add);
});
});
return node;
}
private ObjectNode listAllowedRepositoriesForGroupResponse(ListAllowedRepositoriesForGroupResult result) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("allowedRepositories");
result.allowedRepositories().forEach(items::add);
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return response;
}
private ObjectNode listAssociatedPackagesResponse(ListAssociatedPackagesResult result) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("packages");
result.packages().forEach(p -> {
ObjectNode node = objectMapper.createObjectNode();
node.put("format", p.format());
if (p.namespace() != null) {
node.put("namespace", p.namespace());
}
node.put("package", p.packageName());
node.put("associationType", p.associationType());
items.add(node);
});
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return response;
}
private ObjectNode getAssociatedPackageGroupResponse(GetAssociatedPackageGroupResult result) {
ObjectNode response = objectMapper.createObjectNode();
response.set("packageGroup", packageGroupDescription(result.packageGroup()));
response.put("associationType", result.associationType());
return response;
}
private Map<String, String> readPackageGroupRestrictions(JsonNode restrictionsNode) {
Map<String, String> values = new LinkedHashMap<>();
if (restrictionsNode == null || restrictionsNode.isNull()) {
return values;
}
if (!restrictionsNode.isObject()) {
throw new AwsException("ValidationException",
"restrictions must be an object of restriction type to mode.", 400);
}
restrictionsNode.fields().forEachRemaining(e -> {
if (!e.getValue().isTextual()) {
throw new AwsException("ValidationException",
"restrictions['" + e.getKey() + "'] must be a string.", 400);
}
values.put(e.getKey(), e.getValue().textValue());
});
return values;
}
private List<PackageGroupAllowedRepositoryEdit> readAllowedRepositoryEdits(JsonNode arrayNode, String field) {
List<PackageGroupAllowedRepositoryEdit> edits = new ArrayList<>();
if (arrayNode == null || arrayNode.isNull()) {
return edits;
}
if (!arrayNode.isArray()) {
throw new AwsException("ValidationException",
field + " must be an array of {repositoryName, originRestrictionType} objects.", 400);
}
arrayNode.forEach(n -> edits.add(new PackageGroupAllowedRepositoryEdit(text(n, "repositoryName"),
text(n, "originRestrictionType"))));
return edits;
}
private ObjectNode single(String field, ObjectNode value) {
ObjectNode wrapper = objectMapper.createObjectNode();
wrapper.set(field, value);
@@ -21,6 +21,8 @@ import io.floci.aws.services.codeartifact.model.CodeArtifactPackageVersion;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
import io.floci.aws.services.codeartifact.model.PackageAsset;
import io.floci.aws.services.codeartifact.model.PackageGroup;
import io.floci.aws.services.codeartifact.model.PackageGroupRestriction;
import io.floci.aws.services.codeartifact.model.PackageOriginConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -41,6 +43,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -115,6 +118,22 @@ public class CodeArtifactService implements Resettable {
private static final Set<String> DISPOSE_EXPECTED_STATUSES =
Set.of("Published", "Unlisted", "Archived", "Unfinished", "Disposed");
/** The real {@code PackageGroupOriginRestrictionType} wire enum, in the order every
* restrictions map this service returns iterates them. */
private static final List<String> PACKAGE_GROUP_RESTRICTION_TYPES =
List.of("PUBLISH", "EXTERNAL_UPSTREAM", "INTERNAL_UPSTREAM");
/** The real {@code PackageGroupOriginRestrictionMode} wire enum. */
private static final Set<String> PACKAGE_GROUP_MODES =
Set.of("ALLOW", "ALLOW_SPECIFIC_REPOSITORIES", "BLOCK", "INHERIT");
/** {@code PackageGroupPattern}'s own wire pattern: any run of characters that are neither a
* Unicode "Other" category codepoint nor whitespace, 2-520 characters long. Deliberately not
* reused from {@link #PACKAGE_TOKEN}: that pattern forbids {@code #}/{@code /}/whitespace,
* but a package group pattern's own {@code /}-separated shape and {@code $}/{@code ~}/{@code *}
* terminators are exactly what {@link PackageGroupPatterns#parse} exists to interpret, so this
* only rejects what AWS itself rejects at the wire level, leaving syntax validation to parse().
*/
private static final Pattern PACKAGE_GROUP_PATTERN_TOKEN = Pattern.compile("[^\\p{C}\\p{IsWhitespace}]+");
private static final Logger LOG = Logger.getLogger(CodeArtifactService.class);
private static final Pattern DOMAIN_NAME = Pattern.compile("[a-z][a-z0-9\\-]{0,48}[a-z0-9]");
@@ -207,11 +226,34 @@ public class CodeArtifactService implements Resettable {
public record AuthorizationTokenScope(String owner, String region) {}
private record AuthorizationTokenRecord(String owner, String region, String domain, Instant expiration) {}
// ------------------------------------------------------------- package groups (views)
public record PackageGroupOriginRestrictionView(String mode, String effectiveMode, String inheritedFromArn,
String inheritedFromPattern, long repositoriesCount) {}
public record PackageGroupDescriptionView(String arn, String pattern, String domainName, String domainOwner,
long createdTime, String contactInfo, String description,
Map<String, PackageGroupOriginRestrictionView> restrictions, String parentArn, String parentPattern) {}
public record PackageGroupListResult(List<PackageGroupDescriptionView> packageGroups, String nextToken) {}
public record ListAllowedRepositoriesForGroupResult(List<String> allowedRepositories, String nextToken) {}
public record AssociatedPackageView(String format, String namespace, String packageName, String associationType) {}
public record ListAssociatedPackagesResult(List<AssociatedPackageView> packages, String nextToken) {}
public record GetAssociatedPackageGroupResult(PackageGroupDescriptionView packageGroup, String associationType) {}
public record UpdatePackageGroupOriginConfigurationResult(PackageGroupDescriptionView packageGroup,
Map<String, Map<String, List<String>>> allowedRepositoryUpdates) {}
/** The most specific existing group whose pattern matches a package path, with how strongly
* it matched; {@code null} fields are never used, {@link Optional#empty} models "no group in
* this domain matches this package at all" (see {@link #findAssociatedGroup}'s own javadoc). */
private record AssociatedGroupMatch(PackageGroup group, PackageGroupPatterns.MatchStrength strength) {}
/** One restriction type's resolved mode for a group, and the ancestor it was inherited from
* (if any) — see {@link #resolveEffectiveMode}'s own javadoc. */
private record EffectiveModeResult(String mode, PackageGroup inheritedFrom) {}
private final AccountAwareStorageBackend<CodeArtifactDomain> domains;
private final AccountAwareStorageBackend<CodeArtifactRepository> repositories;
private final AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersions;
private final AccountAwareStorageBackend<PackageOriginConfig> packageOriginConfigs;
private final Set<String> migratedOriginConfigAccounts = new HashSet<>();
private final AccountAwareStorageBackend<PackageGroup> packageGroups;
private final RegionResolver regionResolver;
private final EmulatorConfig config;
private final CodeArtifactSidecarRegistry sidecarRegistry;
@@ -390,6 +432,8 @@ public class CodeArtifactService implements Resettable {
new TypeReference<Map<String, CodeArtifactPackageVersion>>() {}),
storageFactory.create("codeartifact", "codeartifact-package-origin-configs.json",
new TypeReference<Map<String, PackageOriginConfig>>() {}),
storageFactory.create("codeartifact", "codeartifact-package-groups.json",
new TypeReference<Map<String, PackageGroup>>() {}),
regionResolver, config,
"memory".equals(serviceConfigAccess.storageMode("codeartifact")),
Path.of(config.storage().persistentPath()).resolve(ASSET_STORAGE_DIR),
@@ -401,12 +445,14 @@ public class CodeArtifactService implements Resettable {
AccountAwareStorageBackend<CodeArtifactRepository> repositories,
AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersions,
AccountAwareStorageBackend<PackageOriginConfig> packageOriginConfigs,
AccountAwareStorageBackend<PackageGroup> packageGroups,
RegionResolver regionResolver, EmulatorConfig config,
boolean inMemory, Path assetRoot, CodeArtifactSidecarRegistry sidecarRegistry) {
this.domains = domains;
this.repositories = repositories;
this.packageVersions = packageVersions;
this.packageOriginConfigs = packageOriginConfigs;
this.packageGroups = packageGroups;
this.regionResolver = regionResolver;
this.config = config;
this.sidecarRegistry = sidecarRegistry;
@@ -463,6 +509,17 @@ public class CodeArtifactService implements Resettable {
+ "until they are deleted.", domain, "domain");
}
domains.deleteForAccount(owner, key);
// Unlike packageOriginConfigs/packageVersions (repository-scoped, already cleaned up by
// deleteRepository above this point in the call chain), package groups are domain-scoped
// and outlive every repository in the domain being gone: without this, a domain deleted
// and recreated under the same name would inherit the previous one's package groups,
// including a PUBLISH/EXTERNAL_UPSTREAM BLOCK that would reject a publish or retention
// with no way for the caller to know why, and creating a group under an old pattern would
// fail as a duplicate.
String groupPrefix = region + "::" + domain + "::";
packageGroups.keysForAccount(owner).stream()
.filter(k -> k.startsWith(groupPrefix))
.forEach(k -> packageGroups.deleteForAccount(owner, k));
return new DomainView(d, 0, 0L);
}
@@ -2329,6 +2386,17 @@ public class CodeArtifactService implements Resettable {
* the same config {@link #putPackageOriginConfiguration} and {@link
* #isUpstreamRetentionBlocked} key by for a format (nuget, pypi) whose names are
* case/punctuation normalized.
*
* <p>Both the generic {@link #publishPackageVersion} and every native proxy controller (via
* {@link #requireContainerBackedPackagePublishAllowed}) call this one method before their own
* real write, so the package-level check below and the package-group check that follows it
* apply identically regardless of format. Raised by Qodo's review of this PR: the group check
* originally lived inline in {@code publishPackageVersionLocked} (the generic-only caller),
* so {@code mvn deploy}/{@code npm publish}/{@code twine upload}/{@code dotnet nuget push}
* could publish straight past a package group's {@code PUBLISH: BLOCK}, allow-list, or
* weak-match block. Moving it here, below the package-level check both callers already
* shared, closes that gap for every format at once instead of duplicating the check in each
* native controller.
*/
private void requireDirectPublishAllowed(String owner, String region, String domain, String repository,
String format, String namespace, String packageName) {
@@ -2341,6 +2409,29 @@ public class CodeArtifactService implements Resettable {
throw conflict("Package '" + packageName + "' cannot be published because its origin configuration "
+ "blocks direct publish.", packageName, "package");
}
// The package's own origin configuration isn't BLOCK (just enforced above), which the
// User Guide describes as "effectively deferring to the associated package group's
// origin control settings": resolve this package's associated group (if any) and apply
// "How package origin controls interact with package group origin controls" (BLOCK
// always wins over ALLOW). A weak match (see PackageGroupPatterns' own javadoc) is
// blocked outright, regardless of the group's configured mode, as CodeArtifact's defense
// against a dependency-confusion attack that spells a package to just barely dodge a
// strong match.
List<PackageGroup> groupsInDomain = allPackageGroupsInDomain(owner, region, domain);
Optional<AssociatedGroupMatch> associatedGroup = findAssociatedGroup(groupsInDomain,
PackageGroupPatterns.packagePath(format, namespace, packageName));
if (associatedGroup.isPresent()) {
if (associatedGroup.get().strength() == PackageGroupPatterns.MatchStrength.WEAK) {
throw conflict("Package '" + packageName + "' cannot be published because it only weakly "
+ "matches package group '" + associatedGroup.get().group().getPattern() + "', which "
+ "blocks direct publish for weak matches.", packageName, "package");
}
if (!groupAllowsPublish(groupsInDomain, associatedGroup.get().group(), repository)) {
throw conflict("Package '" + packageName + "' cannot be published because its associated "
+ "package group '" + associatedGroup.get().group().getPattern() + "' blocks direct "
+ "publish for this repository.", packageName, "package");
}
}
}
/**
@@ -3030,6 +3121,17 @@ public class CodeArtifactService implements Resettable {
* real content yet, so it is itself the proof this package's real origin is external,
* without weakening the default block a package that has never had such a claim, and so can
* only have gotten real content from a direct publish, still gets.
*
* <p>Once the package's own setting resolves to allowed, this also defers to the package's
* associated package group's {@code EXTERNAL_UPSTREAM} mode, the same "{@code BLOCK} always
* wins over {@code ALLOW}" interaction {@link #publishPackageVersion}'s own group check
* applies for {@code PUBLISH} (see that method's own javadoc). A weak pattern match (see
* {@link PackageGroupPatterns}' own javadoc) is blocked outright here too: the User Guide's
* package group pattern-matching page states the weak-match block applies to a package
* being "pulled from upstreams" just as much as published, not to {@code PUBLISH} alone.
* {@code INTERNAL_UPSTREAM} is deliberately never resolved here: it gates retention from a
* same-domain upstream repository chain, which this emulator has no real mechanism for yet
* (tracked separately, 16f-UPSTREAM-REPO).
*/
public boolean isUpstreamRetentionBlocked(String region, String domain, String domainOwner, String repository,
String format, String namespace, String packageName) {
@@ -3042,14 +3144,30 @@ public class CodeArtifactService implements Resettable {
String key = packageKey(region, domain, repository, format, namespace,
accountingPackageName(format, packageName));
Optional<PackageOriginConfig> config = packageOriginConfig(owner, key, format);
boolean packageLevelBlocked;
if (config.isPresent()) {
return "BLOCK".equals(config.get().getUpstreamRestriction());
}
if (hasRetainedVersionOriginClaimForAnyVersion(region, domain, owner, repository, format, namespace,
packageLevelBlocked = "BLOCK".equals(config.get().getUpstreamRestriction());
} else if (hasRetainedVersionOriginClaimForAnyVersion(region, domain, owner, repository, format, namespace,
packageName)) {
packageLevelBlocked = false;
} else {
packageLevelBlocked = packageExistsViaVersionsOrSidecar(region, domain, owner, repository, format,
namespace, packageName);
}
if (packageLevelBlocked) {
return true;
}
List<PackageGroup> groupsInDomain = allPackageGroupsInDomain(owner, region, domain);
Optional<AssociatedGroupMatch> associatedGroup = findAssociatedGroup(groupsInDomain,
PackageGroupPatterns.packagePath(format, namespace, packageName));
if (associatedGroup.isEmpty()) {
return false;
}
return packageExistsViaVersionsOrSidecar(region, domain, owner, repository, format, namespace, packageName);
if (associatedGroup.get().strength() == PackageGroupPatterns.MatchStrength.WEAK) {
return true;
}
return !groupAllowsRestriction(groupsInDomain, associatedGroup.get().group(), "EXTERNAL_UPSTREAM",
repository);
}
/**
@@ -5020,11 +5138,448 @@ public class CodeArtifactService implements Resettable {
return Base64Url.encode(bytes);
}
// -------------------------------------------------------------- package groups
/**
* Creates a package group. Per the User Guide, a brand-new group starts with every
* restriction type at {@code INHERIT} (see {@link #resolveEffectiveMode}'s own javadoc for
* how that resolves): nothing is configured here until a caller calls
* {@link #updatePackageGroupOriginConfiguration}.
*/
public synchronized PackageGroupDescriptionView createPackageGroup(String region, String domain,
String domainOwner, String pattern, String contactInfo, String description, Map<String, String> tags) {
validatePackageGroupPattern(pattern);
validateDescription(description);
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
String key = packageGroupKey(region, domain, pattern);
requireDomain(owner, domainKey(region, domain), domain);
if (packageGroups.getForAccount(owner, key).isPresent()) {
throw conflict("A package group with pattern '" + pattern + "' already exists.", pattern,
"package-group");
}
// Unlike domains and repositories (MAX_DOMAINS_PER_ACCOUNT, repositoryCountForDomain's own
// caller), the real CodeArtifact quotas page publishes no numbered "package groups per
// domain" limit at all (confirmed against docs.aws.amazon.com/codeartifact/latest/ug/
// service-limits.html's full table), so there is no documented threshold to enforce here.
String arn = regionResolver.buildArn("codeartifact", region, "package-group/" + domain + pattern);
PackageGroup group = new PackageGroup(pattern, arn, domain, owner, region, contactInfo, description,
Instant.now().getEpochSecond());
group.setTags(validateTags(tags, Map.of(), pattern, "package-group"));
packageGroups.putForAccount(owner, key, group);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
return toDescriptionView(all, group);
}
public synchronized PackageGroupDescriptionView deletePackageGroup(String region, String domain,
String domainOwner, String pattern) {
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
String key = packageGroupKey(region, domain, pattern);
PackageGroup group = requirePackageGroup(owner, key, pattern);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
// Computed before the delete removes it from storage: DeletePackageGroup's own documented
// behavior ("the direct child package groups will become children of the package group's
// direct parent") is a property of the hierarchy as it stood right before this group was
// removed, and the response describes this now-deleted group's own view as it last was.
PackageGroupDescriptionView view = toDescriptionView(all, group);
packageGroups.deleteForAccount(owner, key);
return view;
}
public PackageGroupDescriptionView describePackageGroup(String region, String domain, String domainOwner,
String pattern) {
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
PackageGroup group = requirePackageGroup(owner, packageGroupKey(region, domain, pattern), pattern);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
return toDescriptionView(all, group);
}
/** Unlike every other package group action, this one cannot change {@code pattern} or
* {@code restrictions}: the wire model's own {@code UpdatePackageGroupRequest} carries only
* {@code contactInfo}/{@code description}, confirmed against {@code service-2.json}. */
public synchronized PackageGroupDescriptionView updatePackageGroup(String region, String domain,
String domainOwner, String pattern, String contactInfo, String description) {
validateDescription(description);
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
String key = packageGroupKey(region, domain, pattern);
PackageGroup group = requirePackageGroup(owner, key, pattern);
group.setContactInfo(contactInfo);
group.setDescription(description);
packageGroups.putForAccount(owner, key, group);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
return toDescriptionView(all, group);
}
public synchronized UpdatePackageGroupOriginConfigurationResult updatePackageGroupOriginConfiguration(
String region, String domain, String domainOwner, String pattern, Map<String, String> restrictions,
List<PackageGroupAllowedRepositoryEdit> addAllowedRepositories,
List<PackageGroupAllowedRepositoryEdit> removeAllowedRepositories) {
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
String key = packageGroupKey(region, domain, pattern);
PackageGroup group = requirePackageGroup(owner, key, pattern);
if (restrictions != null) {
restrictions.forEach((type, mode) -> {
if (!PACKAGE_GROUP_RESTRICTION_TYPES.contains(type)) {
throw validation("restrictions key must be one of " + PACKAGE_GROUP_RESTRICTION_TYPES + ".");
}
if (!PACKAGE_GROUP_MODES.contains(mode)) {
throw validation("restrictions value must be one of " + PACKAGE_GROUP_MODES + ".");
}
});
}
Map<String, PackageGroupRestriction> stored = new LinkedHashMap<>(group.getRestrictions());
Map<String, Map<String, List<String>>> allowedRepositoryUpdates = new LinkedHashMap<>();
if (restrictions != null) {
restrictions.forEach((type, mode) ->
stored.put(type, new PackageGroupRestriction(mode, copyAllowedRepositories(stored.get(type)))));
}
applyAllowedRepositoryEdits(stored, addAllowedRepositories, "ADDED", allowedRepositoryUpdates);
applyAllowedRepositoryEdits(stored, removeAllowedRepositories, "REMOVED", allowedRepositoryUpdates);
group.setRestrictions(stored);
packageGroups.putForAccount(owner, key, group);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
return new UpdatePackageGroupOriginConfigurationResult(toDescriptionView(all, group), allowedRepositoryUpdates);
}
/** One {@code addAllowedRepositories}/{@code removeAllowedRepositories} list entry. */
public record PackageGroupAllowedRepositoryEdit(String repositoryName, String originRestrictionType) {}
/**
* {@code existing}'s own allowed-repository list, copied so a caller can mutate it without
* reaching back into stored state, or a fresh empty list when there is no existing restriction
* to copy from yet. Shared by {@link #updatePackageGroupOriginConfiguration} and {@link
* #applyAllowedRepositoryEdits}, which both start from the same "copy what's there, or start
* empty" rule before making their own edit.
*/
private static List<String> copyAllowedRepositories(PackageGroupRestriction existing) {
return existing == null ? new ArrayList<>() : new ArrayList<>(existing.getAllowedRepositories());
}
private void applyAllowedRepositoryEdits(Map<String, PackageGroupRestriction> stored,
List<PackageGroupAllowedRepositoryEdit> edits, String updateType,
Map<String, Map<String, List<String>>> allowedRepositoryUpdates) {
if (edits == null) {
return;
}
for (PackageGroupAllowedRepositoryEdit edit : edits) {
// Raised by Qodo's review of this PR: PACKAGE_GROUP_RESTRICTION_TYPES is an immutable
// List.of(...), whose contains(null) throws NullPointerException rather than returning
// false, so a request that omits originRestrictionType must be rejected explicitly
// before reaching it, not left to fall through to a 500.
if (edit.originRestrictionType() == null
|| !PACKAGE_GROUP_RESTRICTION_TYPES.contains(edit.originRestrictionType())) {
throw validation("originRestrictionType must be one of " + PACKAGE_GROUP_RESTRICTION_TYPES + ".");
}
validateRepositoryName(edit.repositoryName());
PackageGroupRestriction existing = stored.get(edit.originRestrictionType());
List<String> allowedRepositories = copyAllowedRepositories(existing);
String mode = existing == null ? "INHERIT" : existing.getMode();
if ("ADDED".equals(updateType)) {
if (!allowedRepositories.contains(edit.repositoryName())) {
allowedRepositories.add(edit.repositoryName());
}
} else {
allowedRepositories.remove(edit.repositoryName());
}
stored.put(edit.originRestrictionType(), new PackageGroupRestriction(mode, allowedRepositories));
allowedRepositoryUpdates
.computeIfAbsent(edit.originRestrictionType(), ignored -> new LinkedHashMap<>())
.computeIfAbsent(updateType, ignored -> new ArrayList<>())
.add(edit.repositoryName());
}
}
public PackageGroupListResult listPackageGroups(String region, String domain, String domainOwner,
String prefix, Integer maxResults, String nextToken) {
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
requireDomain(owner, domainKey(region, domain), domain);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
List<PackageGroup> matching = all.stream()
.filter(g -> prefix == null || g.getPattern().startsWith(prefix))
.toList();
PaginatedResult<PackageGroup> page = Pagination.paginate(matching, PackageGroup::getPattern, maxResults,
nextToken, 100, 1000, "ValidationException");
List<PackageGroupDescriptionView> views = page.items().stream().map(g -> toDescriptionView(all, g)).toList();
return new PackageGroupListResult(views, page.nextToken());
}
public PackageGroupListResult listSubPackageGroups(String region, String domain, String domainOwner,
String pattern, Integer maxResults, String nextToken) {
requireNonBlank(domain, "domain");
String owner = effectiveOwner(domainOwner);
PackageGroup group = requirePackageGroup(owner, packageGroupKey(region, domain, pattern), pattern);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
List<PackageGroup> children = all.stream()
.filter(candidate -> !candidate.getPattern().equals(group.getPattern()))
.filter(candidate -> findParent(all, parsedPattern(candidate))
.map(PackageGroup::getPattern).filter(p -> p.equals(group.getPattern())).isPresent())
.toList();
PaginatedResult<PackageGroup> page = Pagination.paginate(children, PackageGroup::getPattern, maxResults,
nextToken, 100, 1000, "ValidationException");
List<PackageGroupDescriptionView> views = page.items().stream().map(g -> toDescriptionView(all, g)).toList();
return new PackageGroupListResult(views, page.nextToken());
}
public ListAllowedRepositoriesForGroupResult listAllowedRepositoriesForGroup(String region, String domain,
String domainOwner, String pattern, String originRestrictionType, Integer maxResults, String nextToken) {
requireNonBlank(domain, "domain");
if (originRestrictionType == null || !PACKAGE_GROUP_RESTRICTION_TYPES.contains(originRestrictionType)) {
throw validation("originRestrictionType must be one of " + PACKAGE_GROUP_RESTRICTION_TYPES + ".");
}
String owner = effectiveOwner(domainOwner);
PackageGroup group = requirePackageGroup(owner, packageGroupKey(region, domain, pattern), pattern);
PackageGroupRestriction restriction = group.getRestrictions().get(originRestrictionType);
List<String> repositories = restriction == null ? List.of() : restriction.getAllowedRepositories();
PaginatedResult<String> page = Pagination.paginate(repositories, Function.identity(), maxResults, nextToken,
100, 1000, "ValidationException");
return new ListAllowedRepositoriesForGroupResult(page.items(), page.nextToken());
}
public ListAssociatedPackagesResult listAssociatedPackages(String region, String domain, String domainOwner,
String pattern, Integer maxResults, String nextToken, boolean preview) {
requireNonBlank(domain, "domain");
validatePackageGroupPattern(pattern);
String owner = effectiveOwner(domainOwner);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
if (!preview) {
requirePackageGroup(owner, packageGroupKey(region, domain, pattern), pattern);
}
PackageGroupPatterns.ParsedPattern target = PackageGroupPatterns.parse(pattern);
List<AssociatedPackageView> associated = new ArrayList<>();
for (PackageCoordinate coordinate : allPackageCoordinatesInDomain(owner, region, domain)) {
PackageGroupPatterns.PackagePath path = PackageGroupPatterns.packagePath(coordinate.format(),
coordinate.namespace(), coordinate.packageName());
Optional<AssociatedGroupMatch> match = findAssociatedGroup(all, path);
// preview=true answers "what would be associated with this pattern if it existed",
// so a package only counts if this hypothetical pattern would actually win the
// specificity contest against every group that is already real.
PackageGroupPatterns.MatchStrength targetStrength = PackageGroupPatterns.matchStrength(target, path);
if (targetStrength == null) {
continue;
}
boolean targetWins = match.isEmpty()
|| PackageGroupPatterns.compareSpecificity(target, parsedPattern(match.get().group())) > 0
|| match.get().group().getPattern().equals(pattern);
if (!targetWins) {
continue;
}
associated.add(new AssociatedPackageView(coordinate.format(), coordinate.namespace(),
coordinate.packageName(), targetStrength.name()));
}
PaginatedResult<AssociatedPackageView> page = Pagination.paginate(associated,
v -> v.format() + "::" + escapeKeySegment(v.namespace()) + "::" + escapeKeySegment(v.packageName()),
maxResults, nextToken, 100, 1000, "ValidationException");
return new ListAssociatedPackagesResult(page.items(), page.nextToken());
}
public GetAssociatedPackageGroupResult getAssociatedPackageGroup(String region, String domain,
String domainOwner, String format, String namespace, String packageName) {
requireNonBlank(domain, "domain");
if (format == null || !PACKAGE_FORMATS.contains(format)) {
throw validation("format must be one of " + PACKAGE_FORMATS + ".");
}
requireNonBlank(packageName, "package");
String owner = effectiveOwner(domainOwner);
requireDomain(owner, domainKey(region, domain), domain);
List<PackageGroup> all = allPackageGroupsInDomain(owner, region, domain);
PackageGroupPatterns.PackagePath path = PackageGroupPatterns.packagePath(format, namespace, packageName);
AssociatedGroupMatch match = findAssociatedGroup(all, path)
.orElseThrow(() -> notFound("No package group in domain '" + domain + "' is associated with "
+ "package '" + packageName + "'.", packageName, "package"));
return new GetAssociatedPackageGroupResult(toDescriptionView(all, match.group()), match.strength().name());
}
private List<PackageGroup> allPackageGroupsInDomain(String owner, String region, String domain) {
String prefix = region + "::" + domain + "::";
return packageGroups.scanForAccount(owner, k -> k.startsWith(prefix));
}
private static PackageGroupPatterns.ParsedPattern parsedPattern(PackageGroup group) {
return PackageGroupPatterns.parse(group.getPattern());
}
/**
* The most specific OTHER group in {@code all} that structurally contains {@code pattern}
* (every package {@code pattern} can ever match also matches that other group), per the User
* Guide's own hierarchy rule: "a group's parent is the most specific other existing group
* that is a strict superset." Recomputed from the current set of groups on every call rather
* than stored, since {@link #deletePackageGroup}'s own documented behavior (children
* reparent onto the deleted group's own parent) means this relationship is never stable
* across a create/delete elsewhere in the domain.
*/
private Optional<PackageGroup> findParent(List<PackageGroup> all, PackageGroupPatterns.ParsedPattern pattern) {
PackageGroup best = null;
PackageGroupPatterns.ParsedPattern bestParsed = null;
for (PackageGroup candidate : all) {
PackageGroupPatterns.ParsedPattern candidateParsed = parsedPattern(candidate);
if (!PackageGroupPatterns.isStrictAncestor(candidateParsed, pattern)) {
continue;
}
if (best == null || PackageGroupPatterns.compareSpecificity(candidateParsed, bestParsed) > 0) {
best = candidate;
bestParsed = candidateParsed;
}
}
return Optional.ofNullable(best);
}
/**
* The single group a package is associated with: the most specific group in {@code all}
* whose pattern matches {@code path} at all (strong or weak), per the User Guide's own
* "a package is associated with exactly one package group" rule. {@link Optional#empty}
* models a domain where no created group's pattern reaches this package at all — real
* CodeArtifact has no implicit catch-all root group (confirmed by {@code
* GetAssociatedPackageGroup}'s own documented {@code ResourceNotFoundException}), so callers
* must treat that as "this package has no group," not fall back to a synthesized default.
*/
private Optional<AssociatedGroupMatch> findAssociatedGroup(List<PackageGroup> all,
PackageGroupPatterns.PackagePath path) {
PackageGroup best = null;
PackageGroupPatterns.ParsedPattern bestParsed = null;
PackageGroupPatterns.MatchStrength bestStrength = null;
for (PackageGroup candidate : all) {
PackageGroupPatterns.ParsedPattern candidateParsed = parsedPattern(candidate);
PackageGroupPatterns.MatchStrength strength = PackageGroupPatterns.matchStrength(candidateParsed, path);
if (strength == null) {
continue;
}
int rank = best == null ? 1 : PackageGroupPatterns.compareSpecificity(candidateParsed, bestParsed);
// Raised by Qodo's review of this PR: two patterns can tie on specificity while
// differing only by case or separators (e.g. /npm//foo$ and /npm//Foo$), in which case
// whichever happened to be scanned first used to win regardless of match strength. A
// package that strongly matches one of them must prefer that one over a tied-rank
// pattern it only weakly matches, so its enforcement isn't decided by storage order.
boolean strongDisplacesWeakTie = rank == 0 && strength == PackageGroupPatterns.MatchStrength.STRONG
&& bestStrength == PackageGroupPatterns.MatchStrength.WEAK;
if (best == null || rank > 0 || strongDisplacesWeakTie) {
best = candidate;
bestParsed = candidateParsed;
bestStrength = strength;
}
}
return best == null ? Optional.empty() : Optional.of(new AssociatedGroupMatch(best, bestStrength));
}
/**
* Resolves {@code restrictionType}'s real effective mode for {@code group}, walking up to its
* nearest ancestor with a concrete (non-{@code INHERIT}) setting, per {@code
* PackageGroupOriginRestriction}'s own documented resolution rule ("the first parent group
* which does not have a value of INHERIT"). A brand-new group, and the top of any hierarchy
* that never set this restriction type at all, defaults to {@code ALLOW}: not directly stated
* for this exact case, but the only reading consistent with the User Guide's "Default package
* origin control settings" section, which describes a package associated with such a group as
* seeing {@code ALLOW} for every restriction type.
*/
private EffectiveModeResult resolveEffectiveMode(List<PackageGroup> all, PackageGroup group,
String restrictionType) {
PackageGroup current = group;
while (true) {
PackageGroupRestriction restriction = current.getRestrictions().get(restrictionType);
String mode = restriction == null ? "INHERIT" : restriction.getMode();
if (!"INHERIT".equals(mode)) {
return new EffectiveModeResult(mode, current == group ? null : current);
}
Optional<PackageGroup> parent = findParent(all, parsedPattern(current));
if (parent.isEmpty()) {
return new EffectiveModeResult("ALLOW", null);
}
current = parent.get();
}
}
private Map<String, PackageGroupOriginRestrictionView> buildRestrictionsView(List<PackageGroup> all,
PackageGroup group) {
Map<String, PackageGroupOriginRestrictionView> views = new LinkedHashMap<>();
for (String type : PACKAGE_GROUP_RESTRICTION_TYPES) {
PackageGroupRestriction stored = group.getRestrictions().get(type);
String rawMode = stored == null ? "INHERIT" : stored.getMode();
EffectiveModeResult effective = resolveEffectiveMode(all, group, type);
long repositoriesCount = stored == null ? 0 : stored.getAllowedRepositories().size();
String inheritedFromArn = effective.inheritedFrom() == null ? null : effective.inheritedFrom().getArn();
String inheritedFromPattern = effective.inheritedFrom() == null ? null
: effective.inheritedFrom().getPattern();
views.put(type, new PackageGroupOriginRestrictionView(rawMode, effective.mode(), inheritedFromArn,
inheritedFromPattern, repositoriesCount));
}
return views;
}
private PackageGroupDescriptionView toDescriptionView(List<PackageGroup> all, PackageGroup group) {
Optional<PackageGroup> parent = findParent(all, parsedPattern(group));
return new PackageGroupDescriptionView(group.getArn(), group.getPattern(), group.getDomainName(),
group.getDomainOwner(), group.getCreatedTime(), group.getContactInfo(), group.getDescription(),
buildRestrictionsView(all, group), parent.map(PackageGroup::getArn).orElse(null),
parent.map(PackageGroup::getPattern).orElse(null));
}
/**
* Resolves {@code group}'s own effective {@code PUBLISH} mode for {@code repository}, folding
* in {@code ALLOW_SPECIFIC_REPOSITORIES}'s own per-repository allow-list: used by {@link
* #publishPackageVersion} to decide a direct publish once the package's own origin
* configuration has already deferred to its group (see that method's own javadoc for the
* full "BLOCK always wins" interaction this is one half of).
*/
private boolean groupAllowsPublish(List<PackageGroup> all, PackageGroup group, String repository) {
return groupAllowsRestriction(all, group, "PUBLISH", repository);
}
/**
* Resolves {@code group}'s own effective mode for {@code restrictionType} (one of {@code
* PUBLISH}, {@code EXTERNAL_UPSTREAM}, {@code INTERNAL_UPSTREAM}), folding in {@code
* ALLOW_SPECIFIC_REPOSITORIES}'s own per-repository allow-list: the User Guide's package
* group origin controls page documents the exact same three modes, the same allow-list
* shape, for all three restriction types alike, not something specific to {@code PUBLISH}.
*/
private boolean groupAllowsRestriction(List<PackageGroup> all, PackageGroup group, String restrictionType,
String repository) {
EffectiveModeResult effective = resolveEffectiveMode(all, group, restrictionType);
return switch (effective.mode()) {
case "ALLOW" -> true;
case "BLOCK" -> false;
case "ALLOW_SPECIFIC_REPOSITORIES" -> {
// Raised by Qodo's review of this PR: ALLOW_SPECIFIC_REPOSITORIES can itself be an
// INHERITed mode (resolveEffectiveMode walked up to inheritedFrom to find it), in
// which case the allow-list living on it belongs to that ancestor, not to `group`
// itself, which has no restriction of its own here at all (its own mode was
// INHERIT). Reading group's own (absent) restriction instead of the ancestor's
// rejected every repository the ancestor actually allowed.
PackageGroup source = effective.inheritedFrom() == null ? group : effective.inheritedFrom();
PackageGroupRestriction restriction = source.getRestrictions().get(restrictionType);
yield restriction != null && restriction.getAllowedRepositories().contains(repository);
}
default -> throw new IllegalStateException("resolveEffectiveMode must never return " + effective.mode());
};
}
/** Every (format, namespace, packageName) coordinate with at least one real package anywhere
* in {@code domain}, across every repository, for {@link #listAssociatedPackages}: package
* groups are domain-wide, so association is checked against every package the domain holds,
* not just one repository's. */
private List<PackageCoordinate> allPackageCoordinatesInDomain(String owner, String region, String domain) {
Set<PackageCoordinate> coordinates = new LinkedHashSet<>();
String repositoryPrefix = region + "::" + domain + "::";
for (CodeArtifactRepository repository : repositories.scanForAccount(owner, k -> k.startsWith(repositoryPrefix))) {
coordinates.addAll(allPackagesInRepository(region, domain, owner, owner, repository.getName(), null)
.coordinates());
}
return new ArrayList<>(coordinates);
}
// -------------------------------------------------------------------- tags
public synchronized void tagResource(String resourceArn, Map<String, String> newTags) {
ResourceRef ref = parseResourceArn(resourceArn);
if (ref.repository() == null) {
if ("package-group".equals(ref.type())) {
String key = packageGroupKey(ref.region(), ref.domain(), ref.packageGroupPattern());
PackageGroup g = requirePackageGroup(ref.owner(), key, ref.packageGroupPattern());
g.setTags(validateTags(newTags, g.getTags(), ref.packageGroupPattern(), "package-group"));
packageGroups.putForAccount(ref.owner(), key, g);
} else if (ref.repository() == null) {
String key = domainKey(ref.region(), ref.domain());
CodeArtifactDomain d = requireDomain(ref.owner(), key, ref.domain());
d.setTags(validateTags(newTags, d.getTags(), ref.domain(), "domain"));
@@ -5039,7 +5594,14 @@ public class CodeArtifactService implements Resettable {
public synchronized void untagResource(String resourceArn, List<String> tagKeys) {
ResourceRef ref = parseResourceArn(resourceArn);
if (ref.repository() == null) {
if ("package-group".equals(ref.type())) {
String key = packageGroupKey(ref.region(), ref.domain(), ref.packageGroupPattern());
PackageGroup g = requirePackageGroup(ref.owner(), key, ref.packageGroupPattern());
Map<String, String> tags = new LinkedHashMap<>(g.getTags());
tagKeys.forEach(tags::remove);
g.setTags(tags);
packageGroups.putForAccount(ref.owner(), key, g);
} else if (ref.repository() == null) {
String key = domainKey(ref.region(), ref.domain());
CodeArtifactDomain d = requireDomain(ref.owner(), key, ref.domain());
Map<String, String> tags = new LinkedHashMap<>(d.getTags());
@@ -5058,6 +5620,10 @@ public class CodeArtifactService implements Resettable {
public Map<String, String> listTagsForResource(String resourceArn) {
ResourceRef ref = parseResourceArn(resourceArn);
if ("package-group".equals(ref.type())) {
return requirePackageGroup(ref.owner(), packageGroupKey(ref.region(), ref.domain(),
ref.packageGroupPattern()), ref.packageGroupPattern()).getTags();
}
if (ref.repository() == null) {
return requireDomain(ref.owner(), domainKey(ref.region(), ref.domain()), ref.domain()).getTags();
}
@@ -5074,6 +5640,7 @@ public class CodeArtifactService implements Resettable {
packageOriginConfigs.clear();
migratedOriginConfigAccounts.clear();
}
packageGroups.clear();
containerBackedAssetBytes.clear();
containerBackedPackageDeletionFence.clear();
containerBackedVersionDeletionFence.clear();
@@ -5092,7 +5659,8 @@ public class CodeArtifactService implements Resettable {
// ----------------------------------------------------------------- helpers
private record ResourceRef(String type, String region, String owner, String domain, String repository) {}
private record ResourceRef(String type, String region, String owner, String domain, String repository,
String packageGroupPattern) {}
private ResourceRef parseResourceArn(String resourceArn) {
AwsArnUtils.Arn arn;
@@ -5104,14 +5672,23 @@ public class CodeArtifactService implements Resettable {
if (!"codeartifact".equals(arn.service())) {
throw validation("resourceArn must be a CodeArtifact ARN.");
}
String[] parts = arn.resource().split("/");
// split(..., -1) keeps a trailing empty segment, since a package group pattern can itself
// end in a '/' component (a namespace-less format's pattern, e.g. "/python//requests$"),
// which the default split() would otherwise silently drop.
String[] parts = arn.resource().split("/", -1);
if (parts.length == 2 && "domain".equals(parts[0])) {
return new ResourceRef("domain", arn.region(), arn.accountId(), parts[1], null);
return new ResourceRef("domain", arn.region(), arn.accountId(), parts[1], null, null);
}
if (parts.length == 3 && "repository".equals(parts[0])) {
return new ResourceRef("repository", arn.region(), arn.accountId(), parts[1], parts[2]);
return new ResourceRef("repository", arn.region(), arn.accountId(), parts[1], parts[2], null);
}
throw validation("resourceArn must reference a domain or a repository.");
if (parts.length >= 3 && "package-group".equals(parts[0])) {
// The pattern's own literal '/' separators were split apart along with the ARN's;
// rejoin everything after the domain and restore the pattern's leading '/'.
String pattern = "/" + String.join("/", Arrays.asList(parts).subList(2, parts.length));
return new ResourceRef("package-group", arn.region(), arn.accountId(), parts[1], null, pattern);
}
throw validation("resourceArn must reference a domain, a repository, or a package group.");
}
private String effectiveOwner(String domainOwner) {
@@ -5488,6 +6065,30 @@ public class CodeArtifactService implements Resettable {
.orElseThrow(() -> notFound("Repository not found.", repositoryName, "repository"));
}
private PackageGroup requirePackageGroup(String owner, String key, String pattern) {
if (pattern == null || pattern.isBlank()) {
throw validation("packageGroup is required.");
}
return packageGroups.getForAccount(owner, key)
.orElseThrow(() -> notFound("Package group with pattern '" + pattern + "' was not found.",
pattern, "package-group"));
}
private static void validatePackageGroupPattern(String pattern) {
if (pattern == null || pattern.length() < 2 || pattern.length() > 520
|| !PACKAGE_GROUP_PATTERN_TOKEN.matcher(pattern).matches()) {
throw validation("packageGroup must be 2-520 characters with no control characters or whitespace.");
}
// Surfaces a malformed pattern (missing '/', bad terminator, too many components) as a
// clean ValidationException up front, rather than letting it reach matching/hierarchy
// logic later and fail in a way that looks like an internal error.
try {
PackageGroupPatterns.parse(pattern);
} catch (IllegalArgumentException e) {
throw validation("packageGroup pattern is invalid: " + e.getMessage());
}
}
private void checkRevision(String currentRevision, String requestedRevision, String resourceId,
String resourceType) {
if (requestedRevision != null && !requestedRevision.equals(currentRevision)) {
@@ -5912,32 +6513,49 @@ public class CodeArtifactService implements Resettable {
}
/**
* Escapes a namespace/package/version segment before it goes into a {@code ::}-joined storage
* key. {@code region}/{@code domain}/{@code repository}/{@code format} never need this: they're
* each validated against a pattern that already excludes {@code :}. Namespace, package name, and
* version are different, {@link #PACKAGE_TOKEN} only excludes {@code #}, {@code /}, and
* whitespace, so {@code ::} itself is a legal character sequence in any of them. Without
* escaping, namespace {@code "a::b"} + package {@code "c"} and namespace {@code "a"} + package
* {@code "b::c"} join to the identical key, so one package's stored origin configuration (or
* published version) silently answers for the other.
* {@code escapeKeySegment} applies here too: {@code PackageGroupPattern}'s own wire regex
* ({@code [^\p{C}\p{IsWhitespace}]+}) does not forbid {@code :} or {@code #}, unlike
* {@link #PACKAGE_TOKEN}, so a pattern containing {@code ::} or a literal {@code #} could
* otherwise collide with this store's own {@code ::}-joined key separator, or with this
* method's own escape introducer (see that method's own javadoc for why escaping {@code #}
* too keeps this safe).
*/
private static String packageGroupKey(String region, String domain, String pattern) {
return region + "::" + domain + "::" + escapeKeySegment(pattern);
}
/**
* Escapes a namespace/package/version segment, or a package-group pattern, before it goes
* into a {@code ::}-joined storage key. {@code region}/{@code domain}/{@code repository}/
* {@code format} never need this: they're each validated against a pattern that already
* excludes {@code :}. Namespace, package name, and version are different: {@link
* #PACKAGE_TOKEN} only excludes {@code #}, {@code /}, and whitespace, so {@code ::} itself is
* a legal character sequence in any of them. Without escaping, namespace {@code "a::b"} +
* package {@code "c"} and namespace {@code "a"} + package {@code "b::c"} join to the
* identical key, so one package's stored origin configuration (or published version) silently
* answers for the other. A package-group pattern (see {@link #packageGroupKey}) is looser
* still: unlike a namespace/package/version, its own wire pattern permits a literal {@code #}
* or {@code :} outright.
*
* <p>{@code #} is the escape introducer, not {@code \}: every {@code \} becomes {@code #b} and
* every {@code :} becomes {@code #c}. {@code #} is itself one of the three characters
* {@link #PACKAGE_TOKEN} (and AWS's own {@code PackageName}/{@code PackageNamespace} wire
* pattern) forbids, so no namespace/package/version ever validated through this service, before
* or after this method existed, can contain one. An escaped segment therefore never collides
* with a pre-existing stored key built from a segment that happened to contain a literal
* backslash: that old raw key cannot contain {@code #}, and this method's output only does when
* it actually escaped something. For the overwhelming majority of packages, whose
* namespace/name/version never contain a backslash or colon, this returns the input unchanged,
* so the key built from those segments is byte-identical to the one built before this method
* existed.
* <p>{@code #} is the escape introducer, not {@code \}: every {@code \} becomes {@code #b},
* every {@code :} becomes {@code #c}, and every literal {@code #} becomes {@code #h} (escaping
* the introducer itself, not just the two characters it was first added for). Raised by
* Qodo's review of this PR: before this, a literal {@code #} passed through unescaped, so
* pattern {@code /npm//#c$} (literal {@code #} then {@code c}) and pattern {@code /npm//:$}
* (a literal {@code :}, escaped to {@code #c}) produced the identical key. Escaping every
* literal {@code #} as well means a bare {@code #} can never appear in this method's output
* except as the first character of one of its own three two-character escape sequences, which
* keeps every output injective: no two distinct inputs can ever produce the same escaped
* string. For namespace/package/version, this is a pure no-op change: {@link #PACKAGE_TOKEN}
* already forbids {@code #} there, so no existing stored key built from one of those segments
* can contain a literal {@code #} for this to newly escape, and the output for every such
* segment is byte-identical to what this method returned before.
*/
private static String escapeKeySegment(String value) {
if (value == null) {
return "";
}
if (value.indexOf(':') < 0 && value.indexOf('\\') < 0) {
if (value.indexOf(':') < 0 && value.indexOf('\\') < 0 && value.indexOf('#') < 0) {
return value;
}
StringBuilder escaped = new StringBuilder(value.length() + 4);
@@ -5947,6 +6565,8 @@ public class CodeArtifactService implements Resettable {
escaped.append("#b");
} else if (c == ':') {
escaped.append("#c");
} else if (c == '#') {
escaped.append("#h");
} else {
escaped.append(c);
}
@@ -0,0 +1,303 @@
package io.floci.aws.services.codeartifact;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Package group pattern parsing, matching, and specificity, confirmed against the CodeArtifact
* User Guide's "Package group definition syntax and matching behavior" page rather than inferred:
* a pattern follows a package path's own shape (a leading {@code /}, then up to three
* {@code /}-separated components for format, namespace, and name, in that order), terminated by
* one of three suffix characters that determine how its own last specified component matches:
* {@code $} for an exact match of the full remaining coordinate, {@code ~} for a prefix match on
* a word boundary, or {@code *} (always alone as its own segment) for "every value of this
* component, and everything deeper." A component the pattern never reaches at all (because an
* earlier component already terminated the pattern) is implicitly unconstrained, the same as a
* trailing {@code *} would make it.
*
* <p>Deliberately not modeled: Unicode confusable-character normalization (the User Guide's
* "Additional variations" section mentions it only in passing, as a defense against visually
* similar characters from different alphabets, and implementing it faithfully needs a real
* Unicode confusables table this emulator does not have). Weak-match normalization here only
* casefolds and collapses runs of {@code -}/{@code .}/{@code _} into a single {@code .}, the
* part of that same section with a concrete, testable rule.
*/
final class PackageGroupPatterns {
private PackageGroupPatterns() {
}
/** How the pattern's own last specified component is matched. */
enum TerminalKind { EXACT, PREFIX, WILDCARD }
/** Whether a package matched a pattern exactly as written, or only a casefolded/separator variation of it. */
enum MatchStrength { STRONG, WEAK }
/**
* A package group pattern, parsed once rather than re-parsed on every candidate it is tested
* against. {@code literalSegments} holds every component's own literal text (the terminal
* component's text has its suffix character already stripped); every non-terminal component
* is always a plain exact value, never itself carrying a suffix, since only the pattern's own
* last specified component can terminate it.
*/
record ParsedPattern(String raw, List<String> literalSegments, TerminalKind terminalKind) {
int segmentCount() {
return literalSegments.size();
}
}
/**
* A package's own coordinate, reduced to the same three-component shape a pattern describes.
* {@code namespace} is the empty string (never {@code null}) for a namespace-less format, the
* same "blank namespace section" the User Guide describes for a pattern's own namespace
* component in that case, so the two sides compare on equal footing.
*/
record PackagePath(String format, String namespace, String name) {
PackagePath {
namespace = namespace == null ? "" : namespace;
}
}
/**
* Parses {@code pattern} into its component segments and terminal kind. Throws {@link
* IllegalArgumentException} for anything this emulator cannot confidently interpret: no
* leading {@code /}, more than three components, a non-terminal component carrying a suffix
* character, or a terminal component whose suffix is not one of {@code $}/{@code ~}/{@code *}.
* {@code $} is only accepted on the third (name-level) component: the User Guide's own
* examples never show it used to terminate a pattern any shallower than that, and a shallow
* exact match leaves every deeper component just as unconstrained as a trailing {@code *}
* would, which is already how every shown example expresses that instead.
*/
static ParsedPattern parse(String pattern) {
if (pattern == null || !pattern.startsWith("/")) {
throw new IllegalArgumentException("packageGroup pattern must start with '/'.");
}
String[] rawSegments = pattern.substring(1).split("/", -1);
if (rawSegments.length == 0 || rawSegments.length > 3) {
throw new IllegalArgumentException("packageGroup pattern must have between 1 and 3 "
+ "'/'-separated components.");
}
List<String> literalSegments = new ArrayList<>(rawSegments.length);
for (int i = 0; i < rawSegments.length - 1; i++) {
String segment = rawSegments[i];
if (segment.endsWith("$") || segment.endsWith("~") || segment.equals("*")) {
throw new IllegalArgumentException("Only the last component of a packageGroup pattern may end "
+ "with '$', '~', or be '*'.");
}
literalSegments.add(segment);
}
String terminalSegment = rawSegments[rawSegments.length - 1];
TerminalKind terminalKind;
String terminalLiteral;
if (terminalSegment.equals("*")) {
terminalKind = TerminalKind.WILDCARD;
terminalLiteral = "";
} else if (terminalSegment.endsWith("~") && terminalSegment.length() > 1) {
terminalKind = TerminalKind.PREFIX;
terminalLiteral = terminalSegment.substring(0, terminalSegment.length() - 1);
} else if (terminalSegment.endsWith("$") && terminalSegment.length() > 1) {
if (rawSegments.length != 3) {
throw new IllegalArgumentException("A packageGroup pattern can only end with '$' when it "
+ "specifies format, namespace, and name.");
}
terminalKind = TerminalKind.EXACT;
terminalLiteral = terminalSegment.substring(0, terminalSegment.length() - 1);
} else {
throw new IllegalArgumentException("A packageGroup pattern must end with '$', '~', or '*'.");
}
literalSegments.add(terminalLiteral);
return new ParsedPattern(pattern, literalSegments, terminalKind);
}
/**
* Casefolds and collapses runs of {@code -}/{@code .}/{@code _} into a single {@code .}, the
* documented rule behind weak-match "Additional variations" (confusable-character
* normalization excluded, see this class's own javadoc).
*/
private static String normalizeForWeakMatch(String value) {
return value.toLowerCase(Locale.ROOT).replaceAll("[-._]+", ".");
}
/**
* Whether {@code candidate} starts with {@code prefix} and, if it is longer than {@code
* prefix}, the very next character is not itself part of the same "word" (the User Guide's
* own regex, {@code [\p{L}\p{N}][\p{L}\p{N}\p{M}]*}): {@code foo~} matches {@code foo} and
* {@code foo-bar} but not {@code food} or {@code foot}.
*/
private static boolean matchesWordBoundaryPrefix(String candidate, String prefix) {
if (!candidate.startsWith(prefix)) {
return false;
}
if (candidate.length() == prefix.length()) {
return true;
}
char next = candidate.charAt(prefix.length());
return !Character.isLetterOrDigit(next) && Character.getType(next) != Character.NON_SPACING_MARK
&& Character.getType(next) != Character.COMBINING_SPACING_MARK
&& Character.getType(next) != Character.ENCLOSING_MARK;
}
private static boolean componentMatches(ParsedPattern pattern, int index, String candidateComponent,
boolean weak) {
String patternText = pattern.literalSegments().get(index);
String candidateText = weak ? normalizeForWeakMatch(candidateComponent) : candidateComponent;
String patternComparedText = weak ? normalizeForWeakMatch(patternText) : patternText;
boolean isTerminal = index == pattern.segmentCount() - 1;
if (!isTerminal) {
return candidateText.equals(patternComparedText);
}
return switch (pattern.terminalKind()) {
case WILDCARD -> true;
case EXACT -> candidateText.equals(patternComparedText);
case PREFIX -> matchesWordBoundaryPrefix(candidateText, patternComparedText);
};
}
/**
* The strongest way {@code path} matches {@code pattern}, or {@code null} for no match at
* all. Checked strong first, then weak, exactly like {@link #componentMatches} computes each
* independently: a package matching strongly on every component pattern specifies is a
* {@code STRONG} match; one that only matches once every compared component is casefolded and
* separator-normalized is a {@code WEAK} match.
*/
static MatchStrength matchStrength(ParsedPattern pattern, PackagePath path) {
String[] components = {path.format(), path.namespace(), path.name()};
if (pattern.segmentCount() > components.length) {
return null;
}
boolean strong = true;
boolean weak = true;
for (int i = 0; i < pattern.segmentCount(); i++) {
if (!componentMatches(pattern, i, components[i], false)) {
strong = false;
}
if (!componentMatches(pattern, i, components[i], true)) {
weak = false;
}
}
if (strong) {
return MatchStrength.STRONG;
}
return weak ? MatchStrength.WEAK : null;
}
/**
* A pattern's own specificity, for picking the single most specific match among several
* patterns that all match the same package: a deeper pattern (more components specified) is
* always more specific than a shallower one, since every package the deeper one matches also
* matches the shallower one but not the reverse; at the same depth, {@code EXACT} is more
* specific than {@code PREFIX} (a proper subset of it), which is more specific than {@code
* WILDCARD}; two {@code PREFIX} patterns at the same depth rank by their own literal text
* length, since a longer prefix matches a proper subset of what a shorter one does.
*/
static int compareSpecificity(ParsedPattern a, ParsedPattern b) {
if (a.segmentCount() != b.segmentCount()) {
return Integer.compare(a.segmentCount(), b.segmentCount());
}
int kindRank = terminalKindRank(a.terminalKind()) - terminalKindRank(b.terminalKind());
if (kindRank != 0) {
return kindRank;
}
if (a.terminalKind() == TerminalKind.PREFIX) {
String aliteral = a.literalSegments().get(a.segmentCount() - 1);
String bliteral = b.literalSegments().get(b.segmentCount() - 1);
return Integer.compare(aliteral.length(), bliteral.length());
}
return 0;
}
private static int terminalKindRank(TerminalKind kind) {
return switch (kind) {
case WILDCARD -> 0;
case PREFIX -> 1;
case EXACT -> 2;
};
}
/**
* Whether every package {@code descendant} matches also matches {@code ancestor}, with
* {@code descendant} a strict, proper subset: the structural test behind package group
* hierarchy (a group's {@code parent} is the most specific other existing group this returns
* true for), since the real parent/child relationship is a property of the two patterns
* themselves, not something stored on either one directly, and must stay correct as sibling
* groups are freely created and deleted around them.
*
* <p>Compares every literal component through {@link #normalizeForWeakMatch}, the same
* normalization {@link #matchStrength} applies to a package path: the User Guide defines a
* group's parent as the more specific pattern whose own matched packages are "a proper subset
* of the packages that match" the less specific one, and a weakly-matched package is itself
* documented as "associated with the group" it weakly matches, so that subset relationship is
* computed over the same (strong-or-weak) association weak match already grants a package,
* not case/separator-literal text alone. Raised by Qodo's review of this PR: without this, a
* descendant pattern that only case/separator-varies from its true ancestor (e.g.
* {@code /npm/SPACE/foo$} under {@code /npm/space/*}) found no parent at all, so its own
* {@code INHERIT} setting resolved to the top-of-hierarchy {@code ALLOW} default instead of
* the broader group's actual restriction.
*
* <p>Requires {@code descendant} to be <em>strictly</em> more specific than {@code ancestor}
* under {@link #compareSpecificity}'s own existing ranking (segment depth, terminal-kind
* rank, then prefix literal length) before anything else: two patterns normalization makes
* "equal enough" in every component, e.g. {@code /npm//foo$} and {@code /npm//Foo$}, or
* {@code /npm/space/foo$} and {@code /npm/SPACE/foo$}, match the exact same (strong-or-weak)
* package set, not a proper subset of one another, so without this check normalizing the
* component comparisons below would make each pattern call the other its own strict ancestor
* at once. {@link #resolveEffectiveMode}'s {@code INHERIT} walk has no cycle detection and
* loops forever the moment that happens; found by this PR's own regression test for a
* different fix hanging the test run. {@code compareSpecificity} ties at 0 for exactly the
* pairs that pose this risk (same depth, same terminal kind, and for two {@code PREFIX}
* patterns, equal raw literal length) and is strictly positive for every genuine
* specialization (a deeper pattern, a more specific terminal kind, or a longer raw prefix),
* so this rejects every tie without having to special-case which component normalization
* could have caused it.
*/
static boolean isStrictAncestor(ParsedPattern ancestor, ParsedPattern descendant) {
if (ancestor.raw().equals(descendant.raw())) {
return false;
}
if (compareSpecificity(descendant, ancestor) <= 0) {
return false;
}
for (int i = 0; i < ancestor.segmentCount() - 1; i++) {
if (!normalizeForWeakMatch(ancestor.literalSegments().get(i))
.equals(normalizeForWeakMatch(descendant.literalSegments().get(i)))) {
return false;
}
}
int lastIndex = ancestor.segmentCount() - 1;
if (ancestor.terminalKind() == TerminalKind.WILDCARD) {
return true;
}
String ancestorLiteral = normalizeForWeakMatch(ancestor.literalSegments().get(lastIndex));
boolean descendantTerminalHere = descendant.segmentCount() == ancestor.segmentCount();
if (descendantTerminalHere) {
String descendantLiteral = normalizeForWeakMatch(descendant.literalSegments().get(lastIndex));
if (ancestor.terminalKind() == TerminalKind.EXACT) {
// Unreachable in practice: EXACT already has compareSpecificity's highest
// terminal-kind rank, so nothing can be strictly more specific than it at the
// same depth, and EXACT's own segmentCount is already the pattern's maximum
// depth, so the guard above rejects every same-depth pair before reaching here.
// Left in place (rather than asserting it away) because this branch stays
// correct, not just unreachable, if that ranking ever changes.
return descendant.terminalKind() == TerminalKind.EXACT && ancestorLiteral.equals(descendantLiteral);
}
// ancestor.terminalKind() == PREFIX
if (descendant.terminalKind() == TerminalKind.WILDCARD) {
return false;
}
return matchesWordBoundaryPrefix(descendantLiteral, ancestorLiteral);
}
// descendant goes deeper than ancestor's own terminal component, which (being non-terminal
// for descendant) is always a plain literal value there, never a suffix of its own.
String descendantValueHere = normalizeForWeakMatch(descendant.literalSegments().get(lastIndex));
if (ancestor.terminalKind() == TerminalKind.EXACT) {
return ancestorLiteral.equals(descendantValueHere);
}
return matchesWordBoundaryPrefix(descendantValueHere, ancestorLiteral);
}
/** A package path for a format/namespace/name coordinate, for {@link #matchStrength}. */
static PackagePath packagePath(String format, String namespace, String name) {
return new PackagePath(format, namespace, name);
}
}
@@ -0,0 +1,126 @@
package io.floci.aws.services.codeartifact.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A package group: a domain-wide (not per-repository) origin-control policy applied to every
* package whose format/namespace/name coordinate matches {@code pattern}, per the CodeArtifact
* User Guide's own package group definition syntax (see {@code PackageGroupPatterns}). Only three
* restriction types ever appear in {@code restrictions}: {@code PUBLISH}, {@code
* EXTERNAL_UPSTREAM}, and {@code INTERNAL_UPSTREAM}; a type missing from the map has never been
* set and defaults to {@code INHERIT} the same way an explicit entry would, resolved the same way
* {@code CodeArtifactService}'s own effective-mode computation already treats both.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class PackageGroup {
private String pattern;
private String arn;
private String domainName;
private String domainOwner;
private String region;
private String contactInfo;
private String description;
private long createdTime;
private Map<String, PackageGroupRestriction> restrictions = new LinkedHashMap<>();
private Map<String, String> tags = new LinkedHashMap<>();
public PackageGroup() {
}
public PackageGroup(String pattern, String arn, String domainName, String domainOwner, String region,
String contactInfo, String description, long createdTime) {
this.pattern = pattern;
this.arn = arn;
this.domainName = domainName;
this.domainOwner = domainOwner;
this.region = region;
this.contactInfo = contactInfo;
this.description = description;
this.createdTime = createdTime;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getDomainOwner() {
return domainOwner;
}
public void setDomainOwner(String domainOwner) {
this.domainOwner = domainOwner;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getContactInfo() {
return contactInfo;
}
public void setContactInfo(String contactInfo) {
this.contactInfo = contactInfo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(long createdTime) {
this.createdTime = createdTime;
}
public Map<String, PackageGroupRestriction> getRestrictions() {
return restrictions;
}
public void setRestrictions(Map<String, PackageGroupRestriction> restrictions) {
this.restrictions = restrictions;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
}
@@ -0,0 +1,48 @@
package io.floci.aws.services.codeartifact.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
/**
* One restriction type's own stored setting on a {@link PackageGroup}: a mode ({@code ALLOW},
* {@code BLOCK}, {@code ALLOW_SPECIFIC_REPOSITORIES}, or {@code INHERIT}), plus the
* allowed-repository list {@code ALLOW_SPECIFIC_REPOSITORIES} uses. The list is kept even when
* {@code mode} is not {@code ALLOW_SPECIFIC_REPOSITORIES}, the same way real CodeArtifact
* preserves an allowed-repository list across a mode change away from and back to it (confirmed
* against {@code UpdatePackageGroupOriginConfiguration}'s own documented behavior: {@code
* addAllowedRepositories}/{@code removeAllowedRepositories} are independent of {@code
* restrictions} in the same call).
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class PackageGroupRestriction {
private String mode;
private List<String> allowedRepositories = new ArrayList<>();
public PackageGroupRestriction() {
}
public PackageGroupRestriction(String mode, List<String> allowedRepositories) {
this.mode = mode;
this.allowedRepositories = allowedRepositories;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public List<String> getAllowedRepositories() {
return allowedRepositories;
}
public void setAllowedRepositories(List<String> allowedRepositories) {
this.allowedRepositories = allowedRepositories;
}
}
@@ -12,6 +12,7 @@ import io.floci.aws.services.codeartifact.CodeArtifactService.PublishPackageVers
import io.floci.aws.services.codeartifact.model.CodeArtifactDomain;
import io.floci.aws.services.codeartifact.model.CodeArtifactPackageVersion;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.PackageGroup;
import io.floci.aws.services.codeartifact.model.PackageOriginConfig;
import io.floci.aws.testutil.LogCapture;
import org.junit.jupiter.api.Assumptions;
@@ -680,6 +681,8 @@ class CodeArtifactAssetPersistenceTest {
"codeartifact-package-versions.json", new TypeReference<Map<String, CodeArtifactPackageVersion>>() {});
AccountAwareStorageBackend<PackageOriginConfig> packageOriginConfigStore = accountAware(dir,
"codeartifact-package-origin-configs.json", new TypeReference<Map<String, PackageOriginConfig>>() {});
AccountAwareStorageBackend<PackageGroup> packageGroupStore = accountAware(dir,
"codeartifact-package-groups.json", new TypeReference<Map<String, PackageGroup>>() {});
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
@@ -691,7 +694,7 @@ class CodeArtifactAssetPersistenceTest {
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
return new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore,
regionResolver, config, false, dir.resolve("codeartifact-assets"),
packageGroupStore, regionResolver, config, false, dir.resolve("codeartifact-assets"),
persistenceSidecars());
}
@@ -9,12 +9,20 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationToken;
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.floci.aws.services.codeartifact.CodeArtifactService.DomainView;
import io.floci.aws.services.codeartifact.CodeArtifactService.GetAssociatedPackageGroupResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ListAllowedRepositoriesForGroupResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ListAssociatedPackagesResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupAllowedRepositoryEdit;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupDescriptionView;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageGroupListResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PackageVersionAssetResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.PublishPackageVersionResult;
import io.floci.aws.services.codeartifact.CodeArtifactService.ResourcePolicy;
import io.floci.aws.services.codeartifact.CodeArtifactService.UpdatePackageGroupOriginConfigurationResult;
import io.floci.aws.services.codeartifact.model.CodeArtifactDomain;
import io.floci.aws.services.codeartifact.model.CodeArtifactPackageVersion;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.PackageGroup;
import io.floci.aws.services.codeartifact.model.PackageOriginConfig;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
@@ -104,6 +112,7 @@ class CodeArtifactServiceTest {
AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersionStore =
AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
packageOriginConfigStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
AccountAwareStorageBackend<PackageGroup> packageGroupStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
@@ -123,7 +132,7 @@ class CodeArtifactServiceTest {
bagetterClient = mock(BagetterSidecarClient.class);
when(bagetterClient.format()).thenReturn("nuget");
service = new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore,
regionResolver, config, true, null, new CodeArtifactSidecarRegistry(
packageGroupStore, regionResolver, config, true, null, new CodeArtifactSidecarRegistry(
List.of(verdaccioClient, reposiliteClient, pypiserverClient, bagetterClient)));
}
@@ -1186,6 +1195,40 @@ class CodeArtifactServiceTest {
"widget");
}
/**
* Raised by Qodo's review of this PR: the package-group PUBLISH check used to live only in
* {@code publishPackageVersionLocked} (the generic-format path), so a native publish — {@code
* mvn deploy}, {@code npm publish}, {@code twine upload}, {@code dotnet nuget push} — could
* publish straight past a group's BLOCK, allow-list, or weak-match restriction. Moving it
* into {@code requireDirectPublishAllowed} (the one method both the generic and every native
* path call) closes that for every format.
*/
@Test
void containerBackedPackagePublishIsBlockedByAnAssociatedGroupsBlockMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/maven/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/maven/*", Map.of("PUBLISH", "BLOCK"),
List.of(), List.of());
AwsException e = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void containerBackedPackagePublishIsBlockedByAWeakMatchRegardlessOfTheGroupsMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//AsyncStorage$", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "npm", null,
"asyncstorage"));
assertEquals("ConflictException", e.getErrorCode());
}
/**
* pypi and nuget names are case/punctuation insensitive, and PutPackageOriginConfiguration
* keys by the normalized spelling, so a restriction set under one spelling must block a
@@ -6757,7 +6800,8 @@ class CodeArtifactServiceTest {
AccountAwareStorageBackend<PackageOriginConfig> origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
CodeArtifactService listingService = new CodeArtifactService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
origins, regionResolver, mock(EmulatorConfig.class), true, null,
origins, AccountAwareStorageBackend.inMemory(ACCOUNT_ID), regionResolver,
mock(EmulatorConfig.class), true, null,
new CodeArtifactSidecarRegistry(List.of(pypiserverClient, bagetterClient)));
listingService.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository repository = listingService.createRepository(REGION, "dom", null, "repo",
@@ -7462,8 +7506,8 @@ class CodeArtifactServiceTest {
AccountAwareStorageBackend<PackageOriginConfig> store = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
CodeArtifactService failingService = new CodeArtifactService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
store, regionResolver, mock(EmulatorConfig.class), true, null,
new CodeArtifactSidecarRegistry(List.of()));
store, AccountAwareStorageBackend.inMemory(ACCOUNT_ID), regionResolver,
mock(EmulatorConfig.class), true, null, new CodeArtifactSidecarRegistry(List.of()));
failingService.createDomain(REGION, "dom", null, Map.of());
failingService.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String legacyKey = REGION + "::dom::repo::nuget::::Newtonsoft.Json";
@@ -7608,8 +7652,8 @@ class CodeArtifactServiceTest {
private CodeArtifactService originLookupService(AccountAwareStorageBackend<PackageOriginConfig> origins) {
CodeArtifactService lookupService = new CodeArtifactService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
origins, regionResolver, mock(EmulatorConfig.class), true, null,
new CodeArtifactSidecarRegistry(List.of()));
origins, AccountAwareStorageBackend.inMemory(ACCOUNT_ID), regionResolver,
mock(EmulatorConfig.class), true, null, new CodeArtifactSidecarRegistry(List.of()));
lookupService.createDomain(REGION, "dom", null, Map.of());
lookupService.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
return lookupService;
@@ -7628,4 +7672,526 @@ class CodeArtifactServiceTest {
assertEquals(List.of(),
service.describeRepository(REGION, "refused-update", null, "consumer").getUpstreams());
}
// -------------------------------------------------------------- package groups
@Test
void createPackageGroupRequiresTheDomainToExist() {
AwsException e = assertThrows(AwsException.class,
() -> service.createPackageGroup(REGION, "missing", null, "/npm/*", null, null, Map.of()));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void createPackageGroupRejectsADuplicatePattern() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void createPackageGroupRejectsAPatternWithNoRecognizedSuffix() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.createPackageGroup(REGION, "dom", null, "/npm/space/anycompany", null, null, Map.of()));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void createPackageGroupStartsEveryRestrictionAtInheritResolvingToAllow() {
service.createDomain(REGION, "dom", null, Map.of());
PackageGroupDescriptionView view = service.createPackageGroup(REGION, "dom", null, "/npm/*", "contact",
"desc", Map.of());
assertEquals("/npm/*", view.pattern());
assertEquals("dom", view.domainName());
assertEquals("contact", view.contactInfo());
assertEquals("desc", view.description());
assertNull(view.parentPattern());
assertEquals("INHERIT", view.restrictions().get("PUBLISH").mode());
assertEquals("ALLOW", view.restrictions().get("PUBLISH").effectiveMode());
assertNull(view.restrictions().get("PUBLISH").inheritedFromPattern());
}
@Test
void describePackageGroupReportsTheMostSpecificAncestorAsParent() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null, null, Map.of());
PackageGroupDescriptionView child = service.describePackageGroup(REGION, "dom", null, "/npm/space/*");
assertEquals("/npm/*", child.parentPattern());
PackageGroupDescriptionView root = service.describePackageGroup(REGION, "dom", null, "/npm/*");
assertNull(root.parentPattern());
}
@Test
void describePackageGroupThrowsResourceNotFoundForAnUnknownPattern() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.describePackageGroup(REGION, "dom", null, "/npm/*"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void updatePackageGroupOnlyChangesContactInfoAndDescription() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", "old-contact", "old-desc", Map.of());
PackageGroupDescriptionView updated = service.updatePackageGroup(REGION, "dom", null, "/npm/*",
"new-contact", "new-desc");
assertEquals("new-contact", updated.contactInfo());
assertEquals("new-desc", updated.description());
assertEquals("/npm/*", updated.pattern());
}
@Test
void deletingAParentReparentsItsChildrenOntoTheGrandparent() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/anycompany-ui~", null, null, Map.of());
service.deletePackageGroup(REGION, "dom", null, "/npm/space/*");
PackageGroupDescriptionView grandchild = service.describePackageGroup(REGION, "dom", null,
"/npm/space/anycompany-ui~");
assertEquals("/npm/*", grandchild.parentPattern());
}
@Test
void deletePackageGroupThrowsResourceNotFoundForAnUnknownPattern() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.deletePackageGroup(REGION, "dom", null, "/npm/*"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void listPackageGroupsFiltersByPrefixAndPaginates() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/pypi/*", null, null, Map.of());
PackageGroupListResult all = service.listPackageGroups(REGION, "dom", null, null, null, null);
assertEquals(2, all.packageGroups().size());
PackageGroupListResult npmOnly = service.listPackageGroups(REGION, "dom", null, "/npm", null, null);
assertEquals(1, npmOnly.packageGroups().size());
assertEquals("/npm/*", npmOnly.packageGroups().get(0).pattern());
PackageGroupListResult firstPage = service.listPackageGroups(REGION, "dom", null, null, 1, null);
assertEquals(1, firstPage.packageGroups().size());
assertNotNull(firstPage.nextToken());
}
@Test
void listSubPackageGroupsReturnsOnlyDirectChildrenNotGrandchildren() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/anycompany-ui~", null, null, Map.of());
PackageGroupListResult children = service.listSubPackageGroups(REGION, "dom", null, "/npm/*", null, null);
assertEquals(1, children.packageGroups().size());
assertEquals("/npm/space/*", children.packageGroups().get(0).pattern());
}
@Test
void updatePackageGroupOriginConfigurationSetsModeAndTracksAllowedRepositoryEdits() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
UpdatePackageGroupOriginConfigurationResult result = service.updatePackageGroupOriginConfiguration(REGION,
"dom", null, "/npm/*", Map.of("PUBLISH", "ALLOW_SPECIFIC_REPOSITORIES"),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "PUBLISH"),
new PackageGroupAllowedRepositoryEdit("repo-b", "PUBLISH")),
List.of());
assertEquals("ALLOW_SPECIFIC_REPOSITORIES", result.packageGroup().restrictions().get("PUBLISH").mode());
assertEquals("ALLOW_SPECIFIC_REPOSITORIES",
result.packageGroup().restrictions().get("PUBLISH").effectiveMode());
assertEquals(2, result.packageGroup().restrictions().get("PUBLISH").repositoriesCount());
assertEquals(List.of("repo-a", "repo-b"), result.allowedRepositoryUpdates().get("PUBLISH").get("ADDED"));
UpdatePackageGroupOriginConfigurationResult afterRemove = service.updatePackageGroupOriginConfiguration(
REGION, "dom", null, "/npm/*", Map.of(), List.of(),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "PUBLISH")));
assertEquals(1, afterRemove.packageGroup().restrictions().get("PUBLISH").repositoriesCount());
assertEquals(List.of("repo-a"), afterRemove.allowedRepositoryUpdates().get("PUBLISH").get("REMOVED"));
// The mode itself is untouched by an allowed-repository-only edit.
assertEquals("ALLOW_SPECIFIC_REPOSITORIES", afterRemove.packageGroup().restrictions().get("PUBLISH").mode());
}
@Test
void effectiveModeWalksUpThroughInheritToTheNearestConcreteAncestor() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", Map.of("PUBLISH", "BLOCK"),
List.of(), List.of());
PackageGroupDescriptionView child = service.describePackageGroup(REGION, "dom", null, "/npm/space/*");
assertEquals("INHERIT", child.restrictions().get("PUBLISH").mode());
assertEquals("BLOCK", child.restrictions().get("PUBLISH").effectiveMode());
assertEquals("/npm/*", child.restrictions().get("PUBLISH").inheritedFromPattern());
}
@Test
void listAllowedRepositoriesForGroupReturnsTheStoredList() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*",
Map.of("PUBLISH", "ALLOW_SPECIFIC_REPOSITORIES"),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "PUBLISH")), List.of());
ListAllowedRepositoriesForGroupResult result = service.listAllowedRepositoriesForGroup(REGION, "dom", null,
"/npm/*", "PUBLISH", null, null);
assertEquals(List.of("repo-a"), result.allowedRepositories());
}
@Test
void getAssociatedPackageGroupThrowsResourceNotFoundWhenNoGroupMatches() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.getAssociatedPackageGroup(REGION, "dom", null, "npm", null, "react"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void getAssociatedPackageGroupReportsTheMostSpecificMatchAndItsStrength() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//AsyncStorage$", null, null, Map.of());
GetAssociatedPackageGroupResult strong = service.getAssociatedPackageGroup(REGION, "dom", null, "npm", null,
"AsyncStorage");
assertEquals("/npm//AsyncStorage$", strong.packageGroup().pattern());
assertEquals("STRONG", strong.associationType());
GetAssociatedPackageGroupResult weak = service.getAssociatedPackageGroup(REGION, "dom", null, "npm", null,
"asyncstorage");
assertEquals("/npm//AsyncStorage$", weak.packageGroup().pattern());
assertEquals("WEAK", weak.associationType());
GetAssociatedPackageGroupResult other = service.getAssociatedPackageGroup(REGION, "dom", null, "npm", null,
"some-other-package");
assertEquals("/npm/*", other.packageGroup().pattern());
assertEquals("STRONG", other.associationType());
}
@Test
void listAssociatedPackagesReturnsOnlyPackagesTheGroupWinsForAcrossRepositories() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/space/*", null, null, Map.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "space", "in-space", "1.0.0",
"a.txt", Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo-b", "generic", "other", "not-in-space", "1.0.0",
"a.txt", Digests.sha256Hex(content), "false", content);
ListAssociatedPackagesResult spaceGroup = service.listAssociatedPackages(REGION, "dom", null,
"/generic/space/*", null, null, false);
assertEquals(1, spaceGroup.packages().size());
assertEquals("in-space", spaceGroup.packages().get(0).packageName());
ListAssociatedPackagesResult rootGroup = service.listAssociatedPackages(REGION, "dom", null, "/generic/*",
null, null, false);
assertEquals(1, rootGroup.packages().size());
assertEquals("not-in-space", rootGroup.packages().get(0).packageName());
}
@Test
void listAssociatedPackagesPreviewWorksForAPatternThatDoesNotExistYet() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "space", "in-space", "1.0.0", "a.txt",
Digests.sha256Hex(content), "false", content);
ListAssociatedPackagesResult preview = service.listAssociatedPackages(REGION, "dom", null,
"/generic/space/*", null, null, true);
assertEquals(1, preview.packages().size());
AwsException e = assertThrows(AwsException.class,
() -> service.listAssociatedPackages(REGION, "dom", null, "/generic/space/*", null, null, false));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void publishPackageVersionIsBlockedByAnAssociatedGroupsBlockMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/generic/*", Map.of("PUBLISH", "BLOCK"),
List.of(), List.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void publishPackageVersionAllowsOnlyTheRepositoryListedForAllowSpecificRepositories() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/generic/*",
Map.of("PUBLISH", "ALLOW_SPECIFIC_REPOSITORIES"),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "PUBLISH")), List.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
assertDoesNotThrow(() -> service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "ns",
"my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo-b", "generic", "ns", "other-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false",
content));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void publishPackageVersionIsBlockedByAWeakMatchRegardlessOfTheGroupsMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/ns/AsyncStorage$", null, null, Map.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", "ns", "asyncstorage", "1.0.0", "a.txt", Digests.sha256Hex(content), "false",
content));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void publishPackageVersionWithNoAssociatedGroupIsUnaffected() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
assertDoesNotThrow(() -> service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
}
@Test
void packageLevelBlockWinsOverAGroupLevelAllow() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/*", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK",
"BLOCK");
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", e.getErrorCode());
}
@Test
void isUpstreamRetentionBlockedIsBlockedByAnAssociatedGroupsBlockMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*",
Map.of("EXTERNAL_UPSTREAM", "BLOCK"), List.of(), List.of());
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg"));
}
@Test
void isUpstreamRetentionBlockedAllowsOnlyTheRepositoryListedForAllowSpecificRepositories() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*",
Map.of("EXTERNAL_UPSTREAM", "ALLOW_SPECIFIC_REPOSITORIES"),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "EXTERNAL_UPSTREAM")), List.of());
assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-a", "npm", null, "my-pkg"));
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo-b", "npm", null, "other-pkg"));
}
@Test
void isUpstreamRetentionBlockedIsBlockedByAWeakMatchRegardlessOfTheGroupsMode() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//AsyncStorage$", null, null, Map.of());
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "asyncstorage"));
}
@Test
void isUpstreamRetentionBlockedWithNoAssociatedGroupIsUnaffected() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg"));
}
@Test
void isUpstreamRetentionBlockedPackageLevelBlockWinsOverAGroupLevelAllow() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "npm", null, "my-pkg", "ALLOW", "BLOCK");
assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "npm", null, "my-pkg"));
}
@Test
void packageGroupArnCanBeTaggedAndUntagged() {
service.createDomain(REGION, "dom", null, Map.of());
PackageGroupDescriptionView view = service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null,
null, Map.of("env", "prod"));
assertEquals(Map.of("env", "prod"), service.listTagsForResource(view.arn()));
service.tagResource(view.arn(), Map.of("team", "platform"));
assertEquals(Map.of("env", "prod", "team", "platform"), service.listTagsForResource(view.arn()));
service.untagResource(view.arn(), List.of("env"));
assertEquals(Map.of("team", "platform"), service.listTagsForResource(view.arn()));
}
/**
* Raised by Qodo's review of this PR: {@code PACKAGE_GROUP_RESTRICTION_TYPES} is an immutable
* {@code List.of(...)}, whose {@code contains(null)} throws {@code NullPointerException}
* rather than returning false. Omitting {@code originRestrictionType} on an allowed-repository
* edit must fail with a clean {@code ValidationException}, not an internal error.
*/
@Test
void updatePackageGroupOriginConfigurationRejectsAnAllowedRepositoryEditWithNoRestrictionType() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
AwsException e = assertThrows(AwsException.class, () -> service.updatePackageGroupOriginConfiguration(
REGION, "dom", null, "/npm/*", Map.of(),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", null)), List.of()));
assertEquals("ValidationException", e.getErrorCode());
}
/** Same NPE risk, reached through the query parameter instead of a list entry. */
@Test
void listAllowedRepositoriesForGroupRejectsAMissingRestrictionType() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.listAllowedRepositoriesForGroup(REGION, "dom", null, "/npm/*", null, null, null));
assertEquals("ValidationException", e.getErrorCode());
}
/**
* Raised by Qodo's review of this PR: {@code groupAllowsRestriction}'s {@code
* ALLOW_SPECIFIC_REPOSITORIES} branch used to read the allow-list off {@code group} itself
* even when the effective mode came from an {@code INHERIT} walk up to an ancestor — so an
* {@code INHERIT} child with no restriction of its own rejected every repository its parent
* actually allowed.
*/
@Test
void inheritedAllowSpecificRepositoriesUsesTheAncestorsOwnAllowList() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/*", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/generic/space/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/generic/*",
Map.of("PUBLISH", "ALLOW_SPECIFIC_REPOSITORIES"),
List.of(new PackageGroupAllowedRepositoryEdit("repo-a", "PUBLISH")), List.of());
byte[] content = "c".getBytes(StandardCharsets.UTF_8);
// /generic/space/* itself never configured PUBLISH (stays INHERIT), so the effective mode
// walks up to /generic/*'s ALLOW_SPECIFIC_REPOSITORIES, and that ancestor's own allow-list
// (repo-a) must be what's consulted, not the child's own (absent) one.
assertDoesNotThrow(() -> service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "space",
"in-space", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo-b", "generic", "space", "other", "1.0.0", "a.txt", Digests.sha256Hex(content), "false",
content));
assertEquals("ConflictException", e.getErrorCode());
}
/**
* Raised by Qodo's review of this PR: {@code escapeKeySegment} only escaped {@code :} and
* {@code \}, so a pattern containing a literal {@code #} (legal in a package-group pattern,
* unlike in a namespace/package/version) could collide with another pattern's escaped {@code
* :}. {@code /npm//#c$} (literal {@code #} then {@code c}) and {@code /npm//:$} (a literal
* {@code :}) must be two independently creatable, independently describable groups.
*/
@Test
void packageGroupPatternsContainingHashAndColonDoNotCollide() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//#c$", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//:$", null, null, Map.of());
assertEquals("/npm//#c$", service.describePackageGroup(REGION, "dom", null, "/npm//#c$").pattern());
assertEquals("/npm//:$", service.describePackageGroup(REGION, "dom", null, "/npm//:$").pattern());
}
/**
* Raised by Qodo's review of this PR: {@code isStrictAncestor} compared pattern components
* literally, with no case/separator normalization, even though a package only weakly matching
* a pattern is itself documented as "associated with" that group. A child pattern that is only
* a case variant of its true ancestor must still find that ancestor and inherit its mode,
* rather than resolving INHERIT to the top-of-hierarchy ALLOW default.
*/
@Test
void aCaseVariantChildPatternStillInheritsFromItsNormalizedAncestor() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/space/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/space/*",
Map.of("PUBLISH", "BLOCK"), List.of(), List.of());
service.createPackageGroup(REGION, "dom", null, "/npm/SPACE/foo$", null, null, Map.of());
PackageGroupDescriptionView child = service.describePackageGroup(REGION, "dom", null, "/npm/SPACE/foo$");
assertEquals("/npm/space/*", child.parentPattern());
assertEquals("INHERIT", child.restrictions().get("PUBLISH").mode());
assertEquals("BLOCK", child.restrictions().get("PUBLISH").effectiveMode());
assertEquals("/npm/space/*", child.restrictions().get("PUBLISH").inheritedFromPattern());
}
/**
* Raised by Qodo's review of this PR: when two patterns tie on specificity but differ only by
* case/separators, whichever happened to be scanned first used to win, regardless of which one
* the package actually strongly matches. A package that strongly matches one of two tied-rank
* patterns must resolve to that one, not to the one it only weakly matches.
*/
@Test
void anEquallySpecificStrongMatchWinsOverAWeakMatchRegardlessOfCreationOrder() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//Foo$", null, null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm//foo$", null, null, Map.of());
GetAssociatedPackageGroupResult result = service.getAssociatedPackageGroup(REGION, "dom", null, "npm", null,
"foo");
assertEquals("/npm//foo$", result.packageGroup().pattern());
assertEquals("STRONG", result.associationType());
}
/**
* Raised by Qodo's review of this PR: package groups are domain-scoped but outlive
* {@code deleteRepository}'s own cleanup (which only ever runs once the domain already has no
* repositories left), so without this, a domain deleted and recreated under the same name
* would inherit the previous one's groups, including a PUBLISH:BLOCK a caller has no way to
* know about.
*/
@Test
void deletingADomainRemovesItsPackageGroupsSoARecreatedDomainDoesNotInheritThem() {
service.createDomain(REGION, "dom", null, Map.of());
service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of());
service.updatePackageGroupOriginConfiguration(REGION, "dom", null, "/npm/*", Map.of("PUBLISH", "BLOCK"),
List.of(), List.of());
service.deleteDomain(REGION, "dom", null);
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.describePackageGroup(REGION, "dom", null, "/npm/*"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
assertDoesNotThrow(() -> service.createPackageGroup(REGION, "dom", null, "/npm/*", null, null, Map.of()));
}
}
@@ -0,0 +1,253 @@
package io.floci.aws.services.codeartifact;
import org.junit.jupiter.api.Test;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.MatchStrength.STRONG;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.MatchStrength.WEAK;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.isStrictAncestor;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.matchStrength;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.packagePath;
import static io.floci.aws.services.codeartifact.PackageGroupPatterns.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Every case here is checked against the CodeArtifact User Guide's own "Package group definition
* syntax and matching behavior" worked examples, not inferred: the six pattern shapes it lists,
* the {@code /npm/*}-vs-{@code /npm/space/*} hierarchy example, the {@code foo~} word-boundary
* example, and the {@code AsyncStorage}/strong-weak example.
*/
class PackageGroupPatternsTest {
@Test
void allFormatsPatternMatchesEveryFormat() {
PackageGroupPatterns.ParsedPattern pattern = parse("/*");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", null, "react")));
assertEquals(STRONG, matchStrength(pattern, packagePath("maven", "com.example", "a")));
}
@Test
void oneFormatPatternMatchesOnlyThatFormat() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm/*");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", null, "react")));
assertNull(matchStrength(pattern, packagePath("pypi", null, "react")));
}
@Test
void namespacePrefixPatternMatchesAWordBoundaryPrefixOfTheNamespace() {
PackageGroupPatterns.ParsedPattern pattern = parse("/maven/com.anycompany~");
assertEquals(STRONG, matchStrength(pattern, packagePath("maven", "com.anycompany", "a")));
assertEquals(STRONG, matchStrength(pattern, packagePath("maven", "com.anycompany.foo", "bar")));
assertNull(matchStrength(pattern, packagePath("maven", "com.anycompanyx", "a")));
}
@Test
void namespaceExactPatternMatchesAnyNameUnderThatNamespace() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm/space/*");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "aui.components")));
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "amplify-ui-core")));
assertNull(matchStrength(pattern, packagePath("npm", "other", "amplify-ui-core")));
}
@Test
void namePrefixPatternMatchesAWordBoundaryPrefixOfTheName() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm/space/anycompany-ui~");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "anycompany-ui")));
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "anycompany-ui-components")));
assertNull(matchStrength(pattern, packagePath("npm", "space", "anycompany-uix")));
}
@Test
void fullCoordinatePatternMatchesOnlyThatExactNameUnderThatExactNamespace() {
PackageGroupPatterns.ParsedPattern pattern = parse("/maven/org.apache.logging.log4j/log4j-core$");
assertEquals(STRONG, matchStrength(pattern, packagePath("maven", "org.apache.logging.log4j", "log4j-core")));
assertNull(matchStrength(pattern, packagePath("maven", "org.apache.logging.log4j", "log4j-api")));
assertNull(matchStrength(pattern, packagePath("maven", "org.apache.logging", "log4j-core")));
}
@Test
void namespacelessFormatUsesABlankNamespaceSegment() {
PackageGroupPatterns.ParsedPattern pattern = parse("/python//requests$");
assertEquals(STRONG, matchStrength(pattern, packagePath("python", null, "requests")));
assertNull(matchStrength(pattern, packagePath("python", null, "requests2")));
}
/**
* The User Guide's own word-boundary example: {@code /npm/space/foo~} matches {@code foo} and
* {@code foo-bar}, but not {@code food} or {@code foot}, since {@code d}/{@code t} are word
* characters that continue the same word rather than ending it.
*/
@Test
void prefixMatchRespectsWordBoundariesNotJustTextPrefixes() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm/space/foo~");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "foo")));
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", "space", "foo-bar")));
assertNull(matchStrength(pattern, packagePath("npm", "space", "food")));
assertNull(matchStrength(pattern, packagePath("npm", "space", "foot")));
}
/**
* The User Guide's own strong/weak example: a pattern for the exact-cased name {@code
* AsyncStorage} strong-matches that exact casing, but only weak-matches case variations like
* {@code asyncStorage} or {@code asyncstorage}.
*/
@Test
void caseVariationOfAnExactPatternIsAWeakMatchNotAStrongOne() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm//AsyncStorage$");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", null, "AsyncStorage")));
assertEquals(WEAK, matchStrength(pattern, packagePath("npm", null, "asyncStorage")));
assertEquals(WEAK, matchStrength(pattern, packagePath("npm", null, "asyncstorage")));
}
/**
* The User Guide's own "Additional variations" example: {@code foo-bar}, {@code foo.bar},
* {@code foo..bar}, and {@code foo_bar} are all weak-match equivalents of each other, but
* {@code foobar} (no separator at all) is not.
*/
@Test
void weakMatchTreatsDashDotAndUnderscoreRunsAsEquivalentButNotAsAbsent() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm//foo-bar$");
assertEquals(STRONG, matchStrength(pattern, packagePath("npm", null, "foo-bar")));
assertEquals(WEAK, matchStrength(pattern, packagePath("npm", null, "foo.bar")));
assertEquals(WEAK, matchStrength(pattern, packagePath("npm", null, "foo..bar")));
assertEquals(WEAK, matchStrength(pattern, packagePath("npm", null, "foo_bar")));
assertNull(matchStrength(pattern, packagePath("npm", null, "foobar")));
}
/**
* The User Guide's own hierarchy example: {@code /npm/*} and {@code /npm/space/*} both match
* {@code /npm/space/aui.components}, but {@code /npm/space/*} is the proper subset (every
* package it matches also matches {@code /npm/*}, not the reverse), making it the more
* specific pattern and {@code /npm/*} its parent.
*/
@Test
void moreSpecificNamespacePatternIsAStrictDescendantOfTheFormatOnlyPattern() {
PackageGroupPatterns.ParsedPattern formatOnly = parse("/npm/*");
PackageGroupPatterns.ParsedPattern namespaceExact = parse("/npm/space/*");
assertTrue(isStrictAncestor(formatOnly, namespaceExact));
assertFalse(isStrictAncestor(namespaceExact, formatOnly));
}
@Test
void namePrefixPatternIsAStrictDescendantOfItsOwnNamespaceExactPattern() {
PackageGroupPatterns.ParsedPattern namespaceExact = parse("/npm/space/*");
PackageGroupPatterns.ParsedPattern namePrefix = parse("/npm/space/anycompany-ui~");
assertTrue(isStrictAncestor(namespaceExact, namePrefix));
assertFalse(isStrictAncestor(namePrefix, namespaceExact));
}
@Test
void namespacePrefixPatternIsAStrictAncestorOfAFullCoordinatePatternItReaches() {
PackageGroupPatterns.ParsedPattern namespacePrefix = parse("/maven/com.anycompany~");
PackageGroupPatterns.ParsedPattern fullCoordinate = parse("/maven/com.anycompany.foo/bar$");
assertTrue(isStrictAncestor(namespacePrefix, fullCoordinate));
}
@Test
void disjointPatternsAreNeitherAncestorOfTheOther() {
PackageGroupPatterns.ParsedPattern npm = parse("/npm/*");
PackageGroupPatterns.ParsedPattern pypi = parse("/pypi/*");
assertFalse(isStrictAncestor(npm, pypi));
assertFalse(isStrictAncestor(pypi, npm));
}
@Test
void aPatternIsNeverItsOwnAncestor() {
PackageGroupPatterns.ParsedPattern pattern = parse("/npm/space/*");
assertFalse(isStrictAncestor(pattern, pattern));
}
/**
* Raised by Qodo's review of this PR: a descendant pattern that only case/separator-varies
* from its true ancestor must still be recognized as structurally contained, the same
* normalization {@link PackageGroupPatterns#matchStrength} already applies to a package path
* (a weakly-matched package is itself documented as "associated with" the group it weakly
* matches, so the subset relationship behind hierarchy follows the same rule).
*/
@Test
void aCaseAndSeparatorVariantPatternIsStillAStrictDescendantOfItsNormalizedAncestor() {
PackageGroupPatterns.ParsedPattern ancestor = parse("/npm/space/*");
PackageGroupPatterns.ParsedPattern caseVariantChild = parse("/npm/SPACE/foo$");
assertTrue(isStrictAncestor(ancestor, caseVariantChild));
// Same word, hyphen vs. underscore: both collapse to the same normalized "left.pad".
PackageGroupPatterns.ParsedPattern separatorAncestor = parse("/npm/left-pad/*");
PackageGroupPatterns.ParsedPattern separatorVariantChild = parse("/npm/left_pad/foo$");
assertTrue(isStrictAncestor(separatorAncestor, separatorVariantChild));
}
/** A literal match still holds exactly as before normalization was added. */
@Test
void anExactMatchingDescendantIsUnaffectedByNormalization() {
PackageGroupPatterns.ParsedPattern ancestor = parse("/npm/space/*");
PackageGroupPatterns.ParsedPattern descendant = parse("/npm/space/foo$");
assertTrue(isStrictAncestor(ancestor, descendant));
}
/**
* Guards the cycle this PR's own normalization fix above first introduced and then had to
* close off: two same-depth patterns that tie under {@link PackageGroupPatterns
* #compareSpecificity} once differences are normalized away (same terminal kind, same
* normalized literal) must never both claim to be the other's strict ancestor, or {@code
* resolveEffectiveMode}'s {@code INHERIT} walk loops forever the moment both exist in the
* same domain. Covers the case that actually hung a test run while this PR was in review: an
* {@code EXACT} pair differing only by case in their terminal component, and an {@code EXACT}
* pair differing only by case in a non-terminal component with an identical terminal.
*/
@Test
void sameDepthTiedSpecificityPatternsAreNeverEachOthersAncestorEitherWay() {
PackageGroupPatterns.ParsedPattern lowerFoo = parse("/npm//foo$");
PackageGroupPatterns.ParsedPattern upperFoo = parse("/npm//Foo$");
assertFalse(isStrictAncestor(lowerFoo, upperFoo));
assertFalse(isStrictAncestor(upperFoo, lowerFoo));
PackageGroupPatterns.ParsedPattern lowerSpace = parse("/npm/space/foo$");
PackageGroupPatterns.ParsedPattern upperSpace = parse("/npm/SPACE/foo$");
assertFalse(isStrictAncestor(lowerSpace, upperSpace));
assertFalse(isStrictAncestor(upperSpace, lowerSpace));
PackageGroupPatterns.ParsedPattern lowerPrefix = parse("/npm/space/foo~");
PackageGroupPatterns.ParsedPattern upperPrefix = parse("/npm/SPACE/foo~");
assertFalse(isStrictAncestor(lowerPrefix, upperPrefix));
assertFalse(isStrictAncestor(upperPrefix, lowerPrefix));
}
@Test
void parseRejectsAPatternWithNoLeadingSlash() {
assertThrows(IllegalArgumentException.class, () -> parse("npm/*"));
}
@Test
void parseRejectsAPatternWithNoRecognizedSuffix() {
assertThrows(IllegalArgumentException.class, () -> parse("/npm/space/anycompany"));
}
@Test
void parseRejectsDollarBeforeTheNameLevel() {
assertThrows(IllegalArgumentException.class, () -> parse("/npm/space$"));
}
@Test
void parseRejectsMoreThanThreeComponents() {
assertThrows(IllegalArgumentException.class, () -> parse("/npm/space/name/extra$"));
}
}