diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationConditionsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationConditionsTest.java new file mode 100644 index 0000000000..83d680a2b2 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationConditionsTest.java @@ -0,0 +1,130 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.NoSuchBucketException; +import software.amazon.awssdk.services.sqs.SqsClient; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudFormation conditions with intrinsic operands") +class CloudFormationConditionsTest { + + private static CloudFormationClient cfn; + private static S3Client s3; + private static SqsClient sqs; + private String stackName; + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + s3 = TestFixtures.s3Client(); + sqs = TestFixtures.sqsClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-cond"); + } + + @AfterEach + void cleanup() throws InterruptedException { + // Also when the stack was refused: DeleteStack of a name with no stack does nothing. + cfn.deleteStack(r -> r.stackName(stackName)); + TestFixtures.await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks(); + return stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString()); + } catch (CloudFormationException e) { + return e.getMessage().contains("does not exist"); + } + }, stackName, "deleted", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, + TestFixtures.isRealAws() ? 5_000 : 100); + } + + @AfterAll + static void closeClients() { + cfn.close(); + s3.close(); + sqs.close(); + } + + @Test + @DisplayName("Fn::FindInMap inside Fn::Equals compares the mapped value") + void mappedConditionSelectsTheBucketName() throws InterruptedException { + String region = TestFixtures.region().id(); + String prefix = stackName + "-"; + createStack(""" + { + "Mappings": {"Locations": {"%1$s": {"Code": "false"}}}, + "Conditions": {"UseCode": {"Fn::Not": [{"Fn::Equals": [ + {"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, "false"]}]}}, + "Resources": {"Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": + {"Fn::Join": ["", ["%2$s", {"Fn::If": ["UseCode", + {"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, + {"Ref": "AWS::Region"}]}]]}}}} + } + """.formatted(region, prefix)); + + s3.headBucket(r -> r.bucket(prefix + region)); + assertThatThrownBy(() -> s3.headBucket(r -> r.bucket(prefix + "false"))) + .isInstanceOf(NoSuchBucketException.class); + } + + @Test + @DisplayName("Ref AWS::StackName inside Fn::Equals is the stack's own name") + void stackNameConditionCreatesTheResource() throws InterruptedException { + createStack(""" + { + "Conditions": {"IsThisStack": {"Fn::Equals": [{"Ref": "AWS::StackName"}, "%1$s"]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsThisStack", + "Properties": {"QueueName": "%1$s"}}} + } + """.formatted(stackName)); + + assertThat(sqs.getQueueUrl(r -> r.queueName(stackName)).queueUrl()).endsWith("/" + stackName); + } + + @Test + @DisplayName("Fn::ImportValue inside a condition is a template error") + void importValueInAConditionIsRefused() { + assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody(""" + { + "Conditions": {"IsOn": {"Fn::Equals": [{"Fn::ImportValue": "%s-export"}, "on"]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsOn"}} + } + """.formatted(stackName)))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> { + assertThat(e.statusCode()).isEqualTo(400); + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).contains("Fn::ImportValue"); + }); + assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("does not exist"); + } + + private void createStack(String template) throws InterruptedException { + cfn.createStack(r -> r.stackName(stackName).templateBody(template)); + TestFixtures.await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return "CREATE_COMPLETE".equals(status); + }, stackName, "CREATE_COMPLETE", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, + TestFixtures.isRealAws() ? 5_000 : 100); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationParameterValuesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationParameterValuesTest.java new file mode 100644 index 0000000000..c824453701 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationParameterValuesTest.java @@ -0,0 +1,118 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.Parameter; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.ssm.SsmClient; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudFormation parameters without a value") +class CloudFormationParameterValuesTest { + + private static final String TEMPLATE = """ + { + "Parameters": {"Env": {"Type": "String"}}, + "Resources": { + "Param": { + "Type": "AWS::SSM::Parameter", + "Properties": {"Name": {"Fn::Sub": "/${AWS::StackName}"}, "Type": "String", + "Value": {"Ref": "Env"}, "Description": "%s"} + } + } + } + """; + + private static CloudFormationClient cfn; + private static SsmClient ssm; + private String stackName; + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + ssm = TestFixtures.ssmClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-param-values"); + } + + @AfterEach + void cleanup() throws InterruptedException { + // Also when the stack was refused: DeleteStack of a name with no stack does nothing. + cfn.deleteStack(r -> r.stackName(stackName)); + TestFixtures.await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks(); + return stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString()); + } catch (CloudFormationException e) { + return e.getMessage().contains("does not exist"); + } + }, stackName, "deleted", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, + TestFixtures.isRealAws() ? 5_000 : 100); + } + + @AfterAll + static void closeClients() { + cfn.close(); + ssm.close(); + } + + @Test + @DisplayName("CreateStack refuses a parameter with no value and no Default, and creates nothing") + void createStackRefusesAParameterWithoutAValue() { + assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("one")))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> { + assertThat(e.statusCode()).isEqualTo(400); + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Parameters: [Env] must have values"); + }); + assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("does not exist"); + } + + @Test + @DisplayName("UpdateStack needs the value again, or UsePreviousValue to keep the deployed one") + void updateStackNeedsAValueOrUsePreviousValue() throws InterruptedException { + cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("one")) + .parameters(Parameter.builder().parameterKey("Env").parameterValue("first").build())); + awaitStatus("CREATE_COMPLETE"); + + assertThatThrownBy(() -> cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("two")))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> { + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Parameters: [Env] must have values"); + }); + assertThat(cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).stackStatusAsString()) + .isEqualTo("CREATE_COMPLETE"); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("two")) + .parameters(Parameter.builder().parameterKey("Env").usePreviousValue(true).build())); + awaitStatus("UPDATE_COMPLETE"); + assertThat(ssm.getParameter(r -> r.name("/" + stackName)).parameter().value()).isEqualTo("first"); + } + + private void awaitStatus(String expected) throws InterruptedException { + TestFixtures.await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return expected.equals(status); + }, stackName, expected, TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, + TestFixtures.isRealAws() ? 5_000 : 100); + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 48e27efdde..e2fc9ddce0 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -416,6 +416,19 @@ before provisioning: tags, bucket names) from Parameter Store. - `AWS::SSM::Parameter::Value>` and `AWS::SSM::Parameter::Name` typed parameters are **not yet** resolved — they are passed through as their literal input. +- **A declared parameter needs a value.** One that the request gives no value and the template no + `Default` fails `CreateStack`, `UpdateStack` and `CreateChangeSet` with `ValidationError` + `Parameters: [Env] must have values`, naming each such parameter, before anything changes. An + empty value counts as a value. An update does not carry values over: set `UsePreviousValue` to + keep the deployed one. `UsePreviousValue` on a parameter that has no deployed value passes none. + The values are checked before the template's dependency checks (a cycle, an unresolved + dependency, a malformed condition), which read them, so a template with a cycle and a missing + value gets this error. A request for a stack that does not exist, cannot be updated, or already + exists gets that stack error instead of this one; a dependency error still comes before the + stack error. The same check + refuses `CreateStackSet` and `UpdateStackSet`, and fails a nested stack's resource whose + `Parameters` leave a child parameter without a value. A parameter that an `AWS::Include` defines + is not checked, nor is any parameter in a section that carries an `AWS::Include` of its own. The `AWS::SSM::Parameter` **resource** type exposes `Value`, `Type`, `Name`, and `Arn` attributes through `Ref` / `Fn::GetAtt` so downstream resources can consume a parameter the same stack creates. @@ -481,6 +494,17 @@ Template `Conditions` are evaluated before provisioning. A resource whose `Condi `Ref` / `Fn::GetAtt` are not required to resolve. This matches CloudFormation and is required for the condition-heavy templates CDK and LZA emit. +The operands of `Fn::Equals` are resolved as resource property values are, so `Ref` to a parameter +or a pseudo parameter (`AWS::StackName` and `AWS::StackId` included) and `Fn::FindInMap`, the +functions CloudFormation supports there, work inside a condition. The dependency check a create runs +before the stack exists sees the `AWS::StackId` the stack is then given. An operand Floci cannot +resolve compares as an empty string. `AWS::NotificationARNs` is the empty list everywhere, as +Floci keeps no notification ARNs. `Fn::ImportValue` is not allowed in a condition, as in CloudFormation: `CreateStack`, +`UpdateStack` and `CreateChangeSet` refuse such a template, with the message `Template error: Cannot +use Fn::ImportValue in Conditions.` A SAM template's change set fails with that reason instead, and +so does the stack when CreateStack or UpdateStack executes it; an `AWS::Include` template fails when +it is executed. + ## Custom Resources and the CDK Provider Framework `AWS::CloudFormation::CustomResource` and `Custom::*` resources are backed by their `ServiceToken` diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java index d42df99e6e..74e0aa96ff 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java @@ -716,13 +716,14 @@ public class CloudFormationQueryHandler { /** * @param previousParameters the stack's currently deployed parameters, consulted when a member - * sets {@code UsePreviousValue=true} instead of a {@code ParameterValue} + * sets {@code UsePreviousValue=true} instead of a {@code ParameterValue}. + * A member naming one that has no deployed value is left out: there is + * no value to keep, so the template's Default applies, or none. */ private Map extractParameters( MultivaluedMap params, Map previousParameters) { Map result = new HashMap<>(); - int i = 1; - while (true) { + for (int i = 1; ; i++) { String key = params.getFirst("Parameters.member." + i + ".ParameterKey"); if (key == null) { break; @@ -730,11 +731,13 @@ public class CloudFormationQueryHandler { String value; if (Boolean.parseBoolean(params.getFirst("Parameters.member." + i + ".UsePreviousValue"))) { value = previousParameters.get(key); + if (value == null) { + continue; + } } else { value = params.getFirst("Parameters.member." + i + ".ParameterValue"); } result.put(key, value != null ? value : ""); - i++; } return result; } @@ -902,7 +905,9 @@ public class CloudFormationQueryHandler { private Response updateStackSet(MultivaluedMap params) { try { String stackSetName = params.getFirst("StackSetName"); - Map previousParameters = stackSetService.describeStackSet(stackSetName).getParameters(); + StackSet current = stackSetService.describeStackSet(stackSetName); + Map previousParameters = + cfnService.parametersWithDefaults(current.getTemplateBody(), current.getParameters()); StackSetOperation op = stackSetService.updateStackSet( stackSetName, cfnService.resolveTemplateBody(params.getFirst("TemplateBody"), params.getFirst("TemplateURL")), diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 265b21768f..c57b75e1c4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -377,6 +377,34 @@ public class CloudFormationService implements ResourceProvider { Map tags, String region, String accountId, boolean attachToReviewInProgressStack, boolean fromPreviousTemplate) { String resolvedTemplate = resolveTemplate(templateBody, templateUrl); + boolean isCreateType = "CREATE".equalsIgnoreCase(changeSetType); + // An update names its stack by name or stack ID; the map is keyed by name. One that names no + // live stack is keyed as given, so it lands in the missing-stack branch below. + Stack live = isCreateType ? null : resolveStack(stackName, region, accountId); + + // Ahead of the transform and the preflight below, which both read the parameter values. A + // request the claim below refuses for its stack alone (an update of a stack that is missing + // or cannot be updated, a create over a name in use) gets that refusal instead: there is no + // deployed value for its UsePreviousValue to keep. + Stack named = isCreateType ? stacks.get(stackKey(accountId, stackName, region)) : live; + boolean refusedForItsStack = isCreateType + ? named != null && !(attachToReviewInProgressStack && "REVIEW_IN_PROGRESS".equals(named.getStatus())) + : named == null || "DELETE_COMPLETE".equals(named.getStatus()) || refusesUpdate(named.getStatus()); + if (!refusedForItsStack) { + requireParameterValues(resolvedTemplate, parameters); + } + + // The preflight evaluates AWS::StackName and AWS::StackId as the execution will: an update + // or a create attaching to a placeholder against that stack, any other create against the + // id it is given below, allocated now. A create over a name in use is checked as that new + // stack, never as the stack holding the name; an update of a missing stack, refused below, + // with the name it gave and an empty id. + boolean attaches = isCreateType && named != null && !refusedForItsStack; + String createdStackId = isCreateType && !attaches ? newStackId(stackName, region, accountId) : null; + Stack identity = isCreateType ? (attaches ? named : null) : live; + String preflightStackName = identity != null ? identity.getStackName() : stackName; + String preflightStackId = identity != null ? identity.getStackId() + : createdStackId != null ? createdStackId : ""; // Real CloudFormation runs a declared macro (here, only AWS::Serverless-2016-10-31) // before it ever evaluates the template's own resources or conditions. On real AWS, @@ -392,7 +420,8 @@ public class CloudFormationService implements ResourceProvider { // template declaring the SAM transform, whether or not that transform succeeded, so // gating this call on samTransformFailureReason == null duplicates that check for no // effect. - validateResourceDependencies(resolvedTemplate, parameters, region, accountId); + validateResourceDependencies(resolvedTemplate, parameters, preflightStackName, preflightStackId, + region, accountId); // A CREATE change set against a name that already has a stack of any status - including // ROLLBACK_COMPLETE - is a real conflict: AWS requires an explicit DeleteStack before a @@ -422,10 +451,6 @@ public class CloudFormationService implements ResourceProvider { // was already released, losing an accepted change set or corrupting the map's links. Only // persistStack() stays outside: it is storage I/O, and compute()'s contract is that the // remapping function does short, non-blocking work. - boolean isCreateType = "CREATE".equalsIgnoreCase(changeSetType); - // An update names its stack by name or stack ID; the map is keyed by name. One that names no - // live stack is keyed as given, so it lands in the missing-stack branch below. - Stack live = isCreateType ? null : resolveStack(stackName, region, accountId); String canonicalStackName = live == null ? stackName : live.getStackName(); ChangeSet[] created = new ChangeSet[1]; Stack stack = stacks.compute(stackKey(accountId, canonicalStackName, region), (k, existing) -> { @@ -434,7 +459,10 @@ public class CloudFormationService implements ResourceProvider { if (!isCreateType) { throw noStackToUpdate(stackName, region, accountId); } - target = newStack(stackName, region, accountId); + // The id the preflight saw; a placeholder that left the map since then has none. + target = newStack(stackName, + createdStackId != null ? createdStackId : newStackId(stackName, region, accountId), + region, accountId); if (tags != null) target.getTags().putAll(tags); // A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the // matching stack-level event (as AWS and LocalStack do) so DescribeStackEvents is @@ -635,9 +663,10 @@ public class CloudFormationService implements ResourceProvider { changedParams.add(k); } }); - // A parameter that was deployed but is omitted from this update with no template - // Default is dropped entirely by resolveDefaultParameters (matching what - // ExecuteChangeSet does); flag its disappearance too, not just a value change. + // A parameter that was deployed but that the new template no longer declares, and the + // update does not pass, is absent from the new values, as it is when ExecuteChangeSet + // runs; flag its disappearance too, not just a value change. One the template still + // declares has a value or a Default: createChangeSet refuses the update otherwise. oldResolvedParams.keySet().forEach(k -> { if (!newResolvedParams.containsKey(k)) { changedParams.add(k); @@ -654,7 +683,7 @@ public class CloudFormationService implements ResourceProvider { ? resolveConditions(oldTemplate, oldResolvedParams, stack, region, regionResolver.getAccountId()) : Map.of(); Map newConditions = resolveConditions( - newTemplate, newResolvedParams, null, region, regionResolver.getAccountId()); + newTemplate, newResolvedParams, stack, region, regionResolver.getAccountId()); Set changedConditions = new HashSet<>(); newConditions.forEach((name, val) -> { if (!Objects.equals(val, oldConditions.get(name))) { @@ -2927,28 +2956,57 @@ public class CloudFormationService implements ResourceProvider { private Map resolveConditions(JsonNode template, Map params, Stack stack, String region, String accountId) { + return resolveConditions(template, params, stack.getStackName(), stack.getStackId(), region, accountId); + } + + /** + * Evaluates the template's {@code Conditions} through the template engine, so an operand of + * {@code Fn::Equals} can be any intrinsic the engine resolves, {@code Fn::FindInMap} and the + * pseudo parameters included. {@code AWS::StackName} and {@code AWS::StackId} resolve to the + * name and id given, so every evaluation of one stack's template passes the stack's own; a + * create's preflight passes the id createChangeSet allocates for the stack it then creates. + */ + private Map resolveConditions(JsonNode template, Map params, + String stackName, String stackId, String region, + String accountId) { Map conditions = new HashMap<>(); JsonNode condNode = template.path("Conditions"); if (!condNode.isObject()) { return conditions; } + Map mappings = new HashMap<>(); + template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue())); + // Every declared parameter has a value or a Default once a template is deployed, but a stack + // stored by an older Floci may lack one. It compares as "", as it did when that stack was + // deployed, rather than as its own name, which is how the engine answers a Ref it cannot resolve. + Map conditionParams = new HashMap<>(params); + template.path("Parameters").fieldNames().forEachRemaining(name -> conditionParams.putIfAbsent(name, "")); + // A template being deployed with an import in a condition is refused up front + // (requireStringConditionReferences); one here is a stored template's, which reads it as "". + CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine( + accountId, region, stackName, stackId, conditionParams, Map.of(), Map.of(), + conditions, mappings, objectMapper, name -> ""); // Two-pass: collect all names first, then evaluate (handles forward references) condNode.fields().forEachRemaining(e -> conditions.put(e.getKey(), false)); condNode.fields().forEachRemaining(e -> - conditions.put(e.getKey(), evaluateCondition(e.getValue(), params, conditions, region, accountId))); + conditions.put(e.getKey(), evaluateCondition(e.getValue(), conditions, engine))); return conditions; } private static final String NON_STRING_CONDITION_REFERENCE = "Template error: every Condition object must have a single String value."; + private static final String IMPORT_VALUE_IN_CONDITION = + "Template error: Cannot use Fn::ImportValue in Conditions."; /** * Rejects a template whose conditions name another one with anything but a string, as * CloudFormation does before evaluating any of them: {@code Fn::And}, {@code Fn::Or} and * {@code Fn::Not} stop early, so evaluation alone would read such an operand as false or never * reach it. SAM's translator emits this shape when a conditional function's event invoke - * destination is itself conditional. Checked on the template being deployed only, so a stored - * template is never a reason an update cannot proceed. + * destination is itself conditional. Also rejects {@code Fn::ImportValue} anywhere in a + * condition, which CloudFormation does not allow there. Checked on the template being deployed + * only, so a stored template read as the old side of a diff, a rollback or a delete ordering is + * never a reason an update cannot proceed. */ private static void requireStringConditionReferencesIn(JsonNode template) { template.path("Conditions").forEach(CloudFormationService::requireStringConditionReferences); @@ -2965,9 +3023,63 @@ public class CloudFormationService implements ResourceProvider { if (expression.has("Condition") && !expression.get("Condition").isTextual()) { throw new AwsException("ValidationError", NON_STRING_CONDITION_REFERENCE, 400); } + if (expression.has("Fn::ImportValue")) { + throw new AwsException("ValidationError", IMPORT_VALUE_IN_CONDITION, 400); + } expression.forEach(CloudFormationService::requireStringConditionReferences); } + /** + * Refuses a template that declares a parameter the request gives no value and the template no + * {@code Default}, as CloudFormation refuses CreateStack, UpdateStack and CreateChangeSet, + * naming every such parameter in the order the template declares them. An empty value is a + * value. {@code UsePreviousValue} is one too: the request handler has already replaced it with + * the deployed value, or left the parameter without one when nothing was deployed. A template + * that does not parse is left for the paths that report that, and so is what an + * {@code AWS::Include} supplies, which only execution merges: a parameter whose definition uses + * one, or every parameter when the section itself is one. + */ + void requireParameterValues(String templateBody, Map params) { + JsonNode template; + try { + template = parseTemplate(templateBody); + } catch (Exception ignored) { + // No Parameters section to check; executing the change set reports the parse error. + return; + } + JsonNode declared = template.path("Parameters"); + if (AwsIncludeProcessor.AWS_INCLUDE.equals(declared.path("Fn::Transform").path("Name").asText(""))) { + return; + } + Map given = resolveDefaultParameters(template, params); + List missing = new ArrayList<>(); + declared.properties().forEach(parameter -> { + String name = parameter.getKey(); + if (!"Fn::Transform".equals(name) && !awsIncludeProcessor.containsAwsInclude(parameter.getValue()) + && !given.containsKey(name)) { + missing.add(name); + } + }); + if (!missing.isEmpty()) { + throw new AwsException("ValidationError", + "Parameters: [" + String.join(", ", missing) + "] must have values", 400); + } + } + + /** + * The values a template deploys with: {@code params} over each parameter's {@code Default}, or + * {@code params} alone when the template does not parse. UpdateStackSet resolves + * {@code UsePreviousValue} against these, since a stack set keeps only the values it was given. + */ + Map parametersWithDefaults(String templateBody, Map params) { + try { + return resolveDefaultParameters(parseTemplate(templateBody), params); + } catch (Exception ignored) { + // No Defaults to add from a template that does not parse; the given values stand. + return params != null ? params : Map.of(); + } + } + /** * Fails a create/update before any stack state is mutated when a resource that will be created * depends on a resource excluded by a false condition, or when resources depend on each other @@ -2981,7 +3093,8 @@ public class CloudFormationService implements ResourceProvider { * graph the execution path resolves correctly. */ private void validateResourceDependencies(String templateBody, Map params, - String region, String accountId) { + String stackName, String stackId, String region, + String accountId) { JsonNode template; try { template = parseTemplate(templateBody); @@ -3000,15 +3113,16 @@ public class CloudFormationService implements ResourceProvider { requireStringConditionReferencesIn(template); Map resolvedParams = resolveDefaultParameters(template, params); + // Against the stack name and id the execution will use, which createChangeSet decides. Map conditions = - resolveConditions(template, resolvedParams, null, region, accountId); + resolveConditions(template, resolvedParams, stackName, stackId, region, accountId); // Throws the ValidationError for either case; the order itself is computed again on execution. topologicalSort(resources, conditions); } - private boolean evaluateCondition(JsonNode expr, Map params, - Map conditions, String region, String accountId) { + private boolean evaluateCondition(JsonNode expr, Map conditions, + CloudFormationTemplateEngine engine) { if (expr == null || expr.isNull()) { return false; } @@ -3022,20 +3136,18 @@ public class CloudFormationService implements ResourceProvider { if (expr.has("Fn::Equals")) { JsonNode args = expr.get("Fn::Equals"); if (args.isArray() && args.size() == 2) { - String left = resolveConditionValue(args.get(0), params, region, accountId); - String right = resolveConditionValue(args.get(1), params, region, accountId); - return left.equals(right); + return conditionOperand(args.get(0), engine).equals(conditionOperand(args.get(1), engine)); } } if (expr.has("Fn::Not")) { JsonNode args = expr.get("Fn::Not"); if (args.isArray() && !args.isEmpty()) { - return !evaluateCondition(args.get(0), params, conditions, region, accountId); + return !evaluateCondition(args.get(0), conditions, engine); } } if (expr.has("Fn::And")) { for (JsonNode item : expr.get("Fn::And")) { - if (!evaluateCondition(item, params, conditions, region, accountId)) { + if (!evaluateCondition(item, conditions, engine)) { return false; } } @@ -3043,7 +3155,7 @@ public class CloudFormationService implements ResourceProvider { } if (expr.has("Fn::Or")) { for (JsonNode item : expr.get("Fn::Or")) { - if (evaluateCondition(item, params, conditions, region, accountId)) { + if (evaluateCondition(item, conditions, engine)) { return true; } } @@ -3053,21 +3165,22 @@ public class CloudFormationService implements ResourceProvider { return false; } - private String resolveConditionValue(JsonNode node, Map params, - String region, String accountId) { - if (node.isTextual()) { - return node.textValue(); + /** + * An {@code Fn::Equals} operand as the template engine resolves it. One the engine cannot + * resolve, such as an {@code Fn::Sub} whose template is not a string, compares as an empty + * string, as every function did before conditions went through the engine, so a template that + * evaluated then, stored or new, still evaluates and gets its dependency checks. + */ + private static String conditionOperand(JsonNode operand, CloudFormationTemplateEngine engine) { + try { + return engine.resolve(operand); + } catch (AwsException e) { + throw e; + } catch (RuntimeException e) { + LOG.debugv("Condition operand {0} did not resolve and compares as an empty string: {1}", + operand, e.getMessage()); + return ""; } - if (node.isObject() && node.has("Ref")) { - String name = node.get("Ref").asText(); - return switch (name) { - case "AWS::AccountId" -> accountId; - case "AWS::Region" -> region; - case "AWS::NoValue" -> ""; - default -> params.getOrDefault(name, ""); - }; - } - return node.asText(); } private JsonNode parseTemplate(String templateBody) throws Exception { @@ -3263,6 +3376,34 @@ public class CloudFormationService implements ResourceProvider { String childTemplate = fetchTemplateFromS3(templateUrl); String childStackName = parentStack.getStackName() + "-" + logicalId; + // Resolved as a property value: Parameters may be an Fn::If choosing between whole maps, + // and a value that is AWS::NoValue passes nothing, so the child's Default applies. A list, + // such as an Fn::GetAZs resolves to, is passed joined with commas, and a null as an empty + // string, as before. + Map childParams = new LinkedHashMap<>(); + JsonNode parameters = props == null ? null : engine.resolveNodeOmittingNoValue(props.get("Parameters")); + if (parameters != null && parameters.isObject()) { + parameters.fields().forEachRemaining(e -> { + JsonNode value = e.getValue(); + if (value.isArray()) { + List items = new ArrayList<>(); + value.forEach(item -> items.add(item.asText())); + childParams.put(e.getKey(), String.join(",", items)); + } else { + childParams.put(e.getKey(), value.isNull() ? "" : value.asText()); + } + }); + } + // CloudFormation creates or updates the child with these values, so the call fails as a + // CreateStack or UpdateStack would, before the child is created or changed. + try { + requireParameterValues(childTemplate, childParams); + } catch (AwsException e) { + resource.setStatus("CREATE_FAILED"); + resource.setStatusReason(e.getMessage()); + return resource; + } + Stack childStack = null; boolean childCreate = isCreate || previousResource == null || previousResource.getPhysicalId() == null; @@ -3271,17 +3412,11 @@ public class CloudFormationService implements ResourceProvider { childCreate = childStack == null; } if (childCreate) { - childStack = newStack(childStackName, region, accountId); + childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId); childStack.setStatus("CREATE_IN_PROGRESS"); stacks.put(stackKey(accountId, childStackName, region), childStack); } - Map childParams = new LinkedHashMap<>(); - if (props != null && props.has("Parameters") && props.get("Parameters").isObject()) { - props.get("Parameters").fields().forEachRemaining(e -> - childParams.put(e.getKey(), engine.resolve(e.getValue()))); - } - executeTemplate(childStack, childTemplate, childParams, null, childCreate, region, accountId); resource.setPhysicalId(childStack.getStackId()); @@ -3310,13 +3445,16 @@ public class CloudFormationService implements ResourceProvider { } - private Stack newStack(String stackName, String region, String accountId) { + private static String newStackId(String stackName, String region, String accountId) { + return AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/" + stackName + "/" + UUID.randomUUID()).toString(); + } + + private Stack newStack(String stackName, String stackId, String region, String accountId) { Stack stack = new Stack(); stack.setStackName(stackName); stack.setRegion(region); stack.setAccountId(accountId); stack.setStatus("REVIEW_IN_PROGRESS"); - String stackId = AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/" + stackName + "/" + UUID.randomUUID()).toString(); stack.setStackId(stackId); stack.setCreationTime(now()); return stack; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index d5004d77e6..62a0dca07c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -342,6 +342,8 @@ public class CloudFormationTemplateEngine { case "AWS::StackId" -> stackId; case "AWS::Partition" -> AwsRegions.partitionFor(region); case "AWS::URLSuffix" -> AwsRegions.dnsSuffixFor(region); + // Floci keeps no notification ARNs for a stack, so the list is empty. + case "AWS::NotificationARNs" -> ""; case "AWS::NoValue" -> ""; default -> { if (physicalIds.containsKey(name)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index 48d77d9ef6..48250830e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -128,6 +128,9 @@ public class StackSetService { if ("SELF_MANAGED".equals(resolvedPermissionModel) && (autoDeploymentEnabled || retainStacksOnAccountRemoval)) { throw new AwsException("ValidationError", "AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400); } + // Every instance is deployed with these parameters, so a template parameter left without a + // value would fail each one; refuse the stack set instead. + cfnService.requireParameterValues(templateBody, parameters); StackSet ss = new StackSet(); ss.setStackSetName(name); @@ -194,6 +197,11 @@ public class StackSetService { Boolean retainStacksOnAccountRemoval, Boolean managedExecutionActive) { StackSet ss = getStackSetOrThrow(name); + // Checked against the template and parameters the update leaves the stack set with, before + // either is changed or an operation is recorded. + cfnService.requireParameterValues( + templateBody != null && !templateBody.isBlank() ? templateBody : ss.getTemplateBody(), + parameters != null && !parameters.isEmpty() ? parameters : ss.getParameters()); String operationId = reserveOperation(name, "UPDATE", requestedOperationId).getOperationId(); if (templateBody != null && !templateBody.isBlank()) { ss.setTemplateBody(templateBody); @@ -311,36 +319,42 @@ public class StackSetService { for (String ou : targetOus) validateOuOrRoot(ou); String operationId = reserveOperation(name, "CREATE", requestedOperationId).getOperationId(); - List targets = !directAccounts.isEmpty() - ? directAccounts.stream().map(account -> new TargetAccount(account, Set.of())).toList() - : resolveOrganizationTargets(targetOus, regions, name); - List deployed = new ArrayList<>(); - for (TargetAccount target : targets) { - for (String region : regions) { - String instanceKey = instanceKey(name, target.accountId(), region); - StackInstance existing = instances.get(instanceKey).orElse(null); - if (existing != null && !"OUTDATED".equals(existing.getStatus())) { - if (!target.organizationalUnitIds().isEmpty()) { - Set associations = deploymentTargetsFor(existing); - if (associations.addAll(target.organizationalUnitIds())) { - applyDeploymentTargets(existing, associations); - instances.put(instanceKey, existing); + try { + List targets = !directAccounts.isEmpty() + ? directAccounts.stream().map(account -> new TargetAccount(account, Set.of())).toList() + : resolveOrganizationTargets(targetOus, regions, name); + for (TargetAccount target : targets) { + for (String region : regions) { + String instanceKey = instanceKey(name, target.accountId(), region); + StackInstance existing = instances.get(instanceKey).orElse(null); + if (existing != null && !"OUTDATED".equals(existing.getStatus())) { + if (!target.organizationalUnitIds().isEmpty()) { + Set associations = deploymentTargetsFor(existing); + if (associations.addAll(target.organizationalUnitIds())) { + applyDeploymentTargets(existing, associations); + instances.put(instanceKey, existing); + } } + continue; } - continue; + StackInstance inst = deployInstance(ss, target.accountId(), region, INSTANCE_CHANGE_SET, "CREATE"); + Set associations = existing == null + ? new LinkedHashSet<>() : deploymentTargetsFor(existing); + associations.addAll(target.organizationalUnitIds()); + applyDeploymentTargets(inst, associations); + instances.put(instanceKey, inst); + deployed.add(inst); } - StackInstance inst = deployInstance(ss, target.accountId(), region, INSTANCE_CHANGE_SET, "CREATE"); - Set associations = existing == null - ? new LinkedHashSet<>() : deploymentTargetsFor(existing); - associations.addAll(target.organizationalUnitIds()); - applyDeploymentTargets(inst, associations); - instances.put(instanceKey, inst); - deployed.add(inst); } + completeOperation(name, operationId, deriveOperationStatus(deployed)); + return describeStackSetOperation(name, operationId); + } catch (RuntimeException e) { + // An organizational unit that cannot be resolved, or an instance whose change set is + // refused: the operation fails rather than stay RUNNING, which would refuse every later one. + completeOperation(name, operationId, "FAILED"); + throw e; } - completeOperation(name, operationId, deriveOperationStatus(deployed)); - return describeStackSetOperation(name, operationId); } public List listStackSetAutoDeploymentTargets(String name) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java index 1e6b931118..490445ab6f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java @@ -230,7 +230,7 @@ class CloudFormationChangeSetDiffIntegrationTest { } @Test - void omittedParameterWithNoDefault_isReportedAsAChange() { + void omittedParameterWithNoDefault_isRefused() { String stackName = "cs-diff-omitted-param-no-default-stack"; stacksToDelete.add(stackName); @@ -262,9 +262,9 @@ class CloudFormationChangeSetDiffIntegrationTest { .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. + // Same template, but the update omits Suffix entirely and the template has no Default. An + // update does not carry the deployed value over, so CloudFormation refuses the change set + // rather than preview, or apply, the parameter without a value. given() .contentType("application/x-www-form-urlencoded") .formParam("Action", "CreateChangeSet") @@ -275,19 +275,9 @@ class CloudFormationChangeSetDiffIntegrationTest { .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("Q")) - .body(containsString("Modify")); + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Parameters: [Suffix] must have values")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationParameterValuesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationParameterValuesIntegrationTest.java new file mode 100644 index 0000000000..28ac98a142 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationParameterValuesIntegrationTest.java @@ -0,0 +1,663 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +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.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A declared parameter that the request gives no value and the template no {@code Default} + * fails CreateStack, UpdateStack and CreateChangeSet with {@code Parameters: [X] must have values}, + * before any stack state changes. {@code UsePreviousValue} supplies the deployed value on an update. + */ +@QuarkusTest +class CloudFormationParameterValuesIntegrationTest { + + private static final String BLANK_ENV_TEMPLATE = """ + { + "Parameters": {"Env": {"Type": "String"}}, + "Conditions": {"IsBlank": {"Fn::Equals": [{"Ref": "Env"}, ""]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsBlank"}} + } + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createStackRefusesAParameterWithNoValueAndNoDefault() { + String stackName = "cfn-param-missing-" + Long.toString(System.nanoTime(), 36); + + request("CreateStack", stackName) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + + describeStacks(stackName).then().statusCode(400); + } + + /** Every such parameter is named, in the order the template declares them. */ + @Test + void everyParameterWithoutAValueIsNamed() { + String stackName = "cfn-param-several-" + Long.toString(System.nanoTime(), 36); + + request("CreateStack", stackName) + .formParam("TemplateBody", """ + { + "Parameters": { + "Zeta": {"Type": "String"}, + "Alpha": {"Type": "String", "Default": "a"}, + "Beta": {"Type": "Number"}, + "Gamma": {"Type": "String"} + }, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue"}} + } + """) + .formParam("Parameters.member.1.ParameterKey", "Gamma") + .formParam("Parameters.member.1.ParameterValue", "g") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Zeta, Beta] must have values")); + + describeStacks(stackName).then().statusCode(400); + } + + /** + * The values are checked before the template's dependency checks, which evaluate conditions + * that read them, so a template with both a cycle and a missing value gets the parameter error. + */ + @Test + void aMissingValueIsReportedBeforeADependencyCycle() { + String stackName = "cfn-param-cycle-" + Long.toString(System.nanoTime(), 36); + + request("CreateStack", stackName) + .formParam("TemplateBody", """ + { + "Parameters": {"Env": {"Type": "String"}}, + "Resources": { + "A": {"Type": "AWS::SQS::Queue", "DependsOn": "B"}, + "B": {"Type": "AWS::SQS::Queue", "DependsOn": "A"} + } + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + + describeStacks(stackName).then().statusCode(400); + } + + /** An empty value is a value, and a Default stands in for an omitted one. */ + @Test + void anEmptyValueAndADefaultAreValues() { + String stackName = "cfn-param-empty-" + Long.toString(System.nanoTime(), 36); + String queueName = "param-empty-" + Long.toString(System.nanoTime(), 36); + + request("CreateStack", stackName) + .formParam("TemplateBody", """ + { + "Parameters": { + "Env": {"Type": "String"}, + "Timeout": {"Type": "Number", "Default": "45"} + }, + "Conditions": {"IsBlank": {"Fn::Equals": [{"Ref": "Env"}, ""]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsBlank", + "Properties": {"QueueName": "%s", "VisibilityTimeout": {"Ref": "Timeout"}}}} + } + """.formatted(queueName)) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.ParameterValue", "") + .when() + .post("/") + .then() + .statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + getQueueUrl(queueName).then().statusCode(200); + } finally { + deleteStack(stackName); + } + } + + /** A CREATE change set is refused too, and leaves no REVIEW_IN_PROGRESS stack behind. */ + @Test + void createChangeSetRefusesAParameterWithNoValue() { + String stackName = "cfn-param-changeset-" + Long.toString(System.nanoTime(), 36); + + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "deploy") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + + describeStacks(stackName).then().statusCode(400); + } + + /** + * The check runs before the SAM transform, so a SAM template is refused with the same 400 + * rather than given a change set that fails later. + */ + @Test + void samTemplateWithoutAValueIsRefusedBeforeTheTransform() { + String stackName = "cfn-param-sam-" + Long.toString(System.nanoTime(), 36); + + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "deploy") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Parameters": {"Env": {"Type": "String"}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", + "Properties": {"QueueName": {"Fn::Sub": "sam-${Env}"}}}} + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + + describeStacks(stackName).then().statusCode(400); + } + + /** + * An update does not carry a parameter over: one it omits is refused whether the update sends + * a template or reuses the previous one, and the stack keeps its status and value. + * {@code UsePreviousValue} keeps the deployed value, on UpdateStack and on an UPDATE change set. + */ + @Test + void anUpdateNeedsAValueOrUsePreviousValue() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-param-update-" + suffix; + String queueName = "param-update-" + suffix; + String template = """ + { + "Parameters": {"Env": {"Type": "String"}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", + "Properties": {"QueueName": {"Fn::Sub": "%s-${Env}"}, "VisibilityTimeout": %d}}} + } + """; + request("CreateStack", stackName) + .formParam("TemplateBody", template.formatted(queueName, 30)) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.ParameterValue", "dev") + .when() + .post("/") + .then() + .statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + request("UpdateStack", stackName) + .formParam("TemplateBody", template.formatted(queueName, 60)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + request("UpdateStack", stackName) + .formParam("UsePreviousTemplate", "true") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "omits-env") + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template.formatted(queueName, 60)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + describeStacks(stackName).then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("dev")); + + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "keeps-env") + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template.formatted(queueName, 45)) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(200); + + request("UpdateStack", stackName) + .formParam("TemplateBody", template.formatted(queueName, 60)) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("60", visibilityTimeout(queueName + "-dev")); + describeStacks(stackName).then() + .statusCode(200) + .body(containsString("dev")); + } finally { + deleteStack(stackName); + } + } + + /** + * {@code UsePreviousValue} keeps a deployed value; on a parameter that has none, on a create or + * for a parameter the update adds, it passes nothing, so the template's Default applies, or the + * request is refused. + */ + @Test + void usePreviousValueWithNothingDeployedPassesNoValue() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-param-previous-" + suffix; + String queueName = "param-previous-" + suffix; + + request("CreateStack", stackName) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + + request("CreateStack", stackName) + .formParam("TemplateBody", """ + {"Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%s"}}}} + """.formatted(queueName)) + .when() + .post("/") + .then() + .statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + String added = """ + { + "Parameters": {"Added": {"Type": "String"%s}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", + "Properties": {"QueueName": "%s", "Tags": [{"Key": "added", "Value": {"Ref": "Added"}}]}}} + } + """; + request("UpdateStack", stackName) + .formParam("TemplateBody", added.formatted("", queueName)) + .formParam("Parameters.member.1.ParameterKey", "Added") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Added] must have values")); + + request("UpdateStack", stackName) + .formParam("TemplateBody", added.formatted(", \"Default\": \"fallback\"", queueName)) + .formParam("Parameters.member.1.ParameterKey", "Added") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + describeStacks(stackName).then() + .statusCode(200) + .body(containsString("fallback")); + } finally { + deleteStack(stackName); + } + } + + /** + * A request its stack refuses outright gets that refusal, whatever its parameters: an update of + * a stack that does not exist, whose UsePreviousValue has nothing to keep, and a create over a + * name in use. + */ + @Test + void aRequestItsStackRefusesGetsThatRefusal() { + String suffix = Long.toString(System.nanoTime(), 36); + String missing = "cfn-param-missing-stack-" + suffix; + request("UpdateStack", missing) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Stack with id " + missing + " does not exist")); + + String taken = "cfn-param-taken-" + suffix; + request("CreateStack", taken) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.ParameterValue", "") + .when() + .post("/") + .then() + .statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(taken).status()); + request("CreateStack", taken) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("AlreadyExistsException")); + } finally { + deleteStack(taken); + } + } + + /** + * A REVIEW_IN_PROGRESS placeholder refuses an update, so an update without a value gets that + * refusal; a CREATE change set may attach to it, so one without a value gets the parameter error. + */ + @Test + void aPlaceholderStackRefusesTheUpdateButNotTheAttachingCreate() { + String stackName = "cfn-param-placeholder-" + Long.toString(System.nanoTime(), 36); + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "first") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .formParam("Parameters.member.1.ParameterKey", "Env") + .formParam("Parameters.member.1.ParameterValue", "") + .when() + .post("/") + .then() + .statusCode(200); + try { + request("UpdateStack", stackName) + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", + containsString("is in REVIEW_IN_PROGRESS state and can not be updated.")); + + request("CreateChangeSet", stackName) + .formParam("ChangeSetName", "second") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", BLANK_ENV_TEMPLATE) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Env] must have values")); + } finally { + deleteStack(stackName); + } + } + + /** + * A nested stack is created with the values its resource passes, so a child parameter left + * without one fails that resource, as the child's CreateStack would, and the parent rolls + * back. The child stack is never created. + */ + @Test + void aNestedStackWithoutAValueFailsItsResource() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cfn-param-nested-" + suffix; + String stackName = "cfn-param-nested-" + suffix; + String templateUrl = putChildTemplate(bucket); + try { + request("CreateStack", stackName) + .formParam("TemplateBody", parentTemplate(templateUrl, "{}")) + .when() + .post("/") + .then() + .statusCode(200); + CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE"); + assertEquals("Parameters: [Env] must have values", state.reason()); + request("DescribeStackEvents", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("Parameters: [Env] must have values")); + describeStacks(stackName + "-Child").then().statusCode(400); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + deleteChildTemplate(bucket); + } + } + + /** + * A nested stack update that leaves a child parameter without a value fails the resource + * before the child changes, and the parent rolls back with the child as it was. + */ + @Test + void aNestedStackUpdateWithoutAValueLeavesTheChild() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cfn-param-nested-update-" + suffix; + String stackName = "cfn-param-nested-update-" + suffix; + String templateUrl = putChildTemplate(bucket); + try { + request("CreateStack", stackName) + .formParam("TemplateBody", parentTemplate(templateUrl, "{\"Env\": \"dev\"}")) + .when() + .post("/") + .then() + .statusCode(200); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + request("UpdateStack", stackName) + .formParam("TemplateBody", parentTemplate(templateUrl, "{\"Size\": \"2\"}")) + .when() + .post("/") + .then() + .statusCode(200); + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE"); + request("DescribeStackEvents", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("Parameters: [Env] must have values")); + describeStacks(stackName + "-Child").then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("dev")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + deleteChildTemplate(bucket); + } + } + + /** + * The resource's Parameters resolve as a property value: an Fn::If choosing the whole map + * passes the chosen one, and a value that is AWS::NoValue passes nothing, so the child's + * Default applies. + */ + @Test + void aNestedStacksParametersResolveAsAPropertyValue() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cfn-param-nested-if-" + suffix; + String stackName = "cfn-param-nested-if-" + suffix; + String templateUrl = putChildTemplate(bucket); + try { + request("CreateStack", stackName) + .formParam("TemplateBody", """ + { + "Conditions": {"Always": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Child": { + "Type": "AWS::CloudFormation::Stack", + "Properties": {"TemplateURL": "%s", "Parameters": {"Fn::If": ["Always", + {"Env": "dev", "Size": {"Ref": "AWS::NoValue"}}, {"Env": "prod"}]}} + } + } + } + """.formatted(templateUrl)) + .when() + .post("/") + .then() + .statusCode(200); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + describeStacks(stackName + "-Child").then() + .statusCode(200) + .body("**.find { it.ParameterKey == 'Env' }.ParameterValue", equalTo("dev")) + .body("**.find { it.ParameterKey == 'Size' }.ParameterValue", equalTo("1")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + deleteChildTemplate(bucket); + } + } + + /** + * A parameter definition an AWS::Include supplies is only known once execution merges it, so it + * is not checked up front: a Default the snippet carries still applies. The section's other + * parameters are checked as usual. + */ + @Test + void aParameterAnIncludeDefinesIsNotCheckedUpFront() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cfn-param-include-" + suffix; + String stackName = "cfn-param-include-" + suffix; + String queueName = "param-include-" + suffix; + given().when().put("/" + bucket).then().statusCode(200); + given().body("{\"Type\": \"String\", \"Default\": \"dev\"}") + .when().put("/" + bucket + "/env.json").then().statusCode(200); + try { + request("CreateStack", stackName) + .formParam("TemplateBody", """ + { + "Parameters": {"Env": {"Fn::Transform": {"Name": "AWS::Include", + "Parameters": {"Location": "s3://%s/env.json"}}}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", + "Properties": {"QueueName": {"Fn::Sub": "%s-${Env}"}}}} + } + """.formatted(bucket, queueName)) + .when() + .post("/") + .then() + .statusCode(200); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + getQueueUrl(queueName + "-dev").then().statusCode(200); + + request("CreateStack", stackName + "-other") + .formParam("TemplateBody", """ + { + "Parameters": {"Other": {"Type": "String"}, "Env": {"Fn::Transform": {"Name": "AWS::Include", + "Parameters": {"Location": "s3://%s/env.json"}}}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue"}} + } + """.formatted(bucket)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("Parameters: [Other] must have values")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + given().when().delete("/" + bucket + "/env.json"); + given().when().delete("/" + bucket); + } + } + + /** Puts a child template declaring Env (no Default) and Size (Default 1) in a new bucket. */ + private static String putChildTemplate(String bucket) { + given().when().put("/" + bucket).then().statusCode(200); + given().contentType("application/json") + .body(""" + { + "Parameters": {"Env": {"Type": "String"}, "Size": {"Type": "Number", "Default": "1"}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue"}} + } + """) + .when() + .put("/" + bucket + "/child.json") + .then() + .statusCode(200); + return "http://localhost/" + bucket + "/child.json"; + } + + private static void deleteChildTemplate(String bucket) { + given().when().delete("/" + bucket + "/child.json"); + given().when().delete("/" + bucket); + } + + private static String parentTemplate(String templateUrl, String parameters) { + return """ + { + "Resources": { + "Child": { + "Type": "AWS::CloudFormation::Stack", + "Properties": {"TemplateURL": "%s", "Parameters": %s} + } + } + } + """.formatted(templateUrl, parameters); + } + + private static RequestSpecification request(String action, String stackName) { + return given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("StackName", stackName); + } + + private static Response describeStacks(String stackName) { + return request("DescribeStacks", stackName).when().post("/"); + } + + private static void deleteStack(String stackName) { + request("DeleteStack", stackName).when().post("/").then().statusCode(200); + } + + private static Response getQueueUrl(String queueName) { + return given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueUrl") + .formParam("QueueName", queueName) + .when() + .post("/"); + } + + private static String visibilityTimeout(String queueName) { + String queueUrl = getQueueUrl(queueName).then().statusCode(200).extract().xmlPath() + .getString("GetQueueUrlResponse.GetQueueUrlResult.QueueUrl"); + return given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueAttributes") + .formParam("QueueUrl", queueUrl) + .formParam("AttributeName.1", "VisibilityTimeout") + .when() + .post("/") + .then() + .statusCode(200) + .extract().xmlPath() + .getString("**.find { it.Name == 'VisibilityTimeout' }.Value"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java index ba046b329b..bdb4a24e6a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java @@ -4,11 +4,14 @@ 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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @QuarkusTest @@ -62,6 +65,90 @@ class CloudFormationResourceConditionIntegrationTest { .statusCode(400); } + /** + * Fn::FindInMap inside Fn::Equals resolves through the template's mappings. Read as an empty + * string, a mapped "false" made UseCode true, and the bucket was named after the mapped value. + */ + @ParameterizedTest + @CsvSource({"false,us-east-1", "iad,iad"}) + void mappedConditionSelectsTheBucketName(String mappedValue, String expectedLocation) { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-mapped-condition-" + suffix; + String prefix = "mapped-condition-" + suffix + "-"; + createStack(stackName, """ + { + "Mappings": {"Locations": {"us-east-1": {"Code": "%s"}}}, + "Conditions": { + "UseCode": {"Fn::Not": [{"Fn::Equals": [ + {"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, "false" + ]}]} + }, + "Resources": { + "Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": {"BucketName": {"Fn::Join": ["", ["%s", + {"Fn::If": ["UseCode", + {"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, + {"Ref": "AWS::Region"}]} + ]]}} + } + } + } + """.formatted(mappedValue, prefix)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + given().when().head("/" + prefix + expectedLocation).then().statusCode(200); + given().when().head("/" + prefix + "false").then().statusCode(404); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + given().when().head("/" + prefix + expectedLocation).then().statusCode(404); + } + + /** + * The update's change-set preview and its execution evaluate the mapped condition as the + * create does, so a mapping edit that flips it reaches the property chosen by its Fn::If. + */ + @Test + void mappedConditionIsEvaluatedAgainOnUpdate() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-mapped-update-" + suffix; + String queueName = "mapped-update-" + suffix; + String template = """ + { + "Mappings": {"Locations": {"us-east-1": {"Code": "%s"}}}, + "Conditions": { + "UseCode": {"Fn::Not": [{"Fn::Equals": [ + {"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, "false" + ]}]} + }, + "Resources": { + "Queue": { + "Type": "AWS::SQS::Queue", + "Properties": {"QueueName": "%s", "VisibilityTimeout": {"Fn::If": ["UseCode", 60, 30]}} + } + } + } + """; + createStack(stackName, template.formatted("false", queueName)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("30", visibilityTimeout(queueName)); + + updateStack(stackName, template.formatted("iad", queueName)); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("60", visibilityTimeout(queueName)); + + updateStack(stackName, template.formatted("false", queueName)); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("30", visibilityTimeout(queueName)); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + @Test void createStack_skipsResourceWhenResourceLevelConditionIsFalse() { String suffix = Long.toString(System.nanoTime(), 36); @@ -581,6 +668,340 @@ class CloudFormationResourceConditionIntegrationTest { .post("/"); } + /** + * A create's dependency preflight evaluates {@code AWS::StackId} as the id the stack is given, + * so it agrees with the execution: a dependency on a resource the stack id excludes is refused + * up front, and one on a resource it includes deploys. + */ + @Test + void aCreatesPreflightSeesTheStackIdItWillGet() { + String suffix = Long.toString(System.nanoTime(), 36); + String template = """ + { + "Conditions": { + "NoId": {"Fn::Equals": [{"Ref": "AWS::StackId"}, ""]}, + "HasId": {"Fn::Not": [{"Condition": "NoId"}]} + }, + "Resources": { + "Dependency": {"Type": "AWS::SQS::Queue", "Condition": "%s", + "Properties": {"QueueName": "%s-dependency"}}, + "Dependent": {"Type": "AWS::SQS::Queue", "DependsOn": "Dependency", + "Properties": {"QueueName": "%s-dependent"}} + } + } + """; + String excluded = "cfn-stackid-excluded-" + suffix; + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", excluded) + .formParam("TemplateBody", template.formatted("NoId", excluded, excluded)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", containsString("Unresolved resource dependencies")); + + String included = "cfn-stackid-included-" + suffix; + createStack(included, template.formatted("HasId", included, included)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(included).status()); + getQueueUrl(included + "-dependency").then().statusCode(200); + getQueueUrl(included + "-dependent").then().statusCode(200); + } finally { + deleteStack(included); + CfnStackWaits.awaitStackDeleted(included); + } + } + + /** + * A create over a name in use is checked as the new stack it asks for, not as the stack that + * holds the name, so a template that is valid for a new stack gets AlreadyExistsException. + */ + @Test + void aCreateOverATakenNameIsCheckedAsTheNewStack() { + String stackName = "cfn-stackid-taken-" + Long.toString(System.nanoTime(), 36); + createStack(stackName, """ + {"Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%s"}}}} + """.formatted(stackName)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + String takenId = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().xmlPath().getString("**.find { it.name() == 'StackId' }"); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", """ + { + "Conditions": {"NotTheTakenStack": {"Fn::Not": [{"Fn::Equals": [ + {"Ref": "AWS::StackId"}, "%s"]}]}}, + "Resources": { + "Dependency": {"Type": "AWS::SQS::Queue", "Condition": "NotTheTakenStack"}, + "Dependent": {"Type": "AWS::SQS::Queue", "DependsOn": "Dependency"} + } + } + """.formatted(takenId)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("AlreadyExistsException")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + /** + * The change-set preview, the preflight and the execution all evaluate {@code AWS::StackName} + * against the stack. Read as an empty string, the condition was false and the stack held no + * resources; with only the preview reading it so, the update would skip the queue's edit. + */ + @Test + void stackNameConditionHoldsAcrossAnUpdateThatEditsItsResource() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-stackname-condition-" + suffix; + String queueName = "stackname-condition-" + suffix; + String template = """ + { + "Conditions": {"IsThisStack": {"Fn::Equals": [{"Ref": "AWS::StackName"}, "%s"]}}, + "Resources": { + "Queue": { + "Type": "AWS::SQS::Queue", "Condition": "IsThisStack", + "Properties": {"QueueName": "%s", "VisibilityTimeout": %d} + } + } + } + """; + createStack(stackName, template.formatted(stackName, queueName, 30)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("30", visibilityTimeout(queueName)); + + updateStack(stackName, template.formatted(stackName, queueName, 60)); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("60", visibilityTimeout(queueName)); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + /** + * CloudFormation allows only Ref, Fn::FindInMap and the condition functions inside a + * condition, so a template that uses Fn::ImportValue there is refused, even though the + * exporting stack has the export. + */ + @Test + void importValueInAConditionIsRejectedAsUnsupported() { + String suffix = Long.toString(System.nanoTime(), 36); + String exporter = "cfn-cond-exporter-" + suffix; + String exportName = "cfn-cond-export-" + suffix; + String importer = "cfn-cond-importer-" + suffix; + createStack(exporter, """ + {"Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%s"}}}, + "Outputs": {"Flag": {"Value": "on", "Export": {"Name": "%s"}}}} + """.formatted("cond-export-queue-" + suffix, exportName)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(exporter).status()); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", importer) + .formParam("TemplateBody", """ + {"Conditions": {"IsOn": {"Fn::Equals": [{"Fn::ImportValue": "%s"}, "on"]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsOn"}}} + """.formatted(exportName)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("Template error: Cannot use Fn::ImportValue in Conditions.")); + } finally { + deleteStack(importer); + deleteStack(exporter); + CfnStackWaits.awaitStackDeleted(exporter); + } + } + + /** An import in an Fn::Or operand that evaluation never reaches is still a template error. */ + @Test + void importValueInAConditionOperandEvaluationSkipsIsStillRejected() { + String stackName = "cfn-cond-or-import-" + Long.toString(System.nanoTime(), 36); + try { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", """ + {"Conditions": {"IsOn": {"Fn::Or": [{"Fn::Equals": ["a", "a"]}, + {"Fn::Equals": [{"Fn::ImportValue": "never-resolved"}, "on"]}]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsOn"}}} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("Template error: Cannot use Fn::ImportValue in Conditions.")); + } finally { + deleteStack(stackName); + } + } + + /** + * A SAM template's conditions are checked after the transform, so an import there fails the + * change set with the template error, as a non-string condition reference does. + */ + @Test + void importValueInASamTemplateConditionFailsTheChangeSet() { + String stackName = "cfn-cond-sam-import-" + Long.toString(System.nanoTime(), 36); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "deploy") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", """ + {"Transform": "AWS::Serverless-2016-10-31", + "Conditions": {"IsOn": {"Fn::Equals": [{"Fn::ImportValue": "never-resolved"}, "on"]}}, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsOn"}}} + """) + .when() + .post("/") + .then() + .statusCode(200); + try { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "deploy") + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeChangeSetResponse.DescribeChangeSetResult.Status", equalTo("FAILED")) + .body("DescribeChangeSetResponse.DescribeChangeSetResult.StatusReason", + equalTo("Template error: Cannot use Fn::ImportValue in Conditions.")); + } finally { + deleteStack(stackName); + } + } + + /** + * {@code AWS::NotificationARNs} is the empty list, in a condition and in an output: Floci keeps + * no notification ARNs, and the template engine would otherwise answer the Ref with its name. + */ + @Test + void notificationArnsAreAnEmptyList() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-notification-arns-" + suffix; + String queueName = "notification-arns-" + suffix; + createStack(stackName, """ + { + "Conditions": { + "HasNotifications": {"Fn::Not": [{"Fn::Equals": [ + {"Fn::Join": [",", {"Ref": "AWS::NotificationARNs"}]}, ""]}]} + }, + "Resources": { + "Notified": {"Type": "AWS::SQS::Queue", "Condition": "HasNotifications", + "Properties": {"QueueName": "%s-notified"}}, + "Always": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "%s-always"}} + }, + "Outputs": {"Arns": {"Value": {"Fn::Join": [",", ["arns", {"Fn::Join": [",", + {"Ref": "AWS::NotificationARNs"}]}]]}}} + } + """.formatted(queueName, queueName)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + getQueueUrl(queueName + "-always").then().statusCode(200); + getQueueUrl(queueName + "-notified").then().statusCode(400); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body("**.find { it.OutputKey == 'Arns' }.OutputValue", equalTo("arns,")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + /** + * A condition operand the template engine cannot resolve, here an Fn::Sub whose template is not + * a string, compares as an empty string, as it did before conditions went through the engine: + * the stack deploys, and the dependency checks still run, rather than the request failing with + * a 500 or the stack with the engine's exception. + */ + @Test + void aConditionOperandTheEngineCannotResolveComparesAsEmpty() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-cond-malformed-sub-" + suffix; + String queueName = "cond-malformed-sub-" + suffix; + String condition = """ + "Conditions": {"IsBlank": {"Fn::Equals": [{"Fn::Sub": [{"Ref": "AWS::Region"}, {}]}, ""]}}"""; + createStack(stackName, """ + {%s, + "Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsBlank", + "Properties": {"QueueName": "%s"}}}} + """.formatted(condition, queueName)); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + getQueueUrl(queueName).then().statusCode(200); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName + "-cycle") + .formParam("TemplateBody", """ + {%s, + "Resources": { + "A": {"Type": "AWS::SQS::Queue", "DependsOn": "B"}, + "B": {"Type": "AWS::SQS::Queue", "DependsOn": "A"}}} + """.formatted(condition)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", containsString("Circular dependency between resources")); + } + + private static String visibilityTimeout(String queueName) { + String queueUrl = getQueueUrl(queueName).then().statusCode(200).extract().xmlPath() + .getString("GetQueueUrlResponse.GetQueueUrlResult.QueueUrl"); + return given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueAttributes") + .formParam("QueueUrl", queueUrl) + .formParam("AttributeName.1", "VisibilityTimeout") + .when() + .post("/") + .then() + .statusCode(200) + .extract().xmlPath() + .getString("**.find { it.Name == 'VisibilityTimeout' }.Value"); + } + @Test void createStack_failsWhenResourceReferencesConditionFalseResourceViaGetAtt() { // Verified against real AWS: an unguarded Fn::GetAtt to a condition-false resource is diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java index ba517ec76b..39e01962a5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java @@ -381,6 +381,46 @@ class CloudFormationServiceManagedStackSetsIntegrationTest { assertQueueAbsent(account, queue); } + @Test + void anOrganizationalUnitThatCannotBeResolvedFailsTheOperation() { + // Resolving the targets is part of the operation: a target that fails ends it FAILED rather + // than leave it RUNNING, which would refuse every later operation on the stack set. + String management = "646464646464"; + organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") + .post("/").then().statusCode(200); + String rootId = organizations(management, "ListRoots", "{}") + .post("/").then().statusCode(200) + .extract().jsonPath().getString("Roots[0].Id"); + cloudFormation(management, "ActivateOrganizationsAccess") + .post("/").then().statusCode(200); + + String suffix = UUID.randomUUID().toString().substring(0, 8); + String stackSet = "missing-ou-" + suffix; + cloudFormation(management, "CreateStackSet") + .formParam("StackSetName", stackSet) + .formParam("TemplateBody", queueTemplate("missing-ou-q-" + suffix)) + .formParam("PermissionModel", "SERVICE_MANAGED") + .post("/").then().statusCode(200); + + cloudFormation(management, "CreateStackInstances") + .formParam("StackSetName", stackSet) + .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", "ou-zzzz-zzzzzzzz") + .formParam("Regions.member.1", REGION) + .post("/").then().statusCode(400) + .body(containsString("OrganizationalUnitNotFoundException")); + cloudFormation(management, "ListStackSetOperations") + .formParam("StackSetName", stackSet) + .post("/").then().statusCode(200) + .body(containsString("FAILED")) + .body(not(containsString("RUNNING"))); + + cloudFormation(management, "CreateStackInstances") + .formParam("StackSetName", stackSet) + .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", rootId) + .formParam("Regions.member.1", REGION) + .post("/").then().statusCode(200); + } + @Test void activateOrganizationsAccessRequiresAllFeatures() { String management = "939393939393"; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java index 5d6682f70d..8463b391b2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java @@ -751,6 +751,249 @@ class CloudFormationStackSetsIntegrationTest { assertQueueAbsent(ACCOUNT_C, dependent); } + @Test + void createStackSetWithoutAParameterValueIsRefused() { + // Every instance is deployed with the stack set's parameters, so a declared one the stack + // set has no value for is refused up front, as a stack's CreateStack refuses it. + String setName = "noval-" + UUID.randomUUID().toString().substring(0, 8); + String queue = "noval-q-" + UUID.randomUUID().toString().substring(0, 8); + String template = """ + {"Parameters":{"Suffix":{"Type":"String"}}, + "Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":{"Fn::Sub":"%s-${Suffix}"}}}}} + """.formatted(queue); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", template) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Parameters: [Suffix] must have values")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackSet") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(404) + .body(containsString("StackSetNotFoundException")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", template) + .formParam("Parameters.member.1.ParameterKey", "Suffix") + .formParam("Parameters.member.1.ParameterValue", "b") + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + assertQueueVisible(ACCOUNT_B, queue + "-b"); + } + + @Test + void updateStackSetWithoutAParameterValueChangesNothing() { + // Checked against the template and parameters the update would leave the stack set with, + // before either changes or an operation is recorded. + String setName = "noval-update-" + UUID.randomUUID().toString().substring(0, 8); + String queue = "noval-update-q-" + UUID.randomUUID().toString().substring(0, 8); + String template = """ + {"Parameters":{"Suffix":{"Type":"String"}}, + "Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":{"Fn::Sub":"%s-${Suffix}"}}}}} + """.formatted(queue); + String withExtra = """ + {"Parameters":{"Suffix":{"Type":"String"},"Extra":{"Type":"String"}}, + "Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":{"Fn::Sub":"%s-${Suffix}"}, + "Tags":[{"Key":"extra","Value":{"Ref":"Extra"}}]}}}} + """.formatted(queue); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", template) + .formParam("Parameters.member.1.ParameterKey", "Suffix") + .formParam("Parameters.member.1.ParameterValue", "a") + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + assertQueueVisible(ACCOUNT_B, queue + "-a"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", withExtra) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(400) + .body(containsString("Parameters: [Extra] must have values")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackSet") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(not(containsString("Extra"))); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListStackSetOperations") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(not(containsString("UPDATE"))); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", withExtra) + .formParam("Parameters.member.1.ParameterKey", "Suffix") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .formParam("Parameters.member.2.ParameterKey", "Extra") + .formParam("Parameters.member.2.ParameterValue", "x") + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListStackSetOperations") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("UPDATE")) + .body(not(containsString("FAILED"))); + } + + @Test + void updateStackSetUsePreviousValueKeepsAValueTheStackSetTookFromItsDefault() { + // A stack set keeps only the values it was given, so UsePreviousValue also reads the + // previous template's Default: the instances deployed with it, and an update that drops + // that Default keeps them on it. + String setName = "upv-default-" + UUID.randomUUID().toString().substring(0, 8); + String queue = "upv-default-q-" + UUID.randomUUID().toString().substring(0, 8); + String template = """ + {"Parameters":{"Suffix":{"Type":"String"%s}}, + "Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":{"Fn::Sub":"%s-${Suffix}"}}}}} + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", template.formatted(",\"Default\":\"d1\"", queue)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + assertQueueVisible(ACCOUNT_B, queue + "-d1"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", template.formatted("", queue)) + .formParam("Parameters.member.1.ParameterKey", "Suffix") + .formParam("Parameters.member.1.UsePreviousValue", "true") + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + 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("d1")); + assertQueueVisible(ACCOUNT_B, queue + "-d1"); + } + + @Test + void createStackInstancesThatIsRefusedFailsItsOperation() { + // An instance whose change set is refused fails the operation instead of leaving it + // RUNNING, which would refuse every later operation on the stack set. + String setName = "refused-op-" + UUID.randomUUID().toString().substring(0, 8); + String conditional = "refused-c-" + UUID.randomUUID().toString().substring(0, 8); + String dependent = "refused-d-" + UUID.randomUUID().toString().substring(0, 8); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", conditionalDependentTemplate(ACCOUNT_B, conditional, dependent)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_C) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(400) + .body(containsString("Unresolved resource dependencies")); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListStackSetOperations") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("FAILED")) + .body(not(containsString("RUNNING"))); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + assertQueueVisible(ACCOUNT_B, conditional); + assertQueueVisible(ACCOUNT_B, dependent); + } + @Test void createStackInstancesRejectsInvalidAccountBeforeDeployment() { String setName = "invalid-account-" + UUID.randomUUID().toString().substring(0, 8);