mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): CDK Provider-framework custom resources and changeset/SSM param fidelity (#2688)
* feat(cloudformation): changeset diffs, stack params, SSM attributes CDK's deploy loop reads all three: DescribeChangeSet now returns computed Add/Modify/Remove resource changes instead of an empty list (an empty list makes CDK skip ExecuteChangeSet on updates), DescribeStacks echoes the stack's merged parameters, and AWS::SSM::Parameter resources expose Value/Type/Name attributes so Fn::GetAtt resolves the bootstrap version (cherry picked from commit 80ac80063e84ef1be977fe625334e722cc1ed8bb) * feat(cloudformation): resolve SSM-typed stack parameters AWS::SSM::Parameter::Value<String> template parameters resolve through SSM for the stack's account and region; missing parameters fail with the real ValidationError message. Landing Zone Accelerator's security and logging stacks depend on this typed-parameter resolution. The IAM password-policy and S3 replication-config changes from the same source commit ship separately in the iam and s3 branches. (cherry picked from commit 10dbabbf5e31d763a398fc1fff16ab0484958af0) * feat(cloudformation): drive CDK Provider framework custom resources The CDK Provider framework defers its ResponseURL callback to a Step Functions waiter that polls framework.isComplete on a Retry cadence until the resource is ready. The custom-resource provisioner only waited the synchronous single-lambda budget for a ResponseURL PUT, so the waiter-driven PUT never landed. A framework.onEvent ServiceToken is now awaited on a bounded async budget so that PUT is captured; onEvent-only and single-lambda resources are unchanged. The engine-side half of the original commit -- a Task-only Retry implementation for the ASL executor (ErrorEquals/IntervalSeconds/ MaxAttempts/BackoffRate/MaxDelaySeconds) -- is dropped here: upstream #2455 ("feat(sfn): support Retry policies in Task, Parallel, and Map states") landed a broader Retry implementation independently (Task, Parallel, and Map states; JitterStrategy; $$.State.RetryCount; Retry-before-Catch ordering), a strict superset of what this commit needed. The full stepfunctions suite (411 tests) is green against it on this branch, and CustomResourceProviderFrameworkTest (a hermetic test of the provisioner's own detect-and-wait logic, no Step Functions involved) is unaffected by the drop. (cherry picked from commit 5b3502d8c9dddf3766ca3f94fe7f146042dc00fd) * docs(cloudformation): document CDK provisioning Documents the CDK Provider-framework custom-resource support and folds its cross-reference into upstream's existing "Retry policies" section in step-functions.md rather than duplicating it with a separate "State Retry" section (upstream #2455 already documents the Retry engine itself). * feat(cloudformation): budget custom-resource waits by idleness, not total time The async custom-resource wait was a fixed 3-minute total budget. That is a property of the emulator, but the time a CDK provider-framework resource needs is a property of the work: Custom::CreateOrganizationAccounts creates exactly one account per 15s waiter poll, so a 3-account org finishes in ~45s while a 15-account org needs ~195s. Past the budget the Lambda is guillotined mid- success -- the accounts all exist, but the resource reports CREATE_FAILED, the stack rolls back, and CDK's readback then surfaces the misleading "NoStack: CloudFormationStack object does not hold a stack". Measure idleness instead. The provisioner already embeds its callback token in the ResponseURL it puts on every event, and the framework echoes that event into each framework.isComplete poll, so a poll arriving at LambdaService is proof of progress for a specific pending resource. Each poll resets the budget, which makes the wait proportional to the work without CloudFormation needing to know what the work is -- and a genuinely hung resource still fails after 3 idle minutes exactly as before. CustomResourceLiveness lives in core.common so the Lambda service can report progress without depending on CloudFormation; the dependency already runs the other way. (cherry picked from commit 14087c992ebb75d109999153a9e8af7e3c2d79f4) (cherry picked from commit 51349e4e017ed08d90e6e71212414e2f306c826b) * fix(cloudformation): call the caller-scoped getStackOrThrow overload that exists The changeset-diff commit re-derived onto main carried a call to a three-arg getStackOrThrow(name, region, accountId) overload that only existed on the account-scoping commit deliberately skipped as superseded by upstream. Upstream's resolveStack already scopes to the caller's account, so the two-arg form is equivalent and compiles. * fix(cloudformation): honour an arrived custom-resource response past its budget A synchronous custom-resource handler PUTs to the ResponseURL from inside the invoke the provisioner is blocked on, so its response can already be delivered by the time await() is entered. Two independent flaws then threw it away. The idle clock started at register(), before the invoke. A provider-framework onEvent-only handler that took 75s to return -- two nested cold container starts -- had spent its 10s CR_RESPONSE_TIMEOUT six times over before await was reached, so the very first deadline check was already negative. Idleness of the wait cannot include time the handler spent working; the clock now starts when the caller starts waiting. The deadline guard also threw without ever consulting the future, so a response that had completed it was discarded as a timeout. Observed on AccessAnalyzerServiceLinkedRoleCreateServiceLinkedRoleResource: the handler logged its response at 15:52:11.768 and the resource was failed 24ms later. An arrived response outranks the clock. Both are pinned by red-first tests. The existing idle-timeout guarantees are unchanged: nothing arriving still times out, and a resource that stops reporting liveness still dies on schedule from its last touch. (cherry picked from commit 7dc8bbca7d47b2a029b5656a89421a556b8296be) (cherry picked from commit 77b71b31a634ae27d7460a078b52dac250d67dc7) * refactor(cloudformation): extract Provider-framework detection from the provisioner The CDK Provider-framework `framework.onEvent` detection and the longer idle budget it earns lived in CloudFormationResourceProvisioner, adding ~55 lines to a class that is being dismantled rather than grown. Move the concern to ProviderFrameworkDetector: it owns the two waiter marker env vars, the best-effort environment probe, the 3-minute async budget and the test seam that shortens it. CustomResourceResponseStore — which already owns the idle-timeout concept via touch/await — gains an await overload that resolves the budget for a ServiceToken and delegates to the existing one, so the provisioner only passes the token through and appends the store's timeout detail to its error. Behaviour is unchanged. (cherry picked from commit 5f93439f409a32012a01b996c5edd0c29d23b260) * fix(stepfunctions): report custom-resource liveness on waiter polls A CDK provider-framework waiter's framework.isComplete poll is itself a Lambda Task the state machine invokes, so it goes through AslExecutor.invokeResource -> LambdaExecutorService directly, bypassing LambdaService.invoke() and the liveness hook it carries. A long-but- progressing custom resource's idle budget in CustomResourceResponseStore ticked down as if no polls were arriving, even while they kept landing. AslExecutor now reports liveness the same way LambdaService does: extract the callback token from the invoke payload and touch() it before invoking. * perf(core): avoid materializing the full payload string in tokenIn CustomResourceLiveness.tokenIn() ran on every Lambda invoke once liveness reporting is wired in, decoding the whole invoke payload as a UTF-8 String even though the overwhelming majority of invokes carry no callback URL at all. Scan the raw bytes for the ASCII "/cfn-response/" marker instead, and only allocate a String for the small token substring when one is found. * fix(cloudformation): compute accurate changeset resource diffs computeChangeSetChanges never read cs.getParameters(), so an update that only changed parameter values reported an empty diff and CDK skipped execution, leaving the old parameter-derived config deployed. It also diffed a SAM change set's raw template against the stack's expanded deployed template, reporting spurious Modify/Remove on every SAM-generated resource for a no-op update, and hardcoded Replacement=False even when a resource's Type changed. Now the diff expands a SAM change set's template before comparing, marks a resource Modify when it references a changed parameter, and reports Replacement=True when a resource's Type changes. * fix(cloudformation): restore last-successful parameters on update rollback executeTemplate overwrote the stack's live parameter map with an update's attempted values before resolving SSM-typed parameters, which can fail. A failed resolution rolled the stack back, but the update snapshot never captured parameters, so DescribeStacks reported the failed update's attempted values instead of the last successfully deployed ones. StackUpdateSnapshot now captures the stack's parameters alongside its template body, and rollbackFailedUpdate restores them together. * fix(cloudformation): log tolerated wait-slice timeouts in custom-resource poll loop Each slice of the custom-resource poll loop below the outer idle budget hit an intentionally-tolerated TimeoutException that was swallowed with only a comment, against the repo's convention of logging deliberately caught exceptions. * fix(cloudformation): honor Parameters.member.N.UsePreviousValue extractParameters never read UsePreviousValue, so submitting it without a ParameterValue stored an empty string for that key. The new parameter-diff logic in computeChangeSetChanges (9fb02c6a9) then treated that empty string as different from the deployed value, reporting a spurious Modify for every resource referencing an otherwise-unchanged parameter. extractParameters now takes the stack's current parameters and resolves UsePreviousValue against them; CloudFormationService.currentParameters looks those up (empty map if the stack doesn't exist yet, e.g. a CREATE change set). * fix(cloudformation): resolve UsePreviousValue against deployed StackSet parameters UpdateStackSet extracted parameters with the previous-value-unaware extractParameters() overload, so a member with UsePreviousValue=true and no ParameterValue stored an empty string and clobbered the StackSet's deployed value instead of preserving it. * fix(cloudformation): resolve template defaults for omitted parameters in changeset diff computeChangeSetChanges compared only explicitly submitted parameters against the deployed stack, so an update that omits a parameter (falling back to its template Default) was never flagged as a change even when that default differs from the deployed value. ExecuteChangeSet applies the default when it actually runs, so the preview under-reported what would change. Resolve defaults for the change set's parameters the same way execution does before diffing. * fix(cloudformation): resolve SSM parameter drift and no-default omissions in changeset diff computeChangeSetChanges compared raw submitted parameter values against the deployed stack, so it missed two cases ExecuteChangeSet actually handles differently: an omitted parameter with no template Default disappears entirely from the resolved map (previously undetected since the diff only walked the new parameter set), and AWS::SSM::Parameter::Value<String> parameters are resolved against the live SSM store at execution time but compared as raw parameter names in the preview, masking a changed SSM value behind an unchanged parameter name. Stack now tracks resolvedParameters (the SSM-resolved map executeTemplate last applied, restored on rollback like parameters already was) so the diff can compare resolved values on both sides. The diff falls back to unresolved values if SSM resolution fails, since a preview must not fail harder than the operation it previews - ExecuteChangeSet still raises the real ValidationError when it resolves for real. * fix(stepfunctions): pass CustomResourceLiveness to AslExecutor in error-termination test Upstream's issue #2666 regression test predates this branch's addition of CustomResourceLiveness to AslExecutor's constructor. The merge from upstream/main brought the file in as new content with no line overlap, so it auto-merged cleanly but left the constructor call one argument short. * fix(cloudformation): evaluate Conditions in changeset diff, always restore params on rollback computeChangeSetChanges never evaluated template Conditions, so a resource whose Condition depends on a changed parameter but whose own definition text is unchanged was invisible to the diff even though ExecuteChangeSet would Add or Remove it once the condition flips (see deleteRemovedOrConditionFalseResources). The diff now resolves Conditions against the new resolved parameters and compares against whether the resource is actually present in stack.getResources() - the same ground truth execution already uses to decide whether a resource was created - falling back to the existing text-based Modify detection when the condition doesn't change. rollbackFailedUpdate only restored the last-successful parameter maps when resource rollback itself also succeeded, so a stack that lands in UPDATE_ROLLBACK_FAILED (resource rollback failed too) kept serving the failed update's attempted parameter values via DescribeStacks and later change-set previews. Parameters are independent of resource-rollback outcome and are now restored unconditionally; templateBody restoration stays gated on rollback success since a partially-rolled-back resource set doesn't correspond to either template. * fix(stepfunctions): pass EventBridgeHandler/SchedulerService/SchedulerController mocks in AslExecutor test Merging upstream/main (55acdec6e) added these three constructor parameters to AslExecutor without updating this test's call site, breaking test-compile.
This commit is contained in:
1 parent
54dacfc56f
commit
08e532ab1a
37 files changed
+2759
-56
No files matched your search
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Token extraction is the one part of the heartbeat that can fail silently: if it never matches, the
|
||||
* idle budget simply never resets and the original fixed-timeout bug is back, invisibly. So the
|
||||
* payloads here are shaped like the ones actually observed on the wire rather than invented.
|
||||
*/
|
||||
class CustomResourceLivenessTest {
|
||||
|
||||
private static final String TOKEN = "6ef77fe2-38c8-41b0-bec6-68879687fbc8";
|
||||
|
||||
private Optional<String> tokenIn(String payload) {
|
||||
return CustomResourceLiveness.tokenIn(payload.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsTheTokenInAProviderFrameworkPoll() {
|
||||
// Verbatim shape of the isComplete poll captured from a Prepare-stage run.
|
||||
String payload = "{\"RequestType\":\"Create\","
|
||||
+ "\"ServiceToken\":\"arn:aws:lambda:us-east-1:000000000000:function:framework-onEvent\","
|
||||
+ "\"ResponseURL\":\"http://localhost.floci.io:4566/cfn-response/" + TOKEN + "\","
|
||||
+ "\"StackId\":\"arn:aws:cloudformation:us-east-1:000000000000:stack/AWSAccelerator-PrepareStack/abc\","
|
||||
+ "\"RequestId\":\"req-1\",\"LogicalResourceId\":\"CreateAccounts\","
|
||||
+ "\"ResourceType\":\"Custom::CreateOrganizationAccounts\","
|
||||
+ "\"ResourceProperties\":{\"ServiceToken\":\"arn:aws:lambda:...\",\"uuid\":\"72f7b8a8\"}}";
|
||||
|
||||
assertEquals(Optional.of(TOKEN), tokenIn(payload));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsTheTokenWhenTheUrlIsTheLastFieldWithNoTrailingPunctuation() {
|
||||
assertEquals(Optional.of(TOKEN),
|
||||
tokenIn("http://localhost.floci.io:4566/cfn-response/" + TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsTheTokenAcrossJsonWhitespaceAndSingleQuotedRenderings() {
|
||||
assertEquals(Optional.of(TOKEN),
|
||||
tokenIn("{ \"ResponseURL\" : 'http://host:4566/cfn-response/" + TOKEN + "' }"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresOrdinaryInvokesThatCarryNoCallbackUrl() {
|
||||
assertTrue(tokenIn("{\"Records\":[{\"body\":\"hello\"}]}").isEmpty());
|
||||
assertTrue(CustomResourceLiveness.tokenIn(new byte[0]).isEmpty());
|
||||
assertTrue(CustomResourceLiveness.tokenIn(null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresATruncatedUrlWithNoTokenAfterThePath() {
|
||||
// The framework's own logging redacts ResponseURL to "..."; that rendering must not produce
|
||||
// a bogus token that would touch nothing and mask the real signal.
|
||||
assertTrue(tokenIn("{\"ResponseURL\":\"...\"}").isEmpty());
|
||||
assertTrue(tokenIn("http://host:4566/cfn-response/").isEmpty());
|
||||
}
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* End-to-end checks for the CloudFormation responses CDK's deploy loop depends on:
|
||||
* DescribeChangeSet must report a real Add/Modify/Remove diff (an empty Changes list makes CDK
|
||||
* skip ExecuteChangeSet on updates), Fn::GetAtt [Param, Value] on an SSM parameter must resolve
|
||||
* to the stored value (CDK reads its bootstrap version that way), and DescribeStacks must echo
|
||||
* the stack's parameters (CDK's parameter merge treats a missing list as an empty set).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationCdkDeployLoopIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260808/us-east-1/cloudformation/aws4_request";
|
||||
|
||||
@Test
|
||||
void describeChangeSet_createType_reportsAllResourcesAsAdd() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cs-diff-create-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Bucket": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"Properties": {"BucketName": "cs-diff-create-bucket-%s"}
|
||||
},
|
||||
"Queue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-create-queue-%s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix, suffix);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "create-changeset")
|
||||
.formParam("ChangeSetType", "CREATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Id>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "create-changeset")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Changes/>")))
|
||||
.body(containsString("<ResourceChange><Action>Add</Action>"
|
||||
+ "<LogicalResourceId>Bucket</LogicalResourceId>"
|
||||
+ "<ResourceType>AWS::S3::Bucket</ResourceType>"
|
||||
+ "<Scope/><Details/></ResourceChange>"))
|
||||
.body(containsString("<ResourceChange><Action>Add</Action>"
|
||||
+ "<LogicalResourceId>Queue</LogicalResourceId>"
|
||||
+ "<ResourceType>AWS::SQS::Queue</ResourceType>"
|
||||
+ "<Scope/><Details/></ResourceChange>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeChangeSet_updateType_reportsAddModifyRemove() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cs-diff-update-stack-" + suffix;
|
||||
|
||||
String initialTemplate = """
|
||||
{
|
||||
"Resources": {
|
||||
"KeepQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-keep-%s"}
|
||||
},
|
||||
"ModQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-mod-%s", "DelaySeconds": 0}
|
||||
},
|
||||
"OldQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-old-%s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix, suffix, suffix);
|
||||
|
||||
String updatedTemplate = """
|
||||
{
|
||||
"Resources": {
|
||||
"KeepQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-keep-%s"}
|
||||
},
|
||||
"ModQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-mod-%s", "DelaySeconds": 5}
|
||||
},
|
||||
"NewQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-new-%s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix, suffix, suffix);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", initialTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "update-changeset")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", updatedTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Id>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "update-changeset")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ResourceChange><Action>Add</Action>"
|
||||
+ "<LogicalResourceId>NewQueue</LogicalResourceId>"
|
||||
+ "<ResourceType>AWS::SQS::Queue</ResourceType>"
|
||||
+ "<Scope/><Details/></ResourceChange>"))
|
||||
.body(containsString("<Action>Modify</Action>"
|
||||
+ "<LogicalResourceId>ModQueue</LogicalResourceId>"
|
||||
+ "<PhysicalResourceId>"))
|
||||
.body(containsString("<Replacement>False</Replacement>"))
|
||||
.body(containsString("<Action>Remove</Action>"
|
||||
+ "<LogicalResourceId>OldQueue</LogicalResourceId>"
|
||||
+ "<PhysicalResourceId>"))
|
||||
.body(not(containsString("<LogicalResourceId>KeepQueue</LogicalResourceId>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAttOnSsmParameter_resolvesValueInOutputs() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "ssm-getatt-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"CdkBootstrapVersion": {
|
||||
"Type": "AWS::SSM::Parameter",
|
||||
"Properties": {
|
||||
"Name": "/ssm-getatt-test/%s/version",
|
||||
"Type": "String",
|
||||
"Value": "21"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"BootstrapVersion": {"Value": {"Fn::GetAtt": ["CdkBootstrapVersion", "Value"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<OutputKey>BootstrapVersion</OutputKey><OutputValue>21</OutputValue>"))
|
||||
.body(not(containsString("CdkBootstrapVersion.Value")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeStacks_includesMergedStackParameters() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "params-echo-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Env": {"Type": "String"},
|
||||
"Tier": {"Type": "String", "Default": "standard"}
|
||||
},
|
||||
"Resources": {
|
||||
"Queue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "params-echo-queue-%s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Env")
|
||||
.formParam("Parameters.member.1.ParameterValue", "dev")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<ParameterKey>Env</ParameterKey><ParameterValue>dev</ParameterValue>"))
|
||||
.body(containsString("<ParameterKey>Tier</ParameterKey><ParameterValue>standard</ParameterValue>"));
|
||||
}
|
||||
}
|
||||
+711
@@ -0,0 +1,711 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Covers three ways {@code computeChangeSetChanges} previously misreported a change set's diff:
|
||||
* ignoring parameter-only updates, comparing a SAM stack's raw template against its expanded
|
||||
* deployed template, and hardcoding {@code Replacement=False} even when a Type change forces a
|
||||
* replacement.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationChangeSetDiffIntegrationTest {
|
||||
|
||||
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
private final List<String> stacksToDelete = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteStacks() {
|
||||
for (String stackName : stacksToDelete) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
stacksToDelete.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void parameterOnlyUpdate_isReportedAsAChange() {
|
||||
String stackName = "cs-diff-param-only-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Suffix": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-${Suffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Same template, only the parameter value changes.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "param-only-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "two")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "param-only-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Modify</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void usePreviousValueParameter_isNotReportedAsAChange() {
|
||||
String stackName = "cs-diff-use-previous-value-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Suffix": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-upv-${Suffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Same template, and the parameter says UsePreviousValue instead of resubmitting its value.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "use-previous-value-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.UsePreviousValue", "true")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "use-previous-value-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Action>Modify</Action>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedParameterFallingBackToDefault_isReportedAsAChange() {
|
||||
String stackName = "cs-diff-omitted-param-default-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Suffix": {"Type": "String", "Default": "fallback"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-omit-${Suffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "override")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Same template, but the update omits Suffix entirely - real CloudFormation falls back to
|
||||
// the template Default ("fallback"), which differs from the deployed value ("override").
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "omitted-param-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "omitted-param-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Modify</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedParameterWithNoDefault_isReportedAsAChange() {
|
||||
String stackName = "cs-diff-omitted-param-no-default-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Suffix": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-omit-nodefault-${Suffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "override")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Same template, but the update omits Suffix entirely and the template has no Default -
|
||||
// resolveDefaultParameters drops the parameter, and ExecuteChangeSet would apply the
|
||||
// resulting (missing) value. The preview must flag the resource as changed too.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "omitted-param-no-default-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "omitted-param-no-default-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Modify</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingSsmParameterInPreview_doesNotFailTheDescribe() {
|
||||
String stackName = "cs-diff-ssm-missing-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
String deployedSsmParamName = "/cfn/test/cs-diff-ssm-missing-deployed";
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "%s",
|
||||
"Value": "one",
|
||||
"Type": "String",
|
||||
"Overwrite": true
|
||||
}
|
||||
""".formatted(deployedSsmParamName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"QueueSuffix": {"Type": "AWS::SSM::Parameter::Value<String>"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-ssm-missing-${QueueSuffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", deployedSsmParamName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// The update points QueueSuffix at an SSM parameter that was never put. ExecuteChangeSet
|
||||
// would fail resolving it, but DescribeChangeSet is only a preview - it must not 400 just
|
||||
// because the current value can't be resolved.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "ssm-missing-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "/cfn/test/cs-diff-ssm-missing-never-put")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "ssm-missing-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void samStackNoOpUpdate_doesNotReportSpuriousChanges() {
|
||||
String stackName = "cs-diff-sam-noop-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Resources:
|
||||
HelloFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
FunctionName: cs-diff-sam-func
|
||||
Handler: index.handler
|
||||
Runtime: nodejs22.x
|
||||
InlineCode: |
|
||||
exports.handler = async () => ({ statusCode: 200, body: 'ok' });
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Byte-identical re-submission of the same SAM source: the deployed template is the
|
||||
// *expanded* form, so diffing the raw SAM source against it must not report the
|
||||
// SAM-generated IAM role as removed or the function as modified.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "sam-noop-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "sam-noop-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Action>Remove</Action>")))
|
||||
.body(not(containsString("<Action>Modify</Action>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceTypeChange_reportsReplacementTrue() {
|
||||
String stackName = "cs-diff-replacement-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String initialTemplate = """
|
||||
{
|
||||
"Resources": {
|
||||
"R": {
|
||||
"Type": "AWS::SNS::Topic",
|
||||
"Properties": {"TopicName": "cs-diff-repl-topic"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
// Same logical id, different resource Type: AWS always forces a replacement here.
|
||||
String replacedTemplate = """
|
||||
{
|
||||
"Resources": {
|
||||
"R": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {"QueueName": "cs-diff-repl-queue"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", initialTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "replacement-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", replacedTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "replacement-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Replacement>True</Replacement>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ssmParameterValueDrift_isReportedAsAChange() {
|
||||
String stackName = "cs-diff-ssm-drift-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
String ssmParamName = "/cfn/test/cs-diff-ssm-drift-suffix";
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "%s",
|
||||
"Value": "one",
|
||||
"Type": "String",
|
||||
"Overwrite": true
|
||||
}
|
||||
""".formatted(ssmParamName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"QueueSuffix": {"Type": "AWS::SSM::Parameter::Value<String>"}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cs-diff-ssm-${QueueSuffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", ssmParamName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// The SSM parameter's value changes in Parameter Store; the referencing template parameter
|
||||
// (the SSM parameter *name*) is resubmitted unchanged. Real CloudFormation re-resolves the
|
||||
// SSM value at CreateChangeSet time, so ExecuteChangeSet would apply "two" to the queue —
|
||||
// the preview must report that Modify, not compare the unchanged raw parameter name.
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "%s",
|
||||
"Value": "two",
|
||||
"Type": "String",
|
||||
"Overwrite": true
|
||||
}
|
||||
""".formatted(ssmParamName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "ssm-drift-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", ssmParamName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "ssm-drift-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Modify</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parameterChangeFlippingConditionToTrue_isReportedAsAnAdd() {
|
||||
String stackName = "cs-diff-condition-add-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Env": {"Type": "String"}
|
||||
},
|
||||
"Conditions": {
|
||||
"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Condition": "IsProd",
|
||||
"Properties": {"QueueName": "cs-diff-condition-add-queue"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Env")
|
||||
.formParam("Parameters.member.1.ParameterValue", "dev")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Q's definition text is unchanged, but Env flips IsProd from false to true - Q was never
|
||||
// created, and ExecuteChangeSet would create it now.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "condition-add-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Env")
|
||||
.formParam("Parameters.member.1.ParameterValue", "prod")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "condition-add-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Add</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parameterChangeFlippingConditionToFalse_isReportedAsARemove() {
|
||||
String stackName = "cs-diff-condition-remove-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Env": {"Type": "String"}
|
||||
},
|
||||
"Conditions": {
|
||||
"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Condition": "IsProd",
|
||||
"Properties": {"QueueName": "cs-diff-condition-remove-queue"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Env")
|
||||
.formParam("Parameters.member.1.ParameterValue", "prod")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Q's definition text is unchanged, but Env flips IsProd from true to false - Q was created,
|
||||
// and ExecuteChangeSet would delete it now.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "condition-remove-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Env")
|
||||
.formParam("Parameters.member.1.ParameterValue", "dev")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "condition-remove-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
|
||||
.body(containsString("<Action>Remove</Action>"));
|
||||
}
|
||||
}
|
||||
+2
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -45,6 +46,7 @@ class CloudFormationServiceRollbackTest {
|
||||
service = new CloudFormationService(
|
||||
provisioner,
|
||||
mock(S3Service.class),
|
||||
mock(SsmService.class),
|
||||
new ObjectMapper(),
|
||||
config,
|
||||
mock(RegionResolver.class),
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationSsmParameterIntegrationTest {
|
||||
|
||||
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_resolvesSsmTypedParameterValue() {
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "/cfn/test/queue-suffix",
|
||||
"Value": "orders-primary",
|
||||
"Type": "String",
|
||||
"Overwrite": true
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"QueueSuffix": {
|
||||
"Type": "AWS::SSM::Parameter::Value<String>",
|
||||
"Default": "/cfn/test/queue-suffix"
|
||||
}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": { "Fn::Sub": "cfn-ssm-${QueueSuffix}" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ResolvedSuffix": { "Value": { "Ref": "QueueSuffix" } }
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "ssm-param-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", "ssm-param-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<OutputValue>orders-primary</OutputValue>"))
|
||||
.body(not(containsString("<OutputValue>/cfn/test/queue-suffix</OutputValue>")));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetQueueUrl")
|
||||
.formParam("QueueName", "cfn-ssm-orders-primary")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("cfn-ssm-orders-primary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_missingSsmParameterFailsWithValidationError() {
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"MissingParam": {
|
||||
"Type": "AWS::SSM::Parameter::Value<String>",
|
||||
"Default": "/cfn/test/does-not-exist"
|
||||
}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": { "Fn::Sub": "cfn-ssm-missing-${MissingParam}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "ssm-missing-param-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", "ssm-missing-param-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_FAILED</StackStatus>"))
|
||||
.body(containsString(
|
||||
"Unable to fetch parameters [/cfn/test/does-not-exist] from parameter store for this account"));
|
||||
}
|
||||
}
|
||||
+44
@@ -345,6 +345,50 @@ class CloudFormationStackSetsIntegrationTest {
|
||||
.body(containsString("<Action>UPDATE</Action>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackSetWithUsePreviousValuePreservesTheDeployedParameter() {
|
||||
// UpdateStackSet, unlike UpdateStack, resolves its Parameters through the single-arg
|
||||
// extractParameters() overload that has no previous-value map to consult. A member
|
||||
// with UsePreviousValue=true and no ParameterValue must still resolve to the StackSet's
|
||||
// currently deployed value, not an empty string that clobbers it.
|
||||
String setName = "upv-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String q1 = "upv-q1-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String original = "orig-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStackSet")
|
||||
.formParam("StackSetName", setName)
|
||||
.formParam("TemplateBody", queueTemplate(q1))
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", original)
|
||||
.header("Authorization", auth(ADMIN, "cloudformation"))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStackSet")
|
||||
.formParam("StackSetName", setName)
|
||||
.formParam("TemplateBody", queueTemplate(q1))
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.UsePreviousValue", "true")
|
||||
.header("Authorization", auth(ADMIN, "cloudformation"))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body(containsString("<OperationId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackSet")
|
||||
.formParam("StackSetName", setName)
|
||||
.header("Authorization", auth(ADMIN, "cloudformation"))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body(containsString("<ParameterValue>" + original + "</ParameterValue>"))
|
||||
.body(not(containsString("<ParameterValue></ParameterValue>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stackSetErrorPaths() {
|
||||
String setName = "errset-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* When an update references a missing SSM parameter, resolution fails before any resource is
|
||||
* touched — but {@code executeTemplate} used to overwrite the stack's live parameter map with the
|
||||
* attempted (unresolved) values first. After the rollback, {@code DescribeStacks} must still
|
||||
* report the last successfully deployed parameter values, not the failed update's inputs.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationUpdateRollbackParametersTest {
|
||||
|
||||
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSsmParameterUpdate_retainsLastSuccessfulParameterValues() {
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "/cfn/test/rollback-suffix",
|
||||
"Value": "orders-primary",
|
||||
"Type": "String",
|
||||
"Overwrite": true
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"QueueSuffix": {
|
||||
"Type": "AWS::SSM::Parameter::Value<String>"
|
||||
}
|
||||
},
|
||||
"Resources": {
|
||||
"Q": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"Properties": {
|
||||
"QueueName": {"Fn::Sub": "cfn-rollback-${QueueSuffix}"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "ssm-rollback-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "/cfn/test/rollback-suffix")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", "ssm-rollback-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<ParameterValue>/cfn/test/rollback-suffix</ParameterValue>"));
|
||||
|
||||
// Update references an SSM parameter name that was never put — resolution fails and the
|
||||
// update must roll back before any resource change is committed.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", "ssm-rollback-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Parameters.member.1.ParameterKey", "QueueSuffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "/cfn/test/does-not-exist")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", "ssm-rollback-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>UPDATE_ROLLBACK_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<ParameterValue>/cfn/test/rollback-suffix</ParameterValue>"))
|
||||
.body(not(containsString("<ParameterValue>/cfn/test/does-not-exist</ParameterValue>")));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", "ssm-rollback-stack")
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* When resource rollback itself also fails (not just the template update), the stack lands in
|
||||
* UPDATE_ROLLBACK_FAILED rather than UPDATE_ROLLBACK_COMPLETE. Parameter restoration must not be
|
||||
* skipped in that path — the last successfully deployed values are independent of whether the
|
||||
* resource rollback succeeded.
|
||||
*/
|
||||
@Test
|
||||
void failedUpdateWithFailedResourceRollback_stillRetainsLastSuccessfulParameterValues() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "rollback-failed-params-stack-" + suffix;
|
||||
String parameterName = "/cfn/test/rollback-failed-params-" + suffix;
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Suffix": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Parameter": {
|
||||
"Type": "AWS::SSM::Parameter",
|
||||
"Properties": {
|
||||
"Name": "%s",
|
||||
"Type": "String",
|
||||
"Value": {"Fn::Sub": "value-${Suffix}"}
|
||||
}
|
||||
}
|
||||
%s
|
||||
}
|
||||
}
|
||||
""";
|
||||
String initialTemplate = template.formatted(parameterName, "");
|
||||
String failingTemplate = template.formatted(parameterName, """
|
||||
,
|
||||
"BadSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"DependsOn": "Parameter",
|
||||
"Properties": {
|
||||
"Name": "rollback-failed-params-secret-%s",
|
||||
"SecretString": "explicit",
|
||||
"GenerateSecretString": {"PasswordLength": 32}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", initialTemplate)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// The update changes Suffix (which the Parameter resource's Value depends on) and also
|
||||
// introduces BadSecret, which fails to create. Rollback must then also fail: rollback isn't
|
||||
// implemented for AWS::SSM::Parameter, so the stack lands in UPDATE_ROLLBACK_FAILED.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", failingTemplate)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Suffix")
|
||||
.formParam("Parameters.member.1.ParameterValue", "two")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>UPDATE_ROLLBACK_FAILED</StackStatus>"))
|
||||
.body(containsString("<ParameterValue>one</ParameterValue>"))
|
||||
.body(not(containsString("<ParameterValue>two</ParameterValue>")));
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Hermetic coverage for the CDK Provider-framework (two-phase async) custom-resource path. The
|
||||
* backing {@code framework.onEvent} Lambda is mocked so that — like the real framework — it returns
|
||||
* WITHOUT PUTting and the ResponseURL callback lands asynchronously (as the waiter state machine's
|
||||
* {@code framework.isComplete} / {@code framework.onTimeout} would drive it). No Docker / Step
|
||||
* Functions involved: this isolates the provisioner's detect-and-wait logic.
|
||||
*/
|
||||
class CustomResourceProviderFrameworkTest {
|
||||
|
||||
private static final String SERVICE_TOKEN =
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:framework-onEvent";
|
||||
private static final String WAITER_ARN =
|
||||
"arn:aws:states:us-east-1:000000000000:stateMachine:waiter";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private LambdaService lambdaService;
|
||||
private ProviderFrameworkDetector detector;
|
||||
private CustomResourceResponseStore store;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
detector = new ProviderFrameworkDetector(lambdaService);
|
||||
store = new CustomResourceResponseStore(detector);
|
||||
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
|
||||
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
|
||||
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, lambdaService, null, null, null, null, null,
|
||||
null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
null, null,
|
||||
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()),
|
||||
mock(io.github.hectorvent.floci.config.EmulatorConfig.class));
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
|
||||
(Function<String, String>) name -> null);
|
||||
}
|
||||
|
||||
private ObjectNode props() {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("ServiceToken", SERVICE_TOKEN);
|
||||
return props;
|
||||
}
|
||||
|
||||
/** Registers the ServiceToken as a framework.onEvent Lambda: env carries the two async markers. */
|
||||
private void stubFrameworkOnEvent() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("framework-onEvent");
|
||||
fn.setFunctionArn(SERVICE_TOKEN);
|
||||
fn.setEnvironment(Map.of(
|
||||
"USER_ON_EVENT_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:onEvent",
|
||||
"USER_IS_COMPLETE_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:isComplete",
|
||||
"WAITER_STATE_MACHINE_ARN", WAITER_ARN));
|
||||
when(lambdaService.getFunction(eq("us-east-1"), eq(SERVICE_TOKEN))).thenReturn(fn);
|
||||
}
|
||||
|
||||
/** Registers the ServiceToken as an onEvent-ONLY provider: no isComplete/waiter markers. */
|
||||
private void stubOnEventOnly() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("framework-onEvent");
|
||||
fn.setFunctionArn(SERVICE_TOKEN);
|
||||
fn.setEnvironment(Map.of(
|
||||
"USER_ON_EVENT_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:onEvent"));
|
||||
when(lambdaService.getFunction(eq("us-east-1"), eq(SERVICE_TOKEN))).thenReturn(fn);
|
||||
}
|
||||
|
||||
/** onEvent returns without PUTting; a background PUT lands after {@code delayMs}, as the waiter would. */
|
||||
private void stubDeferredPut(String status, String physicalId, Map<String, String> data, long delayMs) {
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(inv -> {
|
||||
String token = tokenOf(inv.getArgument(2));
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(delayMs);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", status);
|
||||
if (physicalId != null) {
|
||||
response.put("PhysicalResourceId", physicalId);
|
||||
}
|
||||
if (data != null) {
|
||||
ObjectNode dataNode = response.putObject("Data");
|
||||
data.forEach(dataNode::put);
|
||||
}
|
||||
if (!"SUCCESS".equals(status)) {
|
||||
response.put("Reason", "onTimeout: resource never became complete");
|
||||
}
|
||||
store.complete(token, response);
|
||||
}, "deferred-put");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
return new InvokeResult(200, null, "null".getBytes(), null, "req-1");
|
||||
});
|
||||
}
|
||||
|
||||
private String tokenOf(byte[] payload) throws Exception {
|
||||
JsonNode event = mapper.readTree(payload);
|
||||
String responseUrl = event.get("ResponseURL").asText();
|
||||
return responseUrl.substring(responseUrl.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void frameworkOnEventAwaitsAsyncPutAndPropagatesData() {
|
||||
stubFrameworkOnEvent();
|
||||
stubDeferredPut("SUCCESS", "account-provisioned", Map.of("AccountId", "111122223333"), 150);
|
||||
|
||||
StackResource r = provisioner.provision("CreateAccounts", "Custom::CreateOrganizationAccounts",
|
||||
props(), engine(), "us-east-1", "000000000000", "my-stack");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus());
|
||||
assertEquals("account-provisioned", r.getPhysicalId());
|
||||
assertEquals("111122223333", r.getAttributes().get("AccountId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onEventOnlyProviderStillSucceedsViaSynchronousPut() {
|
||||
stubOnEventOnly();
|
||||
// Synchronous PUT during the invoke, exactly as an onEvent-only framework.onEvent does.
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(inv -> {
|
||||
String token = tokenOf(inv.getArgument(2));
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", "SUCCESS");
|
||||
response.put("PhysicalResourceId", "moved");
|
||||
store.complete(token, response);
|
||||
return new InvokeResult(200, null, "null".getBytes(), null, "req-1");
|
||||
});
|
||||
|
||||
StackResource r = provisioner.provision("MoveAccounts", "Custom::MoveAccounts",
|
||||
props(), engine(), "us-east-1", "000000000000", "my-stack");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus());
|
||||
assertEquals("moved", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void asyncPutThatNeverArrivesFailsCleanlyWithinBudget() {
|
||||
detector.setAsyncCustomResourceTimeoutForTesting(Duration.ofMillis(300));
|
||||
stubFrameworkOnEvent();
|
||||
// onEvent returns without PUTting and nothing ever calls back.
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, null, "null".getBytes(), null, "req-1"));
|
||||
|
||||
StackResource r = provisioner.provision("CreateAccounts", "Custom::CreateOrganizationAccounts",
|
||||
props(), engine(), "us-east-1", "000000000000", "my-stack");
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertTrue(r.getStatusReason().contains("Timed out"),
|
||||
"expected a bounded timeout failure, got: " + r.getStatusReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waiterOnTimeoutFailurePropagatesAsResourceFailure() {
|
||||
stubFrameworkOnEvent();
|
||||
stubDeferredPut("FAILED", null, null, 150);
|
||||
|
||||
StackResource r = provisioner.provision("CreateAccounts", "Custom::CreateOrganizationAccounts",
|
||||
props(), engine(), "us-east-1", "000000000000", "my-stack");
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertTrue(r.getStatusReason().contains("onTimeout"),
|
||||
"expected the onTimeout FAILED reason to surface, got: " + r.getStatusReason());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -42,7 +42,7 @@ class CustomResourceProvisionerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
store = new CustomResourceResponseStore();
|
||||
store = new CustomResourceResponseStore(new ProviderFrameworkDetector(lambdaService));
|
||||
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
|
||||
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
|
||||
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* The await budget is an IDLE timeout, not a total one.
|
||||
*
|
||||
* <p>A CDK provider-framework waiter drives {@code framework.isComplete} on a fixed cadence and only
|
||||
* PUTs to the ResponseURL once the underlying work finishes. How long that takes is a function of
|
||||
* the work, not of the emulator: {@code Custom::CreateOrganizationAccounts} creates exactly one
|
||||
* account per poll, so a 15-account org needs ~15 polls where a 6-account org needs ~3. A total-time
|
||||
* budget therefore has to be re-tuned every time a config set grows, and when it is exceeded the
|
||||
* Lambda is guillotined mid-success — the accounts exist, but the resource reports CREATE_FAILED and
|
||||
* the stack rolls back.
|
||||
*
|
||||
* <p>Measuring idleness instead makes the budget proportional to the work without the CloudFormation
|
||||
* layer needing to know what the work IS: every poll is liveness, so progress buys unbounded
|
||||
* wall-clock while a genuinely hung resource still dies on schedule.
|
||||
*/
|
||||
class CustomResourceResponseStoreTest {
|
||||
|
||||
private final CustomResourceResponseStore store = new CustomResourceResponseStore(
|
||||
new ProviderFrameworkDetector(mock(LambdaService.class)));
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ObjectNode success() {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
node.put("Status", "SUCCESS");
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Polls {@code count} times at 100ms, then optionally PUTs. Mirrors the waiter's cadence. */
|
||||
private Thread waiterPolling(String token, int count, boolean thenComplete) {
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
for (int i = 0; i < count; i++) {
|
||||
Thread.sleep(100);
|
||||
store.touch(token);
|
||||
}
|
||||
if (thenComplete) {
|
||||
store.complete(token, success());
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitOutlivesItsBudgetWhileTouchesKeepArriving() throws Exception {
|
||||
String token = store.register();
|
||||
// ~900ms of polling against a 300ms budget: three times over, the way 15 accounts run three
|
||||
// times past a budget sized for 6.
|
||||
Thread waiter = waiterPolling(token, 9, true);
|
||||
|
||||
JsonNode response = store.await(token, Duration.ofMillis(300));
|
||||
|
||||
assertEquals("SUCCESS", response.get("Status").asText());
|
||||
waiter.join(2_000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitStillTimesOutOnceTheTouchesStop() throws Exception {
|
||||
String token = store.register();
|
||||
// Three polls, then the resource hangs. The budget must still fire from the LAST poll.
|
||||
Thread waiter = waiterPolling(token, 3, false);
|
||||
|
||||
assertThrows(TimeoutException.class, () -> store.await(token, Duration.ofMillis(300)));
|
||||
waiter.join(2_000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitTimesOutWhenNothingEverHappens() {
|
||||
String token = store.register();
|
||||
|
||||
assertThrows(TimeoutException.class, () -> store.await(token, Duration.ofMillis(150)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitReturnsAResponseThatArrivedBeforeTheBudgetWasChecked() throws Exception {
|
||||
// A synchronous handler PUTs from inside the invoke the provisioner is blocked on, so its
|
||||
// response can already be here by the time await is entered. Whatever the clock says, a
|
||||
// response that arrived is a response — the future outranks the budget.
|
||||
String token = store.register();
|
||||
store.complete(token, success());
|
||||
|
||||
JsonNode response = store.await(token, Duration.ZERO);
|
||||
|
||||
assertEquals("SUCCESS", response.get("Status").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitBudgetsIdlenessFromWhenTheCallerStartsWaitingNotFromRegistration() throws Exception {
|
||||
String token = store.register();
|
||||
// The token is registered before the invoke, and a slow handler — a cold container start, or
|
||||
// two of them nested — can burn longer than the whole budget before await is ever reached.
|
||||
// That is the handler working, not the resource going idle, so it must not be charged here.
|
||||
Thread.sleep(400);
|
||||
|
||||
Thread waiter = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
store.complete(token, success());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
waiter.setDaemon(true);
|
||||
waiter.start();
|
||||
|
||||
JsonNode response = store.await(token, Duration.ofMillis(300));
|
||||
|
||||
assertEquals("SUCCESS", response.get("Status").asText());
|
||||
waiter.join(2_000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void touchForAnUnknownTokenIsIgnored() {
|
||||
// Polls can outlive their await (timeout, rollback). Liveness for a token nobody is waiting
|
||||
// on is not an error — it is the normal tail of a resource that already failed.
|
||||
assertDoesNotThrow(() -> store.touch("no-such-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void toleratedWaitSliceTimeoutIsLogged() throws Exception {
|
||||
// Every slice of the poll loop below the outer budget hits an internal TimeoutException that
|
||||
// is intentionally swallowed and retried. Per the repo's logging convention, a caught
|
||||
// exception that is deliberately tolerated must still be logged (at trace level, since this
|
||||
// is the normal, expected tail of every wait) rather than disappearing silently.
|
||||
java.util.logging.Logger julLogger =
|
||||
java.util.logging.Logger.getLogger(CustomResourceResponseStore.class.getName());
|
||||
julLogger.setLevel(java.util.logging.Level.ALL);
|
||||
java.util.List<java.util.logging.LogRecord> records = new java.util.ArrayList<>();
|
||||
java.util.logging.Handler handler = new java.util.logging.Handler() {
|
||||
@Override
|
||||
public void publish(java.util.logging.LogRecord record) {
|
||||
records.add(record);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
};
|
||||
handler.setLevel(java.util.logging.Level.ALL);
|
||||
julLogger.addHandler(handler);
|
||||
try {
|
||||
String token = store.register();
|
||||
Thread waiter = waiterPolling(token, 9, true);
|
||||
|
||||
store.await(token, Duration.ofMillis(300));
|
||||
waiter.join(2_000);
|
||||
} finally {
|
||||
julLogger.removeHandler(handler);
|
||||
}
|
||||
|
||||
assertTrue(records.stream().anyMatch(r -> r.getMessage() != null
|
||||
&& r.getMessage().toLowerCase().contains("wait slice")),
|
||||
"expected a log record for a tolerated wait-slice timeout, got: " + records);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The two-phase CDK Provider framework is recognised from the {@code framework.onEvent} Lambda's
|
||||
* environment: only that shape PUTs asynchronously, and only it earns the longer idle budget.
|
||||
*/
|
||||
class ProviderFrameworkDetectorTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SERVICE_TOKEN =
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:framework-onEvent";
|
||||
private static final Duration SYNCHRONOUS = Duration.ofSeconds(10);
|
||||
|
||||
private LambdaService lambdaService;
|
||||
private ProviderFrameworkDetector detector;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
detector = new ProviderFrameworkDetector(lambdaService);
|
||||
}
|
||||
|
||||
private void stubEnvironment(Map<String, String> env) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("framework-onEvent");
|
||||
fn.setFunctionArn(SERVICE_TOKEN);
|
||||
fn.setEnvironment(env);
|
||||
when(lambdaService.getFunction(eq(REGION), eq(SERVICE_TOKEN))).thenReturn(fn);
|
||||
}
|
||||
|
||||
private Map<String, String> frameworkEnv() {
|
||||
return Map.of(
|
||||
"USER_ON_EVENT_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:onEvent",
|
||||
"USER_IS_COMPLETE_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:isComplete",
|
||||
"WAITER_STATE_MACHINE_ARN", "arn:aws:states:us-east-1:000000000000:stateMachine:waiter");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothWaiterMarkersPresentMeansProviderFramework() {
|
||||
stubEnvironment(frameworkEnv());
|
||||
|
||||
assertTrue(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onEventOnlyProviderIsNotProviderFramework() {
|
||||
stubEnvironment(Map.of(
|
||||
"USER_ON_EVENT_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:onEvent"));
|
||||
|
||||
assertFalse(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isCompleteWithoutWaiterIsNotProviderFramework() {
|
||||
stubEnvironment(Map.of(
|
||||
"USER_IS_COMPLETE_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:isComplete"));
|
||||
|
||||
assertFalse(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankMarkerIsNotProviderFramework() {
|
||||
stubEnvironment(Map.of(
|
||||
"USER_IS_COMPLETE_FUNCTION_ARN", "arn:aws:lambda:us-east-1:000000000000:function:isComplete",
|
||||
"WAITER_STATE_MACHINE_ARN", " "));
|
||||
|
||||
assertFalse(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionWithNoEnvironmentIsNotProviderFramework() {
|
||||
stubEnvironment(null);
|
||||
|
||||
assertFalse(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
}
|
||||
|
||||
/** Detection is best-effort: an unresolvable ServiceToken must not fail the resource. */
|
||||
@Test
|
||||
void unresolvableFunctionIsTreatedAsSynchronousHandler() {
|
||||
when(lambdaService.getFunction(any(), any()))
|
||||
.thenThrow(new RuntimeException("ResourceNotFoundException"));
|
||||
|
||||
assertFalse(detector.isProviderFrameworkOnEvent(SERVICE_TOKEN, REGION));
|
||||
assertEquals(SYNCHRONOUS, detector.responseTimeout(SERVICE_TOKEN, REGION, SYNCHRONOUS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void providerFrameworkGetsTheAsyncBudgetAndOthersTheSynchronousOne() {
|
||||
stubEnvironment(frameworkEnv());
|
||||
assertEquals(Duration.ofMinutes(3), detector.responseTimeout(SERVICE_TOKEN, REGION, SYNCHRONOUS));
|
||||
|
||||
stubEnvironment(Map.of("USER_ON_EVENT_FUNCTION_ARN", "arn:aws:lambda:us-east-1:0:function:onEvent"));
|
||||
assertEquals(SYNCHRONOUS, detector.responseTimeout(SERVICE_TOKEN, REGION, SYNCHRONOUS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSeamShortensTheAsyncBudget() {
|
||||
stubEnvironment(frameworkEnv());
|
||||
detector.setAsyncCustomResourceTimeoutForTesting(Duration.ofMillis(300));
|
||||
|
||||
assertEquals(Duration.ofMillis(300), detector.responseTimeout(SERVICE_TOKEN, REGION, SYNCHRONOUS));
|
||||
}
|
||||
}
|
||||
+3
@@ -67,6 +67,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);
|
||||
@@ -127,6 +128,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
InvokeResult versionResult = service.invokeArn(
|
||||
@@ -265,6 +267,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ class AslExecutorArrayParamsTest {
|
||||
|
||||
private AslExecutor newExecutor() {
|
||||
return new AslExecutor(null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, mapper, null, null, null, null);
|
||||
null, null, null, null, null, mapper, null, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ class AslExecutorCatchTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.vertx.mutiny.core.Vertx;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A CDK provider-framework waiter's {@code framework.isComplete} poll is itself a Lambda Task in
|
||||
* the state machine Step Functions runs on our behalf, so it lands in {@link
|
||||
* AslExecutor#invokeResource} rather than {@link
|
||||
* io.github.hectorvent.floci.services.lambda.LambdaService#invoke}. Greptile/Copilot both flagged
|
||||
* that this path never told {@link CustomResourceLiveness} about the poll, so a long-but-progressing
|
||||
* custom resource's idle budget kept ticking down as if no polls were arriving at all.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AslExecutorCustomResourceLivenessTest {
|
||||
|
||||
private static final String REGION = "us-east-2";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String FUNCTION_NAME = "framework-onEvent";
|
||||
private static final String FUNCTION_ARN =
|
||||
"arn:aws:lambda:%s:%s:function:%s".formatted(REGION, ACCOUNT, FUNCTION_NAME);
|
||||
private static final String TOKEN = "6ef77fe2-38c8-41b0-bec6-68879687fbc8";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private CustomResourceLiveness customResourceLiveness;
|
||||
private AslExecutor executor;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
LambdaExecutorService lambdaExecutor = mock(LambdaExecutorService.class);
|
||||
LambdaFunctionStore functionStore = mock(LambdaFunctionStore.class);
|
||||
LambdaFunction function = new LambdaFunction();
|
||||
function.setFunctionName(FUNCTION_NAME);
|
||||
function.setFunctionArn(FUNCTION_ARN);
|
||||
customResourceLiveness = mock(CustomResourceLiveness.class);
|
||||
|
||||
when(functionStore.get(REGION, FUNCTION_NAME)).thenReturn(Optional.of(function));
|
||||
when(lambdaExecutor.invoke(eq(function), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, null, "{}".getBytes(), null, "poll-request"));
|
||||
|
||||
executor = new AslExecutor(
|
||||
lambdaExecutor,
|
||||
functionStore,
|
||||
mock(DynamoDbService.class),
|
||||
mock(DynamoDbJsonHandler.class),
|
||||
mock(SqsJsonHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
|
||||
mock(S3Service.class),
|
||||
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
|
||||
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, customResourceLiveness);
|
||||
}
|
||||
|
||||
@Test
|
||||
void waiterPollThroughDirectFunctionArnTouchesTheEmbeddedCallbackToken() throws Exception {
|
||||
run("""
|
||||
{
|
||||
"StartAt": "Poll",
|
||||
"States": {
|
||||
"Poll": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(FUNCTION_ARN),
|
||||
"{\"RequestType\":\"Create\",\"ResponseURL\":\"http://host:4566/cfn-response/" + TOKEN + "\"}");
|
||||
|
||||
verify(customResourceLiveness).touch(TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void waiterPollThroughOptimizedIntegrationTouchesTheEmbeddedCallbackToken() throws Exception {
|
||||
run("""
|
||||
{
|
||||
"StartAt": "Poll",
|
||||
"States": {
|
||||
"Poll": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::lambda:invoke",
|
||||
"Parameters": {"FunctionName": "%s", "Payload.$": "$"},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(FUNCTION_ARN),
|
||||
"{\"RequestType\":\"Create\",\"ResponseURL\":\"http://host:4566/cfn-response/" + TOKEN + "\"}");
|
||||
|
||||
verify(customResourceLiveness).touch(TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryLambdaInvokeWithNoCallbackUrlNeverTouchesLiveness() throws Exception {
|
||||
run("""
|
||||
{
|
||||
"StartAt": "Poll",
|
||||
"States": {
|
||||
"Poll": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(FUNCTION_ARN),
|
||||
"{\"Records\":[{\"body\":\"hello\"}]}");
|
||||
|
||||
verify(customResourceLiveness, never()).touch(org.mockito.ArgumentMatchers.anyString());
|
||||
}
|
||||
|
||||
private void run(String definition, String input) {
|
||||
StateMachine stateMachine = new StateMachine();
|
||||
stateMachine.setName("waiter-liveness");
|
||||
stateMachine.setStateMachineArn(
|
||||
"arn:aws:states:%s:%s:stateMachine:waiter-liveness".formatted(REGION, ACCOUNT));
|
||||
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
|
||||
stateMachine.setDefinition(definition);
|
||||
|
||||
Execution execution = new Execution();
|
||||
execution.setName("waiter-liveness-execution");
|
||||
execution.setExecutionArn("arn:aws:states:%s:%s:execution:waiter-liveness:run-1"
|
||||
.formatted(REGION, ACCOUNT));
|
||||
execution.setStateMachineArn(stateMachine.getStateMachineArn());
|
||||
execution.setInput(input);
|
||||
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
executor.executeSync(stateMachine, execution, history, (updated, events) -> {
|
||||
});
|
||||
assertEquals("SUCCEEDED", execution.getStatus());
|
||||
}
|
||||
}
|
||||
+1
@@ -76,6 +76,7 @@ class AslExecutorEcsRunTaskModeTest {
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class),
|
||||
mock(EmulatorConfig.class),
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -87,7 +87,8 @@ class AslExecutorErrorTerminationTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new CrashingJsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx,
|
||||
mock(io.github.hectorvent.floci.core.common.CustomResourceLiveness.class));
|
||||
}
|
||||
|
||||
private static final String PASS_WITH_JSONATA_OUTPUT = """
|
||||
|
||||
+2
-1
@@ -176,7 +176,8 @@ class AslExecutorHttpInvokeTest {
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class),
|
||||
emulatorConfig,
|
||||
vertx);
|
||||
vertx,
|
||||
null);
|
||||
}
|
||||
|
||||
private void recordRequest(final RoutingContext ctx, String body) {
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ class AslExecutorIntrinsicContextTest {
|
||||
/** Only ObjectMapper is exercised by the path/intrinsic resolution methods under test. */
|
||||
private AslExecutor newExecutor() {
|
||||
return new AslExecutor(null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, mapper, null, null, null, null);
|
||||
null, null, null, null, null, mapper, null, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
@@ -55,6 +55,7 @@ class AslExecutorJsonMergeTest {
|
||||
new JsonataEvaluator(mapper),
|
||||
mock(Instance.class),
|
||||
mock(EmulatorConfig.class),
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ class AslExecutorLambdaInvokeResultTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class AslExecutorMockedResponsesTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
@@ -49,6 +49,7 @@ class AslExecutorPathIntrinsicsTest {
|
||||
new JsonataEvaluator(mapper),
|
||||
mock(Instance.class),
|
||||
mock(EmulatorConfig.class),
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -75,6 +75,7 @@ class AslExecutorResultWriterTest {
|
||||
new JsonataEvaluator(mapper),
|
||||
sfnService,
|
||||
mock(EmulatorConfig.class),
|
||||
null,
|
||||
null);
|
||||
|
||||
sm = new StateMachine();
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ class AslExecutorRetryTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ class AslExecutorTerminalStateTest {
|
||||
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user