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

Per-service provisioner over BackupService. Ref and Fn::GetAtt
BackupVaultName are the vault name and Fn::GetAtt BackupVaultArn its ARN. 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 as well.
BackupVaultTags are driven to the template's set on update, untagging dropped
keys since TagResource only adds. Stack deletion deletes the vault and leaves
the non-empty-vault refusal to surface as on AWS.

The docs generator gains a label and row position for the new AWS::Backup
namespace.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-06 22:18:18 -05:00
1 parent 3a4982c294
commit 631df1dc01
7 files changed
+546

No files matched your search

@@ -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();
}
}
@@ -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;
@@ -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));
}
}