fix(backup): retain deleted plans for IncludeDeleted listings (#7871)

* fix(backup): retain deleted plans for IncludeDeleted listings

Retain deleted backup-plan listing metadata while excluding deleted plans from active operations. Serialize selection creation with deletion using the existing plan lock.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* perf(backup): resolve plan tags by stored plan identity

Avoid scanning retained backup plans for tag operations. Require the exact stored ARN and active state before retaining the existing locked mutation checks.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-09 22:36:59 -04:00
1 parent fcb2421ee4
commit 184f99490b
4 files changed
+344 -27

No files matched your search

@@ -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<BackupPlan> 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<BackupPlan> 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<BackupPlan> innerPlans = new ParkingStore<>();
ParkingStore<BackupSelection> innerSelections = new ParkingStore<>();
AccountAwareStorageBackend<BackupPlan> plans = new AccountAwareStorageBackend<>(innerPlans, null, ACCOUNT);
AccountAwareStorageBackend<BackupSelection> 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<Thread> competing = new AtomicReference<>();
Future<AwsException> 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<BackupPlan> 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<BackupPlan> 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<BackupPlan> plans,
AccountAwareStorageBackend<BackupSelection> 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));
}
}
@@ -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<BackupPlan> store = storage.create("backup", "backup-plans.json",
new TypeReference<Map<String, BackupPlan>>() {});
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<BackupPlansListMember> 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.<Runnable>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<String> vaults = new ArrayList<>();