Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): resolve Fn::GetStackOutput as CloudFormation does (#5848)
Alessandro Lattaoe12b878b778b
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 0939febd0e..fa7566be58 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -483,6 +483,55 @@ export table — so two accounts can each own an export with the same name withohow CloudFormation isolates exports per account and region. This is what lets a multi-account LZAdeployment reuse identical export names across its member accounts.+## Stack Output References (`Fn::GetStackOutput`)++`Fn::GetStackOutput` reads an output of another stack, which needs no `Export`. It is what the CDK+synthesizes for a weak cross-stack reference. The value is read when the consuming resource is created+or updated. Floci follows what CloudFormation does, measured against it, where that departs from the+intrinsic's reference page:++- `StackName` and `OutputName` are required; `Region` defaults to the consuming stack's Region, and+ `RoleArn` names a role in the account that owns the referenced stack. A key the function does not+ define is ignored.+- A parameter value may use any intrinsic function, including a `Ref` or `Fn::GetAtt` to a resource+ of the same stack, `Fn::ImportValue` and another `Fn::GetStackOutput`; it resolves like any property.+ A dynamic reference is not resolved there, one inside an `Fn::Sub` variable map included: the stack+ name reaches DescribeStacks as written and fails its name constraint (`1 validation error detected: Value '{{resolve:ssm:...}}' at 'stackName'+ failed to satisfy constraint: ...`), as on AWS.+- A referenced stack that does not exist fails the resource with DescribeStacks' `ValidationError`+ (`Stack with id X does not exist (Service: AmazonCloudFormation; ...)`), and an output that does not+ exist with `TemplateError: Fn::GetStackOutput references output O from stack S, but this output was+ not found. The output may have been deleted.` The reference never resolves to an empty string.+- A `Region` that is not a Region fails with `TemplateError: Region R in Fn::GetStackOutput is not a+ valid AWS region.`, and one of another partition with `InvalidClientTokenId`, as the call to it does.+- A `RoleArn` that is not an ARN fails with `TemplateError: Invalid RoleArn parameter X in+ Fn::GetStackOutput`. Any other ARN that is not an existing role (a user, a role of another+ partition, a role that does not exist) fails with STS's `AccessDenied`, naming the account's root+ as the caller. On AWS the role is assumed by the stack's execution role, or without one by the+ caller of the stack operation, and the outputs are read with DescribeStacks in a session named+ `GetStackOutput`; the CDK's role trusts the consuming account's execution role. Floci runs stack+ operations under no execution role and keeps no caller for them. With IAM enforcement off, as+ `AssumeRole`, it evaluates neither the role's trust policy nor its permissions. With enforcement on,+ the trust policy has to allow a principal in the consuming account (its root, or any principal of+ it the policy names, such as the CDK's execution role), or STS's `AccessDenied` fails the resource,+ and the role's policies have to allow `cloudformation:DescribeStacks` on the stack, or+ DescribeStacks' `AccessDenied` does (`User: arn:aws:sts::A:assumed-role/R/GetStackOutput is not+ authorized to perform: cloudformation:DescribeStacks on resource: ... because no identity-based+ policy allows the cloudformation:DescribeStacks action`).+- Arguments that are not a map, or that lack `StackName` or `OutputName`, are refused when the stack+ operation is requested, with `ValidationError` `TemplateError: Fn::GetStackOutput requires a map of+ named parameters` or `GetStackOutput: StackName is required`, as on AWS.+- An output whose `Condition` is false is never read, so one naming a stack that does not exist+ leaves the operation complete; like any output whose condition is false, it is not listed.+- It resolves inside an `Fn::Sub` variable map, inside `Fn::Base64` and as a direct `Outputs` value,+ which the reference page lists as not supported yet. An output that cannot be read fails the+ operation once the resources exist, and the stack rolls back. Anywhere in `Conditions`, and inside+ `Fn::ImportValue`, the stack operation is refused when it is requested, with `ValidationError`,+ `AWS::Include` fragments included; in an output's `Export.Name` too, with `Template format error:+ Output O is malformed. The Name field of Export must not depend on any resources, imported values,+ or Fn::GetAZs.` In a nested stack's template the same rules fail the child's resource with the+ same message when the child is created, and the parent rolls back.+## Template ParametersParameters passed to `CreateStack` / `UpdateStack` (and echoed back by `DescribeStacks`) are resolveddiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex 1022e7357b..88b3f8ff64 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -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 {@Injectpublic 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) {+ 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(failedResource.getStatusReason());+ stack.setStatusReason(reason);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());+ "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.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.javaindex 62a0dca07c..b511f22283 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java@@ -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)";+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParser.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParser.javaindex 66cb9c4c19..08a02a83eb 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParser.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParser.java@@ -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));diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.javanew file mode 100644index 0000000000..46219fb412--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.java@@ -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));+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.javaindex 762526729f..fbe8aceb61 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java@@ -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.diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputEnforcementIntegrationTest.javanew file mode 100644index 0000000000..24a839648d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputEnforcementIntegrationTest.java@@ -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));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputIntegrationTest.javanew file mode 100644index 0000000000..82458df7f1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationGetStackOutputIntegrationTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.javaindex 75356feedf..6fb6b30848 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java@@ -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. */diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineGetStackOutputTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineGetStackOutputTest.javanew file mode 100644index 0000000000..3eeb422026--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineGetStackOutputTest.java@@ -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"]+ """)));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParserTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParserTest.javaindex 905fe7b359..6bdcbfe2d2 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParserTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationYamlParserTest.java@@ -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());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputFixtures.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputFixtures.javanew file mode 100644index 0000000000..c3346bd956--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputFixtures.java@@ -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();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.javaindex 412f5f792c..02ecf86fa1 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java@@ -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"));+ }+@Testvoid allowsAccountRootPrincipal() {assertTrue(evaluator.allows(diff --git a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.javaindex 529a28c2d3..2375d593bf 100644--- a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java+++ b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java@@ -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;