feat(backup): configure a vault with an access policy, notifications and a lock (#4412)

* feat(backup): configure a vault — access policy, notifications and vault lock

CreateBackupVault worked, and then every write that configures the vault it
just created was unrouted. PutBackupVaultAccessPolicy, PutBackupVaultNotifications
and PutBackupVaultLockConfiguration all matched no route, so a vault could be
created but never given a policy, a lock or a notification target — which is most
of what a vault is configured for.

The two GET paths already existed as deliberate stubs that always threw
ResourceNotFoundException, on the reasoning that these are "never-configured" in
the emulator. That error contract was right and is kept for the genuinely
unconfigured case; what was missing was any way to configure one.

Adds the three PUTs, the three DELETEs, and real read paths for the two GETs:

  PUT|GET|DELETE  /backup-vaults/{name}/access-policy
  PUT|GET|DELETE  /backup-vaults/{name}/notification-configuration
  PUT|DELETE      /backup-vaults/{name}/vault-lock

Details worth knowing:

- Vault Lock has two modes and the difference is the point of the feature. With
  ChangeableForDays the lock is governance mode: LockDate is set that far ahead
  and the lock stays removable until then. Without it the lock is compliance
  mode, immutable immediately. Modelling only the first would make a compliance
  lock look reversible, which is exactly the property a caller sets one to get.
  A locked vault also refuses DeleteBackupVault.

- The lock fields live on BackupVault because AWS returns them from
  DescribeBackupVault. The access policy and notification configuration do not:
  AWS exposes each only through its own Get, so they are held in their own
  stores rather than as vault fields, which keeps DescribeBackupVault from
  growing members real AWS does not send. Locked is a primitive so it is always
  present, matching AWS and letting a client tell "not locked" from "not
  modelled".

- BackupVaultEvents outside the documented set are rejected rather than stored.
  An emulator that accepts a misspelt event and echoes it back lets a config
  real AWS refuses pass a local test.

- Deleting an unset policy or notification configuration is a no-op, so a
  Terraform destroy re-run does not fail, and both sub-resources are dropped
  with their vault so a recreated vault of the same name does not inherit them.

Reported as #4103, found by running the Gruntwork Terraform corpus against
Floci: four roots in terraform-aws-data-storage fail on this and nothing else.

Tests: 16 new integration cases covering both lock modes, the round-trips, the
rejected event, the idempotent deletes and the recreate-under-the-same-name case.
61 Backup-related tests pass.

* fix(backup): correct the vault lock modes, the delete rule and the event list

Three corrections from review, all of them cases where the first version of this
branch was confidently wrong about AWS.

1. THE TWO LOCK MODES WERE INVERTED. ChangeableForDays PRESENT means compliance
   mode — a lock date that far ahead, immutable on and after it. ABSENT means
   governance mode — no lock date, removable at any time. The reference says so
   directly: "If this parameter is not specified, you can delete Vault Lock from
   the vault using DeleteBackupVaultLockConfiguration or change the Vault Lock
   configuration using PutBackupVaultLockConfiguration at any time." The previous
   revision had it the other way round, which turned AWS's freely removable
   governance lock into a permanent one and its vault into an undeletable one.

2. A LOCK NO LONGER BLOCKS DELETING THE VAULT. A lock protects the recovery
   points, not the vault shell: AWS deletes an empty vault even under a compliance
   lock, and the pre-existing non-empty check is already the case AWS refuses. The
   added check could therefore only ever fire where AWS succeeds — and it reached
   outside this service, since BackupVaultCfnProvisioner deletes vaults during
   stack teardown and tolerates only not-found.

3. THE EVENT LIST WAS 17 OF 30. Missing CONTINUOUS_BACKUP_INTERRUPTED, the three
   RECOVERY_POINT_INDEX* values, the three EKS_* values and the six ACCESS_POINT_*
   values. Since unknown values are rejected with 400, each missing one failed an
   apply that AWS accepts. Rejecting is still right; the data was stale.

The tests asserted the inverted lock behaviour, so the suite could not have caught
any of this. Both modes are now pinned separately and in opposite directions, and
the gaps review named are covered: the cooling-off floor, the retention floors,
reconfiguring a governance lock in place, deleting an empty locked vault, the
object-bodied Policy branch, and the notification store being dropped with its
vault.

66 Backup-related tests pass, including the CloudFormation provisioner suites.

* style: use -- rather than an em dash in added prose

AGENTS.md forbids em dashes in all content and the conformance check flags
them. Five in lines this branch added, across the service, the notifications
model and the docs page. Upstream lines that already carry one are left alone.

* fix(backup): reject a non-integral vault lock retention instead of coercing it

longOrNull used JsonNode.asLong(), which silently accepts anything: 1.5
truncates to 1, true becomes 1, and the string "7" parses to 7. AWS rejects a
non-integral value for a long-typed member, so the emulator was letting a
request AWS refuses succeed against a number the caller never sent, and a
retention floor could be set from it.

Rejects with InvalidParameterValueException instead, matching the existing
shape in KinesisJsonHandler#optionalMaxRecordSize and
TimestreamInfluxDbValidation, which both refuse on !isIntegralNumber().

Found by Greptile on fork PR #16. Covered by a test that drives all three
coercions and requires each to 400.

* style(backup): import ChronoUnit instead of naming it inline

AGENTS.md requires used classes to be imported unless there is a genuine name
collision, and putBackupVaultLockConfiguration spelled
java.time.temporal.ChronoUnit.DAYS in full. There is no ChronoUnit collision in
this file.

Found by Greptile on fork PR #16, in its first review that saw the real 6-file
diff rather than the 132 files a stale base had been handing it.

* fix(backup): reject a retention value too large to represent, and free the order clash

Two follow-ups from review of the previous commit, both of which it got wrong.

THE COERCION CLASS WAS NOT CLOSED. isIntegralNumber() alone still let one
through: 99999999999999999999 IS an integral number, and longValue() truncates
it to 7766279631452241919, which then passed the retention checks as though the
caller had sent it. That is the same silent-acceptance the commit claimed to
fix, one rung up. Now guarded with canConvertToLong() as well, matching
KinesisJsonHandler#optionalMaxRecordSize, which pairs isIntegralNumber() with
canConvertToInt() for exactly this reason.

Proved by weakening the guard and running the ordered class: exactly one
failure, lockRejectsANonIntegralRetention, "Expected status code <400> but was
<204>" -- the vault lock silently set from the truncated number. Running that
test alone is not a valid control here: it 404s on a vault the earlier ordered
tests create, so it fails for the wrong reason and proves nothing.

THE NEW TEST REUSED @Order(136), already held by the retention-floor test.
Harmless in effect, since both only make requests that 400, but their relative
order was unspecified. Moved to the first genuinely free number rather than the
next one along, which was also taken.

* fix(backup): bound every Vault Lock day value at AWS's documented 36,500

AWS: "It must be a number no less than 3 and no greater than 36,500; otherwise,
an error will return." Only the floors were checked, which left two holes from
one root cause.

MinRetentionDays=40000 was accepted here and refused by AWS. That is the shape
this corpus exists to find: a Terraform configuration with changeable_for_days
= 40000 applies locally and fails for real.

Worse, Long.MAX_VALUE is a perfectly good long, so it survived the integral
check added in 5e1bed0ef -- that commit fixed representability, not the
documented range -- and reached Instant.plus(value, DAYS), which throws
ArithmeticException: long overflow. The only ExceptionMapper in the tree handles
AwsException, so it escaped as HTTP 500 rather than the documented 400. Bounding
the value makes the overflow unreachable rather than catching it afterwards.

The three floor checks become one requireDayRange so the range is stated once.

Both tests fail with the ceiling removed, which is the state before this commit:
the 40000 case and the Long.MAX_VALUE case each go from 400 to something else.

* docs(backup): stop the branch contradicting itself, and clear the order clash

Four corrections from review, all to things this branch introduced.

docs/services/backup.md:15 was changed here to "Delete an empty, unlocked
backup vault", which contradicts :132 ("A lock does not stop the vault being
deleted") and the code, where deleteBackupVault deliberately omits a lock check.
The AWS Vault Lock guide is with :132 and the code: the vault itself can be
deleted if it is empty. Line 15 was the wrong one.

BackupVaultCfnProvisioner's javadoc still said AccessPolicy, Notifications and
LockConfiguration "have no counterpart in the emulated vault". They have
counterparts now, which this branch added. The provisioner still ignores all
three, so a template declaring AccessPolicy reports CREATE_COMPLETE with nothing
attached; that is now stated as a gap in the provisioner rather than implied to
be a gap in the service. Wiring them through is separate work.

The lock log line printed "changeable for null day(s)" on a governance lock,
which is the mode where the value is absent by definition. It now names the mode.

The two tests added in the previous commit took @Order(141), which an existing
test already held -- the same clash 5e1bed0ef had to clear once. They move to the
end as 142 and 143, and the file now has no duplicate order. The pre-existing 140
declared between 136 and 137 is left alone: it executes correctly and moving a
method would be churn.

* fix(backup): accept an absent Policy on PutBackupVaultAccessPolicy

The PutBackupVaultAccessPolicy reference documents Policy as "Type: String,
Required: No", and we refused a request without one with HTTP 400. A call real
AWS accepts therefore failed locally, which is the exact divergence class this
branch exists to catch rather than introduce.

What AWS does with an omitted Policy is undetermined: the reference does not say
whether it clears the stored policy or stores an empty one, and we have not
measured it against real AWS. Clearing is the behaviour chosen here, on two
grounds. It leaves the vault carrying exactly the policy the request carried,
rather than silently retaining one the caller did not send, and the end state is
readable back through GetBackupVaultAccessPolicy, so a caller can tell what
happened. Storing an empty string would make that read return a value that is
not a valid policy document.

Present-but-empty stays an InvalidParameterValueException: an empty string is
supplied and unusable, which is a different fault from not supplying one.

The pinning test at Order(111) now asserts the clear, and it reads the policy
back through a separate GET after Order(110) has written one, so it fails if the
omission is refused and also if it is accepted as a no-op. Order(115) keeps the
old empty-document assertion.

* fix(backup): answer a missing notification parameter with MissingParameterValueException

PutBackupVaultNotifications lists MissingParameterValueException, "Indicates
that a required parameter is missing", in its Errors section, and we answered
InvalidParameterValueException for both an absent SNSTopicArn and absent
BackupVaultEvents. An SDK maps __type onto a typed exception, so a caller
catching the error AWS documents for this case never saw it.

Present-but-empty keeps InvalidParameterValueException, which is the deliberate
half of the distinction: "BackupVaultEvents": [] was supplied and is unusable,
which is not the same fault as not supplying it. A blank SNSTopicArn is now
treated the same way, where before it collapsed into the missing case.

The controller has to carry the distinction too: readStringList answers an empty
list for an absent member, so the service could not tell [] from absent. It now
passes null when the member is missing or null.

No new exception class or mapper was needed. AwsException takes the error code
as a string and jsonType() passes through any code not in its Query-to-JSON
remapping table, so MissingParameterValueException surfaces as HTTP 400 with
__type MissingParameterValueException. The test asserts that on the wire rather
than trusting it.

* fix(backup): quote the real Vault Lock day limits, and drop the invented MinRetentionDays ceiling

Two lines of this branch, one in BackupService and one in the test, attributed a
quotation to AWS that the PutBackupVaultLockConfiguration reference does not
contain: "no less than 3 and no greater than 36,500", presented as a single
ceiling covering every day value. The reference states three separate things,
per field:

  ChangeableForDays  "you must set ChangeableForDays to 3 or greater" and
                     "The maximum value you can specify is 36,500 days"
  MaxRetentionDays   "The longest maximum retention period you can specify is
                     36500 days"
  MinRetentionDays   "The shortest minimum retention period you can specify is
                     1 day", and no maximum at all

The fabricated sentence is replaced by those three, attributed to the field each
one belongs to. No claim about AWS appears here that is not read from the
reference; the floor of 1 on MaxRetentionDays is left in place but is no longer
presented as an AWS citation, because the reference does not state one.

MinRetentionDays no longer carries the 36,500 ceiling. The choice was to drop it
rather than keep it labelled as our own inference: applying an undocumented
maximum refuses a value real AWS accepts, which is the same divergence class the
Policy fix two commits back removed, pointing the other way. Nothing else
depends on the bound. Only ChangeableForDays reaches Instant.plus, so the
overflow the ceiling was also protecting against stays unreachable, and the
min-versus-max cross-check still applies when both are supplied.

requireDayRange takes a nullable ceiling, null meaning the reference documents
no maximum. Order(142) now asserts the ceiling on the two fields that have one
and asserts that MinRetentionDays 40000 is accepted and reads back, so the
dropped bound is pinned rather than merely absent.

* test(backup): pin the canConvertToLong guard with a value that wraps into range

The !n.canConvertToLong() half of the integral-number guard was load-bearing and
untested: deleting it left all 58 tests green. Order(140) fed it
99999999999999999999, which longValue() truncates to 7766279631452241919, and
that is above the retention ceiling, so the range check rejected the request
whether or not the guard was there. The test could not see the difference.

The value is now 18446744073709551623, which is 2^64 + 7: longValue() keeps the
low 64 bits and it wraps to 7, comfortably inside the valid range. Nothing
downstream rejects it, so the guard is the only thing standing between the
request and a lock configured from a number the caller never sent.

Verified by deleting !n.canConvertToLong() from the guard and re-running:
lockRejectsANonIntegralRetention fails, 204 where it expects 400. Restored, it
passes. Production code is unchanged apart from comments.

Also drops "#16" from the Greptile attribution in BackupController. On a fork PR
it is a live reference; reaching floci-io/floci it would auto-link to an
unrelated upstream issue. The comment's worked example is updated to the value
the test now uses.

* test(backup): cover the blank SNSTopicArn rejection, which no test reached

3c4e6321f split a blank SNSTopicArn out of the missing case and gave it its own
InvalidParameterValueException, and nothing exercised it: deleting the
snsTopicArn.isBlank() branch left all 59 tests green, so a vault would have been
configured to notify an empty topic ARN with no test noticing. It was also the
asymmetry with the blank-Policy case, which Order(115) does cover.

Order(122) now sends "SNSTopicArn": "" alongside a valid event list and expects
400 InvalidParameterValueException naming SNSTopicArn, which is the only request
shape that reaches that branch: absent is answered earlier by the missing case,
and a non-blank ARN passes both.

Verified by deleting the isBlank branch and re-running:
notificationsRequireATopicAndAtLeastOneEvent fails on the new case, 204 where it
expects 400. Restored, 59 pass. Test-only change.

* docs(backup): record the three vault decisions that lived only in javadoc

AGENTS.md asks for intentional deviations to be documented, and three of this
branch's user-visible decisions were reachable only by reading the source or the
commit log.

The omitted-Policy behaviour is the one a user is most likely to be surprised
by, and it is written with the same hedge the javadoc carries: AWS's behaviour
is undocumented and unmeasured, and clearing is the choice we took, not an
observed AWS behaviour. It is not upgraded to a measured claim here.

The other two are the MissingParameterValueException versus
InvalidParameterValueException split on PutBackupVaultNotifications, and the
per-field Vault Lock day limits, including that MinRetentionDays deliberately
carries no maximum because AWS documents none.

Documentation only. backup.md is hand-written, not generated, so docs-sync has
nothing to say about it; docs-check passes once this is committed, because its
last gate is git diff --exit-code over docs/.

* docs(backup): stop claiming AWS behaviour the reference does not state

"Deleting an access policy that is not set is a no-op, matching AWS: the
operation is idempotent" was an AWS attribution nobody had read. The
DeleteBackupVaultAccessPolicy reference lists ResourceNotFoundException among
this operation's errors and does not say what an unset policy does, so AWS may
well not be idempotent here. The no-op is kept, described as Floci's choice, and
the reference's silence is stated rather than papered over.

The same audit over everything these commits added turned up five more claims
that outran the reference. None was a fabricated quotation; each asserted an AWS
behaviour inferred from the reference rather than read in it.

Three inferred acceptance from silence: "no documented maximum" was written as
"inventing one would refuse a value real AWS accepts" in BackupService, "stricter
than AWS" in the test, and "would refuse a value real AWS accepts" in backup.md.
An undocumented limit is not an absent limit, so all three now say the bound is
a risk we decline to take, not a measured AWS acceptance.

Two inferred which error AWS picks. The reference names
MissingParameterValueException for a missing required parameter; it does not say
what AWS returns for a parameter that is present and unusable. "AWS answers them
differently" and "an error real AWS would not have returned" are now scoped to
what the reference actually names, with the present-but-unusable half called
Floci's reading.

Comments and documentation only. Verified mechanically: with comments stripped
and blank lines ignored, the executable content of BackupService.java,
BackupController.java and BackupIntegrationTest.java is identical to
3cb81fd41, 524 lines to 524 lines in the service.

* fix(backup): make the vault lock enforce something, and stop accepting values it cannot use

Six review findings on this branch, four of them one shape: state written that
nothing consumed. The lock is the clearest case. 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. getMinRetentionDays and getMaxRetentionDays had zero readers
anywhere in the tree. The lock was decorative.

Both directions of what a lock does now hold. DeleteRecoveryPoint refuses a
recovery point younger than MinRetentionDays while the vault is locked: Vault Lock
"prevents the deletion of recovery points before their retention periods expire".
StartBackupJob refuses a lifecycle whose DeleteAfterDays falls outside
[MinRetentionDays, MaxRetentionDays]: "backup jobs will fail if the lifecycle
policy of the backup plan is outside the vault lock's retention period". The second
is what gives MaxRetentionDays a reader at all, and it matters for the reason this
emulator exists: a configuration pairing a lock with a shorter plan lifecycle used
to apply cleanly here and fail its first backup on real AWS.

Governance mode enforces as compliance mode does, and the docs say so. Real AWS
lets a principal holding backup:DisableGovernanceRetention override a governance
lock; Floci does not model that permission, so it cannot grant the override.
Stricter for that one caller, identical for every other, and the safe direction: a
local test that deletes a protected recovery point and passes would be describing
behaviour that needs a specific permission to reproduce.

Two validation gaps, both the emulator being more permissive than AWS, which is
the one direction that costs a user real time -- it passes locally and the deploy
is where they find out:

  - A Policy is now required to parse as a JSON object. The blank check accepted
    any other string, so `not a policy` was stored, PUT reported success and GET
    returned it unchanged. Syntax only; nothing here evaluates what a policy
    grants, and PutBackupVaultAccessPolicy does not list
    MalformedPolicyDocumentException among its errors.
  - SNSTopicArn must be a JSON string. asText() turned the number 123 into the
    nonblank string "123", which passed every present-and-nonblank check and was
    stored as the topic. Same coercion already fixed in longOrNull on this branch,
    in the other direction, and it gets the same answer.

Vault teardown now removes the sub-resources BEFORE the vault record, and
CreateBackupVault sweeps both sub-resource keys before taking ownership of a name.
There is no transaction across the three stores, so the order is load-bearing:
with the vault removed first, a concurrent recreate could be configured in the gap
and the deletes still to come would erase the new vault's configuration.

Stated plainly because the measurement is unflattering: the recreate test still
passes with the create-side sweep removed, since deleteBackupVault already covers
the sequential path. The interleaving the sweep exists for is not reachable from a
single-threaded HTTP test, so no test pins it. Keeping it is a judgement that the
race is real, not a claim that it is covered. Every other test here was measured
failing with its fix reverted -- four of the six do, and the fifth is the negative
control that must pass either way.

Two findings are documented rather than fixed, in docs/services/backup.md under
Not Yet Supported, because each is its own change and neither belongs in a
sub-resource PR:

  - Notification delivery. The configuration is stored and reported; no vault
    event is ever published to the topic.
  - Access policy enforcement. The policy is stored and reported; no authorization
    path consults it. S3 bucket policies are the only resource policies any Floci
    service enforces today, so this matches the tree rather than being specific to
    Backup. Said out loud because a stored-and-ignored policy is otherwise
    indistinguishable from an enforced one.

* fix(backup): key vault sub-resources per vault, and stop an absent lifecycle bypassing the lock ceiling

Both findings from the second review round, and both were mine to own.

**An omitted lifecycle bypassed MaxRetentionDays.** The previous commit returned early
whenever DeleteAfterDays was missing, reasoning that indefinite retention cannot exceed a
maximum. That is backwards: retaining forever is the largest retention there is, so it
exceeds every finite ceiling, and dropping one member from the request was a one-line
bypass of the limit the lock exists to impose. An absent lifecycle is now refused when the
lock sets a maximum, and still accepted when it sets only a minimum, because a floor IS
satisfied by indefinite retention. The 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.

**The create-side sweep traded one race for a worse one.** Two creates of the same name can
both pass the existence check, so if a policy were applied against the first vault before
the second reached its sweep, the sweep would delete a live configuration while both creates
reported success. Removing a configuration that a caller had just successfully applied is
worse than the stale-record problem the sweep was there to prevent.

So the shared key is removed rather than policed. Sub-resources are keyed per vault
INCARNATION -- vault key plus creation date -- which means a new vault cannot see an old
vault's records, and cleanup for an old vault cannot touch a newer vault's. No sweep, and no
dependence on the order two stores are written in. The delete path still removes the vault's
own sub-resources, now because they are its own rather than because nothing else has claimed
them yet, and still dependents-first so any observable intermediate state is a vault without
configuration rather than a configuration without a vault.

Two vaults of one name within the same second would still collide on the key, which is why
the delete path does its own cleanup rather than relying on the key alone.

Tests: the absent-lifecycle refusal was measured failing with its guard reverted, and
aLockWithOnlyAMinimumStillAcceptsAJobWithNoLifecycle is its negative control -- refusing
there would refuse a request AWS accepts. subResourcesAreKeyedPerVaultIncarnationRatherThanPerName
pins the sequential behaviour and says in the test itself that it cannot pin the races,
which need two interleaved requests and are not reachable from a single-threaded HTTP test.
67 backup integration tests plus both CloudFormation backup suites pass.

* fix(backup): make CreateBackupVault atomic for a name, and take the parser by injection

Three findings from the third round, all correct.

**The sub-resource key was only as unique as the creation date.** Two creates of the same
name racing within one second could both find the name free, both write, and share a
sub-resource key, so the second vault could read configuration applied to the first.
AlreadyExistsException would never have fired either. The key was not the real problem: the
unsynchronised check-then-write was, and AWS's CreateBackupVault is atomic for a name.

Create and delete now hold a per-name monitor, following SecretsManagerService#lockFor and
KinesisService's append locks. That makes the existence check meaningful, which in turn is
what makes the creation date unique per name and the incarnation key sound. The javadoc says
so rather than leaving the key looking self-sufficient, and the delete path still removes its
own sub-resources for a record surviving any other way.

**The ObjectMapper came in through a field initializer**, against the AGENTS.md constructor
injection rule. Taken through the constructor now, like every other collaborator here. No
caller constructs BackupService by hand, so nothing else changes.

**Two tests spelled class names inline** rather than importing them. java.util.Map is
imported and used, and the policy request builds its body with Map.of instead of constructing
an ObjectMapper inline to serialise one string.

67 backup integration tests and both CloudFormation backup suites pass.

* test(backup): wait for a backup job to complete instead of sleeping

Three tests stood a fixed Thread.sleep(2000) in for a wait-on-condition, against a
job-completion-delay-seconds=1 test config. A 2x margin is not a guarantee: on a loaded
runner the job is simply still RUNNING when the sleep expires, and the failure then lands
on the assertion that follows -- State, RecoveryPointArn, or a delete's status code --
none of which is the behaviour under test. That is the worst shape of flake, because it
accuses the wrong code.

awaitJobCompleted polls GET /backup-jobs/{id} for COMPLETED, following the awaitility
idiom already used in 34 files here, AppSyncExecutionIntegrationTest.awaitSchemaSuccess
most closely: atMost 10s, pollInterval 25ms. It returns as soon as the job finishes rather
than always paying the worst case, so the ceiling can be generous without costing time.

The third site was inside a try/catch rather than a bare call, which is why a scan for the
two obvious ones misses it; all three are the same wait and now share one helper. Removing
them also drops two throws InterruptedException clauses.

Measured on this machine, same 67 tests passing either way:
  before  Tests run: 67, Failures: 0, Errors: 0 -- Time elapsed: 9.569 s
  after   Tests run: 67, Failures: 0, Errors: 0 -- Time elapsed: 5.922 s
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-25 18:43:33 -04:00
1 parent 3d35eabf51
commit 6656c8e5df
7 files changed
+1610 -38

No files matched your search

@@ -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}.
*
* <p>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"));
}
}