From a98380b3873a9a0ddc31ffb53e375d3a105f0f6f Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Tue, 3 Nov 2026 21:18:03 -0600 Subject: [PATCH] fix: preserve legacy CodeArtifact package origin records (#7469) --- .../codeartifact/CodeArtifactService.java | 107 ++++++- .../CodeArtifactAssetPersistenceTest.java | 58 +++- .../codeartifact/CodeArtifactServiceTest.java | 300 ++++++++++++++++++ 3 files changed, 447 insertions(+), 18 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java index 3633fcfd02..a69e042b18 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java @@ -41,6 +41,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -194,6 +195,7 @@ public class CodeArtifactService implements Resettable { private final AccountAwareStorageBackend repositories; private final AccountAwareStorageBackend packageVersions; private final AccountAwareStorageBackend packageOriginConfigs; + private final Set migratedOriginConfigAccounts = new HashSet<>(); private final RegionResolver regionResolver; private final EmulatorConfig config; private final CodeArtifactSidecarRegistry sidecarRegistry; @@ -1185,7 +1187,7 @@ public class CodeArtifactService implements Resettable { String originKey = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); - boolean hasOriginConfig = packageOriginConfigs.getForAccount(owner, originKey).isPresent(); + boolean hasOriginConfig = packageOriginConfig(owner, originKey, format).isPresent(); List entries; String preferredDisplayVersion = null; if (CONTAINER_BACKED_FORMATS.contains(format)) { @@ -2270,7 +2272,7 @@ public class CodeArtifactService implements Resettable { String format, String namespace, String packageName) { String originKey = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); - String publishRestriction = packageOriginConfigs.getForAccount(owner, originKey) + String publishRestriction = packageOriginConfig(owner, originKey, format) .map(PackageOriginConfig::getPublishRestriction) .orElse("ALLOW"); if ("BLOCK".equals(publishRestriction)) { @@ -2601,8 +2603,9 @@ public class CodeArtifactService implements Resettable { * records' own {@code format}/{@code namespace}/{@code packageName} fields (the same technique * {@link #genericPackageVersions} already uses for one known package, here scanned * repository-wide instead of by one package's own prefix), plus any origin-config-only - * package's own matching fields on {@link PackageOriginConfig}, never by parsing a scanned key - * back into parts, which {@link #escapeKeySegment}'s own javadoc explains is lossy. Every + * package's own matching fields on {@link PackageOriginConfig}. Historical NuGet and PyPI + * origin records without those fields are first repaired from their scoped keys; these formats + * have no namespace, and {@link #escapeKeySegment}'s escapes recover the package name. Every * container-backed format's own new {@link RepositorySidecarManager#listPackages} answers the * same for real sidecar content, plus the same origin-config-only union. {@code domainOwner} * is threaded through (rather than just the already-resolved {@code owner}) only because @@ -2633,6 +2636,7 @@ public class CodeArtifactService implements Resettable { accountingPackageName(pv.getFormat(), pv.getPackageName()))); } } + migrateOriginConfigs(owner); for (PackageOriginConfig config : packageOriginConfigs.scanForAccount(owner, k -> k.startsWith(originPrefix))) { if (config.getFormat() != null @@ -2640,7 +2644,9 @@ public class CodeArtifactService implements Resettable { PackageCoordinate coordinate = new PackageCoordinate(config.getFormat(), config.getNamespace(), accountingPackageName(config.getFormat(), config.getPackageName())); coordinates.add(coordinate); - originConfigsByCoordinate.put(coordinate, config); + packageOriginConfig(owner, packageKey(region, domain, repository, coordinate.format(), + coordinate.namespace(), coordinate.packageName()), coordinate.format()) + .ifPresent(current -> originConfigsByCoordinate.put(coordinate, current)); } } for (String format : CONTAINER_BACKED_FORMATS) { @@ -2766,13 +2772,8 @@ public class CodeArtifactService implements Resettable { // under its caller's original, un-normalized spelling. Optional config = Optional.ofNullable( packages.originConfigsByCoordinate().get(coordinate)); - // Raised by Greptile's review: a PackageOriginConfig persisted before format/namespace/ - // packageName existed on it (see that model's own javadoc) has none of the three, so - // allPackagesInRepository's own scan can never resolve it into this map at all, even - // though the package it configures is still found here through its real version record - // or sidecar listing. Falling back to the original key-based lookup, exactly like - // describePackage's own, is what keeps that package's real restriction (not the ALLOW/ - // BLOCK default) resolving for it too. + // The discovery pass already migrated NuGet/PyPI aliases. Read remaining metadata-free + // records directly without rescanning every origin key for each unconfigured package. if (config.isEmpty()) { config = packageOriginConfigs.getForAccount(owner, packageKey(region, domain, repository, coordinate.format(), coordinate.namespace(), coordinate.packageName())); @@ -2802,6 +2803,73 @@ public class CodeArtifactService implements Resettable { public record PackageDescription(String format, String namespace, String packageName, String publishRestriction, String upstreamRestriction) {} + private Optional packageOriginConfig(String owner, String key, String format) { + migrateOriginConfigs(owner); + return packageOriginConfigs.getForAccount(owner, key); + } + + private synchronized void migrateOriginConfigs(String owner) { + if (migratedOriginConfigAccounts.contains(owner)) { + return; + } + Map> aliasesByCanonicalKey = new LinkedHashMap<>(); + for (String storedKey : packageOriginConfigs.keysForAccount(owner).stream().sorted().toList()) { + String[] parts = storedKey.split("::", -1); + if (parts.length != 6 || !parts[4].isEmpty() + || (!"nuget".equals(parts[3]) && !"pypi".equals(parts[3]))) { + continue; + } + String key = storedKey.substring(0, storedKey.lastIndexOf("::") + 2) + + accountingPackageName(parts[3], parts[5]); + aliasesByCanonicalKey.computeIfAbsent(key, ignored -> new ArrayList<>()).add(storedKey); + } + for (Map.Entry> entry : aliasesByCanonicalKey.entrySet()) { + String key = entry.getKey(); + String format = key.split("::", -1)[3]; + PackageOriginConfig canonical = packageOriginConfigs.getForAccount(owner, key).orElse(null); + PackageOriginConfig migrated = canonical == null ? null : originConfigWithCoordinates(canonical, key, format); + if (canonical == null) { + for (String legacyKey : entry.getValue()) { + PackageOriginConfig legacy = packageOriginConfigs.getForAccount(owner, legacyKey).orElse(null); + if (legacy == null) { + continue; + } + if (migrated == null) { + migrated = originConfigWithCoordinates(legacy, key, format); + } else { + if ("BLOCK".equals(legacy.getPublishRestriction())) { + migrated.setPublishRestriction("BLOCK"); + } + if ("BLOCK".equals(legacy.getUpstreamRestriction())) { + migrated.setUpstreamRestriction("BLOCK"); + } + } + } + } + if (migrated == null) { + continue; + } + // Persist repaired coordinates before deleting aliases; unchanged canonical records are already durable. + if (canonical == null || !Objects.equals(canonical.getFormat(), migrated.getFormat()) + || !Objects.equals(canonical.getNamespace(), migrated.getNamespace()) + || !Objects.equals(canonical.getPackageName(), migrated.getPackageName())) { + packageOriginConfigs.putForAccount(owner, key, migrated); + } + for (String legacyKey : entry.getValue()) { + if (!legacyKey.equals(key)) { + packageOriginConfigs.deleteForAccount(owner, legacyKey); + } + } + } + migratedOriginConfigAccounts.add(owner); + } + + private PackageOriginConfig originConfigWithCoordinates(PackageOriginConfig config, String key, String format) { + String name = key.substring(key.lastIndexOf("::") + 2).replace("#b", "\\").replace("#c", ":"); + return new PackageOriginConfig(config.getPublishRestriction(), config.getUpstreamRestriction(), + format, null, name); + } + public PackageDescription describePackage(String region, String domain, String domainOwner, String repository, String format, String namespace, String packageName) { validatePackageCoordinates(format, namespace, packageName, "describing"); @@ -2811,7 +2879,7 @@ public class CodeArtifactService implements Resettable { requireRepository(owner, repositoryKey(region, domain, repository), repository); String originKey = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); - Optional originConfig = packageOriginConfigs.getForAccount(owner, originKey); + Optional originConfig = packageOriginConfig(owner, originKey, format); // PutPackageOriginConfiguration can be called on a package with no versions yet, creating // it with no versions (its own documented behavior): a stored config, even with zero // versions behind it, already proves the package exists, and the && below must short-circuit @@ -2867,6 +2935,7 @@ public class CodeArtifactService implements Resettable { // same normalized spelling, so a restriction set under one casing is found under any other. String key = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); + migrateOriginConfigs(owner); packageOriginConfigs.putForAccount(owner, key, new PackageOriginConfig(publishRestriction, upstreamRestriction, format, namespace, packageName)); return new PackageDescription(format, namespace, packageName, publishRestriction, upstreamRestriction); @@ -2910,7 +2979,7 @@ public class CodeArtifactService implements Resettable { // match a request spelled the other. String key = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); - Optional config = packageOriginConfigs.getForAccount(owner, key); + Optional config = packageOriginConfig(owner, key, format); if (config.isPresent()) { return "BLOCK".equals(config.get().getUpstreamRestriction()); } @@ -2981,7 +3050,7 @@ public class CodeArtifactService implements Resettable { if (currentFence != packageFenceSnapshot) { return; } - if (packageOriginConfigs.getForAccount(owner, key).isPresent()) { + if (packageOriginConfig(owner, key, format).isPresent()) { return; } packageOriginConfigs.putForAccount(owner, key, @@ -3474,7 +3543,7 @@ public class CodeArtifactService implements Resettable { // key already serves every other per-package map below too. String accountingKey = packageKey(region, domain, repository, format, namespace, accountingPackageName(format, packageName)); - Optional originConfig = packageOriginConfigs.getForAccount(owner, accountingKey); + Optional originConfig = packageOriginConfig(owner, accountingKey, format); boolean hadRealContent; if (CONTAINER_BACKED_FORMATS.contains(format)) { hadRealContent = deleteContainerBackedPackageIfPresent(region, domain, owner, repository, format, @@ -3559,6 +3628,7 @@ public class CodeArtifactService implements Resettable { // were actually in effect, not CodeArtifact's bare defaults. A later DescribePackage on the // same coordinates must 404 rather than finding a zero-version package the deleted config // left behind. + migrateOriginConfigs(owner); packageOriginConfigs.deleteForAccount(owner, accountingKey); // Harmless no-op for generic (nothing is ever recorded there under this key; its bytes // live in packageVersions instead, already gone via the version-deleting branch above). @@ -4735,7 +4805,10 @@ public class CodeArtifactService implements Resettable { domains.clear(); repositories.clear(); packageVersions.clear(); - packageOriginConfigs.clear(); + synchronized (this) { + packageOriginConfigs.clear(); + migratedOriginConfigAccounts.clear(); + } containerBackedAssetBytes.clear(); containerBackedPackageDeletionFence.clear(); containerBackedVersionDeletionFence.clear(); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java index 0f52219c51..1557998431 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java @@ -623,6 +623,54 @@ class CodeArtifactAssetPersistenceTest { } } + @Test + void legacyNugetOriginConfigurationMigratesAndStaysDeletedAfterRestart(@TempDir Path dir) { + legacyOriginConfigurationMigratesAndStaysDeleted(dir, "nuget", "Newtonsoft.Json", "newtonsoft.json"); + } + + @Test + void legacyPypiOriginConfigurationMigratesAndStaysDeletedAfterRestart(@TempDir Path dir) { + legacyOriginConfigurationMigratesAndStaysDeleted(dir, "pypi", "My_Proj", "my-proj"); + } + + private void legacyOriginConfigurationMigratesAndStaysDeleted(Path dir, String format, + String original, String normalized) { + CodeArtifactService first = newService(dir); + first.createDomain(REGION, "dom", null, Map.of()); + first.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String file = "codeartifact-package-origin-configs.json"; + String prefix = REGION + "::dom::repo::" + format + "::::"; + AccountAwareStorageBackend oldStore = accountAware(dir, file, + new TypeReference>() {}); + oldStore.putForAccount(ACCOUNT_ID, prefix + original, + new PackageOriginConfig("BLOCK", "BLOCK", null, null, null)); + + CodeArtifactService upgraded = newService(dir); + CodeArtifactService.ListPackagesResult listed = upgraded.listPackages(REGION, "dom", null, "repo", + format, null, null, null, null, "BLOCK", "BLOCK"); + assertEquals(List.of(normalized), listed.packages().stream() + .map(CodeArtifactService.PackageSummaryEntry::packageName).toList()); + assertTrue(upgraded.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + AccountAwareStorageBackend migrated = accountAware(dir, file, + new TypeReference>() {}); + assertTrue(migrated.getForAccount(ACCOUNT_ID, prefix + original).isEmpty()); + assertTrue(migrated.getForAccount(ACCOUNT_ID, prefix + normalized).isPresent()); + + CodeArtifactService restarted = newService(dir); + CodeArtifactService.PackageDescription described = restarted.describePackage(REGION, "dom", null, + "repo", format, null, original); + assertEquals("BLOCK", described.publishRestriction()); + assertEquals("BLOCK", described.upstreamRestriction()); + restarted.deletePackage(REGION, "dom", null, "repo", format, null, normalized); + + CodeArtifactService afterDelete = newService(dir); + assertThrows(AwsException.class, () -> afterDelete.describePackage(REGION, "dom", null, + "repo", format, null, original)); + AccountAwareStorageBackend deleted = accountAware(dir, file, + new TypeReference>() {}); + assertTrue(deleted.keysForAccount(ACCOUNT_ID).isEmpty()); + } + private CodeArtifactService newService(Path dir) { AccountAwareStorageBackend domainStore = accountAware(dir, "codeartifact-domains.json", new TypeReference>() {}); @@ -644,7 +692,15 @@ class CodeArtifactAssetPersistenceTest { return new CodeArtifactService(domainStore, repoStore, packageVersionStore, packageOriginConfigStore, regionResolver, config, false, dir.resolve("codeartifact-assets"), - new CodeArtifactSidecarRegistry(List.of())); + persistenceSidecars()); + } + + private CodeArtifactSidecarRegistry persistenceSidecars() { + BagetterSidecarClient nuget = mock(BagetterSidecarClient.class); + when(nuget.format()).thenReturn("nuget"); + PypiserverSidecarClient pypi = mock(PypiserverSidecarClient.class); + when(pypi.format()).thenReturn("pypi"); + return new CodeArtifactSidecarRegistry(List.of(nuget, pypi)); } private AccountAwareStorageBackend accountAware(Path dir, String fileName, TypeReference> type) { diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java index 28a9ad2c99..8d5e607d7d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java @@ -20,6 +20,8 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InOrder; import java.io.ByteArrayOutputStream; @@ -67,6 +69,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -6511,6 +6514,36 @@ class CodeArtifactServiceTest { assertEquals(3, result.packages().stream().filter(p -> "my-pkg".equals(p.packageName())).count()); } + @ParameterizedTest + @ValueSource(strings = {"nuget", "pypi"}) + void listPackagesDoesNotRescanOriginKeysForUnconfiguredPackages(String format) { + AccountAwareStorageBackend 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, + new CodeArtifactSidecarRegistry(List.of(pypiserverClient, bagetterClient))); + listingService.createDomain(REGION, "dom", null, Map.of()); + CodeArtifactRepository repository = listingService.createRepository(REGION, "dom", null, "repo", + null, null, Map.of()); + origins.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::" + format + "::::configured", + new PackageOriginConfig("BLOCK", "ALLOW", format, null, "configured")); + RepositorySidecarManager manager = "nuget".equals(format) ? bagetterClient : pypiserverClient; + when(manager.listPackages(eq(repository.getSidecarContainerIds().get(format)), eq("dom"), eq("repo"))) + .thenReturn(List.of(new RepositorySidecarManager.PackageIdentifier(null, "first"), + new RepositorySidecarManager.PackageIdentifier(null, "second"))); + clearInvocations(origins); + + CodeArtifactService.ListPackagesResult result = listingService.listPackages(REGION, "dom", null, "repo", + format, null, null, null, null, null, null); + + assertEquals(3, result.packages().size()); + assertEquals(2, result.packages().stream().filter(entry -> "ALLOW".equals(entry.publishRestriction()) + && "BLOCK".equals(entry.upstreamRestriction())).count()); + assertTrue(result.packages().stream().anyMatch(entry -> "configured".equals(entry.packageName()) + && "BLOCK".equals(entry.publishRestriction()) && "ALLOW".equals(entry.upstreamRestriction()))); + verify(origins, times(1)).keysForAccount(ACCOUNT_ID); + } + @Test void listPackagesFormatFilterOnlyTouchesThatOneFormatsSidecar() { service.createDomain(REGION, "dom", null, Map.of()); @@ -7078,4 +7111,271 @@ class CodeArtifactServiceTest { "my-pkg", "1.0.0"); assertEquals(assetCount, pv.getAssets().size()); } + + @Test + void legacyNugetOriginRestrictionRemainsEffective() { + assertLegacyRestriction("nuget", "Newtonsoft.Json", "newtonsoft.json"); + } + + @Test + void legacyPypiOriginRestrictionRemainsEffective() { + assertLegacyRestriction("pypi", "My_Proj", "my-proj"); + } + + private void assertLegacyRestriction(String format, String original, String normalized) { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + String legacyKey = REGION + "::dom::repo::" + format + "::::" + original; + packageOriginConfigStore.putForAccount(ACCOUNT_ID, legacyKey, + new PackageOriginConfig("BLOCK", "BLOCK", format, null, original)); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + } + + @Test + void normalizedNugetOriginRestrictionControl() { + assertNormalizedRestriction("nuget", "Newtonsoft.Json", "newtonsoft.json"); + } + + @Test + void normalizedPypiOriginRestrictionControl() { + assertNormalizedRestriction("pypi", "My_Proj", "my-proj"); + } + + private void assertNormalizedRestriction(String format, String original, String normalized) { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", format, null, original, "BLOCK", "BLOCK"); + assertTrue(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, normalized)); + } + @Test + void readingLegacyOriginConfigMigratesItBeforeRemovingTheOldKey() { + assertLegacyRestriction("nuget", "Newtonsoft.Json", "newtonsoft.json"); + assertTrue(packageOriginConfigStore.getForAccount(ACCOUNT_ID, + REGION + "::dom::repo::nuget::::Newtonsoft.Json").isEmpty()); + assertTrue(packageOriginConfigStore.getForAccount(ACCOUNT_ID, + REGION + "::dom::repo::nuget::::newtonsoft.json").isPresent()); + assertEquals("BLOCK", service.describePackage(REGION, "dom", null, "repo", "nuget", null, + "NEWTONSOFT.JSON").publishRestriction()); + assertThrows(AwsException.class, () -> service.requireContainerBackedPackagePublishAllowed(REGION, + "dom", null, "repo", "nuget", null, "NEWTONSOFT.JSON")); + } + + @Test + void explicitOriginUpdateRetiresEveryLegacySpelling() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + for (String name : List.of("My_Proj", "MY.PROJ")) { + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::" + name, + new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, name)); + } + service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", null, "my-proj", + "ALLOW", "ALLOW"); + assertEquals(List.of(REGION + "::dom::repo::pypi::::my-proj"), + packageOriginConfigStore.keysForAccount(ACCOUNT_ID).stream().sorted().toList()); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ")); + } + + @Test + void accountMigrationPreservesOtherOwnersAndCoordinateBoundaries() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + PackageOriginConfig config = new PackageOriginConfig("BLOCK", "BLOCK", "nuget", null, "Newtonsoft.Json"); + packageOriginConfigStore.putForAccount("999999999999", REGION + "::dom::repo::nuget::::Newtonsoft.Json", config); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::other::nuget::::Newtonsoft.Json", config); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, OTHER_REGION + "::dom::repo::nuget::::Newtonsoft.Json", config); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "nuget", null, "newtonsoft.json")); + assertTrue(packageOriginConfigStore.getForAccount(ACCOUNT_ID, + REGION + "::dom::repo::nuget::::newtonsoft.json").isEmpty()); + assertEquals(2, packageOriginConfigStore.keysForAccount(ACCOUNT_ID).size()); + assertEquals(1, packageOriginConfigStore.keysForAccount("999999999999").size()); + } + + @Test + void conflictingLegacySpellingsPreserveBothBlocks() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::My_Proj", + new PackageOriginConfig("BLOCK", "ALLOW", "pypi", null, "My_Proj")); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::MY.PROJ", + new PackageOriginConfig("ALLOW", "BLOCK", "pypi", null, "MY.PROJ")); + CodeArtifactService.PackageDescription description = service.describePackage(REGION, "dom", null, "repo", + "pypi", null, "my-proj"); + assertEquals("BLOCK", description.publishRestriction()); + assertEquals("BLOCK", description.upstreamRestriction()); + assertEquals(1, packageOriginConfigStore.keysForAccount(ACCOUNT_ID).size()); + } + + @Test + void deletingCanonicalPackageAlsoRemovesLegacyOriginEntries() { + service.createDomain(REGION, "dom", null, Map.of()); + service.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::my-proj", + new PackageOriginConfig("ALLOW", "ALLOW", "pypi", null, "my-proj")); + packageOriginConfigStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::My_Proj", + new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); + assertFalse(service.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "MY_PROJ")); + service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my-proj"); + assertTrue(packageOriginConfigStore.keysForAccount(ACCOUNT_ID).isEmpty()); + assertThrows(AwsException.class, () -> service.describePackage(REGION, "dom", null, "repo", + "pypi", null, "MY_PROJ")); + } + + @Test + void failedMigrationSavePreservesLegacyRestrictionsForRetry() { + AccountAwareStorageBackend 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())); + 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"; + String canonicalKey = REGION + "::dom::repo::nuget::::newtonsoft.json"; + store.putForAccount(ACCOUNT_ID, legacyKey, + new PackageOriginConfig("BLOCK", "BLOCK", "nuget", null, "Newtonsoft.Json")); + doThrow(new IllegalStateException("save failed")).when(store) + .putForAccount(eq(ACCOUNT_ID), eq(canonicalKey), any(PackageOriginConfig.class)); + assertThrows(IllegalStateException.class, () -> failingService.isUpstreamRetentionBlocked(REGION, + "dom", null, "repo", "nuget", null, "newtonsoft.json")); + assertTrue(store.getForAccount(ACCOUNT_ID, legacyKey).isPresent()); + assertTrue(store.getForAccount(ACCOUNT_ID, canonicalKey).isEmpty()); + doAnswer(invocation -> invocation.callRealMethod()).when(store) + .putForAccount(eq(ACCOUNT_ID), eq(canonicalKey), any(PackageOriginConfig.class)); + assertTrue(failingService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "nuget", null, + "newtonsoft.json")); + assertTrue(store.getForAccount(ACCOUNT_ID, legacyKey).isEmpty()); + assertTrue(store.getForAccount(ACCOUNT_ID, canonicalKey).isPresent()); + } + + @ParameterizedTest + @ValueSource(strings = {"nuget", "pypi"}) + void ordinaryOriginLookupsMigrateAccountOnlyOnce(String format) { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + origins.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::" + format + "::::Legacy_Package", + new PackageOriginConfig("BLOCK", "BLOCK", format, null, "Legacy_Package")); + clearInvocations(origins); + + for (String name : List.of("first", "second")) { + lookupService.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", format, null, name); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, name)); + assertThrows(AwsException.class, () -> lookupService.describePackage(REGION, "dom", null, "repo", + format, null, name)); + lookupService.listPackages(REGION, "dom", null, "repo", format, null, null, null, null, null, null); + } + String normalized = "pypi".equals(format) ? "legacy-package" : "legacy_package"; + assertEquals("BLOCK", lookupService.describePackage(REGION, "dom", null, "repo", format, null, + normalized).publishRestriction()); + assertThrows(AwsException.class, () -> lookupService.requireContainerBackedPackagePublishAllowed(REGION, + "dom", null, "repo", format, null, normalized)); + verify(origins, times(1)).keysForAccount(ACCOUNT_ID); + } + + @Test + void accountMigrationRetriesFailedAliasDeletionBeforeCachingCompletion() { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + String legacy = REGION + "::dom::repo::pypi::::My_Proj"; + String canonical = REGION + "::dom::repo::pypi::::my-proj"; + origins.putForAccount(ACCOUNT_ID, legacy, new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); + doThrow(new IllegalStateException("controlled delete failure")).when(origins).deleteForAccount(ACCOUNT_ID, legacy); + assertThrows(IllegalStateException.class, () -> lookupService.isUpstreamRetentionBlocked(REGION, + "dom", null, "repo", "pypi", null, "my-proj")); + assertTrue(origins.getForAccount(ACCOUNT_ID, canonical).isPresent()); + assertTrue(origins.getForAccount(ACCOUNT_ID, legacy).isPresent()); + doAnswer(invocation -> invocation.callRealMethod()).when(origins).deleteForAccount(ACCOUNT_ID, legacy); + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj")); + assertTrue(origins.getForAccount(ACCOUNT_ID, legacy).isEmpty()); + lookupService.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "pypi", null, "new"); + verify(origins, times(2)).keysForAccount(ACCOUNT_ID); + } + + @Test + void clearingServiceResetsAccountMigration() { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "absent")); + lookupService.clear(); + lookupService.createDomain(REGION, "dom", null, Map.of()); + lookupService.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + origins.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::pypi::::My_Proj", + new PackageOriginConfig("BLOCK", "BLOCK", "pypi", null, "My_Proj")); + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", "pypi", null, "my-proj")); + verify(origins, times(2)).keysForAccount(ACCOUNT_ID); + } + + @ParameterizedTest + @ValueSource(strings = {"nuget", "pypi"}) + void firstOriginLookupDoesNotRewriteCanonicalRecords(String format) { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + for (String name : List.of("first", "second", "third")) { + origins.putForAccount(ACCOUNT_ID, REGION + "::dom::repo::" + format + "::::" + name, + new PackageOriginConfig("BLOCK", "ALLOW", format, null, name)); + } + clearInvocations(origins); + + assertEquals("BLOCK", lookupService.describePackage(REGION, "dom", null, "repo", format, null, + "first").publishRestriction()); + assertFalse(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "second")); + + verify(origins, never()).putForAccount(anyString(), anyString(), any(PackageOriginConfig.class)); + verify(origins, never()).deleteForAccount(anyString(), anyString()); + verify(origins, times(1)).keysForAccount(ACCOUNT_ID); + } + + @ParameterizedTest + @ValueSource(strings = {"nuget", "pypi"}) + void canonicalOriginCoordinatesAreRepairedBeforeAliasRemoval(String format) { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + String canonical = REGION + "::dom::repo::" + format + "::::example"; + String legacy = REGION + "::dom::repo::" + format + "::::EXAMPLE"; + origins.putForAccount(ACCOUNT_ID, canonical, new PackageOriginConfig("ALLOW", "BLOCK", null, null, null)); + origins.putForAccount(ACCOUNT_ID, legacy, new PackageOriginConfig("BLOCK", "ALLOW", format, null, "EXAMPLE")); + clearInvocations(origins); + + assertTrue(lookupService.isUpstreamRetentionBlocked(REGION, "dom", null, "repo", format, null, "example")); + + PackageOriginConfig repaired = origins.getForAccount(ACCOUNT_ID, canonical).orElseThrow(); + assertEquals(format, repaired.getFormat()); + assertNull(repaired.getNamespace()); + assertEquals("example", repaired.getPackageName()); + assertEquals("ALLOW", repaired.getPublishRestriction()); + assertEquals("BLOCK", repaired.getUpstreamRestriction()); + InOrder order = inOrder(origins); + order.verify(origins).putForAccount(ACCOUNT_ID, canonical, repaired); + order.verify(origins).deleteForAccount(ACCOUNT_ID, legacy); + verify(origins, times(1)).putForAccount(anyString(), anyString(), any(PackageOriginConfig.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"nuget", "pypi"}) + void unchangedCanonicalOriginRemovesAliasesWithoutRewriting(String format) { + AccountAwareStorageBackend origins = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); + CodeArtifactService lookupService = originLookupService(origins); + String canonical = REGION + "::dom::repo::" + format + "::::example"; + String legacy = REGION + "::dom::repo::" + format + "::::EXAMPLE"; + origins.putForAccount(ACCOUNT_ID, canonical, new PackageOriginConfig("ALLOW", "BLOCK", format, null, "example")); + origins.putForAccount(ACCOUNT_ID, legacy, new PackageOriginConfig("BLOCK", "ALLOW", format, null, "EXAMPLE")); + clearInvocations(origins); + + assertEquals("ALLOW", lookupService.describePackage(REGION, "dom", null, "repo", format, null, + "example").publishRestriction()); + assertTrue(origins.getForAccount(ACCOUNT_ID, legacy).isEmpty()); + assertEquals("BLOCK", origins.getForAccount(ACCOUNT_ID, canonical).orElseThrow().getUpstreamRestriction()); + verify(origins, never()).putForAccount(anyString(), anyString(), any(PackageOriginConfig.class)); + verify(origins).deleteForAccount(ACCOUNT_ID, legacy); + } + + private CodeArtifactService originLookupService(AccountAwareStorageBackend 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())); + lookupService.createDomain(REGION, "dom", null, Map.of()); + lookupService.createRepository(REGION, "dom", null, "repo", null, null, Map.of()); + return lookupService; + } + }