Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision AWS::Backup::BackupVault (#3125)

lex00631df1dc016e
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index ac10cc035d..887cb3061e 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -94,6 +94,7 @@ cross-resource references.
| ACM | `Certificate` |
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
| EventBridge Scheduler | `ScheduleGroup` |
+| Backup | `BackupVault` |
| Pipes | `Pipe` |
| Kinesis | `Stream` |
| Kinesis Data Firehose | `DeliveryStream` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisioner.java
new file mode 100644
index 0000000000..08aca2e6c6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisioner.java
@@ -0,0 +1,159 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.backup.BackupService;
+import io.github.hectorvent.floci.services.backup.model.BackupVault;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * CloudFormation provisioning for {@code AWS::Backup::BackupVault}, backed by {@link BackupService}.
+ * {@code Ref} and {@code Fn::GetAtt BackupVaultName} are the vault name and
+ * {@code Fn::GetAtt BackupVaultArn} its ARN, matching AWS.
+ *
+ * <p>The name is the physical id and createOnly, so an unnamed vault keeps its generated name across
+ * updates instead of getting a second vault, and a rename is refused as a replacement. EncryptionKeyArn
+ * is createOnly too. BackupVaultTags update in place. AccessPolicy, Notifications and
+ * LockConfiguration have no counterpart in the emulated vault and are accepted without effect.
+ */
+@ApplicationScoped
+public class BackupVaultCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(BackupVaultCfnProvisioner.class);
+
+ private static final String TYPE = "AWS::Backup::BackupVault";
+ private static final String NOT_FOUND = "ResourceNotFoundException";
+ /** The Backup API's limit on a vault name. */
+ private static final int VAULT_NAME_MAX = 50;
+
+ private final BackupService backupService;
+
+ @Inject
+ public BackupVaultCfnProvisioner(BackupService backupService) {
+ this.backupService = backupService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "BackupVaultName"),
+ r.getLogicalId(), VAULT_NAME_MAX, false);
+ String encryptionKeyArn = blankToNull(ctx.resolveOptional(props, "EncryptionKeyArn"));
+ Map<String, String> tags = vaultTags(props, ctx);
+
+ if (ctx.isUpdate()) {
+ if (!ctx.reusesPriorEntity(name)) {
+ throw replacementNotSupported("BackupVaultName");
+ }
+ BackupVault existing = findVault(name, ctx.region());
+ if (existing != null) {
+ rejectIfChanged("EncryptionKeyArn", existing.getEncryptionKeyArn(), encryptionKeyArn);
+ reconcileTags(existing, tags);
+ record(r, existing);
+ return;
+ }
+ }
+ record(r, backupService.createBackupVault(name, encryptionKeyArn, UUID.randomUUID().toString(),
+ tags, ctx.region()));
+ }
+
+ /**
+ * Drives the vault's tags to the template's set. TagResource only adds, so a key the template
+ * dropped has to be untagged explicitly.
+ */
+ private void reconcileTags(BackupVault vault, Map<String, String> desired) {
+ Map<String, String> current = vault.getTags() == null ? Map.of() : vault.getTags();
+ List<String> stale = ProvisionContext.staleTagKeys(current, desired);
+ if (!stale.isEmpty()) {
+ backupService.untagResource(vault.getBackupVaultArn(), stale);
+ }
+ boolean changed = desired.entrySet().stream()
+ .anyMatch(e -> !Objects.equals(current.get(e.getKey()), e.getValue()));
+ if (changed) {
+ backupService.tagResource(vault.getBackupVaultArn(), desired);
+ }
+ }
+
+ private BackupVault findVault(String name, String region) {
+ try {
+ return backupService.describeBackupVault(name, region);
+ } catch (AwsException e) {
+ if (!NOT_FOUND.equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("Backup vault {0} from the previous provision is gone, creating it again", name);
+ return null;
+ }
+ }
+
+ /**
+ * {@code BackupVaultTags} is a plain JSON object of key/value pairs, not the {@code [{Key, Value}]}
+ * list most types use, so {@code ProvisionContext.resolveTags} does not apply. Values still go
+ * through the engine so a {@code Ref} or {@code Fn::Sub} inside the map resolves.
+ */
+ private static Map<String, String> vaultTags(JsonNode props, ProvisionContext ctx) {
+ Map<String, String> tags = new LinkedHashMap<>();
+ if (props == null || !props.hasNonNull("BackupVaultTags")) {
+ return tags;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get("BackupVaultTags"));
+ if (resolved == null || !resolved.isObject()) {
+ return tags;
+ }
+ for (Iterator<Map.Entry<String, JsonNode>> it = resolved.fields(); it.hasNext();) {
+ Map.Entry<String, JsonNode> entry = it.next();
+ String value = ctx.engine().resolve(entry.getValue());
+ tags.put(entry.getKey(), value == null ? "" : value);
+ }
+ return tags;
+ }
+
+ private static void record(StackResource r, BackupVault vault) {
+ r.setPhysicalId(vault.getBackupVaultName());
+ r.getAttributes().put("BackupVaultName", vault.getBackupVaultName());
+ r.getAttributes().put("BackupVaultArn", vault.getBackupVaultArn());
+ }
+
+ private static void rejectIfChanged(String property, String existing, String requested) {
+ if (!Objects.equals(blankToNull(existing), blankToNull(requested))) {
+ throw replacementNotSupported(property);
+ }
+ }
+
+ private static AwsException replacementNotSupported(String property) {
+ return new AwsException("ValidationError",
+ "Updating " + property + " requires resource replacement, which is not supported.", 400);
+ }
+
+ private static String blankToNull(String value) {
+ return value == null || value.isBlank() ? null : value;
+ }
+
+ /**
+ * Without this the vault outlives its stack. A vault that still holds recovery points refuses to
+ * go, as on AWS, and that failure is left to surface on the stack delete.
+ */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ CfnDeletes.safeDelete("backup vault", physicalId,
+ () -> backupService.deleteBackupVault(physicalId, region), NOT_FOUND);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/BackupVaultCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/BackupVaultCfnIntegrationTest.java
new file mode 100644
index 0000000000..f99c228278
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/BackupVaultCfnIntegrationTest.java
@@ -0,0 +1,157 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Provisions two {@code AWS::Backup::BackupVault} resources through a CloudFormation stack, one
+ * named with a KMS key and tags and one with no properties at all. Asserts that {@code Ref} and
+ * {@code Fn::GetAtt BackupVaultName} are the name and {@code Fn::GetAtt BackupVaultArn} the ARN
+ * {@code DescribeBackupVault} serves, that an update changes tags on the same vault, and that
+ * deleting the stack removes both vaults.
+ */
+@QuarkusTest
+class BackupVaultCfnIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
+ private static final String BACKUP_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/backup/aws4_request";
+ private static final String STACK = "backup-vault-cfn-it";
+ private static final String NAMED = "backup-vault-cfn-it-named";
+ private static final String KMS = "arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555";
+
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {"TagValue": {"Type": "String"}},
+ "Resources": {
+ "Named": {
+ "Type": "AWS::Backup::BackupVault",
+ "Properties": {
+ "BackupVaultName": "%s",
+ "EncryptionKeyArn": "%s",
+ "BackupVaultTags": {"stack": {"Ref": "TagValue"}, "team": "core"}
+ }
+ },
+ "Unnamed": {"Type": "AWS::Backup::BackupVault"}
+ },
+ "Outputs": {
+ "NamedRef": {"Value": {"Ref": "Named"}},
+ "NamedName": {"Value": {"Fn::GetAtt": ["Named", "BackupVaultName"]}},
+ "NamedArn": {"Value": {"Fn::GetAtt": ["Named", "BackupVaultArn"]}},
+ "UnnamedRef": {"Value": {"Ref": "Unnamed"}}
+ }
+ }
+ """.formatted(NAMED, KMS);
+
+ @Test
+ void createUpdateAndDeleteBackupVaults() throws InterruptedException {
+ cloudFormation("CreateStack", Map.of("TagValue", "v1"));
+ String created = describeStacks("CREATE_COMPLETE");
+ String namedArn = outputValue(created, "NamedArn");
+ String unnamed = outputValue(created, "UnnamedRef");
+
+ // Ref and Fn::GetAtt BackupVaultName are the name; the ARN is what the service reports.
+ assertEquals(NAMED, outputValue(created, "NamedRef"));
+ assertEquals(NAMED, outputValue(created, "NamedName"));
+ describeVault(NAMED)
+ .statusCode(200)
+ .body("BackupVaultArn", equalTo(namedArn))
+ .body("EncryptionKeyArn", equalTo(KMS))
+ .body("Tags.stack", equalTo("v1"))
+ .body("Tags.team", equalTo("core"));
+
+ // A vault with no properties gets a CloudFormation-style generated name within the 50-char limit.
+ describeVault(unnamed)
+ .statusCode(200)
+ .body("BackupVaultName", startsWith(STACK + "-Unnamed-"))
+ .body("EncryptionKeyArn", nullValue());
+
+ cloudFormation("UpdateStack", Map.of("TagValue", "v2"));
+ String updated = describeStacks("UPDATE_COMPLETE");
+
+ // The tag changes on the same vault; nothing is replaced.
+ assertEquals(namedArn, outputValue(updated, "NamedArn"));
+ assertEquals(unnamed, outputValue(updated, "UnnamedRef"));
+ describeVault(NAMED)
+ .statusCode(200)
+ .body("Tags.stack", equalTo("v2"))
+ .body("Tags.team", equalTo("core"));
+
+ cloudFormation("DeleteStack", Map.of());
+ awaitStackDeleted();
+
+ describeVault(NAMED).statusCode(404);
+ describeVault(unnamed).statusCode(404);
+ }
+
+ private static void cloudFormation(String action, Map<String, String> parameters) {
+ RequestSpecification request = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", STACK);
+ if (!"DeleteStack".equals(action)) {
+ request.formParam("TemplateBody", TEMPLATE);
+ }
+ int index = 1;
+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {
+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
+ index++;
+ }
+ request.when().post("/").then().statusCode(200);
+ }
+
+ private static String describeStacks(String expectedStatus) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", STACK)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
+ .extract().asString();
+ }
+
+ /** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
+ private static void awaitStackDeleted() throws InterruptedException {
+ for (int i = 0; i < 100; i++) {
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", STACK)
+ .when().post("/").then().extract().asString();
+ if (body.contains("does not exist")) {
+ return;
+ }
+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
+ fail("stack delete failed: " + body);
+ }
+ Thread.sleep(50);
+ }
+ fail("stack " + STACK + " was not deleted within the timeout");
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+
+ private static ValidatableResponse describeVault(String name) {
+ return given().header("Authorization", BACKUP_AUTH).when().get("/backup-vaults/" + name).then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 04bba8690e..bfa090883e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+import io.github.hectorvent.floci.services.backup.BackupService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.batch.BatchService;
@@ -28,6 +29,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
@@ -163,6 +165,7 @@ final class CfnProvisionerFixture {
private OrganizationsService organizationsService;
private SqsService sqsService;
private WafV2Service wafV2Service;
+ private BackupService backupService;
private CloudFormationResourceRegistry resourceRegistry;
private boolean registryChosenByTest;
private CfnDynamicReferences dynamicReferences;
@@ -282,6 +285,9 @@ final class CfnProvisionerFixture {
if (sqsService != null) {
discovered.add(new SqsCfnProvisioner(sqsService));
}
+ if (backupService != null) {
+ discovered.add(new BackupVaultCfnProvisioner(backupService));
+ }
if (wafV2Service != null) {
discovered.add(new WafV2CfnProvisioner(wafV2Service));
}
@@ -517,6 +523,11 @@ final class CfnProvisionerFixture {
return this;
}
+ public Builder backup(BackupService v) {
+ this.backupService = v;
+ return this;
+ }
+
public Builder registry(CloudFormationResourceRegistry v) {
this.resourceRegistry = v;
this.registryChosenByTest = true;
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisionerTest.java
new file mode 100644
index 0000000000..ac14af5991
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BackupVaultCfnProvisionerTest.java
@@ -0,0 +1,215 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.backup.BackupService;
+import io.github.hectorvent.floci.services.backup.model.BackupVault;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** The Backup vault CFN provisioner in isolation, against a mocked {@link BackupService}. */
+class BackupVaultCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String TYPE = "AWS::Backup::BackupVault";
+ private static final String ARN = "arn:aws:backup:us-east-1:000000000000:backup-vault:my-vault";
+ private static final String KMS = "arn:aws:kms:us-east-1:000000000000:key/abc";
+ private static final AwsException NOT_FOUND =
+ new AwsException("ResourceNotFoundException", "Backup vault not found: my-vault", 404);
+
+ private final BackupService backup = mock(BackupService.class);
+ private final BackupVaultCfnProvisioner provisioner = new BackupVaultCfnProvisioner(backup);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private static StackResource resource(String priorPhysicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyVault");
+ r.setResourceType(TYPE);
+ r.setPhysicalId(priorPhysicalId);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static BackupVault vault(String name, String encryptionKeyArn, Map<String, String> tags) {
+ BackupVault vault = new BackupVault();
+ vault.setBackupVaultName(name);
+ vault.setBackupVaultArn(ARN);
+ vault.setEncryptionKeyArn(encryptionKeyArn);
+ vault.setTags(new HashMap<>(tags));
+ return vault;
+ }
+
+ private ObjectNode props(String name, String encryptionKeyArn, Map<String, String> tags) {
+ ObjectNode props = mapper.createObjectNode();
+ if (name != null) {
+ props.put("BackupVaultName", name);
+ }
+ if (encryptionKeyArn != null) {
+ props.put("EncryptionKeyArn", encryptionKeyArn);
+ }
+ if (tags != null) {
+ ObjectNode node = props.putObject("BackupVaultTags");
+ tags.forEach(node::put);
+ }
+ return props;
+ }
+
+ @Test
+ void createSendsNameKeyAndTagsAndRecordsBothAttributes() {
+ when(backup.createBackupVault(eq("my-vault"), eq(KMS), anyString(), anyMap(), eq(REGION)))
+ .thenReturn(vault("my-vault", KMS, Map.of("env", "prod")));
+ StackResource r = resource(null);
+
+ provisioner.provision(r, props("my-vault", KMS, Map.of("env", "prod")), ctx());
+
+ assertEquals("my-vault", r.getPhysicalId());
+ assertEquals("my-vault", r.getAttributes().get("BackupVaultName"));
+ assertEquals(ARN, r.getAttributes().get("BackupVaultArn"));
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.forClass(Map.class);
+ verify(backup).createBackupVault(eq("my-vault"), eq(KMS), anyString(), tags.capture(), eq(REGION));
+ assertEquals(Map.of("env", "prod"), tags.getValue());
+ }
+
+ @Test
+ void unnamedVaultGetsAGeneratedName() {
+ when(backup.createBackupVault(anyString(), isNull(), anyString(), anyMap(), eq(REGION)))
+ .thenReturn(vault("generated", null, Map.of()));
+
+ provisioner.provision(resource(null), mapper.createObjectNode(), ctx());
+
+ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
+ verify(backup).createBackupVault(name.capture(), isNull(), anyString(), eq(Map.of()), eq(REGION));
+ assertTrue(name.getValue().startsWith("my-stack-MyVault-"), name.getValue());
+ assertTrue(name.getValue().length() <= 50, name.getValue());
+ }
+
+ @Test
+ void updateKeepsTheVaultAndDrivesTagsToTheTemplate() {
+ when(backup.describeBackupVault("my-vault", REGION))
+ .thenReturn(vault("my-vault", KMS, Map.of("env", "prod", "stale", "x")));
+ StackResource r = resource("my-vault");
+
+ provisioner.provision(r, props("my-vault", KMS, Map.of("env", "dev", "team", "core")), ctx("my-vault"));
+
+ verify(backup, never()).createBackupVault(any(), any(), any(), anyMap(), any());
+ verify(backup).untagResource(ARN, List.of("stale"));
+ verify(backup).tagResource(ARN, Map.of("env", "dev", "team", "core"));
+ assertEquals("my-vault", r.getPhysicalId());
+ assertEquals(ARN, r.getAttributes().get("BackupVaultArn"));
+ }
+
+ @Test
+ void anUnnamedVaultKeepsItsGeneratedNameAcrossAnUpdate() {
+ when(backup.describeBackupVault("my-stack-MyVault-abc", REGION))
+ .thenReturn(vault("my-stack-MyVault-abc", null, Map.of()));
+ StackResource r = resource("my-stack-MyVault-abc");
+
+ provisioner.provision(r, mapper.createObjectNode(), ctx("my-stack-MyVault-abc"));
+
+ verify(backup, never()).createBackupVault(any(), any(), any(), anyMap(), any());
+ assertEquals("my-stack-MyVault-abc", r.getPhysicalId());
+ }
+
+ @Test
+ void anUnchangedUpdateTouchesNothing() {
+ when(backup.describeBackupVault("my-vault", REGION)).thenReturn(vault("my-vault", KMS, Map.of("env", "prod")));
+
+ provisioner.provision(resource("my-vault"), props("my-vault", KMS, Map.of("env", "prod")), ctx("my-vault"));
+
+ verify(backup, never()).createBackupVault(any(), any(), any(), anyMap(), any());
+ verify(backup, never()).tagResource(any(), anyMap());
+ verify(backup, never()).untagResource(any(), anyList());
+ }
+
+ @Test
+ void aRenameIsRefusedAsReplacementWorthy() {
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("my-vault"), props("other-vault", null, null), ctx("my-vault")));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("BackupVaultName"), e.getMessage());
+ verify(backup, never()).describeBackupVault(any(), any());
+ verify(backup, never()).createBackupVault(any(), any(), any(), anyMap(), any());
+ }
+
+ @Test
+ void aChangedEncryptionKeyIsRefusedAsReplacementWorthy() {
+ when(backup.describeBackupVault("my-vault", REGION)).thenReturn(vault("my-vault", KMS, Map.of()));
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("my-vault"), props("my-vault", "arn:aws:kms:us-east-1:000000000000:key/other", null),
+ ctx("my-vault")));
+
+ assertTrue(e.getMessage().contains("EncryptionKeyArn"), e.getMessage());
+ verify(backup, never()).tagResource(any(), anyMap());
+ }
+
+ @Test
+ void aVaultDeletedOutOfBandIsCreatedAgain() {
+ when(backup.describeBackupVault("my-vault", REGION)).thenThrow(NOT_FOUND);
+ when(backup.createBackupVault(eq("my-vault"), isNull(), anyString(), anyMap(), eq(REGION)))
+ .thenReturn(vault("my-vault", null, Map.of()));
+ StackResource r = resource("my-vault");
+
+ provisioner.provision(r, props("my-vault", null, null), ctx("my-vault"));
+
+ verify(backup).createBackupVault(eq("my-vault"), isNull(), anyString(), anyMap(), eq(REGION));
+ assertEquals(ARN, r.getAttributes().get("BackupVaultArn"));
+ }
+
+ @Test
+ void deleteDelegatesAndToleratesAMissingVault() {
+ provisioner.delete(TYPE, "my-vault", REGION);
+ verify(backup).deleteBackupVault("my-vault", REGION);
+
+ doThrow(NOT_FOUND).when(backup).deleteBackupVault("gone", REGION);
+ assertDoesNotThrow(() -> provisioner.delete(TYPE, "gone", REGION));
+ }
+
+ @Test
+ void deleteOfANonEmptyVaultStillFails() {
+ doThrow(new AwsException("InvalidRequestException", "Non-empty backup vault cannot be deleted: full", 400))
+ .when(backup).deleteBackupVault("full", REGION);
+
+ assertThrows(AwsException.class, () -> provisioner.delete(TYPE, "full", REGION));
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index e866fe0e85..53e1bf9776 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -20,6 +20,7 @@ AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH
AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
AWS::AutoScaling::ScalingPolicy AutoScalingScalingPolicyCfnProvisioner
+AWS::Backup::BackupVault BackupVaultCfnProvisioner
AWS::Batch::ComputeEnvironment LEGACY_SWITCH
AWS::Batch::JobDefinition LEGACY_SWITCH
AWS::Batch::JobQueue LEGACY_SWITCH
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index f03c3f2f7e..6cda91ee01 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -38,6 +38,7 @@ order:
- AWS::CertificateManager
- AWS::Events
- AWS::Scheduler
+ - AWS::Backup
- AWS::Pipes
- AWS::Kinesis
- AWS::KinesisFirehose
@@ -99,6 +100,7 @@ service_labels:
AWS::ApiGatewayV2: API Gateway v2
AWS::AutoScaling: Auto Scaling
AWS::Batch: Batch
+ AWS::Backup: Backup
AWS::CDK: CDK
AWS::CertificateManager: ACM
AWS::CloudFormation: CloudFormation