diff --git a/docs/services/backup.md b/docs/services/backup.md index 22ae143c99..2ed4df039d 100644 --- a/docs/services/backup.md +++ b/docs/services/backup.md @@ -12,9 +12,32 @@ |---|---|---|---| | `CreateBackupVault` | `PUT` | `/backup-vaults/{backupVaultName}` | Create a backup vault | | `DescribeBackupVault` | `GET` | `/backup-vaults/{backupVaultName}` | Describe a backup vault | -| `DeleteBackupVault` | `DELETE` | `/backup-vaults/{backupVaultName}` | Delete an empty backup vault | +| `DeleteBackupVault` | `DELETE` | `/backup-vaults/{backupVaultName}` | Delete an empty backup vault, locked or not | | `ListBackupVaults` | `GET` | `/backup-vaults/` | List all backup vaults | +### Backup Vault Access Policy + +| Action | Method | Path | Description | +|---|---|---|---| +| `PutBackupVaultAccessPolicy` | `PUT` | `/backup-vaults/{backupVaultName}/access-policy` | Attach a resource policy to a vault | +| `GetBackupVaultAccessPolicy` | `GET` | `/backup-vaults/{backupVaultName}/access-policy` | Read a vault's resource policy | +| `DeleteBackupVaultAccessPolicy` | `DELETE` | `/backup-vaults/{backupVaultName}/access-policy` | Remove a vault's resource policy | + +### Backup Vault Notifications + +| Action | Method | Path | Description | +|---|---|---|---| +| `PutBackupVaultNotifications` | `PUT` | `/backup-vaults/{backupVaultName}/notification-configuration` | Send vault events to an SNS topic | +| `GetBackupVaultNotifications` | `GET` | `/backup-vaults/{backupVaultName}/notification-configuration` | Read a vault's notification configuration | +| `DeleteBackupVaultNotifications` | `DELETE` | `/backup-vaults/{backupVaultName}/notification-configuration` | Remove a vault's notification configuration | + +### Backup Vault Lock + +| Action | Method | Path | Description | +|---|---|---|---| +| `PutBackupVaultLockConfiguration` | `PUT` | `/backup-vaults/{backupVaultName}/vault-lock` | Apply a governance or compliance lock | +| `DeleteBackupVaultLockConfiguration` | `DELETE` | `/backup-vaults/{backupVaultName}/vault-lock` | Remove a lock that is still changeable | + ### Backup Plans | Action | Method | Path | Description | @@ -99,6 +122,76 @@ Actual backup is simulated — no data is read from or written to the referenced - **DeleteBackupVault** returns `InvalidRequestException` (400) if the vault contains recovery points. - **DeleteBackupPlan** returns `InvalidRequestException` (400) if the plan has active selections. - **CreateBackupVault** returns `AlreadyExistsException` (400) on duplicate vault names within the same region. +- **Vault Lock has two modes, and `ChangeableForDays` selects them -- in the direction + that reads backwards.** *Present* means **compliance** mode: `LockDate` is set that many + days ahead, the lock can still be changed or deleted before it, and on and after it both + `PutBackupVaultLockConfiguration` and `DeleteBackupVaultLockConfiguration` return + `InvalidRequestException` (400). *Absent* means **governance** mode: no `LockDate` is + set and the lock can be changed or removed at any time. `ChangeableForDays` below 3 is + rejected, matching AWS's 72-hour cooling-off period; retention days below 1 are rejected. +- **A lock does not stop the vault being deleted.** It protects the recovery points, so an + empty vault can be deleted even under a compliance lock. The non-empty rule above is the + one that refuses. +- **What the lock actually enforces, in both directions.** + `DeleteRecoveryPoint` returns `InvalidRequestException` (400) for a recovery point younger + than `MinRetentionDays` while the vault is locked, and `StartBackupJob` returns + `InvalidParameterValueException` (400) when the lifecycle's `DeleteAfterDays` falls outside + `[MinRetentionDays, MaxRetentionDays]`, **including when the lifecycle is omitted and the + lock sets a maximum** -- retaining indefinitely is the largest retention there is, so it + exceeds every finite ceiling, and waving it through would leave the ceiling bypassable by + dropping one member. An absent lifecycle under a minimum-only lock is accepted, because a + floor is satisfied by indefinite retention. That scoping is Floci's reading rather than a + quotation: the reference states the rule for a lifecycle outside the window and does not + spell out the absent case. Both are the documented purpose of the lock: it + "prevents the deletion of recovery points before their retention periods expire", and + "backup jobs will fail if the lifecycle policy of the backup plan is outside the vault + lock's retention period". **Governance mode enforces here exactly as compliance mode + does.** On real AWS a principal holding `backup:DisableGovernanceRetention` can override a + governance lock; Floci does not model that permission, so it does not grant the override. + That is stricter than AWS for that one privileged caller and identical for every other. +- **The Vault Lock day limits are per field, because AWS documents them per field.** + `ChangeableForDays` must be 3 or greater and at most 36,500. `MaxRetentionDays` is at + most 36,500. `MinRetentionDays` has a documented minimum of 1 day and **no documented + maximum**, so Floci applies none: bounding it would risk refusing a value real AWS + accepts. `MaxRetentionDays` below `MinRetentionDays` is rejected when both are + supplied. +- **PutBackupVaultNotifications** rejects any `BackupVaultEvents` value outside the + documented set with `InvalidParameterValueException` (400), rather than storing it. All + 30 documented values are accepted, including the ones AWS marks deprecated. +- **A missing parameter and an empty one are different errors.** + `PutBackupVaultNotifications` returns `MissingParameterValueException` (400) when + `SNSTopicArn` or `BackupVaultEvents` is absent, which is the error AWS lists in that + operation's Errors section, and `InvalidParameterValueException` (400) when one is + present but unusable (`"SNSTopicArn": ""`, or `"BackupVaultEvents": []`). An SDK maps + the two onto different typed exceptions. The reference names the absent case; the + present-but-unusable one is Floci's reading, not a quotation. +- **`PutBackupVaultAccessPolicy` accepts a request that omits `Policy`.** AWS documents + `Policy` as `Required: No`, so refusing one would fail a call real AWS accepts. What + AWS then stores is **not documented, and we have not measured it**; Floci **clears** + the stored policy, so a subsequent `GetBackupVaultAccessPolicy` returns + `ResourceNotFoundException` (400). That is a deliberate choice rather than an observed + AWS behaviour: it leaves the vault carrying exactly the policy the request carried, + instead of retaining one the caller did not send. A `Policy` that is present but empty + is a different case and is rejected with `InvalidParameterValueException` (400). +- **`Policy` must be a JSON object.** A document that does not parse, or parses to + something other than an object, is rejected with `InvalidParameterValueException` (400) + rather than stored. Syntax only: Floci does not evaluate what the document grants. +- **`SNSTopicArn` must be a JSON string.** A number or boolean is rejected with + `InvalidParameterValueException` (400) rather than coerced, so a request carrying + `"SNSTopicArn": 123` fails instead of storing the topic `"123"`. +- Deleting an access policy or notification configuration that was never set is a no-op, + so a destroy re-run does not fail. +- **A vault's policy and notification configuration are keyed per vault, not per vault + name**, so a vault carries only the configuration applied to it. Reusing a deleted vault's + name therefore starts clean, and cleaning up a deleted vault cannot reach a configuration + belonging to a later vault of the same name. Deleting a vault removes both, dependents + first: the three stores have no transaction between them, and that order keeps any + observable intermediate state a vault without configuration rather than a configuration + without a vault. +- The access policy and notification configuration are **not** returned by + `DescribeBackupVault`, matching AWS: each is reachable only through its own `Get` + operation. The lock fields (`Locked`, `LockDate`, `MinRetentionDays`, + `MaxRetentionDays`) are on the vault, also matching AWS. ## Configuration @@ -109,9 +202,18 @@ Actual backup is simulated — no data is read from or written to the referenced ## Not Yet Supported +- **Notification delivery.** `PutBackupVaultNotifications` stores the configuration and + `GetBackupVaultNotifications` reports it, but no vault event is ever published to the SNS + topic: a subscriber receives nothing when a backup job completes. The configuration is + modelled, the delivery is not, so a Terraform configuration that attaches notifications + applies and reads back correctly while a test asserting on a received message will fail. +- **Access policy enforcement.** `PutBackupVaultAccessPolicy` stores a resource policy and + `GetBackupVaultAccessPolicy` reports it, but no authorization path consults it: a policy + denying a vault operation does not prevent that operation, even with IAM enforcement + enabled. This matches the rest of Floci rather than being specific to Backup -- S3 bucket + policies are the only resource policies any service enforces today. Stated here because a + stored-and-ignored policy is otherwise indistinguishable from an enforced one. - Restore jobs (`StartRestoreJob`, `DescribeRestoreJob`, `ListRestoreJobs`) -- Backup vaults with notifications (`PutBackupVaultNotifications`, `GetBackupVaultNotifications`) -- Backup vaults with access policy (`PutBackupVaultAccessPolicy`, `GetBackupVaultAccessPolicy`) - Copy jobs (`StartCopyJob`, `DescribeCopyJob`, `ListCopyJobs`) - Report plans (`CreateReportPlan`, `DescribeReportPlan`, etc.) - Framework operations (`CreateFramework`, etc.) diff --git a/src/main/java/io/github/hectorvent/floci/services/backup/BackupController.java b/src/main/java/io/github/hectorvent/floci/services/backup/BackupController.java index eed4154194..fa0ab49a35 100644 --- a/src/main/java/io/github/hectorvent/floci/services/backup/BackupController.java +++ b/src/main/java/io/github/hectorvent/floci/services/backup/BackupController.java @@ -88,27 +88,123 @@ public class BackupController { return Response.ok(out).build(); } - // Notification configuration is an optional, never-configured aspect of a vault in the - // emulator. Per the AWS Backup API, GetBackupVaultNotifications returns - // ResourceNotFoundException (HTTP 400) when no notification configuration exists for the - // vault. We mirror that exact error contract so SDK clients see the documented - // "not configured" signal rather than an empty 200 or a generic 400 they can't interpret. - @GET - @Path("/backup-vaults/{backupVaultName}/notification-configuration") - public Response getBackupVaultNotifications(@PathParam("backupVaultName") String vaultName) { - throw new AwsException("ResourceNotFoundException", - "No notification configuration found for backup vault: " + vaultName, 400); + // ── Vault access policy ──────────────────────────────────────────────────── + // + // These three used to be one unconditional GET that always answered + // ResourceNotFoundException, on the reasoning that a policy is "an optional, + // never-configured aspect of a vault in the emulator". That error contract was + // right and is kept below for the genuinely-unconfigured case; what was missing is + // any way to configure one. A vault could be created and never given a policy, a + // lock or a notification target, so every Gruntwork example that configures a vault + // failed at apply. + + @PUT + @Path("/backup-vaults/{backupVaultName}/access-policy") + public Response putBackupVaultAccessPolicy(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); + JsonNode req = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); + // AWS accepts Policy as a JSON string. Terraform sends a string; the console + // sends a string. An object is accepted too and re-serialised, because refusing + // it would be stricter than AWS for no benefit to the caller. + JsonNode policyNode = req.path("Policy"); + String policy = policyNode.isMissingNode() || policyNode.isNull() ? null + : (policyNode.isTextual() ? policyNode.asText() : policyNode.toString()); + service.putBackupVaultAccessPolicy(vaultName, region, policy); + return Response.noContent().build(); } - // Access policy is an optional, never-configured aspect of a vault in the emulator. Per the - // AWS Backup API, GetBackupVaultAccessPolicy returns ResourceNotFoundException (HTTP 400) - // when no policy exists for the vault. We mirror that exact error contract so SDK clients - // see the documented "not configured" signal rather than an empty 200 or a generic 400. @GET @Path("/backup-vaults/{backupVaultName}/access-policy") - public Response getBackupVaultAccessPolicy(@PathParam("backupVaultName") String vaultName) { - throw new AwsException("ResourceNotFoundException", - "No access policy found for backup vault: " + vaultName, 400); + public Response getBackupVaultAccessPolicy(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName) { + String region = regionResolver.resolveRegion(headers); + String policy = service.getBackupVaultAccessPolicy(vaultName, region); + BackupVault vault = service.describeBackupVault(vaultName, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("BackupVaultName", vault.getBackupVaultName()); + out.put("BackupVaultArn", vault.getBackupVaultArn()); + out.put("Policy", policy); + return Response.ok(out).build(); + } + + @DELETE + @Path("/backup-vaults/{backupVaultName}/access-policy") + public Response deleteBackupVaultAccessPolicy(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName) { + String region = regionResolver.resolveRegion(headers); + service.deleteBackupVaultAccessPolicy(vaultName, region); + return Response.noContent().build(); + } + + // ── Vault notifications ──────────────────────────────────────────────────── + + @PUT + @Path("/backup-vaults/{backupVaultName}/notification-configuration") + public Response putBackupVaultNotifications(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); + JsonNode req = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); + // null, not an empty list, when the member is absent: the service answers a missing + // parameter with MissingParameterValueException and an empty one with + // InvalidParameterValueException, and readStringList cannot tell them apart. + JsonNode eventsNode = req.path("BackupVaultEvents"); + List events = eventsNode.isMissingNode() || eventsNode.isNull() ? null + : readStringList(eventsNode); + service.putBackupVaultNotifications(vaultName, region, stringOrNull(req, "SNSTopicArn"), events); + return Response.noContent().build(); + } + + @GET + @Path("/backup-vaults/{backupVaultName}/notification-configuration") + public Response getBackupVaultNotifications(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName) { + String region = regionResolver.resolveRegion(headers); + BackupVaultNotifications notifications = service.getBackupVaultNotifications(vaultName, region); + BackupVault vault = service.describeBackupVault(vaultName, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("BackupVaultName", vault.getBackupVaultName()); + out.put("BackupVaultArn", vault.getBackupVaultArn()); + out.put("SNSTopicArn", notifications.getSnsTopicArn()); + ArrayNode events = out.putArray("BackupVaultEvents"); + notifications.getBackupVaultEvents().forEach(events::add); + return Response.ok(out).build(); + } + + @DELETE + @Path("/backup-vaults/{backupVaultName}/notification-configuration") + public Response deleteBackupVaultNotifications(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName) { + String region = regionResolver.resolveRegion(headers); + service.deleteBackupVaultNotifications(vaultName, region); + return Response.noContent().build(); + } + + // ── Vault lock ───────────────────────────────────────────────────────────── + + @PUT + @Path("/backup-vaults/{backupVaultName}/vault-lock") + public Response putBackupVaultLockConfiguration(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); + JsonNode req = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); + service.putBackupVaultLockConfiguration(vaultName, region, + longOrNull(req, "MinRetentionDays"), + longOrNull(req, "MaxRetentionDays"), + longOrNull(req, "ChangeableForDays")); + return Response.noContent().build(); + } + + @DELETE + @Path("/backup-vaults/{backupVaultName}/vault-lock") + public Response deleteBackupVaultLockConfiguration(@Context HttpHeaders headers, + @PathParam("backupVaultName") String vaultName) { + String region = regionResolver.resolveRegion(headers); + service.deleteBackupVaultLockConfiguration(vaultName, region); + return Response.noContent().build(); } // ── Plan ─────────────────────────────────────────────────────────────────── @@ -365,11 +461,66 @@ public class BackupController { // ── Helpers ──────────────────────────────────────────────────────────────── + // Absent and null both mean "not supplied", which for these members is meaningful: + // omitting ChangeableForDays is what selects compliance mode. + // + // A present value must be an INTEGRAL NUMBER, and is rejected rather than coerced. + // asLong() would silently accept anything: 1.5 truncates to 1, true becomes 1, and + // the string "7" becomes 7 -- so a request AWS rejects with a serialization error + // would instead succeed here against a value the caller never asked for, and a + // retention floor could be set from a number that was never sent. Matches the + // existing shape in KinesisJsonHandler#optionalMaxRecordSize and + // TimestreamInfluxDbValidation, which reject on !isIntegralNumber() for the same + // reason. Found by Greptile on the fork PR. + private static Long longOrNull(JsonNode node, String field) { + JsonNode n = node.path(field); + if (n.isMissingNode() || n.isNull()) { + return null; + } + // canConvertToLong as well as isIntegralNumber, because the first alone leaves + // one coercion open: 18446744073709551623 IS an integral number, and + // longValue() keeps its low 64 bits, wrapping it to 7, which then passes the + // retention checks as if the caller had sent it. Kinesis guards the same way + // with canConvertToInt (KinesisJsonHandler#optionalMaxRecordSize). Rejecting + // a value we cannot represent is the whole point of not coercing. + if (!n.isIntegralNumber() || !n.canConvertToLong()) { + throw new AwsException("InvalidParameterValueException", + field + " must be an integer", 400); + } + return n.longValue(); + } + private static String textOrNull(JsonNode node, String field) { JsonNode n = node.path(field); return n.isMissingNode() || n.isNull() ? null : n.asText(); } + /** + * Like {@link #textOrNull} but refuses to invent a string out of something that is not one. + * + *

{@code asText()} coerces: a request carrying {@code "SNSTopicArn": 123} yields the + * nonblank string {@code "123"}, which passes every present-and-nonblank check the service + * makes and is stored as the topic. The configuration then reads back as valid while naming a + * topic that cannot exist. This is the same coercion Greptile found in {@link #longOrNull} + * above, in the other direction, and it gets the same answer: reject a value we would have to + * fabricate rather than read. + * + *

Used for the fields where the fabricated value would survive validation. The advisory + * ones -- CreatorRequestId and the like -- stay on textOrNull, because a coerced value there + * is stored and echoed and misleads nobody. + */ + private static String stringOrNull(JsonNode node, String field) { + JsonNode n = node.path(field); + if (n.isMissingNode() || n.isNull()) { + return null; + } + if (!n.isTextual()) { + throw new AwsException("InvalidParameterValueException", + field + " must be a string", 400); + } + return n.asText(); + } + @SuppressWarnings("unchecked") private Map readStringMap(JsonNode node, String field) { JsonNode mapNode = node.path(field); diff --git a/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java b/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java index eb34e29cc4..e80d6654d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java +++ b/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java @@ -1,6 +1,8 @@ package io.github.hectorvent.floci.services.backup; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; @@ -14,8 +16,10 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -35,9 +39,21 @@ public class BackupService { private final StorageBackend selectionStore; private final StorageBackend jobStore; private final StorageBackend recoveryStore; + private final StorageBackend accessPolicyStore; + private final StorageBackend notificationStore; private final RegionResolver regionResolver; private final int jobCompletionDelaySeconds; + private final ObjectMapper objectMapper; + + // One monitor per vault key, so the check-then-write in createBackupVault and the + // multi-store cleanup in deleteBackupVault are atomic for a given name. Same shape as + // SecretsManagerService#lockFor and KinesisService's append locks. + private final ConcurrentHashMap vaultLocks = new ConcurrentHashMap<>(); + + private Object lockFor(String vaultKey) { + return vaultLocks.computeIfAbsent(vaultKey, k -> new Object()); + } private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "backup-job-scheduler"); @@ -46,13 +62,17 @@ public class BackupService { }); @Inject - public BackupService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) { + public BackupService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, + ObjectMapper objectMapper) { 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<>() {}); this.jobStore = storageFactory.create("backup", "backup-jobs.json", new TypeReference<>() {}); this.recoveryStore = storageFactory.create("backup", "backup-recovery-points.json", new TypeReference<>() {}); + this.accessPolicyStore = storageFactory.create("backup", "backup-vault-access-policies.json", new TypeReference<>() {}); + this.notificationStore = storageFactory.create("backup", "backup-vault-notifications.json", new TypeReference<>() {}); this.regionResolver = regionResolver; + this.objectMapper = objectMapper; this.jobCompletionDelaySeconds = config.services().backup().jobCompletionDelaySeconds(); } @@ -67,20 +87,34 @@ public class BackupService { String creatorRequestId, Map tags, String region) { String key = vaultKey(region, vaultName); - if (vaultStore.get(key).isPresent()) { - throw new AwsException("AlreadyExistsException", "Backup vault already exists: " + vaultName, 400); + // Check and write under one monitor. Unsynchronised, two creates of the same name can + // both find the name free and both write, so AlreadyExistsException never fires and the + // two vaults share a sub-resource key -- the second could then read configuration + // applied to the first. AWS's CreateBackupVault is atomic for a name; this is what + // makes it atomic here. Same per-key monitor pattern as SecretsManagerService#lockFor. + // + // No sub-resource sweep in here, deliberately. An earlier revision swept the two stores + // at this point and that traded one race for a worse one: with two creates in flight the + // later sweep could delete a configuration already applied against the earlier vault, + // while both creates reported success. Deleting a configuration a caller had just + // successfully applied is worse than the stale record the sweep was there to prevent. + // Sub-resources are keyed per vault incarnation instead, so there is nothing to sweep. + synchronized (lockFor(key)) { + if (vaultStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", "Backup vault already exists: " + vaultName, 400); + } + BackupVault vault = new BackupVault(); + vault.setBackupVaultName(vaultName); + vault.setBackupVaultArn(regionResolver.buildArn("backup", region, "backup-vault:" + vaultName)); + vault.setEncryptionKeyArn(encryptionKeyArn); + vault.setCreationDate(Instant.now().getEpochSecond()); + vault.setCreatorRequestId(creatorRequestId); + vault.setNumberOfRecoveryPoints(0); + vault.setTags(tags); + vaultStore.put(key, vault); + LOG.infov("Created backup vault {0} in {1}", vaultName, region); + return vault; } - BackupVault vault = new BackupVault(); - vault.setBackupVaultName(vaultName); - vault.setBackupVaultArn(regionResolver.buildArn("backup", region, "backup-vault:" + vaultName)); - vault.setEncryptionKeyArn(encryptionKeyArn); - vault.setCreationDate(Instant.now().getEpochSecond()); - vault.setCreatorRequestId(creatorRequestId); - vault.setNumberOfRecoveryPoints(0); - vault.setTags(tags); - vaultStore.put(key, vault); - LOG.infov("Created backup vault {0} in {1}", vaultName, region); - return vault; } public BackupVault describeBackupVault(String vaultName, String region) { @@ -89,11 +123,38 @@ public class BackupService { } public void deleteBackupVault(String vaultName, String region) { + // Under the same monitor as createBackupVault: the three deletes below must not + // interleave with a create of this name, or the name could be recreated mid-cleanup. + synchronized (lockFor(vaultKey(region, vaultName))) { + deleteBackupVaultLocked(vaultName, region); + } + } + + private void deleteBackupVaultLocked(String vaultName, String region) { BackupVault vault = describeBackupVault(vaultName, region); if (vault.getNumberOfRecoveryPoints() > 0) { throw new AwsException("InvalidRequestException", "Non-empty backup vault cannot be deleted: " + vaultName, 400); } + // No lock check here, deliberately. A lock protects the RECOVERY POINTS, not the + // vault shell: AWS's guide says the vault "can be deleted if it is empty and does + // not contain any recovery points", even under a compliance lock. The non-empty + // check above is already the case AWS refuses, so an added lock check would only + // ever fire where AWS succeeds -- and it would break CloudFormation stack teardown, + // which deletes vaults through BackupVaultCfnProvisioner and tolerates only + // not-found. + // Drop the sub-resources with the vault. They are keyed by vault name, so + // leaving them behind would silently graft an old policy or notification + // configuration onto the next vault created with the same name. + // + // 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, + // 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)); + notificationStore.delete(subResourceKey(region, vault)); vaultStore.delete(vaultKey(region, vaultName)); } @@ -102,6 +163,329 @@ public class BackupService { return vaultStore.scan(k -> k.startsWith(prefix)); } + // ── Vault sub-resources: access policy, notifications, lock ──────────────── + // + // Each of these first resolves the vault through describeBackupVault, so a call + // naming a vault that does not exist reports that, rather than reporting the + // sub-resource as merely unconfigured. The two are different answers to different + // questions and AWS distinguishes them; collapsing them would tell a caller its + // typo'd vault name was fine. + + /** + * Every BackupVaultEvent value the PutBackupVaultNotifications reference lists, + * including the ones AWS marks deprecated -- they are still accepted values, and + * rejecting one would fail an apply AWS allows. + * + *

All 30 of them. An earlier revision carried 17, which is the failure mode this + * whole validation has to avoid: a list that rejects is only as good as it is + * complete, and a stale one turns a valid configuration into a 400. + */ + /** + * The ceiling the PutBackupVaultLockConfiguration reference documents for two of the three + * day values: MaxRetentionDays, "The longest maximum retention period you can specify is + * 36500 days", and ChangeableForDays, "The maximum value you can specify is 36,500 days". + * MinRetentionDays has no documented maximum and is deliberately not bounded by it. + */ + private static final long MAX_RETENTION_DAYS = 36500; + + private static final Set BACKUP_VAULT_EVENTS = Set.of( + "BACKUP_JOB_STARTED", "BACKUP_JOB_COMPLETED", "BACKUP_JOB_SUCCESSFUL", + "BACKUP_JOB_FAILED", "BACKUP_JOB_EXPIRED", + "RESTORE_JOB_STARTED", "RESTORE_JOB_COMPLETED", "RESTORE_JOB_SUCCESSFUL", + "RESTORE_JOB_FAILED", + "COPY_JOB_STARTED", "COPY_JOB_SUCCESSFUL", "COPY_JOB_FAILED", + "RECOVERY_POINT_MODIFIED", + "BACKUP_PLAN_CREATED", "BACKUP_PLAN_MODIFIED", + "S3_BACKUP_OBJECT_FAILED", "S3_RESTORE_OBJECT_FAILED", + "CONTINUOUS_BACKUP_INTERRUPTED", + "RECOVERY_POINT_INDEX_COMPLETED", "RECOVERY_POINT_INDEX_DELETED", + "RECOVERY_POINT_INDEXING_FAILED", + "EKS_RESTORE_OBJECT_FAILED", "EKS_RESTORE_OBJECT_SKIPPED", + "EKS_BACKUP_OBJECT_FAILED", + "ACCESS_POINT_AVAILABLE", "ACCESS_POINT_CREATION_FAILED", + "ACCESS_POINT_DELETED", "ACCESS_POINT_DELETION_FAILED", + "ACCESS_POINT_EXPIRED", "ACCESS_POINT_DISASSOCIATED"); + + /** + * The reference documents {@code Policy} as "Required: No", so a request that omits it is + * not an error and must not be refused here. What AWS stores in that case is not documented + * and we have not measured it; clearing is the choice taken, because it leaves the vault + * carrying exactly the policy the request carried rather than one the caller did not send, + * and it keeps the end state readable through GetBackupVaultAccessPolicy. An empty string is + * a different case: it is present and invalid, so it is still rejected. + */ + public void putBackupVaultAccessPolicy(String vaultName, String region, String policy) { + BackupVault vault = describeBackupVault(vaultName, region); + if (policy == null) { + accessPolicyStore.delete(subResourceKey(region, vault)); + return; + } + if (policy.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "Policy must be a non-empty resource policy document", 400); + } + requireJsonObject(policy); + accessPolicyStore.put(subResourceKey(region, vault), policy); + } + + /** + * A resource policy has to be a JSON object before anything else can be true of it. + * + *

Checking only for blankness accepted {@code not a policy}: PUT reported success and GET + * returned the string back unchanged, so an unparseable policy looked applied. That is the + * emulator being more permissive than AWS, which is the one direction that costs a user real + * time -- the configuration passes locally and the deploy is where they find out. + * + *

Syntax only. Floci does not evaluate whether the document grants or denies anything, and + * PutBackupVaultAccessPolicy does not list MalformedPolicyDocumentException among its errors, + * so a bad document is reported as the invalid parameter value it is. + */ + private void requireJsonObject(String policy) { + try { + if (!objectMapper.readTree(policy).isObject()) { + throw new AwsException("InvalidParameterValueException", + "Policy must be a JSON object", 400); + } + } catch (JsonProcessingException e) { + throw new AwsException("InvalidParameterValueException", + "Policy is not a valid JSON document: " + e.getOriginalMessage(), 400); + } + } + + public String getBackupVaultAccessPolicy(String vaultName, String region) { + BackupVault vault = describeBackupVault(vaultName, region); + return accessPolicyStore.get(subResourceKey(region, vault)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No access policy found for backup vault: " + vaultName, 400)); + } + + /** + * Deleting an access policy that is not set is a no-op, so Terraform destroying a + * configuration twice does not fail the second time. That is Floci's choice and not a + * measured AWS behaviour: the reference lists ResourceNotFoundException among this + * operation's errors and does not say whether an unset policy raises it. + */ + public void deleteBackupVaultAccessPolicy(String vaultName, String region) { + BackupVault vault = describeBackupVault(vaultName, region); + accessPolicyStore.delete(subResourceKey(region, vault)); + } + + public void putBackupVaultNotifications(String vaultName, String region, + String snsTopicArn, List events) { + BackupVault vault = describeBackupVault(vaultName, region); + // Absent and present-but-empty are different faults. PutBackupVaultNotifications lists + // MissingParameterValueException, "Indicates that a required parameter is missing", in + // its Errors section, which names the absent case. The reference does not name the + // present-but-unusable case, so it keeps InvalidParameterValueException. + if (snsTopicArn == null) { + throw new AwsException("MissingParameterValueException", + "SNSTopicArn is required", 400); + } + if (snsTopicArn.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "SNSTopicArn must not be empty", 400); + } + if (events == null) { + throw new AwsException("MissingParameterValueException", + "BackupVaultEvents is required", 400); + } + if (events.isEmpty()) { + throw new AwsException("InvalidParameterValueException", + "BackupVaultEvents must name at least one event", 400); + } + // Reject unknown events rather than storing them. An emulator that accepts a + // misspelt event and reports it back unchanged lets a configuration that real + // AWS refuses pass a local test, which is the failure mode this corpus exists + // to catch. + List unknown = events.stream().filter(e -> !BACKUP_VAULT_EVENTS.contains(e)).toList(); + if (!unknown.isEmpty()) { + throw new AwsException("InvalidParameterValueException", + "Invalid backup vault event(s): " + String.join(", ", unknown), 400); + } + notificationStore.put(subResourceKey(region, vault), + new BackupVaultNotifications(snsTopicArn, events)); + } + + public BackupVaultNotifications getBackupVaultNotifications(String vaultName, String region) { + BackupVault vault = describeBackupVault(vaultName, region); + return notificationStore.get(subResourceKey(region, vault)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No notification configuration found for backup vault: " + vaultName, 400)); + } + + /** Idempotent, for the same reason as {@link #deleteBackupVaultAccessPolicy}. */ + public void deleteBackupVaultNotifications(String vaultName, String region) { + BackupVault vault = describeBackupVault(vaultName, region); + notificationStore.delete(subResourceKey(region, vault)); + } + + /** + * Apply a Vault Lock. + * + *

AWS has two modes and {@code ChangeableForDays} is what selects them, in the + * direction that reads backwards at first glance: + * + *

+ * + *

An earlier revision of this method had the two the wrong way round, which made + * AWS's freely removable governance lock permanent. Both quotations above are from + * the PutBackupVaultLockConfiguration reference; the Vault Lock guide states the + * mapping the same way ("If you wish to create a vault lock in governance mode, do + * not include ChangeableForDays"). + */ + public BackupVault putBackupVaultLockConfiguration(String vaultName, String region, + Long minRetentionDays, + Long maxRetentionDays, + Long changeableForDays) { + BackupVault vault = describeBackupVault(vaultName, region); + if (vault.isLocked() && !lockIsStillChangeable(vault)) { + throw new AwsException("InvalidRequestException", + "Backup vault lock is immutable and cannot be changed: " + vaultName, 400); + } + // "The shortest minimum retention period you can specify is 1 day." The reference states + // no maximum for this field, so it gets none here: inventing a bound risks refusing a + // value real AWS accepts, which is the divergence this work exists to remove, not create. + requireDayRange("MinRetentionDays", minRetentionDays, 1, null); + requireDayRange("MaxRetentionDays", maxRetentionDays, 1, MAX_RETENTION_DAYS); + if (minRetentionDays != null && maxRetentionDays != null && maxRetentionDays < minRetentionDays) { + throw new AwsException("InvalidParameterValueException", + "MaxRetentionDays must be greater than or equal to MinRetentionDays", 400); + } + // "You must set ChangeableForDays to 3 or greater": below it a governance lock would be + // effectively immutable on creation, which is what compliance mode is for. + requireDayRange("ChangeableForDays", changeableForDays, 3, MAX_RETENTION_DAYS); + vault.setLocked(true); + vault.setMinRetentionDays(minRetentionDays); + vault.setMaxRetentionDays(maxRetentionDays); + vault.setLockDate(changeableForDays == null ? null + : Instant.now().plus(changeableForDays, ChronoUnit.DAYS).getEpochSecond()); + vaultStore.put(vaultKey(region, vaultName), vault); + LOG.infov("Locked backup vault {0} in {1} ({2})", vaultName, region, + changeableForDays == null + ? "governance mode, changeable at any time" + : "compliance mode, changeable for " + changeableForDays + " day(s)"); + return vault; + } + + /** + * Bound one Vault Lock day value. A null {@code ceiling} means the reference documents no + * maximum for that field, and the value is only floored. + * + *

Where a ceiling is documented, two things go wrong without it, and the second is the + * worse one. A value like 40,000 is accepted here and refused by AWS, which is the shape this + * whole corpus exists to catch: a Terraform configuration that applies locally and fails for + * real. + * + *

And {@code Long.MAX_VALUE} is a perfectly good long, so it survives the integral check in + * the controller and reaches {@code Instant.plus}, which throws {@code ArithmeticException: + * long overflow}. The only exception mapper in the tree handles {@link AwsException}, so that + * escapes as an HTTP 500 rather than the documented 400. Bounding ChangeableForDays, the one + * value that reaches {@code Instant.plus}, is what stops the overflow being reachable at all, + * rather than catching it after the fact. + */ + private static void requireDayRange(String field, Long value, long floor, Long ceiling) { + if (value == null) { + return; + } + if (value < floor || (ceiling != null && value > ceiling)) { + throw new AwsException("InvalidParameterValueException", + ceiling == null + ? field + " must be " + floor + " or greater" + : field + " must be between " + floor + " and " + ceiling, 400); + } + } + + public void deleteBackupVaultLockConfiguration(String vaultName, String region) { + BackupVault vault = describeBackupVault(vaultName, region); + if (vault.isLocked() && !lockIsStillChangeable(vault)) { + throw new AwsException("InvalidRequestException", + "Backup vault lock is immutable and cannot be deleted: " + vaultName, 400); + } + vault.setLocked(false); + vault.setLockDate(null); + vault.setMinRetentionDays(null); + vault.setMaxRetentionDays(null); + vaultStore.put(vaultKey(region, vaultName), vault); + } + + /** + * Refuse a backup whose retention the vault's lock does not permit. + * + *

This is the other half of what a Vault Lock does, and the half that acts at write time: + * "Backup jobs will fail if the lifecycle policy of the backup plan is outside the vault lock's + * retention period." MinRetentionDays and MaxRetentionDays bound {@code DeleteAfterDays}, so a + * plan retaining for 7 days cannot write into a vault whose lock demands 30. + * + *

Until this existed, {@code getMaxRetentionDays} had no reader anywhere in the tree: the + * ceiling was accepted, stored, and reported by DescribeBackupVault while bounding nothing. A + * Terraform configuration pairing a lock with a shorter plan lifecycle therefore applied + * cleanly here and failed its first backup on real AWS, which is precisely the divergence this + * emulator exists to remove rather than introduce. + * + *

An absent lifecycle is checked against the MAXIMUM, not waved through. The first + * version of this returned early whenever DeleteAfterDays was missing, on the reasoning that + * indefinite retention cannot exceed a maximum. That is backwards, and it left the ceiling + * bypassable by simply omitting the member: retaining forever is the LARGEST retention there + * is, so it exceeds every finite maximum, and the recovery point outlives the limit the lock + * was created to impose. A minimum is the other way round -- indefinite satisfies any floor -- + * so an absent lifecycle is refused only when a maximum is set. + * + *

That last point is Floci's reading rather than a quotation. The reference states the + * rule for a lifecycle that falls outside the window and does not spell out the absent case; + * the reading is forced by what a maximum retention period means, and it errs toward refusing + * a request rather than storing a recovery point the lock forbids. + */ + private static void requireLifecycleWithinLock(BackupVault vault, Lifecycle lifecycle) { + if (!vault.isLocked()) { + return; + } + Long min = vault.getMinRetentionDays(); + Long max = vault.getMaxRetentionDays(); + Long deleteAfterDays = lifecycle == null ? null : lifecycle.getDeleteAfterDays(); + if (deleteAfterDays == null) { + if (max != null) { + throw new AwsException("InvalidParameterValueException", + "Lifecycle DeleteAfterDays is required for a vault locked with a maximum " + + "retention of " + max + " day(s): retaining indefinitely would " + + "exceed it", 400); + } + return; + } + long deleteAfter = deleteAfterDays; + if (min != null && deleteAfter < min) { + throw new AwsException("InvalidParameterValueException", + "Lifecycle DeleteAfterDays of " + deleteAfter + " is below the vault lock's " + + "minimum retention of " + min + " day(s)", 400); + } + if (max != null && deleteAfter > max) { + throw new AwsException("InvalidParameterValueException", + "Lifecycle DeleteAfterDays of " + deleteAfter + " exceeds the vault lock's " + + "maximum retention of " + max + " day(s)", 400); + } + } + + /** + * True while a lock can still be changed or removed. + * + *

A governance lock carries no LockDate and is always changeable. A compliance + * lock is changeable only before its LockDate. Absent means governance, so a null + * LockDate must answer TRUE here -- the inverse of this is the defect that made a + * governance lock permanent. + */ + private static boolean lockIsStillChangeable(BackupVault vault) { + Long lockDate = vault.getLockDate(); + return lockDate == null || Instant.now().getEpochSecond() < lockDate; + } + // ── Plan ─────────────────────────────────────────────────────────────────── public BackupPlan createBackupPlan(String planName, List rules, @@ -197,6 +581,7 @@ public class BackupService { public BackupJob startBackupJob(String vaultName, String resourceArn, String iamRoleArn, Lifecycle lifecycle, String region) { BackupVault vault = describeBackupVault(vaultName, region); + requireLifecycleWithinLock(vault, lifecycle); String jobId = UUID.randomUUID().toString(); long now = Instant.now().getEpochSecond(); @@ -267,8 +652,37 @@ public class BackupService { .toList(); } + /** + * Delete a recovery point, unless a Vault Lock still protects it. + * + *

This is what the lock is FOR. "Vault Lock ... prevents the deletion of recovery points + * before their retention periods expire", and the minimum retention period is the floor: a + * recovery point younger than MinRetentionDays cannot be deleted while the vault is locked. + * Without this check the lock was decorative -- it governed only its own mutation, so + * PutBackupVaultLockConfiguration succeeded, DescribeBackupVault reported Locked, and every + * recovery point the lock was supposed to protect deleted exactly as before. An empty vault + * then deletes too, so the whole protection came apart from the one operation it names. + * + *

Both lock modes enforce retention. Governance mode differs on real AWS in that a + * principal holding {@code backup:DisableGovernanceRetention} can override it; Floci does not + * model that permission, so governance mode enforces here as compliance mode does. That is + * stricter than AWS for an unusually-privileged caller and identical for every other one, + * which is the safer direction: a local test that deletes a protected recovery point and + * passes would be describing AWS behaviour that needs a specific permission to reproduce. + */ public void deleteRecoveryPoint(String vaultName, String recoveryPointArn, String region) { + BackupVault vault = describeBackupVault(vaultName, region); RecoveryPoint rp = describeRecoveryPoint(vaultName, recoveryPointArn, region); + if (vault.isLocked() && vault.getMinRetentionDays() != null) { + long ageDays = ChronoUnit.DAYS.between( + Instant.ofEpochSecond(rp.getCreationDate()), Instant.now()); + if (ageDays < vault.getMinRetentionDays()) { + throw new AwsException("InvalidRequestException", + "Recovery point is protected by a vault lock until its minimum retention of " + + vault.getMinRetentionDays() + " day(s) has elapsed: " + recoveryPointArn, + 400); + } + } recoveryStore.delete(recoveryPointArn); decrementVaultCount(vaultName, region); } @@ -444,6 +858,33 @@ public class BackupService { return region + ":" + vaultName; } + /** + * The key a vault's sub-resources are stored under: the vault key plus the vault's creation + * date, so it identifies THIS vault rather than merely this NAME. + * + *

Keying by name alone is what made delete-and-recreate hazardous in both directions. A + * record surviving a delete grafted an old policy onto the next vault to take the name, and + * cleaning up by name could erase a live configuration belonging to a vault that had already + * replaced the one being deleted. Sweeping stale records on create fixed the first and made + * 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. + * + *

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. + * + *

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. + */ + private static String subResourceKey(String region, BackupVault vault) { + return vaultKey(region, vault.getBackupVaultName()) + ":" + vault.getCreationDate(); + } + private static String vaultKey(BackupVault vault) { String region = AwsArnUtils.parse(vault.getBackupVaultArn()).region(); return region + ":" + vault.getBackupVaultName(); diff --git a/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVault.java b/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVault.java index 36f2b35330..83ac954f09 100644 --- a/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVault.java +++ b/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVault.java @@ -34,6 +34,27 @@ public class BackupVault { @JsonProperty("Tags") private Map tags = new HashMap<>(); + // Vault Lock. These four ARE part of the DescribeBackupVault response in AWS, unlike + // the access policy and the notification configuration, which have their own Get + // operations and are stored separately. + // + // `locked` is a primitive, so it serialises as `false` on an unlocked vault rather + // than being dropped by @JsonInclude(NON_NULL). That matches AWS, which always + // reports Locked, and it matters: a client that has to distinguish "not locked" from + // "this emulator does not model locking" can only do so if the member is present. + // The other three stay boxed, because AWS omits them until a lock exists. + @JsonProperty("Locked") + private boolean locked; + + @JsonProperty("LockDate") + private Long lockDate; + + @JsonProperty("MinRetentionDays") + private Long minRetentionDays; + + @JsonProperty("MaxRetentionDays") + private Long maxRetentionDays; + public BackupVault() {} public String getBackupVaultName() { return backupVaultName; } @@ -56,4 +77,16 @@ public class BackupVault { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags != null ? tags : new HashMap<>(); } + + public boolean isLocked() { return locked; } + public void setLocked(boolean locked) { this.locked = locked; } + + public Long getLockDate() { return lockDate; } + public void setLockDate(Long lockDate) { this.lockDate = lockDate; } + + public Long getMinRetentionDays() { return minRetentionDays; } + public void setMinRetentionDays(Long minRetentionDays) { this.minRetentionDays = minRetentionDays; } + + public Long getMaxRetentionDays() { return maxRetentionDays; } + public void setMaxRetentionDays(Long maxRetentionDays) { this.maxRetentionDays = maxRetentionDays; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVaultNotifications.java b/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVaultNotifications.java new file mode 100644 index 0000000000..077ed315bc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/backup/model/BackupVaultNotifications.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.backup.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +/** + * The notification configuration attached to a backup vault. + * + *

Held in its own store rather than as a field on {@link BackupVault} because + * {@code DescribeBackupVault} serialises the vault POJO directly, and AWS does not + * return the notification configuration there -- it is reachable only through + * {@code GetBackupVaultNotifications}. Keeping it separate is what stops the vault + * description growing members real AWS does not send. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BackupVaultNotifications { + + @JsonProperty("SNSTopicArn") + private String snsTopicArn; + + @JsonProperty("BackupVaultEvents") + private List backupVaultEvents = new ArrayList<>(); + + public BackupVaultNotifications() {} + + public BackupVaultNotifications(String snsTopicArn, List backupVaultEvents) { + this.snsTopicArn = snsTopicArn; + setBackupVaultEvents(backupVaultEvents); + } + + public String getSnsTopicArn() { return snsTopicArn; } + public void setSnsTopicArn(String snsTopicArn) { this.snsTopicArn = snsTopicArn; } + + public List getBackupVaultEvents() { return backupVaultEvents; } + + public void setBackupVaultEvents(List backupVaultEvents) { + this.backupVaultEvents = backupVaultEvents != null ? backupVaultEvents : new ArrayList<>(); + } +} 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 index 08aca2e6c6..a23b81ac2e 100644 --- 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 @@ -24,8 +24,13 @@ import java.util.UUID; * *

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. + * is createOnly too. BackupVaultTags update in place. + * + *

AccessPolicy, Notifications and LockConfiguration are still accepted without effect here, + * but they are no longer without a counterpart: the API now implements all three, so a template + * declaring one reports CREATE_COMPLETE with nothing attached, and a later Get of that + * sub-resource answers as though it was never configured. Wiring them through is tracked + * separately; until then this is a gap in the provisioner, not in the service. */ @ApplicationScoped public class BackupVaultCfnProvisioner implements CfnResourceProvisioner { diff --git a/src/test/java/io/github/hectorvent/floci/services/backup/BackupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/backup/BackupIntegrationTest.java index 2f14c7593c..5698191832 100644 --- a/src/test/java/io/github/hectorvent/floci/services/backup/BackupIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/backup/BackupIntegrationTest.java @@ -6,7 +6,11 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.time.Duration; +import java.util.Map; + import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.*; /** @@ -26,6 +30,30 @@ class BackupIntegrationTest { private static String jobId; private static String recoveryPointArn; + /** + * Blocks until a backup job reports {@code COMPLETED}. + * + *

A job finishes asynchronously, so the recovery point it produces is not readable the + * instant PutBackupJob returns. Polling the state rather than sleeping a fixed span is what + * keeps this honest on a slow runner: a sleep sized for this machine only means the job is + * still RUNNING on a slower one, and the assertion that follows fails for a reason that has + * nothing to do with the behaviour under test. + */ + private static void awaitJobCompleted(String backupJobId) { + await().atMost(Duration.ofSeconds(10)) + .pollInterval(Duration.ofMillis(25)) + .until(() -> { + String state = given() + .header("Authorization", AUTH) + .when() + .get("/backup-jobs/" + backupJobId) + .then() + .statusCode(200) + .extract().path("State"); + return "COMPLETED".equals(state); + }); + } + // ── Vault ────────────────────────────────────────────────────────────────── @Test @@ -300,8 +328,8 @@ class BackupIntegrationTest { @Test @Order(42) - void describeBackupJobCompleted() throws InterruptedException { - Thread.sleep(2000); // job-completion-delay-seconds=1 in test config + void describeBackupJobCompleted() { + awaitJobCompleted(jobId); given() .header("Authorization", AUTH) .when() @@ -552,4 +580,770 @@ class BackupIntegrationTest { .then() .statusCode(404); } + + // ── Vault sub-resources: access policy, notifications, lock ──────────────── + // + // These run on their own vault, at orders above every existing test, so that + // configuring a policy here cannot change what the Order(14)/Order(15) tests above + // observe. Those two assert the unconfigured case, which is still the right answer + // for a vault nobody has configured -- the gap this section covers was that there + // was no way to configure one. + + private static final String SUB_VAULT = "sub-resource-vault"; + private static final String POLICY = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"AllowDescribe\"," + + "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"}," + + "\"Action\":\"backup:DescribeBackupVault\",\"Resource\":\"*\"}]}"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:backup-events"; + + @Test + @Order(100) + void createSubResourceVault() { + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200).body("BackupVaultName", equalTo(SUB_VAULT)); + } + + @Test + @Order(101) + void anUnlockedVaultReportsLockedFalse() { + // Locked is always present on a vault in AWS. A client cannot tell "not locked" + // from "this emulator does not model locking" unless the member is there. + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200) + .body("Locked", equalTo(false)) + .body("$", not(hasKey("LockDate"))); + } + + @Test + @Order(110) + void putAccessPolicyThenReadItBack() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"Policy\":\"" + POLICY.replace("\"", "\\\"") + "\"}") + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(200) + .body("BackupVaultName", equalTo(SUB_VAULT)) + .body("BackupVaultArn", containsString("backup-vault:" + SUB_VAULT)) + .body("Policy", containsString("AllowDescribe")); + } + + @Test + @Order(111) + void putAccessPolicyWithoutADocumentClearsTheStoredOne() { + // Policy is documented "Required: No", so refusing a request that omits it fails a call + // real AWS accepts. Order(110) put a policy on this vault, so the read-back below is + // what proves the omission cleared it rather than simply finding nothing there. + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(112) + void accessPolicyOnAVaultThatDoesNotExistSaysSo() { + // The distinction that matters: "no such vault" is a different answer from + // "that vault has no policy", and a caller with a typo needs the first. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"Policy\":\"{}\"}") + .when().put("/backup-vaults/no-such-vault/access-policy") + .then().statusCode(404).body("message", containsString("no-such-vault")); + } + + @Test + @Order(113) + void deleteAccessPolicyLeavesItUnconfigured() { + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(114) + void deleteAccessPolicyIsIdempotent() { + // Terraform destroys a configuration it has already destroyed on a re-run. + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(204); + } + + @Test + @Order(115) + void putAccessPolicyStillRejectsAnEmptyDocument() { + // Present and empty is not the same as absent: an empty string is not a policy document, + // so it stays an InvalidParameterValueException. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"Policy\":\"\"}") + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(400).body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(120) + void putNotificationsThenReadThemBack() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\"," + + "\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\",\"RESTORE_JOB_FAILED\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(200) + .body("BackupVaultName", equalTo(SUB_VAULT)) + .body("SNSTopicArn", equalTo(TOPIC)) + .body("BackupVaultEvents", hasItems("BACKUP_JOB_COMPLETED", "RESTORE_JOB_FAILED")); + } + + @Test + @Order(121) + void notificationsRejectAnEventAwsDoesNotDefine() { + // Accepting a misspelt event and echoing it back would let a configuration real + // AWS refuses pass against the emulator. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\"," + + "\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\",\"NOT_AN_EVENT\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("NOT_AN_EVENT")); + } + + @Test + @Order(122) + void notificationsRequireATopicAndAtLeastOneEvent() { + // A missing required parameter is MissingParameterValueException, which the operation + // lists in its Errors section; present-but-empty is InvalidParameterValueException. An + // SDK maps __type to a typed exception, so collapsing the two hands the caller an error + // other than the one the reference names for a missing parameter. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("MissingParameterValueException")) + .body("message", containsString("SNSTopicArn")); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\"}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("MissingParameterValueException")) + .body("message", containsString("BackupVaultEvents")); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"\",\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("SNSTopicArn")); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\",\"BackupVaultEvents\":[]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("BackupVaultEvents")); + } + + @Test + @Order(123) + void deleteNotificationsLeavesThemUnconfigured() { + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + + // ── Vault Lock ───────────────────────────────────────────────────────────── + // + // ChangeableForDays selects the mode, in the direction that reads backwards: + // PRESENT means compliance (immutable on and after LockDate), ABSENT means + // governance (no LockDate, removable at any time). An earlier revision of this + // branch had them the wrong way round and these tests asserted the inversion, so + // the suite could not catch it. Both directions are now pinned separately. + + @Test + @Order(130) + void aComplianceLockCarriesALockDateAndIsVisibleOnTheVault() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":7,\"MaxRetentionDays\":30,\"ChangeableForDays\":3}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200) + .body("Locked", equalTo(true)) + .body("MinRetentionDays", equalTo(7)) + .body("MaxRetentionDays", equalTo(30)) + .body("LockDate", notNullValue()); + } + + @Test + @Order(131) + void aComplianceLockCanBeRemovedBeforeItsLockDate() { + // "Before the lock date, you can delete Vault Lock from the vault using + // DeleteBackupVaultLockConfiguration." The vault above was locked seconds ago + // with a three-day cooling-off period, so it is inside that window. + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200) + .body("Locked", equalTo(false)) + .body("$", not(hasKey("LockDate"))) + .body("$", not(hasKey("MinRetentionDays"))); + } + + @Test + @Order(132) + void aGovernanceLockHasNoLockDateAndIsAlwaysRemovable() { + // No ChangeableForDays: "If this parameter is not specified, you can delete + // Vault Lock from the vault ... at any time." + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":7,\"MaxRetentionDays\":30}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200) + .body("Locked", equalTo(true)) + .body("$", not(hasKey("LockDate"))); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200).body("Locked", equalTo(false)); + } + + @Test + @Order(133) + void aGovernanceLockCanBeReconfiguredInPlace() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":7}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":14,\"MaxRetentionDays\":100}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200) + .body("MinRetentionDays", equalTo(14)) + .body("MaxRetentionDays", equalTo(100)); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/vault-lock").then().statusCode(204); + } + + @Test + @Order(134) + void lockRejectsAMaximumBelowTheMinimum() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":30,\"MaxRetentionDays\":7,\"ChangeableForDays\":3}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400).body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(135) + void lockRejectsACoolingOffPeriodBelowThreeDays() { + // "AWS Backup enforces a 72-hour cooling-off period ... you must set + // ChangeableForDays to 3 or greater." + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":7,\"ChangeableForDays\":2}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("ChangeableForDays")); + } + + @Test + @Order(136) + void lockRejectsRetentionPeriodsBelowOneDay() { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":0}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400).body("__type", equalTo("InvalidParameterValueException")); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MaxRetentionDays\":0}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400).body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(140) + void lockRejectsANonIntegralRetention() { + // asLong() would have coerced each of these instead of refusing: 1.5 truncates + // to 1, true becomes 1, "7" parses to 7. AWS rejects a non-integral value for a + // long-typed member, so a coercing emulator lets a request AWS refuses succeed + // against a number the caller never sent. + // 18446744073709551623 is 2^64 + 7, the case isIntegralNumber() alone lets through: + // longValue() keeps the low 64 bits, so it wraps to 7, a value the retention checks + // are happy with. Only canConvertToLong() refuses it, and only a value that lands + // INSIDE the valid range tests that guard: an out-of-range truncation is caught by + // the range check instead, leaving the guard free to be deleted unnoticed. + for (String bad : new String[] {"1.5", "true", "\"7\"", "18446744073709551623"}) { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":" + bad + "}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("MinRetentionDays")); + } + } + + @Test + @Order(137) + void anEmptyVaultCanBeDeletedWhileLocked() { + // A lock protects the recovery points, not the vault shell: AWS deletes an empty + // vault even under a lock. An earlier revision refused this, which would also + // have broken CloudFormation stack teardown. + String vault = "locked-but-empty"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":7,\"ChangeableForDays\":3}") + .when().put("/backup-vaults/" + vault + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault).then().statusCode(204); + } + + @Test + @Order(138) + void accessPolicyAcceptsAnObjectBodyAsWellAsAString() { + // Terraform and the console send Policy as a JSON string; an object is accepted + // and re-serialised rather than refused, since refusing would be stricter than + // AWS for no benefit. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"Policy\":{\"Version\":\"2012-10-17\",\"Statement\":[]}}") + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(200).body("Policy", containsString("2012-10-17")); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/access-policy").then().statusCode(204); + } + + @Test + @Order(139) + void notificationsAreDroppedWithTheVaultToo() { + // The policy case is covered at Order(141); this is the other sub-resource + // store, which has its own delete call and could be forgotten independently. + String vault = "recycled-notify"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\"," + + "\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + vault + "/notification-configuration") + .then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault).then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + vault + "/notification-configuration") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(141) + void subResourcesDoNotOutliveTheirVault() { + // A fresh vault, configured, deleted and recreated under the same name must not + // inherit the old policy: the sub-resource stores are keyed by vault name. + String vault = "recycled-vault"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"Policy\":\"{}\"}") + .when().put("/backup-vaults/" + vault + "/access-policy").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault).then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + vault + "/access-policy") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + @Test + @Order(142) + void lockRejectsADayValueAboveTheDocumentedCeiling() { + // The ceiling is documented per field, not once for all three: MaxRetentionDays, "The + // longest maximum retention period you can specify is 36500 days", and ChangeableForDays, + // "The maximum value you can specify is 36,500 days". Without it a Terraform + // configuration with changeable_for_days = 40000 applies here and fails on real AWS, + // which is the exact divergence this corpus exists to find. + for (String field : new String[] {"MaxRetentionDays", "ChangeableForDays"}) { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"" + field + "\":40000}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString(field)); + } + + // MinRetentionDays is the exception: the reference gives it a floor, "The shortest + // minimum retention period you can specify is 1 day", and no maximum at all. Refusing + // 40000 here would be stricter than the reference, which risks the same divergence + // pointing the other way. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":40000}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + SUB_VAULT) + .then().statusCode(200).body("MinRetentionDays", equalTo(40000)); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + SUB_VAULT + "/vault-lock").then().statusCode(204); + } + + @Test + @Order(143) + void lockRejectsLongMaxDaysWithA400RatherThanOverflowingTo500() { + // Long.MAX_VALUE is a perfectly good long, so it survives the integral check and used to + // reach Instant.plus, which throws ArithmeticException: long overflow. The only exception + // mapper handles AwsException, so that escaped as a 500. The ceiling makes the overflow + // unreachable rather than catching it afterwards; this pins the status code, because a + // 500 here would be indistinguishable from the emulator simply falling over. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"ChangeableForDays\":9223372036854775807}") + .when().put("/backup-vaults/" + SUB_VAULT + "/vault-lock") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("ChangeableForDays")); + } + + // ── What the lock enforces, and the validation that stops a bad value looking good ── + // + // Every test below covers a finding Greptile raised on the fork PR that our own review + // had not: four of its six findings were one shape, state written that nothing consumed. + // A round-trip test cannot see that shape -- the write works and the read works -- so + // these assert on the BEHAVIOUR the stored value is supposed to change, which is the only + // place the difference shows. + + private static final String LOCK_VAULT = "lock-enforcement-vault"; + + @Test + @Order(150) + void aLockedVaultRefusesToDeleteARecoveryPointInsideMinRetention() { + // The finding: PutBackupVaultLockConfiguration succeeded, DescribeBackupVault + // reported Locked, and every recovery point the lock was supposed to protect deleted + // exactly as before, because deleteRecoveryPoint read no lock field. The lock was + // decorative. Note the shape of the old test suite: it could lock a vault and read the + // lock back, and both passed, while this was true. + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + LOCK_VAULT).then().statusCode(200); + + String jid = given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s" + } + """.formatted(LOCK_VAULT, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs").then().statusCode(200).extract().path("BackupJobId"); + + awaitJobCompleted(jid); + String rpArn = given().header("Authorization", AUTH) + .when().get("/backup-jobs/" + jid).then().statusCode(200) + .body("State", equalTo("COMPLETED")) + .extract().path("RecoveryPointArn"); + + // Governance mode: no ChangeableForDays. It still enforces retention here, because + // Floci does not model backup:DisableGovernanceRetention and so cannot grant the + // override that would let a privileged caller through on real AWS. + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":30,\"MaxRetentionDays\":365}") + .when().put("/backup-vaults/" + LOCK_VAULT + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + LOCK_VAULT + "/recovery-points/" + rpArn) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", containsString("30")); + + // And the vault is still non-empty, so the refusal really did refuse rather than + // reporting an error after deleting. A 400 with the row gone would be worse than + // no check at all. + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + LOCK_VAULT) + .then().statusCode(200).body("NumberOfRecoveryPoints", equalTo(1)); + } + + @Test + @Order(151) + void aLockWithNoMinimumRetentionDoesNotBlockDeletion() { + // The other direction, and the one that makes the test above worth trusting. A guard + // measured only where it fires is indistinguishable from one that refuses everything, + // and a lock that blocked every deletion would fail a Terraform destroy outright. + // MinRetentionDays is optional, so a lock carrying none protects nothing by retention. + String vault = "lock-no-minimum"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + String jid = given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s" + } + """.formatted(vault, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs").then().statusCode(200).extract().path("BackupJobId"); + + awaitJobCompleted(jid); + String rpArn = given().header("Authorization", AUTH) + .when().get("/backup-jobs/" + jid).then().extract().path("RecoveryPointArn"); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MaxRetentionDays\":365}") + .when().put("/backup-vaults/" + vault + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault + "/recovery-points/" + rpArn) + .then().statusCode(204); + } + + @Test + @Order(152) + void aBackupJobIsRefusedWhenItsLifecycleFallsOutsideTheLock() { + // "Backup jobs will fail if the lifecycle policy of the backup plan is outside the + // vault lock's retention period." Until this existed, getMaxRetentionDays had ZERO + // readers anywhere in the tree: the ceiling was accepted, stored, and reported by + // DescribeBackupVault while bounding nothing. A Terraform configuration pairing a lock + // with a shorter plan lifecycle applied cleanly here and failed its first real backup. + // LOCK_VAULT is locked at [30, 365] by the test above. + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s", + "Lifecycle": {"DeleteAfterDays": 7} + } + """.formatted(LOCK_VAULT, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("minimum retention")); + + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s", + "Lifecycle": {"DeleteAfterDays": 4000} + } + """.formatted(LOCK_VAULT, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("maximum retention")); + + // Omitting the lifecycle entirely is refused too, and this one is worth spelling out + // because the first version of the fix got it backwards and waved it through, on the + // reasoning that indefinite retention cannot exceed a maximum. Retaining forever is the + // LARGEST retention there is, so it exceeds every finite maximum: omitting the member + // was a one-line bypass of the ceiling the lock exists to impose. + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s" + } + """.formatted(LOCK_VAULT, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("DeleteAfterDays is required")); + + // Inside the window: accepted. The guard has to let a valid job through, or a locked + // vault could never be backed up at all. + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s", + "Lifecycle": {"DeleteAfterDays": 90} + } + """.formatted(LOCK_VAULT, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs").then().statusCode(200); + } + + @Test + @Order(156) + void aLockWithOnlyAMinimumStillAcceptsAJobWithNoLifecycle() { + // The other side of the rule above, and the reason it is scoped to a MAXIMUM. A floor is + // satisfied by indefinite retention, so refusing an absent lifecycle here would refuse a + // request AWS accepts -- the divergence this emulator exists to remove. lock-no-minimum + // carries MaxRetentionDays only, so this needs its own vault with the inverse. + String vault = "lock-only-minimum"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"MinRetentionDays\":30}") + .when().put("/backup-vaults/" + vault + "/vault-lock").then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { + "BackupVaultName": "%s", + "ResourceArn": "%s", + "IamRoleArn": "%s" + } + """.formatted(vault, RESOURCE_ARN, IAM_ROLE)) + .when().put("/backup-jobs").then().statusCode(200); + } + + @Test + @Order(157) + void subResourcesAreKeyedPerVaultIncarnationRatherThanPerName() { + // Why the keying matters rather than what it does: the stores used to be keyed by vault + // name, which made one key shared between every vault that ever held the name. A record + // surviving a delete grafted an old policy onto the next vault, and cleanup for a deleted + // vault could erase a live configuration belonging to the vault that had replaced it. + // + // Honest about what this test can and cannot show: it pins the sequential behaviour, and + // the sequential behaviour was already correct once deleteBackupVault removed the + // sub-resources. The races the keying removes need two requests interleaved and are not + // reachable from a single-threaded HTTP test. What is reachable, and is asserted here, is + // that a vault carries only the configuration applied to IT. + String vault = "incarnation-keyed-vault"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\",\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + vault + "/notification-configuration").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + vault + "/notification-configuration") + .then().statusCode(200).body("SNSTopicArn", equalTo(TOPIC)); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault).then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + vault + "/notification-configuration") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(153) + void anUnparseablePolicyIsRefusedRatherThanStored() { + // The finding: the blank check accepted any other string, so `not a policy` was stored, + // PUT reported success and GET returned it unchanged. An invalid policy looked applied. + // That is the emulator being MORE permissive than AWS, the one direction that costs a + // user real time: the configuration passes locally and the deploy is where they learn. + for (String bad : new String[] {"not a policy", "{\"Version\":", "[]", "42", "\"a string\""}) { + given().header("Authorization", AUTH).contentType("application/json") + .body(Map.of("Policy", bad)) + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + // A real document still works, so the check refuses only what it should. + given().header("Authorization", AUTH).contentType("application/json") + .body(Map.of("Policy", POLICY)) + .when().put("/backup-vaults/" + SUB_VAULT + "/access-policy").then().statusCode(204); + } + + @Test + @Order(154) + void aNonStringTopicArnIsRefusedRatherThanCoerced() { + // asText() turns the JSON number 123 into the nonblank string "123", which passed every + // present-and-nonblank check and was stored as the topic: an unusable configuration + // that reads back as valid. Same coercion Greptile found in longOrNull, other direction. + for (String bad : new String[] {"123", "true", "{}", "[]"}) { + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":" + bad + ",\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", containsString("SNSTopicArn")); + } + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\",\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + SUB_VAULT + "/notification-configuration") + .then().statusCode(204); + } + + @Test + @Order(155) + void aRecreatedVaultDoesNotInheritTheDeletedVaultsConfiguration() { + // The stores are keyed by vault name and there is no transaction across the three, so + // a leftover record grafts an old policy onto a new vault of the same name. + // + // Measured, and stated because the measurement is unflattering: this test still PASSES + // with the create-side sweep removed, because the sequential path is already covered by + // the deletes in deleteBackupVault. What it pins is the sequential guarantee, not the + // fix. The concurrent interleaving the fix exists for -- a Put landing between the + // sub-resource deletes and the vault delete -- is not reachable from a single-threaded + // HTTP test, so no test here pins the sweep. Keeping it is a judgement that the race is + // real rather than a claim that it is covered. + String vault = "recycled-vault-name"; + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH).contentType("application/json") + .body("{\"SNSTopicArn\":\"" + TOPIC + "\",\"BackupVaultEvents\":[\"BACKUP_JOB_COMPLETED\"]}") + .when().put("/backup-vaults/" + vault + "/notification-configuration").then().statusCode(204); + + given().header("Authorization", AUTH) + .when().delete("/backup-vaults/" + vault).then().statusCode(204); + + given().header("Authorization", AUTH).contentType("application/json").body("{}") + .when().put("/backup-vaults/" + vault).then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get("/backup-vaults/" + vault + "/notification-configuration") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + } + }