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

@@ -98,7 +98,8 @@ public class CloudFormationService implements ResourceProvider {
+ " to review their current state before your next update.";
private static final String FORCE_WITH_SKIPS = "ForceRollback and ResourcesToSkip are mutually exclusive";
private static final String CONTINUE_STACK_MISSING = "Stack: %s does not exist";
private static final Pattern CONTINUE_STACK_NAME =
/** The StackName pattern ContinueUpdateRollback and DescribeStacks validate a name against. */
private static final Pattern STACK_NAME =
Pattern.compile("[a-zA-Z][-a-zA-Z0-9]*|arn:[-a-zA-Z0-9:/._+]*");
private static final Pattern RESOURCE_TO_SKIP =
Pattern.compile("[a-zA-Z0-9]+|[a-zA-Z][-a-zA-Z0-9]*\\.[a-zA-Z0-9]+");
@@ -119,6 +120,7 @@ public class CloudFormationService implements ResourceProvider {
private final CfnResourceDispatcher dispatcher;
private final S3Service s3Service;
private final SsmService ssmService;
private final GetStackOutputRoleAuthorizer stackOutputRoles;
private final CfnDynamicReferences dynamicReferences;
private final ObjectMapper objectMapper;
private final EmulatorConfig config;
@@ -136,13 +138,15 @@ public class CloudFormationService implements ResourceProvider {
@Inject
public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service,
SsmService ssmService, CfnDynamicReferences dynamicReferences,
SsmService ssmService, GetStackOutputRoleAuthorizer stackOutputRoles,
CfnDynamicReferences dynamicReferences,
ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver, Clock clock,
StorageFactory storageFactory) {
this.dispatcher = dispatcher;
this.s3Service = s3Service;
this.ssmService = ssmService;
this.stackOutputRoles = stackOutputRoles;
this.dynamicReferences = dynamicReferences;
this.objectMapper = objectMapper;
this.config = config;
@@ -436,6 +440,7 @@ 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.
validateGetStackOutputPlacement(resolvedTemplate);
validateResourceDependencies(resolvedTemplate, parameters, preflightStackName, preflightStackId,
region, accountId);
@@ -1410,9 +1415,9 @@ public class CloudFormationService implements ResourceProvider {
violations.add("Value '' at 'stackName' failed to satisfy constraint:"
+ " Member must have length greater than or equal to 1");
}
if (!CONTINUE_STACK_NAME.matcher(stackNameOrArn).matches()) {
if (!STACK_NAME.matcher(stackNameOrArn).matches()) {
violations.add("Value '" + stackNameOrArn + "' at 'stackName' failed to satisfy constraint:"
+ " Member must satisfy regular expression pattern: " + CONTINUE_STACK_NAME.pattern());
+ " Member must satisfy regular expression pattern: " + STACK_NAME.pattern());
}
}
if (resourcesToSkip.stream().anyMatch(skip -> !RESOURCE_TO_SKIP.matcher(skip).matches())) {
@@ -2001,7 +2006,9 @@ public class CloudFormationService implements ResourceProvider {
accountId, region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(accountExportKey(accountId, exportKey(region, name))),
value -> dynamicReferences.resolveDynamicReferences(value, region, false));
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
(name, output, outputRegion, roleArn) ->
resolveStackOutput(accountId, name, output, outputRegion, roleArn));
StackResource resource = stack.getResources().get(logicalId);
StackResource previousResource = resource;
@@ -2167,7 +2174,9 @@ public class CloudFormationService implements ResourceProvider {
accountId, region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(accountExportKey(accountId, exportKey(region, name))),
value -> dynamicReferences.resolveDynamicReferences(value, region, false));
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
(name, output, outputRegion, roleArn) ->
resolveStackOutput(accountId, name, output, outputRegion, roleArn));
// Resolve outputs before mutating stack/global export state, so failed updates do not
// leave stale or partially registered exports behind.
@@ -2175,23 +2184,46 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> newOutputs = new LinkedHashMap<>();
Map<String, String> newExports = new LinkedHashMap<>();
Map<String, String> newOutputExportNames = new LinkedHashMap<>();
JsonNode outputs = template.path("Outputs");
if (outputs.isObject()) {
outputs.fields().forEachRemaining(e -> {
JsonNode outputDef = e.getValue();
String value = finalEngine.resolve(outputDef.path("Value"));
newOutputs.put(e.getKey(), value);
// Register exports
JsonNode exportNode = outputDef.path("Export").path("Name");
if (!exportNode.isMissingNode()) {
String exportName = finalEngine.resolve(exportNode);
validateExportNameAvailable(region, exportName, oldExports, newExports);
newExports.put(exportName, value);
newOutputExportNames.put(e.getKey(), exportName);
}
});
// An output whose Condition is false is left out unresolved, as on AWS: DescribeStacks
// does not list it, and what it reads is never read (measured, eu-west-1, 2026-10-16).
Map<String, JsonNode> outputs = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> output : template.path("Outputs").properties()) {
String condition = output.getValue().path("Condition").asText(null);
if (condition == null || conditions.getOrDefault(condition, false)) {
outputs.put(output.getKey(), output.getValue());
}
}
Map<String, String> outputValues = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> output : outputs.entrySet()) {
try {
outputValues.put(output.getKey(), finalEngine.resolve(output.getValue().path("Value")));
} catch (AwsException e) {
if (!CloudFormationTemplateEngine.containsGetStackOutput(output.getValue())) {
throw e;
}
// An output whose Fn::GetStackOutput cannot be read fails the operation once the
// resources exist, and the stack rolls back as for a resource that failed
// (measured: a create deletes them and ends ROLLBACK_COMPLETE).
LOG.warnv("Stack {0} output {1} failed: {2}", stack.getStackName(), output.getKey(),
e.getMessage());
rollbackFailedExecution(stack, region, isCreate, e.getMessage(), previousState,
attemptedResourceIds);
return;
}
}
outputs.forEach((key, outputDef) -> {
String value = outputValues.get(key);
newOutputs.put(key, value);
// Register exports
JsonNode exportNode = outputDef.path("Export").path("Name");
if (!exportNode.isMissingNode()) {
String exportName = finalEngine.resolve(exportNode);
validateExportNameAvailable(region, exportName, oldExports, newExports);
newExports.put(exportName, value);
newOutputExportNames.put(key, exportName);
}
});
removeStackExports(stack, region);
stack.replaceOutputs(newOutputs);
@@ -2329,18 +2361,30 @@ public class CloudFormationService implements ResourceProvider {
StackResource failedResource,
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds) {
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(failedResource.getStatusReason());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", failStatus, failedResource.getStatusReason());
LOG.warnv("Stack {0} resource {1} failed: {2}", stack.getStackName(),
failedResource.getLogicalId(), failedResource.getStatusReason());
rollbackFailedExecution(stack, region, isCreate, failedResource.getStatusReason(), previousState,
attemptedResourceIds);
}
/** As above, for a failure that is not one resource's: the reason is the stack's. */
private void rollbackFailedExecution(
Stack stack,
String region,
boolean isCreate,
String reason,
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds) {
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(reason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", failStatus, reason);
if (isCreate) {
stack.setStatus("ROLLBACK_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", failedResource.getStatusReason());
"AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", reason);
List<String> rollbackFailures = rollbackCreatedResources(stack, region);
stack.setLastUpdatedTime(now());
if (rollbackFailures.isEmpty()) {
@@ -2349,18 +2393,18 @@ public class CloudFormationService implements ResourceProvider {
"AWS::CloudFormation::Stack", "ROLLBACK_COMPLETE", null);
LOG.infov("Stack {0} rolled back to a clean slate (ROLLBACK_COMPLETE)", stack.getStackName());
} else {
String reason = "The following resource(s) failed to roll back: ["
String rollbackReason = "The following resource(s) failed to roll back: ["
+ String.join(", ", rollbackFailures) + "].";
stack.setStatus("ROLLBACK_FAILED");
stack.setStatusReason(reason);
stack.setStatusReason(rollbackReason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_FAILED", reason);
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), reason);
"AWS::CloudFormation::Stack", "ROLLBACK_FAILED", rollbackReason);
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), rollbackReason);
}
} else {
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds,
failedResource.getStatusReason());
reason);
return;
}
persistStack(stack);
@@ -3631,9 +3675,12 @@ public class CloudFormationService implements ResourceProvider {
});
}
// 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.
// CreateStack or UpdateStack would, before the child is created or changed: a parameter
// without a value, or a Fn::GetStackOutput where the child's template may not hold one
// (measured: the Child resource fails with the template error, and the parent rolls back).
try {
requireParameterValues(childTemplate, childParams);
validateGetStackOutputPlacement(childTemplate);
} catch (AwsException e) {
resource.setStatus("CREATE_FAILED");
resource.setStatusReason(e.getMessage());
@@ -3848,6 +3895,114 @@ public class CloudFormationService implements ResourceProvider {
return changeSet;
}
/**
* Reads the output a {@code Fn::GetStackOutput} names, as DescribeStacks does in the
* referenced account and Region: the consuming stack's account, or the account of
* {@code roleArn}, a role CloudFormation has to be able to assume, which
* {@link GetStackOutputRoleAuthorizer} decides. The failures carry the messages AWS reports for
* them: STS's or DescribeStacks' AccessDenied for the role, DescribeStacks' ValidationError for a
* missing stack, and a template error for a missing output.
*/
private String resolveStackOutput(String accountId, String stackName, String outputName,
String region, String roleArn) {
String partition = AwsRegions.partitionFor(region);
String ownerAccount = roleArn == null ? accountId : stackOutputRoles.assume(roleArn, accountId, partition);
// CloudFormation hands the stack name to DescribeStacks as written, a dynamic reference
// included (it resolves none inside Fn::GetStackOutput), and DescribeStacks validates it.
if (!STACK_NAME.matcher(stackName).matches()) {
throw new AwsException("ValidationError", CloudFormationTemplateEngine.sdkErrorMessage(
"1 validation error detected: Value '" + stackName + "' at 'stackName' failed to satisfy"
+ " constraint: Member must satisfy regular expression pattern: "
+ STACK_NAME.pattern(),
"AmazonCloudFormation", 400, "ValidationError"), 400);
}
Stack referenced = resolveStack(stackName, region, ownerAccount);
if (referenced == null) {
throw new AwsException("ValidationError", CloudFormationTemplateEngine.sdkErrorMessage(
"Stack with id " + stackName + " does not exist", "AmazonCloudFormation", 400,
"ValidationError"), 400);
}
if (roleArn != null) {
stackOutputRoles.requireDescribeStacks(roleArn, referenced.getStackId(), partition);
}
String value = referenced.outputsSnapshot().get(outputName);
if (value == null) {
throw new AwsException("ValidationError", "TemplateError: Fn::GetStackOutput references output "
+ outputName + " from stack " + stackName
+ ", but this output was not found. The output may have been deleted.", 400);
}
return value;
}
/**
* The places AWS refuses {@code Fn::GetStackOutput} when the stack operation is requested,
* before anything runs (measured, eu-west-1, 2026-10-04 and 2026-10-17): anywhere in the
* Conditions section, inside an {@code Fn::ImportValue}, and in an output's
* {@code Export.Name}, neither of which may depend on another stack. A nested stack's template
* is checked when the child is created, and the child's resource fails with the same message.
*/
private void validateGetStackOutputPlacement(String templateBody) {
JsonNode parsed;
try {
parsed = parseTemplate(templateBody);
} catch (Exception e) {
// As validateResourceDependencies: a template that does not parse fails where it is
// processed, with the parser's error.
LOG.debugv("Skipping Fn::GetStackOutput placement validation; template did not parse: {0}",
e.getMessage());
return;
}
JsonNode template;
try {
// The rules hold for the template as processed: an AWS::Include fragment can carry it.
template = awsIncludeProcessor.mergeIncludes(parsed);
} catch (AwsException e) {
// A fragment that cannot be read fails the operation as the transform does, where the
// includes are processed; the request itself is not refused for it on AWS.
LOG.debugv("Skipping Fn::GetStackOutput placement validation; an AWS::Include failed: {0}",
e.getMessage());
return;
}
if (CloudFormationTemplateEngine.containsGetStackOutput(template.path("Conditions"))) {
throw new AwsException("ValidationError",
"Template error: Cannot use Fn::GetStackOutput in Conditions.", 400);
}
if (template.findValues("Fn::ImportValue").stream()
.anyMatch(CloudFormationTemplateEngine::containsGetStackOutput)) {
throw new AwsException("ValidationError", "Template error: the attribute in Fn::ImportValue must not"
+ " depend on any resources, imported values, or Fn::GetAZs", 400);
}
for (Map.Entry<String, JsonNode> output : template.path("Outputs").properties()) {
if (CloudFormationTemplateEngine.containsGetStackOutput(output.getValue().path("Export").path("Name"))) {
throw new AwsException("ValidationError", "Template format error: Output " + output.getKey()
+ " is malformed. The Name field of Export must not depend on any resources, imported"
+ " values, or Fn::GetAZs.", 400);
}
}
requireGetStackOutputArguments(template);
}
/**
* Refuses a {@code Fn::GetStackOutput} without the map of parameters it takes, or without its
* StackName or OutputName, when the stack operation is requested, with the messages AWS gives
* (measured, eu-west-1, 2026-10-16). A value of the wrong type is DescribeStacks' to refuse.
*/
private static void requireGetStackOutputArguments(JsonNode template) {
for (JsonNode arguments : template.findValues("Fn::GetStackOutput")) {
if (!arguments.isObject()) {
throw new AwsException("ValidationError",
"TemplateError: Fn::GetStackOutput requires a map of named parameters", 400);
}
for (String required : List.of("StackName", "OutputName")) {
if (!arguments.has(required)) {
throw new AwsException("ValidationError", "GetStackOutput: " + required + " is required", 400);
}
}
// findValues does not look inside what it found; a parameter may hold another reference.
requireGetStackOutputArguments(arguments);
}
}
/**
* Resolves a live stack by name or ARN. An ARN is a stack id and resolves only to the stack
* carrying that exact id, never to a newer stack that reused the name.
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import org.jboss.logging.Logger;
@@ -17,6 +18,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
@@ -24,12 +26,31 @@ import java.util.regex.Pattern;
/**
* Resolves CloudFormation intrinsic functions and pseudo-parameters in template nodes.
* Supported: Ref, Fn::Sub, Fn::Join, Fn::Select, Fn::If, Fn::Split, Fn::Base64,
* Fn::GetAtt, Fn::GetAZs, Fn::Cidr, Fn::FindInMap, Fn::ImportValue, Condition.
* Fn::GetAtt, Fn::GetAZs, Fn::Cidr, Fn::FindInMap, Fn::ImportValue, Fn::GetStackOutput, Condition.
*/
public class CloudFormationTemplateEngine {
private static final Logger LOG = Logger.getLogger(CloudFormationTemplateEngine.class);
static final String GET_STACK_OUTPUT = "Fn::GetStackOutput";
/**
* Reads an output of another stack for {@code Fn::GetStackOutput}, the way CloudFormation does
* with DescribeStacks in the referenced account and Region.
*/
@FunctionalInterface
public interface StackOutputResolver {
/**
* @param region the Region of the referenced stack, already validated
* @param roleArn the role to read it with, or {@code null} for the stack's own account
* @return the output's value; never {@code null}
* @throws AwsException when the stack or the output does not exist, or the role cannot
* be assumed
*/
String resolve(String stackName, String outputName, String region, String roleArn);
}
private final String accountId;
private final String region;
private final String stackName;
@@ -42,7 +63,13 @@ public class CloudFormationTemplateEngine {
private final ObjectMapper objectMapper;
private final Function<String, String> importValueResolver;
private final UnaryOperator<String> dynamicReferenceResolver;
private final StackOutputResolver stackOutputResolver;
private final List<String> unresolvedIntrinsics = new ArrayList<>();
/**
* Above zero while {@code Fn::GetStackOutput}'s arguments resolve: CloudFormation hands them on
* with their dynamic references unresolved.
*/
private int dynamicReferencesSuspended;
/**
* A minimal engine for a resource provisioned outside any stack (Cloud Control CreateResource).
@@ -89,6 +116,24 @@ public class CloudFormationTemplateEngine {
ObjectMapper objectMapper,
Function<String, String> importValueResolver,
UnaryOperator<String> dynamicReferenceResolver) {
this(accountId, region, stackName, stackId, parameters, physicalIds, resourceAttributes,
conditions, mappings, objectMapper, importValueResolver, dynamicReferenceResolver, null);
}
/**
* @param stackOutputResolver reads another stack's output for {@code Fn::GetStackOutput};
* {@code null} fails every such reference, as nothing can answer it
*/
CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId,
Map<String, String> parameters,
Map<String, String> physicalIds,
Map<String, Map<String, String>> resourceAttributes,
Map<String, Boolean> conditions,
Map<String, JsonNode> mappings,
ObjectMapper objectMapper,
Function<String, String> importValueResolver,
UnaryOperator<String> dynamicReferenceResolver,
StackOutputResolver stackOutputResolver) {
this.accountId = accountId;
this.region = region;
this.stackName = stackName;
@@ -101,6 +146,7 @@ public class CloudFormationTemplateEngine {
this.objectMapper = objectMapper;
this.importValueResolver = importValueResolver;
this.dynamicReferenceResolver = dynamicReferenceResolver;
this.stackOutputResolver = stackOutputResolver;
}
/** The id of the stack this engine resolves for, as {@code AWS::StackId} returns it. */
@@ -181,6 +227,9 @@ public class CloudFormationTemplateEngine {
if (node.has("Fn::FindInMap")) {
return resolveFindInMap(node.get("Fn::FindInMap"));
}
if (node.has(GET_STACK_OUTPUT)) {
return resolveGetStackOutput(node.get(GET_STACK_OUTPUT));
}
}
return node.asText();
}
@@ -208,7 +257,7 @@ public class CloudFormationTemplateEngine {
if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) {
return objectMapper.valueToTree(resolveList(node));
}
if (isIntrinsic(node)) {
if (isIntrinsic(node) || node.has(GET_STACK_OUTPUT)) {
return TextNode.valueOf(resolve(node));
}
// Plain object: resolve each field.
@@ -294,7 +343,8 @@ public class CloudFormationTemplateEngine {
* text an intrinsic function (e.g. {@code Fn::Sub}) produces.
*/
private TextNode resolveDynamicReferences(String value) {
if (dynamicReferenceResolver == null || value == null || !value.contains("{{resolve:")) {
if (dynamicReferenceResolver == null || dynamicReferencesSuspended > 0 || value == null
|| !value.contains("{{resolve:")) {
return TextNode.valueOf(value);
}
return TextNode.valueOf(dynamicReferenceResolver.apply(value));
@@ -697,4 +747,92 @@ public class CloudFormationTemplateEngine {
LOG.warnv("Unresolved Fn::ImportValue: {0}", exportName);
throw new AwsException("ValidationError", "No export named " + exportName + " found", 400);
}
/** Whether {@code node} holds {@code Fn::GetStackOutput} anywhere inside it. */
static boolean containsGetStackOutput(JsonNode node) {
return node != null && !node.findValues(GET_STACK_OUTPUT).isEmpty();
}
/**
* {@code Fn::GetStackOutput}: the value of another stack's output, read when this resource is
* created or updated. A stack or an output that does not exist fails the operation, as on AWS;
* the reference never resolves to an empty string.
*
* <p>What AWS does, measured rather than read: a parameter value may use any intrinsic,
* a resource's {@code Ref} or {@code Fn::GetAtt} included, and it is resolved like any other
* property; a key the function does not define is ignored; {@code Region} defaults to this
* stack's, and one of another partition fails the call the way an invalid token does;
* {@code RoleArn} must parse as an ARN, and whether it can be assumed is the resolver's call.
* The positions AWS's page lists as unsupported (an Fn::Sub variable map, Fn::Base64, a
* direct Outputs value) resolve; Conditions and Fn::ImportValue are refused when the stack
* operation is requested, before this runs.
*/
private String resolveGetStackOutput(JsonNode args) {
if (args == null || !args.isObject()) {
throw new AwsException("ValidationError",
"TemplateError: Fn::GetStackOutput requires a map of named parameters", 400);
}
String referencedStack = getStackOutputParameter(args, "StackName");
String outputName = getStackOutputParameter(args, "OutputName");
String referencedRegion = getStackOutputParameter(args, "Region");
String roleArn = getStackOutputParameter(args, "RoleArn");
if (referencedStack.isEmpty()) {
throw new AwsException("ValidationError", "GetStackOutput: StackName is required", 400);
}
if (outputName.isEmpty()) {
throw new AwsException("ValidationError", "GetStackOutput: OutputName is required", 400);
}
if (referencedRegion.isEmpty()) {
referencedRegion = region;
} else if (!referencedRegion.equals(region)) {
if (!AwsRegions.isRegionId(referencedRegion)) {
throw new AwsException("ValidationError", "TemplateError: Region " + referencedRegion
+ " in Fn::GetStackOutput is not a valid AWS region.", 400);
}
if (!AwsRegions.partitionFor(referencedRegion).equals(AwsRegions.partitionFor(region))) {
throw new AwsException("InvalidClientTokenId", sdkErrorMessage(
"The security token included in the request is invalid", "AmazonCloudFormation", 403,
"InvalidClientTokenId"), 403);
}
}
if (roleArn.isEmpty()) {
roleArn = null;
} else if (!AwsArnUtils.isArn(roleArn)) {
throw new AwsException("ValidationError",
"TemplateError: Invalid RoleArn parameter " + roleArn + " in Fn::GetStackOutput", 400);
}
if (stackOutputResolver == null) {
throw new AwsException("ValidationError",
"Template error: Fn::GetStackOutput cannot be resolved outside a stack", 400);
}
return stackOutputResolver.resolve(referencedStack, outputName, referencedRegion, roleArn);
}
/**
* A parameter's value, with every dynamic reference in it left as written, one inside an
* {@code Fn::Sub} variable map included: CloudFormation does not resolve them there, so the
* stack name reaches DescribeStacks unresolved and fails its name constraint (measured,
* eu-west-1, 2026-10-17).
*/
private String getStackOutputParameter(JsonNode args, String name) {
JsonNode value = args.get(name);
if (value == null || value.isNull()) {
return "";
}
dynamicReferencesSuspended++;
try {
return resolveIntrinsic(value);
} finally {
dynamicReferencesSuspended--;
}
}
/**
* The message CloudFormation reports for an error a service call returned while it resolved a
* reference: the service's message followed by the SDK's description of the call.
*/
static String sdkErrorMessage(String message, String service, int status, String errorCode) {
return message + " (Service: " + service + "; Status Code: " + status + "; Error Code: " + errorCode
+ "; Request ID: " + UUID.randomUUID() + "; Proxy: null)";
}
}
@@ -59,6 +59,7 @@ public class CloudFormationYamlParser {
register("!Cidr", n -> fnMap("Fn::Cidr", n));
register("!GetAZs", n -> fnMap("Fn::GetAZs", n));
register("!ImportValue",n -> fnMap("Fn::ImportValue", n));
register("!GetStackOutput", n -> fnMap("Fn::GetStackOutput", n));
register("!Condition", n -> scalarMap("Condition", scalar(n)));
register("!And", n -> fnMap("Fn::And", n));
register("!Or", n -> fnMap("Fn::Or", n));
@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDecision;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Decides whether CloudFormation may read another stack's outputs through the role a
* {@code Fn::GetStackOutput} names. On AWS CloudFormation assumes the role as the stack's
* execution role, or without one as the caller of the stack operation, and reads the outputs with
* DescribeStacks in a session named {@code GetStackOutput} (measured, eu-west-1, 2026-10-16).
* Floci runs stack operations under no execution role and keeps no caller for them, so the role
* has to exist, and with IAM enforcement on, its trust policy has to allow a principal in the
* consuming account and its policies have to allow DescribeStacks on the stack, as
* {@code AssumeRole} and {@code AppSyncDataSourceAuthorizer} evaluate a role.
*/
@ApplicationScoped
public class GetStackOutputRoleAuthorizer {
private static final String DESCRIBE_STACKS = "cloudformation:DescribeStacks";
private static final String SESSION_NAME = "GetStackOutput";
private final IamService iamService;
private final AssumeRolePolicyEvaluator trustEvaluator;
private final IamPolicyEvaluator policyEvaluator;
private final EmulatorConfig config;
@Inject
public GetStackOutputRoleAuthorizer(IamService iamService, AssumeRolePolicyEvaluator trustEvaluator,
IamPolicyEvaluator policyEvaluator, EmulatorConfig config) {
this.iamService = iamService;
this.trustEvaluator = trustEvaluator;
this.policyEvaluator = policyEvaluator;
this.config = config;
}
/**
* Returns the account whose stacks {@code roleArn} reads for a stack in {@code consumerAccount}.
*
* @throws AwsException STS's AccessDenied, as CloudFormation reports it, when the role does not
* exist in {@code partition} or, with IAM enforcement on, does not trust
* the consuming account
*/
public String assume(String roleArn, String consumerAccount, String partition) {
Optional<IamRole> role = role(roleArn, partition);
if (role.isEmpty() || (enforced() && !trustEvaluator.allowsAnyPrincipalOf(
role.get().getAssumeRolePolicyDocument(), consumerAccount, partition))) {
throw new AwsException("AccessDenied", CloudFormationTemplateEngine.sdkErrorMessage(
"User: " + AwsArnUtils.Arn.global(partition, "iam", consumerAccount, "root")
+ " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,
"AWSSecurityTokenService", 403, "AccessDenied"), 403);
}
return AwsArnUtils.parse(roleArn).accountId();
}
/**
* With IAM enforcement on, refuses a read of {@code stackId} that the policies of the role
* {@link #assume} accepted do not allow, with the AccessDenied DescribeStacks answers its
* session (measured: "because no identity-based policy allows the cloudformation:DescribeStacks
* action").
*/
public void requireDescribeStacks(String roleArn, String stackId, String partition) {
if (!enforced()) {
return;
}
IamRole role = role(roleArn, partition).orElseThrow();
CallerContext caller = iamService.resolvePrincipalContext(role.getArn());
AwsArnUtils.Arn stack = AwsArnUtils.parse(stackId);
SimulationDecision decision = policyEvaluator.simulatePrincipalPolicy(caller, DESCRIBE_STACKS, stackId,
Map.of("aws:RequestedRegion", List.of(stack.region())));
if (decision == SimulationDecision.ALLOWED) {
return;
}
String reason = decision == SimulationDecision.EXPLICIT_DENY
? "with an explicit deny in an identity-based policy"
: "because no identity-based policy allows the " + DESCRIBE_STACKS + " action";
String session = AwsArnUtils.Arn.global(partition, "sts", stack.accountId(),
"assumed-role/" + role.getRoleName() + "/" + SESSION_NAME).toString();
throw new AwsException("AccessDenied", CloudFormationTemplateEngine.sdkErrorMessage(
"User: " + session + " is not authorized to perform: " + DESCRIBE_STACKS + " on resource: "
+ stackId + " " + reason, "AmazonCloudFormation", 403, "AccessDenied"), 403);
}
private boolean enforced() {
return config.services().iam().enforcementEnabled();
}
/** The role {@code roleArn} names, matched as STS {@code AssumeRole} matches a role ARN. */
private Optional<IamRole> role(String roleArn, String partition) {
if (!AwsArnUtils.isArn(roleArn)) {
return Optional.empty();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn);
if (!"iam".equals(arn.service()) || !partition.equals(arn.partition())
|| !arn.resource().startsWith("role/")) {
return Optional.empty();
}
String roleName = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
return iamService.findRole(arn.accountId(), roleName)
.filter(role -> IamService.roleArnMatches(roleArn, role));
}
}
@@ -8,6 +8,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -83,6 +84,71 @@ public class AssumeRolePolicyEvaluator {
return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT;
}
/**
* Returns true if {@code trustPolicyDocument} lets some principal of {@code account} assume the
* role: the account itself, through its root, or a principal of it that an Allow names, each
* decided by {@link #decide} with its conditions and Deny statements. It answers for a service
* that assumes a role on an account's behalf without a caller Floci knows, as CloudFormation does
* for {@code Fn::GetStackOutput}: Floci keeps no execution role or caller for a stack operation.
*/
public boolean allowsAnyPrincipalOf(String trustPolicyDocument, String account, String partition) {
String root = AwsArnUtils.Arn.global(partition, "iam", account, "root").toString();
if (allows(trustPolicyDocument, IamService.CallerArns.accountRoot(root, account), account, Map.of())) {
return true;
}
for (String principal : allowedAwsPrincipals(trustPolicyDocument)) {
if (AwsArnUtils.isArn(principal) && account.equals(AwsArnUtils.parse(principal).accountId())
&& allows(trustPolicyDocument, callerNamed(principal), account, Map.of())) {
return true;
}
}
return false;
}
/** The {@code Principal.AWS} entries of the Allow statements that apply to {@code sts:AssumeRole}. */
private List<String> allowedAwsPrincipals(String trustPolicyDocument) {
List<String> principals = new ArrayList<>();
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return principals;
}
JsonNode statements;
try {
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
} catch (Exception e) {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return principals;
}
if (!isWellFormed(statements)) {
return principals;
}
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
for (JsonNode stmt : statementList) {
if (effectOf(stmt) != Match.ALLOW || !actionApplies(stmt)) {
continue;
}
JsonNode aws = stmt.path("Principal").path("AWS");
Iterable<JsonNode> awsList = aws.isArray() ? aws : List.of(aws);
for (JsonNode entry : awsList) {
if (entry.isTextual()) {
principals.add(entry.asText());
}
}
}
return principals;
}
/** The principal {@code principalArn} names, as it calls: a role through a session of it. */
private static IamService.CallerArns callerNamed(String principalArn) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(principalArn);
if (!arn.resource().startsWith("role/")) {
return new IamService.CallerArns(principalArn, principalArn);
}
String roleName = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
String session = AwsArnUtils.Arn.global(arn.partition(), "sts", arn.accountId(), "assumed-role/" + roleName)
.toString();
return new IamService.CallerArns(session, principalArn, IamService.CallerArns.TYPE_ASSUMED_ROLE, null, null);
}
/**
* Decides whether {@code trustPolicyDocument} lets {@code caller} (in {@code callerAccount})
* perform {@code sts:AssumeRole}, and through which principal.