fix(backup): publish BACKUP_JOB_COMPLETED to the vault's SNS topic (#5623)

* fix(backup): publish BACKUP_JOB_COMPLETED to the vault's SNS topic

PutBackupVaultNotifications stored the configuration but job completion
never read it, so a subscriber received nothing. When a backup job
completes in a vault whose BackupVaultEvents include BACKUP_JOB_COMPLETED,
publish one message to the configured SNSTopicArn after the job and
recovery point are stored. A failed publish is logged and never undoes
the completion. Other events remain stored-only; docs say which.

* fix(backup): log the exception when a BACKUP_JOB_COMPLETED publish fails

* test(backup): import log-capture classes instead of qualifying them inline

* fix(backup): notify only the vault a job started in, not a same-name replacement

completeJob looked the vault up by name at completion time, so a job whose
vault was deleted and recreated mid-run published BACKUP_JOB_COMPLETED to the
replacement vault's topic. Pin the vault's sub-resource key (which carries its
creation date) when the job starts and read the notification configuration
through it; a deleted vault's configuration goes with it, so nothing is sent.

* fix(backup): match AWS's BACKUP_JOB_COMPLETED message and pin vaults by id

The published notification now follows AWS's documented "Backup job
completed" example: the body ends at the BackupJob ID with no vault name,
and the publish carries the EventType, State, AccountId, Id and StartTime
message attributes that subscription filter policies match on.

Vault sub-resources and in-flight jobs were bound to a vault by its
creation second, so a vault deleted and recreated within the same second
shared a key with its predecessor and a running job could notify the
replacement. Each vault now gets a random FlociVaultId at creation and
the sub-resource key uses it; vaults stored before the field existed fall
back to the creation date, so their stored configuration is still found.
The id is persisted but stripped from DescribeBackupVault and
ListBackupVaults responses.

* test(backup): spell out the RequestSpecification type instead of var
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-15 23:14:33 -04:00
1 parent 007744b925
commit c23641457a
5 files changed
+277 -23

No files matched your search

@@ -65,7 +65,7 @@ public class BackupController {
public Response describeBackupVault(@Context HttpHeaders headers,
@PathParam("backupVaultName") String vaultName) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(service.describeBackupVault(vaultName, region)).build();
return Response.ok(vaultJson(service.describeBackupVault(vaultName, region))).build();
}
@DELETE
@@ -84,10 +84,17 @@ public class BackupController {
List<BackupVault> vaults = service.listBackupVaults(region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("BackupVaultList");
vaults.forEach(list::addPOJO);
vaults.forEach(v -> list.add(vaultJson(v)));
return Response.ok(out).build();
}
/** The vault as AWS reports it: its stored form minus Floci's internal incarnation id. */
private ObjectNode vaultJson(BackupVault vault) {
ObjectNode node = objectMapper.valueToTree(vault);
node.remove(BackupVault.VAULT_ID_FIELD);
return node;
}
// ── Vault access policy ────────────────────────────────────────────────────
//
// These three used to be one unconditional GET that always answered
@@ -11,12 +11,15 @@ import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.backup.model.*;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -43,6 +46,7 @@ public class BackupService {
private final StorageBackend<String, BackupVaultNotifications> notificationStore;
private final RegionResolver regionResolver;
private final SnsService snsService;
private final int jobCompletionDelaySeconds;
private final ObjectMapper objectMapper;
@@ -63,7 +67,7 @@ public class BackupService {
@Inject
public BackupService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
ObjectMapper objectMapper) {
ObjectMapper objectMapper, SnsService snsService) {
this.vaultStore = storageFactory.create("backup", "backup-vaults.json", new TypeReference<>() {});
this.planStore = storageFactory.create("backup", "backup-plans.json", new TypeReference<>() {});
this.selectionStore = storageFactory.create("backup", "backup-selections.json", new TypeReference<>() {});
@@ -73,6 +77,7 @@ public class BackupService {
this.notificationStore = storageFactory.create("backup", "backup-vault-notifications.json", new TypeReference<>() {});
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.snsService = snsService;
this.jobCompletionDelaySeconds = config.services().backup().jobCompletionDelaySeconds();
}
@@ -108,6 +113,7 @@ public class BackupService {
vault.setBackupVaultArn(regionResolver.buildArn("backup", region, "backup-vault:" + vaultName));
vault.setEncryptionKeyArn(encryptionKeyArn);
vault.setCreationDate(Instant.now().getEpochSecond());
vault.setVaultId(UUID.randomUUID().toString());
vault.setCreatorRequestId(creatorRequestId);
vault.setNumberOfRecoveryPoints(0);
vault.setTags(tags);
@@ -150,7 +156,7 @@ public class BackupService {
// Dependents first, the vault record last. There is no transaction across three
// stores, so whatever sits between the first delete and the last is observable, and
// this order keeps the observable state a vault with no configuration rather than a
// configuration with no vault. The sub-resource keys carry this vault's creation date,
// configuration with no vault. The sub-resource keys carry this vault's FlociVaultId,
// so these two deletes cannot reach a configuration belonging to a later vault that
// has taken the same name -- which is what made the previous order lose data.
accessPolicyStore.delete(subResourceKey(region, vault));
@@ -601,13 +607,16 @@ public class BackupService {
String accountId = regionResolver.getAccountId();
job.setAccountId(accountId);
jobStore.put(jobId, job);
// Pinned now, not looked up by name at completion: if this vault is deleted and the name
// reused while the job runs, the job must not notify the replacement vault's topic.
String notificationKey = subResourceKey(region, vault);
// The scheduler thread has no request context; run in the caller's account
// so the account-aware stores and buildArn resolve the right partition.
scheduler.schedule(() -> RequestScopes.runAs(accountId,
() -> transitionJob(jobId, vaultName, region)), 1, TimeUnit.SECONDS);
scheduler.schedule(() -> RequestScopes.runAs(accountId,
() -> completeJob(jobId, vaultName, region)), jobCompletionDelaySeconds, TimeUnit.SECONDS);
() -> completeJob(jobId, vaultName, region, notificationKey)), jobCompletionDelaySeconds, TimeUnit.SECONDS);
return job;
}
@@ -725,7 +734,7 @@ public class BackupService {
});
}
private void completeJob(String jobId, String vaultName, String region) {
private void completeJob(String jobId, String vaultName, String region, String notificationKey) {
jobStore.get(jobId).ifPresent(job -> {
if ("RUNNING".equals(job.getState())) {
long now = Instant.now().getEpochSecond();
@@ -757,10 +766,45 @@ public class BackupService {
incrementVaultCount(vaultName, region);
LOG.infov("Backup job {0} completed, recovery point: {1}", jobId, rpArn);
notifyJobCompleted(job, vaultName, region, notificationKey);
}
});
}
/**
* Publishes BACKUP_JOB_COMPLETED to the vault's SNS topic, if the vault asked for it.
* Runs after the job and recovery point are stored, and never fails the completion: AWS
* does not undo a backup because its notification could not be delivered.
*
* <p>{@code notificationKey} is the sub-resource key of the vault the job started in. A vault
* deleted mid-job takes its configuration with it, so the job publishes nothing rather than
* reaching a later vault that took the same name.
*/
private void notifyJobCompleted(BackupJob job, String vaultName, String region, String notificationKey) {
try {
notificationStore.get(notificationKey)
.filter(n -> n.getBackupVaultEvents() != null
&& n.getBackupVaultEvents().contains("BACKUP_JOB_COMPLETED"))
.ifPresent(n -> snsService.publish(n.getSnsTopicArn(), null, null,
"An AWS Backup job was completed successfully. Recovery point ARN: "
+ job.getRecoveryPointArn() + ". Resource ARN : " + job.getResourceArn()
+ ". BackupJob ID : " + job.getBackupJobId(),
"Notification from AWS Backup",
// AWS's documented "Backup job completed" example; subscription
// filter policies match on these.
Map.of("EventType", new MessageAttributeValue("BACKUP_JOB", "String"),
"State", new MessageAttributeValue("COMPLETED", "String"),
"AccountId", new MessageAttributeValue(job.getAccountId(), "String"),
"Id", new MessageAttributeValue(job.getBackupJobId(), "String"),
"StartTime", new MessageAttributeValue(DateTimeFormatter.ISO_INSTANT
.format(Instant.ofEpochSecond(job.getCreationDate())), "String")),
AwsArnUtils.regionOrDefault(n.getSnsTopicArn(), region)));
} catch (Exception e) {
LOG.warnv(e, "Failed to publish BACKUP_JOB_COMPLETED for job {0} in vault {1}",
job.getBackupJobId(), vaultName);
}
}
private void abortJob(String jobId) {
jobStore.get(jobId).ifPresent(job -> {
if ("ABORTING".equals(job.getState())) {
@@ -875,20 +919,19 @@ public class BackupService {
* the second worse, because two creates racing the existence check would both sweep, and the
* later sweep would delete a configuration applied against the earlier vault.
*
* <p>Including the creation date removes the shared key instead of policing it. A new vault
* cannot read, and cleanup for an old vault cannot touch, a record belonging to a different
* incarnation of the name -- no sweep, and no dependence on the order two stores are written
* in. Deleting a vault still removes its own records, now because they are its own rather
* than because nothing else has claimed them yet.
*
* <p>The creation date is only unique per name because {@code createBackupVault} holds a
* per-name monitor across its check and its write, so two vaults of one name cannot exist
* and cannot be created in the same second. Without that lock this key would still collide
* and the two vaults could read each other's configuration. The delete path also removes its
* own sub-resources, which covers a record surviving for any other reason.
* <p>Including the vault's {@code FlociVaultId}, a random id minted at creation, removes the
* shared key instead of policing it. A new vault cannot read, and cleanup for an old vault
* cannot touch, a record belonging to a different incarnation of the name -- no sweep, and
* no dependence on the order two stores are written in, and no dependence on the clock: a
* vault deleted and recreated within the same second still gets a different key. Deleting a
* vault still removes its own records, now because they are its own rather than because
* nothing else has claimed them yet.
*/
private static String subResourceKey(String region, BackupVault vault) {
return vaultKey(region, vault.getBackupVaultName()) + ":" + vault.getCreationDate();
// Vaults stored before FlociVaultId existed keep their creation-date key, so their
// stored policy and notification configuration are still found.
String incarnation = vault.getVaultId() != null ? vault.getVaultId() : String.valueOf(vault.getCreationDate());
return vaultKey(region, vault.getBackupVaultName()) + ":" + incarnation;
}
private static String vaultKey(BackupVault vault) {
@@ -55,6 +55,16 @@ public class BackupVault {
@JsonProperty("MaxRetentionDays")
private Long maxRetentionDays;
// Floci-internal, not an AWS member: identifies this incarnation of the vault name, so
// sub-resources and in-flight jobs bind to the vault rather than to a name that a
// delete-and-recreate can hand to a different vault within the same second. Persisted,
// but BackupController strips it from every response. Null on vaults stored before it
// existed; BackupService falls back to the creation date for those.
@JsonProperty(VAULT_ID_FIELD)
private String vaultId;
public static final String VAULT_ID_FIELD = "FlociVaultId";
public BackupVault() {}
public String getBackupVaultName() { return backupVaultName; }
@@ -63,6 +73,9 @@ public class BackupVault {
public String getBackupVaultArn() { return backupVaultArn; }
public void setBackupVaultArn(String backupVaultArn) { this.backupVaultArn = backupVaultArn; }
public String getVaultId() { return vaultId; }
public void setVaultId(String vaultId) { this.vaultId = vaultId; }
public String getEncryptionKeyArn() { return encryptionKeyArn; }
public void setEncryptionKeyArn(String encryptionKeyArn) { this.encryptionKeyArn = encryptionKeyArn; }