fix(cloudformation): resolve Fn::GetStackOutput as CloudFormation does (#5848)

* fix(cloudformation): resolve Fn::GetStackOutput as CloudFormation does

Fn::GetStackOutput was not implemented, and an intrinsic the template
engine does not know falls through to the node's text, which for an
object is "". A weak cross-stack reference, which aws-cdk-lib synthesizes
as Fn::GetStackOutput, therefore deployed CREATE_COMPLETE with an empty
string wherever the value was used.

The engine now resolves it through a StackOutputResolver that
CloudFormationService answers as DescribeStacks would in the referenced
account and Region, and the YAML parser maps the !GetStackOutput short
form. Every rule follows what CloudFormation does, measured in eu-west-1,
where that departs from the function's reference page: a missing stack
or output fails the resource and the stack rolls back, an output that
cannot be read rolls the stack back once the resources exist, an output
whose Condition is false is never read, a dynamic reference reaches
DescribeStacks unresolved, and the function is refused in Conditions and
inside Fn::ImportValue when the operation is requested, AWS::Include
fragments included. A RoleArn has to name an existing role: Floci runs
no stack operation under an execution role, so, as AssumeRole does with
IAM enforcement off, its trust policy is not evaluated.

* fix(cloudformation): refuse Fn::GetStackOutput in export names and nested stacks as AWS does

Answers the review of #5848, each point measured on CloudFormation in
eu-west-1 on 2026-10-17.

An output's Export.Name holding Fn::GetStackOutput is refused when the
operation is requested, with "Template format error: Output O is
malformed.  The Name field of Export must not depend on any resources,
imported values, or Fn::GetAZs.", so it never reaches execution. A
nested stack's template is checked when the child is created: the Child
resource fails with the template error and the parent rolls back.

A dynamic reference inside an Fn::Sub variable map of the function's
arguments is left as written too: CloudFormation hands it to
DescribeStacks unresolved, which refuses the name. The engine suspends
dynamic references while it resolves the arguments.

An output that cannot be read now logs the stack and the output before
the rollback, and the placement check skips only a template that does
not parse or an AWS::Include that fails, which the operation reports
where it processes them.

* fix(cloudformation): check a Fn::GetStackOutput role's trust and permissions under IAM enforcement

With IAM enforcement on, a RoleArn only had to name an existing role, so a
stack could read another account's outputs through any role there,
whatever the role trusted. GetStackOutputRoleAuthorizer now decides the
role as AssumeRole and AppSyncDataSourceAuthorizer do: its trust policy
has to allow a principal in the consuming account, and its policies,
through IamPolicyEvaluator, have to allow cloudformation:DescribeStacks
on the referenced stack. The refusals carry the messages measured on
CloudFormation: STS's AccessDenied, and DescribeStacks' for the
GetStackOutput session. With enforcement off nothing changes.

Which principal CloudFormation acts as is not known in Floci, which runs
stack operations under no execution role and keeps no caller, so a grant
to any principal of the consuming account is enough: its root, or any
principal of it the policy names, such as the CDK's execution role.
That question is AssumeRolePolicyEvaluator.allowsAnyPrincipalOf, built on
its own decide(), so the trust policy is parsed and evaluated in one
place.

Reuse instead of copies: the tests use EnforcementFixtures.auth, a new
EnforcementFixtures.createRole overload taking the trust policy, and
PartitionCleanup, and the two GetStackOutput tests share their stack and
parameter helpers. The placement checks find the function with
JsonNode.findValues instead of three hand-written walks, and the
resolveOutputValue wrapper of resolve() is gone.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-17 09:09:24 -04:00
1 parent 6604f513c0
commit e12b878b77
14 files changed
+1679 -45

No files matched your search

@@ -0,0 +1,191 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* With IAM enforcement on, the role a {@code Fn::GetStackOutput} names has to trust a principal in
* the consuming account, and its policies have to allow DescribeStacks on the referenced stack. On
* AWS CloudFormation assumes the role as the stack's execution role, or as the caller, and reads in
* a session named {@code GetStackOutput} (measured, eu-west-1, 2026-10-16); Floci keeps neither, so
* a grant to any principal of the consuming account is enough.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class CloudFormationGetStackOutputEnforcementIntegrationTest {
private static final String CONSUMER = "131313131313";
private static final String OWNER = "242424242424";
private static final String OTHER = "353535353535";
private static final String REGION = "us-east-1";
private static final String DESCRIBE_STACKS = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"cloudformation:DescribeStacks","Resource":"*"}]}""";
@TestHTTPResource
URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private final String suffix = Long.toString(System.nanoTime(), 36);
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aRoleTrustingTheConsumingAccount_readsTheOutput() {
String producer = producer("vpc-account");
String roleArn = role("account", allow("{\"AWS\":\"arn:aws:iam::" + CONSUMER + ":root\"}"), DESCRIBE_STACKS);
String consumer = consume("account", producer, roleArn);
assertEquals("CREATE_COMPLETE", awaitConsumer(consumer).status());
parameterValue("account").body("Parameter.Value", equalTo("vpc-account"));
}
/** The CDK's role trusts the consuming account's CloudFormation execution role. */
@Test
void aRoleTrustingARoleOfTheConsumingAccount_readsTheOutput() {
String executionRole = "cdk-exec-" + suffix;
String executionRoleArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), CONSUMER, "/",
executionRole, DESCRIBE_STACKS);
String producer = producer("vpc-cdk");
String roleArn = role("cdk", allow("{\"AWS\":\"" + executionRoleArn + "\"}"), DESCRIBE_STACKS);
String consumer = consume("cdk", producer, roleArn);
assertEquals("CREATE_COMPLETE", awaitConsumer(consumer).status());
parameterValue("cdk").body("Parameter.Value", equalTo("vpc-cdk"));
}
@Test
void aRoleTrustingOnlyAService_isRefused() {
assertCannotBeAssumed("service", allow("{\"Service\":\"lambda.amazonaws.com\"}"));
}
@Test
void aRoleTrustingAnotherAccount_isRefused() {
assertCannotBeAssumed("other", allow("{\"AWS\":\"arn:aws:iam::" + OTHER + ":root\"}"));
}
@Test
void aTrustPolicyDenyingTheConsumingAccount_isRefused() {
String principal = "{\"AWS\":\"arn:aws:iam::" + CONSUMER + ":root\"}";
assertCannotBeAssumed("denied", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":%1$s,"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":%1$s,"Action":"sts:AssumeRole"}]}""".formatted(principal));
}
/** Measured: "because no identity-based policy allows the cloudformation:DescribeStacks action". */
@Test
void aRoleWithoutDescribeStacks_isRefusedByDescribeStacks() {
assertCannotDescribe("no-describe", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""",
"because no identity-based policy allows the cloudformation:DescribeStacks action");
}
@Test
void aRoleDenyingDescribeStacks_isRefusedByDescribeStacks() {
assertCannotDescribe("deny-describe", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"cloudformation:DescribeStacks","Resource":"*"}]}""",
"with an explicit deny in an identity-based policy");
}
private void assertCannotBeAssumed(String base, String trustPolicy) {
String producer = producer("vpc-" + base);
String roleArn = role(base, trustPolicy, DESCRIBE_STACKS);
CfnStackWaits.StackState state = awaitConsumer(consume(base, producer, roleArn));
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("User: arn:aws:iam::" + CONSUMER + ":root is not authorized to"
+ " perform: sts:AssumeRole on resource: " + roleArn + " (Service: AWSSecurityTokenService; Status"
+ " Code: 403; Error Code: AccessDenied; Request ID: "));
}
private void assertCannotDescribe(String base, String policy, String reason) {
String producer = producer("vpc-" + base);
String roleArn = role(base, allow("{\"AWS\":\"arn:aws:iam::" + CONSUMER + ":root\"}"), policy);
CfnStackWaits.StackState state = awaitConsumer(consume(base, producer, roleArn));
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("User: arn:aws:sts::" + OWNER + ":assumed-role/" + name(base)
+ "/GetStackOutput is not authorized to perform: cloudformation:DescribeStacks on resource:"
+ " arn:aws:cloudformation:" + REGION + ":" + OWNER + ":stack/" + producer + "/"));
assertThat(state.reason(), containsString(" " + reason + " (Service: AmazonCloudFormation; Status Code: 403;"
+ " Error Code: AccessDenied; Request ID: "));
}
private String name(String base) {
return "gso-enf-" + base + "-" + suffix;
}
private static String allow(String principal) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":" + principal
+ ",\"Action\":\"sts:AssumeRole\"}]}";
}
private String role(String base, String trustPolicy, String policy) {
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OWNER, "/", name(base), trustPolicy, policy);
}
/** A stack in the owning account whose output VpcId is {@code vpcId}. */
private String producer(String vpcId) {
String producer = name("producer-" + vpcId);
createStack(OWNER, producer, "{\"Outputs\": {\"VpcId\": {\"Value\": \"" + vpcId + "\"}}}");
assertEquals("CREATE_COMPLETE",
CfnStackWaits.awaitTerminal(producer, auth(OWNER, REGION, "cloudformation")).status());
return producer;
}
/** A stack in the consuming account copying the producer's VpcId into a parameter, through the role. */
private String consume(String base, String producer, String roleArn) {
String consumer = name("consumer-" + base);
createStack(CONSUMER, consumer, """
{"Resources": {"Copy": {"Type": "AWS::SSM::Parameter", "Properties": {"Name": "%s", "Type": "String",
"Value": {"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId", "RoleArn": "%s"}}}}}}
""".formatted(parameter(base), producer, roleArn));
return consumer;
}
private static CfnStackWaits.StackState awaitConsumer(String consumer) {
return CfnStackWaits.awaitTerminal(consumer, auth(CONSUMER, REGION, "cloudformation"));
}
private String parameter(String base) {
return "/gso-enf/" + suffix + "/" + base;
}
private void createStack(String account, String stackName, String template) {
GetStackOutputFixtures.createStack(cleanup, account, REGION, stackName, template);
}
private ValidatableResponse parameterValue(String base) {
return GetStackOutputFixtures.parameterValue(CONSUMER, REGION, parameter(base));
}
}
@@ -0,0 +1,546 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@code Fn::GetStackOutput} reads another stack's output, without an export, in the same
* account and Region, another Region, or another account through a role. A stack or an output
* that does not exist fails the deploy; it never resolves to an empty string.
*/
@QuarkusTest
class CloudFormationGetStackOutputIntegrationTest {
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String OTHER_ACCOUNT = "000000000042";
private static final String US_EAST_1 = "us-east-1";
private static final String EU_WEST_1 = "eu-west-1";
private static final String DESCRIBE_STACKS = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"cloudformation:DescribeStacks","Resource":"*"}]}""";
@Inject
S3Service s3Service;
@Inject
SsmService ssmService;
@TestHTTPResource
URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private final String suffix = Long.toString(System.nanoTime(), 36);
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void sameAccountSameRegion_resourcePropertyGetsTheOutput() {
String producer = name("producer");
String consumer = name("consumer");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-0123456789");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("same"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\"}}"));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("same")).body("Parameter.Value", equalTo("vpc-0123456789"));
}
@Test
void yamlShortFormInsideJoin_resolves() {
String producer = name("yaml-producer");
String consumer = name("yaml-consumer");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "subnet-42");
String template = """
Resources:
Copy:
Type: AWS::SSM::Parameter
Properties:
Name: %s
Type: String
Value: !Join
- "-"
- - !GetStackOutput
StackName: %s
OutputName: VpcId
- copy
""".formatted(parameter("yaml"), producer);
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, template);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("yaml")).body("Parameter.Value", equalTo("subnet-42-copy"));
}
@Test
void missingOutput_failsTheDeploy() {
String producer = name("missing-output-producer");
String consumer = name("missing-output");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-1");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("missing-output"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"Nope\"}}"));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("TemplateError: Fn::GetStackOutput references output Nope from stack "
+ producer + ", but this output was not found. The output may have been deleted."));
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("missing-output")).statusCode(400);
}
@Test
void missingStack_failsTheDeploy() {
String missing = name("never-created");
String consumer = name("missing-stack");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("missing-stack"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + missing + "\", \"OutputName\": \"VpcId\"}}"));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("Stack with id " + missing + " does not exist (Service:"
+ " AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: "));
assertThat(state.reason(), endsWith("; Proxy: null)"));
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("missing-stack")).statusCode(400);
}
@Test
void crossRegion_readsTheNamedRegionOnly() {
String producer = name("region-producer");
String consumer = name("region-consumer");
String regionDefault = name("region-default");
createProducer(DEFAULT_ACCOUNT, EU_WEST_1, producer, "vpc-eu");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("region"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\","
+ " \"Region\": \"eu-west-1\"}}"));
createStack(DEFAULT_ACCOUNT, US_EAST_1, regionDefault, consumer(parameter("region-default"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\"}}"));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("region")).body("Parameter.Value", equalTo("vpc-eu"));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(regionDefault).status());
}
@Test
void crossAccount_readsThroughTheRoleAndFailsWithoutIt() {
String reader = name("reader");
String producer = name("account-producer");
String consumer = name("account-consumer");
String noRole = name("account-no-role");
String missingRole = name("account-missing-role");
createRole(OTHER_ACCOUNT, reader);
createProducer(OTHER_ACCOUNT, US_EAST_1, producer, "vpc-other-account");
String roleArn = "arn:aws:iam::" + OTHER_ACCOUNT + ":role/" + reader;
String nobodyArn = "arn:aws:iam::" + OTHER_ACCOUNT + ":role/" + name("nobody");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("account"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\","
+ " \"RoleArn\": \"" + roleArn + "\"}}"));
createStack(DEFAULT_ACCOUNT, US_EAST_1, noRole, consumer(parameter("account-no-role"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\"}}"));
createStack(DEFAULT_ACCOUNT, US_EAST_1, missingRole, consumer(parameter("account-missing-role"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\","
+ " \"RoleArn\": \"" + nobodyArn + "\"}}"));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("account")).body("Parameter.Value", equalTo("vpc-other-account"));
assertThat(CfnStackWaits.awaitTerminal(noRole).reason(),
containsString("Stack with id " + producer + " does not exist"));
CfnStackWaits.StackState missingRoleState = CfnStackWaits.awaitTerminal(missingRole);
assertEquals("ROLLBACK_COMPLETE", missingRoleState.status());
assertThat(missingRoleState.reason(), containsString("is not authorized to perform: sts:AssumeRole on resource: "
+ nobodyArn + " (Service: AWSSecurityTokenService; Status Code: 403;"
+ " Error Code: AccessDenied; Request ID: "));
}
/**
* With IAM enforcement off, as AssumeRole, Floci requires the role to exist and evaluates no
* trust policy: the CDK's shape resolves, as one trusting only a service does.
* {@code CloudFormationGetStackOutputEnforcementIntegrationTest} covers enforcement on.
*/
@Test
void crossAccount_theRolesTrustPolicyIsNotEvaluated() {
String cdkShape = name("cdk-shape");
String lambdaOnly = name("lambda-only");
String producer = name("trust-producer");
createRole(OTHER_ACCOUNT, cdkShape, "{\"AWS\":\"arn:aws:iam::" + DEFAULT_ACCOUNT
+ ":role/cdk-hnb659fds-cfn-exec-role-" + DEFAULT_ACCOUNT + "-us-east-1\"}");
createRole(OTHER_ACCOUNT, lambdaOnly, "{\"Service\":\"lambda.amazonaws.com\"}");
createProducer(OTHER_ACCOUNT, US_EAST_1, producer, "vpc-trust");
for (String role : List.of(cdkShape, lambdaOnly)) {
createStack(DEFAULT_ACCOUNT, US_EAST_1, role + "-consumer", consumer(parameter(role),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + producer + "\", \"OutputName\": \"VpcId\","
+ " \"RoleArn\": \"arn:aws:iam::" + OTHER_ACCOUNT + ":role/" + role + "\"}}"));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(role + "-consumer").status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter(role)).body("Parameter.Value", equalTo("vpc-trust"));
}
}
/**
* Measured (eu-west-1, 2026-10-04): an output that cannot be read fails the create after the
* resources exist, and the stack rolls back, deleting them.
*/
@Test
void anOutputThatCannotBeReadRollsTheStackBack() {
String producer = name("output-producer");
String consumer = name("output-consumer");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-output");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, """
{"Resources": {"Copy": {"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "%s", "Type": "String", "Value": "created"}}},
"Outputs": {"Missing": {"Value": {"Fn::GetStackOutput": {
"StackName": "%s", "OutputName": "Missing"}}}}}
""".formatted(parameter("output-rollback"), producer));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("TemplateError: Fn::GetStackOutput references output Missing"));
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("output-rollback"))
.statusCode(400)
.body(containsString("ParameterNotFound"));
}
/**
* Measured (eu-west-1, 2026-10-04): CloudFormation does not resolve a dynamic reference inside
* Fn::GetStackOutput; the stack name reaches DescribeStacks as written, which refuses it.
*/
@Test
void aDynamicReferenceInTheStackNameIsNotResolved() {
String consumer = name("dynamic-consumer");
String reference = "{{resolve:ssm:" + parameter("producer-name") + "}}";
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("dynamic"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + reference + "\", \"OutputName\": \"VpcId\"}}"));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("1 validation error detected: Value '" + reference + "'"
+ " at 'stackName' failed to satisfy constraint: Member must satisfy regular expression pattern:"
+ " [a-zA-Z][-a-zA-Z0-9]*|arn:[-a-zA-Z0-9:/._+]* (Service: AmazonCloudFormation; Status Code: 400;"
+ " Error Code: ValidationError; Request ID: "));
}
/**
* Measured (eu-west-1, 2026-10-17): nor is one inside an Fn::Sub variable map, although the
* parameter it names holds the producer's name.
*/
@Test
void aDynamicReferenceInAnFnSubVariableMapIsNotResolved() {
String producer = name("sub-producer");
String consumer = name("sub-dynamic");
String producerName = parameter("sub-producer-name");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-sub");
ssmService.putParameter(producerName, producer, "String", null, true, US_EAST_1);
String reference = "{{resolve:ssm:" + producerName + "}}";
try {
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("sub-dynamic"),
"{\"Fn::GetStackOutput\": {\"StackName\": {\"Fn::Sub\": [\"${N}\", {\"N\": \"" + reference
+ "\"}]}, \"OutputName\": \"VpcId\"}}"));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("1 validation error detected: Value '" + reference
+ "' at 'stackName' failed to satisfy constraint"));
} finally {
ssmService.deleteParameter(producerName, US_EAST_1);
}
}
@Test
void crossPartitionRegion_failsTheDeploy() {
String consumer = name("partition");
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, consumer(parameter("partition"),
"{\"Fn::GetStackOutput\": {\"StackName\": \"" + name("producer") + "\", \"OutputName\": \"VpcId\","
+ " \"Region\": \"cn-north-1\"}}"));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(consumer);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("The security token included in the request is invalid (Service:"
+ " AmazonCloudFormation; Status Code: 403; Error Code: InvalidClientTokenId; Request ID: "));
}
@Test
void directOutputsValue_resolves() {
String producer = name("outputs-producer");
String consumer = name("outputs-consumer");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-out");
String template = """
{"Outputs": {"Copied": {"Value":
{"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}}}}
""".formatted(producer);
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, template);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", consumer)
.when().post("/").then()
.statusCode(200)
.body(containsString("<OutputValue>vpc-out</OutputValue>"));
}
@Test
void anywhereInConditions_isRefusedOnCreate() {
String template = """
{"Conditions": {"IsProd": {"Fn::Not": [{"Fn::Equals": [
{"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}, "prod"]}]}},
"Resources": {"Topic": {"Type": "AWS::SNS::Topic", "Condition": "IsProd"}}}
""".formatted(name("producer"));
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name("conditions"))
.formParam("TemplateBody", template)
.when().post("/").then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Template error: Cannot use Fn::GetStackOutput in Conditions."));
}
/**
* Measured (eu-west-1, 2026-10-16): arguments that are not a map, or that lack StackName or
* OutputName, are refused when the stack operation is requested.
*/
@Test
void malformedArguments_areRefusedOnCreate() {
String producer = name("producer");
String[][] cases = {
{"{\"StackName\": \"" + producer + "\"}", "GetStackOutput: OutputName is required"},
{"{\"OutputName\": \"VpcId\"}", "GetStackOutput: StackName is required"},
{"[\"" + producer + "\", \"VpcId\"]", "TemplateError: Fn::GetStackOutput requires a map of named parameters"},
};
for (String[] c : cases) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name("malformed"))
.formParam("TemplateBody", consumer(parameter("malformed"), "{\"Fn::GetStackOutput\": " + c[0] + "}"))
.when().post("/").then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString(c[1]));
}
}
/**
* Measured (eu-west-1, 2026-10-16): an output whose Condition is false is never read, so one
* naming a stack that does not exist leaves the deploy complete, and it is not listed.
*/
@Test
void anOutputWhoseConditionIsFalse_isNotRead() {
String producer = name("gated-producer");
String consumer = name("gated");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-gated");
String template = """
{"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
"Resources": {"Topic": {"Type": "AWS::SNS::Topic"}},
"Outputs": {
"Read": {"Value": {"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}},
"Gated": {"Condition": "Never",
"Value": {"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}}}}
""".formatted(producer, name("missing"));
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, template);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", consumer)
.when().post("/").then()
.statusCode(200)
.body(containsString("<OutputValue>vpc-gated</OutputValue>"))
.body(not(containsString("<OutputKey>Gated</OutputKey>")));
}
/** The placement rules apply to the template as processed, AWS::Include fragments merged. */
@Test
void inConditionsThroughAnInclude_isRefusedOnCreate() {
String bucket = name("include");
s3Service.createBucket(bucket, US_EAST_1);
s3Service.putObject(bucket, "conditions.json", """
{"IsProd": {"Fn::Equals": [
{"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}, "prod"]}}
""".formatted(name("producer")).getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
String template = """
{"Conditions": {"Fn::Transform": {"Name": "AWS::Include",
"Parameters": {"Location": "s3://%s/conditions.json"}}},
"Resources": {"Topic": {"Type": "AWS::SNS::Topic", "Condition": "IsProd"}}}
""".formatted(bucket);
try {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name("include-conditions"))
.formParam("TemplateBody", template)
.when().post("/").then()
.statusCode(400)
.body(containsString("Template error: Cannot use Fn::GetStackOutput in Conditions."));
} finally {
s3Service.deleteObject(bucket, "conditions.json");
s3Service.deleteBucket(bucket);
}
}
/** Measured (eu-west-1, 2026-10-17): an output's export name may not depend on another stack. */
@Test
void inAnExportName_isRefusedOnCreate() {
String template = """
{"Resources": {"Topic": {"Type": "AWS::SNS::Topic"}},
"Outputs": {"Out": {"Value": "x", "Export": {"Name":
{"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}}}}}
""".formatted(name("producer"));
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name("export-name"))
.formParam("TemplateBody", template)
.when().post("/").then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Template format error: Output Out is malformed. The Name field of Export"
+ " must not depend on any resources, imported values, or Fn::GetAZs."));
}
/**
* Measured (eu-west-1, 2026-10-17): a nested stack's template is checked when the child is
* created. The Child resource fails with the template error, and the parent rolls back.
*/
@Test
void inANestedStacksConditions_failsTheChildResource() {
String bucket = name("nested");
String parent = name("nested-parent");
s3Service.createBucket(bucket, US_EAST_1);
s3Service.putObject(bucket, "child.json", """
{"Conditions": {"C": {"Fn::Equals": [
{"Fn::GetStackOutput": {"StackName": "%s", "OutputName": "VpcId"}}, "x"]}},
"Resources": {"Topic": {"Type": "AWS::SNS::Topic", "Condition": "C"}}}
""".formatted(name("producer")).getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
try {
createStack(DEFAULT_ACCOUNT, US_EAST_1, parent, """
{"Resources": {"Child": {"Type": "AWS::CloudFormation::Stack",
"Properties": {"TemplateURL": "http://localhost/%s/child.json"}}}}
""".formatted(bucket));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(parent);
assertEquals("ROLLBACK_COMPLETE", state.status());
assertThat(state.reason(), containsString("Template error: Cannot use Fn::GetStackOutput in Conditions."));
} finally {
s3Service.deleteObject(bucket, "child.json");
s3Service.deleteBucket(bucket);
}
}
@Test
void insideImportValue_isRefusedOnCreate() {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", name("import"))
.formParam("TemplateBody", consumer(parameter("import"), "{\"Fn::ImportValue\": {\"Fn::GetStackOutput\":"
+ " {\"StackName\": \"" + name("producer") + "\", \"OutputName\": \"VpcId\"}}}"))
.when().post("/").then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Template error: the attribute in Fn::ImportValue must not depend on any"
+ " resources, imported values, or Fn::GetAZs"));
}
/**
* What AWS resolves beyond its documentation: a resource's Ref in a parameter, an Fn::Sub
* variable map, Fn::Base64, and a key the function does not define, which is ignored.
*/
@Test
void parametersMayNameAResource_andEveryPositionResolves() {
String producer = name("ref-producer");
String consumer = name("ref-consumer");
createProducer(DEFAULT_ACCOUNT, US_EAST_1, producer, "vpc-ref");
String template = """
{"Resources": {
"Name": {"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "%1$s", "Type": "String", "Value": "unused"}},
"ByRef": {"Type": "AWS::SSM::Parameter", "Properties": {"Name": "%2$s", "Type": "String",
"Value": {"Fn::GetStackOutput": {"StackName": {"Ref": "Name"}, "OutputName": "VpcId", "Extra": 1}}}},
"BySub": {"Type": "AWS::SSM::Parameter", "Properties": {"Name": "%3$s", "Type": "String",
"Value": {"Fn::Sub": ["x-${V}", {"V": {"Fn::GetStackOutput":
{"StackName": "%1$s", "OutputName": "VpcId"}}}]}}},
"ByBase64": {"Type": "AWS::SSM::Parameter", "Properties": {"Name": "%4$s", "Type": "String",
"Value": {"Fn::Base64": {"Fn::GetStackOutput":
{"StackName": "%1$s", "OutputName": "VpcId"}}}}}}}
""".formatted(producer, parameter("by-ref"), parameter("by-sub"), parameter("by-base64"));
createStack(DEFAULT_ACCOUNT, US_EAST_1, consumer, template);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(consumer).status());
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("by-ref")).body("Parameter.Value", equalTo("vpc-ref"));
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("by-sub")).body("Parameter.Value", equalTo("x-vpc-ref"));
parameterValue(DEFAULT_ACCOUNT, US_EAST_1, parameter("by-base64")).body("Parameter.Value", equalTo("dnBjLXJlZg=="));
}
/** A name unique to this run, so a rerun in the same JVM never meets a stack of an earlier one. */
private String name(String base) {
return "gso-" + base + "-" + suffix;
}
private String parameter(String base) {
return "/gso/" + suffix + "/" + base;
}
private static String consumer(String parameterName, String value) {
return """
{"Resources": {"Copy": {"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "%s", "Type": "String", "Value": %s}}}}
""".formatted(parameterName, value);
}
private void createProducer(String account, String region, String stackName, String vpcId) {
createStack(account, region, stackName,
"{\"Outputs\": {\"VpcId\": {\"Value\": \"" + vpcId + "\"}}}");
assertEquals("CREATE_COMPLETE",
CfnStackWaits.awaitTerminal(stackName, auth(account, region, "cloudformation")).status());
}
private void createStack(String account, String region, String stackName, String template) {
GetStackOutputFixtures.createStack(cleanup, account, region, stackName, template);
}
private void createRole(String account, String roleName) {
createRole(account, roleName, "{\"AWS\":\"arn:aws:iam::" + DEFAULT_ACCOUNT + ":root\"}");
}
/** A role in {@code account} whose trust policy allows {@code principal}, a Principal element's value. */
private void createRole(String account, String roleName, String principal) {
EnforcementFixtures.createRole(cleanup, baseUri.getPort(), account, "/", roleName,
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":" + principal
+ ",\"Action\":\"sts:AssumeRole\"}]}", DESCRIBE_STACKS);
}
private static ValidatableResponse parameterValue(String account, String region, String name) {
return GetStackOutputFixtures.parameterValue(account, region, name);
}
}
@@ -84,6 +84,7 @@ class CloudFormationServiceRollbackTest {
provisioner,
mock(S3Service.class),
mock(SsmService.class),
mock(GetStackOutputRoleAuthorizer.class),
mock(CfnDynamicReferences.class),
new ObjectMapper(),
config,
@@ -462,8 +463,8 @@ class CloudFormationServiceRollbackTest {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
CloudFormationService deleteService = new CloudFormationService(cleanupDispatcher, mock(S3Service.class),
mock(SsmService.class), mock(CfnDynamicReferences.class), new ObjectMapper(), config,
mock(RegionResolver.class), Clock.systemUTC(), new InMemoryStorageFactory());
mock(SsmService.class), mock(GetStackOutputRoleAuthorizer.class), mock(CfnDynamicReferences.class), new ObjectMapper(),
config, mock(RegionResolver.class), Clock.systemUTC(), new InMemoryStorageFactory());
assertThrows(IllegalStateException.class, () -> deleteService.deleteStackResources(stack, REGION, ACCOUNT));
assertEquals("DELETE_FAILED", stack.getStatus());
@@ -796,8 +797,8 @@ class CloudFormationServiceRollbackTest {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
return new CloudFormationService(provisioner, mock(S3Service.class), mock(SsmService.class),
mock(CfnDynamicReferences.class), new ObjectMapper(), config, regionResolver, clock,
new InMemoryStorageFactory());
mock(GetStackOutputRoleAuthorizer.class), mock(CfnDynamicReferences.class), new ObjectMapper(), config,
regionResolver, clock, new InMemoryStorageFactory());
}
/** The stack as {@code PersistentStorage} writes it and reads it back. */
@@ -0,0 +1,263 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CloudFormationTemplateEngineGetStackOutputTest {
private final ObjectMapper mapper = new ObjectMapper();
private final List<List<String>> lookups = new ArrayList<>();
private CloudFormationTemplateEngine engine() {
return engine(Map.of("Env", "prod"), Map.of("Enabled", true));
}
private CloudFormationTemplateEngine engine(Map<String, String> parameters, Map<String, Boolean> conditions) {
return new CloudFormationTemplateEngine("111111111111", "us-east-1", "consumer", "stack/id",
parameters, Map.of("Bucket", "bucket-1"), Map.of(), conditions, Map.of(), mapper,
name -> "exported-" + name, null, this::lookup);
}
private String lookup(String stackName, String outputName, String region, String roleArn) {
lookups.add(Arrays.asList(stackName, outputName, region, roleArn));
if ("Missing".equals(stackName)) {
throw new AwsException("ValidationError", "Stack with id Missing does not exist", 400);
}
return stackName + "/" + outputName + "@" + region;
}
private JsonNode json(String s) {
try {
return mapper.readTree(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private AwsException failure(String template) {
return assertThrows(AwsException.class, () -> engine().resolve(json(template)));
}
@Test
void sameAccountSameRegion_readsTheOutputWithTheStacksRegion() {
assertEquals("Producer/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId"}}
""")));
assertEquals(List.of(Arrays.asList("Producer", "VpcId", "us-east-1", null)), lookups);
}
/**
* CloudFormation hands the parameters to the lookup as resolved, whitespace included: a stack
* name with spaces then fails DescribeStacks' name constraint, it is not read as another name.
*/
@Test
void parameterValues_reachTheLookupUntrimmed() {
engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": " Producer ", "OutputName": " VpcId"}}
"""));
assertEquals(List.of(Arrays.asList(" Producer ", " VpcId", "us-east-1", null)), lookups);
}
@Test
void resolveNode_returnsTheOutputAsText() {
assertEquals(TextNode.valueOf("Producer/VpcId@us-east-1"), engine().resolveNode(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId"}}
""")));
}
@Test
void crossRegion_readsTheNamedRegion() {
assertEquals("Producer/VpcId@us-west-2", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId", "Region": "us-west-2"}}
""")));
}
@Test
void crossAccount_passesTheRole() {
engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId",
"RoleArn": "arn:aws:iam::222222222222:role/GetStackOutputRole", "Region": "us-west-2"}}
"""));
assertEquals(List.of(List.of("Producer", "VpcId", "us-west-2",
"arn:aws:iam::222222222222:role/GetStackOutputRole")), lookups);
}
@Test
void supportedPositions_joinIfAndSelect() {
assertEquals("Producer/A@us-east-1-suffix", engine().resolve(json("""
{"Fn::Join": ["-", [{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "A"}}, "suffix"]]}
""")));
assertEquals("Producer/B@us-east-1", engine().resolve(json("""
{"Fn::If": ["Enabled", {"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "B"}}, "off"]}
""")));
assertEquals("Producer/C@us-east-1", engine().resolve(json("""
{"Fn::Select": [1, ["x", {"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "C"}}]]}
""")));
}
@Test
void parameterValues_acceptTheDocumentedFunctions() {
assertEquals("prod-net/Vpc@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {
"StackName": {"Fn::Join": ["-", [{"Ref": "Env"}, "net"]]},
"OutputName": {"Fn::Sub": "Vpc"},
"Region": {"Fn::If": ["Enabled", {"Ref": "AWS::Region"}, "us-west-2"]}}}
""")));
assertEquals("prod-us-east-1/Vpc@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": {"Fn::Sub": "${Env}-${AWS::Region}"}, "OutputName": "Vpc"}}
""")));
}
@Test
void missingStack_failsInsteadOfResolvingToEmpty() {
AwsException e = failure("""
{"Fn::GetStackOutput": {"StackName": "Missing", "OutputName": "VpcId"}}
""");
assertEquals("ValidationError", e.getErrorCode());
assertThat(e.getMessage(), containsString("does not exist"));
}
@Test
void requiredParameters_areValidated() {
assertEquals("GetStackOutput: StackName is required", failure("""
{"Fn::GetStackOutput": {"OutputName": "VpcId"}}
""").getMessage());
assertEquals("GetStackOutput: OutputName is required", failure("""
{"Fn::GetStackOutput": {"StackName": "Producer"}}
""").getMessage());
assertEquals("TemplateError: Fn::GetStackOutput requires a map of named parameters", failure("""
{"Fn::GetStackOutput": ["Producer", "VpcId"]}
""").getMessage());
assertTrue(lookups.isEmpty());
}
@Test
void aKeyTheFunctionDoesNotDefine_isIgnored() {
assertEquals("Producer/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId", "Account": "2"}}
""")));
}
/** AWS resolves any function in a parameter, a resource's Ref and an import included. */
@Test
void parameterValues_resolveWhateverTheyName() {
assertEquals("bucket-1/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": {"Ref": "Bucket"}, "OutputName": "VpcId"}}
""")));
assertEquals("bucket-1/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": {"Fn::Sub": "${Bucket}"}, "OutputName": "VpcId"}}
""")));
assertEquals("exported-Shared/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": {"Fn::ImportValue": "Shared"}, "OutputName": "VpcId"}}
""")));
assertEquals("Other/Name@us-east-1/VpcId@us-east-1", engine().resolve(json("""
{"Fn::GetStackOutput": {"StackName": {"Fn::GetStackOutput": {"StackName": "Other", "OutputName": "Name"}},
"OutputName": "VpcId"}}
""")));
}
@Test
void invalidRegion_isATemplateError() {
AwsException e = failure("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId", "Region": "us-nowhere-9"}}
""");
assertEquals("ValidationError", e.getErrorCode());
assertEquals("TemplateError: Region us-nowhere-9 in Fn::GetStackOutput is not a valid AWS region.",
e.getMessage());
assertTrue(lookups.isEmpty());
}
/** A Region of another partition fails the way AWS's cross-partition call does. */
@Test
void anotherPartitionsRegion_failsWithAnInvalidToken() {
AwsException e = failure("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId", "Region": "cn-north-1"}}
""");
assertEquals("InvalidClientTokenId", e.getErrorCode());
assertThat(e.getMessage(), containsString("The security token included in the request is invalid (Service:"
+ " AmazonCloudFormation; Status Code: 403; Error Code: InvalidClientTokenId; Request ID: "));
assertTrue(lookups.isEmpty());
}
@Test
void aRoleArnThatIsNoArn_isATemplateError() {
AwsException e = failure("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId", "RoleArn": "not-an-arn"}}
""");
assertEquals("ValidationError", e.getErrorCode());
assertEquals("TemplateError: Invalid RoleArn parameter not-an-arn in Fn::GetStackOutput", e.getMessage());
}
/** Any ARN goes to the role assumption, which is what refuses a user, an S3 or an aws-cn ARN. */
@ParameterizedTest
@ValueSource(strings = {"arn:aws:iam::222222222222:user/Reader", "arn:aws:s3:::bucket",
"arn:aws-cn:iam::222222222222:role/Reader"})
void anyArn_reachesTheRoleAssumption(String roleArn) {
engine().resolve(json("{\"Fn::GetStackOutput\": {\"StackName\": \"Producer\","
+ " \"OutputName\": \"VpcId\", \"RoleArn\": \"" + roleArn + "\"}}"));
assertEquals(List.of(Arrays.asList("Producer", "VpcId", "us-east-1", roleArn)), lookups);
}
@ParameterizedTest
@ValueSource(strings = {
"{\"Fn::Base64\": {\"Fn::GetStackOutput\": {\"StackName\": \"P\", \"OutputName\": \"O\"}}}",
"{\"Fn::Sub\": [\"${V}\", {\"V\": {\"Fn::GetStackOutput\": {\"StackName\": \"P\", \"OutputName\": \"O\"}}}]}"
})
void positionsTheDocumentationListsAsUnsupported_resolve(String template) {
engine().resolve(json(template));
assertEquals(List.of(Arrays.asList("P", "O", "us-east-1", null)), lookups);
}
/**
* Measured (eu-west-1, 2026-10-17): a dynamic reference in an argument is handed on as written,
* one inside an Fn::Sub variable map included, while the same Fn::Sub elsewhere resolves it.
*/
@Test
void dynamicReferencesInTheArguments_areLeftAsWritten() {
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine("111111111111", "us-east-1",
"consumer", "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
name -> null, value -> value.replace("{{resolve:ssm:/name}}", "Producer"), this::lookup);
String sub = "{\"Fn::Sub\": [\"${N}\", {\"N\": \"{{resolve:ssm:/name}}\"}]}";
engine.resolve(json("{\"Fn::GetStackOutput\": {\"StackName\": " + sub + ", \"OutputName\": \"VpcId\"}}"));
assertEquals(List.of(Arrays.asList("{{resolve:ssm:/name}}", "VpcId", "us-east-1", null)), lookups);
assertEquals("Producer", engine.resolve(json(sub)));
}
@Test
void withoutAResolver_theReferenceFails() {
CloudFormationTemplateEngine standalone = CloudFormationTemplateEngine.standalone("111111111111",
"us-east-1", "cloudcontrol", mapper, null);
assertThrows(AwsException.class, () -> standalone.resolve(json("""
{"Fn::GetStackOutput": {"StackName": "Producer", "OutputName": "VpcId"}}
""")));
}
@Test
void containsGetStackOutput_findsNestedReferences() {
assertTrue(CloudFormationTemplateEngine.containsGetStackOutput(json("""
[{"Fn::Join": ["", [{"Fn::GetStackOutput": {"StackName": "P", "OutputName": "O"}}]]}, "x"]
""")));
assertFalse(CloudFormationTemplateEngine.containsGetStackOutput(json("""
[{"Ref": "Env"}, "x"]
""")));
}
}
@@ -43,4 +43,23 @@ class CloudFormationYamlParserTest {
""");
assertEquals(longForm, shorthand);
}
@Test
void getStackOutputShorthandExpandsToFnGetStackOutput() throws Exception {
JsonNode shorthand = parse("""
SubnetId: !GetStackOutput
StackName: Producer
OutputName: SubnetId
Region: us-west-2
""");
JsonNode longForm = parse("""
SubnetId:
Fn::GetStackOutput:
StackName: Producer
OutputName: SubnetId
Region: us-west-2
""");
assertEquals(longForm, shorthand);
assertEquals("Producer", shorthand.get("SubnetId").get("Fn::GetStackOutput").get("StackName").asText());
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.restassured.response.ValidatableResponse;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
/**
* What the {@code Fn::GetStackOutput} integration tests, with IAM enforcement off and on, do to
* stacks and parameters, each request signed as an account's root.
*/
final class GetStackOutputFixtures {
private GetStackOutputFixtures() {
}
/** Creates {@code stackName} in {@code account} and {@code region}, its deletion registered first. */
static void createStack(PartitionCleanup cleanup, String account, String region, String stackName,
String template) {
String authorization = auth(account, region, "cloudformation");
cleanup.register(() -> given().header("Authorization", authorization)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/"));
given().header("Authorization", authorization)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
}
/** SSM's GetParameter for {@code name}, as the root of {@code account}. */
static ValidatableResponse parameterValue(String account, String region, String name) {
return given().header("Authorization", auth(account, region, "ssm"))
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType("application/x-amz-json-1.1")
.body("{\"Name\": \"" + name + "\"}")
.when().post("/").then();
}
}
@@ -65,6 +65,45 @@ class AssumeRolePolicyEvaluatorTest {
trust("{\"Service\":\"redshift.AMAZONAWS.COM.CN\"}"), "redshift.amazonaws.com"));
}
@Test
void anyPrincipalOfTheAccount_throughItsRootOrAPrincipalItNames() {
assertTrue(evaluator.allowsAnyPrincipalOf(trust("{\"AWS\":\"arn:aws:iam::111111111111:root\"}"),
CALLER_ACCOUNT, "aws"));
assertTrue(evaluator.allowsAnyPrincipalOf(trust("{\"AWS\":\"111111111111\"}"), CALLER_ACCOUNT, "aws"));
assertTrue(evaluator.allowsAnyPrincipalOf(trust("\"*\""), CALLER_ACCOUNT, "aws"));
assertTrue(evaluator.allowsAnyPrincipalOf(
trust("{\"AWS\":[\"arn:aws:iam::999999999999:root\",\"arn:aws:iam::111111111111:role/cfn-exec\"]}"),
CALLER_ACCOUNT, "aws"));
assertTrue(evaluator.allowsAnyPrincipalOf(trust("{\"AWS\":\"arn:aws:iam::111111111111:user/alice\"}"),
CALLER_ACCOUNT, "aws"));
}
@Test
void anyPrincipalOfTheAccount_notAnotherAccountNorAService() {
assertFalse(evaluator.allowsAnyPrincipalOf(trust("{\"AWS\":\"arn:aws:iam::999999999999:root\"}"),
CALLER_ACCOUNT, "aws"));
assertFalse(evaluator.allowsAnyPrincipalOf(trust("{\"AWS\":\"arn:aws:iam::999999999999:role/cfn-exec\"}"),
CALLER_ACCOUNT, "aws"));
assertFalse(evaluator.allowsAnyPrincipalOf(trust("{\"Service\":\"lambda.amazonaws.com\"}"),
CALLER_ACCOUNT, "aws"));
assertFalse(evaluator.allowsAnyPrincipalOf(null, CALLER_ACCOUNT, "aws"));
}
/** A Deny on the account reaches each of its principals; a condition no key here answers grants nothing. */
@Test
void anyPrincipalOfTheAccount_honoursDenyAndConditions() {
assertFalse(evaluator.allowsAnyPrincipalOf("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:role/cfn-exec"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole"}]}
""", CALLER_ACCOUNT, "aws"));
assertFalse(evaluator.allowsAnyPrincipalOf("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"sts:ExternalId":"secret"}}}]}
""", CALLER_ACCOUNT, "aws"));
}
@Test
void allowsAccountRootPrincipal() {
assertTrue(evaluator.allows(
@@ -113,13 +113,22 @@ public final class EnforcementFixtures {
*/
public static String createRole(PartitionCleanup cleanup, int port, String account, String path,
String roleName, String policy) {
return createRole(cleanup, port, account, path, roleName, """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
.formatted(account), policy);
}
/**
* Creates a role as {@link #createRole(PartitionCleanup, int, String, String, String, String)}
* does, trusting whatever {@code trustPolicy} allows instead of its own account's root.
*/
public static String createRole(PartitionCleanup cleanup, int port, String account, String path,
String roleName, String trustPolicy, String policy) {
String authorization = auth(account, "iam");
cleanup.register(() -> removeRole(port, authorization, roleName));
iam(port, authorization, "CreateRole", "RoleName", roleName, "Path", path,
"AssumeRolePolicyDocument", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
.formatted(account)).statusCode(200);
"AssumeRolePolicyDocument", trustPolicy).statusCode(200);
iam(port, authorization, "PutRolePolicy", "RoleName", roleName, "PolicyName", "p",
"PolicyDocument", policy).statusCode(200);
return "arn:aws:iam::" + account + ":role" + path + roleName;