diff --git a/docs/services/backup.md b/docs/services/backup.md index 1c52951e4b..ce2e14ef36 100644 --- a/docs/services/backup.md +++ b/docs/services/backup.md @@ -267,8 +267,10 @@ Continue with `nextToken` in the same account and region, keeping `includeDelete unchanged. Region and deletion-date filters apply before paging. Final pages omit `NextToken`, and deleting or renaming the cursor plan does not skip the next plan. `includeDeleted` defaults to false. When true, retained records include their -`DeletionDate`; normal plan deletion still removes the record, so deleted history -is not retained. +`DeletionDate`. Deleting a plan retains its listing metadata in the configured +storage backend. Deleted plans remain unavailable to Get, Update, tags and new +selections, and are omitted from default listings. Plans with active selections +cannot be deleted. ## Examples diff --git a/src/main/java/io/floci/aws/services/backup/BackupService.java b/src/main/java/io/floci/aws/services/backup/BackupService.java index 5569a53ef3..f11d407213 100644 --- a/src/main/java/io/floci/aws/services/backup/BackupService.java +++ b/src/main/java/io/floci/aws/services/backup/BackupService.java @@ -661,6 +661,7 @@ public class BackupService { public BackupPlan getBackupPlan(String planId) { return planStore.get(planId) + .filter(plan -> plan.getDeletionDate() == null) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Backup plan not found: " + planId, 400)); } @@ -688,19 +689,22 @@ public class BackupService { throw new AwsException("InvalidRequestException", "Backup plan has active selections and cannot be deleted", 400); } - planStore.delete(planId); - plan.setDeletionDate(Instant.now().getEpochSecond()); - return plan; + BackupPlan deleted = objectMapper.convertValue(plan, BackupPlan.class); + deleted.setDeletionDate(Instant.now().getEpochSecond()); + planStore.put(planId, deleted); + return deleted; } } public List listBackupPlans() { - return planStore.scan(k -> true); + return planStore.scan(k -> true).stream() + .filter(plan -> plan.getDeletionDate() == null) + .toList(); } public PaginatedResult listBackupPlans(String region, boolean includeDeleted, Integer maxResults, String nextToken) { - List plans = listBackupPlans().stream() + List plans = planStore.scan(k -> true).stream() .filter(plan -> region.equals(AwsArnUtils.regionOrDefault(plan.getBackupPlanArn(), regionResolver.getDefaultRegion()))) .filter(plan -> includeDeleted || plan.getDeletionDate() == null) @@ -714,19 +718,21 @@ public class BackupService { public BackupSelection createBackupSelection(String planId, String selectionName, String iamRoleArn, List resources, List notResources, String creatorRequestId) { - getBackupPlan(planId); - String selectionId = UUID.randomUUID().toString(); - BackupSelection selection = new BackupSelection(); - selection.setSelectionId(selectionId); - selection.setSelectionName(selectionName); - selection.setBackupPlanId(planId); - selection.setIamRoleArn(iamRoleArn); - selection.setResources(resources); - selection.setNotResources(notResources); - selection.setCreationDate(Instant.now().getEpochSecond()); - selection.setCreatorRequestId(creatorRequestId); - selectionStore.put(selectionId, selection); - return selection; + synchronized (lockFor(planLockKey(planId))) { + getBackupPlan(planId); + String selectionId = UUID.randomUUID().toString(); + BackupSelection selection = new BackupSelection(); + selection.setSelectionId(selectionId); + selection.setSelectionName(selectionName); + selection.setBackupPlanId(planId); + selection.setIamRoleArn(iamRoleArn); + selection.setResources(resources); + selection.setNotResources(notResources); + selection.setCreationDate(Instant.now().getEpochSecond()); + selection.setCreatorRequestId(creatorRequestId); + selectionStore.put(selectionId, selection); + return selection; + } } public BackupSelection getBackupSelection(String planId, String selectionId) { @@ -1034,9 +1040,11 @@ public class BackupService { } private BackupPlan findPlanByArn(String arn) { - return planStore.scan(k -> true).stream() - .filter(plan -> arn.equals(plan.getBackupPlanArn())) - .findFirst() + return AwsArnUtils.resourceIfArnFor(arn, "backup") + .filter(resource -> resource.startsWith("backup-plan:")) + .map(resource -> resource.substring("backup-plan:".length())) + .flatMap(planStore::get) + .filter(plan -> arn.equals(plan.getBackupPlanArn()) && plan.getDeletionDate() == null) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource not found: " + arn, 400)); } diff --git a/src/test/java/io/floci/aws/services/backup/BackupDeletedPlanServiceTest.java b/src/test/java/io/floci/aws/services/backup/BackupDeletedPlanServiceTest.java new file mode 100644 index 0000000000..e4ffc43ceb --- /dev/null +++ b/src/test/java/io/floci/aws/services/backup/BackupDeletedPlanServiceTest.java @@ -0,0 +1,228 @@ +package io.floci.aws.services.backup; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.ServiceConfigAccess; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.backup.model.BackupPlan; +import io.floci.aws.services.backup.model.BackupSelection; +import io.floci.aws.services.sns.SnsService; +import io.floci.aws.testing.ParkingStore; +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class BackupDeletedPlanServiceTest { + private static final String ACCOUNT = "741677900013"; + private static final String REGION = "eu-west-2"; + + @ParameterizedTest + @ValueSource(strings = {"persistent", "hybrid", "wal"}) + void deletionSurvivesStorageLifecycleWithoutRestoringActiveAccess(String mode, @TempDir Path path) { + EmulatorConfig config = config(); + when(config.storage().persistentPath()).thenReturn(path.toString()); + when(config.storage().wal().compactionIntervalMs()).thenReturn(60000L); + ServiceConfigAccess access = mock(ServiceConfigAccess.class); + when(access.storageMode("backup")).thenReturn(mode); + when(access.storageFlushInterval("backup")).thenReturn(60000L); + StorageFactory storage = new StorageFactory(config, access); + BackupService service = service(storage, config); + BackupPlan deleted; + try { + BackupPlan plan = service.createBackupPlan("retained", List.of(), null, Map.of("env", "test"), REGION); + deleted = service.deleteBackupPlan(plan.getBackupPlanId()); + assertNotNull(deleted.getDeletionDate()); + } finally { + service.shutdown(); + storage.shutdownAll(); + } + StorageFactory reloadedStorage = new StorageFactory(config, access); + BackupService reloaded = service(reloadedStorage, config); + try { + List history = reloaded.listBackupPlans(REGION, true, null, null).items(); + assertEquals(1, history.size()); + BackupPlan restored = history.getFirst(); + assertEquals(deleted.getBackupPlanId(), restored.getBackupPlanId()); + assertEquals(deleted.getBackupPlanArn(), restored.getBackupPlanArn()); + assertEquals(deleted.getVersionId(), restored.getVersionId()); + assertEquals(deleted.getCreationDate(), restored.getCreationDate()); + assertEquals(deleted.getDeletionDate(), restored.getDeletionDate()); + assertTrue(reloaded.listBackupPlans().isEmpty()); + assertTrue(reloaded.listBackupPlans(REGION, false, null, null).items().isEmpty()); + assertTrue(reloaded.listBackupPlans("us-east-1", true, null, null).items().isEmpty()); + assertNotFound(() -> reloaded.getBackupPlan(restored.getBackupPlanId())); + assertNotFound(() -> reloaded.deleteBackupPlan(restored.getBackupPlanId())); + assertNotFound(() -> reloaded.tagResource(restored.getBackupPlanArn(), Map.of("late", "tag"))); + } finally { + reloaded.shutdown(); + reloadedStorage.shutdownAll(); + } + } + + @Test + void failedRetentionWriteLeavesThePlanActiveAndRetryable() { + AccountAwareStorageBackend plans = spy(AccountAwareStorageBackend.inMemory(ACCOUNT)); + StorageFactory storage = storage(plans, AccountAwareStorageBackend.inMemory(ACCOUNT)); + BackupService service = service(storage, config()); + try { + BackupPlan plan = service.createBackupPlan("retry", List.of(), null, REGION); + doThrow(new IllegalStateException("write refused")).when(plans).put(eq(plan.getBackupPlanId()), any()); + assertThrows(IllegalStateException.class, () -> service.deleteBackupPlan(plan.getBackupPlanId())); + assertSame(plan, service.getBackupPlan(plan.getBackupPlanId())); + assertNull(plan.getDeletionDate()); + assertEquals(1, service.listBackupPlans().size()); + doCallRealMethod().when(plans).put(eq(plan.getBackupPlanId()), any()); + service.deleteBackupPlan(plan.getBackupPlanId()); + assertEquals(1, service.listBackupPlans(REGION, true, null, null).items().size()); + assertNotFound(() -> service.getBackupPlan(plan.getBackupPlanId())); + } finally { + service.shutdown(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectionAndDeletionPublishInPlanLockOrder(boolean deleteFirst) throws Exception { + ParkingStore innerPlans = new ParkingStore<>(); + ParkingStore innerSelections = new ParkingStore<>(); + AccountAwareStorageBackend plans = new AccountAwareStorageBackend<>(innerPlans, null, ACCOUNT); + AccountAwareStorageBackend selections = + new AccountAwareStorageBackend<>(innerSelections, null, ACCOUNT); + BackupService service = service(storage(plans, selections), config()); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + BackupPlan plan = service.createBackupPlan("ordered", List.of(), null, REGION); + Runnable delete = () -> service.deleteBackupPlan(plan.getBackupPlanId()); + Runnable select = () -> service.createBackupSelection(plan.getBackupPlanId(), "selection", "role", + List.of("resource"), List.of(), null); + if (deleteFirst) { + innerPlans.parkNextWrite(); + } else { + innerSelections.parkNextWrite(); + } + Future first = workers.submit(deleteFirst ? delete : select); + assertTrue(deleteFirst ? innerPlans.awaitParked() : innerSelections.awaitParked()); + AtomicReference competing = new AtomicReference<>(); + Future second = workers.submit(() -> { + competing.set(Thread.currentThread()); + return assertThrows(AwsException.class, (deleteFirst ? select : delete)::run); + }); + ThreadStates.awaitBlockedOrDone(competing, second); + assertFalse(second.isDone(), "competing mutation must wait for the same plan lock"); + innerPlans.release(); + innerSelections.release(); + first.get(5, TimeUnit.SECONDS); + assertEquals(deleteFirst ? "ResourceNotFoundException" : "InvalidRequestException", + second.get(5, TimeUnit.SECONDS).getErrorCode()); + assertEquals(deleteFirst ? 0 : 1, service.listBackupSelections(plan.getBackupPlanId()).size()); + assertEquals(deleteFirst ? 0 : 1, service.listBackupPlans().size()); + assertEquals(1, service.listBackupPlans(REGION, true, null, null).items().size()); + } finally { + innerPlans.release(); + innerSelections.release(); + workers.shutdownNow(); + assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS)); + service.shutdown(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"list", "tag", "untag"}) + void planTagsUseKeyedLookupWithoutScanningRetainedHistory(String operation) { + AccountAwareStorageBackend plans = spy(AccountAwareStorageBackend.inMemory(ACCOUNT)); + BackupService service = service(storage(plans, AccountAwareStorageBackend.inMemory(ACCOUNT)), config()); + try { + BackupPlan retained = service.createBackupPlan("deleted", List.of(), null, REGION); + service.deleteBackupPlan(retained.getBackupPlanId()); + BackupPlan active = service.createBackupPlan("active", List.of(), null, Map.of("env", "test"), REGION); + clearInvocations(plans); + switch (operation) { + case "list" -> assertEquals(Map.of("env", "test"), service.listTags(active.getBackupPlanArn())); + case "tag" -> { + service.tagResource(active.getBackupPlanArn(), Map.of("new", "value")); + assertEquals(Map.of("env", "test", "new", "value"), service.listTags(active.getBackupPlanArn())); + } + case "untag" -> { + service.untagResource(active.getBackupPlanArn(), List.of("env")); + assertTrue(service.listTags(active.getBackupPlanArn()).isEmpty()); + } + default -> throw new IllegalArgumentException(operation); + } + verify(plans, never()).scan(any()); + verify(plans, atLeastOnce()).get(active.getBackupPlanId()); + } finally { + service.shutdown(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"account", "region", "partition", "service", "type", "malformed", "deleted"}) + void keyedPlanTagsStillRequireExactActiveArn(String mismatch) { + AccountAwareStorageBackend plans = spy(AccountAwareStorageBackend.inMemory(ACCOUNT)); + BackupService service = service(storage(plans, AccountAwareStorageBackend.inMemory(ACCOUNT)), config()); + try { + BackupPlan plan = service.createBackupPlan("exact", List.of(), null, Map.of("env", "test"), REGION); + String arn = switch (mismatch) { + case "account" -> plan.getBackupPlanArn().replace(ACCOUNT, "999999999999"); + case "region" -> plan.getBackupPlanArn().replace(REGION, "us-east-1"); + case "partition" -> plan.getBackupPlanArn().replace("arn:aws:", "arn:aws-cn:"); + case "service" -> plan.getBackupPlanArn().replace(":backup:", ":other:"); + case "type" -> plan.getBackupPlanArn().replace("backup-plan:", "backup-vault:"); + case "malformed" -> "not-an-arn"; + case "deleted" -> service.deleteBackupPlan(plan.getBackupPlanId()).getBackupPlanArn(); + default -> throw new IllegalArgumentException(mismatch); + }; + assertNotFound(() -> service.listTags(arn)); + assertNotFound(() -> service.tagResource(arn, Map.of("late", "tag"))); + assertNotFound(() -> service.untagResource(arn, List.of("env"))); + assertEquals(Map.of("env", "test"), plans.get(plan.getBackupPlanId()).orElseThrow().getTags()); + } finally { + service.shutdown(); + } + } + + private static void assertNotFound(Runnable operation) { + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, operation::run).getErrorCode()); + } + + private static EmulatorConfig config() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultAccountId()).thenReturn(ACCOUNT); + when(config.services().backup().jobCompletionDelaySeconds()).thenReturn(3600); + return config; + } + + private static StorageFactory storage(AccountAwareStorageBackend plans, + AccountAwareStorageBackend selections) { + StorageFactory storage = mock(StorageFactory.class); + when(storage.create(eq("backup"), anyString(), any())).thenAnswer(call -> switch ((String) call.getArgument(1)) { + case "backup-plans.json" -> plans; + case "backup-selections.json" -> selections; + default -> AccountAwareStorageBackend.inMemory(ACCOUNT); + }); + return storage; + } + + private static BackupService service(StorageFactory storage, EmulatorConfig config) { + return new BackupService(storage, config, new RegionResolver(REGION, ACCOUNT), new ObjectMapper(), + mock(SnsService.class)); + } +} diff --git a/src/test/java/io/floci/aws/services/backup/BackupListPlansPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/backup/BackupListPlansPaginationIntegrationTest.java index 3044ffd6cf..76a6739b32 100644 --- a/src/test/java/io/floci/aws/services/backup/BackupListPlansPaginationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/backup/BackupListPlansPaginationIntegrationTest.java @@ -1,6 +1,10 @@ package io.floci.aws.services.backup; +import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.backup.model.BackupPlan; import io.floci.aws.services.backup.model.BackupRule; import io.floci.aws.testing.AwsTestClients; import io.floci.aws.testing.RestAssuredJsonUtils; @@ -18,12 +22,14 @@ import software.amazon.awssdk.services.backup.BackupClient; import software.amazon.awssdk.services.backup.model.BackupException; import software.amazon.awssdk.services.backup.model.BackupPlansListMember; import software.amazon.awssdk.services.backup.model.BackupRuleInput; +import software.amazon.awssdk.services.backup.model.GetBackupPlanResponse; import software.amazon.awssdk.services.backup.model.ListBackupPlansRequest; import software.amazon.awssdk.services.backup.model.ListBackupPlansResponse; import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import static io.restassured.RestAssured.given; @@ -47,6 +53,9 @@ class BackupListPlansPaginationIntegrationTest { @Inject BackupService service; + @Inject + StorageFactory storage; + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -61,7 +70,15 @@ class BackupListPlansPaginationIntegrationTest { @AfterEach void cleanUp() { try { - RequestScopes.runAs(ACCOUNT, REGION, () -> plans.forEach(service::deleteBackupPlan)); + RequestScopes.runAs(ACCOUNT, REGION, () -> { + AccountAwareStorageBackend store = storage.create("backup", "backup-plans.json", + new TypeReference>() {}); + for (BackupPlan plan : store.scan(key -> true)) { + if (plan.getBackupPlanName().startsWith(name + "-")) { + store.delete(plan.getBackupPlanId()); + } + } + }); client.deleteBackupVault(request -> request.backupVaultName(name)); } finally { client.close(); @@ -113,9 +130,8 @@ class BackupListPlansPaginationIntegrationTest { create(); create(); String deletedId = plans.getFirst(); - Instant deletion = Instant.ofEpochSecond(1720000000); - RequestScopes.runAs(ACCOUNT, REGION, - () -> service.getBackupPlan(deletedId).setDeletionDate(deletion.getEpochSecond())); + Instant deletion = client.deleteBackupPlan(request -> request.backupPlanId(deletedId)).deletionDate(); + assertNotNull(deletion); assertEquals(2, client.listBackupPlans(request -> request.includeDeleted(false)).backupPlansList().size()); ListBackupPlansResponse first = client.listBackupPlans(request -> request.maxResults(1)); assertEquals(1, first.backupPlansList().size()); @@ -130,6 +146,69 @@ class BackupListPlansPaginationIntegrationTest { .findFirst().orElseThrow().deletionDate()); } + @Test + void deletedPlanRetainsItsSummaryButRejectsActiveOperations() { + create(); + String id = plans.getFirst(); + GetBackupPlanResponse before = + client.getBackupPlan(request -> request.backupPlanId(id)); + Instant deleted = client.deleteBackupPlan(request -> request.backupPlanId(id)).deletionDate(); + assertTrue(client.listBackupPlans().backupPlansList().isEmpty()); + assertTrue(client.listBackupPlans(request -> request.includeDeleted(false)).backupPlansList().isEmpty()); + List history = client.listBackupPlans(request -> request.includeDeleted(true)) + .backupPlansList(); + assertEquals(1, history.size()); + BackupPlansListMember summary = history.getFirst(); + assertEquals(id, summary.backupPlanId()); + assertEquals(before.backupPlanArn(), summary.backupPlanArn()); + assertEquals(before.versionId(), summary.versionId()); + assertEquals(before.creationDate(), summary.creationDate()); + assertEquals(deleted, summary.deletionDate()); + for (Runnable operation : List.of( + () -> client.getBackupPlan(request -> request.backupPlanId(id)), + () -> client.deleteBackupPlan(request -> request.backupPlanId(id)), + () -> client.updateBackupPlan(request -> request.backupPlanId(id).backupPlan(body -> body + .backupPlanName(name).rules(BackupRuleInput.builder().ruleName("daily") + .targetBackupVaultName(name).build()))), + () -> client.tagResource(request -> request.resourceArn(before.backupPlanArn()).tags(Map.of("x", "y"))), + () -> client.untagResource(request -> request.resourceArn(before.backupPlanArn()).tagKeyList("x")), + () -> client.listTags(request -> request.resourceArn(before.backupPlanArn())), + () -> client.createBackupSelection(request -> request.backupPlanId(id).backupSelection(body -> body + .selectionName("late").iamRoleArn("arn:aws:iam::" + ACCOUNT + ":role/backup") + .resources("arn:aws:s3:::example"))))) { + BackupException error = assertThrows(BackupException.class, operation::run); + assertEquals("ResourceNotFoundException", error.awsErrorDetails().errorCode()); + } + assertEquals(deleted, client.listBackupPlans(request -> request.includeDeleted(true)) + .backupPlansList().getFirst().deletionDate()); + } + + @ParameterizedTest + @CsvSource({"741664900002,eu-north-1", "741664900001,us-west-2"}) + void deletedHistoryAndItsTokensRemainAccountAndRegionScoped(String account, String region) { + create(); + create(); + client.deleteBackupPlan(request -> request.backupPlanId(plans.getFirst())); + ListBackupPlansResponse page = client.listBackupPlans(request -> request.includeDeleted(true).maxResults(1)); + assertNotNull(page.nextToken()); + assertEquals(2, client.listBackupPlans(request -> request.includeDeleted(true)).backupPlansList().size()); + try (BackupClient other = AwsTestClients.create(BackupClient.builder(), account, Region.of(region))) { + assertTrue(other.listBackupPlans(request -> request.includeDeleted(true)).backupPlansList().stream() + .noneMatch(plan -> plans.contains(plan.backupPlanId()))); + BackupException error = assertThrows(BackupException.class, () -> other.listBackupPlans(request -> request + .includeDeleted(true).nextToken(page.nextToken()))); + assertEquals("InvalidParameterValueException", error.awsErrorDetails().errorCode()); + } + BackupException error = assertThrows(BackupException.class, () -> client.listBackupPlans(request -> request + .includeDeleted(false).nextToken(page.nextToken()))); + assertEquals("InvalidParameterValueException", error.awsErrorDetails().errorCode()); + ListBackupPlansResponse remaining = client.listBackupPlans(request -> request.includeDeleted(true) + .nextToken(page.nextToken())); + assertEquals(plans.stream().sorted().toList(), List.of(page, remaining).stream() + .flatMap(result -> result.backupPlansList().stream()).map(BackupPlansListMember::backupPlanId).toList()); + assertNull(remaining.nextToken()); + } + @Test void vaultListingTokenCannotBeUsedForPlans() { List vaults = new ArrayList<>();